diff --git a/venv/lib/python3.10/site-packages/anyio/__init__.py b/venv/lib/python3.10/site-packages/anyio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..791a3901786fc1e92252708db704211345127996 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/__init__.py @@ -0,0 +1,108 @@ +from __future__ import annotations + +from ._core._contextmanagers import AsyncContextManagerMixin as AsyncContextManagerMixin +from ._core._contextmanagers import ContextManagerMixin as ContextManagerMixin +from ._core._eventloop import current_time as current_time +from ._core._eventloop import get_all_backends as get_all_backends +from ._core._eventloop import get_cancelled_exc_class as get_cancelled_exc_class +from ._core._eventloop import run as run +from ._core._eventloop import sleep as sleep +from ._core._eventloop import sleep_forever as sleep_forever +from ._core._eventloop import sleep_until as sleep_until +from ._core._exceptions import BrokenResourceError as BrokenResourceError +from ._core._exceptions import BrokenWorkerInterpreter as BrokenWorkerInterpreter +from ._core._exceptions import BrokenWorkerProcess as BrokenWorkerProcess +from ._core._exceptions import BusyResourceError as BusyResourceError +from ._core._exceptions import ClosedResourceError as ClosedResourceError +from ._core._exceptions import ConnectionFailed as ConnectionFailed +from ._core._exceptions import DelimiterNotFound as DelimiterNotFound +from ._core._exceptions import EndOfStream as EndOfStream +from ._core._exceptions import IncompleteRead as IncompleteRead +from ._core._exceptions import TypedAttributeLookupError as TypedAttributeLookupError +from ._core._exceptions import WouldBlock as WouldBlock +from ._core._fileio import AsyncFile as AsyncFile +from ._core._fileio import Path as Path +from ._core._fileio import open_file as open_file +from ._core._fileio import wrap_file as wrap_file +from ._core._resources import aclose_forcefully as aclose_forcefully +from ._core._signals import open_signal_receiver as open_signal_receiver +from ._core._sockets import TCPConnectable as TCPConnectable +from ._core._sockets import UNIXConnectable as UNIXConnectable +from ._core._sockets import as_connectable as as_connectable +from ._core._sockets import connect_tcp as connect_tcp +from ._core._sockets import connect_unix as connect_unix +from ._core._sockets import create_connected_udp_socket as create_connected_udp_socket +from ._core._sockets import ( + create_connected_unix_datagram_socket as create_connected_unix_datagram_socket, +) +from ._core._sockets import create_tcp_listener as create_tcp_listener +from ._core._sockets import create_udp_socket as create_udp_socket +from ._core._sockets import create_unix_datagram_socket as create_unix_datagram_socket +from ._core._sockets import create_unix_listener as create_unix_listener +from ._core._sockets import getaddrinfo as getaddrinfo +from ._core._sockets import getnameinfo as getnameinfo +from ._core._sockets import notify_closing as notify_closing +from ._core._sockets import wait_readable as wait_readable +from ._core._sockets import wait_socket_readable as wait_socket_readable +from ._core._sockets import wait_socket_writable as wait_socket_writable +from ._core._sockets import wait_writable as wait_writable +from ._core._streams import create_memory_object_stream as create_memory_object_stream +from ._core._subprocesses import open_process as open_process +from ._core._subprocesses import run_process as run_process +from ._core._synchronization import CapacityLimiter as CapacityLimiter +from ._core._synchronization import ( + CapacityLimiterStatistics as CapacityLimiterStatistics, +) +from ._core._synchronization import Condition as Condition +from ._core._synchronization import ConditionStatistics as ConditionStatistics +from ._core._synchronization import Event as Event +from ._core._synchronization import EventStatistics as EventStatistics +from ._core._synchronization import Lock as Lock +from ._core._synchronization import LockStatistics as LockStatistics +from ._core._synchronization import ResourceGuard as ResourceGuard +from ._core._synchronization import Semaphore as Semaphore +from ._core._synchronization import SemaphoreStatistics as SemaphoreStatistics +from ._core._tasks import TASK_STATUS_IGNORED as TASK_STATUS_IGNORED +from ._core._tasks import CancelScope as CancelScope +from ._core._tasks import create_task_group as create_task_group +from ._core._tasks import current_effective_deadline as current_effective_deadline +from ._core._tasks import fail_after as fail_after +from ._core._tasks import move_on_after as move_on_after +from ._core._tempfile import NamedTemporaryFile as NamedTemporaryFile +from ._core._tempfile import SpooledTemporaryFile as SpooledTemporaryFile +from ._core._tempfile import TemporaryDirectory as TemporaryDirectory +from ._core._tempfile import TemporaryFile as TemporaryFile +from ._core._tempfile import gettempdir as gettempdir +from ._core._tempfile import gettempdirb as gettempdirb +from ._core._tempfile import mkdtemp as mkdtemp +from ._core._tempfile import mkstemp as mkstemp +from ._core._testing import TaskInfo as TaskInfo +from ._core._testing import get_current_task as get_current_task +from ._core._testing import get_running_tasks as get_running_tasks +from ._core._testing import wait_all_tasks_blocked as wait_all_tasks_blocked +from ._core._typedattr import TypedAttributeProvider as TypedAttributeProvider +from ._core._typedattr import TypedAttributeSet as TypedAttributeSet +from ._core._typedattr import typed_attribute as typed_attribute + +# Re-export imports so they look like they live directly in this package +for __value in list(locals().values()): + if getattr(__value, "__module__", "").startswith("anyio."): + __value.__module__ = __name__ + + +del __value + + +def __getattr__(attr: str) -> type[BrokenWorkerInterpreter]: + """Support deprecated aliases.""" + if attr == "BrokenWorkerIntepreter": + import warnings + + warnings.warn( + "The 'BrokenWorkerIntepreter' alias is deprecated, use 'BrokenWorkerInterpreter' instead.", + DeprecationWarning, + stacklevel=2, + ) + return BrokenWorkerInterpreter + + raise AttributeError(f"module {__name__!r} has no attribute {attr!r}") diff --git a/venv/lib/python3.10/site-packages/anyio/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b90b4ae13e9a98b2536e9e8019b103c28cdce96 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/__pycache__/from_thread.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/__pycache__/from_thread.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..435a5a682e3f1cb216943344882db59ca6070ae2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/__pycache__/from_thread.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/__pycache__/lowlevel.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/__pycache__/lowlevel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..976fb988cfa2901449842ec9bb0c5b78bb59a310 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/__pycache__/lowlevel.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/__pycache__/pytest_plugin.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/__pycache__/pytest_plugin.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9637ce065dd33c1bbc69f581b3e242f3e69be666 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/__pycache__/pytest_plugin.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/__pycache__/to_interpreter.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/__pycache__/to_interpreter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f012ff9862607c074d62eeff156d925d58183e0a Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/__pycache__/to_interpreter.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/__pycache__/to_process.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/__pycache__/to_process.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad9d93ca7c09cf5d8bd7e489c80420abc2398e02 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/__pycache__/to_process.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/__pycache__/to_thread.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/__pycache__/to_thread.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56c07fe92a3654844b85252fdc2f4bff95d8b08e Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/__pycache__/to_thread.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_backends/__init__.py b/venv/lib/python3.10/site-packages/anyio/_backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/anyio/_backends/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_backends/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1de5bc9d2158c8ad433617bcbeb5db093bf23b76 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_backends/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90698af034a4bd688fff82e9cca97bcaf30e5ff5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_backends/__pycache__/_trio.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_backends/__pycache__/_trio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a4035d249934c855b65da9d680dcc242538f415 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_backends/__pycache__/_trio.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_backends/_asyncio.py b/venv/lib/python3.10/site-packages/anyio/_backends/_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..9bb742be48adab2245cb56656680d756ff39d121 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_backends/_asyncio.py @@ -0,0 +1,2946 @@ +from __future__ import annotations + +import array +import asyncio +import concurrent.futures +import contextvars +import math +import os +import socket +import sys +import threading +import weakref +from asyncio import ( + AbstractEventLoop, + CancelledError, + all_tasks, + create_task, + current_task, + get_running_loop, + sleep, +) +from asyncio.base_events import _run_until_complete_cb # type: ignore[attr-defined] +from collections import OrderedDict, deque +from collections.abc import ( + AsyncGenerator, + AsyncIterator, + Awaitable, + Callable, + Collection, + Coroutine, + Iterable, + Sequence, +) +from concurrent.futures import Future +from contextlib import AbstractContextManager, suppress +from contextvars import Context, copy_context +from dataclasses import dataclass +from functools import partial, wraps +from inspect import ( + CORO_RUNNING, + CORO_SUSPENDED, + getcoroutinestate, + iscoroutine, +) +from io import IOBase +from os import PathLike +from queue import Queue +from signal import Signals +from socket import AddressFamily, SocketKind +from threading import Thread +from types import CodeType, TracebackType +from typing import ( + IO, + TYPE_CHECKING, + Any, + Optional, + TypeVar, + cast, +) +from weakref import WeakKeyDictionary + +import sniffio + +from .. import ( + CapacityLimiterStatistics, + EventStatistics, + LockStatistics, + TaskInfo, + abc, +) +from .._core._eventloop import claim_worker_thread, threadlocals +from .._core._exceptions import ( + BrokenResourceError, + BusyResourceError, + ClosedResourceError, + EndOfStream, + WouldBlock, + iterate_exceptions, +) +from .._core._sockets import convert_ipv6_sockaddr +from .._core._streams import create_memory_object_stream +from .._core._synchronization import ( + CapacityLimiter as BaseCapacityLimiter, +) +from .._core._synchronization import Event as BaseEvent +from .._core._synchronization import Lock as BaseLock +from .._core._synchronization import ( + ResourceGuard, + SemaphoreStatistics, +) +from .._core._synchronization import Semaphore as BaseSemaphore +from .._core._tasks import CancelScope as BaseCancelScope +from ..abc import ( + AsyncBackend, + IPSockAddrType, + SocketListener, + UDPPacketType, + UNIXDatagramPacketType, +) +from ..abc._eventloop import StrOrBytesPath +from ..lowlevel import RunVar +from ..streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike +else: + FileDescriptorLike = object + +if sys.version_info >= (3, 10): + from typing import ParamSpec +else: + from typing_extensions import ParamSpec + +if sys.version_info >= (3, 11): + from asyncio import Runner + from typing import TypeVarTuple, Unpack +else: + import contextvars + import enum + import signal + from asyncio import coroutines, events, exceptions, tasks + + from exceptiongroup import BaseExceptionGroup + from typing_extensions import TypeVarTuple, Unpack + + class _State(enum.Enum): + CREATED = "created" + INITIALIZED = "initialized" + CLOSED = "closed" + + class Runner: + # Copied from CPython 3.11 + def __init__( + self, + *, + debug: bool | None = None, + loop_factory: Callable[[], AbstractEventLoop] | None = None, + ): + self._state = _State.CREATED + self._debug = debug + self._loop_factory = loop_factory + self._loop: AbstractEventLoop | None = None + self._context = None + self._interrupt_count = 0 + self._set_event_loop = False + + def __enter__(self) -> Runner: + self._lazy_init() + return self + + def __exit__( + self, + exc_type: type[BaseException], + exc_val: BaseException, + exc_tb: TracebackType, + ) -> None: + self.close() + + def close(self) -> None: + """Shutdown and close event loop.""" + if self._state is not _State.INITIALIZED: + return + try: + loop = self._loop + _cancel_all_tasks(loop) + loop.run_until_complete(loop.shutdown_asyncgens()) + if hasattr(loop, "shutdown_default_executor"): + loop.run_until_complete(loop.shutdown_default_executor()) + else: + loop.run_until_complete(_shutdown_default_executor(loop)) + finally: + if self._set_event_loop: + events.set_event_loop(None) + loop.close() + self._loop = None + self._state = _State.CLOSED + + def get_loop(self) -> AbstractEventLoop: + """Return embedded event loop.""" + self._lazy_init() + return self._loop + + def run(self, coro: Coroutine[T_Retval], *, context=None) -> T_Retval: + """Run a coroutine inside the embedded event loop.""" + if not coroutines.iscoroutine(coro): + raise ValueError(f"a coroutine was expected, got {coro!r}") + + if events._get_running_loop() is not None: + # fail fast with short traceback + raise RuntimeError( + "Runner.run() cannot be called from a running event loop" + ) + + self._lazy_init() + + if context is None: + context = self._context + task = context.run(self._loop.create_task, coro) + + if ( + threading.current_thread() is threading.main_thread() + and signal.getsignal(signal.SIGINT) is signal.default_int_handler + ): + sigint_handler = partial(self._on_sigint, main_task=task) + try: + signal.signal(signal.SIGINT, sigint_handler) + except ValueError: + # `signal.signal` may throw if `threading.main_thread` does + # not support signals (e.g. embedded interpreter with signals + # not registered - see gh-91880) + sigint_handler = None + else: + sigint_handler = None + + self._interrupt_count = 0 + try: + return self._loop.run_until_complete(task) + except exceptions.CancelledError: + if self._interrupt_count > 0: + uncancel = getattr(task, "uncancel", None) + if uncancel is not None and uncancel() == 0: + raise KeyboardInterrupt # noqa: B904 + raise # CancelledError + finally: + if ( + sigint_handler is not None + and signal.getsignal(signal.SIGINT) is sigint_handler + ): + signal.signal(signal.SIGINT, signal.default_int_handler) + + def _lazy_init(self) -> None: + if self._state is _State.CLOSED: + raise RuntimeError("Runner is closed") + if self._state is _State.INITIALIZED: + return + if self._loop_factory is None: + self._loop = events.new_event_loop() + if not self._set_event_loop: + # Call set_event_loop only once to avoid calling + # attach_loop multiple times on child watchers + events.set_event_loop(self._loop) + self._set_event_loop = True + else: + self._loop = self._loop_factory() + if self._debug is not None: + self._loop.set_debug(self._debug) + self._context = contextvars.copy_context() + self._state = _State.INITIALIZED + + def _on_sigint(self, signum, frame, main_task: asyncio.Task) -> None: + self._interrupt_count += 1 + if self._interrupt_count == 1 and not main_task.done(): + main_task.cancel() + # wakeup loop if it is blocked by select() with long timeout + self._loop.call_soon_threadsafe(lambda: None) + return + raise KeyboardInterrupt() + + def _cancel_all_tasks(loop: AbstractEventLoop) -> None: + to_cancel = tasks.all_tasks(loop) + if not to_cancel: + return + + for task in to_cancel: + task.cancel() + + loop.run_until_complete(tasks.gather(*to_cancel, return_exceptions=True)) + + for task in to_cancel: + if task.cancelled(): + continue + if task.exception() is not None: + loop.call_exception_handler( + { + "message": "unhandled exception during asyncio.run() shutdown", + "exception": task.exception(), + "task": task, + } + ) + + async def _shutdown_default_executor(loop: AbstractEventLoop) -> None: + """Schedule the shutdown of the default executor.""" + + def _do_shutdown(future: asyncio.futures.Future) -> None: + try: + loop._default_executor.shutdown(wait=True) # type: ignore[attr-defined] + loop.call_soon_threadsafe(future.set_result, None) + except Exception as ex: + loop.call_soon_threadsafe(future.set_exception, ex) + + loop._executor_shutdown_called = True + if loop._default_executor is None: + return + future = loop.create_future() + thread = threading.Thread(target=_do_shutdown, args=(future,)) + thread.start() + try: + await future + finally: + thread.join() + + +T_Retval = TypeVar("T_Retval") +T_contra = TypeVar("T_contra", contravariant=True) +PosArgsT = TypeVarTuple("PosArgsT") +P = ParamSpec("P") + +_root_task: RunVar[asyncio.Task | None] = RunVar("_root_task") + + +def find_root_task() -> asyncio.Task: + root_task = _root_task.get(None) + if root_task is not None and not root_task.done(): + return root_task + + # Look for a task that has been started via run_until_complete() + for task in all_tasks(): + if task._callbacks and not task.done(): + callbacks = [cb for cb, context in task._callbacks] + for cb in callbacks: + if ( + cb is _run_until_complete_cb + or getattr(cb, "__module__", None) == "uvloop.loop" + ): + _root_task.set(task) + return task + + # Look up the topmost task in the AnyIO task tree, if possible + task = cast(asyncio.Task, current_task()) + state = _task_states.get(task) + if state: + cancel_scope = state.cancel_scope + while cancel_scope and cancel_scope._parent_scope is not None: + cancel_scope = cancel_scope._parent_scope + + if cancel_scope is not None: + return cast(asyncio.Task, cancel_scope._host_task) + + return task + + +def get_callable_name(func: Callable) -> str: + module = getattr(func, "__module__", None) + qualname = getattr(func, "__qualname__", None) + return ".".join([x for x in (module, qualname) if x]) + + +# +# Event loop +# + +_run_vars: WeakKeyDictionary[asyncio.AbstractEventLoop, Any] = WeakKeyDictionary() + + +def _task_started(task: asyncio.Task) -> bool: + """Return ``True`` if the task has been started and has not finished.""" + # The task coro should never be None here, as we never add finished tasks to the + # task list + coro = task.get_coro() + assert coro is not None + try: + return getcoroutinestate(coro) in (CORO_RUNNING, CORO_SUSPENDED) + except AttributeError: + # task coro is async_genenerator_asend https://bugs.python.org/issue37771 + raise Exception(f"Cannot determine if task {task} has started or not") from None + + +# +# Timeouts and cancellation +# + + +def is_anyio_cancellation(exc: CancelledError) -> bool: + # Sometimes third party frameworks catch a CancelledError and raise a new one, so as + # a workaround we have to look at the previous ones in __context__ too for a + # matching cancel message + while True: + if ( + exc.args + and isinstance(exc.args[0], str) + and exc.args[0].startswith("Cancelled by cancel scope ") + ): + return True + + if isinstance(exc.__context__, CancelledError): + exc = exc.__context__ + continue + + return False + + +class CancelScope(BaseCancelScope): + def __new__( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> CancelScope: + return object.__new__(cls) + + def __init__(self, deadline: float = math.inf, shield: bool = False): + self._deadline = deadline + self._shield = shield + self._parent_scope: CancelScope | None = None + self._child_scopes: set[CancelScope] = set() + self._cancel_called = False + self._cancelled_caught = False + self._active = False + self._timeout_handle: asyncio.TimerHandle | None = None + self._cancel_handle: asyncio.Handle | None = None + self._tasks: set[asyncio.Task] = set() + self._host_task: asyncio.Task | None = None + if sys.version_info >= (3, 11): + self._pending_uncancellations: int | None = 0 + else: + self._pending_uncancellations = None + + def __enter__(self) -> CancelScope: + if self._active: + raise RuntimeError( + "Each CancelScope may only be used for a single 'with' block" + ) + + self._host_task = host_task = cast(asyncio.Task, current_task()) + self._tasks.add(host_task) + try: + task_state = _task_states[host_task] + except KeyError: + task_state = TaskState(None, self) + _task_states[host_task] = task_state + else: + self._parent_scope = task_state.cancel_scope + task_state.cancel_scope = self + if self._parent_scope is not None: + # If using an eager task factory, the parent scope may not even contain + # the host task + self._parent_scope._child_scopes.add(self) + self._parent_scope._tasks.discard(host_task) + + self._timeout() + self._active = True + + # Start cancelling the host task if the scope was cancelled before entering + if self._cancel_called: + self._deliver_cancellation(self) + + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + del exc_tb + + if not self._active: + raise RuntimeError("This cancel scope is not active") + if current_task() is not self._host_task: + raise RuntimeError( + "Attempted to exit cancel scope in a different task than it was " + "entered in" + ) + + assert self._host_task is not None + host_task_state = _task_states.get(self._host_task) + if host_task_state is None or host_task_state.cancel_scope is not self: + raise RuntimeError( + "Attempted to exit a cancel scope that isn't the current tasks's " + "current cancel scope" + ) + + try: + self._active = False + if self._timeout_handle: + self._timeout_handle.cancel() + self._timeout_handle = None + + self._tasks.remove(self._host_task) + if self._parent_scope is not None: + self._parent_scope._child_scopes.remove(self) + self._parent_scope._tasks.add(self._host_task) + + host_task_state.cancel_scope = self._parent_scope + + # Restart the cancellation effort in the closest visible, cancelled parent + # scope if necessary + self._restart_cancellation_in_parent() + + # We only swallow the exception iff it was an AnyIO CancelledError, either + # directly as exc_val or inside an exception group and there are no cancelled + # parent cancel scopes visible to us here + if self._cancel_called and not self._parent_cancellation_is_visible_to_us: + # For each level-cancel() call made on the host task, call uncancel() + while self._pending_uncancellations: + self._host_task.uncancel() + self._pending_uncancellations -= 1 + + # Update cancelled_caught and check for exceptions we must not swallow + cannot_swallow_exc_val = False + if exc_val is not None: + for exc in iterate_exceptions(exc_val): + if isinstance(exc, CancelledError) and is_anyio_cancellation( + exc + ): + self._cancelled_caught = True + else: + cannot_swallow_exc_val = True + + return self._cancelled_caught and not cannot_swallow_exc_val + else: + if self._pending_uncancellations: + assert self._parent_scope is not None + assert self._parent_scope._pending_uncancellations is not None + self._parent_scope._pending_uncancellations += ( + self._pending_uncancellations + ) + self._pending_uncancellations = 0 + + return False + finally: + self._host_task = None + del exc_val + + @property + def _effectively_cancelled(self) -> bool: + cancel_scope: CancelScope | None = self + while cancel_scope is not None: + if cancel_scope._cancel_called: + return True + + if cancel_scope.shield: + return False + + cancel_scope = cancel_scope._parent_scope + + return False + + @property + def _parent_cancellation_is_visible_to_us(self) -> bool: + return ( + self._parent_scope is not None + and not self.shield + and self._parent_scope._effectively_cancelled + ) + + def _timeout(self) -> None: + if self._deadline != math.inf: + loop = get_running_loop() + if loop.time() >= self._deadline: + self.cancel() + else: + self._timeout_handle = loop.call_at(self._deadline, self._timeout) + + def _deliver_cancellation(self, origin: CancelScope) -> bool: + """ + Deliver cancellation to directly contained tasks and nested cancel scopes. + + Schedule another run at the end if we still have tasks eligible for + cancellation. + + :param origin: the cancel scope that originated the cancellation + :return: ``True`` if the delivery needs to be retried on the next cycle + + """ + should_retry = False + current = current_task() + for task in self._tasks: + should_retry = True + if task._must_cancel: # type: ignore[attr-defined] + continue + + # The task is eligible for cancellation if it has started + if task is not current and (task is self._host_task or _task_started(task)): + waiter = task._fut_waiter # type: ignore[attr-defined] + if not isinstance(waiter, asyncio.Future) or not waiter.done(): + task.cancel(f"Cancelled by cancel scope {id(origin):x}") + if ( + task is origin._host_task + and origin._pending_uncancellations is not None + ): + origin._pending_uncancellations += 1 + + # Deliver cancellation to child scopes that aren't shielded or running their own + # cancellation callbacks + for scope in self._child_scopes: + if not scope._shield and not scope.cancel_called: + should_retry = scope._deliver_cancellation(origin) or should_retry + + # Schedule another callback if there are still tasks left + if origin is self: + if should_retry: + self._cancel_handle = get_running_loop().call_soon( + self._deliver_cancellation, origin + ) + else: + self._cancel_handle = None + + return should_retry + + def _restart_cancellation_in_parent(self) -> None: + """ + Restart the cancellation effort in the closest directly cancelled parent scope. + + """ + scope = self._parent_scope + while scope is not None: + if scope._cancel_called: + if scope._cancel_handle is None: + scope._deliver_cancellation(scope) + + break + + # No point in looking beyond any shielded scope + if scope._shield: + break + + scope = scope._parent_scope + + def cancel(self) -> None: + if not self._cancel_called: + if self._timeout_handle: + self._timeout_handle.cancel() + self._timeout_handle = None + + self._cancel_called = True + if self._host_task is not None: + self._deliver_cancellation(self) + + @property + def deadline(self) -> float: + return self._deadline + + @deadline.setter + def deadline(self, value: float) -> None: + self._deadline = float(value) + if self._timeout_handle is not None: + self._timeout_handle.cancel() + self._timeout_handle = None + + if self._active and not self._cancel_called: + self._timeout() + + @property + def cancel_called(self) -> bool: + return self._cancel_called + + @property + def cancelled_caught(self) -> bool: + return self._cancelled_caught + + @property + def shield(self) -> bool: + return self._shield + + @shield.setter + def shield(self, value: bool) -> None: + if self._shield != value: + self._shield = value + if not value: + self._restart_cancellation_in_parent() + + +# +# Task states +# + + +class TaskState: + """ + Encapsulates auxiliary task information that cannot be added to the Task instance + itself because there are no guarantees about its implementation. + """ + + __slots__ = "parent_id", "cancel_scope", "__weakref__" + + def __init__(self, parent_id: int | None, cancel_scope: CancelScope | None): + self.parent_id = parent_id + self.cancel_scope = cancel_scope + + +_task_states: WeakKeyDictionary[asyncio.Task, TaskState] = WeakKeyDictionary() + + +# +# Task groups +# + + +class _AsyncioTaskStatus(abc.TaskStatus): + def __init__(self, future: asyncio.Future, parent_id: int): + self._future = future + self._parent_id = parent_id + + def started(self, value: T_contra | None = None) -> None: + try: + self._future.set_result(value) + except asyncio.InvalidStateError: + if not self._future.cancelled(): + raise RuntimeError( + "called 'started' twice on the same task status" + ) from None + + task = cast(asyncio.Task, current_task()) + _task_states[task].parent_id = self._parent_id + + +if sys.version_info >= (3, 12): + _eager_task_factory_code: CodeType | None = asyncio.eager_task_factory.__code__ +else: + _eager_task_factory_code = None + + +class TaskGroup(abc.TaskGroup): + def __init__(self) -> None: + self.cancel_scope: CancelScope = CancelScope() + self._active = False + self._exceptions: list[BaseException] = [] + self._tasks: set[asyncio.Task] = set() + self._on_completed_fut: asyncio.Future[None] | None = None + + async def __aenter__(self) -> TaskGroup: + self.cancel_scope.__enter__() + self._active = True + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + try: + if exc_val is not None: + self.cancel_scope.cancel() + if not isinstance(exc_val, CancelledError): + self._exceptions.append(exc_val) + + loop = get_running_loop() + try: + if self._tasks: + with CancelScope() as wait_scope: + while self._tasks: + self._on_completed_fut = loop.create_future() + + try: + await self._on_completed_fut + except CancelledError as exc: + # Shield the scope against further cancellation attempts, + # as they're not productive (#695) + wait_scope.shield = True + self.cancel_scope.cancel() + + # Set exc_val from the cancellation exception if it was + # previously unset. However, we should not replace a native + # cancellation exception with one raise by a cancel scope. + if exc_val is None or ( + isinstance(exc_val, CancelledError) + and not is_anyio_cancellation(exc) + ): + exc_val = exc + + self._on_completed_fut = None + else: + # If there are no child tasks to wait on, run at least one checkpoint + # anyway + await AsyncIOBackend.cancel_shielded_checkpoint() + + self._active = False + if self._exceptions: + # The exception that got us here should already have been + # added to self._exceptions so it's ok to break exception + # chaining and avoid adding a "During handling of above..." + # for each nesting level. + raise BaseExceptionGroup( + "unhandled errors in a TaskGroup", self._exceptions + ) from None + elif exc_val: + raise exc_val + except BaseException as exc: + if self.cancel_scope.__exit__(type(exc), exc, exc.__traceback__): + return True + + raise + + return self.cancel_scope.__exit__(exc_type, exc_val, exc_tb) + finally: + del exc_val, exc_tb, self._exceptions + + def _spawn( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], + args: tuple[Unpack[PosArgsT]], + name: object, + task_status_future: asyncio.Future | None = None, + ) -> asyncio.Task: + def task_done(_task: asyncio.Task) -> None: + task_state = _task_states[_task] + assert task_state.cancel_scope is not None + assert _task in task_state.cancel_scope._tasks + task_state.cancel_scope._tasks.remove(_task) + self._tasks.remove(task) + del _task_states[_task] + + if self._on_completed_fut is not None and not self._tasks: + try: + self._on_completed_fut.set_result(None) + except asyncio.InvalidStateError: + pass + + try: + exc = _task.exception() + except CancelledError as e: + while isinstance(e.__context__, CancelledError): + e = e.__context__ + + exc = e + + if exc is not None: + # The future can only be in the cancelled state if the host task was + # cancelled, so return immediately instead of adding one more + # CancelledError to the exceptions list + if task_status_future is not None and task_status_future.cancelled(): + return + + if task_status_future is None or task_status_future.done(): + if not isinstance(exc, CancelledError): + self._exceptions.append(exc) + + if not self.cancel_scope._effectively_cancelled: + self.cancel_scope.cancel() + else: + task_status_future.set_exception(exc) + elif task_status_future is not None and not task_status_future.done(): + task_status_future.set_exception( + RuntimeError("Child exited without calling task_status.started()") + ) + + if not self._active: + raise RuntimeError( + "This task group is not active; no new tasks can be started." + ) + + kwargs = {} + if task_status_future: + parent_id = id(current_task()) + kwargs["task_status"] = _AsyncioTaskStatus( + task_status_future, id(self.cancel_scope._host_task) + ) + else: + parent_id = id(self.cancel_scope._host_task) + + coro = func(*args, **kwargs) + if not iscoroutine(coro): + prefix = f"{func.__module__}." if hasattr(func, "__module__") else "" + raise TypeError( + f"Expected {prefix}{func.__qualname__}() to return a coroutine, but " + f"the return value ({coro!r}) is not a coroutine object" + ) + + name = get_callable_name(func) if name is None else str(name) + loop = asyncio.get_running_loop() + if ( + (factory := loop.get_task_factory()) + and getattr(factory, "__code__", None) is _eager_task_factory_code + and (closure := getattr(factory, "__closure__", None)) + ): + custom_task_constructor = closure[0].cell_contents + task = custom_task_constructor(coro, loop=loop, name=name) + else: + task = create_task(coro, name=name) + + # Make the spawned task inherit the task group's cancel scope + _task_states[task] = TaskState( + parent_id=parent_id, cancel_scope=self.cancel_scope + ) + self.cancel_scope._tasks.add(task) + self._tasks.add(task) + task.add_done_callback(task_done) + return task + + def start_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], + *args: Unpack[PosArgsT], + name: object = None, + ) -> None: + self._spawn(func, args, name) + + async def start( + self, func: Callable[..., Awaitable[Any]], *args: object, name: object = None + ) -> Any: + future: asyncio.Future = asyncio.Future() + task = self._spawn(func, args, name, future) + + # If the task raises an exception after sending a start value without a switch + # point between, the task group is cancelled and this method never proceeds to + # process the completed future. That's why we have to have a shielded cancel + # scope here. + try: + return await future + except CancelledError: + # Cancel the task and wait for it to exit before returning + task.cancel() + with CancelScope(shield=True), suppress(CancelledError): + await task + + raise + + +# +# Threads +# + +_Retval_Queue_Type = tuple[Optional[T_Retval], Optional[BaseException]] + + +class WorkerThread(Thread): + MAX_IDLE_TIME = 10 # seconds + + def __init__( + self, + root_task: asyncio.Task, + workers: set[WorkerThread], + idle_workers: deque[WorkerThread], + ): + super().__init__(name="AnyIO worker thread") + self.root_task = root_task + self.workers = workers + self.idle_workers = idle_workers + self.loop = root_task._loop + self.queue: Queue[ + tuple[Context, Callable, tuple, asyncio.Future, CancelScope] | None + ] = Queue(2) + self.idle_since = AsyncIOBackend.current_time() + self.stopping = False + + def _report_result( + self, future: asyncio.Future, result: Any, exc: BaseException | None + ) -> None: + self.idle_since = AsyncIOBackend.current_time() + if not self.stopping: + self.idle_workers.append(self) + + if not future.cancelled(): + if exc is not None: + if isinstance(exc, StopIteration): + new_exc = RuntimeError("coroutine raised StopIteration") + new_exc.__cause__ = exc + exc = new_exc + + future.set_exception(exc) + else: + future.set_result(result) + + def run(self) -> None: + with claim_worker_thread(AsyncIOBackend, self.loop): + while True: + item = self.queue.get() + if item is None: + # Shutdown command received + return + + context, func, args, future, cancel_scope = item + if not future.cancelled(): + result = None + exception: BaseException | None = None + threadlocals.current_cancel_scope = cancel_scope + try: + result = context.run(func, *args) + except BaseException as exc: + exception = exc + finally: + del threadlocals.current_cancel_scope + + if not self.loop.is_closed(): + self.loop.call_soon_threadsafe( + self._report_result, future, result, exception + ) + + del result, exception + + self.queue.task_done() + del item, context, func, args, future, cancel_scope + + def stop(self, f: asyncio.Task | None = None) -> None: + self.stopping = True + self.queue.put_nowait(None) + self.workers.discard(self) + try: + self.idle_workers.remove(self) + except ValueError: + pass + + +_threadpool_idle_workers: RunVar[deque[WorkerThread]] = RunVar( + "_threadpool_idle_workers" +) +_threadpool_workers: RunVar[set[WorkerThread]] = RunVar("_threadpool_workers") + + +class BlockingPortal(abc.BlockingPortal): + def __new__(cls) -> BlockingPortal: + return object.__new__(cls) + + def __init__(self) -> None: + super().__init__() + self._loop = get_running_loop() + + def _spawn_task_from_thread( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + name: object, + future: Future[T_Retval], + ) -> None: + AsyncIOBackend.run_sync_from_thread( + partial(self._task_group.start_soon, name=name), + (self._call_func, func, args, kwargs, future), + self._loop, + ) + + +# +# Subprocesses +# + + +@dataclass(eq=False) +class StreamReaderWrapper(abc.ByteReceiveStream): + _stream: asyncio.StreamReader + + async def receive(self, max_bytes: int = 65536) -> bytes: + data = await self._stream.read(max_bytes) + if data: + return data + else: + raise EndOfStream + + async def aclose(self) -> None: + self._stream.set_exception(ClosedResourceError()) + await AsyncIOBackend.checkpoint() + + +@dataclass(eq=False) +class StreamWriterWrapper(abc.ByteSendStream): + _stream: asyncio.StreamWriter + + async def send(self, item: bytes) -> None: + self._stream.write(item) + await self._stream.drain() + + async def aclose(self) -> None: + self._stream.close() + await AsyncIOBackend.checkpoint() + + +@dataclass(eq=False) +class Process(abc.Process): + _process: asyncio.subprocess.Process + _stdin: StreamWriterWrapper | None + _stdout: StreamReaderWrapper | None + _stderr: StreamReaderWrapper | None + + async def aclose(self) -> None: + with CancelScope(shield=True) as scope: + if self._stdin: + await self._stdin.aclose() + if self._stdout: + await self._stdout.aclose() + if self._stderr: + await self._stderr.aclose() + + scope.shield = False + try: + await self.wait() + except BaseException: + scope.shield = True + self.kill() + await self.wait() + raise + + async def wait(self) -> int: + return await self._process.wait() + + def terminate(self) -> None: + self._process.terminate() + + def kill(self) -> None: + self._process.kill() + + def send_signal(self, signal: int) -> None: + self._process.send_signal(signal) + + @property + def pid(self) -> int: + return self._process.pid + + @property + def returncode(self) -> int | None: + return self._process.returncode + + @property + def stdin(self) -> abc.ByteSendStream | None: + return self._stdin + + @property + def stdout(self) -> abc.ByteReceiveStream | None: + return self._stdout + + @property + def stderr(self) -> abc.ByteReceiveStream | None: + return self._stderr + + +def _forcibly_shutdown_process_pool_on_exit( + workers: set[Process], _task: object +) -> None: + """ + Forcibly shuts down worker processes belonging to this event loop.""" + child_watcher: asyncio.AbstractChildWatcher | None = None + if sys.version_info < (3, 12): + try: + child_watcher = asyncio.get_event_loop_policy().get_child_watcher() + except NotImplementedError: + pass + + # Close as much as possible (w/o async/await) to avoid warnings + for process in workers: + if process.returncode is None: + continue + + process._stdin._stream._transport.close() # type: ignore[union-attr] + process._stdout._stream._transport.close() # type: ignore[union-attr] + process._stderr._stream._transport.close() # type: ignore[union-attr] + process.kill() + if child_watcher: + child_watcher.remove_child_handler(process.pid) + + +async def _shutdown_process_pool_on_exit(workers: set[abc.Process]) -> None: + """ + Shuts down worker processes belonging to this event loop. + + NOTE: this only works when the event loop was started using asyncio.run() or + anyio.run(). + + """ + process: abc.Process + try: + await sleep(math.inf) + except asyncio.CancelledError: + for process in workers: + if process.returncode is None: + process.kill() + + for process in workers: + await process.aclose() + + +# +# Sockets and networking +# + + +class StreamProtocol(asyncio.Protocol): + read_queue: deque[bytes] + read_event: asyncio.Event + write_event: asyncio.Event + exception: Exception | None = None + is_at_eof: bool = False + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + self.read_queue = deque() + self.read_event = asyncio.Event() + self.write_event = asyncio.Event() + self.write_event.set() + cast(asyncio.Transport, transport).set_write_buffer_limits(0) + + def connection_lost(self, exc: Exception | None) -> None: + if exc: + self.exception = BrokenResourceError() + self.exception.__cause__ = exc + + self.read_event.set() + self.write_event.set() + + def data_received(self, data: bytes) -> None: + # ProactorEventloop sometimes sends bytearray instead of bytes + self.read_queue.append(bytes(data)) + self.read_event.set() + + def eof_received(self) -> bool | None: + self.is_at_eof = True + self.read_event.set() + return True + + def pause_writing(self) -> None: + self.write_event = asyncio.Event() + + def resume_writing(self) -> None: + self.write_event.set() + + +class DatagramProtocol(asyncio.DatagramProtocol): + read_queue: deque[tuple[bytes, IPSockAddrType]] + read_event: asyncio.Event + write_event: asyncio.Event + exception: Exception | None = None + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + self.read_queue = deque(maxlen=100) # arbitrary value + self.read_event = asyncio.Event() + self.write_event = asyncio.Event() + self.write_event.set() + + def connection_lost(self, exc: Exception | None) -> None: + self.read_event.set() + self.write_event.set() + + def datagram_received(self, data: bytes, addr: IPSockAddrType) -> None: + addr = convert_ipv6_sockaddr(addr) + self.read_queue.append((data, addr)) + self.read_event.set() + + def error_received(self, exc: Exception) -> None: + self.exception = exc + + def pause_writing(self) -> None: + self.write_event.clear() + + def resume_writing(self) -> None: + self.write_event.set() + + +class SocketStream(abc.SocketStream): + def __init__(self, transport: asyncio.Transport, protocol: StreamProtocol): + self._transport = transport + self._protocol = protocol + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + self._closed = False + + @property + def _raw_socket(self) -> socket.socket: + return self._transport.get_extra_info("socket") + + async def receive(self, max_bytes: int = 65536) -> bytes: + with self._receive_guard: + if ( + not self._protocol.read_event.is_set() + and not self._transport.is_closing() + and not self._protocol.is_at_eof + ): + self._transport.resume_reading() + await self._protocol.read_event.wait() + self._transport.pause_reading() + else: + await AsyncIOBackend.checkpoint() + + try: + chunk = self._protocol.read_queue.popleft() + except IndexError: + if self._closed: + raise ClosedResourceError from None + elif self._protocol.exception: + raise self._protocol.exception from None + else: + raise EndOfStream from None + + if len(chunk) > max_bytes: + # Split the oversized chunk + chunk, leftover = chunk[:max_bytes], chunk[max_bytes:] + self._protocol.read_queue.appendleft(leftover) + + # If the read queue is empty, clear the flag so that the next call will + # block until data is available + if not self._protocol.read_queue: + self._protocol.read_event.clear() + + return chunk + + async def send(self, item: bytes) -> None: + with self._send_guard: + await AsyncIOBackend.checkpoint() + + if self._closed: + raise ClosedResourceError + elif self._protocol.exception is not None: + raise self._protocol.exception + + try: + self._transport.write(item) + except RuntimeError as exc: + if self._transport.is_closing(): + raise BrokenResourceError from exc + else: + raise + + await self._protocol.write_event.wait() + + async def send_eof(self) -> None: + try: + self._transport.write_eof() + except OSError: + pass + + async def aclose(self) -> None: + if not self._transport.is_closing(): + self._closed = True + try: + self._transport.write_eof() + except OSError: + pass + + self._transport.close() + await sleep(0) + self._transport.abort() + + +class _RawSocketMixin: + _receive_future: asyncio.Future | None = None + _send_future: asyncio.Future | None = None + _closing = False + + def __init__(self, raw_socket: socket.socket): + self.__raw_socket = raw_socket + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + @property + def _raw_socket(self) -> socket.socket: + return self.__raw_socket + + def _wait_until_readable(self, loop: asyncio.AbstractEventLoop) -> asyncio.Future: + def callback(f: object) -> None: + del self._receive_future + loop.remove_reader(self.__raw_socket) + + f = self._receive_future = asyncio.Future() + loop.add_reader(self.__raw_socket, f.set_result, None) + f.add_done_callback(callback) + return f + + def _wait_until_writable(self, loop: asyncio.AbstractEventLoop) -> asyncio.Future: + def callback(f: object) -> None: + del self._send_future + loop.remove_writer(self.__raw_socket) + + f = self._send_future = asyncio.Future() + loop.add_writer(self.__raw_socket, f.set_result, None) + f.add_done_callback(callback) + return f + + async def aclose(self) -> None: + if not self._closing: + self._closing = True + if self.__raw_socket.fileno() != -1: + self.__raw_socket.close() + + if self._receive_future: + self._receive_future.set_result(None) + if self._send_future: + self._send_future.set_result(None) + + +class UNIXSocketStream(_RawSocketMixin, abc.UNIXSocketStream): + async def send_eof(self) -> None: + with self._send_guard: + self._raw_socket.shutdown(socket.SHUT_WR) + + async def receive(self, max_bytes: int = 65536) -> bytes: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._receive_guard: + while True: + try: + data = self._raw_socket.recv(max_bytes) + except BlockingIOError: + await self._wait_until_readable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + if not data: + raise EndOfStream + + return data + + async def send(self, item: bytes) -> None: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._send_guard: + view = memoryview(item) + while view: + try: + bytes_sent = self._raw_socket.send(view) + except BlockingIOError: + await self._wait_until_writable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + view = view[bytes_sent:] + + async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: + if not isinstance(msglen, int) or msglen < 0: + raise ValueError("msglen must be a non-negative integer") + if not isinstance(maxfds, int) or maxfds < 1: + raise ValueError("maxfds must be a positive integer") + + loop = get_running_loop() + fds = array.array("i") + await AsyncIOBackend.checkpoint() + with self._receive_guard: + while True: + try: + message, ancdata, flags, addr = self._raw_socket.recvmsg( + msglen, socket.CMSG_LEN(maxfds * fds.itemsize) + ) + except BlockingIOError: + await self._wait_until_readable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + if not message and not ancdata: + raise EndOfStream + + break + + for cmsg_level, cmsg_type, cmsg_data in ancdata: + if cmsg_level != socket.SOL_SOCKET or cmsg_type != socket.SCM_RIGHTS: + raise RuntimeError( + f"Received unexpected ancillary data; message = {message!r}, " + f"cmsg_level = {cmsg_level}, cmsg_type = {cmsg_type}" + ) + + fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) + + return message, list(fds) + + async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: + if not message: + raise ValueError("message must not be empty") + if not fds: + raise ValueError("fds must not be empty") + + loop = get_running_loop() + filenos: list[int] = [] + for fd in fds: + if isinstance(fd, int): + filenos.append(fd) + elif isinstance(fd, IOBase): + filenos.append(fd.fileno()) + + fdarray = array.array("i", filenos) + await AsyncIOBackend.checkpoint() + with self._send_guard: + while True: + try: + # The ignore can be removed after mypy picks up + # https://github.com/python/typeshed/pull/5545 + self._raw_socket.sendmsg( + [message], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fdarray)] + ) + break + except BlockingIOError: + await self._wait_until_writable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + + +class TCPSocketListener(abc.SocketListener): + _accept_scope: CancelScope | None = None + _closed = False + + def __init__(self, raw_socket: socket.socket): + self.__raw_socket = raw_socket + self._loop = cast(asyncio.BaseEventLoop, get_running_loop()) + self._accept_guard = ResourceGuard("accepting connections from") + + @property + def _raw_socket(self) -> socket.socket: + return self.__raw_socket + + async def accept(self) -> abc.SocketStream: + if self._closed: + raise ClosedResourceError + + with self._accept_guard: + await AsyncIOBackend.checkpoint() + with CancelScope() as self._accept_scope: + try: + client_sock, _addr = await self._loop.sock_accept(self._raw_socket) + except asyncio.CancelledError: + # Workaround for https://bugs.python.org/issue41317 + try: + self._loop.remove_reader(self._raw_socket) + except (ValueError, NotImplementedError): + pass + + if self._closed: + raise ClosedResourceError from None + + raise + finally: + self._accept_scope = None + + client_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + transport, protocol = await self._loop.connect_accepted_socket( + StreamProtocol, client_sock + ) + return SocketStream(transport, protocol) + + async def aclose(self) -> None: + if self._closed: + return + + self._closed = True + if self._accept_scope: + # Workaround for https://bugs.python.org/issue41317 + try: + self._loop.remove_reader(self._raw_socket) + except (ValueError, NotImplementedError): + pass + + self._accept_scope.cancel() + await sleep(0) + + self._raw_socket.close() + + +class UNIXSocketListener(abc.SocketListener): + def __init__(self, raw_socket: socket.socket): + self.__raw_socket = raw_socket + self._loop = get_running_loop() + self._accept_guard = ResourceGuard("accepting connections from") + self._closed = False + + async def accept(self) -> abc.SocketStream: + await AsyncIOBackend.checkpoint() + with self._accept_guard: + while True: + try: + client_sock, _ = self.__raw_socket.accept() + client_sock.setblocking(False) + return UNIXSocketStream(client_sock) + except BlockingIOError: + f: asyncio.Future = asyncio.Future() + self._loop.add_reader(self.__raw_socket, f.set_result, None) + f.add_done_callback( + lambda _: self._loop.remove_reader(self.__raw_socket) + ) + await f + except OSError as exc: + if self._closed: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + + async def aclose(self) -> None: + self._closed = True + self.__raw_socket.close() + + @property + def _raw_socket(self) -> socket.socket: + return self.__raw_socket + + +class UDPSocket(abc.UDPSocket): + def __init__( + self, transport: asyncio.DatagramTransport, protocol: DatagramProtocol + ): + self._transport = transport + self._protocol = protocol + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + self._closed = False + + @property + def _raw_socket(self) -> socket.socket: + return self._transport.get_extra_info("socket") + + async def aclose(self) -> None: + if not self._transport.is_closing(): + self._closed = True + self._transport.close() + + async def receive(self) -> tuple[bytes, IPSockAddrType]: + with self._receive_guard: + await AsyncIOBackend.checkpoint() + + # If the buffer is empty, ask for more data + if not self._protocol.read_queue and not self._transport.is_closing(): + self._protocol.read_event.clear() + await self._protocol.read_event.wait() + + try: + return self._protocol.read_queue.popleft() + except IndexError: + if self._closed: + raise ClosedResourceError from None + else: + raise BrokenResourceError from None + + async def send(self, item: UDPPacketType) -> None: + with self._send_guard: + await AsyncIOBackend.checkpoint() + await self._protocol.write_event.wait() + if self._closed: + raise ClosedResourceError + elif self._transport.is_closing(): + raise BrokenResourceError + else: + self._transport.sendto(*item) + + +class ConnectedUDPSocket(abc.ConnectedUDPSocket): + def __init__( + self, transport: asyncio.DatagramTransport, protocol: DatagramProtocol + ): + self._transport = transport + self._protocol = protocol + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + self._closed = False + + @property + def _raw_socket(self) -> socket.socket: + return self._transport.get_extra_info("socket") + + async def aclose(self) -> None: + if not self._transport.is_closing(): + self._closed = True + self._transport.close() + + async def receive(self) -> bytes: + with self._receive_guard: + await AsyncIOBackend.checkpoint() + + # If the buffer is empty, ask for more data + if not self._protocol.read_queue and not self._transport.is_closing(): + self._protocol.read_event.clear() + await self._protocol.read_event.wait() + + try: + packet = self._protocol.read_queue.popleft() + except IndexError: + if self._closed: + raise ClosedResourceError from None + else: + raise BrokenResourceError from None + + return packet[0] + + async def send(self, item: bytes) -> None: + with self._send_guard: + await AsyncIOBackend.checkpoint() + await self._protocol.write_event.wait() + if self._closed: + raise ClosedResourceError + elif self._transport.is_closing(): + raise BrokenResourceError + else: + self._transport.sendto(item) + + +class UNIXDatagramSocket(_RawSocketMixin, abc.UNIXDatagramSocket): + async def receive(self) -> UNIXDatagramPacketType: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._receive_guard: + while True: + try: + data = self._raw_socket.recvfrom(65536) + except BlockingIOError: + await self._wait_until_readable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + return data + + async def send(self, item: UNIXDatagramPacketType) -> None: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._send_guard: + while True: + try: + self._raw_socket.sendto(*item) + except BlockingIOError: + await self._wait_until_writable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + return + + +class ConnectedUNIXDatagramSocket(_RawSocketMixin, abc.ConnectedUNIXDatagramSocket): + async def receive(self) -> bytes: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._receive_guard: + while True: + try: + data = self._raw_socket.recv(65536) + except BlockingIOError: + await self._wait_until_readable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + return data + + async def send(self, item: bytes) -> None: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._send_guard: + while True: + try: + self._raw_socket.send(item) + except BlockingIOError: + await self._wait_until_writable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + return + + +_read_events: RunVar[dict[int, asyncio.Future[bool]]] = RunVar("read_events") +_write_events: RunVar[dict[int, asyncio.Future[bool]]] = RunVar("write_events") + + +# +# Synchronization +# + + +class Event(BaseEvent): + def __new__(cls) -> Event: + return object.__new__(cls) + + def __init__(self) -> None: + self._event = asyncio.Event() + + def set(self) -> None: + self._event.set() + + def is_set(self) -> bool: + return self._event.is_set() + + async def wait(self) -> None: + if self.is_set(): + await AsyncIOBackend.checkpoint() + else: + await self._event.wait() + + def statistics(self) -> EventStatistics: + return EventStatistics(len(self._event._waiters)) + + +class Lock(BaseLock): + def __new__(cls, *, fast_acquire: bool = False) -> Lock: + return object.__new__(cls) + + def __init__(self, *, fast_acquire: bool = False) -> None: + self._fast_acquire = fast_acquire + self._owner_task: asyncio.Task | None = None + self._waiters: deque[tuple[asyncio.Task, asyncio.Future]] = deque() + + async def acquire(self) -> None: + task = cast(asyncio.Task, current_task()) + if self._owner_task is None and not self._waiters: + await AsyncIOBackend.checkpoint_if_cancelled() + self._owner_task = task + + # Unless on the "fast path", yield control of the event loop so that other + # tasks can run too + if not self._fast_acquire: + try: + await AsyncIOBackend.cancel_shielded_checkpoint() + except CancelledError: + self.release() + raise + + return + + if self._owner_task == task: + raise RuntimeError("Attempted to acquire an already held Lock") + + fut: asyncio.Future[None] = asyncio.Future() + item = task, fut + self._waiters.append(item) + try: + await fut + except CancelledError: + self._waiters.remove(item) + if self._owner_task is task: + self.release() + + raise + + self._waiters.remove(item) + + def acquire_nowait(self) -> None: + task = cast(asyncio.Task, current_task()) + if self._owner_task is None and not self._waiters: + self._owner_task = task + return + + if self._owner_task is task: + raise RuntimeError("Attempted to acquire an already held Lock") + + raise WouldBlock + + def locked(self) -> bool: + return self._owner_task is not None + + def release(self) -> None: + if self._owner_task != current_task(): + raise RuntimeError("The current task is not holding this lock") + + for task, fut in self._waiters: + if not fut.cancelled(): + self._owner_task = task + fut.set_result(None) + return + + self._owner_task = None + + def statistics(self) -> LockStatistics: + task_info = AsyncIOTaskInfo(self._owner_task) if self._owner_task else None + return LockStatistics(self.locked(), task_info, len(self._waiters)) + + +class Semaphore(BaseSemaphore): + def __new__( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> Semaphore: + return object.__new__(cls) + + def __init__( + self, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ): + super().__init__(initial_value, max_value=max_value) + self._value = initial_value + self._max_value = max_value + self._fast_acquire = fast_acquire + self._waiters: deque[asyncio.Future[None]] = deque() + + async def acquire(self) -> None: + if self._value > 0 and not self._waiters: + await AsyncIOBackend.checkpoint_if_cancelled() + self._value -= 1 + + # Unless on the "fast path", yield control of the event loop so that other + # tasks can run too + if not self._fast_acquire: + try: + await AsyncIOBackend.cancel_shielded_checkpoint() + except CancelledError: + self.release() + raise + + return + + fut: asyncio.Future[None] = asyncio.Future() + self._waiters.append(fut) + try: + await fut + except CancelledError: + try: + self._waiters.remove(fut) + except ValueError: + self.release() + + raise + + def acquire_nowait(self) -> None: + if self._value == 0: + raise WouldBlock + + self._value -= 1 + + def release(self) -> None: + if self._max_value is not None and self._value == self._max_value: + raise ValueError("semaphore released too many times") + + for fut in self._waiters: + if not fut.cancelled(): + fut.set_result(None) + self._waiters.remove(fut) + return + + self._value += 1 + + @property + def value(self) -> int: + return self._value + + @property + def max_value(self) -> int | None: + return self._max_value + + def statistics(self) -> SemaphoreStatistics: + return SemaphoreStatistics(len(self._waiters)) + + +class CapacityLimiter(BaseCapacityLimiter): + _total_tokens: float = 0 + + def __new__(cls, total_tokens: float) -> CapacityLimiter: + return object.__new__(cls) + + def __init__(self, total_tokens: float): + self._borrowers: set[Any] = set() + self._wait_queue: OrderedDict[Any, asyncio.Event] = OrderedDict() + self.total_tokens = total_tokens + + async def __aenter__(self) -> None: + await self.acquire() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.release() + + @property + def total_tokens(self) -> float: + return self._total_tokens + + @total_tokens.setter + def total_tokens(self, value: float) -> None: + if not isinstance(value, int) and not math.isinf(value): + raise TypeError("total_tokens must be an int or math.inf") + if value < 1: + raise ValueError("total_tokens must be >= 1") + + waiters_to_notify = max(value - self._total_tokens, 0) + self._total_tokens = value + + # Notify waiting tasks that they have acquired the limiter + while self._wait_queue and waiters_to_notify: + event = self._wait_queue.popitem(last=False)[1] + event.set() + waiters_to_notify -= 1 + + @property + def borrowed_tokens(self) -> int: + return len(self._borrowers) + + @property + def available_tokens(self) -> float: + return self._total_tokens - len(self._borrowers) + + def _notify_next_waiter(self) -> None: + """Notify the next task in line if this limiter has free capacity now.""" + if self._wait_queue and len(self._borrowers) < self._total_tokens: + event = self._wait_queue.popitem(last=False)[1] + event.set() + + def acquire_nowait(self) -> None: + self.acquire_on_behalf_of_nowait(current_task()) + + def acquire_on_behalf_of_nowait(self, borrower: object) -> None: + if borrower in self._borrowers: + raise RuntimeError( + "this borrower is already holding one of this CapacityLimiter's tokens" + ) + + if self._wait_queue or len(self._borrowers) >= self._total_tokens: + raise WouldBlock + + self._borrowers.add(borrower) + + async def acquire(self) -> None: + return await self.acquire_on_behalf_of(current_task()) + + async def acquire_on_behalf_of(self, borrower: object) -> None: + await AsyncIOBackend.checkpoint_if_cancelled() + try: + self.acquire_on_behalf_of_nowait(borrower) + except WouldBlock: + event = asyncio.Event() + self._wait_queue[borrower] = event + try: + await event.wait() + except BaseException: + self._wait_queue.pop(borrower, None) + if event.is_set(): + self._notify_next_waiter() + + raise + + self._borrowers.add(borrower) + else: + try: + await AsyncIOBackend.cancel_shielded_checkpoint() + except BaseException: + self.release() + raise + + def release(self) -> None: + self.release_on_behalf_of(current_task()) + + def release_on_behalf_of(self, borrower: object) -> None: + try: + self._borrowers.remove(borrower) + except KeyError: + raise RuntimeError( + "this borrower isn't holding any of this CapacityLimiter's tokens" + ) from None + + self._notify_next_waiter() + + def statistics(self) -> CapacityLimiterStatistics: + return CapacityLimiterStatistics( + self.borrowed_tokens, + self.total_tokens, + tuple(self._borrowers), + len(self._wait_queue), + ) + + +_default_thread_limiter: RunVar[CapacityLimiter] = RunVar("_default_thread_limiter") + + +# +# Operating system signals +# + + +class _SignalReceiver: + def __init__(self, signals: tuple[Signals, ...]): + self._signals = signals + self._loop = get_running_loop() + self._signal_queue: deque[Signals] = deque() + self._future: asyncio.Future = asyncio.Future() + self._handled_signals: set[Signals] = set() + + def _deliver(self, signum: Signals) -> None: + self._signal_queue.append(signum) + if not self._future.done(): + self._future.set_result(None) + + def __enter__(self) -> _SignalReceiver: + for sig in set(self._signals): + self._loop.add_signal_handler(sig, self._deliver, sig) + self._handled_signals.add(sig) + + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + for sig in self._handled_signals: + self._loop.remove_signal_handler(sig) + + def __aiter__(self) -> _SignalReceiver: + return self + + async def __anext__(self) -> Signals: + await AsyncIOBackend.checkpoint() + if not self._signal_queue: + self._future = asyncio.Future() + await self._future + + return self._signal_queue.popleft() + + +# +# Testing and debugging +# + + +class AsyncIOTaskInfo(TaskInfo): + def __init__(self, task: asyncio.Task): + task_state = _task_states.get(task) + if task_state is None: + parent_id = None + else: + parent_id = task_state.parent_id + + coro = task.get_coro() + assert coro is not None, "created TaskInfo from a completed Task" + super().__init__(id(task), parent_id, task.get_name(), coro) + self._task = weakref.ref(task) + + def has_pending_cancellation(self) -> bool: + if not (task := self._task()): + # If the task isn't around anymore, it won't have a pending cancellation + return False + + if task._must_cancel: # type: ignore[attr-defined] + return True + elif ( + isinstance(task._fut_waiter, asyncio.Future) # type: ignore[attr-defined] + and task._fut_waiter.cancelled() # type: ignore[attr-defined] + ): + return True + + if task_state := _task_states.get(task): + if cancel_scope := task_state.cancel_scope: + return cancel_scope._effectively_cancelled + + return False + + +class TestRunner(abc.TestRunner): + _send_stream: MemoryObjectSendStream[tuple[Awaitable[Any], asyncio.Future[Any]]] + + def __init__( + self, + *, + debug: bool | None = None, + use_uvloop: bool = False, + loop_factory: Callable[[], AbstractEventLoop] | None = None, + ) -> None: + if use_uvloop and loop_factory is None: + import uvloop + + loop_factory = uvloop.new_event_loop + + self._runner = Runner(debug=debug, loop_factory=loop_factory) + self._exceptions: list[BaseException] = [] + self._runner_task: asyncio.Task | None = None + + def __enter__(self) -> TestRunner: + self._runner.__enter__() + self.get_loop().set_exception_handler(self._exception_handler) + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self._runner.__exit__(exc_type, exc_val, exc_tb) + + def get_loop(self) -> AbstractEventLoop: + return self._runner.get_loop() + + def _exception_handler( + self, loop: asyncio.AbstractEventLoop, context: dict[str, Any] + ) -> None: + if isinstance(context.get("exception"), Exception): + self._exceptions.append(context["exception"]) + else: + loop.default_exception_handler(context) + + def _raise_async_exceptions(self) -> None: + # Re-raise any exceptions raised in asynchronous callbacks + if self._exceptions: + exceptions, self._exceptions = self._exceptions, [] + if len(exceptions) == 1: + raise exceptions[0] + elif exceptions: + raise BaseExceptionGroup( + "Multiple exceptions occurred in asynchronous callbacks", exceptions + ) + + async def _run_tests_and_fixtures( + self, + receive_stream: MemoryObjectReceiveStream[ + tuple[Awaitable[T_Retval], asyncio.Future[T_Retval]] + ], + ) -> None: + from _pytest.outcomes import OutcomeException + + with receive_stream, self._send_stream: + async for coro, future in receive_stream: + try: + retval = await coro + except CancelledError as exc: + if not future.cancelled(): + future.cancel(*exc.args) + + raise + except BaseException as exc: + if not future.cancelled(): + future.set_exception(exc) + + if not isinstance(exc, (Exception, OutcomeException)): + raise + else: + if not future.cancelled(): + future.set_result(retval) + + async def _call_in_runner_task( + self, + func: Callable[P, Awaitable[T_Retval]], + *args: P.args, + **kwargs: P.kwargs, + ) -> T_Retval: + if not self._runner_task: + self._send_stream, receive_stream = create_memory_object_stream[ + tuple[Awaitable[Any], asyncio.Future] + ](1) + self._runner_task = self.get_loop().create_task( + self._run_tests_and_fixtures(receive_stream) + ) + + coro = func(*args, **kwargs) + future: asyncio.Future[T_Retval] = self.get_loop().create_future() + self._send_stream.send_nowait((coro, future)) + return await future + + def run_asyncgen_fixture( + self, + fixture_func: Callable[..., AsyncGenerator[T_Retval, Any]], + kwargs: dict[str, Any], + ) -> Iterable[T_Retval]: + asyncgen = fixture_func(**kwargs) + fixturevalue: T_Retval = self.get_loop().run_until_complete( + self._call_in_runner_task(asyncgen.asend, None) + ) + self._raise_async_exceptions() + + yield fixturevalue + + try: + self.get_loop().run_until_complete( + self._call_in_runner_task(asyncgen.asend, None) + ) + except StopAsyncIteration: + self._raise_async_exceptions() + else: + self.get_loop().run_until_complete(asyncgen.aclose()) + raise RuntimeError("Async generator fixture did not stop") + + def run_fixture( + self, + fixture_func: Callable[..., Coroutine[Any, Any, T_Retval]], + kwargs: dict[str, Any], + ) -> T_Retval: + retval = self.get_loop().run_until_complete( + self._call_in_runner_task(fixture_func, **kwargs) + ) + self._raise_async_exceptions() + return retval + + def run_test( + self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] + ) -> None: + try: + self.get_loop().run_until_complete( + self._call_in_runner_task(test_func, **kwargs) + ) + except Exception as exc: + self._exceptions.append(exc) + + self._raise_async_exceptions() + + +class AsyncIOBackend(AsyncBackend): + @classmethod + def run( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + options: dict[str, Any], + ) -> T_Retval: + @wraps(func) + async def wrapper() -> T_Retval: + task = cast(asyncio.Task, current_task()) + task.set_name(get_callable_name(func)) + _task_states[task] = TaskState(None, None) + + try: + return await func(*args) + finally: + del _task_states[task] + + debug = options.get("debug", None) + loop_factory = options.get("loop_factory", None) + if loop_factory is None and options.get("use_uvloop", False): + import uvloop + + loop_factory = uvloop.new_event_loop + + with Runner(debug=debug, loop_factory=loop_factory) as runner: + return runner.run(wrapper()) + + @classmethod + def current_token(cls) -> object: + return get_running_loop() + + @classmethod + def current_time(cls) -> float: + return get_running_loop().time() + + @classmethod + def cancelled_exception_class(cls) -> type[BaseException]: + return CancelledError + + @classmethod + async def checkpoint(cls) -> None: + await sleep(0) + + @classmethod + async def checkpoint_if_cancelled(cls) -> None: + task = current_task() + if task is None: + return + + try: + cancel_scope = _task_states[task].cancel_scope + except KeyError: + return + + while cancel_scope: + if cancel_scope.cancel_called: + await sleep(0) + elif cancel_scope.shield: + break + else: + cancel_scope = cancel_scope._parent_scope + + @classmethod + async def cancel_shielded_checkpoint(cls) -> None: + with CancelScope(shield=True): + await sleep(0) + + @classmethod + async def sleep(cls, delay: float) -> None: + await sleep(delay) + + @classmethod + def create_cancel_scope( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> CancelScope: + return CancelScope(deadline=deadline, shield=shield) + + @classmethod + def current_effective_deadline(cls) -> float: + if (task := current_task()) is None: + return math.inf + + try: + cancel_scope = _task_states[task].cancel_scope + except KeyError: + return math.inf + + deadline = math.inf + while cancel_scope: + deadline = min(deadline, cancel_scope.deadline) + if cancel_scope._cancel_called: + deadline = -math.inf + break + elif cancel_scope.shield: + break + else: + cancel_scope = cancel_scope._parent_scope + + return deadline + + @classmethod + def create_task_group(cls) -> abc.TaskGroup: + return TaskGroup() + + @classmethod + def create_event(cls) -> abc.Event: + return Event() + + @classmethod + def create_lock(cls, *, fast_acquire: bool) -> abc.Lock: + return Lock(fast_acquire=fast_acquire) + + @classmethod + def create_semaphore( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> abc.Semaphore: + return Semaphore(initial_value, max_value=max_value, fast_acquire=fast_acquire) + + @classmethod + def create_capacity_limiter(cls, total_tokens: float) -> abc.CapacityLimiter: + return CapacityLimiter(total_tokens) + + @classmethod + async def run_sync_in_worker_thread( # type: ignore[return] + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + abandon_on_cancel: bool = False, + limiter: abc.CapacityLimiter | None = None, + ) -> T_Retval: + await cls.checkpoint() + + # If this is the first run in this event loop thread, set up the necessary + # variables + try: + idle_workers = _threadpool_idle_workers.get() + workers = _threadpool_workers.get() + except LookupError: + idle_workers = deque() + workers = set() + _threadpool_idle_workers.set(idle_workers) + _threadpool_workers.set(workers) + + async with limiter or cls.current_default_thread_limiter(): + with CancelScope(shield=not abandon_on_cancel) as scope: + future = asyncio.Future[T_Retval]() + root_task = find_root_task() + if not idle_workers: + worker = WorkerThread(root_task, workers, idle_workers) + worker.start() + workers.add(worker) + root_task.add_done_callback( + worker.stop, context=contextvars.Context() + ) + else: + worker = idle_workers.pop() + + # Prune any other workers that have been idle for MAX_IDLE_TIME + # seconds or longer + now = cls.current_time() + while idle_workers: + if ( + now - idle_workers[0].idle_since + < WorkerThread.MAX_IDLE_TIME + ): + break + + expired_worker = idle_workers.popleft() + expired_worker.root_task.remove_done_callback( + expired_worker.stop + ) + expired_worker.stop() + + context = copy_context() + context.run(sniffio.current_async_library_cvar.set, None) + if abandon_on_cancel or scope._parent_scope is None: + worker_scope = scope + else: + worker_scope = scope._parent_scope + + worker.queue.put_nowait((context, func, args, future, worker_scope)) + return await future + + @classmethod + def check_cancelled(cls) -> None: + scope: CancelScope | None = threadlocals.current_cancel_scope + while scope is not None: + if scope.cancel_called: + raise CancelledError(f"Cancelled by cancel scope {id(scope):x}") + + if scope.shield: + return + + scope = scope._parent_scope + + @classmethod + def run_async_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + async def task_wrapper(scope: CancelScope) -> T_Retval: + __tracebackhide__ = True + task = cast(asyncio.Task, current_task()) + _task_states[task] = TaskState(None, scope) + scope._tasks.add(task) + try: + return await func(*args) + except CancelledError as exc: + raise concurrent.futures.CancelledError(str(exc)) from None + finally: + scope._tasks.discard(task) + + loop = cast(AbstractEventLoop, token) + context = copy_context() + context.run(sniffio.current_async_library_cvar.set, "asyncio") + wrapper = task_wrapper(threadlocals.current_cancel_scope) + f: concurrent.futures.Future[T_Retval] = context.run( + asyncio.run_coroutine_threadsafe, wrapper, loop + ) + return f.result() + + @classmethod + def run_sync_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + @wraps(func) + def wrapper() -> None: + try: + sniffio.current_async_library_cvar.set("asyncio") + f.set_result(func(*args)) + except BaseException as exc: + f.set_exception(exc) + if not isinstance(exc, Exception): + raise + + f: concurrent.futures.Future[T_Retval] = Future() + loop = cast(AbstractEventLoop, token) + loop.call_soon_threadsafe(wrapper) + return f.result() + + @classmethod + def create_blocking_portal(cls) -> abc.BlockingPortal: + return BlockingPortal() + + @classmethod + async def open_process( + cls, + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + stdin: int | IO[Any] | None, + stdout: int | IO[Any] | None, + stderr: int | IO[Any] | None, + **kwargs: Any, + ) -> Process: + await cls.checkpoint() + if isinstance(command, PathLike): + command = os.fspath(command) + + if isinstance(command, (str, bytes)): + process = await asyncio.create_subprocess_shell( + command, + stdin=stdin, + stdout=stdout, + stderr=stderr, + **kwargs, + ) + else: + process = await asyncio.create_subprocess_exec( + *command, + stdin=stdin, + stdout=stdout, + stderr=stderr, + **kwargs, + ) + + stdin_stream = StreamWriterWrapper(process.stdin) if process.stdin else None + stdout_stream = StreamReaderWrapper(process.stdout) if process.stdout else None + stderr_stream = StreamReaderWrapper(process.stderr) if process.stderr else None + return Process(process, stdin_stream, stdout_stream, stderr_stream) + + @classmethod + def setup_process_pool_exit_at_shutdown(cls, workers: set[abc.Process]) -> None: + create_task( + _shutdown_process_pool_on_exit(workers), + name="AnyIO process pool shutdown task", + ) + find_root_task().add_done_callback( + partial(_forcibly_shutdown_process_pool_on_exit, workers) # type:ignore[arg-type] + ) + + @classmethod + async def connect_tcp( + cls, host: str, port: int, local_address: IPSockAddrType | None = None + ) -> abc.SocketStream: + transport, protocol = cast( + tuple[asyncio.Transport, StreamProtocol], + await get_running_loop().create_connection( + StreamProtocol, host, port, local_addr=local_address + ), + ) + transport.pause_reading() + return SocketStream(transport, protocol) + + @classmethod + async def connect_unix(cls, path: str | bytes) -> abc.UNIXSocketStream: + await cls.checkpoint() + loop = get_running_loop() + raw_socket = socket.socket(socket.AF_UNIX) + raw_socket.setblocking(False) + while True: + try: + raw_socket.connect(path) + except BlockingIOError: + f: asyncio.Future = asyncio.Future() + loop.add_writer(raw_socket, f.set_result, None) + f.add_done_callback(lambda _: loop.remove_writer(raw_socket)) + await f + except BaseException: + raw_socket.close() + raise + else: + return UNIXSocketStream(raw_socket) + + @classmethod + def create_tcp_listener(cls, sock: socket.socket) -> SocketListener: + return TCPSocketListener(sock) + + @classmethod + def create_unix_listener(cls, sock: socket.socket) -> SocketListener: + return UNIXSocketListener(sock) + + @classmethod + async def create_udp_socket( + cls, + family: AddressFamily, + local_address: IPSockAddrType | None, + remote_address: IPSockAddrType | None, + reuse_port: bool, + ) -> UDPSocket | ConnectedUDPSocket: + transport, protocol = await get_running_loop().create_datagram_endpoint( + DatagramProtocol, + local_addr=local_address, + remote_addr=remote_address, + family=family, + reuse_port=reuse_port, + ) + if protocol.exception: + transport.close() + raise protocol.exception + + if not remote_address: + return UDPSocket(transport, protocol) + else: + return ConnectedUDPSocket(transport, protocol) + + @classmethod + async def create_unix_datagram_socket( # type: ignore[override] + cls, raw_socket: socket.socket, remote_path: str | bytes | None + ) -> abc.UNIXDatagramSocket | abc.ConnectedUNIXDatagramSocket: + await cls.checkpoint() + loop = get_running_loop() + + if remote_path: + while True: + try: + raw_socket.connect(remote_path) + except BlockingIOError: + f: asyncio.Future = asyncio.Future() + loop.add_writer(raw_socket, f.set_result, None) + f.add_done_callback(lambda _: loop.remove_writer(raw_socket)) + await f + except BaseException: + raw_socket.close() + raise + else: + return ConnectedUNIXDatagramSocket(raw_socket) + else: + return UNIXDatagramSocket(raw_socket) + + @classmethod + async def getaddrinfo( + cls, + host: bytes | str | None, + port: str | int | None, + *, + family: int | AddressFamily = 0, + type: int | SocketKind = 0, + proto: int = 0, + flags: int = 0, + ) -> Sequence[ + tuple[ + AddressFamily, + SocketKind, + int, + str, + tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], + ] + ]: + return await get_running_loop().getaddrinfo( + host, port, family=family, type=type, proto=proto, flags=flags + ) + + @classmethod + async def getnameinfo( + cls, sockaddr: IPSockAddrType, flags: int = 0 + ) -> tuple[str, str]: + return await get_running_loop().getnameinfo(sockaddr, flags) + + @classmethod + async def wait_readable(cls, obj: FileDescriptorLike) -> None: + try: + read_events = _read_events.get() + except LookupError: + read_events = {} + _read_events.set(read_events) + + fd = obj if isinstance(obj, int) else obj.fileno() + if read_events.get(fd): + raise BusyResourceError("reading from") + + loop = get_running_loop() + fut: asyncio.Future[bool] = loop.create_future() + + def cb() -> None: + try: + del read_events[fd] + except KeyError: + pass + else: + remove_reader(fd) + + try: + fut.set_result(True) + except asyncio.InvalidStateError: + pass + + try: + loop.add_reader(fd, cb) + except NotImplementedError: + from anyio._core._asyncio_selector_thread import get_selector + + selector = get_selector() + selector.add_reader(fd, cb) + remove_reader = selector.remove_reader + else: + remove_reader = loop.remove_reader + + read_events[fd] = fut + try: + success = await fut + finally: + try: + del read_events[fd] + except KeyError: + pass + else: + remove_reader(fd) + + if not success: + raise ClosedResourceError + + @classmethod + async def wait_writable(cls, obj: FileDescriptorLike) -> None: + try: + write_events = _write_events.get() + except LookupError: + write_events = {} + _write_events.set(write_events) + + fd = obj if isinstance(obj, int) else obj.fileno() + if write_events.get(fd): + raise BusyResourceError("writing to") + + loop = get_running_loop() + fut: asyncio.Future[bool] = loop.create_future() + + def cb() -> None: + try: + del write_events[fd] + except KeyError: + pass + else: + remove_writer(fd) + + try: + fut.set_result(True) + except asyncio.InvalidStateError: + pass + + try: + loop.add_writer(fd, cb) + except NotImplementedError: + from anyio._core._asyncio_selector_thread import get_selector + + selector = get_selector() + selector.add_writer(fd, cb) + remove_writer = selector.remove_writer + else: + remove_writer = loop.remove_writer + + write_events[fd] = fut + try: + success = await fut + finally: + try: + del write_events[fd] + except KeyError: + pass + else: + remove_writer(fd) + + if not success: + raise ClosedResourceError + + @classmethod + def notify_closing(cls, obj: FileDescriptorLike) -> None: + fd = obj if isinstance(obj, int) else obj.fileno() + loop = get_running_loop() + + try: + write_events = _write_events.get() + except LookupError: + pass + else: + try: + fut = write_events.pop(fd) + except KeyError: + pass + else: + try: + fut.set_result(False) + except asyncio.InvalidStateError: + pass + + try: + loop.remove_writer(fd) + except NotImplementedError: + from anyio._core._asyncio_selector_thread import get_selector + + get_selector().remove_writer(fd) + + try: + read_events = _read_events.get() + except LookupError: + pass + else: + try: + fut = read_events.pop(fd) + except KeyError: + pass + else: + try: + fut.set_result(False) + except asyncio.InvalidStateError: + pass + + try: + loop.remove_reader(fd) + except NotImplementedError: + from anyio._core._asyncio_selector_thread import get_selector + + get_selector().remove_reader(fd) + + @classmethod + async def wrap_listener_socket(cls, sock: socket.socket) -> SocketListener: + return TCPSocketListener(sock) + + @classmethod + async def wrap_stream_socket(cls, sock: socket.socket) -> SocketStream: + transport, protocol = await get_running_loop().create_connection( + StreamProtocol, sock=sock + ) + return SocketStream(transport, protocol) + + @classmethod + async def wrap_unix_stream_socket(cls, sock: socket.socket) -> UNIXSocketStream: + return UNIXSocketStream(sock) + + @classmethod + async def wrap_udp_socket(cls, sock: socket.socket) -> UDPSocket: + transport, protocol = await get_running_loop().create_datagram_endpoint( + DatagramProtocol, sock=sock + ) + return UDPSocket(transport, protocol) + + @classmethod + async def wrap_connected_udp_socket(cls, sock: socket.socket) -> ConnectedUDPSocket: + transport, protocol = await get_running_loop().create_datagram_endpoint( + DatagramProtocol, sock=sock + ) + return ConnectedUDPSocket(transport, protocol) + + @classmethod + async def wrap_unix_datagram_socket(cls, sock: socket.socket) -> UNIXDatagramSocket: + return UNIXDatagramSocket(sock) + + @classmethod + async def wrap_connected_unix_datagram_socket( + cls, sock: socket.socket + ) -> ConnectedUNIXDatagramSocket: + return ConnectedUNIXDatagramSocket(sock) + + @classmethod + def current_default_thread_limiter(cls) -> CapacityLimiter: + try: + return _default_thread_limiter.get() + except LookupError: + limiter = CapacityLimiter(40) + _default_thread_limiter.set(limiter) + return limiter + + @classmethod + def open_signal_receiver( + cls, *signals: Signals + ) -> AbstractContextManager[AsyncIterator[Signals]]: + return _SignalReceiver(signals) + + @classmethod + def get_current_task(cls) -> TaskInfo: + return AsyncIOTaskInfo(current_task()) # type: ignore[arg-type] + + @classmethod + def get_running_tasks(cls) -> Sequence[TaskInfo]: + return [AsyncIOTaskInfo(task) for task in all_tasks() if not task.done()] + + @classmethod + async def wait_all_tasks_blocked(cls) -> None: + await cls.checkpoint() + this_task = current_task() + while True: + for task in all_tasks(): + if task is this_task: + continue + + waiter = task._fut_waiter # type: ignore[attr-defined] + if waiter is None or waiter.done(): + await sleep(0.1) + break + else: + return + + @classmethod + def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: + return TestRunner(**options) + + +backend_class = AsyncIOBackend diff --git a/venv/lib/python3.10/site-packages/anyio/_backends/_trio.py b/venv/lib/python3.10/site-packages/anyio/_backends/_trio.py new file mode 100644 index 0000000000000000000000000000000000000000..021f11170f0900511f8be3c92441d519c38f0e26 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_backends/_trio.py @@ -0,0 +1,1375 @@ +from __future__ import annotations + +import array +import math +import os +import socket +import sys +import types +import weakref +from collections.abc import ( + AsyncGenerator, + AsyncIterator, + Awaitable, + Callable, + Collection, + Coroutine, + Iterable, + Sequence, +) +from concurrent.futures import Future +from contextlib import AbstractContextManager +from dataclasses import dataclass +from functools import partial +from io import IOBase +from os import PathLike +from signal import Signals +from socket import AddressFamily, SocketKind +from types import TracebackType +from typing import ( + IO, + TYPE_CHECKING, + Any, + Generic, + NoReturn, + TypeVar, + cast, + overload, +) + +import trio.from_thread +import trio.lowlevel +from outcome import Error, Outcome, Value +from trio.lowlevel import ( + current_root_task, + current_task, + notify_closing, + wait_readable, + wait_writable, +) +from trio.socket import SocketType as TrioSocketType +from trio.to_thread import run_sync + +from .. import ( + CapacityLimiterStatistics, + EventStatistics, + LockStatistics, + TaskInfo, + WouldBlock, + abc, +) +from .._core._eventloop import claim_worker_thread +from .._core._exceptions import ( + BrokenResourceError, + BusyResourceError, + ClosedResourceError, + EndOfStream, +) +from .._core._sockets import convert_ipv6_sockaddr +from .._core._streams import create_memory_object_stream +from .._core._synchronization import ( + CapacityLimiter as BaseCapacityLimiter, +) +from .._core._synchronization import Event as BaseEvent +from .._core._synchronization import Lock as BaseLock +from .._core._synchronization import ( + ResourceGuard, + SemaphoreStatistics, +) +from .._core._synchronization import Semaphore as BaseSemaphore +from .._core._tasks import CancelScope as BaseCancelScope +from ..abc import IPSockAddrType, UDPPacketType, UNIXDatagramPacketType +from ..abc._eventloop import AsyncBackend, StrOrBytesPath +from ..streams.memory import MemoryObjectSendStream + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike + +if sys.version_info >= (3, 10): + from typing import ParamSpec +else: + from typing_extensions import ParamSpec + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from exceptiongroup import BaseExceptionGroup + from typing_extensions import TypeVarTuple, Unpack + +T = TypeVar("T") +T_Retval = TypeVar("T_Retval") +T_SockAddr = TypeVar("T_SockAddr", str, IPSockAddrType) +PosArgsT = TypeVarTuple("PosArgsT") +P = ParamSpec("P") + + +# +# Event loop +# + +RunVar = trio.lowlevel.RunVar + + +# +# Timeouts and cancellation +# + + +class CancelScope(BaseCancelScope): + def __new__( + cls, original: trio.CancelScope | None = None, **kwargs: object + ) -> CancelScope: + return object.__new__(cls) + + def __init__(self, original: trio.CancelScope | None = None, **kwargs: Any) -> None: + self.__original = original or trio.CancelScope(**kwargs) + + def __enter__(self) -> CancelScope: + self.__original.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + return self.__original.__exit__(exc_type, exc_val, exc_tb) + + def cancel(self) -> None: + self.__original.cancel() + + @property + def deadline(self) -> float: + return self.__original.deadline + + @deadline.setter + def deadline(self, value: float) -> None: + self.__original.deadline = value + + @property + def cancel_called(self) -> bool: + return self.__original.cancel_called + + @property + def cancelled_caught(self) -> bool: + return self.__original.cancelled_caught + + @property + def shield(self) -> bool: + return self.__original.shield + + @shield.setter + def shield(self, value: bool) -> None: + self.__original.shield = value + + +# +# Task groups +# + + +class TaskGroup(abc.TaskGroup): + def __init__(self) -> None: + self._active = False + self._nursery_manager = trio.open_nursery(strict_exception_groups=True) + self.cancel_scope = None # type: ignore[assignment] + + async def __aenter__(self) -> TaskGroup: + self._active = True + self._nursery = await self._nursery_manager.__aenter__() + self.cancel_scope = CancelScope(self._nursery.cancel_scope) + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + try: + # trio.Nursery.__exit__ returns bool; .open_nursery has wrong type + return await self._nursery_manager.__aexit__(exc_type, exc_val, exc_tb) # type: ignore[return-value] + except BaseExceptionGroup as exc: + if not exc.split(trio.Cancelled)[1]: + raise trio.Cancelled._create() from exc + + raise + finally: + del exc_val, exc_tb + self._active = False + + def start_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], + *args: Unpack[PosArgsT], + name: object = None, + ) -> None: + if not self._active: + raise RuntimeError( + "This task group is not active; no new tasks can be started." + ) + + self._nursery.start_soon(func, *args, name=name) + + async def start( + self, func: Callable[..., Awaitable[Any]], *args: object, name: object = None + ) -> Any: + if not self._active: + raise RuntimeError( + "This task group is not active; no new tasks can be started." + ) + + return await self._nursery.start(func, *args, name=name) + + +# +# Threads +# + + +class BlockingPortal(abc.BlockingPortal): + def __new__(cls) -> BlockingPortal: + return object.__new__(cls) + + def __init__(self) -> None: + super().__init__() + self._token = trio.lowlevel.current_trio_token() + + def _spawn_task_from_thread( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + name: object, + future: Future[T_Retval], + ) -> None: + trio.from_thread.run_sync( + partial(self._task_group.start_soon, name=name), + self._call_func, + func, + args, + kwargs, + future, + trio_token=self._token, + ) + + +# +# Subprocesses +# + + +@dataclass(eq=False) +class ReceiveStreamWrapper(abc.ByteReceiveStream): + _stream: trio.abc.ReceiveStream + + async def receive(self, max_bytes: int | None = None) -> bytes: + try: + data = await self._stream.receive_some(max_bytes) + except trio.ClosedResourceError as exc: + raise ClosedResourceError from exc.__cause__ + except trio.BrokenResourceError as exc: + raise BrokenResourceError from exc.__cause__ + + if data: + return bytes(data) + else: + raise EndOfStream + + async def aclose(self) -> None: + await self._stream.aclose() + + +@dataclass(eq=False) +class SendStreamWrapper(abc.ByteSendStream): + _stream: trio.abc.SendStream + + async def send(self, item: bytes) -> None: + try: + await self._stream.send_all(item) + except trio.ClosedResourceError as exc: + raise ClosedResourceError from exc.__cause__ + except trio.BrokenResourceError as exc: + raise BrokenResourceError from exc.__cause__ + + async def aclose(self) -> None: + await self._stream.aclose() + + +@dataclass(eq=False) +class Process(abc.Process): + _process: trio.Process + _stdin: abc.ByteSendStream | None + _stdout: abc.ByteReceiveStream | None + _stderr: abc.ByteReceiveStream | None + + async def aclose(self) -> None: + with CancelScope(shield=True): + if self._stdin: + await self._stdin.aclose() + if self._stdout: + await self._stdout.aclose() + if self._stderr: + await self._stderr.aclose() + + try: + await self.wait() + except BaseException: + self.kill() + with CancelScope(shield=True): + await self.wait() + raise + + async def wait(self) -> int: + return await self._process.wait() + + def terminate(self) -> None: + self._process.terminate() + + def kill(self) -> None: + self._process.kill() + + def send_signal(self, signal: Signals) -> None: + self._process.send_signal(signal) + + @property + def pid(self) -> int: + return self._process.pid + + @property + def returncode(self) -> int | None: + return self._process.returncode + + @property + def stdin(self) -> abc.ByteSendStream | None: + return self._stdin + + @property + def stdout(self) -> abc.ByteReceiveStream | None: + return self._stdout + + @property + def stderr(self) -> abc.ByteReceiveStream | None: + return self._stderr + + +class _ProcessPoolShutdownInstrument(trio.abc.Instrument): + def after_run(self) -> None: + super().after_run() + + +current_default_worker_process_limiter: trio.lowlevel.RunVar = RunVar( + "current_default_worker_process_limiter" +) + + +async def _shutdown_process_pool(workers: set[abc.Process]) -> None: + try: + await trio.sleep(math.inf) + except trio.Cancelled: + for process in workers: + if process.returncode is None: + process.kill() + + with CancelScope(shield=True): + for process in workers: + await process.aclose() + + +# +# Sockets and networking +# + + +class _TrioSocketMixin(Generic[T_SockAddr]): + def __init__(self, trio_socket: TrioSocketType) -> None: + self._trio_socket = trio_socket + self._closed = False + + def _check_closed(self) -> None: + if self._closed: + raise ClosedResourceError + if self._trio_socket.fileno() < 0: + raise BrokenResourceError + + @property + def _raw_socket(self) -> socket.socket: + return self._trio_socket._sock # type: ignore[attr-defined] + + async def aclose(self) -> None: + if self._trio_socket.fileno() >= 0: + self._closed = True + self._trio_socket.close() + + def _convert_socket_error(self, exc: BaseException) -> NoReturn: + if isinstance(exc, trio.ClosedResourceError): + raise ClosedResourceError from exc + elif self._trio_socket.fileno() < 0 and self._closed: + raise ClosedResourceError from None + elif isinstance(exc, OSError): + raise BrokenResourceError from exc + else: + raise exc + + +class SocketStream(_TrioSocketMixin, abc.SocketStream): + def __init__(self, trio_socket: TrioSocketType) -> None: + super().__init__(trio_socket) + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + async def receive(self, max_bytes: int = 65536) -> bytes: + with self._receive_guard: + try: + data = await self._trio_socket.recv(max_bytes) + except BaseException as exc: + self._convert_socket_error(exc) + + if data: + return data + else: + raise EndOfStream + + async def send(self, item: bytes) -> None: + with self._send_guard: + view = memoryview(item) + while view: + try: + bytes_sent = await self._trio_socket.send(view) + except BaseException as exc: + self._convert_socket_error(exc) + + view = view[bytes_sent:] + + async def send_eof(self) -> None: + self._trio_socket.shutdown(socket.SHUT_WR) + + +class UNIXSocketStream(SocketStream, abc.UNIXSocketStream): + async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: + if not isinstance(msglen, int) or msglen < 0: + raise ValueError("msglen must be a non-negative integer") + if not isinstance(maxfds, int) or maxfds < 1: + raise ValueError("maxfds must be a positive integer") + + fds = array.array("i") + await trio.lowlevel.checkpoint() + with self._receive_guard: + while True: + try: + message, ancdata, flags, addr = await self._trio_socket.recvmsg( + msglen, socket.CMSG_LEN(maxfds * fds.itemsize) + ) + except BaseException as exc: + self._convert_socket_error(exc) + else: + if not message and not ancdata: + raise EndOfStream + + break + + for cmsg_level, cmsg_type, cmsg_data in ancdata: + if cmsg_level != socket.SOL_SOCKET or cmsg_type != socket.SCM_RIGHTS: + raise RuntimeError( + f"Received unexpected ancillary data; message = {message!r}, " + f"cmsg_level = {cmsg_level}, cmsg_type = {cmsg_type}" + ) + + fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) + + return message, list(fds) + + async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: + if not message: + raise ValueError("message must not be empty") + if not fds: + raise ValueError("fds must not be empty") + + filenos: list[int] = [] + for fd in fds: + if isinstance(fd, int): + filenos.append(fd) + elif isinstance(fd, IOBase): + filenos.append(fd.fileno()) + + fdarray = array.array("i", filenos) + await trio.lowlevel.checkpoint() + with self._send_guard: + while True: + try: + await self._trio_socket.sendmsg( + [message], + [ + ( + socket.SOL_SOCKET, + socket.SCM_RIGHTS, + fdarray, + ) + ], + ) + break + except BaseException as exc: + self._convert_socket_error(exc) + + +class TCPSocketListener(_TrioSocketMixin, abc.SocketListener): + def __init__(self, raw_socket: socket.socket): + super().__init__(trio.socket.from_stdlib_socket(raw_socket)) + self._accept_guard = ResourceGuard("accepting connections from") + + async def accept(self) -> SocketStream: + with self._accept_guard: + try: + trio_socket, _addr = await self._trio_socket.accept() + except BaseException as exc: + self._convert_socket_error(exc) + + trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + return SocketStream(trio_socket) + + +class UNIXSocketListener(_TrioSocketMixin, abc.SocketListener): + def __init__(self, raw_socket: socket.socket): + super().__init__(trio.socket.from_stdlib_socket(raw_socket)) + self._accept_guard = ResourceGuard("accepting connections from") + + async def accept(self) -> UNIXSocketStream: + with self._accept_guard: + try: + trio_socket, _addr = await self._trio_socket.accept() + except BaseException as exc: + self._convert_socket_error(exc) + + return UNIXSocketStream(trio_socket) + + +class UDPSocket(_TrioSocketMixin[IPSockAddrType], abc.UDPSocket): + def __init__(self, trio_socket: TrioSocketType) -> None: + super().__init__(trio_socket) + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + async def receive(self) -> tuple[bytes, IPSockAddrType]: + with self._receive_guard: + try: + data, addr = await self._trio_socket.recvfrom(65536) + return data, convert_ipv6_sockaddr(addr) + except BaseException as exc: + self._convert_socket_error(exc) + + async def send(self, item: UDPPacketType) -> None: + with self._send_guard: + try: + await self._trio_socket.sendto(*item) + except BaseException as exc: + self._convert_socket_error(exc) + + +class ConnectedUDPSocket(_TrioSocketMixin[IPSockAddrType], abc.ConnectedUDPSocket): + def __init__(self, trio_socket: TrioSocketType) -> None: + super().__init__(trio_socket) + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + async def receive(self) -> bytes: + with self._receive_guard: + try: + return await self._trio_socket.recv(65536) + except BaseException as exc: + self._convert_socket_error(exc) + + async def send(self, item: bytes) -> None: + with self._send_guard: + try: + await self._trio_socket.send(item) + except BaseException as exc: + self._convert_socket_error(exc) + + +class UNIXDatagramSocket(_TrioSocketMixin[str], abc.UNIXDatagramSocket): + def __init__(self, trio_socket: TrioSocketType) -> None: + super().__init__(trio_socket) + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + async def receive(self) -> UNIXDatagramPacketType: + with self._receive_guard: + try: + data, addr = await self._trio_socket.recvfrom(65536) + return data, addr + except BaseException as exc: + self._convert_socket_error(exc) + + async def send(self, item: UNIXDatagramPacketType) -> None: + with self._send_guard: + try: + await self._trio_socket.sendto(*item) + except BaseException as exc: + self._convert_socket_error(exc) + + +class ConnectedUNIXDatagramSocket( + _TrioSocketMixin[str], abc.ConnectedUNIXDatagramSocket +): + def __init__(self, trio_socket: TrioSocketType) -> None: + super().__init__(trio_socket) + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + async def receive(self) -> bytes: + with self._receive_guard: + try: + return await self._trio_socket.recv(65536) + except BaseException as exc: + self._convert_socket_error(exc) + + async def send(self, item: bytes) -> None: + with self._send_guard: + try: + await self._trio_socket.send(item) + except BaseException as exc: + self._convert_socket_error(exc) + + +# +# Synchronization +# + + +class Event(BaseEvent): + def __new__(cls) -> Event: + return object.__new__(cls) + + def __init__(self) -> None: + self.__original = trio.Event() + + def is_set(self) -> bool: + return self.__original.is_set() + + async def wait(self) -> None: + return await self.__original.wait() + + def statistics(self) -> EventStatistics: + orig_statistics = self.__original.statistics() + return EventStatistics(tasks_waiting=orig_statistics.tasks_waiting) + + def set(self) -> None: + self.__original.set() + + +class Lock(BaseLock): + def __new__(cls, *, fast_acquire: bool = False) -> Lock: + return object.__new__(cls) + + def __init__(self, *, fast_acquire: bool = False) -> None: + self._fast_acquire = fast_acquire + self.__original = trio.Lock() + + @staticmethod + def _convert_runtime_error_msg(exc: RuntimeError) -> None: + if exc.args == ("attempt to re-acquire an already held Lock",): + exc.args = ("Attempted to acquire an already held Lock",) + + async def acquire(self) -> None: + if not self._fast_acquire: + try: + await self.__original.acquire() + except RuntimeError as exc: + self._convert_runtime_error_msg(exc) + raise + + return + + # This is the "fast path" where we don't let other tasks run + await trio.lowlevel.checkpoint_if_cancelled() + try: + self.__original.acquire_nowait() + except trio.WouldBlock: + await self.__original._lot.park() + except RuntimeError as exc: + self._convert_runtime_error_msg(exc) + raise + + def acquire_nowait(self) -> None: + try: + self.__original.acquire_nowait() + except trio.WouldBlock: + raise WouldBlock from None + except RuntimeError as exc: + self._convert_runtime_error_msg(exc) + raise + + def locked(self) -> bool: + return self.__original.locked() + + def release(self) -> None: + self.__original.release() + + def statistics(self) -> LockStatistics: + orig_statistics = self.__original.statistics() + owner = TrioTaskInfo(orig_statistics.owner) if orig_statistics.owner else None + return LockStatistics( + orig_statistics.locked, owner, orig_statistics.tasks_waiting + ) + + +class Semaphore(BaseSemaphore): + def __new__( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> Semaphore: + return object.__new__(cls) + + def __init__( + self, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> None: + super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire) + self.__original = trio.Semaphore(initial_value, max_value=max_value) + + async def acquire(self) -> None: + if not self._fast_acquire: + await self.__original.acquire() + return + + # This is the "fast path" where we don't let other tasks run + await trio.lowlevel.checkpoint_if_cancelled() + try: + self.__original.acquire_nowait() + except trio.WouldBlock: + await self.__original._lot.park() + + def acquire_nowait(self) -> None: + try: + self.__original.acquire_nowait() + except trio.WouldBlock: + raise WouldBlock from None + + @property + def max_value(self) -> int | None: + return self.__original.max_value + + @property + def value(self) -> int: + return self.__original.value + + def release(self) -> None: + self.__original.release() + + def statistics(self) -> SemaphoreStatistics: + orig_statistics = self.__original.statistics() + return SemaphoreStatistics(orig_statistics.tasks_waiting) + + +class CapacityLimiter(BaseCapacityLimiter): + def __new__( + cls, + total_tokens: float | None = None, + *, + original: trio.CapacityLimiter | None = None, + ) -> CapacityLimiter: + return object.__new__(cls) + + def __init__( + self, + total_tokens: float | None = None, + *, + original: trio.CapacityLimiter | None = None, + ) -> None: + if original is not None: + self.__original = original + else: + assert total_tokens is not None + self.__original = trio.CapacityLimiter(total_tokens) + + async def __aenter__(self) -> None: + return await self.__original.__aenter__() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.__original.__aexit__(exc_type, exc_val, exc_tb) + + @property + def total_tokens(self) -> float: + return self.__original.total_tokens + + @total_tokens.setter + def total_tokens(self, value: float) -> None: + self.__original.total_tokens = value + + @property + def borrowed_tokens(self) -> int: + return self.__original.borrowed_tokens + + @property + def available_tokens(self) -> float: + return self.__original.available_tokens + + def acquire_nowait(self) -> None: + self.__original.acquire_nowait() + + def acquire_on_behalf_of_nowait(self, borrower: object) -> None: + self.__original.acquire_on_behalf_of_nowait(borrower) + + async def acquire(self) -> None: + await self.__original.acquire() + + async def acquire_on_behalf_of(self, borrower: object) -> None: + await self.__original.acquire_on_behalf_of(borrower) + + def release(self) -> None: + return self.__original.release() + + def release_on_behalf_of(self, borrower: object) -> None: + return self.__original.release_on_behalf_of(borrower) + + def statistics(self) -> CapacityLimiterStatistics: + orig = self.__original.statistics() + return CapacityLimiterStatistics( + borrowed_tokens=orig.borrowed_tokens, + total_tokens=orig.total_tokens, + borrowers=tuple(orig.borrowers), + tasks_waiting=orig.tasks_waiting, + ) + + +_capacity_limiter_wrapper: trio.lowlevel.RunVar = RunVar("_capacity_limiter_wrapper") + + +# +# Signal handling +# + + +class _SignalReceiver: + _iterator: AsyncIterator[int] + + def __init__(self, signals: tuple[Signals, ...]): + self._signals = signals + + def __enter__(self) -> _SignalReceiver: + self._cm = trio.open_signal_receiver(*self._signals) + self._iterator = self._cm.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool | None: + return self._cm.__exit__(exc_type, exc_val, exc_tb) + + def __aiter__(self) -> _SignalReceiver: + return self + + async def __anext__(self) -> Signals: + signum = await self._iterator.__anext__() + return Signals(signum) + + +# +# Testing and debugging +# + + +class TestRunner(abc.TestRunner): + def __init__(self, **options: Any) -> None: + from queue import Queue + + self._call_queue: Queue[Callable[[], object]] = Queue() + self._send_stream: MemoryObjectSendStream | None = None + self._options = options + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> None: + if self._send_stream: + self._send_stream.close() + while self._send_stream is not None: + self._call_queue.get()() + + async def _run_tests_and_fixtures(self) -> None: + self._send_stream, receive_stream = create_memory_object_stream(1) + with receive_stream: + async for coro, outcome_holder in receive_stream: + try: + retval = await coro + except BaseException as exc: + outcome_holder.append(Error(exc)) + else: + outcome_holder.append(Value(retval)) + + def _main_task_finished(self, outcome: object) -> None: + self._send_stream = None + + def _call_in_runner_task( + self, + func: Callable[P, Awaitable[T_Retval]], + *args: P.args, + **kwargs: P.kwargs, + ) -> T_Retval: + if self._send_stream is None: + trio.lowlevel.start_guest_run( + self._run_tests_and_fixtures, + run_sync_soon_threadsafe=self._call_queue.put, + done_callback=self._main_task_finished, + **self._options, + ) + while self._send_stream is None: + self._call_queue.get()() + + outcome_holder: list[Outcome] = [] + self._send_stream.send_nowait((func(*args, **kwargs), outcome_holder)) + while not outcome_holder: + self._call_queue.get()() + + return outcome_holder[0].unwrap() + + def run_asyncgen_fixture( + self, + fixture_func: Callable[..., AsyncGenerator[T_Retval, Any]], + kwargs: dict[str, Any], + ) -> Iterable[T_Retval]: + asyncgen = fixture_func(**kwargs) + fixturevalue: T_Retval = self._call_in_runner_task(asyncgen.asend, None) + + yield fixturevalue + + try: + self._call_in_runner_task(asyncgen.asend, None) + except StopAsyncIteration: + pass + else: + self._call_in_runner_task(asyncgen.aclose) + raise RuntimeError("Async generator fixture did not stop") + + def run_fixture( + self, + fixture_func: Callable[..., Coroutine[Any, Any, T_Retval]], + kwargs: dict[str, Any], + ) -> T_Retval: + return self._call_in_runner_task(fixture_func, **kwargs) + + def run_test( + self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] + ) -> None: + self._call_in_runner_task(test_func, **kwargs) + + +class TrioTaskInfo(TaskInfo): + def __init__(self, task: trio.lowlevel.Task): + parent_id = None + if task.parent_nursery and task.parent_nursery.parent_task: + parent_id = id(task.parent_nursery.parent_task) + + super().__init__(id(task), parent_id, task.name, task.coro) + self._task = weakref.proxy(task) + + def has_pending_cancellation(self) -> bool: + try: + return self._task._cancel_status.effectively_cancelled + except ReferenceError: + # If the task is no longer around, it surely doesn't have a cancellation + # pending + return False + + +class TrioBackend(AsyncBackend): + @classmethod + def run( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + options: dict[str, Any], + ) -> T_Retval: + return trio.run(func, *args) + + @classmethod + def current_token(cls) -> object: + return trio.lowlevel.current_trio_token() + + @classmethod + def current_time(cls) -> float: + return trio.current_time() + + @classmethod + def cancelled_exception_class(cls) -> type[BaseException]: + return trio.Cancelled + + @classmethod + async def checkpoint(cls) -> None: + await trio.lowlevel.checkpoint() + + @classmethod + async def checkpoint_if_cancelled(cls) -> None: + await trio.lowlevel.checkpoint_if_cancelled() + + @classmethod + async def cancel_shielded_checkpoint(cls) -> None: + await trio.lowlevel.cancel_shielded_checkpoint() + + @classmethod + async def sleep(cls, delay: float) -> None: + await trio.sleep(delay) + + @classmethod + def create_cancel_scope( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> abc.CancelScope: + return CancelScope(deadline=deadline, shield=shield) + + @classmethod + def current_effective_deadline(cls) -> float: + return trio.current_effective_deadline() + + @classmethod + def create_task_group(cls) -> abc.TaskGroup: + return TaskGroup() + + @classmethod + def create_event(cls) -> abc.Event: + return Event() + + @classmethod + def create_lock(cls, *, fast_acquire: bool) -> Lock: + return Lock(fast_acquire=fast_acquire) + + @classmethod + def create_semaphore( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> abc.Semaphore: + return Semaphore(initial_value, max_value=max_value, fast_acquire=fast_acquire) + + @classmethod + def create_capacity_limiter(cls, total_tokens: float) -> CapacityLimiter: + return CapacityLimiter(total_tokens) + + @classmethod + async def run_sync_in_worker_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + abandon_on_cancel: bool = False, + limiter: abc.CapacityLimiter | None = None, + ) -> T_Retval: + def wrapper() -> T_Retval: + with claim_worker_thread(TrioBackend, token): + return func(*args) + + token = TrioBackend.current_token() + return await run_sync( + wrapper, + abandon_on_cancel=abandon_on_cancel, + limiter=cast(trio.CapacityLimiter, limiter), + ) + + @classmethod + def check_cancelled(cls) -> None: + trio.from_thread.check_cancelled() + + @classmethod + def run_async_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + return trio.from_thread.run(func, *args) + + @classmethod + def run_sync_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + return trio.from_thread.run_sync(func, *args) + + @classmethod + def create_blocking_portal(cls) -> abc.BlockingPortal: + return BlockingPortal() + + @classmethod + async def open_process( + cls, + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + stdin: int | IO[Any] | None, + stdout: int | IO[Any] | None, + stderr: int | IO[Any] | None, + **kwargs: Any, + ) -> Process: + def convert_item(item: StrOrBytesPath) -> str: + str_or_bytes = os.fspath(item) + if isinstance(str_or_bytes, str): + return str_or_bytes + else: + return os.fsdecode(str_or_bytes) + + if isinstance(command, (str, bytes, PathLike)): + process = await trio.lowlevel.open_process( + convert_item(command), + stdin=stdin, + stdout=stdout, + stderr=stderr, + shell=True, + **kwargs, + ) + else: + process = await trio.lowlevel.open_process( + [convert_item(item) for item in command], + stdin=stdin, + stdout=stdout, + stderr=stderr, + shell=False, + **kwargs, + ) + + stdin_stream = SendStreamWrapper(process.stdin) if process.stdin else None + stdout_stream = ReceiveStreamWrapper(process.stdout) if process.stdout else None + stderr_stream = ReceiveStreamWrapper(process.stderr) if process.stderr else None + return Process(process, stdin_stream, stdout_stream, stderr_stream) + + @classmethod + def setup_process_pool_exit_at_shutdown(cls, workers: set[abc.Process]) -> None: + trio.lowlevel.spawn_system_task(_shutdown_process_pool, workers) + + @classmethod + async def connect_tcp( + cls, host: str, port: int, local_address: IPSockAddrType | None = None + ) -> SocketStream: + family = socket.AF_INET6 if ":" in host else socket.AF_INET + trio_socket = trio.socket.socket(family) + trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + if local_address: + await trio_socket.bind(local_address) + + try: + await trio_socket.connect((host, port)) + except BaseException: + trio_socket.close() + raise + + return SocketStream(trio_socket) + + @classmethod + async def connect_unix(cls, path: str | bytes) -> abc.UNIXSocketStream: + trio_socket = trio.socket.socket(socket.AF_UNIX) + try: + await trio_socket.connect(path) + except BaseException: + trio_socket.close() + raise + + return UNIXSocketStream(trio_socket) + + @classmethod + def create_tcp_listener(cls, sock: socket.socket) -> abc.SocketListener: + return TCPSocketListener(sock) + + @classmethod + def create_unix_listener(cls, sock: socket.socket) -> abc.SocketListener: + return UNIXSocketListener(sock) + + @classmethod + async def create_udp_socket( + cls, + family: socket.AddressFamily, + local_address: IPSockAddrType | None, + remote_address: IPSockAddrType | None, + reuse_port: bool, + ) -> UDPSocket | ConnectedUDPSocket: + trio_socket = trio.socket.socket(family=family, type=socket.SOCK_DGRAM) + + if reuse_port: + trio_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + + if local_address: + await trio_socket.bind(local_address) + + if remote_address: + await trio_socket.connect(remote_address) + return ConnectedUDPSocket(trio_socket) + else: + return UDPSocket(trio_socket) + + @classmethod + @overload + async def create_unix_datagram_socket( + cls, raw_socket: socket.socket, remote_path: None + ) -> abc.UNIXDatagramSocket: ... + + @classmethod + @overload + async def create_unix_datagram_socket( + cls, raw_socket: socket.socket, remote_path: str | bytes + ) -> abc.ConnectedUNIXDatagramSocket: ... + + @classmethod + async def create_unix_datagram_socket( + cls, raw_socket: socket.socket, remote_path: str | bytes | None + ) -> abc.UNIXDatagramSocket | abc.ConnectedUNIXDatagramSocket: + trio_socket = trio.socket.from_stdlib_socket(raw_socket) + + if remote_path: + await trio_socket.connect(remote_path) + return ConnectedUNIXDatagramSocket(trio_socket) + else: + return UNIXDatagramSocket(trio_socket) + + @classmethod + async def getaddrinfo( + cls, + host: bytes | str | None, + port: str | int | None, + *, + family: int | AddressFamily = 0, + type: int | SocketKind = 0, + proto: int = 0, + flags: int = 0, + ) -> Sequence[ + tuple[ + AddressFamily, + SocketKind, + int, + str, + tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], + ] + ]: + return await trio.socket.getaddrinfo(host, port, family, type, proto, flags) + + @classmethod + async def getnameinfo( + cls, sockaddr: IPSockAddrType, flags: int = 0 + ) -> tuple[str, str]: + return await trio.socket.getnameinfo(sockaddr, flags) + + @classmethod + async def wait_readable(cls, obj: FileDescriptorLike) -> None: + try: + await wait_readable(obj) + except trio.ClosedResourceError as exc: + raise ClosedResourceError().with_traceback(exc.__traceback__) from None + except trio.BusyResourceError: + raise BusyResourceError("reading from") from None + + @classmethod + async def wait_writable(cls, obj: FileDescriptorLike) -> None: + try: + await wait_writable(obj) + except trio.ClosedResourceError as exc: + raise ClosedResourceError().with_traceback(exc.__traceback__) from None + except trio.BusyResourceError: + raise BusyResourceError("writing to") from None + + @classmethod + def notify_closing(cls, obj: FileDescriptorLike) -> None: + notify_closing(obj) + + @classmethod + async def wrap_listener_socket(cls, sock: socket.socket) -> abc.SocketListener: + return TCPSocketListener(sock) + + @classmethod + async def wrap_stream_socket(cls, sock: socket.socket) -> SocketStream: + trio_sock = trio.socket.from_stdlib_socket(sock) + return SocketStream(trio_sock) + + @classmethod + async def wrap_unix_stream_socket(cls, sock: socket.socket) -> UNIXSocketStream: + trio_sock = trio.socket.from_stdlib_socket(sock) + return UNIXSocketStream(trio_sock) + + @classmethod + async def wrap_udp_socket(cls, sock: socket.socket) -> UDPSocket: + trio_sock = trio.socket.from_stdlib_socket(sock) + return UDPSocket(trio_sock) + + @classmethod + async def wrap_connected_udp_socket(cls, sock: socket.socket) -> ConnectedUDPSocket: + trio_sock = trio.socket.from_stdlib_socket(sock) + return ConnectedUDPSocket(trio_sock) + + @classmethod + async def wrap_unix_datagram_socket(cls, sock: socket.socket) -> UNIXDatagramSocket: + trio_sock = trio.socket.from_stdlib_socket(sock) + return UNIXDatagramSocket(trio_sock) + + @classmethod + async def wrap_connected_unix_datagram_socket( + cls, sock: socket.socket + ) -> ConnectedUNIXDatagramSocket: + trio_sock = trio.socket.from_stdlib_socket(sock) + return ConnectedUNIXDatagramSocket(trio_sock) + + @classmethod + def current_default_thread_limiter(cls) -> CapacityLimiter: + try: + return _capacity_limiter_wrapper.get() + except LookupError: + limiter = CapacityLimiter( + original=trio.to_thread.current_default_thread_limiter() + ) + _capacity_limiter_wrapper.set(limiter) + return limiter + + @classmethod + def open_signal_receiver( + cls, *signals: Signals + ) -> AbstractContextManager[AsyncIterator[Signals]]: + return _SignalReceiver(signals) + + @classmethod + def get_current_task(cls) -> TaskInfo: + task = current_task() + return TrioTaskInfo(task) + + @classmethod + def get_running_tasks(cls) -> Sequence[TaskInfo]: + root_task = current_root_task() + assert root_task + task_infos = [TrioTaskInfo(root_task)] + nurseries = root_task.child_nurseries + while nurseries: + new_nurseries: list[trio.Nursery] = [] + for nursery in nurseries: + for task in nursery.child_tasks: + task_infos.append(TrioTaskInfo(task)) + new_nurseries.extend(task.child_nurseries) + + nurseries = new_nurseries + + return task_infos + + @classmethod + async def wait_all_tasks_blocked(cls) -> None: + from trio.testing import wait_all_tasks_blocked + + await wait_all_tasks_blocked() + + @classmethod + def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: + return TestRunner(**options) + + +backend_class = TrioBackend diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__init__.py b/venv/lib/python3.10/site-packages/anyio/_core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ad50aff3ea903bf75aa248a08946653fc2ebd12 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_asyncio_selector_thread.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_asyncio_selector_thread.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff7cfec78c499e965c128e83ae294a717057b65b Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_asyncio_selector_thread.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_contextmanagers.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_contextmanagers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c642f35909d6ab9f3cf81ab81a35d42b6327ee4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_contextmanagers.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_eventloop.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_eventloop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0ab9ae5026c0c580d74612bea2371e0a4a9fa9f Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_eventloop.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_exceptions.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..246d0e52b4a57fd7fe68facdcbf6da23c95f1df4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_exceptions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_fileio.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_fileio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fa0f1d5e626429dd1f8c741645463a5e7880835 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_fileio.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_resources.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_resources.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ee8226e6d79e0b115bfb067dedf00a24f379a23 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_resources.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_signals.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_signals.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c50d63832d13f20d59fb0cc3915f16a627058f39 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_signals.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_sockets.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_sockets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cc34f16c7bdd1cbfcf469250f912a647f98706d Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_sockets.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_streams.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_streams.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16db0a4b275add042c50412c1a76787a235f7cec Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_streams.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_subprocesses.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_subprocesses.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0d4ba20238da40c1b13fb34b0512e5baa49c315 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_subprocesses.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_synchronization.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_synchronization.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38bbde8d28d9f35b601b1e49d081a3fbc73d0ef4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_synchronization.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_tasks.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_tasks.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00d2ee590bf6f33debcae37d4aea3cdf71ce1e3d Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_tasks.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_tempfile.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_tempfile.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e84bf339980666b51419c93126ea072b58d4ad1c Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_tempfile.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_testing.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_testing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5310dce7db9927ab1bc519a7618226df4ba4c0d0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_testing.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_typedattr.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_typedattr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90997188b1f71804e44fdca82f41988ddfd356dd Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/_core/__pycache__/_typedattr.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/_asyncio_selector_thread.py b/venv/lib/python3.10/site-packages/anyio/_core/_asyncio_selector_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..9f35bae568e33e6a9e1219761c83cc8350fa0532 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_core/_asyncio_selector_thread.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +import asyncio +import socket +import threading +from collections.abc import Callable +from selectors import EVENT_READ, EVENT_WRITE, DefaultSelector +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike + +_selector_lock = threading.Lock() +_selector: Selector | None = None + + +class Selector: + def __init__(self) -> None: + self._thread = threading.Thread(target=self.run, name="AnyIO socket selector") + self._selector = DefaultSelector() + self._send, self._receive = socket.socketpair() + self._send.setblocking(False) + self._receive.setblocking(False) + # This somewhat reduces the amount of memory wasted queueing up data + # for wakeups. With these settings, maximum number of 1-byte sends + # before getting BlockingIOError: + # Linux 4.8: 6 + # macOS (darwin 15.5): 1 + # Windows 10: 525347 + # Windows you're weird. (And on Windows setting SNDBUF to 0 makes send + # blocking, even on non-blocking sockets, so don't do that.) + self._receive.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1) + self._send.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1) + # On Windows this is a TCP socket so this might matter. On other + # platforms this fails b/c AF_UNIX sockets aren't actually TCP. + try: + self._send.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + except OSError: + pass + + self._selector.register(self._receive, EVENT_READ) + self._closed = False + + def start(self) -> None: + self._thread.start() + threading._register_atexit(self._stop) # type: ignore[attr-defined] + + def _stop(self) -> None: + global _selector + self._closed = True + self._notify_self() + self._send.close() + self._thread.join() + self._selector.unregister(self._receive) + self._receive.close() + self._selector.close() + _selector = None + assert not self._selector.get_map(), ( + "selector still has registered file descriptors after shutdown" + ) + + def _notify_self(self) -> None: + try: + self._send.send(b"\x00") + except BlockingIOError: + pass + + def add_reader(self, fd: FileDescriptorLike, callback: Callable[[], Any]) -> None: + loop = asyncio.get_running_loop() + try: + key = self._selector.get_key(fd) + except KeyError: + self._selector.register(fd, EVENT_READ, {EVENT_READ: (loop, callback)}) + else: + if EVENT_READ in key.data: + raise ValueError( + "this file descriptor is already registered for reading" + ) + + key.data[EVENT_READ] = loop, callback + self._selector.modify(fd, key.events | EVENT_READ, key.data) + + self._notify_self() + + def add_writer(self, fd: FileDescriptorLike, callback: Callable[[], Any]) -> None: + loop = asyncio.get_running_loop() + try: + key = self._selector.get_key(fd) + except KeyError: + self._selector.register(fd, EVENT_WRITE, {EVENT_WRITE: (loop, callback)}) + else: + if EVENT_WRITE in key.data: + raise ValueError( + "this file descriptor is already registered for writing" + ) + + key.data[EVENT_WRITE] = loop, callback + self._selector.modify(fd, key.events | EVENT_WRITE, key.data) + + self._notify_self() + + def remove_reader(self, fd: FileDescriptorLike) -> bool: + try: + key = self._selector.get_key(fd) + except KeyError: + return False + + if new_events := key.events ^ EVENT_READ: + del key.data[EVENT_READ] + self._selector.modify(fd, new_events, key.data) + else: + self._selector.unregister(fd) + + return True + + def remove_writer(self, fd: FileDescriptorLike) -> bool: + try: + key = self._selector.get_key(fd) + except KeyError: + return False + + if new_events := key.events ^ EVENT_WRITE: + del key.data[EVENT_WRITE] + self._selector.modify(fd, new_events, key.data) + else: + self._selector.unregister(fd) + + return True + + def run(self) -> None: + while not self._closed: + for key, events in self._selector.select(): + if key.fileobj is self._receive: + try: + while self._receive.recv(4096): + pass + except BlockingIOError: + pass + + continue + + if events & EVENT_READ: + loop, callback = key.data[EVENT_READ] + self.remove_reader(key.fd) + try: + loop.call_soon_threadsafe(callback) + except RuntimeError: + pass # the loop was already closed + + if events & EVENT_WRITE: + loop, callback = key.data[EVENT_WRITE] + self.remove_writer(key.fd) + try: + loop.call_soon_threadsafe(callback) + except RuntimeError: + pass # the loop was already closed + + +def get_selector() -> Selector: + global _selector + + with _selector_lock: + if _selector is None: + _selector = Selector() + _selector.start() + + return _selector diff --git a/venv/lib/python3.10/site-packages/anyio/_core/_contextmanagers.py b/venv/lib/python3.10/site-packages/anyio/_core/_contextmanagers.py new file mode 100644 index 0000000000000000000000000000000000000000..302f32b0c78a7071605b195c55054cfdb0b55f37 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_core/_contextmanagers.py @@ -0,0 +1,200 @@ +from __future__ import annotations + +from abc import abstractmethod +from contextlib import AbstractAsyncContextManager, AbstractContextManager +from inspect import isasyncgen, iscoroutine, isgenerator +from types import TracebackType +from typing import Protocol, TypeVar, cast, final + +_T_co = TypeVar("_T_co", covariant=True) +_ExitT_co = TypeVar("_ExitT_co", covariant=True, bound="bool | None") + + +class _SupportsCtxMgr(Protocol[_T_co, _ExitT_co]): + def __contextmanager__(self) -> AbstractContextManager[_T_co, _ExitT_co]: ... + + +class _SupportsAsyncCtxMgr(Protocol[_T_co, _ExitT_co]): + def __asynccontextmanager__( + self, + ) -> AbstractAsyncContextManager[_T_co, _ExitT_co]: ... + + +class ContextManagerMixin: + """ + Mixin class providing context manager functionality via a generator-based + implementation. + + This class allows you to implement a context manager via :meth:`__contextmanager__` + which should return a generator. The mechanics are meant to mirror those of + :func:`@contextmanager `. + + .. note:: Classes using this mix-in are not reentrant as context managers, meaning + that once you enter it, you can't re-enter before first exiting it. + + .. seealso:: :doc:`contextmanagers` + """ + + __cm: AbstractContextManager[object, bool | None] | None = None + + @final + def __enter__(self: _SupportsCtxMgr[_T_co, bool | None]) -> _T_co: + # Needed for mypy to assume self still has the __cm member + assert isinstance(self, ContextManagerMixin) + if self.__cm is not None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has already been entered" + ) + + cm = self.__contextmanager__() + if not isinstance(cm, AbstractContextManager): + if isgenerator(cm): + raise TypeError( + "__contextmanager__() returned a generator object instead of " + "a context manager. Did you forget to add the @contextmanager " + "decorator?" + ) + + raise TypeError( + f"__contextmanager__() did not return a context manager object, " + f"but {cm.__class__!r}" + ) + + if cm is self: + raise TypeError( + f"{self.__class__.__qualname__}.__contextmanager__() returned " + f"self. Did you forget to add the @contextmanager decorator and a " + f"'yield' statement?" + ) + + value = cm.__enter__() + self.__cm = cm + return value + + @final + def __exit__( + self: _SupportsCtxMgr[object, _ExitT_co], + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> _ExitT_co: + # Needed for mypy to assume self still has the __cm member + assert isinstance(self, ContextManagerMixin) + if self.__cm is None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has not been entered yet" + ) + + # Prevent circular references + cm = self.__cm + del self.__cm + + return cast(_ExitT_co, cm.__exit__(exc_type, exc_val, exc_tb)) + + @abstractmethod + def __contextmanager__(self) -> AbstractContextManager[object, bool | None]: + """ + Implement your context manager logic here. + + This method **must** be decorated with + :func:`@contextmanager `. + + .. note:: Remember that the ``yield`` will raise any exception raised in the + enclosed context block, so use a ``finally:`` block to clean up resources! + + :return: a context manager object + """ + + +class AsyncContextManagerMixin: + """ + Mixin class providing async context manager functionality via a generator-based + implementation. + + This class allows you to implement a context manager via + :meth:`__asynccontextmanager__`. The mechanics are meant to mirror those of + :func:`@asynccontextmanager `. + + .. note:: Classes using this mix-in are not reentrant as context managers, meaning + that once you enter it, you can't re-enter before first exiting it. + + .. seealso:: :doc:`contextmanagers` + """ + + __cm: AbstractAsyncContextManager[object, bool | None] | None = None + + @final + async def __aenter__(self: _SupportsAsyncCtxMgr[_T_co, bool | None]) -> _T_co: + # Needed for mypy to assume self still has the __cm member + assert isinstance(self, AsyncContextManagerMixin) + if self.__cm is not None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has already been entered" + ) + + cm = self.__asynccontextmanager__() + if not isinstance(cm, AbstractAsyncContextManager): + if isasyncgen(cm): + raise TypeError( + "__asynccontextmanager__() returned an async generator instead of " + "an async context manager. Did you forget to add the " + "@asynccontextmanager decorator?" + ) + elif iscoroutine(cm): + cm.close() + raise TypeError( + "__asynccontextmanager__() returned a coroutine object instead of " + "an async context manager. Did you forget to add the " + "@asynccontextmanager decorator and a 'yield' statement?" + ) + + raise TypeError( + f"__asynccontextmanager__() did not return an async context manager, " + f"but {cm.__class__!r}" + ) + + if cm is self: + raise TypeError( + f"{self.__class__.__qualname__}.__asynccontextmanager__() returned " + f"self. Did you forget to add the @asynccontextmanager decorator and a " + f"'yield' statement?" + ) + + value = await cm.__aenter__() + self.__cm = cm + return value + + @final + async def __aexit__( + self: _SupportsAsyncCtxMgr[object, _ExitT_co], + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> _ExitT_co: + assert isinstance(self, AsyncContextManagerMixin) + if self.__cm is None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has not been entered yet" + ) + + # Prevent circular references + cm = self.__cm + del self.__cm + + return cast(_ExitT_co, await cm.__aexit__(exc_type, exc_val, exc_tb)) + + @abstractmethod + def __asynccontextmanager__( + self, + ) -> AbstractAsyncContextManager[object, bool | None]: + """ + Implement your async context manager logic here. + + This method **must** be decorated with + :func:`@asynccontextmanager `. + + .. note:: Remember that the ``yield`` will raise any exception raised in the + enclosed context block, so use a ``finally:`` block to clean up resources! + + :return: an async context manager object + """ diff --git a/venv/lib/python3.10/site-packages/anyio/_core/_eventloop.py b/venv/lib/python3.10/site-packages/anyio/_core/_eventloop.py new file mode 100644 index 0000000000000000000000000000000000000000..6dcb45898184ec7ea5143e42bd147138fd8ed304 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_core/_eventloop.py @@ -0,0 +1,166 @@ +from __future__ import annotations + +import math +import sys +import threading +from collections.abc import Awaitable, Callable, Generator +from contextlib import contextmanager +from importlib import import_module +from typing import TYPE_CHECKING, Any, TypeVar + +import sniffio + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if TYPE_CHECKING: + from ..abc import AsyncBackend + +# This must be updated when new backends are introduced +BACKENDS = "asyncio", "trio" + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + +threadlocals = threading.local() +loaded_backends: dict[str, type[AsyncBackend]] = {} + + +def run( + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + *args: Unpack[PosArgsT], + backend: str = "asyncio", + backend_options: dict[str, Any] | None = None, +) -> T_Retval: + """ + Run the given coroutine function in an asynchronous event loop. + + The current thread must not be already running an event loop. + + :param func: a coroutine function + :param args: positional arguments to ``func`` + :param backend: name of the asynchronous event loop implementation – currently + either ``asyncio`` or ``trio`` + :param backend_options: keyword arguments to call the backend ``run()`` + implementation with (documented :ref:`here `) + :return: the return value of the coroutine function + :raises RuntimeError: if an asynchronous event loop is already running in this + thread + :raises LookupError: if the named backend is not found + + """ + try: + asynclib_name = sniffio.current_async_library() + except sniffio.AsyncLibraryNotFoundError: + pass + else: + raise RuntimeError(f"Already running {asynclib_name} in this thread") + + try: + async_backend = get_async_backend(backend) + except ImportError as exc: + raise LookupError(f"No such backend: {backend}") from exc + + token = None + if sniffio.current_async_library_cvar.get(None) is None: + # Since we're in control of the event loop, we can cache the name of the async + # library + token = sniffio.current_async_library_cvar.set(backend) + + try: + backend_options = backend_options or {} + return async_backend.run(func, args, {}, backend_options) + finally: + if token: + sniffio.current_async_library_cvar.reset(token) + + +async def sleep(delay: float) -> None: + """ + Pause the current task for the specified duration. + + :param delay: the duration, in seconds + + """ + return await get_async_backend().sleep(delay) + + +async def sleep_forever() -> None: + """ + Pause the current task until it's cancelled. + + This is a shortcut for ``sleep(math.inf)``. + + .. versionadded:: 3.1 + + """ + await sleep(math.inf) + + +async def sleep_until(deadline: float) -> None: + """ + Pause the current task until the given time. + + :param deadline: the absolute time to wake up at (according to the internal + monotonic clock of the event loop) + + .. versionadded:: 3.1 + + """ + now = current_time() + await sleep(max(deadline - now, 0)) + + +def current_time() -> float: + """ + Return the current value of the event loop's internal clock. + + :return: the clock value (seconds) + + """ + return get_async_backend().current_time() + + +def get_all_backends() -> tuple[str, ...]: + """Return a tuple of the names of all built-in backends.""" + return BACKENDS + + +def get_cancelled_exc_class() -> type[BaseException]: + """Return the current async library's cancellation exception class.""" + return get_async_backend().cancelled_exception_class() + + +# +# Private API +# + + +@contextmanager +def claim_worker_thread( + backend_class: type[AsyncBackend], token: object +) -> Generator[Any, None, None]: + threadlocals.current_async_backend = backend_class + threadlocals.current_token = token + try: + yield + finally: + del threadlocals.current_async_backend + del threadlocals.current_token + + +def get_async_backend(asynclib_name: str | None = None) -> type[AsyncBackend]: + if asynclib_name is None: + asynclib_name = sniffio.current_async_library() + + # We use our own dict instead of sys.modules to get the already imported back-end + # class because the appropriate modules in sys.modules could potentially be only + # partially initialized + try: + return loaded_backends[asynclib_name] + except KeyError: + module = import_module(f"anyio._backends._{asynclib_name}") + loaded_backends[asynclib_name] = module.backend_class + return module.backend_class diff --git a/venv/lib/python3.10/site-packages/anyio/_core/_exceptions.py b/venv/lib/python3.10/site-packages/anyio/_core/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..daa067768a3a729662c30e965b67e8d461e22e88 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_core/_exceptions.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +import sys +from collections.abc import Generator +from textwrap import dedent +from typing import Any + +if sys.version_info < (3, 11): + from exceptiongroup import BaseExceptionGroup + + +class BrokenResourceError(Exception): + """ + Raised when trying to use a resource that has been rendered unusable due to external + causes (e.g. a send stream whose peer has disconnected). + """ + + +class BrokenWorkerProcess(Exception): + """ + Raised by :meth:`~anyio.to_process.run_sync` if the worker process terminates abruptly or + otherwise misbehaves. + """ + + +class BrokenWorkerInterpreter(Exception): + """ + Raised by :meth:`~anyio.to_interpreter.run_sync` if an unexpected exception is + raised in the subinterpreter. + """ + + def __init__(self, excinfo: Any): + # This was adapted from concurrent.futures.interpreter.ExecutionFailed + msg = excinfo.formatted + if not msg: + if excinfo.type and excinfo.msg: + msg = f"{excinfo.type.__name__}: {excinfo.msg}" + else: + msg = excinfo.type.__name__ or excinfo.msg + + super().__init__(msg) + self.excinfo = excinfo + + def __str__(self) -> str: + try: + formatted = self.excinfo.errdisplay + except Exception: + return super().__str__() + else: + return dedent( + f""" + {super().__str__()} + + Uncaught in the interpreter: + + {formatted} + """.strip() + ) + + +class BusyResourceError(Exception): + """ + Raised when two tasks are trying to read from or write to the same resource + concurrently. + """ + + def __init__(self, action: str): + super().__init__(f"Another task is already {action} this resource") + + +class ClosedResourceError(Exception): + """Raised when trying to use a resource that has been closed.""" + + +class ConnectionFailed(OSError): + """ + Raised when a connection attempt fails. + + .. note:: This class inherits from :exc:`OSError` for backwards compatibility. + """ + + +def iterate_exceptions( + exception: BaseException, +) -> Generator[BaseException, None, None]: + if isinstance(exception, BaseExceptionGroup): + for exc in exception.exceptions: + yield from iterate_exceptions(exc) + else: + yield exception + + +class DelimiterNotFound(Exception): + """ + Raised during + :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the + maximum number of bytes has been read without the delimiter being found. + """ + + def __init__(self, max_bytes: int) -> None: + super().__init__( + f"The delimiter was not found among the first {max_bytes} bytes" + ) + + +class EndOfStream(Exception): + """ + Raised when trying to read from a stream that has been closed from the other end. + """ + + +class IncompleteRead(Exception): + """ + Raised during + :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_exactly` or + :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the + connection is closed before the requested amount of bytes has been read. + """ + + def __init__(self) -> None: + super().__init__( + "The stream was closed before the read operation could be completed" + ) + + +class TypedAttributeLookupError(LookupError): + """ + Raised by :meth:`~anyio.TypedAttributeProvider.extra` when the given typed attribute + is not found and no default value has been given. + """ + + +class WouldBlock(Exception): + """Raised by ``X_nowait`` functions if ``X()`` would block.""" diff --git a/venv/lib/python3.10/site-packages/anyio/_core/_fileio.py b/venv/lib/python3.10/site-packages/anyio/_core/_fileio.py new file mode 100644 index 0000000000000000000000000000000000000000..2eae029e4826c27764d0d8f398ae42bd8f0856fc --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_core/_fileio.py @@ -0,0 +1,740 @@ +from __future__ import annotations + +import os +import pathlib +import sys +from collections.abc import ( + AsyncIterator, + Callable, + Iterable, + Iterator, + Sequence, +) +from dataclasses import dataclass +from functools import partial +from os import PathLike +from typing import ( + IO, + TYPE_CHECKING, + Any, + AnyStr, + ClassVar, + Final, + Generic, + overload, +) + +from .. import to_thread +from ..abc import AsyncResource + +if TYPE_CHECKING: + from types import ModuleType + + from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBuffer +else: + ReadableBuffer = OpenBinaryMode = OpenTextMode = WriteableBuffer = object + + +class AsyncFile(AsyncResource, Generic[AnyStr]): + """ + An asynchronous file object. + + This class wraps a standard file object and provides async friendly versions of the + following blocking methods (where available on the original file object): + + * read + * read1 + * readline + * readlines + * readinto + * readinto1 + * write + * writelines + * truncate + * seek + * tell + * flush + + All other methods are directly passed through. + + This class supports the asynchronous context manager protocol which closes the + underlying file at the end of the context block. + + This class also supports asynchronous iteration:: + + async with await open_file(...) as f: + async for line in f: + print(line) + """ + + def __init__(self, fp: IO[AnyStr]) -> None: + self._fp: Any = fp + + def __getattr__(self, name: str) -> object: + return getattr(self._fp, name) + + @property + def wrapped(self) -> IO[AnyStr]: + """The wrapped file object.""" + return self._fp + + async def __aiter__(self) -> AsyncIterator[AnyStr]: + while True: + line = await self.readline() + if line: + yield line + else: + break + + async def aclose(self) -> None: + return await to_thread.run_sync(self._fp.close) + + async def read(self, size: int = -1) -> AnyStr: + return await to_thread.run_sync(self._fp.read, size) + + async def read1(self: AsyncFile[bytes], size: int = -1) -> bytes: + return await to_thread.run_sync(self._fp.read1, size) + + async def readline(self) -> AnyStr: + return await to_thread.run_sync(self._fp.readline) + + async def readlines(self) -> list[AnyStr]: + return await to_thread.run_sync(self._fp.readlines) + + async def readinto(self: AsyncFile[bytes], b: WriteableBuffer) -> int: + return await to_thread.run_sync(self._fp.readinto, b) + + async def readinto1(self: AsyncFile[bytes], b: WriteableBuffer) -> int: + return await to_thread.run_sync(self._fp.readinto1, b) + + @overload + async def write(self: AsyncFile[bytes], b: ReadableBuffer) -> int: ... + + @overload + async def write(self: AsyncFile[str], b: str) -> int: ... + + async def write(self, b: ReadableBuffer | str) -> int: + return await to_thread.run_sync(self._fp.write, b) + + @overload + async def writelines( + self: AsyncFile[bytes], lines: Iterable[ReadableBuffer] + ) -> None: ... + + @overload + async def writelines(self: AsyncFile[str], lines: Iterable[str]) -> None: ... + + async def writelines(self, lines: Iterable[ReadableBuffer] | Iterable[str]) -> None: + return await to_thread.run_sync(self._fp.writelines, lines) + + async def truncate(self, size: int | None = None) -> int: + return await to_thread.run_sync(self._fp.truncate, size) + + async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int: + return await to_thread.run_sync(self._fp.seek, offset, whence) + + async def tell(self) -> int: + return await to_thread.run_sync(self._fp.tell) + + async def flush(self) -> None: + return await to_thread.run_sync(self._fp.flush) + + +@overload +async def open_file( + file: str | PathLike[str] | int, + mode: OpenBinaryMode, + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + closefd: bool = ..., + opener: Callable[[str, int], int] | None = ..., +) -> AsyncFile[bytes]: ... + + +@overload +async def open_file( + file: str | PathLike[str] | int, + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + closefd: bool = ..., + opener: Callable[[str, int], int] | None = ..., +) -> AsyncFile[str]: ... + + +async def open_file( + file: str | PathLike[str] | int, + mode: str = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + closefd: bool = True, + opener: Callable[[str, int], int] | None = None, +) -> AsyncFile[Any]: + """ + Open a file asynchronously. + + The arguments are exactly the same as for the builtin :func:`open`. + + :return: an asynchronous file object + + """ + fp = await to_thread.run_sync( + open, file, mode, buffering, encoding, errors, newline, closefd, opener + ) + return AsyncFile(fp) + + +def wrap_file(file: IO[AnyStr]) -> AsyncFile[AnyStr]: + """ + Wrap an existing file as an asynchronous file. + + :param file: an existing file-like object + :return: an asynchronous file object + + """ + return AsyncFile(file) + + +@dataclass(eq=False) +class _PathIterator(AsyncIterator["Path"]): + iterator: Iterator[PathLike[str]] + + async def __anext__(self) -> Path: + nextval = await to_thread.run_sync( + next, self.iterator, None, abandon_on_cancel=True + ) + if nextval is None: + raise StopAsyncIteration from None + + return Path(nextval) + + +class Path: + """ + An asynchronous version of :class:`pathlib.Path`. + + This class cannot be substituted for :class:`pathlib.Path` or + :class:`pathlib.PurePath`, but it is compatible with the :class:`os.PathLike` + interface. + + It implements the Python 3.10 version of :class:`pathlib.Path` interface, except for + the deprecated :meth:`~pathlib.Path.link_to` method. + + Some methods may be unavailable or have limited functionality, based on the Python + version: + + * :meth:`~pathlib.Path.copy` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.copy_into` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.from_uri` (available on Python 3.13 or later) + * :meth:`~pathlib.PurePath.full_match` (available on Python 3.13 or later) + * :attr:`~pathlib.Path.info` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.is_junction` (available on Python 3.12 or later) + * :meth:`~pathlib.PurePath.match` (the ``case_sensitive`` parameter is only + available on Python 3.13 or later) + * :meth:`~pathlib.Path.move` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.move_into` (available on Python 3.14 or later) + * :meth:`~pathlib.PurePath.relative_to` (the ``walk_up`` parameter is only available + on Python 3.12 or later) + * :meth:`~pathlib.Path.walk` (available on Python 3.12 or later) + + Any methods that do disk I/O need to be awaited on. These methods are: + + * :meth:`~pathlib.Path.absolute` + * :meth:`~pathlib.Path.chmod` + * :meth:`~pathlib.Path.cwd` + * :meth:`~pathlib.Path.exists` + * :meth:`~pathlib.Path.expanduser` + * :meth:`~pathlib.Path.group` + * :meth:`~pathlib.Path.hardlink_to` + * :meth:`~pathlib.Path.home` + * :meth:`~pathlib.Path.is_block_device` + * :meth:`~pathlib.Path.is_char_device` + * :meth:`~pathlib.Path.is_dir` + * :meth:`~pathlib.Path.is_fifo` + * :meth:`~pathlib.Path.is_file` + * :meth:`~pathlib.Path.is_junction` + * :meth:`~pathlib.Path.is_mount` + * :meth:`~pathlib.Path.is_socket` + * :meth:`~pathlib.Path.is_symlink` + * :meth:`~pathlib.Path.lchmod` + * :meth:`~pathlib.Path.lstat` + * :meth:`~pathlib.Path.mkdir` + * :meth:`~pathlib.Path.open` + * :meth:`~pathlib.Path.owner` + * :meth:`~pathlib.Path.read_bytes` + * :meth:`~pathlib.Path.read_text` + * :meth:`~pathlib.Path.readlink` + * :meth:`~pathlib.Path.rename` + * :meth:`~pathlib.Path.replace` + * :meth:`~pathlib.Path.resolve` + * :meth:`~pathlib.Path.rmdir` + * :meth:`~pathlib.Path.samefile` + * :meth:`~pathlib.Path.stat` + * :meth:`~pathlib.Path.symlink_to` + * :meth:`~pathlib.Path.touch` + * :meth:`~pathlib.Path.unlink` + * :meth:`~pathlib.Path.walk` + * :meth:`~pathlib.Path.write_bytes` + * :meth:`~pathlib.Path.write_text` + + Additionally, the following methods return an async iterator yielding + :class:`~.Path` objects: + + * :meth:`~pathlib.Path.glob` + * :meth:`~pathlib.Path.iterdir` + * :meth:`~pathlib.Path.rglob` + """ + + __slots__ = "_path", "__weakref__" + + __weakref__: Any + + def __init__(self, *args: str | PathLike[str]) -> None: + self._path: Final[pathlib.Path] = pathlib.Path(*args) + + def __fspath__(self) -> str: + return self._path.__fspath__() + + def __str__(self) -> str: + return self._path.__str__() + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.as_posix()!r})" + + def __bytes__(self) -> bytes: + return self._path.__bytes__() + + def __hash__(self) -> int: + return self._path.__hash__() + + def __eq__(self, other: object) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__eq__(target) + + def __lt__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__lt__(target) + + def __le__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__le__(target) + + def __gt__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__gt__(target) + + def __ge__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__ge__(target) + + def __truediv__(self, other: str | PathLike[str]) -> Path: + return Path(self._path / other) + + def __rtruediv__(self, other: str | PathLike[str]) -> Path: + return Path(other) / self + + @property + def parts(self) -> tuple[str, ...]: + return self._path.parts + + @property + def drive(self) -> str: + return self._path.drive + + @property + def root(self) -> str: + return self._path.root + + @property + def anchor(self) -> str: + return self._path.anchor + + @property + def parents(self) -> Sequence[Path]: + return tuple(Path(p) for p in self._path.parents) + + @property + def parent(self) -> Path: + return Path(self._path.parent) + + @property + def name(self) -> str: + return self._path.name + + @property + def suffix(self) -> str: + return self._path.suffix + + @property + def suffixes(self) -> list[str]: + return self._path.suffixes + + @property + def stem(self) -> str: + return self._path.stem + + async def absolute(self) -> Path: + path = await to_thread.run_sync(self._path.absolute) + return Path(path) + + def as_posix(self) -> str: + return self._path.as_posix() + + def as_uri(self) -> str: + return self._path.as_uri() + + if sys.version_info >= (3, 13): + parser: ClassVar[ModuleType] = pathlib.Path.parser + + @classmethod + def from_uri(cls, uri: str) -> Path: + return Path(pathlib.Path.from_uri(uri)) + + def full_match( + self, path_pattern: str, *, case_sensitive: bool | None = None + ) -> bool: + return self._path.full_match(path_pattern, case_sensitive=case_sensitive) + + def match( + self, path_pattern: str, *, case_sensitive: bool | None = None + ) -> bool: + return self._path.match(path_pattern, case_sensitive=case_sensitive) + else: + + def match(self, path_pattern: str) -> bool: + return self._path.match(path_pattern) + + if sys.version_info >= (3, 14): + + @property + def info(self) -> Any: # TODO: add return type annotation when Typeshed gets it + return self._path.info + + async def copy( + self, + target: str | os.PathLike[str], + *, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + ) -> Path: + func = partial( + self._path.copy, + follow_symlinks=follow_symlinks, + preserve_metadata=preserve_metadata, + ) + return Path(await to_thread.run_sync(func, pathlib.Path(target))) + + async def copy_into( + self, + target_dir: str | os.PathLike[str], + *, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + ) -> Path: + func = partial( + self._path.copy_into, + follow_symlinks=follow_symlinks, + preserve_metadata=preserve_metadata, + ) + return Path(await to_thread.run_sync(func, pathlib.Path(target_dir))) + + async def move(self, target: str | os.PathLike[str]) -> Path: + # Upstream does not handle anyio.Path properly as a PathLike + target = pathlib.Path(target) + return Path(await to_thread.run_sync(self._path.move, target)) + + async def move_into( + self, + target_dir: str | os.PathLike[str], + ) -> Path: + return Path(await to_thread.run_sync(self._path.move_into, target_dir)) + + def is_relative_to(self, other: str | PathLike[str]) -> bool: + try: + self.relative_to(other) + return True + except ValueError: + return False + + async def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: + func = partial(os.chmod, follow_symlinks=follow_symlinks) + return await to_thread.run_sync(func, self._path, mode) + + @classmethod + async def cwd(cls) -> Path: + path = await to_thread.run_sync(pathlib.Path.cwd) + return cls(path) + + async def exists(self) -> bool: + return await to_thread.run_sync(self._path.exists, abandon_on_cancel=True) + + async def expanduser(self) -> Path: + return Path( + await to_thread.run_sync(self._path.expanduser, abandon_on_cancel=True) + ) + + def glob(self, pattern: str) -> AsyncIterator[Path]: + gen = self._path.glob(pattern) + return _PathIterator(gen) + + async def group(self) -> str: + return await to_thread.run_sync(self._path.group, abandon_on_cancel=True) + + async def hardlink_to( + self, target: str | bytes | PathLike[str] | PathLike[bytes] + ) -> None: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(os.link, target, self) + + @classmethod + async def home(cls) -> Path: + home_path = await to_thread.run_sync(pathlib.Path.home) + return cls(home_path) + + def is_absolute(self) -> bool: + return self._path.is_absolute() + + async def is_block_device(self) -> bool: + return await to_thread.run_sync( + self._path.is_block_device, abandon_on_cancel=True + ) + + async def is_char_device(self) -> bool: + return await to_thread.run_sync( + self._path.is_char_device, abandon_on_cancel=True + ) + + async def is_dir(self) -> bool: + return await to_thread.run_sync(self._path.is_dir, abandon_on_cancel=True) + + async def is_fifo(self) -> bool: + return await to_thread.run_sync(self._path.is_fifo, abandon_on_cancel=True) + + async def is_file(self) -> bool: + return await to_thread.run_sync(self._path.is_file, abandon_on_cancel=True) + + if sys.version_info >= (3, 12): + + async def is_junction(self) -> bool: + return await to_thread.run_sync(self._path.is_junction) + + async def is_mount(self) -> bool: + return await to_thread.run_sync( + os.path.ismount, self._path, abandon_on_cancel=True + ) + + def is_reserved(self) -> bool: + return self._path.is_reserved() + + async def is_socket(self) -> bool: + return await to_thread.run_sync(self._path.is_socket, abandon_on_cancel=True) + + async def is_symlink(self) -> bool: + return await to_thread.run_sync(self._path.is_symlink, abandon_on_cancel=True) + + async def iterdir(self) -> AsyncIterator[Path]: + gen = ( + self._path.iterdir() + if sys.version_info < (3, 13) + else await to_thread.run_sync(self._path.iterdir, abandon_on_cancel=True) + ) + async for path in _PathIterator(gen): + yield path + + def joinpath(self, *args: str | PathLike[str]) -> Path: + return Path(self._path.joinpath(*args)) + + async def lchmod(self, mode: int) -> None: + await to_thread.run_sync(self._path.lchmod, mode) + + async def lstat(self) -> os.stat_result: + return await to_thread.run_sync(self._path.lstat, abandon_on_cancel=True) + + async def mkdir( + self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False + ) -> None: + await to_thread.run_sync(self._path.mkdir, mode, parents, exist_ok) + + @overload + async def open( + self, + mode: OpenBinaryMode, + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + ) -> AsyncFile[bytes]: ... + + @overload + async def open( + self, + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + ) -> AsyncFile[str]: ... + + async def open( + self, + mode: str = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> AsyncFile[Any]: + fp = await to_thread.run_sync( + self._path.open, mode, buffering, encoding, errors, newline + ) + return AsyncFile(fp) + + async def owner(self) -> str: + return await to_thread.run_sync(self._path.owner, abandon_on_cancel=True) + + async def read_bytes(self) -> bytes: + return await to_thread.run_sync(self._path.read_bytes) + + async def read_text( + self, encoding: str | None = None, errors: str | None = None + ) -> str: + return await to_thread.run_sync(self._path.read_text, encoding, errors) + + if sys.version_info >= (3, 12): + + def relative_to( + self, *other: str | PathLike[str], walk_up: bool = False + ) -> Path: + # relative_to() should work with any PathLike but it doesn't + others = [pathlib.Path(other) for other in other] + return Path(self._path.relative_to(*others, walk_up=walk_up)) + + else: + + def relative_to(self, *other: str | PathLike[str]) -> Path: + return Path(self._path.relative_to(*other)) + + async def readlink(self) -> Path: + target = await to_thread.run_sync(os.readlink, self._path) + return Path(target) + + async def rename(self, target: str | pathlib.PurePath | Path) -> Path: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(self._path.rename, target) + return Path(target) + + async def replace(self, target: str | pathlib.PurePath | Path) -> Path: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(self._path.replace, target) + return Path(target) + + async def resolve(self, strict: bool = False) -> Path: + func = partial(self._path.resolve, strict=strict) + return Path(await to_thread.run_sync(func, abandon_on_cancel=True)) + + def rglob(self, pattern: str) -> AsyncIterator[Path]: + gen = self._path.rglob(pattern) + return _PathIterator(gen) + + async def rmdir(self) -> None: + await to_thread.run_sync(self._path.rmdir) + + async def samefile(self, other_path: str | PathLike[str]) -> bool: + if isinstance(other_path, Path): + other_path = other_path._path + + return await to_thread.run_sync( + self._path.samefile, other_path, abandon_on_cancel=True + ) + + async def stat(self, *, follow_symlinks: bool = True) -> os.stat_result: + func = partial(os.stat, follow_symlinks=follow_symlinks) + return await to_thread.run_sync(func, self._path, abandon_on_cancel=True) + + async def symlink_to( + self, + target: str | bytes | PathLike[str] | PathLike[bytes], + target_is_directory: bool = False, + ) -> None: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(self._path.symlink_to, target, target_is_directory) + + async def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: + await to_thread.run_sync(self._path.touch, mode, exist_ok) + + async def unlink(self, missing_ok: bool = False) -> None: + try: + await to_thread.run_sync(self._path.unlink) + except FileNotFoundError: + if not missing_ok: + raise + + if sys.version_info >= (3, 12): + + async def walk( + self, + top_down: bool = True, + on_error: Callable[[OSError], object] | None = None, + follow_symlinks: bool = False, + ) -> AsyncIterator[tuple[Path, list[str], list[str]]]: + def get_next_value() -> tuple[pathlib.Path, list[str], list[str]] | None: + try: + return next(gen) + except StopIteration: + return None + + gen = self._path.walk(top_down, on_error, follow_symlinks) + while True: + value = await to_thread.run_sync(get_next_value) + if value is None: + return + + root, dirs, paths = value + yield Path(root), dirs, paths + + def with_name(self, name: str) -> Path: + return Path(self._path.with_name(name)) + + def with_stem(self, stem: str) -> Path: + return Path(self._path.with_name(stem + self._path.suffix)) + + def with_suffix(self, suffix: str) -> Path: + return Path(self._path.with_suffix(suffix)) + + def with_segments(self, *pathsegments: str | PathLike[str]) -> Path: + return Path(*pathsegments) + + async def write_bytes(self, data: bytes) -> int: + return await to_thread.run_sync(self._path.write_bytes, data) + + async def write_text( + self, + data: str, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> int: + # Path.write_text() does not support the "newline" parameter before Python 3.10 + def sync_write_text() -> int: + with self._path.open( + "w", encoding=encoding, errors=errors, newline=newline + ) as fp: + return fp.write(data) + + return await to_thread.run_sync(sync_write_text) + + +PathLike.register(Path) diff --git a/venv/lib/python3.10/site-packages/anyio/_core/_resources.py b/venv/lib/python3.10/site-packages/anyio/_core/_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..b9a5344aef2962670f9b305a02cd0b11f2087d2f --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_core/_resources.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from ..abc import AsyncResource +from ._tasks import CancelScope + + +async def aclose_forcefully(resource: AsyncResource) -> None: + """ + Close an asynchronous resource in a cancelled scope. + + Doing this closes the resource without waiting on anything. + + :param resource: the resource to close + + """ + with CancelScope() as scope: + scope.cancel() + await resource.aclose() diff --git a/venv/lib/python3.10/site-packages/anyio/_core/_signals.py b/venv/lib/python3.10/site-packages/anyio/_core/_signals.py new file mode 100644 index 0000000000000000000000000000000000000000..f3451d302f514a6b2c9b4f96c6b3e17e36d7d050 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_core/_signals.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +from collections.abc import AsyncIterator +from contextlib import AbstractContextManager +from signal import Signals + +from ._eventloop import get_async_backend + + +def open_signal_receiver( + *signals: Signals, +) -> AbstractContextManager[AsyncIterator[Signals]]: + """ + Start receiving operating system signals. + + :param signals: signals to receive (e.g. ``signal.SIGINT``) + :return: an asynchronous context manager for an asynchronous iterator which yields + signal numbers + + .. warning:: Windows does not support signals natively so it is best to avoid + relying on this in cross-platform applications. + + .. warning:: On asyncio, this permanently replaces any previous signal handler for + the given signals, as set via :meth:`~asyncio.loop.add_signal_handler`. + + """ + return get_async_backend().open_signal_receiver(*signals) diff --git a/venv/lib/python3.10/site-packages/anyio/_core/_sockets.py b/venv/lib/python3.10/site-packages/anyio/_core/_sockets.py new file mode 100644 index 0000000000000000000000000000000000000000..9781c6022be901678e4efc1a5714fc7bcafaf4ac --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_core/_sockets.py @@ -0,0 +1,934 @@ +from __future__ import annotations + +import errno +import os +import socket +import ssl +import stat +import sys +from collections.abc import Awaitable +from dataclasses import dataclass +from ipaddress import IPv4Address, IPv6Address, ip_address +from os import PathLike, chmod +from socket import AddressFamily, SocketKind +from typing import TYPE_CHECKING, Any, Literal, cast, overload + +from .. import ConnectionFailed, to_thread +from ..abc import ( + ByteStreamConnectable, + ConnectedUDPSocket, + ConnectedUNIXDatagramSocket, + IPAddressType, + IPSockAddrType, + SocketListener, + SocketStream, + UDPSocket, + UNIXDatagramSocket, + UNIXSocketStream, +) +from ..streams.stapled import MultiListener +from ..streams.tls import TLSConnectable, TLSStream +from ._eventloop import get_async_backend +from ._resources import aclose_forcefully +from ._synchronization import Event +from ._tasks import create_task_group, move_on_after + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike +else: + FileDescriptorLike = object + +if sys.version_info < (3, 11): + from exceptiongroup import ExceptionGroup + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + +if sys.version_info < (3, 13): + from typing_extensions import deprecated +else: + from warnings import deprecated + +IPPROTO_IPV6 = getattr(socket, "IPPROTO_IPV6", 41) # https://bugs.python.org/issue29515 + +AnyIPAddressFamily = Literal[ + AddressFamily.AF_UNSPEC, AddressFamily.AF_INET, AddressFamily.AF_INET6 +] +IPAddressFamily = Literal[AddressFamily.AF_INET, AddressFamily.AF_INET6] + + +# tls_hostname given +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + ssl_context: ssl.SSLContext | None = ..., + tls_standard_compatible: bool = ..., + tls_hostname: str, + happy_eyeballs_delay: float = ..., +) -> TLSStream: ... + + +# ssl_context given +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + ssl_context: ssl.SSLContext, + tls_standard_compatible: bool = ..., + tls_hostname: str | None = ..., + happy_eyeballs_delay: float = ..., +) -> TLSStream: ... + + +# tls=True +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + tls: Literal[True], + ssl_context: ssl.SSLContext | None = ..., + tls_standard_compatible: bool = ..., + tls_hostname: str | None = ..., + happy_eyeballs_delay: float = ..., +) -> TLSStream: ... + + +# tls=False +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + tls: Literal[False], + ssl_context: ssl.SSLContext | None = ..., + tls_standard_compatible: bool = ..., + tls_hostname: str | None = ..., + happy_eyeballs_delay: float = ..., +) -> SocketStream: ... + + +# No TLS arguments +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + happy_eyeballs_delay: float = ..., +) -> SocketStream: ... + + +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = None, + tls: bool = False, + ssl_context: ssl.SSLContext | None = None, + tls_standard_compatible: bool = True, + tls_hostname: str | None = None, + happy_eyeballs_delay: float = 0.25, +) -> SocketStream | TLSStream: + """ + Connect to a host using the TCP protocol. + + This function implements the stateless version of the Happy Eyeballs algorithm (RFC + 6555). If ``remote_host`` is a host name that resolves to multiple IP addresses, + each one is tried until one connection attempt succeeds. If the first attempt does + not connected within 250 milliseconds, a second attempt is started using the next + address in the list, and so on. On IPv6 enabled systems, an IPv6 address (if + available) is tried first. + + When the connection has been established, a TLS handshake will be done if either + ``ssl_context`` or ``tls_hostname`` is not ``None``, or if ``tls`` is ``True``. + + :param remote_host: the IP address or host name to connect to + :param remote_port: port on the target host to connect to + :param local_host: the interface address or name to bind the socket to before + connecting + :param tls: ``True`` to do a TLS handshake with the connected stream and return a + :class:`~anyio.streams.tls.TLSStream` instead + :param ssl_context: the SSL context object to use (if omitted, a default context is + created) + :param tls_standard_compatible: If ``True``, performs the TLS shutdown handshake + before closing the stream and requires that the server does this as well. + Otherwise, :exc:`~ssl.SSLEOFError` may be raised during reads from the stream. + Some protocols, such as HTTP, require this option to be ``False``. + See :meth:`~ssl.SSLContext.wrap_socket` for details. + :param tls_hostname: host name to check the server certificate against (defaults to + the value of ``remote_host``) + :param happy_eyeballs_delay: delay (in seconds) before starting the next connection + attempt + :return: a socket stream object if no TLS handshake was done, otherwise a TLS stream + :raises ConnectionFailed: if the connection fails + + """ + # Placed here due to https://github.com/python/mypy/issues/7057 + connected_stream: SocketStream | None = None + + async def try_connect(remote_host: str, event: Event) -> None: + nonlocal connected_stream + try: + stream = await asynclib.connect_tcp(remote_host, remote_port, local_address) + except OSError as exc: + oserrors.append(exc) + return + else: + if connected_stream is None: + connected_stream = stream + tg.cancel_scope.cancel() + else: + await stream.aclose() + finally: + event.set() + + asynclib = get_async_backend() + local_address: IPSockAddrType | None = None + family = socket.AF_UNSPEC + if local_host: + gai_res = await getaddrinfo(str(local_host), None) + family, *_, local_address = gai_res[0] + + target_host = str(remote_host) + try: + addr_obj = ip_address(remote_host) + except ValueError: + addr_obj = None + + if addr_obj is not None: + if isinstance(addr_obj, IPv6Address): + target_addrs = [(socket.AF_INET6, addr_obj.compressed)] + else: + target_addrs = [(socket.AF_INET, addr_obj.compressed)] + else: + # getaddrinfo() will raise an exception if name resolution fails + gai_res = await getaddrinfo( + target_host, remote_port, family=family, type=socket.SOCK_STREAM + ) + + # Organize the list so that the first address is an IPv6 address (if available) + # and the second one is an IPv4 addresses. The rest can be in whatever order. + v6_found = v4_found = False + target_addrs = [] + for af, *_, sa in gai_res: + if af == socket.AF_INET6 and not v6_found: + v6_found = True + target_addrs.insert(0, (af, sa[0])) + elif af == socket.AF_INET and not v4_found and v6_found: + v4_found = True + target_addrs.insert(1, (af, sa[0])) + else: + target_addrs.append((af, sa[0])) + + oserrors: list[OSError] = [] + try: + async with create_task_group() as tg: + for _af, addr in target_addrs: + event = Event() + tg.start_soon(try_connect, addr, event) + with move_on_after(happy_eyeballs_delay): + await event.wait() + + if connected_stream is None: + cause = ( + oserrors[0] + if len(oserrors) == 1 + else ExceptionGroup("multiple connection attempts failed", oserrors) + ) + raise OSError("All connection attempts failed") from cause + finally: + oserrors.clear() + + if tls or tls_hostname or ssl_context: + try: + return await TLSStream.wrap( + connected_stream, + server_side=False, + hostname=tls_hostname or str(remote_host), + ssl_context=ssl_context, + standard_compatible=tls_standard_compatible, + ) + except BaseException: + await aclose_forcefully(connected_stream) + raise + + return connected_stream + + +async def connect_unix(path: str | bytes | PathLike[Any]) -> UNIXSocketStream: + """ + Connect to the given UNIX socket. + + Not available on Windows. + + :param path: path to the socket + :return: a socket stream object + :raises ConnectionFailed: if the connection fails + + """ + path = os.fspath(path) + return await get_async_backend().connect_unix(path) + + +async def create_tcp_listener( + *, + local_host: IPAddressType | None = None, + local_port: int = 0, + family: AnyIPAddressFamily = socket.AddressFamily.AF_UNSPEC, + backlog: int = 65536, + reuse_port: bool = False, +) -> MultiListener[SocketStream]: + """ + Create a TCP socket listener. + + :param local_port: port number to listen on + :param local_host: IP address of the interface to listen on. If omitted, listen on + all IPv4 and IPv6 interfaces. To listen on all interfaces on a specific address + family, use ``0.0.0.0`` for IPv4 or ``::`` for IPv6. + :param family: address family (used if ``local_host`` was omitted) + :param backlog: maximum number of queued incoming connections (up to a maximum of + 2**16, or 65536) + :param reuse_port: ``True`` to allow multiple sockets to bind to the same + address/port (not supported on Windows) + :return: a multi-listener object containing one or more socket listeners + + """ + asynclib = get_async_backend() + backlog = min(backlog, 65536) + local_host = str(local_host) if local_host is not None else None + gai_res = await getaddrinfo( + local_host, + local_port, + family=family, + type=socket.SocketKind.SOCK_STREAM if sys.platform == "win32" else 0, + flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, + ) + listeners: list[SocketListener] = [] + try: + # The set() is here to work around a glibc bug: + # https://sourceware.org/bugzilla/show_bug.cgi?id=14969 + sockaddr: tuple[str, int] | tuple[str, int, int, int] + for fam, kind, *_, sockaddr in sorted(set(gai_res)): + # Workaround for an uvloop bug where we don't get the correct scope ID for + # IPv6 link-local addresses when passing type=socket.SOCK_STREAM to + # getaddrinfo(): https://github.com/MagicStack/uvloop/issues/539 + if sys.platform != "win32" and kind is not SocketKind.SOCK_STREAM: + continue + + raw_socket = socket.socket(fam) + raw_socket.setblocking(False) + + # For Windows, enable exclusive address use. For others, enable address + # reuse. + if sys.platform == "win32": + raw_socket.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) + else: + raw_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + + if reuse_port: + raw_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + + # If only IPv6 was requested, disable dual stack operation + if fam == socket.AF_INET6: + raw_socket.setsockopt(IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) + + # Workaround for #554 + if "%" in sockaddr[0]: + addr, scope_id = sockaddr[0].split("%", 1) + sockaddr = (addr, sockaddr[1], 0, int(scope_id)) + + raw_socket.bind(sockaddr) + raw_socket.listen(backlog) + listener = asynclib.create_tcp_listener(raw_socket) + listeners.append(listener) + except BaseException: + for listener in listeners: + await listener.aclose() + + raise + + return MultiListener(listeners) + + +async def create_unix_listener( + path: str | bytes | PathLike[Any], + *, + mode: int | None = None, + backlog: int = 65536, +) -> SocketListener: + """ + Create a UNIX socket listener. + + Not available on Windows. + + :param path: path of the socket + :param mode: permissions to set on the socket + :param backlog: maximum number of queued incoming connections (up to a maximum of + 2**16, or 65536) + :return: a listener object + + .. versionchanged:: 3.0 + If a socket already exists on the file system in the given path, it will be + removed first. + + """ + backlog = min(backlog, 65536) + raw_socket = await setup_unix_local_socket(path, mode, socket.SOCK_STREAM) + try: + raw_socket.listen(backlog) + return get_async_backend().create_unix_listener(raw_socket) + except BaseException: + raw_socket.close() + raise + + +async def create_udp_socket( + family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC, + *, + local_host: IPAddressType | None = None, + local_port: int = 0, + reuse_port: bool = False, +) -> UDPSocket: + """ + Create a UDP socket. + + If ``port`` has been given, the socket will be bound to this port on the local + machine, making this socket suitable for providing UDP based services. + + :param family: address family (``AF_INET`` or ``AF_INET6``) – automatically + determined from ``local_host`` if omitted + :param local_host: IP address or host name of the local interface to bind to + :param local_port: local port to bind to + :param reuse_port: ``True`` to allow multiple sockets to bind to the same + address/port (not supported on Windows) + :return: a UDP socket + + """ + if family is AddressFamily.AF_UNSPEC and not local_host: + raise ValueError('Either "family" or "local_host" must be given') + + if local_host: + gai_res = await getaddrinfo( + str(local_host), + local_port, + family=family, + type=socket.SOCK_DGRAM, + flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, + ) + family = cast(AnyIPAddressFamily, gai_res[0][0]) + local_address = gai_res[0][-1] + elif family is AddressFamily.AF_INET6: + local_address = ("::", 0) + else: + local_address = ("0.0.0.0", 0) + + sock = await get_async_backend().create_udp_socket( + family, local_address, None, reuse_port + ) + return cast(UDPSocket, sock) + + +async def create_connected_udp_socket( + remote_host: IPAddressType, + remote_port: int, + *, + family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC, + local_host: IPAddressType | None = None, + local_port: int = 0, + reuse_port: bool = False, +) -> ConnectedUDPSocket: + """ + Create a connected UDP socket. + + Connected UDP sockets can only communicate with the specified remote host/port, an + any packets sent from other sources are dropped. + + :param remote_host: remote host to set as the default target + :param remote_port: port on the remote host to set as the default target + :param family: address family (``AF_INET`` or ``AF_INET6``) – automatically + determined from ``local_host`` or ``remote_host`` if omitted + :param local_host: IP address or host name of the local interface to bind to + :param local_port: local port to bind to + :param reuse_port: ``True`` to allow multiple sockets to bind to the same + address/port (not supported on Windows) + :return: a connected UDP socket + + """ + local_address = None + if local_host: + gai_res = await getaddrinfo( + str(local_host), + local_port, + family=family, + type=socket.SOCK_DGRAM, + flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, + ) + family = cast(AnyIPAddressFamily, gai_res[0][0]) + local_address = gai_res[0][-1] + + gai_res = await getaddrinfo( + str(remote_host), remote_port, family=family, type=socket.SOCK_DGRAM + ) + family = cast(AnyIPAddressFamily, gai_res[0][0]) + remote_address = gai_res[0][-1] + + sock = await get_async_backend().create_udp_socket( + family, local_address, remote_address, reuse_port + ) + return cast(ConnectedUDPSocket, sock) + + +async def create_unix_datagram_socket( + *, + local_path: None | str | bytes | PathLike[Any] = None, + local_mode: int | None = None, +) -> UNIXDatagramSocket: + """ + Create a UNIX datagram socket. + + Not available on Windows. + + If ``local_path`` has been given, the socket will be bound to this path, making this + socket suitable for receiving datagrams from other processes. Other processes can + send datagrams to this socket only if ``local_path`` is set. + + If a socket already exists on the file system in the ``local_path``, it will be + removed first. + + :param local_path: the path on which to bind to + :param local_mode: permissions to set on the local socket + :return: a UNIX datagram socket + + """ + raw_socket = await setup_unix_local_socket( + local_path, local_mode, socket.SOCK_DGRAM + ) + return await get_async_backend().create_unix_datagram_socket(raw_socket, None) + + +async def create_connected_unix_datagram_socket( + remote_path: str | bytes | PathLike[Any], + *, + local_path: None | str | bytes | PathLike[Any] = None, + local_mode: int | None = None, +) -> ConnectedUNIXDatagramSocket: + """ + Create a connected UNIX datagram socket. + + Connected datagram sockets can only communicate with the specified remote path. + + If ``local_path`` has been given, the socket will be bound to this path, making + this socket suitable for receiving datagrams from other processes. Other processes + can send datagrams to this socket only if ``local_path`` is set. + + If a socket already exists on the file system in the ``local_path``, it will be + removed first. + + :param remote_path: the path to set as the default target + :param local_path: the path on which to bind to + :param local_mode: permissions to set on the local socket + :return: a connected UNIX datagram socket + + """ + remote_path = os.fspath(remote_path) + raw_socket = await setup_unix_local_socket( + local_path, local_mode, socket.SOCK_DGRAM + ) + return await get_async_backend().create_unix_datagram_socket( + raw_socket, remote_path + ) + + +async def getaddrinfo( + host: bytes | str | None, + port: str | int | None, + *, + family: int | AddressFamily = 0, + type: int | SocketKind = 0, + proto: int = 0, + flags: int = 0, +) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int]]]: + """ + Look up a numeric IP address given a host name. + + Internationalized domain names are translated according to the (non-transitional) + IDNA 2008 standard. + + .. note:: 4-tuple IPv6 socket addresses are automatically converted to 2-tuples of + (host, port), unlike what :func:`socket.getaddrinfo` does. + + :param host: host name + :param port: port number + :param family: socket family (`'AF_INET``, ...) + :param type: socket type (``SOCK_STREAM``, ...) + :param proto: protocol number + :param flags: flags to pass to upstream ``getaddrinfo()`` + :return: list of tuples containing (family, type, proto, canonname, sockaddr) + + .. seealso:: :func:`socket.getaddrinfo` + + """ + # Handle unicode hostnames + if isinstance(host, str): + try: + encoded_host: bytes | None = host.encode("ascii") + except UnicodeEncodeError: + import idna + + encoded_host = idna.encode(host, uts46=True) + else: + encoded_host = host + + gai_res = await get_async_backend().getaddrinfo( + encoded_host, port, family=family, type=type, proto=proto, flags=flags + ) + return [ + (family, type, proto, canonname, convert_ipv6_sockaddr(sockaddr)) + for family, type, proto, canonname, sockaddr in gai_res + # filter out IPv6 results when IPv6 is disabled + if not isinstance(sockaddr[0], int) + ] + + +def getnameinfo(sockaddr: IPSockAddrType, flags: int = 0) -> Awaitable[tuple[str, str]]: + """ + Look up the host name of an IP address. + + :param sockaddr: socket address (e.g. (ipaddress, port) for IPv4) + :param flags: flags to pass to upstream ``getnameinfo()`` + :return: a tuple of (host name, service name) + + .. seealso:: :func:`socket.getnameinfo` + + """ + return get_async_backend().getnameinfo(sockaddr, flags) + + +@deprecated("This function is deprecated; use `wait_readable` instead") +def wait_socket_readable(sock: socket.socket) -> Awaitable[None]: + """ + .. deprecated:: 4.7.0 + Use :func:`wait_readable` instead. + + Wait until the given socket has data to be read. + + .. warning:: Only use this on raw sockets that have not been wrapped by any higher + level constructs like socket streams! + + :param sock: a socket object + :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the + socket to become readable + :raises ~anyio.BusyResourceError: if another task is already waiting for the socket + to become readable + + """ + return get_async_backend().wait_readable(sock.fileno()) + + +@deprecated("This function is deprecated; use `wait_writable` instead") +def wait_socket_writable(sock: socket.socket) -> Awaitable[None]: + """ + .. deprecated:: 4.7.0 + Use :func:`wait_writable` instead. + + Wait until the given socket can be written to. + + This does **NOT** work on Windows when using the asyncio backend with a proactor + event loop (default on py3.8+). + + .. warning:: Only use this on raw sockets that have not been wrapped by any higher + level constructs like socket streams! + + :param sock: a socket object + :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the + socket to become writable + :raises ~anyio.BusyResourceError: if another task is already waiting for the socket + to become writable + + """ + return get_async_backend().wait_writable(sock.fileno()) + + +def wait_readable(obj: FileDescriptorLike) -> Awaitable[None]: + """ + Wait until the given object has data to be read. + + On Unix systems, ``obj`` must either be an integer file descriptor, or else an + object with a ``.fileno()`` method which returns an integer file descriptor. Any + kind of file descriptor can be passed, though the exact semantics will depend on + your kernel. For example, this probably won't do anything useful for on-disk files. + + On Windows systems, ``obj`` must either be an integer ``SOCKET`` handle, or else an + object with a ``.fileno()`` method which returns an integer ``SOCKET`` handle. File + descriptors aren't supported, and neither are handles that refer to anything besides + a ``SOCKET``. + + On backends where this functionality is not natively provided (asyncio + ``ProactorEventLoop`` on Windows), it is provided using a separate selector thread + which is set to shut down when the interpreter shuts down. + + .. warning:: Don't use this on raw sockets that have been wrapped by any higher + level constructs like socket streams! + + :param obj: an object with a ``.fileno()`` method or an integer handle + :raises ~anyio.ClosedResourceError: if the object was closed while waiting for the + object to become readable + :raises ~anyio.BusyResourceError: if another task is already waiting for the object + to become readable + + """ + return get_async_backend().wait_readable(obj) + + +def wait_writable(obj: FileDescriptorLike) -> Awaitable[None]: + """ + Wait until the given object can be written to. + + :param obj: an object with a ``.fileno()`` method or an integer handle + :raises ~anyio.ClosedResourceError: if the object was closed while waiting for the + object to become writable + :raises ~anyio.BusyResourceError: if another task is already waiting for the object + to become writable + + .. seealso:: See the documentation of :func:`wait_readable` for the definition of + ``obj`` and notes on backend compatibility. + + .. warning:: Don't use this on raw sockets that have been wrapped by any higher + level constructs like socket streams! + + """ + return get_async_backend().wait_writable(obj) + + +def notify_closing(obj: FileDescriptorLike) -> None: + """ + Call this before closing a file descriptor (on Unix) or socket (on + Windows). This will cause any `wait_readable` or `wait_writable` + calls on the given object to immediately wake up and raise + `~anyio.ClosedResourceError`. + + This doesn't actually close the object – you still have to do that + yourself afterwards. Also, you want to be careful to make sure no + new tasks start waiting on the object in between when you call this + and when it's actually closed. So to close something properly, you + usually want to do these steps in order: + + 1. Explicitly mark the object as closed, so that any new attempts + to use it will abort before they start. + 2. Call `notify_closing` to wake up any already-existing users. + 3. Actually close the object. + + It's also possible to do them in a different order if that's more + convenient, *but only if* you make sure not to have any checkpoints in + between the steps. This way they all happen in a single atomic + step, so other tasks won't be able to tell what order they happened + in anyway. + + :param obj: an object with a ``.fileno()`` method or an integer handle + + """ + get_async_backend().notify_closing(obj) + + +# +# Private API +# + + +def convert_ipv6_sockaddr( + sockaddr: tuple[str, int, int, int] | tuple[str, int], +) -> tuple[str, int]: + """ + Convert a 4-tuple IPv6 socket address to a 2-tuple (address, port) format. + + If the scope ID is nonzero, it is added to the address, separated with ``%``. + Otherwise the flow id and scope id are simply cut off from the tuple. + Any other kinds of socket addresses are returned as-is. + + :param sockaddr: the result of :meth:`~socket.socket.getsockname` + :return: the converted socket address + + """ + # This is more complicated than it should be because of MyPy + if isinstance(sockaddr, tuple) and len(sockaddr) == 4: + host, port, flowinfo, scope_id = sockaddr + if scope_id: + # PyPy (as of v7.3.11) leaves the interface name in the result, so + # we discard it and only get the scope ID from the end + # (https://foss.heptapod.net/pypy/pypy/-/issues/3938) + host = host.split("%")[0] + + # Add scope_id to the address + return f"{host}%{scope_id}", port + else: + return host, port + else: + return sockaddr + + +async def setup_unix_local_socket( + path: None | str | bytes | PathLike[Any], + mode: int | None, + socktype: int, +) -> socket.socket: + """ + Create a UNIX local socket object, deleting the socket at the given path if it + exists. + + Not available on Windows. + + :param path: path of the socket + :param mode: permissions to set on the socket + :param socktype: socket.SOCK_STREAM or socket.SOCK_DGRAM + + """ + path_str: str | None + if path is not None: + path_str = os.fsdecode(path) + + # Linux abstract namespace sockets aren't backed by a concrete file so skip stat call + if not path_str.startswith("\0"): + # Copied from pathlib... + try: + stat_result = os.stat(path) + except OSError as e: + if e.errno not in ( + errno.ENOENT, + errno.ENOTDIR, + errno.EBADF, + errno.ELOOP, + ): + raise + else: + if stat.S_ISSOCK(stat_result.st_mode): + os.unlink(path) + else: + path_str = None + + raw_socket = socket.socket(socket.AF_UNIX, socktype) + raw_socket.setblocking(False) + + if path_str is not None: + try: + await to_thread.run_sync(raw_socket.bind, path_str, abandon_on_cancel=True) + if mode is not None: + await to_thread.run_sync(chmod, path_str, mode, abandon_on_cancel=True) + except BaseException: + raw_socket.close() + raise + + return raw_socket + + +@dataclass +class TCPConnectable(ByteStreamConnectable): + """ + Connects to a TCP server at the given host and port. + + :param host: host name or IP address of the server + :param port: TCP port number of the server + """ + + host: str | IPv4Address | IPv6Address + port: int + + def __post_init__(self) -> None: + if self.port < 1 or self.port > 65535: + raise ValueError("TCP port number out of range") + + @override + async def connect(self) -> SocketStream: + try: + return await connect_tcp(self.host, self.port) + except OSError as exc: + raise ConnectionFailed( + f"error connecting to {self.host}:{self.port}: {exc}" + ) from exc + + +@dataclass +class UNIXConnectable(ByteStreamConnectable): + """ + Connects to a UNIX domain socket at the given path. + + :param path: the file system path of the socket + """ + + path: str | bytes | PathLike[str] | PathLike[bytes] + + @override + async def connect(self) -> UNIXSocketStream: + try: + return await connect_unix(self.path) + except OSError as exc: + raise ConnectionFailed(f"error connecting to {self.path!r}: {exc}") from exc + + +def as_connectable( + remote: ByteStreamConnectable + | tuple[str | IPv4Address | IPv6Address, int] + | str + | bytes + | PathLike[str], + /, + *, + tls: bool = False, + ssl_context: ssl.SSLContext | None = None, + tls_hostname: str | None = None, + tls_standard_compatible: bool = True, +) -> ByteStreamConnectable: + """ + Return a byte stream connectable from the given object. + + If a bytestream connectable is given, it is returned unchanged. + If a tuple of (host, port) is given, a TCP connectable is returned. + If a string or bytes path is given, a UNIX connectable is returned. + + If ``tls=True``, the connectable will be wrapped in a + :class:`~.streams.tls.TLSConnectable`. + + :param remote: a connectable, a tuple of (host, port) or a path to a UNIX socket + :param tls: if ``True``, wrap the plaintext connectable in a + :class:`~.streams.tls.TLSConnectable`, using the provided TLS settings) + :param ssl_context: if ``tls=True``, the SSLContext object to use (if not provided, + a secure default will be created) + :param tls_hostname: if ``tls=True``, host name of the server to use for checking + the server certificate (defaults to the host portion of the address for TCP + connectables) + :param tls_standard_compatible: if ``False`` and ``tls=True``, makes the TLS stream + skip the closing handshake when closing the connection, so it won't raise an + exception if the server does the same + + """ + connectable: TCPConnectable | UNIXConnectable | TLSConnectable + if isinstance(remote, ByteStreamConnectable): + return remote + elif isinstance(remote, tuple) and len(remote) == 2: + connectable = TCPConnectable(*remote) + elif isinstance(remote, (str, bytes, PathLike)): + connectable = UNIXConnectable(remote) + else: + raise TypeError(f"cannot convert {remote!r} to a connectable") + + if tls: + if not tls_hostname and isinstance(connectable, TCPConnectable): + tls_hostname = str(connectable.host) + + connectable = TLSConnectable( + connectable, + ssl_context=ssl_context, + hostname=tls_hostname, + standard_compatible=tls_standard_compatible, + ) + + return connectable diff --git a/venv/lib/python3.10/site-packages/anyio/_core/_streams.py b/venv/lib/python3.10/site-packages/anyio/_core/_streams.py new file mode 100644 index 0000000000000000000000000000000000000000..6a9814e5a91d64e081ecef323a761ed42d3e64de --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_core/_streams.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +import math +from typing import TypeVar +from warnings import warn + +from ..streams.memory import ( + MemoryObjectReceiveStream, + MemoryObjectSendStream, + MemoryObjectStreamState, +) + +T_Item = TypeVar("T_Item") + + +class create_memory_object_stream( + tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]], +): + """ + Create a memory object stream. + + The stream's item type can be annotated like + :func:`create_memory_object_stream[T_Item]`. + + :param max_buffer_size: number of items held in the buffer until ``send()`` starts + blocking + :param item_type: old way of marking the streams with the right generic type for + static typing (does nothing on AnyIO 4) + + .. deprecated:: 4.0 + Use ``create_memory_object_stream[YourItemType](...)`` instead. + :return: a tuple of (send stream, receive stream) + + """ + + def __new__( # type: ignore[misc] + cls, max_buffer_size: float = 0, item_type: object = None + ) -> tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]]: + if max_buffer_size != math.inf and not isinstance(max_buffer_size, int): + raise ValueError("max_buffer_size must be either an integer or math.inf") + if max_buffer_size < 0: + raise ValueError("max_buffer_size cannot be negative") + if item_type is not None: + warn( + "The item_type argument has been deprecated in AnyIO 4.0. " + "Use create_memory_object_stream[YourItemType](...) instead.", + DeprecationWarning, + stacklevel=2, + ) + + state = MemoryObjectStreamState[T_Item](max_buffer_size) + return (MemoryObjectSendStream(state), MemoryObjectReceiveStream(state)) diff --git a/venv/lib/python3.10/site-packages/anyio/_core/_subprocesses.py b/venv/lib/python3.10/site-packages/anyio/_core/_subprocesses.py new file mode 100644 index 0000000000000000000000000000000000000000..36d9b306c992b83a8033c0ee66daa141d23d010c --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_core/_subprocesses.py @@ -0,0 +1,202 @@ +from __future__ import annotations + +import sys +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from io import BytesIO +from os import PathLike +from subprocess import PIPE, CalledProcessError, CompletedProcess +from typing import IO, Any, Union, cast + +from ..abc import Process +from ._eventloop import get_async_backend +from ._tasks import create_task_group + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +StrOrBytesPath: TypeAlias = Union[str, bytes, "PathLike[str]", "PathLike[bytes]"] + + +async def run_process( + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + input: bytes | None = None, + stdin: int | IO[Any] | None = None, + stdout: int | IO[Any] | None = PIPE, + stderr: int | IO[Any] | None = PIPE, + check: bool = True, + cwd: StrOrBytesPath | None = None, + env: Mapping[str, str] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + start_new_session: bool = False, + pass_fds: Sequence[int] = (), + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, +) -> CompletedProcess[bytes]: + """ + Run an external command in a subprocess and wait until it completes. + + .. seealso:: :func:`subprocess.run` + + :param command: either a string to pass to the shell, or an iterable of strings + containing the executable name or path and its arguments + :param input: bytes passed to the standard input of the subprocess + :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, + a file-like object, or `None`; ``input`` overrides this + :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, + a file-like object, or `None` + :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, + :data:`subprocess.STDOUT`, a file-like object, or `None` + :param check: if ``True``, raise :exc:`~subprocess.CalledProcessError` if the + process terminates with a return code other than 0 + :param cwd: If not ``None``, change the working directory to this before running the + command + :param env: if not ``None``, this mapping replaces the inherited environment + variables from the parent process + :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used + to specify process startup parameters (Windows only) + :param creationflags: flags that can be used to control the creation of the + subprocess (see :class:`subprocess.Popen` for the specifics) + :param start_new_session: if ``true`` the setsid() system call will be made in the + child process prior to the execution of the subprocess. (POSIX only) + :param pass_fds: sequence of file descriptors to keep open between the parent and + child processes. (POSIX only) + :param user: effective user to run the process as (Python >= 3.9, POSIX only) + :param group: effective group to run the process as (Python >= 3.9, POSIX only) + :param extra_groups: supplementary groups to set in the subprocess (Python >= 3.9, + POSIX only) + :param umask: if not negative, this umask is applied in the child process before + running the given command (Python >= 3.9, POSIX only) + :return: an object representing the completed process + :raises ~subprocess.CalledProcessError: if ``check`` is ``True`` and the process + exits with a nonzero return code + + """ + + async def drain_stream(stream: AsyncIterable[bytes], index: int) -> None: + buffer = BytesIO() + async for chunk in stream: + buffer.write(chunk) + + stream_contents[index] = buffer.getvalue() + + if stdin is not None and input is not None: + raise ValueError("only one of stdin and input is allowed") + + async with await open_process( + command, + stdin=PIPE if input else stdin, + stdout=stdout, + stderr=stderr, + cwd=cwd, + env=env, + startupinfo=startupinfo, + creationflags=creationflags, + start_new_session=start_new_session, + pass_fds=pass_fds, + user=user, + group=group, + extra_groups=extra_groups, + umask=umask, + ) as process: + stream_contents: list[bytes | None] = [None, None] + async with create_task_group() as tg: + if process.stdout: + tg.start_soon(drain_stream, process.stdout, 0) + + if process.stderr: + tg.start_soon(drain_stream, process.stderr, 1) + + if process.stdin and input: + await process.stdin.send(input) + await process.stdin.aclose() + + await process.wait() + + output, errors = stream_contents + if check and process.returncode != 0: + raise CalledProcessError(cast(int, process.returncode), command, output, errors) + + return CompletedProcess(command, cast(int, process.returncode), output, errors) + + +async def open_process( + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + stdin: int | IO[Any] | None = PIPE, + stdout: int | IO[Any] | None = PIPE, + stderr: int | IO[Any] | None = PIPE, + cwd: StrOrBytesPath | None = None, + env: Mapping[str, str] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + start_new_session: bool = False, + pass_fds: Sequence[int] = (), + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, +) -> Process: + """ + Start an external command in a subprocess. + + .. seealso:: :class:`subprocess.Popen` + + :param command: either a string to pass to the shell, or an iterable of strings + containing the executable name or path and its arguments + :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, a + file-like object, or ``None`` + :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, + a file-like object, or ``None`` + :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, + :data:`subprocess.STDOUT`, a file-like object, or ``None`` + :param cwd: If not ``None``, the working directory is changed before executing + :param env: If env is not ``None``, it must be a mapping that defines the + environment variables for the new process + :param creationflags: flags that can be used to control the creation of the + subprocess (see :class:`subprocess.Popen` for the specifics) + :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used + to specify process startup parameters (Windows only) + :param start_new_session: if ``true`` the setsid() system call will be made in the + child process prior to the execution of the subprocess. (POSIX only) + :param pass_fds: sequence of file descriptors to keep open between the parent and + child processes. (POSIX only) + :param user: effective user to run the process as (POSIX only) + :param group: effective group to run the process as (POSIX only) + :param extra_groups: supplementary groups to set in the subprocess (POSIX only) + :param umask: if not negative, this umask is applied in the child process before + running the given command (POSIX only) + :return: an asynchronous process object + + """ + kwargs: dict[str, Any] = {} + if user is not None: + kwargs["user"] = user + + if group is not None: + kwargs["group"] = group + + if extra_groups is not None: + kwargs["extra_groups"] = group + + if umask >= 0: + kwargs["umask"] = umask + + return await get_async_backend().open_process( + command, + stdin=stdin, + stdout=stdout, + stderr=stderr, + cwd=cwd, + env=env, + startupinfo=startupinfo, + creationflags=creationflags, + start_new_session=start_new_session, + pass_fds=pass_fds, + **kwargs, + ) diff --git a/venv/lib/python3.10/site-packages/anyio/_core/_synchronization.py b/venv/lib/python3.10/site-packages/anyio/_core/_synchronization.py new file mode 100644 index 0000000000000000000000000000000000000000..caa6efc66fb42e47b8289ff8fbc47a498a59780d --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_core/_synchronization.py @@ -0,0 +1,732 @@ +from __future__ import annotations + +import math +from collections import deque +from dataclasses import dataclass +from types import TracebackType + +from sniffio import AsyncLibraryNotFoundError + +from ..lowlevel import checkpoint +from ._eventloop import get_async_backend +from ._exceptions import BusyResourceError +from ._tasks import CancelScope +from ._testing import TaskInfo, get_current_task + + +@dataclass(frozen=True) +class EventStatistics: + """ + :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Event.wait` + """ + + tasks_waiting: int + + +@dataclass(frozen=True) +class CapacityLimiterStatistics: + """ + :ivar int borrowed_tokens: number of tokens currently borrowed by tasks + :ivar float total_tokens: total number of available tokens + :ivar tuple borrowers: tasks or other objects currently holding tokens borrowed from + this limiter + :ivar int tasks_waiting: number of tasks waiting on + :meth:`~.CapacityLimiter.acquire` or + :meth:`~.CapacityLimiter.acquire_on_behalf_of` + """ + + borrowed_tokens: int + total_tokens: float + borrowers: tuple[object, ...] + tasks_waiting: int + + +@dataclass(frozen=True) +class LockStatistics: + """ + :ivar bool locked: flag indicating if this lock is locked or not + :ivar ~anyio.TaskInfo owner: task currently holding the lock (or ``None`` if the + lock is not held by any task) + :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Lock.acquire` + """ + + locked: bool + owner: TaskInfo | None + tasks_waiting: int + + +@dataclass(frozen=True) +class ConditionStatistics: + """ + :ivar int tasks_waiting: number of tasks blocked on :meth:`~.Condition.wait` + :ivar ~anyio.LockStatistics lock_statistics: statistics of the underlying + :class:`~.Lock` + """ + + tasks_waiting: int + lock_statistics: LockStatistics + + +@dataclass(frozen=True) +class SemaphoreStatistics: + """ + :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Semaphore.acquire` + + """ + + tasks_waiting: int + + +class Event: + def __new__(cls) -> Event: + try: + return get_async_backend().create_event() + except AsyncLibraryNotFoundError: + return EventAdapter() + + def set(self) -> None: + """Set the flag, notifying all listeners.""" + raise NotImplementedError + + def is_set(self) -> bool: + """Return ``True`` if the flag is set, ``False`` if not.""" + raise NotImplementedError + + async def wait(self) -> None: + """ + Wait until the flag has been set. + + If the flag has already been set when this method is called, it returns + immediately. + + """ + raise NotImplementedError + + def statistics(self) -> EventStatistics: + """Return statistics about the current state of this event.""" + raise NotImplementedError + + +class EventAdapter(Event): + _internal_event: Event | None = None + _is_set: bool = False + + def __new__(cls) -> EventAdapter: + return object.__new__(cls) + + @property + def _event(self) -> Event: + if self._internal_event is None: + self._internal_event = get_async_backend().create_event() + if self._is_set: + self._internal_event.set() + + return self._internal_event + + def set(self) -> None: + if self._internal_event is None: + self._is_set = True + else: + self._event.set() + + def is_set(self) -> bool: + if self._internal_event is None: + return self._is_set + + return self._internal_event.is_set() + + async def wait(self) -> None: + await self._event.wait() + + def statistics(self) -> EventStatistics: + if self._internal_event is None: + return EventStatistics(tasks_waiting=0) + + return self._internal_event.statistics() + + +class Lock: + def __new__(cls, *, fast_acquire: bool = False) -> Lock: + try: + return get_async_backend().create_lock(fast_acquire=fast_acquire) + except AsyncLibraryNotFoundError: + return LockAdapter(fast_acquire=fast_acquire) + + async def __aenter__(self) -> None: + await self.acquire() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.release() + + async def acquire(self) -> None: + """Acquire the lock.""" + raise NotImplementedError + + def acquire_nowait(self) -> None: + """ + Acquire the lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + raise NotImplementedError + + def release(self) -> None: + """Release the lock.""" + raise NotImplementedError + + def locked(self) -> bool: + """Return True if the lock is currently held.""" + raise NotImplementedError + + def statistics(self) -> LockStatistics: + """ + Return statistics about the current state of this lock. + + .. versionadded:: 3.0 + """ + raise NotImplementedError + + +class LockAdapter(Lock): + _internal_lock: Lock | None = None + + def __new__(cls, *, fast_acquire: bool = False) -> LockAdapter: + return object.__new__(cls) + + def __init__(self, *, fast_acquire: bool = False): + self._fast_acquire = fast_acquire + + @property + def _lock(self) -> Lock: + if self._internal_lock is None: + self._internal_lock = get_async_backend().create_lock( + fast_acquire=self._fast_acquire + ) + + return self._internal_lock + + async def __aenter__(self) -> None: + await self._lock.acquire() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self._internal_lock is not None: + self._internal_lock.release() + + async def acquire(self) -> None: + """Acquire the lock.""" + await self._lock.acquire() + + def acquire_nowait(self) -> None: + """ + Acquire the lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + self._lock.acquire_nowait() + + def release(self) -> None: + """Release the lock.""" + self._lock.release() + + def locked(self) -> bool: + """Return True if the lock is currently held.""" + return self._lock.locked() + + def statistics(self) -> LockStatistics: + """ + Return statistics about the current state of this lock. + + .. versionadded:: 3.0 + + """ + if self._internal_lock is None: + return LockStatistics(False, None, 0) + + return self._internal_lock.statistics() + + +class Condition: + _owner_task: TaskInfo | None = None + + def __init__(self, lock: Lock | None = None): + self._lock = lock or Lock() + self._waiters: deque[Event] = deque() + + async def __aenter__(self) -> None: + await self.acquire() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.release() + + def _check_acquired(self) -> None: + if self._owner_task != get_current_task(): + raise RuntimeError("The current task is not holding the underlying lock") + + async def acquire(self) -> None: + """Acquire the underlying lock.""" + await self._lock.acquire() + self._owner_task = get_current_task() + + def acquire_nowait(self) -> None: + """ + Acquire the underlying lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + self._lock.acquire_nowait() + self._owner_task = get_current_task() + + def release(self) -> None: + """Release the underlying lock.""" + self._lock.release() + + def locked(self) -> bool: + """Return True if the lock is set.""" + return self._lock.locked() + + def notify(self, n: int = 1) -> None: + """Notify exactly n listeners.""" + self._check_acquired() + for _ in range(n): + try: + event = self._waiters.popleft() + except IndexError: + break + + event.set() + + def notify_all(self) -> None: + """Notify all the listeners.""" + self._check_acquired() + for event in self._waiters: + event.set() + + self._waiters.clear() + + async def wait(self) -> None: + """Wait for a notification.""" + await checkpoint() + event = Event() + self._waiters.append(event) + self.release() + try: + await event.wait() + except BaseException: + if not event.is_set(): + self._waiters.remove(event) + + raise + finally: + with CancelScope(shield=True): + await self.acquire() + + def statistics(self) -> ConditionStatistics: + """ + Return statistics about the current state of this condition. + + .. versionadded:: 3.0 + """ + return ConditionStatistics(len(self._waiters), self._lock.statistics()) + + +class Semaphore: + def __new__( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> Semaphore: + try: + return get_async_backend().create_semaphore( + initial_value, max_value=max_value, fast_acquire=fast_acquire + ) + except AsyncLibraryNotFoundError: + return SemaphoreAdapter(initial_value, max_value=max_value) + + def __init__( + self, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ): + if not isinstance(initial_value, int): + raise TypeError("initial_value must be an integer") + if initial_value < 0: + raise ValueError("initial_value must be >= 0") + if max_value is not None: + if not isinstance(max_value, int): + raise TypeError("max_value must be an integer or None") + if max_value < initial_value: + raise ValueError( + "max_value must be equal to or higher than initial_value" + ) + + self._fast_acquire = fast_acquire + + async def __aenter__(self) -> Semaphore: + await self.acquire() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.release() + + async def acquire(self) -> None: + """Decrement the semaphore value, blocking if necessary.""" + raise NotImplementedError + + def acquire_nowait(self) -> None: + """ + Acquire the underlying lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + raise NotImplementedError + + def release(self) -> None: + """Increment the semaphore value.""" + raise NotImplementedError + + @property + def value(self) -> int: + """The current value of the semaphore.""" + raise NotImplementedError + + @property + def max_value(self) -> int | None: + """The maximum value of the semaphore.""" + raise NotImplementedError + + def statistics(self) -> SemaphoreStatistics: + """ + Return statistics about the current state of this semaphore. + + .. versionadded:: 3.0 + """ + raise NotImplementedError + + +class SemaphoreAdapter(Semaphore): + _internal_semaphore: Semaphore | None = None + + def __new__( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> SemaphoreAdapter: + return object.__new__(cls) + + def __init__( + self, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> None: + super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire) + self._initial_value = initial_value + self._max_value = max_value + + @property + def _semaphore(self) -> Semaphore: + if self._internal_semaphore is None: + self._internal_semaphore = get_async_backend().create_semaphore( + self._initial_value, max_value=self._max_value + ) + + return self._internal_semaphore + + async def acquire(self) -> None: + await self._semaphore.acquire() + + def acquire_nowait(self) -> None: + self._semaphore.acquire_nowait() + + def release(self) -> None: + self._semaphore.release() + + @property + def value(self) -> int: + if self._internal_semaphore is None: + return self._initial_value + + return self._semaphore.value + + @property + def max_value(self) -> int | None: + return self._max_value + + def statistics(self) -> SemaphoreStatistics: + if self._internal_semaphore is None: + return SemaphoreStatistics(tasks_waiting=0) + + return self._semaphore.statistics() + + +class CapacityLimiter: + def __new__(cls, total_tokens: float) -> CapacityLimiter: + try: + return get_async_backend().create_capacity_limiter(total_tokens) + except AsyncLibraryNotFoundError: + return CapacityLimiterAdapter(total_tokens) + + async def __aenter__(self) -> None: + raise NotImplementedError + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + raise NotImplementedError + + @property + def total_tokens(self) -> float: + """ + The total number of tokens available for borrowing. + + This is a read-write property. If the total number of tokens is increased, the + proportionate number of tasks waiting on this limiter will be granted their + tokens. + + .. versionchanged:: 3.0 + The property is now writable. + + """ + raise NotImplementedError + + @total_tokens.setter + def total_tokens(self, value: float) -> None: + raise NotImplementedError + + @property + def borrowed_tokens(self) -> int: + """The number of tokens that have currently been borrowed.""" + raise NotImplementedError + + @property + def available_tokens(self) -> float: + """The number of tokens currently available to be borrowed""" + raise NotImplementedError + + def acquire_nowait(self) -> None: + """ + Acquire a token for the current task without waiting for one to become + available. + + :raises ~anyio.WouldBlock: if there are no tokens available for borrowing + + """ + raise NotImplementedError + + def acquire_on_behalf_of_nowait(self, borrower: object) -> None: + """ + Acquire a token without waiting for one to become available. + + :param borrower: the entity borrowing a token + :raises ~anyio.WouldBlock: if there are no tokens available for borrowing + + """ + raise NotImplementedError + + async def acquire(self) -> None: + """ + Acquire a token for the current task, waiting if necessary for one to become + available. + + """ + raise NotImplementedError + + async def acquire_on_behalf_of(self, borrower: object) -> None: + """ + Acquire a token, waiting if necessary for one to become available. + + :param borrower: the entity borrowing a token + + """ + raise NotImplementedError + + def release(self) -> None: + """ + Release the token held by the current task. + + :raises RuntimeError: if the current task has not borrowed a token from this + limiter. + + """ + raise NotImplementedError + + def release_on_behalf_of(self, borrower: object) -> None: + """ + Release the token held by the given borrower. + + :raises RuntimeError: if the borrower has not borrowed a token from this + limiter. + + """ + raise NotImplementedError + + def statistics(self) -> CapacityLimiterStatistics: + """ + Return statistics about the current state of this limiter. + + .. versionadded:: 3.0 + + """ + raise NotImplementedError + + +class CapacityLimiterAdapter(CapacityLimiter): + _internal_limiter: CapacityLimiter | None = None + + def __new__(cls, total_tokens: float) -> CapacityLimiterAdapter: + return object.__new__(cls) + + def __init__(self, total_tokens: float) -> None: + self.total_tokens = total_tokens + + @property + def _limiter(self) -> CapacityLimiter: + if self._internal_limiter is None: + self._internal_limiter = get_async_backend().create_capacity_limiter( + self._total_tokens + ) + + return self._internal_limiter + + async def __aenter__(self) -> None: + await self._limiter.__aenter__() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + return await self._limiter.__aexit__(exc_type, exc_val, exc_tb) + + @property + def total_tokens(self) -> float: + if self._internal_limiter is None: + return self._total_tokens + + return self._internal_limiter.total_tokens + + @total_tokens.setter + def total_tokens(self, value: float) -> None: + if not isinstance(value, int) and value is not math.inf: + raise TypeError("total_tokens must be an int or math.inf") + elif value < 1: + raise ValueError("total_tokens must be >= 1") + + if self._internal_limiter is None: + self._total_tokens = value + return + + self._limiter.total_tokens = value + + @property + def borrowed_tokens(self) -> int: + if self._internal_limiter is None: + return 0 + + return self._internal_limiter.borrowed_tokens + + @property + def available_tokens(self) -> float: + if self._internal_limiter is None: + return self._total_tokens + + return self._internal_limiter.available_tokens + + def acquire_nowait(self) -> None: + self._limiter.acquire_nowait() + + def acquire_on_behalf_of_nowait(self, borrower: object) -> None: + self._limiter.acquire_on_behalf_of_nowait(borrower) + + async def acquire(self) -> None: + await self._limiter.acquire() + + async def acquire_on_behalf_of(self, borrower: object) -> None: + await self._limiter.acquire_on_behalf_of(borrower) + + def release(self) -> None: + self._limiter.release() + + def release_on_behalf_of(self, borrower: object) -> None: + self._limiter.release_on_behalf_of(borrower) + + def statistics(self) -> CapacityLimiterStatistics: + if self._internal_limiter is None: + return CapacityLimiterStatistics( + borrowed_tokens=0, + total_tokens=self.total_tokens, + borrowers=(), + tasks_waiting=0, + ) + + return self._internal_limiter.statistics() + + +class ResourceGuard: + """ + A context manager for ensuring that a resource is only used by a single task at a + time. + + Entering this context manager while the previous has not exited it yet will trigger + :exc:`BusyResourceError`. + + :param action: the action to guard against (visible in the :exc:`BusyResourceError` + when triggered, e.g. "Another task is already {action} this resource") + + .. versionadded:: 4.1 + """ + + __slots__ = "action", "_guarded" + + def __init__(self, action: str = "using"): + self.action: str = action + self._guarded = False + + def __enter__(self) -> None: + if self._guarded: + raise BusyResourceError(self.action) + + self._guarded = True + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self._guarded = False diff --git a/venv/lib/python3.10/site-packages/anyio/_core/_tasks.py b/venv/lib/python3.10/site-packages/anyio/_core/_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..fe49015102b3c8d6c964dc1d85e1da2b42279112 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_core/_tasks.py @@ -0,0 +1,158 @@ +from __future__ import annotations + +import math +from collections.abc import Generator +from contextlib import contextmanager +from types import TracebackType + +from ..abc._tasks import TaskGroup, TaskStatus +from ._eventloop import get_async_backend + + +class _IgnoredTaskStatus(TaskStatus[object]): + def started(self, value: object = None) -> None: + pass + + +TASK_STATUS_IGNORED = _IgnoredTaskStatus() + + +class CancelScope: + """ + Wraps a unit of work that can be made separately cancellable. + + :param deadline: The time (clock value) when this scope is cancelled automatically + :param shield: ``True`` to shield the cancel scope from external cancellation + """ + + def __new__( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> CancelScope: + return get_async_backend().create_cancel_scope(shield=shield, deadline=deadline) + + def cancel(self) -> None: + """Cancel this scope immediately.""" + raise NotImplementedError + + @property + def deadline(self) -> float: + """ + The time (clock value) when this scope is cancelled automatically. + + Will be ``float('inf')`` if no timeout has been set. + + """ + raise NotImplementedError + + @deadline.setter + def deadline(self, value: float) -> None: + raise NotImplementedError + + @property + def cancel_called(self) -> bool: + """``True`` if :meth:`cancel` has been called.""" + raise NotImplementedError + + @property + def cancelled_caught(self) -> bool: + """ + ``True`` if this scope suppressed a cancellation exception it itself raised. + + This is typically used to check if any work was interrupted, or to see if the + scope was cancelled due to its deadline being reached. The value will, however, + only be ``True`` if the cancellation was triggered by the scope itself (and not + an outer scope). + + """ + raise NotImplementedError + + @property + def shield(self) -> bool: + """ + ``True`` if this scope is shielded from external cancellation. + + While a scope is shielded, it will not receive cancellations from outside. + + """ + raise NotImplementedError + + @shield.setter + def shield(self, value: bool) -> None: + raise NotImplementedError + + def __enter__(self) -> CancelScope: + raise NotImplementedError + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + raise NotImplementedError + + +@contextmanager +def fail_after( + delay: float | None, shield: bool = False +) -> Generator[CancelScope, None, None]: + """ + Create a context manager which raises a :class:`TimeoutError` if does not finish in + time. + + :param delay: maximum allowed time (in seconds) before raising the exception, or + ``None`` to disable the timeout + :param shield: ``True`` to shield the cancel scope from external cancellation + :return: a context manager that yields a cancel scope + :rtype: :class:`~typing.ContextManager`\\[:class:`~anyio.CancelScope`\\] + + """ + current_time = get_async_backend().current_time + deadline = (current_time() + delay) if delay is not None else math.inf + with get_async_backend().create_cancel_scope( + deadline=deadline, shield=shield + ) as cancel_scope: + yield cancel_scope + + if cancel_scope.cancelled_caught and current_time() >= cancel_scope.deadline: + raise TimeoutError + + +def move_on_after(delay: float | None, shield: bool = False) -> CancelScope: + """ + Create a cancel scope with a deadline that expires after the given delay. + + :param delay: maximum allowed time (in seconds) before exiting the context block, or + ``None`` to disable the timeout + :param shield: ``True`` to shield the cancel scope from external cancellation + :return: a cancel scope + + """ + deadline = ( + (get_async_backend().current_time() + delay) if delay is not None else math.inf + ) + return get_async_backend().create_cancel_scope(deadline=deadline, shield=shield) + + +def current_effective_deadline() -> float: + """ + Return the nearest deadline among all the cancel scopes effective for the current + task. + + :return: a clock value from the event loop's internal clock (or ``float('inf')`` if + there is no deadline in effect, or ``float('-inf')`` if the current scope has + been cancelled) + :rtype: float + + """ + return get_async_backend().current_effective_deadline() + + +def create_task_group() -> TaskGroup: + """ + Create a task group. + + :return: a task group + + """ + return get_async_backend().create_task_group() diff --git a/venv/lib/python3.10/site-packages/anyio/_core/_tempfile.py b/venv/lib/python3.10/site-packages/anyio/_core/_tempfile.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb6b14a9a8eae9dcaa66eb68ac36d2084617877 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_core/_tempfile.py @@ -0,0 +1,616 @@ +from __future__ import annotations + +import os +import sys +import tempfile +from collections.abc import Iterable +from io import BytesIO, TextIOWrapper +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + AnyStr, + Generic, + overload, +) + +from .. import to_thread +from .._core._fileio import AsyncFile +from ..lowlevel import checkpoint_if_cancelled + +if TYPE_CHECKING: + from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBuffer + + +class TemporaryFile(Generic[AnyStr]): + """ + An asynchronous temporary file that is automatically created and cleaned up. + + This class provides an asynchronous context manager interface to a temporary file. + The file is created using Python's standard `tempfile.TemporaryFile` function in a + background thread, and is wrapped as an asynchronous file using `AsyncFile`. + + :param mode: The mode in which the file is opened. Defaults to "w+b". + :param buffering: The buffering policy (-1 means the default buffering). + :param encoding: The encoding used to decode or encode the file. Only applicable in + text mode. + :param newline: Controls how universal newlines mode works (only applicable in text + mode). + :param suffix: The suffix for the temporary file name. + :param prefix: The prefix for the temporary file name. + :param dir: The directory in which the temporary file is created. + :param errors: The error handling scheme used for encoding/decoding errors. + """ + + _async_file: AsyncFile[AnyStr] + + @overload + def __init__( + self: TemporaryFile[bytes], + mode: OpenBinaryMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + @overload + def __init__( + self: TemporaryFile[str], + mode: OpenTextMode, + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + + def __init__( + self, + mode: OpenTextMode | OpenBinaryMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: + self.mode = mode + self.buffering = buffering + self.encoding = encoding + self.newline = newline + self.suffix: str | None = suffix + self.prefix: str | None = prefix + self.dir: str | None = dir + self.errors = errors + + async def __aenter__(self) -> AsyncFile[AnyStr]: + fp = await to_thread.run_sync( + lambda: tempfile.TemporaryFile( + self.mode, + self.buffering, + self.encoding, + self.newline, + self.suffix, + self.prefix, + self.dir, + errors=self.errors, + ) + ) + self._async_file = AsyncFile(fp) + return self._async_file + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self._async_file.aclose() + + +class NamedTemporaryFile(Generic[AnyStr]): + """ + An asynchronous named temporary file that is automatically created and cleaned up. + + This class provides an asynchronous context manager for a temporary file with a + visible name in the file system. It uses Python's standard + :func:`~tempfile.NamedTemporaryFile` function and wraps the file object with + :class:`AsyncFile` for asynchronous operations. + + :param mode: The mode in which the file is opened. Defaults to "w+b". + :param buffering: The buffering policy (-1 means the default buffering). + :param encoding: The encoding used to decode or encode the file. Only applicable in + text mode. + :param newline: Controls how universal newlines mode works (only applicable in text + mode). + :param suffix: The suffix for the temporary file name. + :param prefix: The prefix for the temporary file name. + :param dir: The directory in which the temporary file is created. + :param delete: Whether to delete the file when it is closed. + :param errors: The error handling scheme used for encoding/decoding errors. + :param delete_on_close: (Python 3.12+) Whether to delete the file on close. + """ + + _async_file: AsyncFile[AnyStr] + + @overload + def __init__( + self: NamedTemporaryFile[bytes], + mode: OpenBinaryMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + delete: bool = ..., + *, + errors: str | None = ..., + delete_on_close: bool = ..., + ): ... + @overload + def __init__( + self: NamedTemporaryFile[str], + mode: OpenTextMode, + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + delete: bool = ..., + *, + errors: str | None = ..., + delete_on_close: bool = ..., + ): ... + + def __init__( + self, + mode: OpenBinaryMode | OpenTextMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + delete: bool = True, + *, + errors: str | None = None, + delete_on_close: bool = True, + ) -> None: + self._params: dict[str, Any] = { + "mode": mode, + "buffering": buffering, + "encoding": encoding, + "newline": newline, + "suffix": suffix, + "prefix": prefix, + "dir": dir, + "delete": delete, + "errors": errors, + } + if sys.version_info >= (3, 12): + self._params["delete_on_close"] = delete_on_close + + async def __aenter__(self) -> AsyncFile[AnyStr]: + fp = await to_thread.run_sync( + lambda: tempfile.NamedTemporaryFile(**self._params) + ) + self._async_file = AsyncFile(fp) + return self._async_file + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self._async_file.aclose() + + +class SpooledTemporaryFile(AsyncFile[AnyStr]): + """ + An asynchronous spooled temporary file that starts in memory and is spooled to disk. + + This class provides an asynchronous interface to a spooled temporary file, much like + Python's standard :class:`~tempfile.SpooledTemporaryFile`. It supports asynchronous + write operations and provides a method to force a rollover to disk. + + :param max_size: Maximum size in bytes before the file is rolled over to disk. + :param mode: The mode in which the file is opened. Defaults to "w+b". + :param buffering: The buffering policy (-1 means the default buffering). + :param encoding: The encoding used to decode or encode the file (text mode only). + :param newline: Controls how universal newlines mode works (text mode only). + :param suffix: The suffix for the temporary file name. + :param prefix: The prefix for the temporary file name. + :param dir: The directory in which the temporary file is created. + :param errors: The error handling scheme used for encoding/decoding errors. + """ + + _rolled: bool = False + + @overload + def __init__( + self: SpooledTemporaryFile[bytes], + max_size: int = ..., + mode: OpenBinaryMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + @overload + def __init__( + self: SpooledTemporaryFile[str], + max_size: int = ..., + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + + def __init__( + self, + max_size: int = 0, + mode: OpenBinaryMode | OpenTextMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: + self._tempfile_params: dict[str, Any] = { + "mode": mode, + "buffering": buffering, + "encoding": encoding, + "newline": newline, + "suffix": suffix, + "prefix": prefix, + "dir": dir, + "errors": errors, + } + self._max_size = max_size + if "b" in mode: + super().__init__(BytesIO()) # type: ignore[arg-type] + else: + super().__init__( + TextIOWrapper( # type: ignore[arg-type] + BytesIO(), + encoding=encoding, + errors=errors, + newline=newline, + write_through=True, + ) + ) + + async def aclose(self) -> None: + if not self._rolled: + self._fp.close() + return + + await super().aclose() + + async def _check(self) -> None: + if self._rolled or self._fp.tell() <= self._max_size: + return + + await self.rollover() + + async def rollover(self) -> None: + if self._rolled: + return + + self._rolled = True + buffer = self._fp + buffer.seek(0) + self._fp = await to_thread.run_sync( + lambda: tempfile.TemporaryFile(**self._tempfile_params) + ) + await self.write(buffer.read()) + buffer.close() + + @property + def closed(self) -> bool: + return self._fp.closed + + async def read(self, size: int = -1) -> AnyStr: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.read(size) + + return await super().read(size) # type: ignore[return-value] + + async def read1(self: SpooledTemporaryFile[bytes], size: int = -1) -> bytes: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.read1(size) + + return await super().read1(size) + + async def readline(self) -> AnyStr: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.readline() + + return await super().readline() # type: ignore[return-value] + + async def readlines(self) -> list[AnyStr]: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.readlines() + + return await super().readlines() # type: ignore[return-value] + + async def readinto(self: SpooledTemporaryFile[bytes], b: WriteableBuffer) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + self._fp.readinto(b) + + return await super().readinto(b) + + async def readinto1(self: SpooledTemporaryFile[bytes], b: WriteableBuffer) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + self._fp.readinto(b) + + return await super().readinto1(b) + + async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.seek(offset, whence) + + return await super().seek(offset, whence) + + async def tell(self) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.tell() + + return await super().tell() + + async def truncate(self, size: int | None = None) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.truncate(size) + + return await super().truncate(size) + + @overload + async def write(self: SpooledTemporaryFile[bytes], b: ReadableBuffer) -> int: ... + @overload + async def write(self: SpooledTemporaryFile[str], b: str) -> int: ... + + async def write(self, b: ReadableBuffer | str) -> int: + """ + Asynchronously write data to the spooled temporary file. + + If the file has not yet been rolled over, the data is written synchronously, + and a rollover is triggered if the size exceeds the maximum size. + + :param s: The data to write. + :return: The number of bytes written. + :raises RuntimeError: If the underlying file is not initialized. + + """ + if not self._rolled: + await checkpoint_if_cancelled() + result = self._fp.write(b) + await self._check() + return result + + return await super().write(b) # type: ignore[misc] + + @overload + async def writelines( + self: SpooledTemporaryFile[bytes], lines: Iterable[ReadableBuffer] + ) -> None: ... + @overload + async def writelines( + self: SpooledTemporaryFile[str], lines: Iterable[str] + ) -> None: ... + + async def writelines(self, lines: Iterable[str] | Iterable[ReadableBuffer]) -> None: + """ + Asynchronously write a list of lines to the spooled temporary file. + + If the file has not yet been rolled over, the lines are written synchronously, + and a rollover is triggered if the size exceeds the maximum size. + + :param lines: An iterable of lines to write. + :raises RuntimeError: If the underlying file is not initialized. + + """ + if not self._rolled: + await checkpoint_if_cancelled() + result = self._fp.writelines(lines) + await self._check() + return result + + return await super().writelines(lines) # type: ignore[misc] + + +class TemporaryDirectory(Generic[AnyStr]): + """ + An asynchronous temporary directory that is created and cleaned up automatically. + + This class provides an asynchronous context manager for creating a temporary + directory. It wraps Python's standard :class:`~tempfile.TemporaryDirectory` to + perform directory creation and cleanup operations in a background thread. + + :param suffix: Suffix to be added to the temporary directory name. + :param prefix: Prefix to be added to the temporary directory name. + :param dir: The parent directory where the temporary directory is created. + :param ignore_cleanup_errors: Whether to ignore errors during cleanup + (Python 3.10+). + :param delete: Whether to delete the directory upon closing (Python 3.12+). + """ + + def __init__( + self, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: AnyStr | None = None, + *, + ignore_cleanup_errors: bool = False, + delete: bool = True, + ) -> None: + self.suffix: AnyStr | None = suffix + self.prefix: AnyStr | None = prefix + self.dir: AnyStr | None = dir + self.ignore_cleanup_errors = ignore_cleanup_errors + self.delete = delete + + self._tempdir: tempfile.TemporaryDirectory | None = None + + async def __aenter__(self) -> str: + params: dict[str, Any] = { + "suffix": self.suffix, + "prefix": self.prefix, + "dir": self.dir, + } + if sys.version_info >= (3, 10): + params["ignore_cleanup_errors"] = self.ignore_cleanup_errors + + if sys.version_info >= (3, 12): + params["delete"] = self.delete + + self._tempdir = await to_thread.run_sync( + lambda: tempfile.TemporaryDirectory(**params) + ) + return await to_thread.run_sync(self._tempdir.__enter__) + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + if self._tempdir is not None: + await to_thread.run_sync( + self._tempdir.__exit__, exc_type, exc_value, traceback + ) + + async def cleanup(self) -> None: + if self._tempdir is not None: + await to_thread.run_sync(self._tempdir.cleanup) + + +@overload +async def mkstemp( + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + text: bool = False, +) -> tuple[int, str]: ... + + +@overload +async def mkstemp( + suffix: bytes | None = None, + prefix: bytes | None = None, + dir: bytes | None = None, + text: bool = False, +) -> tuple[int, bytes]: ... + + +async def mkstemp( + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: AnyStr | None = None, + text: bool = False, +) -> tuple[int, str | bytes]: + """ + Asynchronously create a temporary file and return an OS-level handle and the file + name. + + This function wraps `tempfile.mkstemp` and executes it in a background thread. + + :param suffix: Suffix to be added to the file name. + :param prefix: Prefix to be added to the file name. + :param dir: Directory in which the temporary file is created. + :param text: Whether the file is opened in text mode. + :return: A tuple containing the file descriptor and the file name. + + """ + return await to_thread.run_sync(tempfile.mkstemp, suffix, prefix, dir, text) + + +@overload +async def mkdtemp( + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, +) -> str: ... + + +@overload +async def mkdtemp( + suffix: bytes | None = None, + prefix: bytes | None = None, + dir: bytes | None = None, +) -> bytes: ... + + +async def mkdtemp( + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: AnyStr | None = None, +) -> str | bytes: + """ + Asynchronously create a temporary directory and return its path. + + This function wraps `tempfile.mkdtemp` and executes it in a background thread. + + :param suffix: Suffix to be added to the directory name. + :param prefix: Prefix to be added to the directory name. + :param dir: Parent directory where the temporary directory is created. + :return: The path of the created temporary directory. + + """ + return await to_thread.run_sync(tempfile.mkdtemp, suffix, prefix, dir) + + +async def gettempdir() -> str: + """ + Asynchronously return the name of the directory used for temporary files. + + This function wraps `tempfile.gettempdir` and executes it in a background thread. + + :return: The path of the temporary directory as a string. + + """ + return await to_thread.run_sync(tempfile.gettempdir) + + +async def gettempdirb() -> bytes: + """ + Asynchronously return the name of the directory used for temporary files in bytes. + + This function wraps `tempfile.gettempdirb` and executes it in a background thread. + + :return: The path of the temporary directory as bytes. + + """ + return await to_thread.run_sync(tempfile.gettempdirb) diff --git a/venv/lib/python3.10/site-packages/anyio/_core/_testing.py b/venv/lib/python3.10/site-packages/anyio/_core/_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..9e28b22766d8a4bd0af8949445f3f1aa2f684c6a --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_core/_testing.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +from collections.abc import Awaitable, Generator +from typing import Any, cast + +from ._eventloop import get_async_backend + + +class TaskInfo: + """ + Represents an asynchronous task. + + :ivar int id: the unique identifier of the task + :ivar parent_id: the identifier of the parent task, if any + :vartype parent_id: Optional[int] + :ivar str name: the description of the task (if any) + :ivar ~collections.abc.Coroutine coro: the coroutine object of the task + """ + + __slots__ = "_name", "id", "parent_id", "name", "coro" + + def __init__( + self, + id: int, + parent_id: int | None, + name: str | None, + coro: Generator[Any, Any, Any] | Awaitable[Any], + ): + func = get_current_task + self._name = f"{func.__module__}.{func.__qualname__}" + self.id: int = id + self.parent_id: int | None = parent_id + self.name: str | None = name + self.coro: Generator[Any, Any, Any] | Awaitable[Any] = coro + + def __eq__(self, other: object) -> bool: + if isinstance(other, TaskInfo): + return self.id == other.id + + return NotImplemented + + def __hash__(self) -> int: + return hash(self.id) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(id={self.id!r}, name={self.name!r})" + + def has_pending_cancellation(self) -> bool: + """ + Return ``True`` if the task has a cancellation pending, ``False`` otherwise. + + """ + return False + + +def get_current_task() -> TaskInfo: + """ + Return the current task. + + :return: a representation of the current task + + """ + return get_async_backend().get_current_task() + + +def get_running_tasks() -> list[TaskInfo]: + """ + Return a list of running tasks in the current event loop. + + :return: a list of task info objects + + """ + return cast("list[TaskInfo]", get_async_backend().get_running_tasks()) + + +async def wait_all_tasks_blocked() -> None: + """Wait until all other tasks are waiting for something.""" + await get_async_backend().wait_all_tasks_blocked() diff --git a/venv/lib/python3.10/site-packages/anyio/_core/_typedattr.py b/venv/lib/python3.10/site-packages/anyio/_core/_typedattr.py new file mode 100644 index 0000000000000000000000000000000000000000..f358a448cb12739fd4eda4f4859d3a24ddd1de63 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/_core/_typedattr.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +from collections.abc import Callable, Mapping +from typing import Any, TypeVar, final, overload + +from ._exceptions import TypedAttributeLookupError + +T_Attr = TypeVar("T_Attr") +T_Default = TypeVar("T_Default") +undefined = object() + + +def typed_attribute() -> Any: + """Return a unique object, used to mark typed attributes.""" + return object() + + +class TypedAttributeSet: + """ + Superclass for typed attribute collections. + + Checks that every public attribute of every subclass has a type annotation. + """ + + def __init_subclass__(cls) -> None: + annotations: dict[str, Any] = getattr(cls, "__annotations__", {}) + for attrname in dir(cls): + if not attrname.startswith("_") and attrname not in annotations: + raise TypeError( + f"Attribute {attrname!r} is missing its type annotation" + ) + + super().__init_subclass__() + + +class TypedAttributeProvider: + """Base class for classes that wish to provide typed extra attributes.""" + + @property + def extra_attributes(self) -> Mapping[T_Attr, Callable[[], T_Attr]]: + """ + A mapping of the extra attributes to callables that return the corresponding + values. + + If the provider wraps another provider, the attributes from that wrapper should + also be included in the returned mapping (but the wrapper may override the + callables from the wrapped instance). + + """ + return {} + + @overload + def extra(self, attribute: T_Attr) -> T_Attr: ... + + @overload + def extra(self, attribute: T_Attr, default: T_Default) -> T_Attr | T_Default: ... + + @final + def extra(self, attribute: Any, default: object = undefined) -> object: + """ + extra(attribute, default=undefined) + + Return the value of the given typed extra attribute. + + :param attribute: the attribute (member of a :class:`~TypedAttributeSet`) to + look for + :param default: the value that should be returned if no value is found for the + attribute + :raises ~anyio.TypedAttributeLookupError: if the search failed and no default + value was given + + """ + try: + getter = self.extra_attributes[attribute] + except KeyError: + if default is undefined: + raise TypedAttributeLookupError("Attribute not found") from None + else: + return default + + return getter() diff --git a/venv/lib/python3.10/site-packages/anyio/abc/__init__.py b/venv/lib/python3.10/site-packages/anyio/abc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d560ce3f1fa45a7ee4a3bc8958aa59702caa9d0c --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/abc/__init__.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from ._eventloop import AsyncBackend as AsyncBackend +from ._resources import AsyncResource as AsyncResource +from ._sockets import ConnectedUDPSocket as ConnectedUDPSocket +from ._sockets import ConnectedUNIXDatagramSocket as ConnectedUNIXDatagramSocket +from ._sockets import IPAddressType as IPAddressType +from ._sockets import IPSockAddrType as IPSockAddrType +from ._sockets import SocketAttribute as SocketAttribute +from ._sockets import SocketListener as SocketListener +from ._sockets import SocketStream as SocketStream +from ._sockets import UDPPacketType as UDPPacketType +from ._sockets import UDPSocket as UDPSocket +from ._sockets import UNIXDatagramPacketType as UNIXDatagramPacketType +from ._sockets import UNIXDatagramSocket as UNIXDatagramSocket +from ._sockets import UNIXSocketStream as UNIXSocketStream +from ._streams import AnyByteReceiveStream as AnyByteReceiveStream +from ._streams import AnyByteSendStream as AnyByteSendStream +from ._streams import AnyByteStream as AnyByteStream +from ._streams import AnyByteStreamConnectable as AnyByteStreamConnectable +from ._streams import AnyUnreliableByteReceiveStream as AnyUnreliableByteReceiveStream +from ._streams import AnyUnreliableByteSendStream as AnyUnreliableByteSendStream +from ._streams import AnyUnreliableByteStream as AnyUnreliableByteStream +from ._streams import ByteReceiveStream as ByteReceiveStream +from ._streams import ByteSendStream as ByteSendStream +from ._streams import ByteStream as ByteStream +from ._streams import ByteStreamConnectable as ByteStreamConnectable +from ._streams import Listener as Listener +from ._streams import ObjectReceiveStream as ObjectReceiveStream +from ._streams import ObjectSendStream as ObjectSendStream +from ._streams import ObjectStream as ObjectStream +from ._streams import ObjectStreamConnectable as ObjectStreamConnectable +from ._streams import UnreliableObjectReceiveStream as UnreliableObjectReceiveStream +from ._streams import UnreliableObjectSendStream as UnreliableObjectSendStream +from ._streams import UnreliableObjectStream as UnreliableObjectStream +from ._subprocesses import Process as Process +from ._tasks import TaskGroup as TaskGroup +from ._tasks import TaskStatus as TaskStatus +from ._testing import TestRunner as TestRunner + +# Re-exported here, for backwards compatibility +# isort: off +from .._core._synchronization import ( + CapacityLimiter as CapacityLimiter, + Condition as Condition, + Event as Event, + Lock as Lock, + Semaphore as Semaphore, +) +from .._core._tasks import CancelScope as CancelScope +from ..from_thread import BlockingPortal as BlockingPortal + +# Re-export imports so they look like they live directly in this package +for __value in list(locals().values()): + if getattr(__value, "__module__", "").startswith("anyio.abc."): + __value.__module__ = __name__ + +del __value diff --git a/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99531e1b16b7166e78a6835184e8b50ff1e35d90 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_eventloop.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_eventloop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39310d523bd36483461b8aad5c1687b7b2c4c6d3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_eventloop.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_resources.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_resources.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ccb565b03460ad0509ea56d9d44c8716e38c8a0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_resources.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_sockets.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_sockets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34aa380deda15c1341a474749f7a743c98622ddc Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_sockets.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_streams.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_streams.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1808fa8d4c60d27e5cc319872dd53be6183ac8fa Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_streams.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_subprocesses.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_subprocesses.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37061b5c427c14e2606eaa8ee1b37a473ce06f80 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_subprocesses.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_tasks.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_tasks.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecadccd52400e62a692b1ce0dec39e3a6c4f2472 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_tasks.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_testing.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_testing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dde093965c73caf25b44716ea6ca1d57795452eb Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/abc/__pycache__/_testing.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/abc/_eventloop.py b/venv/lib/python3.10/site-packages/anyio/abc/_eventloop.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd9e08855e359542fe001b1165a0caf47a126dd --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/abc/_eventloop.py @@ -0,0 +1,418 @@ +from __future__ import annotations + +import math +import sys +from abc import ABCMeta, abstractmethod +from collections.abc import AsyncIterator, Awaitable, Callable, Sequence +from contextlib import AbstractContextManager +from os import PathLike +from signal import Signals +from socket import AddressFamily, SocketKind, socket +from typing import ( + IO, + TYPE_CHECKING, + Any, + TypeVar, + Union, + overload, +) + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike + + from .._core._synchronization import CapacityLimiter, Event, Lock, Semaphore + from .._core._tasks import CancelScope + from .._core._testing import TaskInfo + from ..from_thread import BlockingPortal + from ._sockets import ( + ConnectedUDPSocket, + ConnectedUNIXDatagramSocket, + IPSockAddrType, + SocketListener, + SocketStream, + UDPSocket, + UNIXDatagramSocket, + UNIXSocketStream, + ) + from ._subprocesses import Process + from ._tasks import TaskGroup + from ._testing import TestRunner + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") +StrOrBytesPath: TypeAlias = Union[str, bytes, "PathLike[str]", "PathLike[bytes]"] + + +class AsyncBackend(metaclass=ABCMeta): + @classmethod + @abstractmethod + def run( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + options: dict[str, Any], + ) -> T_Retval: + """ + Run the given coroutine function in an asynchronous event loop. + + The current thread must not be already running an event loop. + + :param func: a coroutine function + :param args: positional arguments to ``func`` + :param kwargs: positional arguments to ``func`` + :param options: keyword arguments to call the backend ``run()`` implementation + with + :return: the return value of the coroutine function + """ + + @classmethod + @abstractmethod + def current_token(cls) -> object: + """ + + :return: + """ + + @classmethod + @abstractmethod + def current_time(cls) -> float: + """ + Return the current value of the event loop's internal clock. + + :return: the clock value (seconds) + """ + + @classmethod + @abstractmethod + def cancelled_exception_class(cls) -> type[BaseException]: + """Return the exception class that is raised in a task if it's cancelled.""" + + @classmethod + @abstractmethod + async def checkpoint(cls) -> None: + """ + Check if the task has been cancelled, and allow rescheduling of other tasks. + + This is effectively the same as running :meth:`checkpoint_if_cancelled` and then + :meth:`cancel_shielded_checkpoint`. + """ + + @classmethod + async def checkpoint_if_cancelled(cls) -> None: + """ + Check if the current task group has been cancelled. + + This will check if the task has been cancelled, but will not allow other tasks + to be scheduled if not. + + """ + if cls.current_effective_deadline() == -math.inf: + await cls.checkpoint() + + @classmethod + async def cancel_shielded_checkpoint(cls) -> None: + """ + Allow the rescheduling of other tasks. + + This will give other tasks the opportunity to run, but without checking if the + current task group has been cancelled, unlike with :meth:`checkpoint`. + + """ + with cls.create_cancel_scope(shield=True): + await cls.sleep(0) + + @classmethod + @abstractmethod + async def sleep(cls, delay: float) -> None: + """ + Pause the current task for the specified duration. + + :param delay: the duration, in seconds + """ + + @classmethod + @abstractmethod + def create_cancel_scope( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> CancelScope: + pass + + @classmethod + @abstractmethod + def current_effective_deadline(cls) -> float: + """ + Return the nearest deadline among all the cancel scopes effective for the + current task. + + :return: + - a clock value from the event loop's internal clock + - ``inf`` if there is no deadline in effect + - ``-inf`` if the current scope has been cancelled + :rtype: float + """ + + @classmethod + @abstractmethod + def create_task_group(cls) -> TaskGroup: + pass + + @classmethod + @abstractmethod + def create_event(cls) -> Event: + pass + + @classmethod + @abstractmethod + def create_lock(cls, *, fast_acquire: bool) -> Lock: + pass + + @classmethod + @abstractmethod + def create_semaphore( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> Semaphore: + pass + + @classmethod + @abstractmethod + def create_capacity_limiter(cls, total_tokens: float) -> CapacityLimiter: + pass + + @classmethod + @abstractmethod + async def run_sync_in_worker_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + abandon_on_cancel: bool = False, + limiter: CapacityLimiter | None = None, + ) -> T_Retval: + pass + + @classmethod + @abstractmethod + def check_cancelled(cls) -> None: + pass + + @classmethod + @abstractmethod + def run_async_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + pass + + @classmethod + @abstractmethod + def run_sync_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + pass + + @classmethod + @abstractmethod + def create_blocking_portal(cls) -> BlockingPortal: + pass + + @classmethod + @abstractmethod + async def open_process( + cls, + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + stdin: int | IO[Any] | None, + stdout: int | IO[Any] | None, + stderr: int | IO[Any] | None, + **kwargs: Any, + ) -> Process: + pass + + @classmethod + @abstractmethod + def setup_process_pool_exit_at_shutdown(cls, workers: set[Process]) -> None: + pass + + @classmethod + @abstractmethod + async def connect_tcp( + cls, host: str, port: int, local_address: IPSockAddrType | None = None + ) -> SocketStream: + pass + + @classmethod + @abstractmethod + async def connect_unix(cls, path: str | bytes) -> UNIXSocketStream: + pass + + @classmethod + @abstractmethod + def create_tcp_listener(cls, sock: socket) -> SocketListener: + pass + + @classmethod + @abstractmethod + def create_unix_listener(cls, sock: socket) -> SocketListener: + pass + + @classmethod + @abstractmethod + async def create_udp_socket( + cls, + family: AddressFamily, + local_address: IPSockAddrType | None, + remote_address: IPSockAddrType | None, + reuse_port: bool, + ) -> UDPSocket | ConnectedUDPSocket: + pass + + @classmethod + @overload + async def create_unix_datagram_socket( + cls, raw_socket: socket, remote_path: None + ) -> UNIXDatagramSocket: ... + + @classmethod + @overload + async def create_unix_datagram_socket( + cls, raw_socket: socket, remote_path: str | bytes + ) -> ConnectedUNIXDatagramSocket: ... + + @classmethod + @abstractmethod + async def create_unix_datagram_socket( + cls, raw_socket: socket, remote_path: str | bytes | None + ) -> UNIXDatagramSocket | ConnectedUNIXDatagramSocket: + pass + + @classmethod + @abstractmethod + async def getaddrinfo( + cls, + host: bytes | str | None, + port: str | int | None, + *, + family: int | AddressFamily = 0, + type: int | SocketKind = 0, + proto: int = 0, + flags: int = 0, + ) -> Sequence[ + tuple[ + AddressFamily, + SocketKind, + int, + str, + tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], + ] + ]: + pass + + @classmethod + @abstractmethod + async def getnameinfo( + cls, sockaddr: IPSockAddrType, flags: int = 0 + ) -> tuple[str, str]: + pass + + @classmethod + @abstractmethod + async def wait_readable(cls, obj: FileDescriptorLike) -> None: + pass + + @classmethod + @abstractmethod + async def wait_writable(cls, obj: FileDescriptorLike) -> None: + pass + + @classmethod + @abstractmethod + def notify_closing(cls, obj: FileDescriptorLike) -> None: + pass + + @classmethod + @abstractmethod + async def wrap_listener_socket(cls, sock: socket) -> SocketListener: + pass + + @classmethod + @abstractmethod + async def wrap_stream_socket(cls, sock: socket) -> SocketStream: + pass + + @classmethod + @abstractmethod + async def wrap_unix_stream_socket(cls, sock: socket) -> UNIXSocketStream: + pass + + @classmethod + @abstractmethod + async def wrap_udp_socket(cls, sock: socket) -> UDPSocket: + pass + + @classmethod + @abstractmethod + async def wrap_connected_udp_socket(cls, sock: socket) -> ConnectedUDPSocket: + pass + + @classmethod + @abstractmethod + async def wrap_unix_datagram_socket(cls, sock: socket) -> UNIXDatagramSocket: + pass + + @classmethod + @abstractmethod + async def wrap_connected_unix_datagram_socket( + cls, sock: socket + ) -> ConnectedUNIXDatagramSocket: + pass + + @classmethod + @abstractmethod + def current_default_thread_limiter(cls) -> CapacityLimiter: + pass + + @classmethod + @abstractmethod + def open_signal_receiver( + cls, *signals: Signals + ) -> AbstractContextManager[AsyncIterator[Signals]]: + pass + + @classmethod + @abstractmethod + def get_current_task(cls) -> TaskInfo: + pass + + @classmethod + @abstractmethod + def get_running_tasks(cls) -> Sequence[TaskInfo]: + pass + + @classmethod + @abstractmethod + async def wait_all_tasks_blocked(cls) -> None: + pass + + @classmethod + @abstractmethod + def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: + pass diff --git a/venv/lib/python3.10/site-packages/anyio/abc/_resources.py b/venv/lib/python3.10/site-packages/anyio/abc/_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..10df115a7b9f975493476da763cc1e26dbd822e5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/abc/_resources.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from abc import ABCMeta, abstractmethod +from types import TracebackType +from typing import TypeVar + +T = TypeVar("T") + + +class AsyncResource(metaclass=ABCMeta): + """ + Abstract base class for all closeable asynchronous resources. + + Works as an asynchronous context manager which returns the instance itself on enter, + and calls :meth:`aclose` on exit. + """ + + __slots__ = () + + async def __aenter__(self: T) -> T: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.aclose() + + @abstractmethod + async def aclose(self) -> None: + """Close the resource.""" diff --git a/venv/lib/python3.10/site-packages/anyio/abc/_sockets.py b/venv/lib/python3.10/site-packages/anyio/abc/_sockets.py new file mode 100644 index 0000000000000000000000000000000000000000..3ff60d4d9dfc3c15d416c9fc4a6b3b7f79a9fdb1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/abc/_sockets.py @@ -0,0 +1,405 @@ +from __future__ import annotations + +import errno +import socket +import sys +from abc import abstractmethod +from collections.abc import Callable, Collection, Mapping +from contextlib import AsyncExitStack +from io import IOBase +from ipaddress import IPv4Address, IPv6Address +from socket import AddressFamily +from typing import Any, TypeVar, Union + +from .._core._eventloop import get_async_backend +from .._core._typedattr import ( + TypedAttributeProvider, + TypedAttributeSet, + typed_attribute, +) +from ._streams import ByteStream, Listener, UnreliableObjectStream +from ._tasks import TaskGroup + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +IPAddressType: TypeAlias = Union[str, IPv4Address, IPv6Address] +IPSockAddrType: TypeAlias = tuple[str, int] +SockAddrType: TypeAlias = Union[IPSockAddrType, str] +UDPPacketType: TypeAlias = tuple[bytes, IPSockAddrType] +UNIXDatagramPacketType: TypeAlias = tuple[bytes, str] +T_Retval = TypeVar("T_Retval") + + +def _validate_socket( + sock_or_fd: socket.socket | int, + sock_type: socket.SocketKind, + addr_family: socket.AddressFamily = socket.AF_UNSPEC, + *, + require_connected: bool = False, + require_bound: bool = False, +) -> socket.socket: + if isinstance(sock_or_fd, int): + try: + sock = socket.socket(fileno=sock_or_fd) + except OSError as exc: + if exc.errno == errno.ENOTSOCK: + raise ValueError( + "the file descriptor does not refer to a socket" + ) from exc + elif require_connected: + raise ValueError("the socket must be connected") from exc + elif require_bound: + raise ValueError("the socket must be bound to a local address") from exc + else: + raise + elif isinstance(sock_or_fd, socket.socket): + sock = sock_or_fd + else: + raise TypeError( + f"expected an int or socket, got {type(sock_or_fd).__qualname__} instead" + ) + + try: + if require_connected: + try: + sock.getpeername() + except OSError as exc: + raise ValueError("the socket must be connected") from exc + + if require_bound: + try: + if sock.family in (socket.AF_INET, socket.AF_INET6): + bound_addr = sock.getsockname()[1] + else: + bound_addr = sock.getsockname() + except OSError: + bound_addr = None + + if not bound_addr: + raise ValueError("the socket must be bound to a local address") + + if addr_family != socket.AF_UNSPEC and sock.family != addr_family: + raise ValueError( + f"address family mismatch: expected {addr_family.name}, got " + f"{sock.family.name}" + ) + + if sock.type != sock_type: + raise ValueError( + f"socket type mismatch: expected {sock_type.name}, got {sock.type.name}" + ) + except BaseException: + # Avoid ResourceWarning from the locally constructed socket object + if isinstance(sock_or_fd, int): + sock.detach() + + raise + + sock.setblocking(False) + return sock + + +class SocketAttribute(TypedAttributeSet): + """ + .. attribute:: family + :type: socket.AddressFamily + + the address family of the underlying socket + + .. attribute:: local_address + :type: tuple[str, int] | str + + the local address the underlying socket is connected to + + .. attribute:: local_port + :type: int + + for IP based sockets, the local port the underlying socket is bound to + + .. attribute:: raw_socket + :type: socket.socket + + the underlying stdlib socket object + + .. attribute:: remote_address + :type: tuple[str, int] | str + + the remote address the underlying socket is connected to + + .. attribute:: remote_port + :type: int + + for IP based sockets, the remote port the underlying socket is connected to + """ + + family: AddressFamily = typed_attribute() + local_address: SockAddrType = typed_attribute() + local_port: int = typed_attribute() + raw_socket: socket.socket = typed_attribute() + remote_address: SockAddrType = typed_attribute() + remote_port: int = typed_attribute() + + +class _SocketProvider(TypedAttributeProvider): + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + from .._core._sockets import convert_ipv6_sockaddr as convert + + attributes: dict[Any, Callable[[], Any]] = { + SocketAttribute.family: lambda: self._raw_socket.family, + SocketAttribute.local_address: lambda: convert( + self._raw_socket.getsockname() + ), + SocketAttribute.raw_socket: lambda: self._raw_socket, + } + try: + peername: tuple[str, int] | None = convert(self._raw_socket.getpeername()) + except OSError: + peername = None + + # Provide the remote address for connected sockets + if peername is not None: + attributes[SocketAttribute.remote_address] = lambda: peername + + # Provide local and remote ports for IP based sockets + if self._raw_socket.family in (AddressFamily.AF_INET, AddressFamily.AF_INET6): + attributes[SocketAttribute.local_port] = ( + lambda: self._raw_socket.getsockname()[1] + ) + if peername is not None: + remote_port = peername[1] + attributes[SocketAttribute.remote_port] = lambda: remote_port + + return attributes + + @property + @abstractmethod + def _raw_socket(self) -> socket.socket: + pass + + +class SocketStream(ByteStream, _SocketProvider): + """ + Transports bytes over a socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> SocketStream: + """ + Wrap an existing socket object or file descriptor as a socket stream. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a socket stream + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_STREAM, require_connected=True) + return await get_async_backend().wrap_stream_socket(sock) + + +class UNIXSocketStream(SocketStream): + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> UNIXSocketStream: + """ + Wrap an existing socket object or file descriptor as a UNIX socket stream. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a UNIX socket stream + + """ + sock = _validate_socket( + sock_or_fd, socket.SOCK_STREAM, socket.AF_UNIX, require_connected=True + ) + return await get_async_backend().wrap_unix_stream_socket(sock) + + @abstractmethod + async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: + """ + Send file descriptors along with a message to the peer. + + :param message: a non-empty bytestring + :param fds: a collection of files (either numeric file descriptors or open file + or socket objects) + """ + + @abstractmethod + async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: + """ + Receive file descriptors along with a message from the peer. + + :param msglen: length of the message to expect from the peer + :param maxfds: maximum number of file descriptors to expect from the peer + :return: a tuple of (message, file descriptors) + """ + + +class SocketListener(Listener[SocketStream], _SocketProvider): + """ + Listens to incoming socket connections. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket( + cls, + sock_or_fd: socket.socket | int, + ) -> SocketListener: + """ + Wrap an existing socket object or file descriptor as a socket listener. + + The newly created listener takes ownership of the socket being passed in. + + :param sock_or_fd: a socket object or file descriptor + :return: a socket listener + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_STREAM, require_bound=True) + return await get_async_backend().wrap_listener_socket(sock) + + @abstractmethod + async def accept(self) -> SocketStream: + """Accept an incoming connection.""" + + async def serve( + self, + handler: Callable[[SocketStream], Any], + task_group: TaskGroup | None = None, + ) -> None: + from .. import create_task_group + + async with AsyncExitStack() as stack: + if task_group is None: + task_group = await stack.enter_async_context(create_task_group()) + + while True: + stream = await self.accept() + task_group.start_soon(handler, stream) + + +class UDPSocket(UnreliableObjectStream[UDPPacketType], _SocketProvider): + """ + Represents an unconnected UDP socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> UDPSocket: + """ + Wrap an existing socket object or file descriptor as a UDP socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must be bound to a local address. + + :param sock_or_fd: a socket object or file descriptor + :return: a UDP socket + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_DGRAM, require_bound=True) + return await get_async_backend().wrap_udp_socket(sock) + + async def sendto(self, data: bytes, host: str, port: int) -> None: + """ + Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, (host, port))). + + """ + return await self.send((data, (host, port))) + + +class ConnectedUDPSocket(UnreliableObjectStream[bytes], _SocketProvider): + """ + Represents an connected UDP socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> ConnectedUDPSocket: + """ + Wrap an existing socket object or file descriptor as a connected UDP socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a connected UDP socket + + """ + sock = _validate_socket( + sock_or_fd, + socket.SOCK_DGRAM, + require_connected=True, + ) + return await get_async_backend().wrap_connected_udp_socket(sock) + + +class UNIXDatagramSocket( + UnreliableObjectStream[UNIXDatagramPacketType], _SocketProvider +): + """ + Represents an unconnected Unix datagram socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket( + cls, + sock_or_fd: socket.socket | int, + ) -> UNIXDatagramSocket: + """ + Wrap an existing socket object or file descriptor as a UNIX datagram + socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + + :param sock_or_fd: a socket object or file descriptor + :return: a UNIX datagram socket + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_DGRAM, socket.AF_UNIX) + return await get_async_backend().wrap_unix_datagram_socket(sock) + + async def sendto(self, data: bytes, path: str) -> None: + """Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, path)).""" + return await self.send((data, path)) + + +class ConnectedUNIXDatagramSocket(UnreliableObjectStream[bytes], _SocketProvider): + """ + Represents a connected Unix datagram socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket( + cls, + sock_or_fd: socket.socket | int, + ) -> ConnectedUNIXDatagramSocket: + """ + Wrap an existing socket object or file descriptor as a connected UNIX datagram + socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a connected UNIX datagram socket + + """ + sock = _validate_socket( + sock_or_fd, socket.SOCK_DGRAM, socket.AF_UNIX, require_connected=True + ) + return await get_async_backend().wrap_connected_unix_datagram_socket(sock) diff --git a/venv/lib/python3.10/site-packages/anyio/abc/_streams.py b/venv/lib/python3.10/site-packages/anyio/abc/_streams.py new file mode 100644 index 0000000000000000000000000000000000000000..369df3f36cda74aa0d0893cd98bd4b29d3786faa --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/abc/_streams.py @@ -0,0 +1,239 @@ +from __future__ import annotations + +import sys +from abc import ABCMeta, abstractmethod +from collections.abc import Callable +from typing import Any, Generic, TypeVar, Union + +from .._core._exceptions import EndOfStream +from .._core._typedattr import TypedAttributeProvider +from ._resources import AsyncResource +from ._tasks import TaskGroup + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +T_Item = TypeVar("T_Item") +T_co = TypeVar("T_co", covariant=True) +T_contra = TypeVar("T_contra", contravariant=True) + + +class UnreliableObjectReceiveStream( + Generic[T_co], AsyncResource, TypedAttributeProvider +): + """ + An interface for receiving objects. + + This interface makes no guarantees that the received messages arrive in the order in + which they were sent, or that no messages are missed. + + Asynchronously iterating over objects of this type will yield objects matching the + given type parameter. + """ + + def __aiter__(self) -> UnreliableObjectReceiveStream[T_co]: + return self + + async def __anext__(self) -> T_co: + try: + return await self.receive() + except EndOfStream: + raise StopAsyncIteration from None + + @abstractmethod + async def receive(self) -> T_co: + """ + Receive the next item. + + :raises ~anyio.ClosedResourceError: if the receive stream has been explicitly + closed + :raises ~anyio.EndOfStream: if this stream has been closed from the other end + :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable + due to external causes + """ + + +class UnreliableObjectSendStream( + Generic[T_contra], AsyncResource, TypedAttributeProvider +): + """ + An interface for sending objects. + + This interface makes no guarantees that the messages sent will reach the + recipient(s) in the same order in which they were sent, or at all. + """ + + @abstractmethod + async def send(self, item: T_contra) -> None: + """ + Send an item to the peer(s). + + :param item: the item to send + :raises ~anyio.ClosedResourceError: if the send stream has been explicitly + closed + :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable + due to external causes + """ + + +class UnreliableObjectStream( + UnreliableObjectReceiveStream[T_Item], UnreliableObjectSendStream[T_Item] +): + """ + A bidirectional message stream which does not guarantee the order or reliability of + message delivery. + """ + + +class ObjectReceiveStream(UnreliableObjectReceiveStream[T_co]): + """ + A receive message stream which guarantees that messages are received in the same + order in which they were sent, and that no messages are missed. + """ + + +class ObjectSendStream(UnreliableObjectSendStream[T_contra]): + """ + A send message stream which guarantees that messages are delivered in the same order + in which they were sent, without missing any messages in the middle. + """ + + +class ObjectStream( + ObjectReceiveStream[T_Item], + ObjectSendStream[T_Item], + UnreliableObjectStream[T_Item], +): + """ + A bidirectional message stream which guarantees the order and reliability of message + delivery. + """ + + @abstractmethod + async def send_eof(self) -> None: + """ + Send an end-of-file indication to the peer. + + You should not try to send any further data to this stream after calling this + method. This method is idempotent (does nothing on successive calls). + """ + + +class ByteReceiveStream(AsyncResource, TypedAttributeProvider): + """ + An interface for receiving bytes from a single peer. + + Iterating this byte stream will yield a byte string of arbitrary length, but no more + than 65536 bytes. + """ + + def __aiter__(self) -> ByteReceiveStream: + return self + + async def __anext__(self) -> bytes: + try: + return await self.receive() + except EndOfStream: + raise StopAsyncIteration from None + + @abstractmethod + async def receive(self, max_bytes: int = 65536) -> bytes: + """ + Receive at most ``max_bytes`` bytes from the peer. + + .. note:: Implementers of this interface should not return an empty + :class:`bytes` object, and users should ignore them. + + :param max_bytes: maximum number of bytes to receive + :return: the received bytes + :raises ~anyio.EndOfStream: if this stream has been closed from the other end + """ + + +class ByteSendStream(AsyncResource, TypedAttributeProvider): + """An interface for sending bytes to a single peer.""" + + @abstractmethod + async def send(self, item: bytes) -> None: + """ + Send the given bytes to the peer. + + :param item: the bytes to send + """ + + +class ByteStream(ByteReceiveStream, ByteSendStream): + """A bidirectional byte stream.""" + + @abstractmethod + async def send_eof(self) -> None: + """ + Send an end-of-file indication to the peer. + + You should not try to send any further data to this stream after calling this + method. This method is idempotent (does nothing on successive calls). + """ + + +#: Type alias for all unreliable bytes-oriented receive streams. +AnyUnreliableByteReceiveStream: TypeAlias = Union[ + UnreliableObjectReceiveStream[bytes], ByteReceiveStream +] +#: Type alias for all unreliable bytes-oriented send streams. +AnyUnreliableByteSendStream: TypeAlias = Union[ + UnreliableObjectSendStream[bytes], ByteSendStream +] +#: Type alias for all unreliable bytes-oriented streams. +AnyUnreliableByteStream: TypeAlias = Union[UnreliableObjectStream[bytes], ByteStream] +#: Type alias for all bytes-oriented receive streams. +AnyByteReceiveStream: TypeAlias = Union[ObjectReceiveStream[bytes], ByteReceiveStream] +#: Type alias for all bytes-oriented send streams. +AnyByteSendStream: TypeAlias = Union[ObjectSendStream[bytes], ByteSendStream] +#: Type alias for all bytes-oriented streams. +AnyByteStream: TypeAlias = Union[ObjectStream[bytes], ByteStream] + + +class Listener(Generic[T_co], AsyncResource, TypedAttributeProvider): + """An interface for objects that let you accept incoming connections.""" + + @abstractmethod + async def serve( + self, handler: Callable[[T_co], Any], task_group: TaskGroup | None = None + ) -> None: + """ + Accept incoming connections as they come in and start tasks to handle them. + + :param handler: a callable that will be used to handle each accepted connection + :param task_group: the task group that will be used to start tasks for handling + each accepted connection (if omitted, an ad-hoc task group will be created) + """ + + +class ObjectStreamConnectable(Generic[T_co], metaclass=ABCMeta): + @abstractmethod + async def connect(self) -> ObjectStream[T_co]: + """ + Connect to the remote endpoint. + + :return: an object stream connected to the remote end + :raises ConnectionFailed: if the connection fails + """ + + +class ByteStreamConnectable(metaclass=ABCMeta): + @abstractmethod + async def connect(self) -> ByteStream: + """ + Connect to the remote endpoint. + + :return: a bytestream connected to the remote end + :raises ConnectionFailed: if the connection fails + """ + + +#: Type alias for all connectables returning bytestreams or bytes-oriented object streams +AnyByteStreamConnectable: TypeAlias = Union[ + ObjectStreamConnectable[bytes], ByteStreamConnectable +] diff --git a/venv/lib/python3.10/site-packages/anyio/abc/_subprocesses.py b/venv/lib/python3.10/site-packages/anyio/abc/_subprocesses.py new file mode 100644 index 0000000000000000000000000000000000000000..ce0564ceac8aac425675b5c8f7f7205d08061fd3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/abc/_subprocesses.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +from abc import abstractmethod +from signal import Signals + +from ._resources import AsyncResource +from ._streams import ByteReceiveStream, ByteSendStream + + +class Process(AsyncResource): + """An asynchronous version of :class:`subprocess.Popen`.""" + + @abstractmethod + async def wait(self) -> int: + """ + Wait until the process exits. + + :return: the exit code of the process + """ + + @abstractmethod + def terminate(self) -> None: + """ + Terminates the process, gracefully if possible. + + On Windows, this calls ``TerminateProcess()``. + On POSIX systems, this sends ``SIGTERM`` to the process. + + .. seealso:: :meth:`subprocess.Popen.terminate` + """ + + @abstractmethod + def kill(self) -> None: + """ + Kills the process. + + On Windows, this calls ``TerminateProcess()``. + On POSIX systems, this sends ``SIGKILL`` to the process. + + .. seealso:: :meth:`subprocess.Popen.kill` + """ + + @abstractmethod + def send_signal(self, signal: Signals) -> None: + """ + Send a signal to the subprocess. + + .. seealso:: :meth:`subprocess.Popen.send_signal` + + :param signal: the signal number (e.g. :data:`signal.SIGHUP`) + """ + + @property + @abstractmethod + def pid(self) -> int: + """The process ID of the process.""" + + @property + @abstractmethod + def returncode(self) -> int | None: + """ + The return code of the process. If the process has not yet terminated, this will + be ``None``. + """ + + @property + @abstractmethod + def stdin(self) -> ByteSendStream | None: + """The stream for the standard input of the process.""" + + @property + @abstractmethod + def stdout(self) -> ByteReceiveStream | None: + """The stream for the standard output of the process.""" + + @property + @abstractmethod + def stderr(self) -> ByteReceiveStream | None: + """The stream for the standard error output of the process.""" diff --git a/venv/lib/python3.10/site-packages/anyio/abc/_tasks.py b/venv/lib/python3.10/site-packages/anyio/abc/_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..b4ebff9edfeaabf26396fa944752407f6ddefd7e --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/abc/_tasks.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +import sys +from abc import ABCMeta, abstractmethod +from collections.abc import Awaitable, Callable +from types import TracebackType +from typing import TYPE_CHECKING, Any, Protocol, TypeVar, overload + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if TYPE_CHECKING: + from .._core._tasks import CancelScope + +T_Retval = TypeVar("T_Retval") +T_contra = TypeVar("T_contra", contravariant=True) +PosArgsT = TypeVarTuple("PosArgsT") + + +class TaskStatus(Protocol[T_contra]): + @overload + def started(self: TaskStatus[None]) -> None: ... + + @overload + def started(self, value: T_contra) -> None: ... + + def started(self, value: T_contra | None = None) -> None: + """ + Signal that the task has started. + + :param value: object passed back to the starter of the task + """ + + +class TaskGroup(metaclass=ABCMeta): + """ + Groups several asynchronous tasks together. + + :ivar cancel_scope: the cancel scope inherited by all child tasks + :vartype cancel_scope: CancelScope + + .. note:: On asyncio, support for eager task factories is considered to be + **experimental**. In particular, they don't follow the usual semantics of new + tasks being scheduled on the next iteration of the event loop, and may thus + cause unexpected behavior in code that wasn't written with such semantics in + mind. + """ + + cancel_scope: CancelScope + + @abstractmethod + def start_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], + *args: Unpack[PosArgsT], + name: object = None, + ) -> None: + """ + Start a new task in this task group. + + :param func: a coroutine function + :param args: positional arguments to call the function with + :param name: name of the task, for the purposes of introspection and debugging + + .. versionadded:: 3.0 + """ + + @abstractmethod + async def start( + self, + func: Callable[..., Awaitable[Any]], + *args: object, + name: object = None, + ) -> Any: + """ + Start a new task and wait until it signals for readiness. + + The target callable must accept a keyword argument ``task_status`` (of type + :class:`TaskStatus`). Awaiting on this method will return whatever was passed to + ``task_status.started()`` (``None`` by default). + + .. note:: The :class:`TaskStatus` class is generic, and the type argument should + indicate the type of the value that will be passed to + ``task_status.started()``. + + :param func: a coroutine function that accepts the ``task_status`` keyword + argument + :param args: positional arguments to call the function with + :param name: an optional name for the task, for introspection and debugging + :return: the value passed to ``task_status.started()`` + :raises RuntimeError: if the task finishes without calling + ``task_status.started()`` + + .. seealso:: :ref:`start_initialize` + + .. versionadded:: 3.0 + """ + + @abstractmethod + async def __aenter__(self) -> TaskGroup: + """Enter the task group context and allow starting new tasks.""" + + @abstractmethod + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + """Exit the task group context waiting for all tasks to finish.""" diff --git a/venv/lib/python3.10/site-packages/anyio/abc/_testing.py b/venv/lib/python3.10/site-packages/anyio/abc/_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..7c50ed76dc4d8df41262973a0122295523e2a935 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/abc/_testing.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import types +from abc import ABCMeta, abstractmethod +from collections.abc import AsyncGenerator, Callable, Coroutine, Iterable +from typing import Any, TypeVar + +_T = TypeVar("_T") + + +class TestRunner(metaclass=ABCMeta): + """ + Encapsulates a running event loop. Every call made through this object will use the + same event loop. + """ + + def __enter__(self) -> TestRunner: + return self + + @abstractmethod + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> bool | None: ... + + @abstractmethod + def run_asyncgen_fixture( + self, + fixture_func: Callable[..., AsyncGenerator[_T, Any]], + kwargs: dict[str, Any], + ) -> Iterable[_T]: + """ + Run an async generator fixture. + + :param fixture_func: the fixture function + :param kwargs: keyword arguments to call the fixture function with + :return: an iterator yielding the value yielded from the async generator + """ + + @abstractmethod + def run_fixture( + self, + fixture_func: Callable[..., Coroutine[Any, Any, _T]], + kwargs: dict[str, Any], + ) -> _T: + """ + Run an async fixture. + + :param fixture_func: the fixture function + :param kwargs: keyword arguments to call the fixture function with + :return: the return value of the fixture function + """ + + @abstractmethod + def run_test( + self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] + ) -> None: + """ + Run an async test function. + + :param test_func: the test function + :param kwargs: keyword arguments to call the test function with + """ diff --git a/venv/lib/python3.10/site-packages/anyio/from_thread.py b/venv/lib/python3.10/site-packages/anyio/from_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..288a0871fe6945076ca5ed1ad0c5bd5cf86ac4d6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/from_thread.py @@ -0,0 +1,535 @@ +from __future__ import annotations + +import sys +from collections.abc import Awaitable, Callable, Generator +from concurrent.futures import Future +from contextlib import ( + AbstractAsyncContextManager, + AbstractContextManager, + contextmanager, +) +from dataclasses import dataclass, field +from inspect import isawaitable +from threading import Lock, Thread, current_thread, get_ident +from types import TracebackType +from typing import ( + Any, + Generic, + TypeVar, + cast, + overload, +) + +from ._core import _eventloop +from ._core._eventloop import get_async_backend, get_cancelled_exc_class, threadlocals +from ._core._synchronization import Event +from ._core._tasks import CancelScope, create_task_group +from .abc import AsyncBackend +from .abc._tasks import TaskStatus + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +T_Retval = TypeVar("T_Retval") +T_co = TypeVar("T_co", covariant=True) +PosArgsT = TypeVarTuple("PosArgsT") + + +def run( + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], *args: Unpack[PosArgsT] +) -> T_Retval: + """ + Call a coroutine function from a worker thread. + + :param func: a coroutine function + :param args: positional arguments for the callable + :return: the return value of the coroutine function + + """ + try: + async_backend = threadlocals.current_async_backend + token = threadlocals.current_token + except AttributeError: + raise RuntimeError( + "This function can only be run from an AnyIO worker thread" + ) from None + + return async_backend.run_async_from_thread(func, args, token=token) + + +def run_sync( + func: Callable[[Unpack[PosArgsT]], T_Retval], *args: Unpack[PosArgsT] +) -> T_Retval: + """ + Call a function in the event loop thread from a worker thread. + + :param func: a callable + :param args: positional arguments for the callable + :return: the return value of the callable + + """ + try: + async_backend = threadlocals.current_async_backend + token = threadlocals.current_token + except AttributeError: + raise RuntimeError( + "This function can only be run from an AnyIO worker thread" + ) from None + + return async_backend.run_sync_from_thread(func, args, token=token) + + +class _BlockingAsyncContextManager(Generic[T_co], AbstractContextManager): + _enter_future: Future[T_co] + _exit_future: Future[bool | None] + _exit_event: Event + _exit_exc_info: tuple[ + type[BaseException] | None, BaseException | None, TracebackType | None + ] = (None, None, None) + + def __init__( + self, async_cm: AbstractAsyncContextManager[T_co], portal: BlockingPortal + ): + self._async_cm = async_cm + self._portal = portal + + async def run_async_cm(self) -> bool | None: + try: + self._exit_event = Event() + value = await self._async_cm.__aenter__() + except BaseException as exc: + self._enter_future.set_exception(exc) + raise + else: + self._enter_future.set_result(value) + + try: + # Wait for the sync context manager to exit. + # This next statement can raise `get_cancelled_exc_class()` if + # something went wrong in a task group in this async context + # manager. + await self._exit_event.wait() + finally: + # In case of cancellation, it could be that we end up here before + # `_BlockingAsyncContextManager.__exit__` is called, and an + # `_exit_exc_info` has been set. + result = await self._async_cm.__aexit__(*self._exit_exc_info) + + return result + + def __enter__(self) -> T_co: + self._enter_future = Future() + self._exit_future = self._portal.start_task_soon(self.run_async_cm) + return self._enter_future.result() + + def __exit__( + self, + __exc_type: type[BaseException] | None, + __exc_value: BaseException | None, + __traceback: TracebackType | None, + ) -> bool | None: + self._exit_exc_info = __exc_type, __exc_value, __traceback + self._portal.call(self._exit_event.set) + return self._exit_future.result() + + +class _BlockingPortalTaskStatus(TaskStatus): + def __init__(self, future: Future): + self._future = future + + def started(self, value: object = None) -> None: + self._future.set_result(value) + + +class BlockingPortal: + """An object that lets external threads run code in an asynchronous event loop.""" + + def __new__(cls) -> BlockingPortal: + return get_async_backend().create_blocking_portal() + + def __init__(self) -> None: + self._event_loop_thread_id: int | None = get_ident() + self._stop_event = Event() + self._task_group = create_task_group() + self._cancelled_exc_class = get_cancelled_exc_class() + + async def __aenter__(self) -> BlockingPortal: + await self._task_group.__aenter__() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + await self.stop() + return await self._task_group.__aexit__(exc_type, exc_val, exc_tb) + + def _check_running(self) -> None: + if self._event_loop_thread_id is None: + raise RuntimeError("This portal is not running") + if self._event_loop_thread_id == get_ident(): + raise RuntimeError( + "This method cannot be called from the event loop thread" + ) + + async def sleep_until_stopped(self) -> None: + """Sleep until :meth:`stop` is called.""" + await self._stop_event.wait() + + async def stop(self, cancel_remaining: bool = False) -> None: + """ + Signal the portal to shut down. + + This marks the portal as no longer accepting new calls and exits from + :meth:`sleep_until_stopped`. + + :param cancel_remaining: ``True`` to cancel all the remaining tasks, ``False`` + to let them finish before returning + + """ + self._event_loop_thread_id = None + self._stop_event.set() + if cancel_remaining: + self._task_group.cancel_scope.cancel() + + async def _call_func( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + future: Future[T_Retval], + ) -> None: + def callback(f: Future[T_Retval]) -> None: + if f.cancelled() and self._event_loop_thread_id not in ( + None, + get_ident(), + ): + self.call(scope.cancel) + + try: + retval_or_awaitable = func(*args, **kwargs) + if isawaitable(retval_or_awaitable): + with CancelScope() as scope: + if future.cancelled(): + scope.cancel() + else: + future.add_done_callback(callback) + + retval = await retval_or_awaitable + else: + retval = retval_or_awaitable + except self._cancelled_exc_class: + future.cancel() + future.set_running_or_notify_cancel() + except BaseException as exc: + if not future.cancelled(): + future.set_exception(exc) + + # Let base exceptions fall through + if not isinstance(exc, Exception): + raise + else: + if not future.cancelled(): + future.set_result(retval) + finally: + scope = None # type: ignore[assignment] + + def _spawn_task_from_thread( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + name: object, + future: Future[T_Retval], + ) -> None: + """ + Spawn a new task using the given callable. + + Implementers must ensure that the future is resolved when the task finishes. + + :param func: a callable + :param args: positional arguments to be passed to the callable + :param kwargs: keyword arguments to be passed to the callable + :param name: name of the task (will be coerced to a string if not ``None``) + :param future: a future that will resolve to the return value of the callable, + or the exception raised during its execution + + """ + raise NotImplementedError + + @overload + def call( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + *args: Unpack[PosArgsT], + ) -> T_Retval: ... + + @overload + def call( + self, func: Callable[[Unpack[PosArgsT]], T_Retval], *args: Unpack[PosArgsT] + ) -> T_Retval: ... + + def call( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + *args: Unpack[PosArgsT], + ) -> T_Retval: + """ + Call the given function in the event loop thread. + + If the callable returns a coroutine object, it is awaited on. + + :param func: any callable + :raises RuntimeError: if the portal is not running or if this method is called + from within the event loop thread + + """ + return cast(T_Retval, self.start_task_soon(func, *args).result()) + + @overload + def start_task_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + *args: Unpack[PosArgsT], + name: object = None, + ) -> Future[T_Retval]: ... + + @overload + def start_task_soon( + self, + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + name: object = None, + ) -> Future[T_Retval]: ... + + def start_task_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + *args: Unpack[PosArgsT], + name: object = None, + ) -> Future[T_Retval]: + """ + Start a task in the portal's task group. + + The task will be run inside a cancel scope which can be cancelled by cancelling + the returned future. + + :param func: the target function + :param args: positional arguments passed to ``func`` + :param name: name of the task (will be coerced to a string if not ``None``) + :return: a future that resolves with the return value of the callable if the + task completes successfully, or with the exception raised in the task + :raises RuntimeError: if the portal is not running or if this method is called + from within the event loop thread + :rtype: concurrent.futures.Future[T_Retval] + + .. versionadded:: 3.0 + + """ + self._check_running() + f: Future[T_Retval] = Future() + self._spawn_task_from_thread(func, args, {}, name, f) + return f + + def start_task( + self, + func: Callable[..., Awaitable[T_Retval]], + *args: object, + name: object = None, + ) -> tuple[Future[T_Retval], Any]: + """ + Start a task in the portal's task group and wait until it signals for readiness. + + This method works the same way as :meth:`.abc.TaskGroup.start`. + + :param func: the target function + :param args: positional arguments passed to ``func`` + :param name: name of the task (will be coerced to a string if not ``None``) + :return: a tuple of (future, task_status_value) where the ``task_status_value`` + is the value passed to ``task_status.started()`` from within the target + function + :rtype: tuple[concurrent.futures.Future[T_Retval], Any] + + .. versionadded:: 3.0 + + """ + + def task_done(future: Future[T_Retval]) -> None: + if not task_status_future.done(): + if future.cancelled(): + task_status_future.cancel() + elif future.exception(): + task_status_future.set_exception(future.exception()) + else: + exc = RuntimeError( + "Task exited without calling task_status.started()" + ) + task_status_future.set_exception(exc) + + self._check_running() + task_status_future: Future = Future() + task_status = _BlockingPortalTaskStatus(task_status_future) + f: Future = Future() + f.add_done_callback(task_done) + self._spawn_task_from_thread(func, args, {"task_status": task_status}, name, f) + return f, task_status_future.result() + + def wrap_async_context_manager( + self, cm: AbstractAsyncContextManager[T_co] + ) -> AbstractContextManager[T_co]: + """ + Wrap an async context manager as a synchronous context manager via this portal. + + Spawns a task that will call both ``__aenter__()`` and ``__aexit__()``, stopping + in the middle until the synchronous context manager exits. + + :param cm: an asynchronous context manager + :return: a synchronous context manager + + .. versionadded:: 2.1 + + """ + return _BlockingAsyncContextManager(cm, self) + + +@dataclass +class BlockingPortalProvider: + """ + A manager for a blocking portal. Used as a context manager. The first thread to + enter this context manager causes a blocking portal to be started with the specific + parameters, and the last thread to exit causes the portal to be shut down. Thus, + there will be exactly one blocking portal running in this context as long as at + least one thread has entered this context manager. + + The parameters are the same as for :func:`~anyio.run`. + + :param backend: name of the backend + :param backend_options: backend options + + .. versionadded:: 4.4 + """ + + backend: str = "asyncio" + backend_options: dict[str, Any] | None = None + _lock: Lock = field(init=False, default_factory=Lock) + _leases: int = field(init=False, default=0) + _portal: BlockingPortal = field(init=False) + _portal_cm: AbstractContextManager[BlockingPortal] | None = field( + init=False, default=None + ) + + def __enter__(self) -> BlockingPortal: + with self._lock: + if self._portal_cm is None: + self._portal_cm = start_blocking_portal( + self.backend, self.backend_options + ) + self._portal = self._portal_cm.__enter__() + + self._leases += 1 + return self._portal + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + portal_cm: AbstractContextManager[BlockingPortal] | None = None + with self._lock: + assert self._portal_cm + assert self._leases > 0 + self._leases -= 1 + if not self._leases: + portal_cm = self._portal_cm + self._portal_cm = None + del self._portal + + if portal_cm: + portal_cm.__exit__(None, None, None) + + +@contextmanager +def start_blocking_portal( + backend: str = "asyncio", + backend_options: dict[str, Any] | None = None, + *, + name: str | None = None, +) -> Generator[BlockingPortal, Any, None]: + """ + Start a new event loop in a new thread and run a blocking portal in its main task. + + The parameters are the same as for :func:`~anyio.run`. + + :param backend: name of the backend + :param backend_options: backend options + :param name: name of the thread + :return: a context manager that yields a blocking portal + + .. versionchanged:: 3.0 + Usage as a context manager is now required. + + """ + + async def run_portal() -> None: + async with BlockingPortal() as portal_: + if name is None: + current_thread().name = f"{backend}-portal-{id(portal_):x}" + + future.set_result(portal_) + await portal_.sleep_until_stopped() + + def run_blocking_portal() -> None: + if future.set_running_or_notify_cancel(): + try: + _eventloop.run( + run_portal, backend=backend, backend_options=backend_options + ) + except BaseException as exc: + if not future.done(): + future.set_exception(exc) + + future: Future[BlockingPortal] = Future() + thread = Thread(target=run_blocking_portal, daemon=True, name=name) + thread.start() + try: + cancel_remaining_tasks = False + portal = future.result() + try: + yield portal + except BaseException: + cancel_remaining_tasks = True + raise + finally: + try: + portal.call(portal.stop, cancel_remaining_tasks) + except RuntimeError: + pass + finally: + thread.join() + + +def check_cancelled() -> None: + """ + Check if the cancel scope of the host task's running the current worker thread has + been cancelled. + + If the host task's current cancel scope has indeed been cancelled, the + backend-specific cancellation exception will be raised. + + :raises RuntimeError: if the current thread was not spawned by + :func:`.to_thread.run_sync` + + """ + try: + async_backend: AsyncBackend = threadlocals.current_async_backend + except AttributeError: + raise RuntimeError( + "This function can only be run from an AnyIO worker thread" + ) from None + + async_backend.check_cancelled() diff --git a/venv/lib/python3.10/site-packages/anyio/lowlevel.py b/venv/lib/python3.10/site-packages/anyio/lowlevel.py new file mode 100644 index 0000000000000000000000000000000000000000..a3f6f0173a58861a33854e4e47ef6ab39a2e1304 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/lowlevel.py @@ -0,0 +1,161 @@ +from __future__ import annotations + +import enum +from dataclasses import dataclass +from typing import Any, Generic, Literal, TypeVar, overload +from weakref import WeakKeyDictionary + +from ._core._eventloop import get_async_backend + +T = TypeVar("T") +D = TypeVar("D") + + +async def checkpoint() -> None: + """ + Check for cancellation and allow the scheduler to switch to another task. + + Equivalent to (but more efficient than):: + + await checkpoint_if_cancelled() + await cancel_shielded_checkpoint() + + + .. versionadded:: 3.0 + + """ + await get_async_backend().checkpoint() + + +async def checkpoint_if_cancelled() -> None: + """ + Enter a checkpoint if the enclosing cancel scope has been cancelled. + + This does not allow the scheduler to switch to a different task. + + .. versionadded:: 3.0 + + """ + await get_async_backend().checkpoint_if_cancelled() + + +async def cancel_shielded_checkpoint() -> None: + """ + Allow the scheduler to switch to another task but without checking for cancellation. + + Equivalent to (but potentially more efficient than):: + + with CancelScope(shield=True): + await checkpoint() + + + .. versionadded:: 3.0 + + """ + await get_async_backend().cancel_shielded_checkpoint() + + +def current_token() -> object: + """ + Return a backend specific token object that can be used to get back to the event + loop. + + """ + return get_async_backend().current_token() + + +_run_vars: WeakKeyDictionary[Any, dict[RunVar[Any], Any]] = WeakKeyDictionary() +_token_wrappers: dict[Any, _TokenWrapper] = {} + + +@dataclass(frozen=True) +class _TokenWrapper: + __slots__ = "_token", "__weakref__" + _token: object + + +class _NoValueSet(enum.Enum): + NO_VALUE_SET = enum.auto() + + +class RunvarToken(Generic[T]): + __slots__ = "_var", "_value", "_redeemed" + + def __init__(self, var: RunVar[T], value: T | Literal[_NoValueSet.NO_VALUE_SET]): + self._var = var + self._value: T | Literal[_NoValueSet.NO_VALUE_SET] = value + self._redeemed = False + + +class RunVar(Generic[T]): + """ + Like a :class:`~contextvars.ContextVar`, except scoped to the running event loop. + """ + + __slots__ = "_name", "_default" + + NO_VALUE_SET: Literal[_NoValueSet.NO_VALUE_SET] = _NoValueSet.NO_VALUE_SET + + _token_wrappers: set[_TokenWrapper] = set() + + def __init__( + self, name: str, default: T | Literal[_NoValueSet.NO_VALUE_SET] = NO_VALUE_SET + ): + self._name = name + self._default = default + + @property + def _current_vars(self) -> dict[RunVar[T], T]: + token = current_token() + try: + return _run_vars[token] + except KeyError: + run_vars = _run_vars[token] = {} + return run_vars + + @overload + def get(self, default: D) -> T | D: ... + + @overload + def get(self) -> T: ... + + def get( + self, default: D | Literal[_NoValueSet.NO_VALUE_SET] = NO_VALUE_SET + ) -> T | D: + try: + return self._current_vars[self] + except KeyError: + if default is not RunVar.NO_VALUE_SET: + return default + elif self._default is not RunVar.NO_VALUE_SET: + return self._default + + raise LookupError( + f'Run variable "{self._name}" has no value and no default set' + ) + + def set(self, value: T) -> RunvarToken[T]: + current_vars = self._current_vars + token = RunvarToken(self, current_vars.get(self, RunVar.NO_VALUE_SET)) + current_vars[self] = value + return token + + def reset(self, token: RunvarToken[T]) -> None: + if token._var is not self: + raise ValueError("This token does not belong to this RunVar") + + if token._redeemed: + raise ValueError("This token has already been used") + + if token._value is _NoValueSet.NO_VALUE_SET: + try: + del self._current_vars[self] + except KeyError: + pass + else: + self._current_vars[self] = token._value + + token._redeemed = True + + def __repr__(self) -> str: + return f"" diff --git a/venv/lib/python3.10/site-packages/anyio/py.typed b/venv/lib/python3.10/site-packages/anyio/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/anyio/pytest_plugin.py b/venv/lib/python3.10/site-packages/anyio/pytest_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..21e4ab2285771f30ae33e93a05636040c16035d1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/pytest_plugin.py @@ -0,0 +1,272 @@ +from __future__ import annotations + +import socket +import sys +from collections.abc import Callable, Generator, Iterator +from contextlib import ExitStack, contextmanager +from inspect import isasyncgenfunction, iscoroutinefunction, ismethod +from typing import Any, cast + +import pytest +import sniffio +from _pytest.fixtures import SubRequest +from _pytest.outcomes import Exit + +from ._core._eventloop import get_all_backends, get_async_backend +from ._core._exceptions import iterate_exceptions +from .abc import TestRunner + +if sys.version_info < (3, 11): + from exceptiongroup import ExceptionGroup + +_current_runner: TestRunner | None = None +_runner_stack: ExitStack | None = None +_runner_leases = 0 + + +def extract_backend_and_options(backend: object) -> tuple[str, dict[str, Any]]: + if isinstance(backend, str): + return backend, {} + elif isinstance(backend, tuple) and len(backend) == 2: + if isinstance(backend[0], str) and isinstance(backend[1], dict): + return cast(tuple[str, dict[str, Any]], backend) + + raise TypeError("anyio_backend must be either a string or tuple of (string, dict)") + + +@contextmanager +def get_runner( + backend_name: str, backend_options: dict[str, Any] +) -> Iterator[TestRunner]: + global _current_runner, _runner_leases, _runner_stack + if _current_runner is None: + asynclib = get_async_backend(backend_name) + _runner_stack = ExitStack() + if sniffio.current_async_library_cvar.get(None) is None: + # Since we're in control of the event loop, we can cache the name of the + # async library + token = sniffio.current_async_library_cvar.set(backend_name) + _runner_stack.callback(sniffio.current_async_library_cvar.reset, token) + + backend_options = backend_options or {} + _current_runner = _runner_stack.enter_context( + asynclib.create_test_runner(backend_options) + ) + + _runner_leases += 1 + try: + yield _current_runner + finally: + _runner_leases -= 1 + if not _runner_leases: + assert _runner_stack is not None + _runner_stack.close() + _runner_stack = _current_runner = None + + +def pytest_configure(config: Any) -> None: + config.addinivalue_line( + "markers", + "anyio: mark the (coroutine function) test to be run asynchronously via anyio.", + ) + + +@pytest.hookimpl(hookwrapper=True) +def pytest_fixture_setup(fixturedef: Any, request: Any) -> Generator[Any]: + def wrapper( + *args: Any, anyio_backend: Any, request: SubRequest, **kwargs: Any + ) -> Any: + # Rebind any fixture methods to the request instance + if ( + request.instance + and ismethod(func) + and type(func.__self__) is type(request.instance) + ): + local_func = func.__func__.__get__(request.instance) + else: + local_func = func + + backend_name, backend_options = extract_backend_and_options(anyio_backend) + if has_backend_arg: + kwargs["anyio_backend"] = anyio_backend + + if has_request_arg: + kwargs["request"] = request + + with get_runner(backend_name, backend_options) as runner: + if isasyncgenfunction(local_func): + yield from runner.run_asyncgen_fixture(local_func, kwargs) + else: + yield runner.run_fixture(local_func, kwargs) + + # Only apply this to coroutine functions and async generator functions in requests + # that involve the anyio_backend fixture + func = fixturedef.func + if isasyncgenfunction(func) or iscoroutinefunction(func): + if "anyio_backend" in request.fixturenames: + fixturedef.func = wrapper + original_argname = fixturedef.argnames + + if not (has_backend_arg := "anyio_backend" in fixturedef.argnames): + fixturedef.argnames += ("anyio_backend",) + + if not (has_request_arg := "request" in fixturedef.argnames): + fixturedef.argnames += ("request",) + + try: + return (yield) + finally: + fixturedef.func = func + fixturedef.argnames = original_argname + + return (yield) + + +@pytest.hookimpl(tryfirst=True) +def pytest_pycollect_makeitem(collector: Any, name: Any, obj: Any) -> None: + if collector.istestfunction(obj, name): + inner_func = obj.hypothesis.inner_test if hasattr(obj, "hypothesis") else obj + if iscoroutinefunction(inner_func): + marker = collector.get_closest_marker("anyio") + own_markers = getattr(obj, "pytestmark", ()) + if marker or any(marker.name == "anyio" for marker in own_markers): + pytest.mark.usefixtures("anyio_backend")(obj) + + +@pytest.hookimpl(tryfirst=True) +def pytest_pyfunc_call(pyfuncitem: Any) -> bool | None: + def run_with_hypothesis(**kwargs: Any) -> None: + with get_runner(backend_name, backend_options) as runner: + runner.run_test(original_func, kwargs) + + backend = pyfuncitem.funcargs.get("anyio_backend") + if backend: + backend_name, backend_options = extract_backend_and_options(backend) + + if hasattr(pyfuncitem.obj, "hypothesis"): + # Wrap the inner test function unless it's already wrapped + original_func = pyfuncitem.obj.hypothesis.inner_test + if original_func.__qualname__ != run_with_hypothesis.__qualname__: + if iscoroutinefunction(original_func): + pyfuncitem.obj.hypothesis.inner_test = run_with_hypothesis + + return None + + if iscoroutinefunction(pyfuncitem.obj): + funcargs = pyfuncitem.funcargs + testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames} + with get_runner(backend_name, backend_options) as runner: + try: + runner.run_test(pyfuncitem.obj, testargs) + except ExceptionGroup as excgrp: + for exc in iterate_exceptions(excgrp): + if isinstance(exc, (Exit, KeyboardInterrupt, SystemExit)): + raise exc from excgrp + + raise + + return True + + return None + + +@pytest.fixture(scope="module", params=get_all_backends()) +def anyio_backend(request: Any) -> Any: + return request.param + + +@pytest.fixture +def anyio_backend_name(anyio_backend: Any) -> str: + if isinstance(anyio_backend, str): + return anyio_backend + else: + return anyio_backend[0] + + +@pytest.fixture +def anyio_backend_options(anyio_backend: Any) -> dict[str, Any]: + if isinstance(anyio_backend, str): + return {} + else: + return anyio_backend[1] + + +class FreePortFactory: + """ + Manages port generation based on specified socket kind, ensuring no duplicate + ports are generated. + + This class provides functionality for generating available free ports on the + system. It is initialized with a specific socket kind and can generate ports + for given address families while avoiding reuse of previously generated ports. + + Users should not instantiate this class directly, but use the + ``free_tcp_port_factory`` and ``free_udp_port_factory`` fixtures instead. For simple + uses cases, ``free_tcp_port`` and ``free_udp_port`` can be used instead. + """ + + def __init__(self, kind: socket.SocketKind) -> None: + self._kind = kind + self._generated = set[int]() + + @property + def kind(self) -> socket.SocketKind: + """ + The type of socket connection (e.g., :data:`~socket.SOCK_STREAM` or + :data:`~socket.SOCK_DGRAM`) used to bind for checking port availability + + """ + return self._kind + + def __call__(self, family: socket.AddressFamily | None = None) -> int: + """ + Return an unbound port for the given address family. + + :param family: if omitted, both IPv4 and IPv6 addresses will be tried + :return: a port number + + """ + if family is not None: + families = [family] + else: + families = [socket.AF_INET] + if socket.has_ipv6: + families.append(socket.AF_INET6) + + while True: + port = 0 + with ExitStack() as stack: + for family in families: + sock = stack.enter_context(socket.socket(family, self._kind)) + addr = "::1" if family == socket.AF_INET6 else "127.0.0.1" + try: + sock.bind((addr, port)) + except OSError: + break + + if not port: + port = sock.getsockname()[1] + else: + if port not in self._generated: + self._generated.add(port) + return port + + +@pytest.fixture(scope="session") +def free_tcp_port_factory() -> FreePortFactory: + return FreePortFactory(socket.SOCK_STREAM) + + +@pytest.fixture(scope="session") +def free_udp_port_factory() -> FreePortFactory: + return FreePortFactory(socket.SOCK_DGRAM) + + +@pytest.fixture +def free_tcp_port(free_tcp_port_factory: Callable[[], int]) -> int: + return free_tcp_port_factory() + + +@pytest.fixture +def free_udp_port(free_udp_port_factory: Callable[[], int]) -> int: + return free_udp_port_factory() diff --git a/venv/lib/python3.10/site-packages/anyio/streams/__init__.py b/venv/lib/python3.10/site-packages/anyio/streams/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5af7bde33acae5a7ce5927989552e6064f4f79b1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/buffered.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/buffered.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f01ec5cf21ad6ad80e6469df2e23ec827a1e86c Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/buffered.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/file.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/file.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07b83dd0b86ff4ff1b53e82d6ef9c1312ce96bcd Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/file.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/memory.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/memory.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1e6fe708a5bc2c47095fe8d9d134f57afa30dd3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/memory.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/stapled.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/stapled.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d755664f6023838dee33997095ae564e3b83510 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/stapled.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/text.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/text.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0b1e460f899ae9aa7d94751a4a6a5fc135bc1c2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/text.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/tls.cpython-310.pyc b/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/tls.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bc0423e32d74fe88bf30e17b86f5f2a292863c5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/anyio/streams/__pycache__/tls.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/anyio/streams/buffered.py b/venv/lib/python3.10/site-packages/anyio/streams/buffered.py new file mode 100644 index 0000000000000000000000000000000000000000..ca40eae84822e805adf075cbc231f2f056ea9808 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/streams/buffered.py @@ -0,0 +1,182 @@ +from __future__ import annotations + +import sys +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass, field +from typing import Any, SupportsIndex + +from .. import ClosedResourceError, DelimiterNotFound, EndOfStream, IncompleteRead +from ..abc import ( + AnyByteReceiveStream, + AnyByteStream, + AnyByteStreamConnectable, + ByteReceiveStream, + ByteStream, + ByteStreamConnectable, +) + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + + +@dataclass(eq=False) +class BufferedByteReceiveStream(ByteReceiveStream): + """ + Wraps any bytes-based receive stream and uses a buffer to provide sophisticated + receiving capabilities in the form of a byte stream. + """ + + receive_stream: AnyByteReceiveStream + _buffer: bytearray = field(init=False, default_factory=bytearray) + _closed: bool = field(init=False, default=False) + + async def aclose(self) -> None: + await self.receive_stream.aclose() + self._closed = True + + @property + def buffer(self) -> bytes: + """The bytes currently in the buffer.""" + return bytes(self._buffer) + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return self.receive_stream.extra_attributes + + def feed_data(self, data: Iterable[SupportsIndex], /) -> None: + """ + Append data directly into the buffer. + + Any data in the buffer will be consumed by receive operations before receiving + anything from the wrapped stream. + + :param data: the data to append to the buffer (can be bytes or anything else + that supports ``__index__()``) + + """ + self._buffer.extend(data) + + async def receive(self, max_bytes: int = 65536) -> bytes: + if self._closed: + raise ClosedResourceError + + if self._buffer: + chunk = bytes(self._buffer[:max_bytes]) + del self._buffer[:max_bytes] + return chunk + elif isinstance(self.receive_stream, ByteReceiveStream): + return await self.receive_stream.receive(max_bytes) + else: + # With a bytes-oriented object stream, we need to handle any surplus bytes + # we get from the receive() call + chunk = await self.receive_stream.receive() + if len(chunk) > max_bytes: + # Save the surplus bytes in the buffer + self._buffer.extend(chunk[max_bytes:]) + return chunk[:max_bytes] + else: + return chunk + + async def receive_exactly(self, nbytes: int) -> bytes: + """ + Read exactly the given amount of bytes from the stream. + + :param nbytes: the number of bytes to read + :return: the bytes read + :raises ~anyio.IncompleteRead: if the stream was closed before the requested + amount of bytes could be read from the stream + + """ + while True: + remaining = nbytes - len(self._buffer) + if remaining <= 0: + retval = self._buffer[:nbytes] + del self._buffer[:nbytes] + return bytes(retval) + + try: + if isinstance(self.receive_stream, ByteReceiveStream): + chunk = await self.receive_stream.receive(remaining) + else: + chunk = await self.receive_stream.receive() + except EndOfStream as exc: + raise IncompleteRead from exc + + self._buffer.extend(chunk) + + async def receive_until(self, delimiter: bytes, max_bytes: int) -> bytes: + """ + Read from the stream until the delimiter is found or max_bytes have been read. + + :param delimiter: the marker to look for in the stream + :param max_bytes: maximum number of bytes that will be read before raising + :exc:`~anyio.DelimiterNotFound` + :return: the bytes read (not including the delimiter) + :raises ~anyio.IncompleteRead: if the stream was closed before the delimiter + was found + :raises ~anyio.DelimiterNotFound: if the delimiter is not found within the + bytes read up to the maximum allowed + + """ + delimiter_size = len(delimiter) + offset = 0 + while True: + # Check if the delimiter can be found in the current buffer + index = self._buffer.find(delimiter, offset) + if index >= 0: + found = self._buffer[:index] + del self._buffer[: index + len(delimiter) :] + return bytes(found) + + # Check if the buffer is already at or over the limit + if len(self._buffer) >= max_bytes: + raise DelimiterNotFound(max_bytes) + + # Read more data into the buffer from the socket + try: + data = await self.receive_stream.receive() + except EndOfStream as exc: + raise IncompleteRead from exc + + # Move the offset forward and add the new data to the buffer + offset = max(len(self._buffer) - delimiter_size + 1, 0) + self._buffer.extend(data) + + +class BufferedByteStream(BufferedByteReceiveStream, ByteStream): + """ + A full-duplex variant of :class:`BufferedByteReceiveStream`. All writes are passed + through to the wrapped stream as-is. + """ + + def __init__(self, stream: AnyByteStream): + """ + :param stream: the stream to be wrapped + + """ + super().__init__(stream) + self._stream = stream + + @override + async def send_eof(self) -> None: + await self._stream.send_eof() + + @override + async def send(self, item: bytes) -> None: + await self._stream.send(item) + + +class BufferedConnectable(ByteStreamConnectable): + def __init__(self, connectable: AnyByteStreamConnectable): + """ + :param connectable: the connectable to wrap + + """ + self.connectable = connectable + + @override + async def connect(self) -> BufferedByteStream: + stream = await self.connectable.connect() + return BufferedByteStream(stream) diff --git a/venv/lib/python3.10/site-packages/anyio/streams/file.py b/venv/lib/python3.10/site-packages/anyio/streams/file.py new file mode 100644 index 0000000000000000000000000000000000000000..f492464267ac54b57ee9953a4aad128f06a2110a --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/streams/file.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +from collections.abc import Callable, Mapping +from io import SEEK_SET, UnsupportedOperation +from os import PathLike +from pathlib import Path +from typing import Any, BinaryIO, cast + +from .. import ( + BrokenResourceError, + ClosedResourceError, + EndOfStream, + TypedAttributeSet, + to_thread, + typed_attribute, +) +from ..abc import ByteReceiveStream, ByteSendStream + + +class FileStreamAttribute(TypedAttributeSet): + #: the open file descriptor + file: BinaryIO = typed_attribute() + #: the path of the file on the file system, if available (file must be a real file) + path: Path = typed_attribute() + #: the file number, if available (file must be a real file or a TTY) + fileno: int = typed_attribute() + + +class _BaseFileStream: + def __init__(self, file: BinaryIO): + self._file = file + + async def aclose(self) -> None: + await to_thread.run_sync(self._file.close) + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + attributes: dict[Any, Callable[[], Any]] = { + FileStreamAttribute.file: lambda: self._file, + } + + if hasattr(self._file, "name"): + attributes[FileStreamAttribute.path] = lambda: Path(self._file.name) + + try: + self._file.fileno() + except UnsupportedOperation: + pass + else: + attributes[FileStreamAttribute.fileno] = lambda: self._file.fileno() + + return attributes + + +class FileReadStream(_BaseFileStream, ByteReceiveStream): + """ + A byte stream that reads from a file in the file system. + + :param file: a file that has been opened for reading in binary mode + + .. versionadded:: 3.0 + """ + + @classmethod + async def from_path(cls, path: str | PathLike[str]) -> FileReadStream: + """ + Create a file read stream by opening the given file. + + :param path: path of the file to read from + + """ + file = await to_thread.run_sync(Path(path).open, "rb") + return cls(cast(BinaryIO, file)) + + async def receive(self, max_bytes: int = 65536) -> bytes: + try: + data = await to_thread.run_sync(self._file.read, max_bytes) + except ValueError: + raise ClosedResourceError from None + except OSError as exc: + raise BrokenResourceError from exc + + if data: + return data + else: + raise EndOfStream + + async def seek(self, position: int, whence: int = SEEK_SET) -> int: + """ + Seek the file to the given position. + + .. seealso:: :meth:`io.IOBase.seek` + + .. note:: Not all file descriptors are seekable. + + :param position: position to seek the file to + :param whence: controls how ``position`` is interpreted + :return: the new absolute position + :raises OSError: if the file is not seekable + + """ + return await to_thread.run_sync(self._file.seek, position, whence) + + async def tell(self) -> int: + """ + Return the current stream position. + + .. note:: Not all file descriptors are seekable. + + :return: the current absolute position + :raises OSError: if the file is not seekable + + """ + return await to_thread.run_sync(self._file.tell) + + +class FileWriteStream(_BaseFileStream, ByteSendStream): + """ + A byte stream that writes to a file in the file system. + + :param file: a file that has been opened for writing in binary mode + + .. versionadded:: 3.0 + """ + + @classmethod + async def from_path( + cls, path: str | PathLike[str], append: bool = False + ) -> FileWriteStream: + """ + Create a file write stream by opening the given file for writing. + + :param path: path of the file to write to + :param append: if ``True``, open the file for appending; if ``False``, any + existing file at the given path will be truncated + + """ + mode = "ab" if append else "wb" + file = await to_thread.run_sync(Path(path).open, mode) + return cls(cast(BinaryIO, file)) + + async def send(self, item: bytes) -> None: + try: + await to_thread.run_sync(self._file.write, item) + except ValueError: + raise ClosedResourceError from None + except OSError as exc: + raise BrokenResourceError from exc diff --git a/venv/lib/python3.10/site-packages/anyio/streams/memory.py b/venv/lib/python3.10/site-packages/anyio/streams/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..9a3bac474b5eba460033240b5b8c45effd7bb334 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/streams/memory.py @@ -0,0 +1,319 @@ +from __future__ import annotations + +import warnings +from collections import OrderedDict, deque +from dataclasses import dataclass, field +from types import TracebackType +from typing import Generic, NamedTuple, TypeVar + +from .. import ( + BrokenResourceError, + ClosedResourceError, + EndOfStream, + WouldBlock, +) +from .._core._testing import TaskInfo, get_current_task +from ..abc import Event, ObjectReceiveStream, ObjectSendStream +from ..lowlevel import checkpoint + +T_Item = TypeVar("T_Item") +T_co = TypeVar("T_co", covariant=True) +T_contra = TypeVar("T_contra", contravariant=True) + + +class MemoryObjectStreamStatistics(NamedTuple): + current_buffer_used: int #: number of items stored in the buffer + #: maximum number of items that can be stored on this stream (or :data:`math.inf`) + max_buffer_size: float + open_send_streams: int #: number of unclosed clones of the send stream + open_receive_streams: int #: number of unclosed clones of the receive stream + #: number of tasks blocked on :meth:`MemoryObjectSendStream.send` + tasks_waiting_send: int + #: number of tasks blocked on :meth:`MemoryObjectReceiveStream.receive` + tasks_waiting_receive: int + + +@dataclass(eq=False) +class MemoryObjectItemReceiver(Generic[T_Item]): + task_info: TaskInfo = field(init=False, default_factory=get_current_task) + item: T_Item = field(init=False) + + def __repr__(self) -> str: + # When item is not defined, we get following error with default __repr__: + # AttributeError: 'MemoryObjectItemReceiver' object has no attribute 'item' + item = getattr(self, "item", None) + return f"{self.__class__.__name__}(task_info={self.task_info}, item={item!r})" + + +@dataclass(eq=False) +class MemoryObjectStreamState(Generic[T_Item]): + max_buffer_size: float = field() + buffer: deque[T_Item] = field(init=False, default_factory=deque) + open_send_channels: int = field(init=False, default=0) + open_receive_channels: int = field(init=False, default=0) + waiting_receivers: OrderedDict[Event, MemoryObjectItemReceiver[T_Item]] = field( + init=False, default_factory=OrderedDict + ) + waiting_senders: OrderedDict[Event, T_Item] = field( + init=False, default_factory=OrderedDict + ) + + def statistics(self) -> MemoryObjectStreamStatistics: + return MemoryObjectStreamStatistics( + len(self.buffer), + self.max_buffer_size, + self.open_send_channels, + self.open_receive_channels, + len(self.waiting_senders), + len(self.waiting_receivers), + ) + + +@dataclass(eq=False) +class MemoryObjectReceiveStream(Generic[T_co], ObjectReceiveStream[T_co]): + _state: MemoryObjectStreamState[T_co] + _closed: bool = field(init=False, default=False) + + def __post_init__(self) -> None: + self._state.open_receive_channels += 1 + + def receive_nowait(self) -> T_co: + """ + Receive the next item if it can be done without waiting. + + :return: the received item + :raises ~anyio.ClosedResourceError: if this send stream has been closed + :raises ~anyio.EndOfStream: if the buffer is empty and this stream has been + closed from the sending end + :raises ~anyio.WouldBlock: if there are no items in the buffer and no tasks + waiting to send + + """ + if self._closed: + raise ClosedResourceError + + if self._state.waiting_senders: + # Get the item from the next sender + send_event, item = self._state.waiting_senders.popitem(last=False) + self._state.buffer.append(item) + send_event.set() + + if self._state.buffer: + return self._state.buffer.popleft() + elif not self._state.open_send_channels: + raise EndOfStream + + raise WouldBlock + + async def receive(self) -> T_co: + await checkpoint() + try: + return self.receive_nowait() + except WouldBlock: + # Add ourselves in the queue + receive_event = Event() + receiver = MemoryObjectItemReceiver[T_co]() + self._state.waiting_receivers[receive_event] = receiver + + try: + await receive_event.wait() + finally: + self._state.waiting_receivers.pop(receive_event, None) + + try: + return receiver.item + except AttributeError: + raise EndOfStream from None + + def clone(self) -> MemoryObjectReceiveStream[T_co]: + """ + Create a clone of this receive stream. + + Each clone can be closed separately. Only when all clones have been closed will + the receiving end of the memory stream be considered closed by the sending ends. + + :return: the cloned stream + + """ + if self._closed: + raise ClosedResourceError + + return MemoryObjectReceiveStream(_state=self._state) + + def close(self) -> None: + """ + Close the stream. + + This works the exact same way as :meth:`aclose`, but is provided as a special + case for the benefit of synchronous callbacks. + + """ + if not self._closed: + self._closed = True + self._state.open_receive_channels -= 1 + if self._state.open_receive_channels == 0: + send_events = list(self._state.waiting_senders.keys()) + for event in send_events: + event.set() + + async def aclose(self) -> None: + self.close() + + def statistics(self) -> MemoryObjectStreamStatistics: + """ + Return statistics about the current state of this stream. + + .. versionadded:: 3.0 + """ + return self._state.statistics() + + def __enter__(self) -> MemoryObjectReceiveStream[T_co]: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def __del__(self) -> None: + if not self._closed: + warnings.warn( + f"Unclosed <{self.__class__.__name__} at {id(self):x}>", + ResourceWarning, + stacklevel=1, + source=self, + ) + + +@dataclass(eq=False) +class MemoryObjectSendStream(Generic[T_contra], ObjectSendStream[T_contra]): + _state: MemoryObjectStreamState[T_contra] + _closed: bool = field(init=False, default=False) + + def __post_init__(self) -> None: + self._state.open_send_channels += 1 + + def send_nowait(self, item: T_contra) -> None: + """ + Send an item immediately if it can be done without waiting. + + :param item: the item to send + :raises ~anyio.ClosedResourceError: if this send stream has been closed + :raises ~anyio.BrokenResourceError: if the stream has been closed from the + receiving end + :raises ~anyio.WouldBlock: if the buffer is full and there are no tasks waiting + to receive + + """ + if self._closed: + raise ClosedResourceError + if not self._state.open_receive_channels: + raise BrokenResourceError + + while self._state.waiting_receivers: + receive_event, receiver = self._state.waiting_receivers.popitem(last=False) + if not receiver.task_info.has_pending_cancellation(): + receiver.item = item + receive_event.set() + return + + if len(self._state.buffer) < self._state.max_buffer_size: + self._state.buffer.append(item) + else: + raise WouldBlock + + async def send(self, item: T_contra) -> None: + """ + Send an item to the stream. + + If the buffer is full, this method blocks until there is again room in the + buffer or the item can be sent directly to a receiver. + + :param item: the item to send + :raises ~anyio.ClosedResourceError: if this send stream has been closed + :raises ~anyio.BrokenResourceError: if the stream has been closed from the + receiving end + + """ + await checkpoint() + try: + self.send_nowait(item) + except WouldBlock: + # Wait until there's someone on the receiving end + send_event = Event() + self._state.waiting_senders[send_event] = item + try: + await send_event.wait() + except BaseException: + self._state.waiting_senders.pop(send_event, None) + raise + + if send_event in self._state.waiting_senders: + del self._state.waiting_senders[send_event] + raise BrokenResourceError from None + + def clone(self) -> MemoryObjectSendStream[T_contra]: + """ + Create a clone of this send stream. + + Each clone can be closed separately. Only when all clones have been closed will + the sending end of the memory stream be considered closed by the receiving ends. + + :return: the cloned stream + + """ + if self._closed: + raise ClosedResourceError + + return MemoryObjectSendStream(_state=self._state) + + def close(self) -> None: + """ + Close the stream. + + This works the exact same way as :meth:`aclose`, but is provided as a special + case for the benefit of synchronous callbacks. + + """ + if not self._closed: + self._closed = True + self._state.open_send_channels -= 1 + if self._state.open_send_channels == 0: + receive_events = list(self._state.waiting_receivers.keys()) + self._state.waiting_receivers.clear() + for event in receive_events: + event.set() + + async def aclose(self) -> None: + self.close() + + def statistics(self) -> MemoryObjectStreamStatistics: + """ + Return statistics about the current state of this stream. + + .. versionadded:: 3.0 + """ + return self._state.statistics() + + def __enter__(self) -> MemoryObjectSendStream[T_contra]: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def __del__(self) -> None: + if not self._closed: + warnings.warn( + f"Unclosed <{self.__class__.__name__} at {id(self):x}>", + ResourceWarning, + stacklevel=1, + source=self, + ) diff --git a/venv/lib/python3.10/site-packages/anyio/streams/stapled.py b/venv/lib/python3.10/site-packages/anyio/streams/stapled.py new file mode 100644 index 0000000000000000000000000000000000000000..80f64a2e8e5763ae327c5c213ec12e24f023b4d3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/streams/stapled.py @@ -0,0 +1,141 @@ +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from typing import Any, Generic, TypeVar + +from ..abc import ( + ByteReceiveStream, + ByteSendStream, + ByteStream, + Listener, + ObjectReceiveStream, + ObjectSendStream, + ObjectStream, + TaskGroup, +) + +T_Item = TypeVar("T_Item") +T_Stream = TypeVar("T_Stream") + + +@dataclass(eq=False) +class StapledByteStream(ByteStream): + """ + Combines two byte streams into a single, bidirectional byte stream. + + Extra attributes will be provided from both streams, with the receive stream + providing the values in case of a conflict. + + :param ByteSendStream send_stream: the sending byte stream + :param ByteReceiveStream receive_stream: the receiving byte stream + """ + + send_stream: ByteSendStream + receive_stream: ByteReceiveStream + + async def receive(self, max_bytes: int = 65536) -> bytes: + return await self.receive_stream.receive(max_bytes) + + async def send(self, item: bytes) -> None: + await self.send_stream.send(item) + + async def send_eof(self) -> None: + await self.send_stream.aclose() + + async def aclose(self) -> None: + await self.send_stream.aclose() + await self.receive_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self.send_stream.extra_attributes, + **self.receive_stream.extra_attributes, + } + + +@dataclass(eq=False) +class StapledObjectStream(Generic[T_Item], ObjectStream[T_Item]): + """ + Combines two object streams into a single, bidirectional object stream. + + Extra attributes will be provided from both streams, with the receive stream + providing the values in case of a conflict. + + :param ObjectSendStream send_stream: the sending object stream + :param ObjectReceiveStream receive_stream: the receiving object stream + """ + + send_stream: ObjectSendStream[T_Item] + receive_stream: ObjectReceiveStream[T_Item] + + async def receive(self) -> T_Item: + return await self.receive_stream.receive() + + async def send(self, item: T_Item) -> None: + await self.send_stream.send(item) + + async def send_eof(self) -> None: + await self.send_stream.aclose() + + async def aclose(self) -> None: + await self.send_stream.aclose() + await self.receive_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self.send_stream.extra_attributes, + **self.receive_stream.extra_attributes, + } + + +@dataclass(eq=False) +class MultiListener(Generic[T_Stream], Listener[T_Stream]): + """ + Combines multiple listeners into one, serving connections from all of them at once. + + Any MultiListeners in the given collection of listeners will have their listeners + moved into this one. + + Extra attributes are provided from each listener, with each successive listener + overriding any conflicting attributes from the previous one. + + :param listeners: listeners to serve + :type listeners: Sequence[Listener[T_Stream]] + """ + + listeners: Sequence[Listener[T_Stream]] + + def __post_init__(self) -> None: + listeners: list[Listener[T_Stream]] = [] + for listener in self.listeners: + if isinstance(listener, MultiListener): + listeners.extend(listener.listeners) + del listener.listeners[:] # type: ignore[attr-defined] + else: + listeners.append(listener) + + self.listeners = listeners + + async def serve( + self, handler: Callable[[T_Stream], Any], task_group: TaskGroup | None = None + ) -> None: + from .. import create_task_group + + async with create_task_group() as tg: + for listener in self.listeners: + tg.start_soon(listener.serve, handler, task_group) + + async def aclose(self) -> None: + for listener in self.listeners: + await listener.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + attributes: dict = {} + for listener in self.listeners: + attributes.update(listener.extra_attributes) + + return attributes diff --git a/venv/lib/python3.10/site-packages/anyio/streams/text.py b/venv/lib/python3.10/site-packages/anyio/streams/text.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd8e7a2550a7e217ec280a7147826c2bc3bad96 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/streams/text.py @@ -0,0 +1,169 @@ +from __future__ import annotations + +import codecs +import sys +from collections.abc import Callable, Mapping +from dataclasses import InitVar, dataclass, field +from typing import Any + +from ..abc import ( + AnyByteReceiveStream, + AnyByteSendStream, + AnyByteStream, + AnyByteStreamConnectable, + ObjectReceiveStream, + ObjectSendStream, + ObjectStream, + ObjectStreamConnectable, +) + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + + +@dataclass(eq=False) +class TextReceiveStream(ObjectReceiveStream[str]): + """ + Stream wrapper that decodes bytes to strings using the given encoding. + + Decoding is done using :class:`~codecs.IncrementalDecoder` which returns any + completely received unicode characters as soon as they come in. + + :param transport_stream: any bytes-based receive stream + :param encoding: character encoding to use for decoding bytes to strings (defaults + to ``utf-8``) + :param errors: handling scheme for decoding errors (defaults to ``strict``; see the + `codecs module documentation`_ for a comprehensive list of options) + + .. _codecs module documentation: + https://docs.python.org/3/library/codecs.html#codec-objects + """ + + transport_stream: AnyByteReceiveStream + encoding: InitVar[str] = "utf-8" + errors: InitVar[str] = "strict" + _decoder: codecs.IncrementalDecoder = field(init=False) + + def __post_init__(self, encoding: str, errors: str) -> None: + decoder_class = codecs.getincrementaldecoder(encoding) + self._decoder = decoder_class(errors=errors) + + async def receive(self) -> str: + while True: + chunk = await self.transport_stream.receive() + decoded = self._decoder.decode(chunk) + if decoded: + return decoded + + async def aclose(self) -> None: + await self.transport_stream.aclose() + self._decoder.reset() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return self.transport_stream.extra_attributes + + +@dataclass(eq=False) +class TextSendStream(ObjectSendStream[str]): + """ + Sends strings to the wrapped stream as bytes using the given encoding. + + :param AnyByteSendStream transport_stream: any bytes-based send stream + :param str encoding: character encoding to use for encoding strings to bytes + (defaults to ``utf-8``) + :param str errors: handling scheme for encoding errors (defaults to ``strict``; see + the `codecs module documentation`_ for a comprehensive list of options) + + .. _codecs module documentation: + https://docs.python.org/3/library/codecs.html#codec-objects + """ + + transport_stream: AnyByteSendStream + encoding: InitVar[str] = "utf-8" + errors: str = "strict" + _encoder: Callable[..., tuple[bytes, int]] = field(init=False) + + def __post_init__(self, encoding: str) -> None: + self._encoder = codecs.getencoder(encoding) + + async def send(self, item: str) -> None: + encoded = self._encoder(item, self.errors)[0] + await self.transport_stream.send(encoded) + + async def aclose(self) -> None: + await self.transport_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return self.transport_stream.extra_attributes + + +@dataclass(eq=False) +class TextStream(ObjectStream[str]): + """ + A bidirectional stream that decodes bytes to strings on receive and encodes strings + to bytes on send. + + Extra attributes will be provided from both streams, with the receive stream + providing the values in case of a conflict. + + :param AnyByteStream transport_stream: any bytes-based stream + :param str encoding: character encoding to use for encoding/decoding strings to/from + bytes (defaults to ``utf-8``) + :param str errors: handling scheme for encoding errors (defaults to ``strict``; see + the `codecs module documentation`_ for a comprehensive list of options) + + .. _codecs module documentation: + https://docs.python.org/3/library/codecs.html#codec-objects + """ + + transport_stream: AnyByteStream + encoding: InitVar[str] = "utf-8" + errors: InitVar[str] = "strict" + _receive_stream: TextReceiveStream = field(init=False) + _send_stream: TextSendStream = field(init=False) + + def __post_init__(self, encoding: str, errors: str) -> None: + self._receive_stream = TextReceiveStream( + self.transport_stream, encoding=encoding, errors=errors + ) + self._send_stream = TextSendStream( + self.transport_stream, encoding=encoding, errors=errors + ) + + async def receive(self) -> str: + return await self._receive_stream.receive() + + async def send(self, item: str) -> None: + await self._send_stream.send(item) + + async def send_eof(self) -> None: + await self.transport_stream.send_eof() + + async def aclose(self) -> None: + await self._send_stream.aclose() + await self._receive_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self._send_stream.extra_attributes, + **self._receive_stream.extra_attributes, + } + + +class TextConnectable(ObjectStreamConnectable[str]): + def __init__(self, connectable: AnyByteStreamConnectable): + """ + :param connectable: the bytestream endpoint to wrap + + """ + self.connectable = connectable + + @override + async def connect(self) -> TextStream: + stream = await self.connectable.connect() + return TextStream(stream) diff --git a/venv/lib/python3.10/site-packages/anyio/streams/tls.py b/venv/lib/python3.10/site-packages/anyio/streams/tls.py new file mode 100644 index 0000000000000000000000000000000000000000..17fa200e61c77edc80a52601eb9f6edc89620023 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/streams/tls.py @@ -0,0 +1,417 @@ +from __future__ import annotations + +import logging +import re +import ssl +import sys +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from functools import wraps +from ssl import SSLContext +from typing import Any, TypeVar + +from .. import ( + BrokenResourceError, + EndOfStream, + aclose_forcefully, + get_cancelled_exc_class, + to_thread, +) +from .._core._typedattr import TypedAttributeSet, typed_attribute +from ..abc import ( + AnyByteStream, + AnyByteStreamConnectable, + ByteStream, + ByteStreamConnectable, + Listener, + TaskGroup, +) + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") +_PCTRTT: TypeAlias = tuple[tuple[str, str], ...] +_PCTRTTT: TypeAlias = tuple[_PCTRTT, ...] + + +class TLSAttribute(TypedAttributeSet): + """Contains Transport Layer Security related attributes.""" + + #: the selected ALPN protocol + alpn_protocol: str | None = typed_attribute() + #: the channel binding for type ``tls-unique`` + channel_binding_tls_unique: bytes = typed_attribute() + #: the selected cipher + cipher: tuple[str, str, int] = typed_attribute() + #: the peer certificate in dictionary form (see :meth:`ssl.SSLSocket.getpeercert` + # for more information) + peer_certificate: None | (dict[str, str | _PCTRTTT | _PCTRTT]) = typed_attribute() + #: the peer certificate in binary form + peer_certificate_binary: bytes | None = typed_attribute() + #: ``True`` if this is the server side of the connection + server_side: bool = typed_attribute() + #: ciphers shared by the client during the TLS handshake (``None`` if this is the + #: client side) + shared_ciphers: list[tuple[str, str, int]] | None = typed_attribute() + #: the :class:`~ssl.SSLObject` used for encryption + ssl_object: ssl.SSLObject = typed_attribute() + #: ``True`` if this stream does (and expects) a closing TLS handshake when the + #: stream is being closed + standard_compatible: bool = typed_attribute() + #: the TLS protocol version (e.g. ``TLSv1.2``) + tls_version: str = typed_attribute() + + +@dataclass(eq=False) +class TLSStream(ByteStream): + """ + A stream wrapper that encrypts all sent data and decrypts received data. + + This class has no public initializer; use :meth:`wrap` instead. + All extra attributes from :class:`~TLSAttribute` are supported. + + :var AnyByteStream transport_stream: the wrapped stream + + """ + + transport_stream: AnyByteStream + standard_compatible: bool + _ssl_object: ssl.SSLObject + _read_bio: ssl.MemoryBIO + _write_bio: ssl.MemoryBIO + + @classmethod + async def wrap( + cls, + transport_stream: AnyByteStream, + *, + server_side: bool | None = None, + hostname: str | None = None, + ssl_context: ssl.SSLContext | None = None, + standard_compatible: bool = True, + ) -> TLSStream: + """ + Wrap an existing stream with Transport Layer Security. + + This performs a TLS handshake with the peer. + + :param transport_stream: a bytes-transporting stream to wrap + :param server_side: ``True`` if this is the server side of the connection, + ``False`` if this is the client side (if omitted, will be set to ``False`` + if ``hostname`` has been provided, ``False`` otherwise). Used only to create + a default context when an explicit context has not been provided. + :param hostname: host name of the peer (if host name checking is desired) + :param ssl_context: the SSLContext object to use (if not provided, a secure + default will be created) + :param standard_compatible: if ``False``, skip the closing handshake when + closing the connection, and don't raise an exception if the peer does the + same + :raises ~ssl.SSLError: if the TLS handshake fails + + """ + if server_side is None: + server_side = not hostname + + if not ssl_context: + purpose = ( + ssl.Purpose.CLIENT_AUTH if server_side else ssl.Purpose.SERVER_AUTH + ) + ssl_context = ssl.create_default_context(purpose) + + # Re-enable detection of unexpected EOFs if it was disabled by Python + if hasattr(ssl, "OP_IGNORE_UNEXPECTED_EOF"): + ssl_context.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF + + bio_in = ssl.MemoryBIO() + bio_out = ssl.MemoryBIO() + + # External SSLContext implementations may do blocking I/O in wrap_bio(), + # but the standard library implementation won't + if type(ssl_context) is ssl.SSLContext: + ssl_object = ssl_context.wrap_bio( + bio_in, bio_out, server_side=server_side, server_hostname=hostname + ) + else: + ssl_object = await to_thread.run_sync( + ssl_context.wrap_bio, + bio_in, + bio_out, + server_side, + hostname, + None, + ) + + wrapper = cls( + transport_stream=transport_stream, + standard_compatible=standard_compatible, + _ssl_object=ssl_object, + _read_bio=bio_in, + _write_bio=bio_out, + ) + await wrapper._call_sslobject_method(ssl_object.do_handshake) + return wrapper + + async def _call_sslobject_method( + self, func: Callable[[Unpack[PosArgsT]], T_Retval], *args: Unpack[PosArgsT] + ) -> T_Retval: + while True: + try: + result = func(*args) + except ssl.SSLWantReadError: + try: + # Flush any pending writes first + if self._write_bio.pending: + await self.transport_stream.send(self._write_bio.read()) + + data = await self.transport_stream.receive() + except EndOfStream: + self._read_bio.write_eof() + except OSError as exc: + self._read_bio.write_eof() + self._write_bio.write_eof() + raise BrokenResourceError from exc + else: + self._read_bio.write(data) + except ssl.SSLWantWriteError: + await self.transport_stream.send(self._write_bio.read()) + except ssl.SSLSyscallError as exc: + self._read_bio.write_eof() + self._write_bio.write_eof() + raise BrokenResourceError from exc + except ssl.SSLError as exc: + self._read_bio.write_eof() + self._write_bio.write_eof() + if isinstance(exc, ssl.SSLEOFError) or ( + exc.strerror and "UNEXPECTED_EOF_WHILE_READING" in exc.strerror + ): + if self.standard_compatible: + raise BrokenResourceError from exc + else: + raise EndOfStream from None + + raise + else: + # Flush any pending writes first + if self._write_bio.pending: + await self.transport_stream.send(self._write_bio.read()) + + return result + + async def unwrap(self) -> tuple[AnyByteStream, bytes]: + """ + Does the TLS closing handshake. + + :return: a tuple of (wrapped byte stream, bytes left in the read buffer) + + """ + await self._call_sslobject_method(self._ssl_object.unwrap) + self._read_bio.write_eof() + self._write_bio.write_eof() + return self.transport_stream, self._read_bio.read() + + async def aclose(self) -> None: + if self.standard_compatible: + try: + await self.unwrap() + except BaseException: + await aclose_forcefully(self.transport_stream) + raise + + await self.transport_stream.aclose() + + async def receive(self, max_bytes: int = 65536) -> bytes: + data = await self._call_sslobject_method(self._ssl_object.read, max_bytes) + if not data: + raise EndOfStream + + return data + + async def send(self, item: bytes) -> None: + await self._call_sslobject_method(self._ssl_object.write, item) + + async def send_eof(self) -> None: + tls_version = self.extra(TLSAttribute.tls_version) + match = re.match(r"TLSv(\d+)(?:\.(\d+))?", tls_version) + if match: + major, minor = int(match.group(1)), int(match.group(2) or 0) + if (major, minor) < (1, 3): + raise NotImplementedError( + f"send_eof() requires at least TLSv1.3; current " + f"session uses {tls_version}" + ) + + raise NotImplementedError( + "send_eof() has not yet been implemented for TLS streams" + ) + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self.transport_stream.extra_attributes, + TLSAttribute.alpn_protocol: self._ssl_object.selected_alpn_protocol, + TLSAttribute.channel_binding_tls_unique: ( + self._ssl_object.get_channel_binding + ), + TLSAttribute.cipher: self._ssl_object.cipher, + TLSAttribute.peer_certificate: lambda: self._ssl_object.getpeercert(False), + TLSAttribute.peer_certificate_binary: lambda: self._ssl_object.getpeercert( + True + ), + TLSAttribute.server_side: lambda: self._ssl_object.server_side, + TLSAttribute.shared_ciphers: lambda: self._ssl_object.shared_ciphers() + if self._ssl_object.server_side + else None, + TLSAttribute.standard_compatible: lambda: self.standard_compatible, + TLSAttribute.ssl_object: lambda: self._ssl_object, + TLSAttribute.tls_version: self._ssl_object.version, + } + + +@dataclass(eq=False) +class TLSListener(Listener[TLSStream]): + """ + A convenience listener that wraps another listener and auto-negotiates a TLS session + on every accepted connection. + + If the TLS handshake times out or raises an exception, + :meth:`handle_handshake_error` is called to do whatever post-mortem processing is + deemed necessary. + + Supports only the :attr:`~TLSAttribute.standard_compatible` extra attribute. + + :param Listener listener: the listener to wrap + :param ssl_context: the SSL context object + :param standard_compatible: a flag passed through to :meth:`TLSStream.wrap` + :param handshake_timeout: time limit for the TLS handshake + (passed to :func:`~anyio.fail_after`) + """ + + listener: Listener[Any] + ssl_context: ssl.SSLContext + standard_compatible: bool = True + handshake_timeout: float = 30 + + @staticmethod + async def handle_handshake_error(exc: BaseException, stream: AnyByteStream) -> None: + """ + Handle an exception raised during the TLS handshake. + + This method does 3 things: + + #. Forcefully closes the original stream + #. Logs the exception (unless it was a cancellation exception) using the + ``anyio.streams.tls`` logger + #. Reraises the exception if it was a base exception or a cancellation exception + + :param exc: the exception + :param stream: the original stream + + """ + await aclose_forcefully(stream) + + # Log all except cancellation exceptions + if not isinstance(exc, get_cancelled_exc_class()): + # CPython (as of 3.11.5) returns incorrect `sys.exc_info()` here when using + # any asyncio implementation, so we explicitly pass the exception to log + # (https://github.com/python/cpython/issues/108668). Trio does not have this + # issue because it works around the CPython bug. + logging.getLogger(__name__).exception( + "Error during TLS handshake", exc_info=exc + ) + + # Only reraise base exceptions and cancellation exceptions + if not isinstance(exc, Exception) or isinstance(exc, get_cancelled_exc_class()): + raise + + async def serve( + self, + handler: Callable[[TLSStream], Any], + task_group: TaskGroup | None = None, + ) -> None: + @wraps(handler) + async def handler_wrapper(stream: AnyByteStream) -> None: + from .. import fail_after + + try: + with fail_after(self.handshake_timeout): + wrapped_stream = await TLSStream.wrap( + stream, + ssl_context=self.ssl_context, + standard_compatible=self.standard_compatible, + ) + except BaseException as exc: + await self.handle_handshake_error(exc, stream) + else: + await handler(wrapped_stream) + + await self.listener.serve(handler_wrapper, task_group) + + async def aclose(self) -> None: + await self.listener.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + TLSAttribute.standard_compatible: lambda: self.standard_compatible, + } + + +class TLSConnectable(ByteStreamConnectable): + """ + Wraps another connectable and does TLS negotiation after a successful connection. + + :param connectable: the connectable to wrap + :param hostname: host name of the server (if host name checking is desired) + :param ssl_context: the SSLContext object to use (if not provided, a secure default + will be created) + :param standard_compatible: if ``False``, skip the closing handshake when closing + the connection, and don't raise an exception if the server does the same + """ + + def __init__( + self, + connectable: AnyByteStreamConnectable, + *, + hostname: str | None = None, + ssl_context: ssl.SSLContext | None = None, + standard_compatible: bool = True, + ) -> None: + self.connectable = connectable + self.ssl_context: SSLContext = ssl_context or ssl.create_default_context( + ssl.Purpose.SERVER_AUTH + ) + if not isinstance(self.ssl_context, ssl.SSLContext): + raise TypeError( + "ssl_context must be an instance of ssl.SSLContext, not " + f"{type(self.ssl_context).__name__}" + ) + self.hostname = hostname + self.standard_compatible = standard_compatible + + @override + async def connect(self) -> TLSStream: + stream = await self.connectable.connect() + try: + return await TLSStream.wrap( + stream, + hostname=self.hostname, + ssl_context=self.ssl_context, + standard_compatible=self.standard_compatible, + ) + except BaseException: + await aclose_forcefully(stream) + raise diff --git a/venv/lib/python3.10/site-packages/anyio/to_interpreter.py b/venv/lib/python3.10/site-packages/anyio/to_interpreter.py new file mode 100644 index 0000000000000000000000000000000000000000..bafd221fed4d272e052ec5ee63d9b7bf55705145 --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/to_interpreter.py @@ -0,0 +1,239 @@ +from __future__ import annotations + +import atexit +import os +import sys +from collections import deque +from collections.abc import Callable +from typing import Any, Final, TypeVar + +from . import current_time, to_thread +from ._core._exceptions import BrokenWorkerInterpreter +from ._core._synchronization import CapacityLimiter +from .lowlevel import RunVar + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if sys.version_info >= (3, 14): + from concurrent.interpreters import ExecutionFailed, create + + def _interp_call(func: Callable[..., Any], args: tuple[Any, ...]): + try: + retval = func(*args) + except BaseException as exc: + return exc, True + else: + return retval, False + + class Worker: + last_used: float = 0 + + def __init__(self) -> None: + self._interpreter = create() + + def destroy(self) -> None: + self._interpreter.close() + + def call( + self, + func: Callable[..., T_Retval], + args: tuple[Any, ...], + ) -> T_Retval: + try: + res, is_exception = self._interpreter.call(_interp_call, func, args) + except ExecutionFailed as exc: + raise BrokenWorkerInterpreter(exc.excinfo) from exc + + if is_exception: + raise res + + return res +elif sys.version_info >= (3, 13): + import _interpqueues + import _interpreters + + UNBOUND: Final = 2 # I have no clue how this works, but it was used in the stdlib + FMT_UNPICKLED: Final = 0 + FMT_PICKLED: Final = 1 + QUEUE_PICKLE_ARGS: Final = (FMT_PICKLED, UNBOUND) + QUEUE_UNPICKLE_ARGS: Final = (FMT_UNPICKLED, UNBOUND) + + _run_func = compile( + """ +import _interpqueues +from _interpreters import NotShareableError +from pickle import loads, dumps, HIGHEST_PROTOCOL + +QUEUE_PICKLE_ARGS = (1, 2) +QUEUE_UNPICKLE_ARGS = (0, 2) + +item = _interpqueues.get(queue_id)[0] +try: + func, args = loads(item) + retval = func(*args) +except BaseException as exc: + is_exception = True + retval = exc +else: + is_exception = False + +try: + _interpqueues.put(queue_id, (retval, is_exception), *QUEUE_UNPICKLE_ARGS) +except NotShareableError: + retval = dumps(retval, HIGHEST_PROTOCOL) + _interpqueues.put(queue_id, (retval, is_exception), *QUEUE_PICKLE_ARGS) + """, + "", + "exec", + ) + + class Worker: + last_used: float = 0 + + def __init__(self) -> None: + self._interpreter_id = _interpreters.create() + self._queue_id = _interpqueues.create(1, *QUEUE_UNPICKLE_ARGS) + _interpreters.set___main___attrs( + self._interpreter_id, {"queue_id": self._queue_id} + ) + + def destroy(self) -> None: + _interpqueues.destroy(self._queue_id) + _interpreters.destroy(self._interpreter_id) + + def call( + self, + func: Callable[..., T_Retval], + args: tuple[Any, ...], + ) -> T_Retval: + import pickle + + item = pickle.dumps((func, args), pickle.HIGHEST_PROTOCOL) + _interpqueues.put(self._queue_id, item, *QUEUE_PICKLE_ARGS) + exc_info = _interpreters.exec(self._interpreter_id, _run_func) + if exc_info: + raise BrokenWorkerInterpreter(exc_info) + + res = _interpqueues.get(self._queue_id) + (res, is_exception), fmt = res[:2] + if fmt == FMT_PICKLED: + res = pickle.loads(res) + + if is_exception: + raise res + + return res +else: + + class Worker: + last_used: float = 0 + + def __init__(self) -> None: + raise RuntimeError("subinterpreters require at least Python 3.13") + + def call( + self, + func: Callable[..., T_Retval], + args: tuple[Any, ...], + ) -> T_Retval: + raise NotImplementedError + + def destroy(self) -> None: + pass + + +DEFAULT_CPU_COUNT: Final = 8 # this is just an arbitrarily selected value +MAX_WORKER_IDLE_TIME = ( + 30 # seconds a subinterpreter can be idle before becoming eligible for pruning +) + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + +_idle_workers = RunVar[deque[Worker]]("_available_workers") +_default_interpreter_limiter = RunVar[CapacityLimiter]("_default_interpreter_limiter") + + +def _stop_workers(workers: deque[Worker]) -> None: + for worker in workers: + worker.destroy() + + workers.clear() + + +async def run_sync( + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + limiter: CapacityLimiter | None = None, +) -> T_Retval: + """ + Call the given function with the given arguments in a subinterpreter. + + .. warning:: On Python 3.13, the :mod:`concurrent.interpreters` module was not yet + available, so the code path for that Python version relies on an undocumented, + private API. As such, it is recommended to not rely on this function for anything + mission-critical on Python 3.13. + + :param func: a callable + :param args: the positional arguments for the callable + :param limiter: capacity limiter to use to limit the total number of subinterpreters + running (if omitted, the default limiter is used) + :return: the result of the call + :raises BrokenWorkerInterpreter: if there's an internal error in a subinterpreter + + """ + if limiter is None: + limiter = current_default_interpreter_limiter() + + try: + idle_workers = _idle_workers.get() + except LookupError: + idle_workers = deque() + _idle_workers.set(idle_workers) + atexit.register(_stop_workers, idle_workers) + + async with limiter: + try: + worker = idle_workers.pop() + except IndexError: + worker = Worker() + + try: + return await to_thread.run_sync( + worker.call, + func, + args, + limiter=limiter, + ) + finally: + # Prune workers that have been idle for too long + now = current_time() + while idle_workers: + if now - idle_workers[0].last_used <= MAX_WORKER_IDLE_TIME: + break + + await to_thread.run_sync(idle_workers.popleft().destroy, limiter=limiter) + + worker.last_used = current_time() + idle_workers.append(worker) + + +def current_default_interpreter_limiter() -> CapacityLimiter: + """ + Return the capacity limiter used by default to limit the number of concurrently + running subinterpreters. + + Defaults to the number of CPU cores. + + :return: a capacity limiter object + + """ + try: + return _default_interpreter_limiter.get() + except LookupError: + limiter = CapacityLimiter(os.cpu_count() or DEFAULT_CPU_COUNT) + _default_interpreter_limiter.set(limiter) + return limiter diff --git a/venv/lib/python3.10/site-packages/anyio/to_process.py b/venv/lib/python3.10/site-packages/anyio/to_process.py new file mode 100644 index 0000000000000000000000000000000000000000..495de2ae7111ef3b0382f5efe11a0e8e7cbd186b --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/to_process.py @@ -0,0 +1,258 @@ +from __future__ import annotations + +import os +import pickle +import subprocess +import sys +from collections import deque +from collections.abc import Callable +from importlib.util import module_from_spec, spec_from_file_location +from typing import TypeVar, cast + +from ._core._eventloop import current_time, get_async_backend, get_cancelled_exc_class +from ._core._exceptions import BrokenWorkerProcess +from ._core._subprocesses import open_process +from ._core._synchronization import CapacityLimiter +from ._core._tasks import CancelScope, fail_after +from .abc import ByteReceiveStream, ByteSendStream, Process +from .lowlevel import RunVar, checkpoint_if_cancelled +from .streams.buffered import BufferedByteReceiveStream + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +WORKER_MAX_IDLE_TIME = 300 # 5 minutes + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + +_process_pool_workers: RunVar[set[Process]] = RunVar("_process_pool_workers") +_process_pool_idle_workers: RunVar[deque[tuple[Process, float]]] = RunVar( + "_process_pool_idle_workers" +) +_default_process_limiter: RunVar[CapacityLimiter] = RunVar("_default_process_limiter") + + +async def run_sync( # type: ignore[return] + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + cancellable: bool = False, + limiter: CapacityLimiter | None = None, +) -> T_Retval: + """ + Call the given function with the given arguments in a worker process. + + If the ``cancellable`` option is enabled and the task waiting for its completion is + cancelled, the worker process running it will be abruptly terminated using SIGKILL + (or ``terminateProcess()`` on Windows). + + :param func: a callable + :param args: positional arguments for the callable + :param cancellable: ``True`` to allow cancellation of the operation while it's + running + :param limiter: capacity limiter to use to limit the total amount of processes + running (if omitted, the default limiter is used) + :return: an awaitable that yields the return value of the function. + + """ + + async def send_raw_command(pickled_cmd: bytes) -> object: + try: + await stdin.send(pickled_cmd) + response = await buffered.receive_until(b"\n", 50) + status, length = response.split(b" ") + if status not in (b"RETURN", b"EXCEPTION"): + raise RuntimeError( + f"Worker process returned unexpected response: {response!r}" + ) + + pickled_response = await buffered.receive_exactly(int(length)) + except BaseException as exc: + workers.discard(process) + try: + process.kill() + with CancelScope(shield=True): + await process.aclose() + except ProcessLookupError: + pass + + if isinstance(exc, get_cancelled_exc_class()): + raise + else: + raise BrokenWorkerProcess from exc + + retval = pickle.loads(pickled_response) + if status == b"EXCEPTION": + assert isinstance(retval, BaseException) + raise retval + else: + return retval + + # First pickle the request before trying to reserve a worker process + await checkpoint_if_cancelled() + request = pickle.dumps(("run", func, args), protocol=pickle.HIGHEST_PROTOCOL) + + # If this is the first run in this event loop thread, set up the necessary variables + try: + workers = _process_pool_workers.get() + idle_workers = _process_pool_idle_workers.get() + except LookupError: + workers = set() + idle_workers = deque() + _process_pool_workers.set(workers) + _process_pool_idle_workers.set(idle_workers) + get_async_backend().setup_process_pool_exit_at_shutdown(workers) + + async with limiter or current_default_process_limiter(): + # Pop processes from the pool (starting from the most recently used) until we + # find one that hasn't exited yet + process: Process + while idle_workers: + process, idle_since = idle_workers.pop() + if process.returncode is None: + stdin = cast(ByteSendStream, process.stdin) + buffered = BufferedByteReceiveStream( + cast(ByteReceiveStream, process.stdout) + ) + + # Prune any other workers that have been idle for WORKER_MAX_IDLE_TIME + # seconds or longer + now = current_time() + killed_processes: list[Process] = [] + while idle_workers: + if now - idle_workers[0][1] < WORKER_MAX_IDLE_TIME: + break + + process_to_kill, idle_since = idle_workers.popleft() + process_to_kill.kill() + workers.remove(process_to_kill) + killed_processes.append(process_to_kill) + + with CancelScope(shield=True): + for killed_process in killed_processes: + await killed_process.aclose() + + break + + workers.remove(process) + else: + command = [sys.executable, "-u", "-m", __name__] + process = await open_process( + command, stdin=subprocess.PIPE, stdout=subprocess.PIPE + ) + try: + stdin = cast(ByteSendStream, process.stdin) + buffered = BufferedByteReceiveStream( + cast(ByteReceiveStream, process.stdout) + ) + with fail_after(20): + message = await buffered.receive(6) + + if message != b"READY\n": + raise BrokenWorkerProcess( + f"Worker process returned unexpected response: {message!r}" + ) + + main_module_path = getattr(sys.modules["__main__"], "__file__", None) + pickled = pickle.dumps( + ("init", sys.path, main_module_path), + protocol=pickle.HIGHEST_PROTOCOL, + ) + await send_raw_command(pickled) + except (BrokenWorkerProcess, get_cancelled_exc_class()): + raise + except BaseException as exc: + process.kill() + raise BrokenWorkerProcess( + "Error during worker process initialization" + ) from exc + + workers.add(process) + + with CancelScope(shield=not cancellable): + try: + return cast(T_Retval, await send_raw_command(request)) + finally: + if process in workers: + idle_workers.append((process, current_time())) + + +def current_default_process_limiter() -> CapacityLimiter: + """ + Return the capacity limiter that is used by default to limit the number of worker + processes. + + :return: a capacity limiter object + + """ + try: + return _default_process_limiter.get() + except LookupError: + limiter = CapacityLimiter(os.cpu_count() or 2) + _default_process_limiter.set(limiter) + return limiter + + +def process_worker() -> None: + # Redirect standard streams to os.devnull so that user code won't interfere with the + # parent-worker communication + stdin = sys.stdin + stdout = sys.stdout + sys.stdin = open(os.devnull) + sys.stdout = open(os.devnull, "w") + + stdout.buffer.write(b"READY\n") + while True: + retval = exception = None + try: + command, *args = pickle.load(stdin.buffer) + except EOFError: + return + except BaseException as exc: + exception = exc + else: + if command == "run": + func, args = args + try: + retval = func(*args) + except BaseException as exc: + exception = exc + elif command == "init": + main_module_path: str | None + sys.path, main_module_path = args + del sys.modules["__main__"] + if main_module_path and os.path.isfile(main_module_path): + # Load the parent's main module but as __mp_main__ instead of + # __main__ (like multiprocessing does) to avoid infinite recursion + try: + spec = spec_from_file_location("__mp_main__", main_module_path) + if spec and spec.loader: + main = module_from_spec(spec) + spec.loader.exec_module(main) + sys.modules["__main__"] = main + except BaseException as exc: + exception = exc + try: + if exception is not None: + status = b"EXCEPTION" + pickled = pickle.dumps(exception, pickle.HIGHEST_PROTOCOL) + else: + status = b"RETURN" + pickled = pickle.dumps(retval, pickle.HIGHEST_PROTOCOL) + except BaseException as exc: + exception = exc + status = b"EXCEPTION" + pickled = pickle.dumps(exc, pickle.HIGHEST_PROTOCOL) + + stdout.buffer.write(b"%s %d\n" % (status, len(pickled))) + stdout.buffer.write(pickled) + + # Respect SIGTERM + if isinstance(exception, SystemExit): + raise exception + + +if __name__ == "__main__": + process_worker() diff --git a/venv/lib/python3.10/site-packages/anyio/to_thread.py b/venv/lib/python3.10/site-packages/anyio/to_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..5070516eb56679f863bd446c97cf76376d80d83b --- /dev/null +++ b/venv/lib/python3.10/site-packages/anyio/to_thread.py @@ -0,0 +1,69 @@ +from __future__ import annotations + +import sys +from collections.abc import Callable +from typing import TypeVar +from warnings import warn + +from ._core._eventloop import get_async_backend +from .abc import CapacityLimiter + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + + +async def run_sync( + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + abandon_on_cancel: bool = False, + cancellable: bool | None = None, + limiter: CapacityLimiter | None = None, +) -> T_Retval: + """ + Call the given function with the given arguments in a worker thread. + + If the ``cancellable`` option is enabled and the task waiting for its completion is + cancelled, the thread will still run its course but its return value (or any raised + exception) will be ignored. + + :param func: a callable + :param args: positional arguments for the callable + :param abandon_on_cancel: ``True`` to abandon the thread (leaving it to run + unchecked on own) if the host task is cancelled, ``False`` to ignore + cancellations in the host task until the operation has completed in the worker + thread + :param cancellable: deprecated alias of ``abandon_on_cancel``; will override + ``abandon_on_cancel`` if both parameters are passed + :param limiter: capacity limiter to use to limit the total amount of threads running + (if omitted, the default limiter is used) + :return: an awaitable that yields the return value of the function. + + """ + if cancellable is not None: + abandon_on_cancel = cancellable + warn( + "The `cancellable=` keyword argument to `anyio.to_thread.run_sync` is " + "deprecated since AnyIO 4.1.0; use `abandon_on_cancel=` instead", + DeprecationWarning, + stacklevel=2, + ) + + return await get_async_backend().run_sync_in_worker_thread( + func, args, abandon_on_cancel=abandon_on_cancel, limiter=limiter + ) + + +def current_default_thread_limiter() -> CapacityLimiter: + """ + Return the capacity limiter that is used by default to limit the number of + concurrent threads. + + :return: a capacity limiter object + + """ + return get_async_backend().current_default_thread_limiter() diff --git a/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/METADATA b/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..65b5577fb0287469326c26db4927db9c28317161 --- /dev/null +++ b/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/METADATA @@ -0,0 +1,750 @@ +Metadata-Version: 2.4 +Name: charset-normalizer +Version: 3.4.3 +Summary: The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet. +Author-email: "Ahmed R. TAHRI" +Maintainer-email: "Ahmed R. TAHRI" +License: MIT +Project-URL: Changelog, https://github.com/jawah/charset_normalizer/blob/master/CHANGELOG.md +Project-URL: Documentation, https://charset-normalizer.readthedocs.io/ +Project-URL: Code, https://github.com/jawah/charset_normalizer +Project-URL: Issue tracker, https://github.com/jawah/charset_normalizer/issues +Keywords: encoding,charset,charset-detector,detector,normalization,unicode,chardet,detect +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +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.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Text Processing :: Linguistic +Classifier: Topic :: Utilities +Classifier: Typing :: Typed +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE +Provides-Extra: unicode-backport +Dynamic: license-file + +

Charset Detection, for Everyone 👋

+ +

+ The Real First Universal Charset Detector
+ + + + + Download Count Total + + + + +

+

+ Featured Packages
+ + Static Badge + + + Static Badge + +

+

+ In other language (unofficial port - by the community)
+ + Static Badge + +

+ +> A library that helps you read text from an unknown charset encoding.
Motivated by `chardet`, +> I'm trying to resolve the issue by taking a new approach. +> All IANA character set names for which the Python core library provides codecs are supported. + +

+ >>>>> 👉 Try Me Online Now, Then Adopt Me 👈 <<<<< +

+ +This project offers you an alternative to **Universal Charset Encoding Detector**, also known as **Chardet**. + +| Feature | [Chardet](https://github.com/chardet/chardet) | Charset Normalizer | [cChardet](https://github.com/PyYoshi/cChardet) | +|--------------------------------------------------|:---------------------------------------------:|:--------------------------------------------------------------------------------------------------:|:-----------------------------------------------:| +| `Fast` | ❌ | ✅ | ✅ | +| `Universal**` | ❌ | ✅ | ❌ | +| `Reliable` **without** distinguishable standards | ❌ | ✅ | ✅ | +| `Reliable` **with** distinguishable standards | ✅ | ✅ | ✅ | +| `License` | LGPL-2.1
_restrictive_ | MIT | MPL-1.1
_restrictive_ | +| `Native Python` | ✅ | ✅ | ❌ | +| `Detect spoken language` | ❌ | ✅ | N/A | +| `UnicodeDecodeError Safety` | ❌ | ✅ | ❌ | +| `Whl Size (min)` | 193.6 kB | 42 kB | ~200 kB | +| `Supported Encoding` | 33 | 🎉 [99](https://charset-normalizer.readthedocs.io/en/latest/user/support.html#supported-encodings) | 40 | + +

+Reading Normalized TextCat Reading Text +

+ +*\*\* : They are clearly using specific code for a specific encoding even if covering most of used one*
+ +## ⚡ Performance + +This package offer better performance than its counterpart Chardet. Here are some numbers. + +| Package | Accuracy | Mean per file (ms) | File per sec (est) | +|-----------------------------------------------|:--------:|:------------------:|:------------------:| +| [chardet](https://github.com/chardet/chardet) | 86 % | 63 ms | 16 file/sec | +| charset-normalizer | **98 %** | **10 ms** | 100 file/sec | + +| Package | 99th percentile | 95th percentile | 50th percentile | +|-----------------------------------------------|:---------------:|:---------------:|:---------------:| +| [chardet](https://github.com/chardet/chardet) | 265 ms | 71 ms | 7 ms | +| charset-normalizer | 100 ms | 50 ms | 5 ms | + +_updated as of december 2024 using CPython 3.12_ + +Chardet's performance on larger file (1MB+) are very poor. Expect huge difference on large payload. + +> Stats are generated using 400+ files using default parameters. More details on used files, see GHA workflows. +> And yes, these results might change at any time. The dataset can be updated to include more files. +> The actual delays heavily depends on your CPU capabilities. The factors should remain the same. +> Keep in mind that the stats are generous and that Chardet accuracy vs our is measured using Chardet initial capability +> (e.g. Supported Encoding) Challenge-them if you want. + +## ✨ Installation + +Using pip: + +```sh +pip install charset-normalizer -U +``` + +## 🚀 Basic Usage + +### CLI +This package comes with a CLI. + +``` +usage: normalizer [-h] [-v] [-a] [-n] [-m] [-r] [-f] [-t THRESHOLD] + file [file ...] + +The Real First Universal Charset Detector. Discover originating encoding used +on text file. Normalize text to unicode. + +positional arguments: + files File(s) to be analysed + +optional arguments: + -h, --help show this help message and exit + -v, --verbose Display complementary information about file if any. + Stdout will contain logs about the detection process. + -a, --with-alternative + Output complementary possibilities if any. Top-level + JSON WILL be a list. + -n, --normalize Permit to normalize input file. If not set, program + does not write anything. + -m, --minimal Only output the charset detected to STDOUT. Disabling + JSON output. + -r, --replace Replace file when trying to normalize it instead of + creating a new one. + -f, --force Replace file without asking if you are sure, use this + flag with caution. + -t THRESHOLD, --threshold THRESHOLD + Define a custom maximum amount of chaos allowed in + decoded content. 0. <= chaos <= 1. + --version Show version information and exit. +``` + +```bash +normalizer ./data/sample.1.fr.srt +``` + +or + +```bash +python -m charset_normalizer ./data/sample.1.fr.srt +``` + +🎉 Since version 1.4.0 the CLI produce easily usable stdout result in JSON format. + +```json +{ + "path": "/home/default/projects/charset_normalizer/data/sample.1.fr.srt", + "encoding": "cp1252", + "encoding_aliases": [ + "1252", + "windows_1252" + ], + "alternative_encodings": [ + "cp1254", + "cp1256", + "cp1258", + "iso8859_14", + "iso8859_15", + "iso8859_16", + "iso8859_3", + "iso8859_9", + "latin_1", + "mbcs" + ], + "language": "French", + "alphabets": [ + "Basic Latin", + "Latin-1 Supplement" + ], + "has_sig_or_bom": false, + "chaos": 0.149, + "coherence": 97.152, + "unicode_path": null, + "is_preferred": true +} +``` + +### Python +*Just print out normalized text* +```python +from charset_normalizer import from_path + +results = from_path('./my_subtitle.srt') + +print(str(results.best())) +``` + +*Upgrade your code without effort* +```python +from charset_normalizer import detect +``` + +The above code will behave the same as **chardet**. We ensure that we offer the best (reasonable) BC result possible. + +See the docs for advanced usage : [readthedocs.io](https://charset-normalizer.readthedocs.io/en/latest/) + +## 😇 Why + +When I started using Chardet, I noticed that it was not suited to my expectations, and I wanted to propose a +reliable alternative using a completely different method. Also! I never back down on a good challenge! + +I **don't care** about the **originating charset** encoding, because **two different tables** can +produce **two identical rendered string.** +What I want is to get readable text, the best I can. + +In a way, **I'm brute forcing text decoding.** How cool is that ? 😎 + +Don't confuse package **ftfy** with charset-normalizer or chardet. ftfy goal is to repair Unicode string whereas charset-normalizer to convert raw file in unknown encoding to unicode. + +## 🍰 How + + - Discard all charset encoding table that could not fit the binary content. + - Measure noise, or the mess once opened (by chunks) with a corresponding charset encoding. + - Extract matches with the lowest mess detected. + - Additionally, we measure coherence / probe for a language. + +**Wait a minute**, what is noise/mess and coherence according to **YOU ?** + +*Noise :* I opened hundred of text files, **written by humans**, with the wrong encoding table. **I observed**, then +**I established** some ground rules about **what is obvious** when **it seems like** a mess (aka. defining noise in rendered text). + I know that my interpretation of what is noise is probably incomplete, feel free to contribute in order to + improve or rewrite it. + +*Coherence :* For each language there is on earth, we have computed ranked letter appearance occurrences (the best we can). So I thought +that intel is worth something here. So I use those records against decoded text to check if I can detect intelligent design. + +## ⚡ Known limitations + + - Language detection is unreliable when text contains two or more languages sharing identical letters. (eg. HTML (english tags) + Turkish content (Sharing Latin characters)) + - Every charset detector heavily depends on sufficient content. In common cases, do not bother run detection on very tiny content. + +## ⚠️ About Python EOLs + +**If you are running:** + +- Python >=2.7,<3.5: Unsupported +- Python 3.5: charset-normalizer < 2.1 +- Python 3.6: charset-normalizer < 3.1 +- Python 3.7: charset-normalizer < 4.0 + +Upgrade your Python interpreter as soon as possible. + +## 👤 Contributing + +Contributions, issues and feature requests are very much welcome.
+Feel free to check [issues page](https://github.com/ousret/charset_normalizer/issues) if you want to contribute. + +## 📝 License + +Copyright © [Ahmed TAHRI @Ousret](https://github.com/Ousret).
+This project is [MIT](https://github.com/Ousret/charset_normalizer/blob/master/LICENSE) licensed. + +Characters frequencies used in this project © 2012 [Denny Vrandečić](http://simia.net/letters/) + +## 💼 For Enterprise + +Professional support for charset-normalizer is available as part of the [Tidelift +Subscription][1]. Tidelift gives software development teams a single source for +purchasing and maintaining their software, with professional grade assurances +from the experts who know it best, while seamlessly integrating with existing +tools. + +[1]: https://tidelift.com/subscription/pkg/pypi-charset-normalizer?utm_source=pypi-charset-normalizer&utm_medium=readme + +[![OpenSSF Best Practices](https://www.bestpractices.dev/projects/7297/badge)](https://www.bestpractices.dev/projects/7297) + +# Changelog +All notable changes to charset-normalizer will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +## [3.4.3](https://github.com/Ousret/charset_normalizer/compare/3.4.2...3.4.3) (2025-08-09) + +### Changed +- mypy(c) is no longer a required dependency at build time if `CHARSET_NORMALIZER_USE_MYPYC` isn't set to `1`. (#595) (#583) +- automatically lower confidence on small bytes samples that are not Unicode in `detect` output legacy function. (#391) + +### Added +- Custom build backend to overcome inability to mark mypy as an optional dependency in the build phase. +- Support for Python 3.14 + +### Fixed +- sdist archive contained useless directories. +- automatically fallback on valid UTF-16 or UTF-32 even if the md says it's noisy. (#633) + +### Misc +- SBOM are automatically published to the relevant GitHub release to comply with regulatory changes. + Each published wheel comes with its SBOM. We choose CycloneDX as the format. +- Prebuilt optimized wheel are no longer distributed by default for CPython 3.7 due to a change in cibuildwheel. + +## [3.4.2](https://github.com/Ousret/charset_normalizer/compare/3.4.1...3.4.2) (2025-05-02) + +### Fixed +- Addressed the DeprecationWarning in our CLI regarding `argparse.FileType` by backporting the target class into the package. (#591) +- Improved the overall reliability of the detector with CJK Ideographs. (#605) (#587) + +### Changed +- Optional mypyc compilation upgraded to version 1.15 for Python >= 3.8 + +## [3.4.1](https://github.com/Ousret/charset_normalizer/compare/3.4.0...3.4.1) (2024-12-24) + +### Changed +- Project metadata are now stored using `pyproject.toml` instead of `setup.cfg` using setuptools as the build backend. +- Enforce annotation delayed loading for a simpler and consistent types in the project. +- Optional mypyc compilation upgraded to version 1.14 for Python >= 3.8 + +### Added +- pre-commit configuration. +- noxfile. + +### Removed +- `build-requirements.txt` as per using `pyproject.toml` native build configuration. +- `bin/integration.py` and `bin/serve.py` in favor of downstream integration test (see noxfile). +- `setup.cfg` in favor of `pyproject.toml` metadata configuration. +- Unused `utils.range_scan` function. + +### Fixed +- Converting content to Unicode bytes may insert `utf_8` instead of preferred `utf-8`. (#572) +- Deprecation warning "'count' is passed as positional argument" when converting to Unicode bytes on Python 3.13+ + +## [3.4.0](https://github.com/Ousret/charset_normalizer/compare/3.3.2...3.4.0) (2024-10-08) + +### Added +- Argument `--no-preemptive` in the CLI to prevent the detector to search for hints. +- Support for Python 3.13 (#512) + +### Fixed +- Relax the TypeError exception thrown when trying to compare a CharsetMatch with anything else than a CharsetMatch. +- Improved the general reliability of the detector based on user feedbacks. (#520) (#509) (#498) (#407) (#537) +- Declared charset in content (preemptive detection) not changed when converting to utf-8 bytes. (#381) + +## [3.3.2](https://github.com/Ousret/charset_normalizer/compare/3.3.1...3.3.2) (2023-10-31) + +### Fixed +- Unintentional memory usage regression when using large payload that match several encoding (#376) +- Regression on some detection case showcased in the documentation (#371) + +### Added +- Noise (md) probe that identify malformed arabic representation due to the presence of letters in isolated form (credit to my wife) + +## [3.3.1](https://github.com/Ousret/charset_normalizer/compare/3.3.0...3.3.1) (2023-10-22) + +### Changed +- Optional mypyc compilation upgraded to version 1.6.1 for Python >= 3.8 +- Improved the general detection reliability based on reports from the community + +## [3.3.0](https://github.com/Ousret/charset_normalizer/compare/3.2.0...3.3.0) (2023-09-30) + +### Added +- Allow to execute the CLI (e.g. normalizer) through `python -m charset_normalizer.cli` or `python -m charset_normalizer` +- Support for 9 forgotten encoding that are supported by Python but unlisted in `encoding.aliases` as they have no alias (#323) + +### Removed +- (internal) Redundant utils.is_ascii function and unused function is_private_use_only +- (internal) charset_normalizer.assets is moved inside charset_normalizer.constant + +### Changed +- (internal) Unicode code blocks in constants are updated using the latest v15.0.0 definition to improve detection +- Optional mypyc compilation upgraded to version 1.5.1 for Python >= 3.8 + +### Fixed +- Unable to properly sort CharsetMatch when both chaos/noise and coherence were close due to an unreachable condition in \_\_lt\_\_ (#350) + +## [3.2.0](https://github.com/Ousret/charset_normalizer/compare/3.1.0...3.2.0) (2023-06-07) + +### Changed +- Typehint for function `from_path` no longer enforce `PathLike` as its first argument +- Minor improvement over the global detection reliability + +### Added +- Introduce function `is_binary` that relies on main capabilities, and optimized to detect binaries +- Propagate `enable_fallback` argument throughout `from_bytes`, `from_path`, and `from_fp` that allow a deeper control over the detection (default True) +- Explicit support for Python 3.12 + +### Fixed +- Edge case detection failure where a file would contain 'very-long' camel cased word (Issue #289) + +## [3.1.0](https://github.com/Ousret/charset_normalizer/compare/3.0.1...3.1.0) (2023-03-06) + +### Added +- Argument `should_rename_legacy` for legacy function `detect` and disregard any new arguments without errors (PR #262) + +### Removed +- Support for Python 3.6 (PR #260) + +### Changed +- Optional speedup provided by mypy/c 1.0.1 + +## [3.0.1](https://github.com/Ousret/charset_normalizer/compare/3.0.0...3.0.1) (2022-11-18) + +### Fixed +- Multi-bytes cutter/chunk generator did not always cut correctly (PR #233) + +### Changed +- Speedup provided by mypy/c 0.990 on Python >= 3.7 + +## [3.0.0](https://github.com/Ousret/charset_normalizer/compare/2.1.1...3.0.0) (2022-10-20) + +### Added +- Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results +- Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES +- Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio +- `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl) + +### Changed +- Build with static metadata using 'build' frontend +- Make the language detection stricter +- Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1 + +### Fixed +- CLI with opt --normalize fail when using full path for files +- TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it +- Sphinx warnings when generating the documentation + +### Removed +- Coherence detector no longer return 'Simple English' instead return 'English' +- Coherence detector no longer return 'Classical Chinese' instead return 'Chinese' +- Breaking: Method `first()` and `best()` from CharsetMatch +- UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII) +- Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches +- Breaking: Top-level function `normalize` +- Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch +- Support for the backport `unicodedata2` + +## [3.0.0rc1](https://github.com/Ousret/charset_normalizer/compare/3.0.0b2...3.0.0rc1) (2022-10-18) + +### Added +- Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results +- Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES +- Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio + +### Changed +- Build with static metadata using 'build' frontend +- Make the language detection stricter + +### Fixed +- CLI with opt --normalize fail when using full path for files +- TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it + +### Removed +- Coherence detector no longer return 'Simple English' instead return 'English' +- Coherence detector no longer return 'Classical Chinese' instead return 'Chinese' + +## [3.0.0b2](https://github.com/Ousret/charset_normalizer/compare/3.0.0b1...3.0.0b2) (2022-08-21) + +### Added +- `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl) + +### Removed +- Breaking: Method `first()` and `best()` from CharsetMatch +- UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII) + +### Fixed +- Sphinx warnings when generating the documentation + +## [3.0.0b1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...3.0.0b1) (2022-08-15) + +### Changed +- Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1 + +### Removed +- Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches +- Breaking: Top-level function `normalize` +- Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch +- Support for the backport `unicodedata2` + +## [2.1.1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...2.1.1) (2022-08-19) + +### Deprecated +- Function `normalize` scheduled for removal in 3.0 + +### Changed +- Removed useless call to decode in fn is_unprintable (#206) + +### Fixed +- Third-party library (i18n xgettext) crashing not recognizing utf_8 (PEP 263) with underscore from [@aleksandernovikov](https://github.com/aleksandernovikov) (#204) + +## [2.1.0](https://github.com/Ousret/charset_normalizer/compare/2.0.12...2.1.0) (2022-06-19) + +### Added +- Output the Unicode table version when running the CLI with `--version` (PR #194) + +### Changed +- Re-use decoded buffer for single byte character sets from [@nijel](https://github.com/nijel) (PR #175) +- Fixing some performance bottlenecks from [@deedy5](https://github.com/deedy5) (PR #183) + +### Fixed +- Workaround potential bug in cpython with Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space (PR #175) +- CLI default threshold aligned with the API threshold from [@oleksandr-kuzmenko](https://github.com/oleksandr-kuzmenko) (PR #181) + +### Removed +- Support for Python 3.5 (PR #192) + +### Deprecated +- Use of backport unicodedata from `unicodedata2` as Python is quickly catching up, scheduled for removal in 3.0 (PR #194) + +## [2.0.12](https://github.com/Ousret/charset_normalizer/compare/2.0.11...2.0.12) (2022-02-12) + +### Fixed +- ASCII miss-detection on rare cases (PR #170) + +## [2.0.11](https://github.com/Ousret/charset_normalizer/compare/2.0.10...2.0.11) (2022-01-30) + +### Added +- Explicit support for Python 3.11 (PR #164) + +### Changed +- The logging behavior have been completely reviewed, now using only TRACE and DEBUG levels (PR #163 #165) + +## [2.0.10](https://github.com/Ousret/charset_normalizer/compare/2.0.9...2.0.10) (2022-01-04) + +### Fixed +- Fallback match entries might lead to UnicodeDecodeError for large bytes sequence (PR #154) + +### Changed +- Skipping the language-detection (CD) on ASCII (PR #155) + +## [2.0.9](https://github.com/Ousret/charset_normalizer/compare/2.0.8...2.0.9) (2021-12-03) + +### Changed +- Moderating the logging impact (since 2.0.8) for specific environments (PR #147) + +### Fixed +- Wrong logging level applied when setting kwarg `explain` to True (PR #146) + +## [2.0.8](https://github.com/Ousret/charset_normalizer/compare/2.0.7...2.0.8) (2021-11-24) +### Changed +- Improvement over Vietnamese detection (PR #126) +- MD improvement on trailing data and long foreign (non-pure latin) data (PR #124) +- Efficiency improvements in cd/alphabet_languages from [@adbar](https://github.com/adbar) (PR #122) +- call sum() without an intermediary list following PEP 289 recommendations from [@adbar](https://github.com/adbar) (PR #129) +- Code style as refactored by Sourcery-AI (PR #131) +- Minor adjustment on the MD around european words (PR #133) +- Remove and replace SRTs from assets / tests (PR #139) +- Initialize the library logger with a `NullHandler` by default from [@nmaynes](https://github.com/nmaynes) (PR #135) +- Setting kwarg `explain` to True will add provisionally (bounded to function lifespan) a specific stream handler (PR #135) + +### Fixed +- Fix large (misleading) sequence giving UnicodeDecodeError (PR #137) +- Avoid using too insignificant chunk (PR #137) + +### Added +- Add and expose function `set_logging_handler` to configure a specific StreamHandler from [@nmaynes](https://github.com/nmaynes) (PR #135) +- Add `CHANGELOG.md` entries, format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) (PR #141) + +## [2.0.7](https://github.com/Ousret/charset_normalizer/compare/2.0.6...2.0.7) (2021-10-11) +### Added +- Add support for Kazakh (Cyrillic) language detection (PR #109) + +### Changed +- Further, improve inferring the language from a given single-byte code page (PR #112) +- Vainly trying to leverage PEP263 when PEP3120 is not supported (PR #116) +- Refactoring for potential performance improvements in loops from [@adbar](https://github.com/adbar) (PR #113) +- Various detection improvement (MD+CD) (PR #117) + +### Removed +- Remove redundant logging entry about detected language(s) (PR #115) + +### Fixed +- Fix a minor inconsistency between Python 3.5 and other versions regarding language detection (PR #117 #102) + +## [2.0.6](https://github.com/Ousret/charset_normalizer/compare/2.0.5...2.0.6) (2021-09-18) +### Fixed +- Unforeseen regression with the loss of the backward-compatibility with some older minor of Python 3.5.x (PR #100) +- Fix CLI crash when using --minimal output in certain cases (PR #103) + +### Changed +- Minor improvement to the detection efficiency (less than 1%) (PR #106 #101) + +## [2.0.5](https://github.com/Ousret/charset_normalizer/compare/2.0.4...2.0.5) (2021-09-14) +### Changed +- The project now comply with: flake8, mypy, isort and black to ensure a better overall quality (PR #81) +- The BC-support with v1.x was improved, the old staticmethods are restored (PR #82) +- The Unicode detection is slightly improved (PR #93) +- Add syntax sugar \_\_bool\_\_ for results CharsetMatches list-container (PR #91) + +### Removed +- The project no longer raise warning on tiny content given for detection, will be simply logged as warning instead (PR #92) + +### Fixed +- In some rare case, the chunks extractor could cut in the middle of a multi-byte character and could mislead the mess detection (PR #95) +- Some rare 'space' characters could trip up the UnprintablePlugin/Mess detection (PR #96) +- The MANIFEST.in was not exhaustive (PR #78) + +## [2.0.4](https://github.com/Ousret/charset_normalizer/compare/2.0.3...2.0.4) (2021-07-30) +### Fixed +- The CLI no longer raise an unexpected exception when no encoding has been found (PR #70) +- Fix accessing the 'alphabets' property when the payload contains surrogate characters (PR #68) +- The logger could mislead (explain=True) on detected languages and the impact of one MBCS match (PR #72) +- Submatch factoring could be wrong in rare edge cases (PR #72) +- Multiple files given to the CLI were ignored when publishing results to STDOUT. (After the first path) (PR #72) +- Fix line endings from CRLF to LF for certain project files (PR #67) + +### Changed +- Adjust the MD to lower the sensitivity, thus improving the global detection reliability (PR #69 #76) +- Allow fallback on specified encoding if any (PR #71) + +## [2.0.3](https://github.com/Ousret/charset_normalizer/compare/2.0.2...2.0.3) (2021-07-16) +### Changed +- Part of the detection mechanism has been improved to be less sensitive, resulting in more accurate detection results. Especially ASCII. (PR #63) +- According to the community wishes, the detection will fall back on ASCII or UTF-8 in a last-resort case. (PR #64) + +## [2.0.2](https://github.com/Ousret/charset_normalizer/compare/2.0.1...2.0.2) (2021-07-15) +### Fixed +- Empty/Too small JSON payload miss-detection fixed. Report from [@tseaver](https://github.com/tseaver) (PR #59) + +### Changed +- Don't inject unicodedata2 into sys.modules from [@akx](https://github.com/akx) (PR #57) + +## [2.0.1](https://github.com/Ousret/charset_normalizer/compare/2.0.0...2.0.1) (2021-07-13) +### Fixed +- Make it work where there isn't a filesystem available, dropping assets frequencies.json. Report from [@sethmlarson](https://github.com/sethmlarson). (PR #55) +- Using explain=False permanently disable the verbose output in the current runtime (PR #47) +- One log entry (language target preemptive) was not show in logs when using explain=True (PR #47) +- Fix undesired exception (ValueError) on getitem of instance CharsetMatches (PR #52) + +### Changed +- Public function normalize default args values were not aligned with from_bytes (PR #53) + +### Added +- You may now use charset aliases in cp_isolation and cp_exclusion arguments (PR #47) + +## [2.0.0](https://github.com/Ousret/charset_normalizer/compare/1.4.1...2.0.0) (2021-07-02) +### Changed +- 4x to 5 times faster than the previous 1.4.0 release. At least 2x faster than Chardet. +- Accent has been made on UTF-8 detection, should perform rather instantaneous. +- The backward compatibility with Chardet has been greatly improved. The legacy detect function returns an identical charset name whenever possible. +- The detection mechanism has been slightly improved, now Turkish content is detected correctly (most of the time) +- The program has been rewritten to ease the readability and maintainability. (+Using static typing)+ +- utf_7 detection has been reinstated. + +### Removed +- This package no longer require anything when used with Python 3.5 (Dropped cached_property) +- Removed support for these languages: Catalan, Esperanto, Kazakh, Baque, Volapük, Azeri, Galician, Nynorsk, Macedonian, and Serbocroatian. +- The exception hook on UnicodeDecodeError has been removed. + +### Deprecated +- Methods coherence_non_latin, w_counter, chaos_secondary_pass of the class CharsetMatch are now deprecated and scheduled for removal in v3.0 + +### Fixed +- The CLI output used the relative path of the file(s). Should be absolute. + +## [1.4.1](https://github.com/Ousret/charset_normalizer/compare/1.4.0...1.4.1) (2021-05-28) +### Fixed +- Logger configuration/usage no longer conflict with others (PR #44) + +## [1.4.0](https://github.com/Ousret/charset_normalizer/compare/1.3.9...1.4.0) (2021-05-21) +### Removed +- Using standard logging instead of using the package loguru. +- Dropping nose test framework in favor of the maintained pytest. +- Choose to not use dragonmapper package to help with gibberish Chinese/CJK text. +- Require cached_property only for Python 3.5 due to constraint. Dropping for every other interpreter version. +- Stop support for UTF-7 that does not contain a SIG. +- Dropping PrettyTable, replaced with pure JSON output in CLI. + +### Fixed +- BOM marker in a CharsetNormalizerMatch instance could be False in rare cases even if obviously present. Due to the sub-match factoring process. +- Not searching properly for the BOM when trying utf32/16 parent codec. + +### Changed +- Improving the package final size by compressing frequencies.json. +- Huge improvement over the larges payload. + +### Added +- CLI now produces JSON consumable output. +- Return ASCII if given sequences fit. Given reasonable confidence. + +## [1.3.9](https://github.com/Ousret/charset_normalizer/compare/1.3.8...1.3.9) (2021-05-13) + +### Fixed +- In some very rare cases, you may end up getting encode/decode errors due to a bad bytes payload (PR #40) + +## [1.3.8](https://github.com/Ousret/charset_normalizer/compare/1.3.7...1.3.8) (2021-05-12) + +### Fixed +- Empty given payload for detection may cause an exception if trying to access the `alphabets` property. (PR #39) + +## [1.3.7](https://github.com/Ousret/charset_normalizer/compare/1.3.6...1.3.7) (2021-05-12) + +### Fixed +- The legacy detect function should return UTF-8-SIG if sig is present in the payload. (PR #38) + +## [1.3.6](https://github.com/Ousret/charset_normalizer/compare/1.3.5...1.3.6) (2021-02-09) + +### Changed +- Amend the previous release to allow prettytable 2.0 (PR #35) + +## [1.3.5](https://github.com/Ousret/charset_normalizer/compare/1.3.4...1.3.5) (2021-02-08) + +### Fixed +- Fix error while using the package with a python pre-release interpreter (PR #33) + +### Changed +- Dependencies refactoring, constraints revised. + +### Added +- Add python 3.9 and 3.10 to the supported interpreters + +MIT License + +Copyright (c) 2025 TAHRI Ahmed R. + +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/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/RECORD b/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..c9772ac2cb8ff954625528e6bebcff62afc6e322 --- /dev/null +++ b/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/RECORD @@ -0,0 +1,35 @@ +../../../bin/normalizer,sha256=zEFC2Ql5ri9sExj1zd1J04dm9ULdxz5dqeQpSV0b3sY,303 +charset_normalizer-3.4.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +charset_normalizer-3.4.3.dist-info/METADATA,sha256=nBNOskPUtcqHtaSPPaJafjXrlicPcPIgLFzpJQTgvaA,36700 +charset_normalizer-3.4.3.dist-info/RECORD,, +charset_normalizer-3.4.3.dist-info/WHEEL,sha256=DZl4yYurviXJJQsilHH1qAzCRDsdz--oNtDZ-hUrZUk,190 +charset_normalizer-3.4.3.dist-info/entry_points.txt,sha256=ADSTKrkXZ3hhdOVFi6DcUEHQRS0xfxDIE_pEz4wLIXA,65 +charset_normalizer-3.4.3.dist-info/licenses/LICENSE,sha256=bQ1Bv-FwrGx9wkjJpj4lTQ-0WmDVCoJX0K-SxuJJuIc,1071 +charset_normalizer-3.4.3.dist-info/top_level.txt,sha256=7ASyzePr8_xuZWJsnqJjIBtyV8vhEo0wBCv1MPRRi3Q,19 +charset_normalizer/__init__.py,sha256=OKRxRv2Zhnqk00tqkN0c1BtJjm165fWXLydE52IKuHc,1590 +charset_normalizer/__main__.py,sha256=yzYxMR-IhKRHYwcSlavEv8oGdwxsR89mr2X09qXGdps,109 +charset_normalizer/__pycache__/__init__.cpython-310.pyc,, +charset_normalizer/__pycache__/__main__.cpython-310.pyc,, +charset_normalizer/__pycache__/api.cpython-310.pyc,, +charset_normalizer/__pycache__/cd.cpython-310.pyc,, +charset_normalizer/__pycache__/constant.cpython-310.pyc,, +charset_normalizer/__pycache__/legacy.cpython-310.pyc,, +charset_normalizer/__pycache__/md.cpython-310.pyc,, +charset_normalizer/__pycache__/models.cpython-310.pyc,, +charset_normalizer/__pycache__/utils.cpython-310.pyc,, +charset_normalizer/__pycache__/version.cpython-310.pyc,, +charset_normalizer/api.py,sha256=V07i8aVeCD8T2fSia3C-fn0i9t8qQguEBhsqszg32Ns,22668 +charset_normalizer/cd.py,sha256=WKTo1HDb-H9HfCDc3Bfwq5jzS25Ziy9SE2a74SgTq88,12522 +charset_normalizer/cli/__init__.py,sha256=D8I86lFk2-py45JvqxniTirSj_sFyE6sjaY_0-G1shc,136 +charset_normalizer/cli/__main__.py,sha256=dMaXG6IJXRvqq8z2tig7Qb83-BpWTln55ooiku5_uvg,12646 +charset_normalizer/cli/__pycache__/__init__.cpython-310.pyc,, +charset_normalizer/cli/__pycache__/__main__.cpython-310.pyc,, +charset_normalizer/constant.py,sha256=7UVY4ldYhmQMHUdgQ_sgZmzcQ0xxYxpBunqSZ-XJZ8U,42713 +charset_normalizer/legacy.py,sha256=sYBzSpzsRrg_wF4LP536pG64BItw7Tqtc3SMQAHvFLM,2731 +charset_normalizer/md.cpython-310-x86_64-linux-gnu.so,sha256=vmQPHNPc6Z0rbXxiiMeoCQxfjjh5z8umtRgKpBckk7E,15912 +charset_normalizer/md.py,sha256=-_oN3h3_X99nkFfqamD3yu45DC_wfk5odH0Tr_CQiXs,20145 +charset_normalizer/md__mypyc.cpython-310-x86_64-linux-gnu.so,sha256=6vJ-8gj4dFddrnQJgzsnRFgS3SPDgRhOW6mT_hM63hU,285360 +charset_normalizer/models.py,sha256=lKXhOnIPtiakbK3i__J9wpOfzx3JDTKj7Dn3Rg0VaRI,12394 +charset_normalizer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +charset_normalizer/utils.py,sha256=sTejPgrdlNsKNucZfJCxJ95lMTLA0ShHLLE3n5wpT9Q,12170 +charset_normalizer/version.py,sha256=hBN3id1io4HMVPtyDn9IIRVShbBM0kgVs3haVtppZOE,115 diff --git a/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/WHEEL b/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..6d6bf82d678c683effaf22b612f4dea70dd9933d --- /dev/null +++ b/venv/lib/python3.10/site-packages/charset_normalizer-3.4.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/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/entry_points.txt b/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..65619e73ec06c20c2a70c9507b872ad624d1a85c --- /dev/null +++ b/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +normalizer = charset_normalizer.cli:cli_detect diff --git a/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9725772c7967075d97dc78d60f3735435eccba63 --- /dev/null +++ b/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 TAHRI Ahmed R. + +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/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..66958f0a069d7aea7939bed40b9197608e93b243 --- /dev/null +++ b/venv/lib/python3.10/site-packages/charset_normalizer-3.4.3.dist-info/top_level.txt @@ -0,0 +1 @@ +charset_normalizer diff --git a/venv/lib/python3.10/site-packages/click-8.2.1.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/click-8.2.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/click-8.2.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/click-8.2.1.dist-info/METADATA b/venv/lib/python3.10/site-packages/click-8.2.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..e6c05af4a78cabdf5689f3f6f7fd57304d8a0eb1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/click-8.2.1.dist-info/METADATA @@ -0,0 +1,82 @@ +Metadata-Version: 2.4 +Name: click +Version: 8.2.1 +Summary: Composable command line interface toolkit +Maintainer-email: Pallets +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-Expression: BSD-3-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Typing :: Typed +License-File: LICENSE.txt +Requires-Dist: colorama; platform_system == 'Windows' +Project-URL: Changes, https://click.palletsprojects.com/page/changes/ +Project-URL: Chat, https://discord.gg/pallets +Project-URL: Documentation, https://click.palletsprojects.com/ +Project-URL: Donate, https://palletsprojects.com/donate +Project-URL: Source, https://github.com/pallets/click/ + +# $ click_ + +Click is a Python package for creating beautiful command line interfaces +in a composable way with as little code as necessary. It's the "Command +Line Interface Creation Kit". It's highly configurable but comes with +sensible defaults out of the box. + +It aims to make the process of writing command line tools quick and fun +while also preventing any frustration caused by the inability to +implement an intended CLI API. + +Click in three points: + +- Arbitrary nesting of commands +- Automatic help page generation +- Supports lazy loading of subcommands at runtime + + +## A Simple Example + +```python +import click + +@click.command() +@click.option("--count", default=1, help="Number of greetings.") +@click.option("--name", prompt="Your name", help="The person to greet.") +def hello(count, name): + """Simple program that greets NAME for a total of COUNT times.""" + for _ in range(count): + click.echo(f"Hello, {name}!") + +if __name__ == '__main__': + hello() +``` + +``` +$ python hello.py --count=3 +Your name: Click +Hello, Click! +Hello, Click! +Hello, Click! +``` + + +## Donate + +The Pallets organization develops and supports Click and other popular +packages. In order to grow the community of contributors and users, and +allow the maintainers to devote more time to the projects, [please +donate today][]. + +[please donate today]: https://palletsprojects.com/donate + +## Contributing + +See our [detailed contributing documentation][contrib] for many ways to +contribute, including reporting issues, requesting features, asking or answering +questions, and making PRs. + +[contrib]: https://palletsprojects.com/contributing/ + diff --git a/venv/lib/python3.10/site-packages/click-8.2.1.dist-info/RECORD b/venv/lib/python3.10/site-packages/click-8.2.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..621f456cf0d0bd3be7c24c3f098842cf5370131b --- /dev/null +++ b/venv/lib/python3.10/site-packages/click-8.2.1.dist-info/RECORD @@ -0,0 +1,38 @@ +click-8.2.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +click-8.2.1.dist-info/METADATA,sha256=dI1MbhHTLoKD2tNCCGnx9rK2gok23HDNylFeLKdLSik,2471 +click-8.2.1.dist-info/RECORD,, +click-8.2.1.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +click-8.2.1.dist-info/licenses/LICENSE.txt,sha256=morRBqOU6FO_4h9C9OctWSgZoigF2ZG18ydQKSkrZY0,1475 +click/__init__.py,sha256=6YyS1aeyknZ0LYweWozNZy0A9nZ_11wmYIhv3cbQrYo,4473 +click/__pycache__/__init__.cpython-310.pyc,, +click/__pycache__/_compat.cpython-310.pyc,, +click/__pycache__/_termui_impl.cpython-310.pyc,, +click/__pycache__/_textwrap.cpython-310.pyc,, +click/__pycache__/_winconsole.cpython-310.pyc,, +click/__pycache__/core.cpython-310.pyc,, +click/__pycache__/decorators.cpython-310.pyc,, +click/__pycache__/exceptions.cpython-310.pyc,, +click/__pycache__/formatting.cpython-310.pyc,, +click/__pycache__/globals.cpython-310.pyc,, +click/__pycache__/parser.cpython-310.pyc,, +click/__pycache__/shell_completion.cpython-310.pyc,, +click/__pycache__/termui.cpython-310.pyc,, +click/__pycache__/testing.cpython-310.pyc,, +click/__pycache__/types.cpython-310.pyc,, +click/__pycache__/utils.cpython-310.pyc,, +click/_compat.py,sha256=v3xBZkFbvA1BXPRkFfBJc6-pIwPI7345m-kQEnpVAs4,18693 +click/_termui_impl.py,sha256=ASXhLi9IQIc0Js9KQSS-3-SLZcPet3VqysBf9WgbbpI,26712 +click/_textwrap.py,sha256=BOae0RQ6vg3FkNgSJyOoGzG1meGMxJ_ukWVZKx_v-0o,1400 +click/_winconsole.py,sha256=_vxUuUaxwBhoR0vUWCNuHY8VUefiMdCIyU2SXPqoF-A,8465 +click/core.py,sha256=gUhpNS9cFBGdEXXdisGVG-eRvGf49RTyFagxulqwdFw,117343 +click/decorators.py,sha256=5P7abhJtAQYp_KHgjUvhMv464ERwOzrv2enNknlwHyQ,18461 +click/exceptions.py,sha256=1rdtXgHJ1b3OjGkN-UpXB9t_HCBihJvh_DtpmLmwn9s,9891 +click/formatting.py,sha256=Bhqx4QXdKQ9W4WKknIwj5KPKFmtduGOuGq1yw_THLZ8,9726 +click/globals.py,sha256=gM-Nh6A4M0HB_SgkaF5M4ncGGMDHc_flHXu9_oh4GEU,1923 +click/parser.py,sha256=nU1Ah2p11q29ul1vNdU9swPo_PUuKrxU6YXToi71q1c,18979 +click/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +click/shell_completion.py,sha256=CQSGdjgun4ORbOZrXP0CVhEtPx4knsufOkRsDiK64cM,19857 +click/termui.py,sha256=vAYrKC2a7f_NfEIhAThEVYfa__ib5XQbTSCGtJlABRA,30847 +click/testing.py,sha256=2eLdAaCJCGToP5Tw-XN8JjrDb3wbJIfARxg3d0crW5M,18702 +click/types.py,sha256=KBTRxN28cR1VZ5mb9iJX98MQSw_p9SGzljqfEI8z5Tw,38389 +click/utils.py,sha256=b1Mm-usEDBHtEwcPltPIn3zSK4nw2KTp5GC7_oSTlLo,20245 diff --git a/venv/lib/python3.10/site-packages/click-8.2.1.dist-info/WHEEL b/venv/lib/python3.10/site-packages/click-8.2.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/venv/lib/python3.10/site-packages/click-8.2.1.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/venv/lib/python3.10/site-packages/click-8.2.1.dist-info/licenses/LICENSE.txt b/venv/lib/python3.10/site-packages/click-8.2.1.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..d12a849186982399c537c5b9a8fd77bf2edd5eab --- /dev/null +++ b/venv/lib/python3.10/site-packages/click-8.2.1.dist-info/licenses/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 2014 Pallets + +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. 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/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..9cbf7ce09d84ab7775b9473a64e602ab6d6fc273 --- /dev/null +++ b/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/METADATA @@ -0,0 +1,360 @@ +Metadata-Version: 2.1 +Name: einops +Version: 0.7.0 +Summary: A new flavour of deep learning operations +Project-URL: Homepage, https://github.com/arogozhnikov/einops +Author: Alex Rogozhnikov +License: MIT +License-File: LICENSE +Keywords: deep learning,einops,machine learning,neural networks,scientific computations,tensor manipulation +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Requires-Python: >=3.8 +Description-Content-Type: text/markdown + + + + + + +https://user-images.githubusercontent.com/6318811/177030658-66f0eb5d-e136-44d8-99c9-86ae298ead5b.mp4 + + + + +# einops +[![Run tests](https://github.com/arogozhnikov/einops/actions/workflows/run_tests.yml/badge.svg)](https://github.com/arogozhnikov/einops/actions/workflows/run_tests.yml) +[![PyPI version](https://badge.fury.io/py/einops.svg)](https://badge.fury.io/py/einops) +[![Documentation](https://img.shields.io/badge/documentation-link-blue.svg)](https://einops.rocks/) +![Supported python versions](https://raw.githubusercontent.com/arogozhnikov/einops/master/docs/resources/python_badge.svg) + + +Flexible and powerful tensor operations for readable and reliable code.
+Supports numpy, pytorch, tensorflow, jax, and [others](#supported-frameworks). + +## Recent updates: + +- 0.7.0: no-hassle `torch.compile`, support of [array api standard](https://data-apis.org/array-api/latest/API_specification/index.html) and more +- 10'000🎉: github reports that more than 10k project use einops +- see how to use einops with [torch.compile](https://github.com/arogozhnikov/einops/wiki/Using-torch.compile-with-einops) +- einops 0.6.1: paddle backend added +- einops 0.6 introduces [packing and unpacking](https://github.com/arogozhnikov/einops/blob/master/docs/4-pack-and-unpack.ipynb) +- einops 0.5: einsum is now a part of einops +- [Einops paper](https://openreview.net/pdf?id=oapKSVM2bcj) is accepted for oral presentation at ICLR 2022 (yes, it worth reading). + Talk recordings are [available](https://iclr.cc/virtual/2022/oral/6603) + + +
+Previous updates +- flax and oneflow backend added +- torch.jit.script is supported for pytorch layers +- powerful EinMix added to einops. [Einmix tutorial notebook](https://github.com/arogozhnikov/einops/blob/master/docs/3-einmix-layer.ipynb) +
+ + + +## Tweets + +> In case you need convincing arguments for setting aside time to learn about einsum and einops... +[Tim Rocktäschel, FAIR](https://twitter.com/_rockt/status/1230818967205425152) + +> Writing better code with PyTorch and einops 👌 +[Andrej Karpathy, AI at Tesla](https://twitter.com/karpathy/status/1290826075916779520) + +> Slowly but surely, einops is seeping in to every nook and cranny of my code. If you find yourself shuffling around bazillion dimensional tensors, this might change your life +[Nasim Rahaman, MILA (Montreal)](https://twitter.com/nasim_rahaman/status/1216022614755463169) + +[More testimonials](https://einops.rocks/pages/testimonials/) + + + +## Contents + +- [Installation](#Installation) +- [Documentation](https://einops.rocks/) +- [Tutorial](#Tutorials) +- [API micro-reference](#API) +- [Why using einops](#Why-using-einops-notation) +- [Supported frameworks](#Supported-frameworks) +- [Citing](#Citing) +- [Repository](https://github.com/arogozhnikov/einops) and [discussions](https://github.com/arogozhnikov/einops/discussions) + +## Installation + +Plain and simple: +```bash +pip install einops +``` + + + +## Tutorials + +Tutorials are the most convenient way to see `einops` in action + +- part 1: [einops fundamentals](https://github.com/arogozhnikov/einops/blob/master/docs/1-einops-basics.ipynb) +- part 2: [einops for deep learning](https://github.com/arogozhnikov/einops/blob/master/docs/2-einops-for-deep-learning.ipynb) +- part 3: [packing and unpacking](https://github.com/arogozhnikov/einops/blob/master/docs/4-pack-and-unpack.ipynb) +- part 4: [improve pytorch code with einops](http://einops.rocks/pytorch-examples.html) + +Kapil Sachdeva recorded a small [intro to einops](https://www.youtube.com/watch?v=xGy75Pjsqzo). + +## API + +`einops` has a minimalistic yet powerful API. + +Three core operations provided ([einops tutorial](https://github.com/arogozhnikov/einops/blob/master/docs/) +shows those cover stacking, reshape, transposition, squeeze/unsqueeze, repeat, tile, concatenate, view and numerous reductions) + +```python +from einops import rearrange, reduce, repeat +# rearrange elements according to the pattern +output_tensor = rearrange(input_tensor, 't b c -> b c t') +# combine rearrangement and reduction +output_tensor = reduce(input_tensor, 'b c (h h2) (w w2) -> b h w c', 'mean', h2=2, w2=2) +# copy along a new axis +output_tensor = repeat(input_tensor, 'h w -> h w c', c=3) +``` + +Later additions to the family are `pack` and `unpack` functions (better than stack/split/concatenate): + +```python +from einops import pack, unpack +# pack and unpack allow reversibly 'packing' multiple tensors into one. +# Packed tensors may be of different dimensionality: +packed, ps = pack([class_token_bc, image_tokens_bhwc, text_tokens_btc], 'b * c') +class_emb_bc, image_emb_bhwc, text_emb_btc = unpack(transformer(packed), ps, 'b * c') +``` + +Finally, einops provides einsum with a support of multi-lettered names: + +```python +from einops import einsum, pack, unpack +# einsum is like ... einsum, generic and flexible dot-product +# but 1) axes can be multi-lettered 2) pattern goes last 3) works with multiple frameworks +C = einsum(A, B, 'b t1 head c, b t2 head c -> b head t1 t2') +``` + +### EinMix + +`EinMix` is a generic linear layer, perfect for MLP Mixers and similar architectures. + +### Layers + +Einops provides layers (`einops` keeps a separate version for each framework) that reflect corresponding functions + +```python +from einops.layers.torch import Rearrange, Reduce +from einops.layers.tensorflow import Rearrange, Reduce +from einops.layers.flax import Rearrange, Reduce +from einops.layers.paddle import Rearrange, Reduce +from einops.layers.keras import Rearrange, Reduce +from einops.layers.chainer import Rearrange, Reduce +``` + +
+Example of using layers within a pytorch model +Example given for pytorch, but code in other frameworks is almost identical + +```python +from torch.nn import Sequential, Conv2d, MaxPool2d, Linear, ReLU +from einops.layers.torch import Rearrange + +model = Sequential( + ..., + Conv2d(6, 16, kernel_size=5), + MaxPool2d(kernel_size=2), + # flattening without need to write forward + Rearrange('b c h w -> b (c h w)'), + Linear(16*5*5, 120), + ReLU(), + Linear(120, 10), +) +``` + +No more flatten needed! + +Additionally, torch users will benefit from layers as those are script-able and compile-able. +
+ + + + +## Naming + +`einops` stands for Einstein-Inspired Notation for operations +(though "Einstein operations" is more attractive and easier to remember). + +Notation was loosely inspired by Einstein summation (in particular by `numpy.einsum` operation). + +## Why use `einops` notation?! + + +### Semantic information (being verbose in expectations) + +```python +y = x.view(x.shape[0], -1) +y = rearrange(x, 'b c h w -> b (c h w)') +``` +While these two lines are doing the same job in *some* context, +the second one provides information about the input and output. +In other words, `einops` focuses on interface: *what is the input and output*, not *how* the output is computed. + +The next operation looks similar: + +```python +y = rearrange(x, 'time c h w -> time (c h w)') +``` +but it gives the reader a hint: +this is not an independent batch of images we are processing, +but rather a sequence (video). + +Semantic information makes the code easier to read and maintain. + +### Convenient checks + +Reconsider the same example: + +```python +y = x.view(x.shape[0], -1) # x: (batch, 256, 19, 19) +y = rearrange(x, 'b c h w -> b (c h w)') +``` +The second line checks that the input has four dimensions, +but you can also specify particular dimensions. +That's opposed to just writing comments about shapes since comments don't prevent mistakes, not tested, and without code review tend to be outdated +```python +y = x.view(x.shape[0], -1) # x: (batch, 256, 19, 19) +y = rearrange(x, 'b c h w -> b (c h w)', c=256, h=19, w=19) +``` + +### Result is strictly determined + +Below we have at least two ways to define the depth-to-space operation +```python +# depth-to-space +rearrange(x, 'b c (h h2) (w w2) -> b (c h2 w2) h w', h2=2, w2=2) +rearrange(x, 'b c (h h2) (w w2) -> b (h2 w2 c) h w', h2=2, w2=2) +``` +There are at least four more ways to do it. Which one is used by the framework? + +These details are ignored, since *usually* it makes no difference, +but it can make a big difference (e.g. if you use grouped convolutions in the next stage), +and you'd like to specify this in your code. + + +### Uniformity + +```python +reduce(x, 'b c (x dx) -> b c x', 'max', dx=2) +reduce(x, 'b c (x dx) (y dy) -> b c x y', 'max', dx=2, dy=3) +reduce(x, 'b c (x dx) (y dy) (z dz) -> b c x y z', 'max', dx=2, dy=3, dz=4) +``` +These examples demonstrated that we don't use separate operations for 1d/2d/3d pooling, +those are all defined in a uniform way. + +Space-to-depth and depth-to space are defined in many frameworks but how about width-to-height? Here you go: + +```python +rearrange(x, 'b c h (w w2) -> b c (h w2) w', w2=2) +``` + +### Framework independent behavior + +Even simple functions are defined differently by different frameworks + +```python +y = x.flatten() # or flatten(x) +``` + +Suppose `x`'s shape was `(3, 4, 5)`, then `y` has shape ... + +- numpy, pytorch, cupy, chainer: `(60,)` +- keras, tensorflow.layers, gluon: `(3, 20)` + +`einops` works the same way in all frameworks. + +### Independence of framework terminology + +Example: `tile` vs `repeat` causes lots of confusion. To copy image along width: +```python +np.tile(image, (1, 2)) # in numpy +image.repeat(1, 2) # pytorch's repeat ~ numpy's tile +``` + +With einops you don't need to decipher which axis was repeated: +```python +repeat(image, 'h w -> h (tile w)', tile=2) # in numpy +repeat(image, 'h w -> h (tile w)', tile=2) # in pytorch +repeat(image, 'h w -> h (tile w)', tile=2) # in tf +repeat(image, 'h w -> h (tile w)', tile=2) # in jax +repeat(image, 'h w -> h (tile w)', tile=2) # in cupy +... (etc.) +``` + +[Testimonials](https://einops.rocks/pages/testimonials/) provide users' perspective on the same question. + +## Supported frameworks + +Einops works with ... + +- [numpy](http://www.numpy.org/) +- [pytorch](https://pytorch.org/) +- [tensorflow](https://www.tensorflow.org/) +- [jax](https://github.com/google/jax) +- [cupy](https://cupy.chainer.org/) +- [chainer](https://chainer.org/) +- [tf.keras](https://www.tensorflow.org/guide/keras) +- [oneflow](https://github.com/Oneflow-Inc/oneflow) (experimental) +- [flax](https://github.com/google/flax) (experimental) +- [paddle](https://github.com/PaddlePaddle/Paddle) (experimental) + +Additionally, starting from einops 0.7.0 einops can be used with any framework that supports [Python array API standard](https://data-apis.org/array-api/latest/API_specification/index.html) + +## Citing einops + +Please use the following bibtex record + +```text +@inproceedings{ + rogozhnikov2022einops, + title={Einops: Clear and Reliable Tensor Manipulations with Einstein-like Notation}, + author={Alex Rogozhnikov}, + booktitle={International Conference on Learning Representations}, + year={2022}, + url={https://openreview.net/forum?id=oapKSVM2bcj} +} +``` + + +## Supported python versions + +`einops` works with python 3.8 or later. diff --git a/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..49213191ec2109662bbf4c9c279f36b56c98894f --- /dev/null +++ b/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/RECORD @@ -0,0 +1,45 @@ +einops-0.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +einops-0.7.0.dist-info/METADATA,sha256=iiGuU5-2fSwfbC4q8Rm0bEvaA1WN3qslFMQJxnPUSKg,13078 +einops-0.7.0.dist-info/RECORD,, +einops-0.7.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +einops-0.7.0.dist-info/WHEEL,sha256=9QBuHhg6FNW7lppboF2vKVbCGTVzsFykgRQjjlajrhA,87 +einops-0.7.0.dist-info/licenses/LICENSE,sha256=MNmENkKW9R_67K1LAe4SfpUlDFBokY1LZvyWIGcj5DQ,1073 +einops/__init__.py,sha256=kmiFcK59IAAR7yoWBeIzca6vQqU0X_ITwt_Or6XakRo,388 +einops/__pycache__/__init__.cpython-310.pyc,, +einops/__pycache__/_backends.cpython-310.pyc,, +einops/__pycache__/_torch_specific.cpython-310.pyc,, +einops/__pycache__/array_api.cpython-310.pyc,, +einops/__pycache__/einops.cpython-310.pyc,, +einops/__pycache__/packing.cpython-310.pyc,, +einops/__pycache__/parsing.cpython-310.pyc,, +einops/_backends.py,sha256=e7faFZ1DrYEGHGC-JhPIBM1_npCnYgruwzM8pG6BcqE,19693 +einops/_torch_specific.py,sha256=c9V_pqU_ayd1UE8i1CaCTkOSMeRdlDLm3WDD5q0gsvY,4138 +einops/array_api.py,sha256=rhtT1_nMDj9IYMmvdGZd0oktYvV9r1OG7w-dAiGQeUg,5211 +einops/einops.py,sha256=1Y4AW4htn2rk0jAyBxoW-CtAxZLAbxmEeDZQFx81jN0,36808 +einops/experimental/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +einops/experimental/__pycache__/__init__.cpython-310.pyc,, +einops/experimental/__pycache__/data_api_packing.cpython-310.pyc,, +einops/experimental/__pycache__/indexing.cpython-310.pyc,, +einops/experimental/data_api_packing.py,sha256=CKCxtqMek1T6BlBM6OkG4YvaynFmdWgVEvbPTDZ6DqE,4690 +einops/experimental/indexing.py,sha256=f4d3lVVuS0bzGKYczlpk3Y5U_kk6_AWt887i_2qzjv4,14777 +einops/layers/__init__.py,sha256=n5FI4v2Zs2qLeI1FuuK_7AfyauRiVtsnQTw0c_mr0IM,3747 +einops/layers/__pycache__/__init__.cpython-310.pyc,, +einops/layers/__pycache__/_einmix.cpython-310.pyc,, +einops/layers/__pycache__/chainer.cpython-310.pyc,, +einops/layers/__pycache__/flax.cpython-310.pyc,, +einops/layers/__pycache__/keras.cpython-310.pyc,, +einops/layers/__pycache__/oneflow.cpython-310.pyc,, +einops/layers/__pycache__/paddle.cpython-310.pyc,, +einops/layers/__pycache__/tensorflow.cpython-310.pyc,, +einops/layers/__pycache__/torch.cpython-310.pyc,, +einops/layers/_einmix.py,sha256=szayQWYvJzCwOhdfXJY72A7EtBYrNc91nzvOm-uMREs,8578 +einops/layers/chainer.py,sha256=BPvzqGV9-3xpoXHsVfkIR5wbsvmN0QnPJXY_mdsD2Dk,1981 +einops/layers/flax.py,sha256=rTgGl4HvCwhIoJYLhjpCG_nB3aWC3xGHV7v7q8a2qe8,2621 +einops/layers/keras.py,sha256=RTsR-aim1Sco5VXI2W1Qs639hJRJ0hWIilTZCs3Ftn4,212 +einops/layers/oneflow.py,sha256=XlZugzWGgAp3eGZLM_UsusoU-5Mws2Qfwwn8yywLYWs,2046 +einops/layers/paddle.py,sha256=-nvq9jJitZ8QWN31SdcEPXtjzh2xjpJGLdifOSOC_48,2063 +einops/layers/tensorflow.py,sha256=xEFbNU681Jva6Qy4AjHwwlmxdJfE28sTXDfhYxpF5jg,3299 +einops/layers/torch.py,sha256=Gj3tZ8sSnrnC-RvlK_6zTpgS89jdQofils30vikUVnE,2595 +einops/packing.py,sha256=z9VfP8SWgNTvi76atmYslw608ATkf8vKZHSTUa9srrI,7668 +einops/parsing.py,sha256=ChR0sKBmN2z--lyEpZvExN7gZdjTgm4V3cera0Yf4AM,6717 +einops/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/REQUESTED b/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ba1a8af28bcccdacebb8c22dfda1537447a1a58a --- /dev/null +++ b/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.18.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3a654e906619009358eb2cfe80609bd12b43fa7f --- /dev/null +++ b/venv/lib/python3.10/site-packages/einops-0.7.0.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Alex Rogozhnikov + +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/venv/lib/python3.10/site-packages/exceptiongroup-1.3.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/exceptiongroup-1.3.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/exceptiongroup-1.3.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/exceptiongroup-1.3.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/exceptiongroup-1.3.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..45df9c805ad4dedd7d04a22e91843820761b9a00 --- /dev/null +++ b/venv/lib/python3.10/site-packages/exceptiongroup-1.3.0.dist-info/METADATA @@ -0,0 +1,159 @@ +Metadata-Version: 2.4 +Name: exceptiongroup +Version: 1.3.0 +Summary: Backport of PEP 654 (exception groups) +Author-email: Alex Grönholm +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Typing :: Typed +License-File: LICENSE +Requires-Dist: typing-extensions >= 4.6.0; python_version < '3.13' +Requires-Dist: pytest >= 6 ; extra == "test" +Project-URL: Changelog, https://github.com/agronholm/exceptiongroup/blob/main/CHANGES.rst +Project-URL: Issue Tracker, https://github.com/agronholm/exceptiongroup/issues +Project-URL: Source code, https://github.com/agronholm/exceptiongroup +Provides-Extra: test + +.. image:: https://github.com/agronholm/exceptiongroup/actions/workflows/test.yml/badge.svg + :target: https://github.com/agronholm/exceptiongroup/actions/workflows/test.yml + :alt: Build Status +.. image:: https://coveralls.io/repos/github/agronholm/exceptiongroup/badge.svg?branch=main + :target: https://coveralls.io/github/agronholm/exceptiongroup?branch=main + :alt: Code Coverage + +This is a backport of the ``BaseExceptionGroup`` and ``ExceptionGroup`` classes from +Python 3.11. + +It contains the following: + +* The ``exceptiongroup.BaseExceptionGroup`` and ``exceptiongroup.ExceptionGroup`` + classes +* A utility function (``exceptiongroup.catch()``) for catching exceptions possibly + nested in an exception group +* Patches to the ``TracebackException`` class that properly formats exception groups + (installed on import) +* An exception hook that handles formatting of exception groups through + ``TracebackException`` (installed on import) +* Special versions of some of the functions from the ``traceback`` module, modified to + correctly handle exception groups even when monkey patching is disabled, or blocked by + another custom exception hook: + + * ``traceback.format_exception()`` + * ``traceback.format_exception_only()`` + * ``traceback.print_exception()`` + * ``traceback.print_exc()`` +* A backported version of ``contextlib.suppress()`` from Python 3.12.1 which also + handles suppressing exceptions inside exception groups + +If this package is imported on Python 3.11 or later, the built-in implementations of the +exception group classes are used instead, ``TracebackException`` is not monkey patched +and the exception hook won't be installed. + +See the `standard library documentation`_ for more information on exception groups. + +.. _standard library documentation: https://docs.python.org/3/library/exceptions.html + +Catching exceptions +=================== + +Due to the lack of the ``except*`` syntax introduced by `PEP 654`_ in earlier Python +versions, you need to use ``exceptiongroup.catch()`` to catch exceptions that are +potentially nested inside an exception group. This function returns a context manager +that calls the given handler for any exceptions matching the sole argument. + +The argument to ``catch()`` must be a dict (or any ``Mapping``) where each key is either +an exception class or an iterable of exception classes. Each value must be a callable +that takes a single positional argument. The handler will be called at most once, with +an exception group as an argument which will contain all the exceptions that are any +of the given types, or their subclasses. The exception group may contain nested groups +containing more matching exceptions. + +Thus, the following Python 3.11+ code: + +.. code-block:: python + + try: + ... + except* (ValueError, KeyError) as excgroup: + for exc in excgroup.exceptions: + print('Caught exception:', type(exc)) + except* RuntimeError: + print('Caught runtime error') + +would be written with this backport like this: + +.. code-block:: python + + from exceptiongroup import BaseExceptionGroup, catch + + def value_key_err_handler(excgroup: BaseExceptionGroup) -> None: + for exc in excgroup.exceptions: + print('Caught exception:', type(exc)) + + def runtime_err_handler(exc: BaseExceptionGroup) -> None: + print('Caught runtime error') + + with catch({ + (ValueError, KeyError): value_key_err_handler, + RuntimeError: runtime_err_handler + }): + ... + +**NOTE**: Just like with ``except*``, you cannot handle ``BaseExceptionGroup`` or +``ExceptionGroup`` with ``catch()``. + +Suppressing exceptions +====================== + +This library contains a backport of the ``contextlib.suppress()`` context manager from +Python 3.12.1. It allows you to selectively ignore certain exceptions, even when they're +inside exception groups: + +.. code-block:: python + + from exceptiongroup import suppress + + with suppress(RuntimeError): + raise ExceptionGroup("", [RuntimeError("boo")]) + +Notes on monkey patching +======================== + +To make exception groups render properly when an unhandled exception group is being +printed out, this package does two things when it is imported on any Python version +earlier than 3.11: + +#. The ``traceback.TracebackException`` class is monkey patched to store extra + information about exception groups (in ``__init__()``) and properly format them (in + ``format()``) +#. An exception hook is installed at ``sys.excepthook``, provided that no other hook is + already present. This hook causes the exception to be formatted using + ``traceback.TracebackException`` rather than the built-in rendered. + +If ``sys.exceptionhook`` is found to be set to something else than the default when +``exceptiongroup`` is imported, no monkeypatching is done at all. + +To prevent the exception hook and patches from being installed, set the environment +variable ``EXCEPTIONGROUP_NO_PATCH`` to ``1``. + +Formatting exception groups +--------------------------- + +Normally, the monkey patching applied by this library on import will cause exception +groups to be printed properly in tracebacks. But in cases when the monkey patching is +blocked by a third party exception hook, or monkey patching is explicitly disabled, +you can still manually format exceptions using the special versions of the ``traceback`` +functions, like ``format_exception()``, listed at the top of this page. They work just +like their counterparts in the ``traceback`` module, except that they use a separately +patched subclass of ``TracebackException`` to perform the rendering. + +Particularly in cases where a library installs its own exception hook, it is recommended +to use these special versions to do the actual formatting of exceptions/tracebacks. + +.. _PEP 654: https://www.python.org/dev/peps/pep-0654/ + diff --git a/venv/lib/python3.10/site-packages/exceptiongroup-1.3.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/exceptiongroup-1.3.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..715b363045e8f089c72f7f2b16fd68f19acd97c8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/exceptiongroup-1.3.0.dist-info/RECORD @@ -0,0 +1,18 @@ +exceptiongroup-1.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +exceptiongroup-1.3.0.dist-info/METADATA,sha256=oiAq-llXqOaV0B3dJN316SjtCpthQvuQjmVuVObbaeQ,6725 +exceptiongroup-1.3.0.dist-info/RECORD,, +exceptiongroup-1.3.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +exceptiongroup-1.3.0.dist-info/licenses/LICENSE,sha256=blBw12UDHgrUA6HL-Qrm0ZoCKPgC4yC3rP9GCqcu1Hw,3704 +exceptiongroup/__init__.py,sha256=7DHS0hDk-RIs3IQc3SbZVB0-1MhiSCJ9XgvEyEloL7M,1049 +exceptiongroup/__pycache__/__init__.cpython-310.pyc,, +exceptiongroup/__pycache__/_catch.cpython-310.pyc,, +exceptiongroup/__pycache__/_exceptions.cpython-310.pyc,, +exceptiongroup/__pycache__/_formatting.cpython-310.pyc,, +exceptiongroup/__pycache__/_suppress.cpython-310.pyc,, +exceptiongroup/__pycache__/_version.cpython-310.pyc,, +exceptiongroup/_catch.py,sha256=CaJez3E-Jkr-7B7RT3fzusdLWnuyeekooSFn7KyWt9s,4680 +exceptiongroup/_exceptions.py,sha256=wPwPsZ64SXEptuwb4XrTIa1Mc78uqF5vmCrXTdllLn4,11463 +exceptiongroup/_formatting.py,sha256=4UC6bUN3K-FxEX96_ozzgeX05fCyprl6qCVR-efBmQ0,21032 +exceptiongroup/_suppress.py,sha256=LX11PRNpchwfNWwEMY92nYN1F_5qFenQcS8EjIONXKE,1772 +exceptiongroup/_version.py,sha256=qDtcPZdKzxLpd8vVl6fpIFIMkWt2HK_cO9gLDwaHEdk,511 +exceptiongroup/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/lib/python3.10/site-packages/exceptiongroup-1.3.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/exceptiongroup-1.3.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/venv/lib/python3.10/site-packages/exceptiongroup-1.3.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/venv/lib/python3.10/site-packages/exceptiongroup-1.3.0.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/exceptiongroup-1.3.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..50d4fa5e68439ce837f6eef437b299c0dd7c8594 --- /dev/null +++ b/venv/lib/python3.10/site-packages/exceptiongroup-1.3.0.dist-info/licenses/LICENSE @@ -0,0 +1,73 @@ +The MIT License (MIT) + +Copyright (c) 2022 Alex Grönholm + +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. + + +This project contains code copied from the Python standard library. +The following is the required license notice for those parts. + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. diff --git a/venv/lib/python3.10/site-packages/fastrlock/__init__.pxd b/venv/lib/python3.10/site-packages/fastrlock/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/fastrlock/__init__.py b/venv/lib/python3.10/site-packages/fastrlock/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..406b7dfc13bfa470524a4bc0bdbfd87f39dcd3b1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/fastrlock/__init__.py @@ -0,0 +1,9 @@ +# this is a package + +__version__ = "0.8.3" + + +class LockNotAcquired(Exception): + """ + Exception raised when the lock was not acquired in non-blocking mode. + """ diff --git a/venv/lib/python3.10/site-packages/fastrlock/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/fastrlock/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcc3e6d77fa8eddc028e95e9a3d1bf00fed94d51 Binary files /dev/null and b/venv/lib/python3.10/site-packages/fastrlock/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/fastrlock/_lock.pxi b/venv/lib/python3.10/site-packages/fastrlock/_lock.pxi new file mode 100644 index 0000000000000000000000000000000000000000..32af512727f9a65bcd694bc11f4509a8bb871b8d --- /dev/null +++ b/venv/lib/python3.10/site-packages/fastrlock/_lock.pxi @@ -0,0 +1,75 @@ + +from cpython cimport pythread + +from fastrlock import LockNotAcquired + +cdef extern from *: + # Compatibility definitions for Python + """ + #if PY_VERSION_HEX >= 0x030700a2 + typedef unsigned long pythread_t; + #else + typedef long pythread_t; + #endif + """ + + # Just let Cython understand that pythread_t is + # a long type, but be aware that it is actually + # signed for versions of Python prior to 3.7.0a2 and + # unsigned for later versions + ctypedef unsigned long pythread_t + + +cdef struct _LockStatus: + pythread.PyThread_type_lock lock + pythread_t owner # thread ID of the current lock owner + unsigned int entry_count # number of (re-)entries of the owner + unsigned int pending_requests # number of pending requests for real lock + bint is_locked # whether the real lock is acquired + + +cdef bint _acquire_lock(_LockStatus *lock, long current_thread, + bint blocking) nogil except -1: + # Note that this function *must* hold the GIL when being called. + # We just use 'nogil' in the signature to make sure that no Python + # code execution slips in that might free the GIL + + wait = pythread.WAIT_LOCK if blocking else pythread.NOWAIT_LOCK + if not lock.is_locked and not lock.pending_requests: + # someone owns it but didn't acquire the real lock - do that + # now and tell the owner to release it when done + if pythread.PyThread_acquire_lock(lock.lock, pythread.NOWAIT_LOCK): + lock.is_locked = True + #assert lock._is_locked + + lock.pending_requests += 1 + # wait for the lock owning thread to release it + with nogil: + while True: + locked = pythread.PyThread_acquire_lock(lock.lock, wait) + if locked: + break + if wait == pythread.NOWAIT_LOCK: + lock.pending_requests -= 1 + return False + lock.pending_requests -= 1 + #assert not lock.is_locked + #assert lock.reentry_count == 0 + #assert locked + lock.is_locked = True + lock.owner = current_thread + lock.entry_count = 1 + return True + + +cdef inline void _unlock_lock(_LockStatus *lock) nogil noexcept: + # Note that this function *must* hold the GIL when being called. + # We just use 'nogil' in the signature to make sure that no Python + # code execution slips in that might free the GIL + + #assert lock.entry_count > 0 + lock.entry_count -= 1 + if lock.entry_count == 0: + if lock.is_locked: + pythread.PyThread_release_lock(lock.lock) + lock.is_locked = False diff --git a/venv/lib/python3.10/site-packages/fastrlock/rlock.pxd b/venv/lib/python3.10/site-packages/fastrlock/rlock.pxd new file mode 100644 index 0000000000000000000000000000000000000000..52ec770e992a3f9ae806d713f9fb819d2d2fd819 --- /dev/null +++ b/venv/lib/python3.10/site-packages/fastrlock/rlock.pxd @@ -0,0 +1,10 @@ +# cython: language_level=3 + +cdef create_fastrlock() + +# acquire the lock of a FastRlock instance +# 'current_thread' may be -1 for the current thread +cdef bint lock_fastrlock(rlock, long current_thread, bint blocking) except -1 + +# release the lock of a FastRlock instance +cdef int unlock_fastrlock(rlock) except -1 diff --git a/venv/lib/python3.10/site-packages/fastrlock/rlock.pyx b/venv/lib/python3.10/site-packages/fastrlock/rlock.pyx new file mode 100644 index 0000000000000000000000000000000000000000..6ade43f62f5a5a063bc49a73d49e24a89b34c856 --- /dev/null +++ b/venv/lib/python3.10/site-packages/fastrlock/rlock.pyx @@ -0,0 +1,104 @@ +# cython: language_level=3 +# cython: binding=True + +from cpython cimport pythread + +include "_lock.pxi" + + +cdef class FastRLock: + """Fast, re-entrant locking. + + Under non-congested conditions, the lock is never acquired but only + counted. Only when a second thread comes in and notices that the + lock is needed, it acquires the lock and notifies the first thread + to release it when it's done. This is all made possible by the + wonderful GIL. + """ + cdef _LockStatus _real_lock + + def __cinit__(self): + self._real_lock = _LockStatus( + lock=pythread.PyThread_allocate_lock(), + owner=0, is_locked=False, pending_requests=0, entry_count=0) + if not self._real_lock.lock: + raise MemoryError() + + def __dealloc__(self): + if self._real_lock.lock: + pythread.PyThread_free_lock(self._real_lock.lock) + self._real_lock.lock = NULL + + # compatibility with RLock and expected Python level interface + + def acquire(self, bint blocking=True): + return _lock_rlock( + &self._real_lock, pythread.PyThread_get_thread_ident(), blocking) + + def release(self): + if self._real_lock.entry_count == 0: + raise RuntimeError("cannot release un-acquired lock") + _unlock_lock(&self._real_lock) + + def __enter__(self): + # self.acquire() + if not _lock_rlock( + &self._real_lock, pythread.PyThread_get_thread_ident(), blocking=True): + raise LockNotAcquired() + + def __exit__(self, t, v, tb): + # self.release() + if self._real_lock.entry_count == 0 or self._real_lock.owner != pythread.PyThread_get_thread_ident(): + raise RuntimeError("cannot release un-acquired lock") + _unlock_lock(&self._real_lock) + + def _is_owned(self): + return self._real_lock.entry_count > 0 and self._real_lock.owner == pythread.PyThread_get_thread_ident() + + +cdef inline bint _lock_rlock(_LockStatus *lock, pythread_t current_thread, + bint blocking) nogil except -1: + # Note that this function *must* hold the GIL when being called. + # We just use 'nogil' in the signature to make sure that no Python + # code execution slips in that might free the GIL + + if lock.entry_count: + # locked! - by myself? + if lock.owner == current_thread: + lock.entry_count += 1 + return True + elif not lock.pending_requests: + # not locked, not requested - go! + lock.owner = current_thread + lock.entry_count = 1 + return True + # need to get the real lock + return _acquire_lock(lock, current_thread, blocking) + + +########################################################################### +## public C-API + +cdef create_fastrlock(): + """ + Public C level entry function for creating a FastRlock instance. + """ + return FastRLock.__new__(FastRLock) + + +cdef bint lock_fastrlock(rlock, long current_thread, bint blocking) except -1: + """ + Public C level entry function for locking a FastRlock instance. + + The 'current_thread' argument is deprecated and ignored. Pass -1 for backwards compatibility. + """ + # Note: 'current_thread' used to be set to -1 or the current thread ID, but -1 is signed while "pythread_t" isn't. + return _lock_rlock(&(rlock)._real_lock, pythread.PyThread_get_thread_ident(), blocking) + + +cdef int unlock_fastrlock(rlock) except -1: + """ + Public C level entry function for unlocking a FastRlock instance. + """ + _unlock_lock(&(rlock)._real_lock) + return 0 diff --git a/venv/lib/python3.10/site-packages/gantry/__init__.py b/venv/lib/python3.10/site-packages/gantry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0823f2b36f12e74259fd960a7df0ab1641124255 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/__init__.py @@ -0,0 +1,3 @@ +from .constants import METRICS_FILE, RESULTS_DIR + +__all__ = ["METRICS_FILE", "RESULTS_DIR"] diff --git a/venv/lib/python3.10/site-packages/gantry/__main__.py b/venv/lib/python3.10/site-packages/gantry/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..c7804e565444034739745e745d2d34151fb8ea39 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/__main__.py @@ -0,0 +1,4 @@ +from .commands import main + +if __name__ == "__main__": + main() diff --git a/venv/lib/python3.10/site-packages/gantry/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da6c9b0c6b74876d1e7f413bb924ef113bf4baee Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/__pycache__/__main__.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6a1afc70cf3328a181e7f44d4fa8271f8b924e5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/__pycache__/__main__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/__pycache__/aliases.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/__pycache__/aliases.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6f0624dd0df9e21c4ebfbd949020cd93c2b75a6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/__pycache__/aliases.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/__pycache__/all_reduce_bench.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/__pycache__/all_reduce_bench.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4a346ea1f80b69a1d538bae04c57ac05acc6888 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/__pycache__/all_reduce_bench.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/__pycache__/api.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/__pycache__/api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..210ccb884f97fe6deda5a550a483647bdfc8ce6c Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/__pycache__/api.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/__pycache__/constants.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/__pycache__/constants.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8f39852d57e80777d804540d13ecfb92e017ca8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/__pycache__/constants.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/__pycache__/exceptions.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ed977be84a23813d85d48933bef0f4388721f18 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/__pycache__/exceptions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/__pycache__/git_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/__pycache__/git_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..032e63e24cb128a0d0228a8cf1439f08f6af698c Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/__pycache__/git_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/__pycache__/util.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..535caef586d4d0ca8117c3592ef7cf4b84a97465 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/__pycache__/util.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/__pycache__/version.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/__pycache__/version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d308f98ce63bcac868d13284637c0d935427f95 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/__pycache__/version.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/aliases.py b/venv/lib/python3.10/site-packages/gantry/aliases.py new file mode 100644 index 0000000000000000000000000000000000000000..a1c23530e90056166d134b6893f85f21117115dc --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/aliases.py @@ -0,0 +1,4 @@ +from os import PathLike +from typing import Union + +PathOrStr = Union[PathLike, str] diff --git a/venv/lib/python3.10/site-packages/gantry/all_reduce_bench.py b/venv/lib/python3.10/site-packages/gantry/all_reduce_bench.py new file mode 100644 index 0000000000000000000000000000000000000000..d82eb0c45104225f7b3c50135ae37e4b67c1dcbc --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/all_reduce_bench.py @@ -0,0 +1,93 @@ +import os +from datetime import timedelta + +import torch +import torch.distributed as dist + +TRIALS = 5 + +# these emulate the payload which will become a M * N * 4-sized tensor below +N = 500000 +M = 2000 + + +def get_local_rank() -> int: + return int(os.environ["LOCAL_RANK"]) + + +def print_rank0(*args, **kwargs): + if get_local_rank() == 0: + print(*args, **kwargs) + + +def timed_allreduce( + mat: torch.Tensor, + start_event: torch.cuda.Event, + end_event: torch.cuda.Event, + device: torch.device, +): + dist.barrier() + start_event.record() + dist.all_reduce(mat) + end_event.record() + + torch.cuda.synchronize() + duration = start_event.elapsed_time(end_event) / 1000 + + size = M * N * 4 # 4 is 4 bytes in fp32 + # note that this is following the same math as NVIDIA/nccl-tests + algbw = torch.tensor([size / duration]).to(device) + + # calculate mean across all ranks + dist.reduce(algbw, dst=0, op=dist.ReduceOp.SUM) + algbw /= dist.get_world_size() + + return algbw + + +def main(): + device = torch.device(f"cuda:{get_local_rank()}") + torch.cuda.set_device(device) + + try: + print_rank0("Initializing distributed process group...") + dist.init_process_group("nccl", timeout=timedelta(seconds=30), device_id=device) + print_rank0("Done.") + + mat = torch.rand(N, M, dtype=torch.float32).to(device) + + start_event: torch.cuda.Event = torch.cuda.Event(enable_timing=True) + end_event: torch.cuda.Event = torch.cuda.Event(enable_timing=True) + + # do a few warm up iterations + print_rank0("Starting warm-up...") + for i in range(2): + timed_allreduce(mat, start_event, end_event, device) + print_rank0("Done.") + + # real benchmark + print_rank0("Starting benchmark...") + algbw_gather = [] + for i in range(TRIALS): + print_rank0(f"Run {i+1}...") + algbw_gather += timed_allreduce(mat, start_event, end_event, device) + + algbw = torch.mean(torch.stack(algbw_gather)) + + # the 2*(n-1)/n busbw correction factor specific to all-reduce is explained here: + # https://github.com/NVIDIA/nccl-tests/blob/master/doc/PERFORMANCE.md#allreduce + # busbw reflects how optimally the hardware is used + n = dist.get_world_size() + busbw = algbw * (2 * (n - 1) / n) + + print_rank0( + f"The average bandwidth of all_reduce with a {M*N*4/1e9}GB payload ({TRIALS} trials, {n} ranks):\n" + f"algbw: {algbw/1e9:.3f} GBps ({algbw*8/1e9:.1f} Gbps)\n" + f"busbw: {busbw/1e9:.3f} GBps ({busbw*8/1e9:.1f} Gbps)\n" + ) + finally: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/venv/lib/python3.10/site-packages/gantry/api.py b/venv/lib/python3.10/site-packages/gantry/api.py new file mode 100644 index 0000000000000000000000000000000000000000..8dc56564d5e47a37ec40a518f9f10eba652efadb --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/api.py @@ -0,0 +1,869 @@ +""" +Gantry's public API. +""" + +import random +import string +import sys +import time +from pathlib import Path +from typing import List, Literal, Optional, Sequence, Tuple, Union + +import rich +from beaker import ( + Beaker, + BeakerCancelationCode, + BeakerCluster, + BeakerExperimentSpec, + BeakerGroup, + BeakerJob, + BeakerJobPriority, + BeakerRetrySpec, + BeakerSortOrder, + BeakerTask, + BeakerTaskResources, + BeakerTaskSpec, + BeakerWorkload, + BeakerWorkloadStatus, +) +from beaker.exceptions import ( + BeakerExperimentConflict, + BeakerGroupNotFound, + BeakerImageNotFound, + BeakerSecretNotFound, +) +from rich import print, prompt +from rich.status import Status + +from . import constants, util +from .aliases import PathOrStr +from .exceptions import * +from .git_utils import GitRepoState +from .util import get_local_python_version, print_stderr +from .version import VERSION + +__all__ = ["GitRepoState", "launch_experiment", "follow_workload"] + + +def _wait_for_job_to_start( + *, + beaker: Beaker, + job: BeakerJob, + status: Status, + start_time: float, + timeout: int = 0, + show_logs: bool = True, +) -> BeakerJob: + # Pull events until job is running (or fails)... + events = set() + while not (job.status.HasField("finalized") or (show_logs and job.status.HasField("started"))): + if timeout > 0 and (time.monotonic() - start_time) > timeout: + raise BeakerJobTimeoutError(f"Timed out while waiting for job '{job.id}' to finish") + + for event in beaker.job.list_summarized_events( + job, sort_order=BeakerSortOrder.descending, sort_field="latest_occurrence" + ): + event_hashable = (event.latest_occurrence.ToSeconds(), event.latest_message) + if event_hashable not in events: + status.update(f"[i]{event.latest_message}[/]") + events.add(event_hashable) + time.sleep(0.5) + + time.sleep(0.5) + job = beaker.job.get(job.id) + + return job + + +def _job_preempted(job: BeakerJob) -> bool: + return job.status.status == BeakerWorkloadStatus.canceled and job.status.canceled_code in ( + BeakerCancelationCode.system_preemption, + BeakerCancelationCode.user_preemption, + ) + + +def _validate_args(args: Sequence[str]): + if not args: + raise ConfigurationError( + "[ARGS]... are required! For example:\n$ gantry run -- python -c 'print(\"Hello, World!\")'" + ) + + try: + arg_index = sys.argv.index("--") + except ValueError: + raise ConfigurationError("[ARGS]... are required and must all come after '--'") + + # NOTE: if a value was accidentally provided to a flag, like '--preemptible false', click will + # surprisingly add that value to the args. So we do a check here for that situation. + given_args = sys.argv[arg_index + 1 :] + invalid_args = args[: -len(given_args)] + if invalid_args: + raise ConfigurationError( + f"Invalid options, found extra arguments before the '--': " + f"{', '.join([repr(s) for s in invalid_args])}.\n" + "Hint: you might be trying to pass a value to a FLAG option.\n" + "Try 'gantry run --help' for help." + ) + + +def launch_experiment( + args: Sequence[str], + name: Optional[str] = None, + description: Optional[str] = None, + task_name: str = "main", + workspace: Optional[str] = None, + group_names: Optional[Sequence[str]] = None, + clusters: Optional[Sequence[str]] = None, + gpu_types: Optional[Sequence[str]] = None, + tags: Optional[Sequence[str]] = None, + hostnames: Optional[Sequence[str]] = None, + beaker_image: Optional[str] = None, + docker_image: Optional[str] = None, + cpus: Optional[float] = None, + gpus: Optional[int] = None, + memory: Optional[str] = None, + shared_memory: Optional[str] = None, + datasets: Optional[Sequence[str]] = None, + gh_token_secret: str = constants.GITHUB_TOKEN_SECRET, + ref: Optional[str] = None, + branch: Optional[str] = None, + conda_file: Optional[PathOrStr] = None, + conda_env: Optional[str] = None, + python_manager: Optional[Literal["uv", "conda"]] = None, + system_python: bool = False, + uv_venv: Optional[str] = None, + uv_extras: Optional[Sequence[str]] = None, + uv_all_extras: Optional[bool] = None, + uv_torch_backend: Optional[str] = None, + env_vars: Optional[Sequence[str]] = None, + env_secrets: Optional[Sequence[str]] = None, + dataset_secrets: Optional[Sequence[str]] = None, + timeout: Optional[int] = None, + task_timeout: Optional[str] = None, + show_logs: Optional[bool] = None, + allow_dirty: bool = False, + dry_run: bool = False, + yes: bool = False, + save_spec: Optional[PathOrStr] = None, + priority: Optional[str] = None, + install: Optional[str] = None, + no_python: bool = False, + replicas: Optional[int] = None, + leader_selection: bool = False, + host_networking: bool = False, + propagate_failure: Optional[bool] = None, + propagate_preemption: Optional[bool] = None, + synchronized_start_timeout: Optional[str] = None, + mounts: Optional[Sequence[str]] = None, + weka: Optional[str] = None, + budget: Optional[str] = None, + preemptible: Optional[bool] = None, + retries: Optional[int] = None, + results: str = constants.RESULTS_DIR, + runtime_dir: str = constants.RUNTIME_DIR, + exec_method: Literal["exec", "bash"] = "exec", + skip_tcpxo_setup: bool = False, + default_python_version: str = get_local_python_version(), + pre_setup: Optional[str] = None, + post_setup: Optional[str] = None, +): + """ + Launch an experiment on Beaker. Same as the ``gantry run`` command. + """ + + _validate_args(args) + + if timeout is None: + timeout = -1 if show_logs else 0 + if show_logs is None: + show_logs = timeout != 0 + + if beaker_image is None and docker_image is None: + beaker_image = constants.DEFAULT_IMAGE + elif (beaker_image is None) == (docker_image is None): + raise ConfigurationError( + "Either --beaker-image or --docker-image must be specified, but not both." + ) + + task_resources = BeakerTaskResources( + cpu_count=cpus, gpu_count=gpus, memory=memory, shared_memory=shared_memory + ) + + # Get git information. + git_config = GitRepoState.from_env(ref=ref, branch=branch) + + # Validate repo state. + if ref is None and not allow_dirty and git_config.is_dirty: + raise DirtyRepoError("You have uncommitted changes! Use --allow-dirty to force.") + + # Initialize Beaker client and validate workspace. + with util.init_client(workspace=workspace, yes=yes) as beaker: + if beaker_image is not None and beaker_image != constants.DEFAULT_IMAGE: + try: + beaker_image = beaker.image.get(beaker_image).id + except BeakerImageNotFound: + raise ConfigurationError(f"Beaker image '{beaker_image}' not found") + + if budget is None and not beaker.workspace.get().budget_id: + budget = prompt.Prompt.ask( + "[yellow]Missing '--budget' option, " + "see https://beaker-docs.apps.allenai.org/concept/budgets.html for more information.[/]\n" + "[i]Please enter the budget account to associate with this experiment[/]", + ) + + if not budget: + raise ConfigurationError("Budget account must be specified!") + + # Maybe resolve or create group. + groups: List[BeakerGroup] = [] + if group_names: + for group_name in group_names: + group = util.resolve_group(beaker, group_name) + if group is None: + if "/" in group_name and not group_name.startswith(f"{beaker.user_name}/"): + raise BeakerGroupNotFound(group_name) + + if prompt.Confirm.ask( + f"Group [green]{group_name}[/] not found in workspace, would you like to create this group?" + ): + group_name = group_name.split("/", 1)[-1] + group = beaker.group.create(group_name) + print(f"Group created: {util.group_url(beaker, group)}") + else: + print_stderr("[yellow]canceled[/]") + sys.exit(1) + + groups.append(group) + + # Get the entrypoint dataset. + entrypoint_dataset = util.ensure_entrypoint_dataset(beaker) + + # Get / set the GitHub token secret. + if not git_config.is_public: + try: + beaker.secret.get(gh_token_secret) + except BeakerSecretNotFound: + print_stderr( + f"[yellow]GitHub token secret '{gh_token_secret}' not found in workspace.[/]\n" + f"You can create a suitable GitHub token by going to https://github.com/settings/tokens/new " + f"and generating a token with the '\N{ballot box with check} repo' scope." + ) + gh_token = prompt.Prompt.ask( + "[i]Please paste your GitHub token here[/]", + password=True, + ) + if not gh_token: + raise ConfigurationError("token cannot be empty!") + beaker.secret.write(gh_token_secret, gh_token) + print( + f"GitHub token secret uploaded to workspace as '{gh_token_secret}'.\n" + f"If you need to update this secret in the future, use the command:\n" + f"[i]$ gantry config set-gh-token[/]" + ) + + gh_token_secret = util.ensure_github_token_secret(beaker, gh_token_secret) + + # Validate the input datasets. + datasets_to_use = ensure_datasets(beaker, *datasets) if datasets else [] + + env_vars_to_use = [] + for e in env_vars or []: + try: + env_name, val = e.split("=", 1) + except ValueError: + raise ValueError("Invalid --env option: {e}") + env_vars_to_use.append((env_name, val)) + + env_secrets_to_use = [] + for e in env_secrets or []: + try: + env_secret_name, secret = e.split("=", 1) + except ValueError: + raise ValueError(f"Invalid --env-secret option: '{e}'") + env_secrets_to_use.append((env_secret_name, secret)) + + dataset_secrets_to_use = [] + for ds in dataset_secrets or []: + try: + secret, mount_path = ds.split(":", 1) + except ValueError: + raise ValueError(f"Invalid --dataset-secret option: '{ds}'") + dataset_secrets_to_use.append((secret, mount_path)) + + mounts_to_use = [] + for m in mounts or []: + try: + source, target = m.split(":", 1) + except ValueError: + raise ValueError(f"Invalid --mount option: '{m}'") + mounts_to_use.append((source, target)) + + weka_buckets = [] + for m in weka or []: + try: + source, target = m.split(":", 1) + except ValueError: + raise ValueError(f"Invalid --weka option: '{m}'") + weka_buckets.append((source, target)) + + if weka_buckets and (not tags or "storage:weka" not in tags): + tags = list(tags or []) + tags.append("storage:weka") + + # Validate clusters. + if clusters or gpu_types or tags: + constraints = [] + if clusters: + constraints.append(f'''name matches any of: "{'", "'.join(clusters)}"''') + if tags: + constraints.append(f'''has the tag(s): "{'", "'.join(tags)}"''') + if gpu_types: + constraints.append( + f'''has any one of these GPU types: "{'", "'.join(gpu_types)}"''' + ) + + # Collect all clusters that support batch jobs. + all_clusters: List[BeakerCluster] = [] + for cl in beaker.cluster.list(): + # If 'max_task_timeout' is set to 0 then tasks are not allowed. + if cl.HasField("max_task_timeout") and cl.max_task_timeout.ToMilliseconds() == 0: + continue + else: + all_clusters.append(cl) + + if not all_clusters: + raise RuntimeError("Failed to find any clusters that support batch jobs") + + # Maybe filter clusters based on provided patterns. + if clusters: + all_clusters = util.filter_clusters_by_name(beaker, all_clusters, clusters) + + # Maybe filter based on tags. + if tags: + all_clusters = util.filter_clusters_by_tags(beaker, all_clusters, tags) + + # Filter based on GPU types. + if gpu_types: + all_clusters = util.filter_clusters_by_gpu_type(beaker, all_clusters, gpu_types) + + if not all_clusters: + constraints_str = "\n - ".join(constraints) + raise ConfigurationError( + f"Failed to find clusters satisfying the given constraints:\n - {constraints_str}" + ) + else: + clusters = [f"{cl.organization_name}/{cl.name}" for cl in all_clusters] + + # Default to preemptible when no cluster has been specified. + if not clusters and preemptible is None: + preemptible = True + + # Initialize experiment and task spec. + spec = _build_experiment_spec( + task_name=task_name, + clusters=list(clusters or []), + task_resources=task_resources, + arguments=list(args), + entrypoint_dataset=entrypoint_dataset.id, + git_config=git_config, + budget=budget, + group_names=[group.full_name for group in groups], + description=description, + beaker_image=beaker_image, + docker_image=docker_image, + gh_token_secret=gh_token_secret if not git_config.is_public else None, + conda_file=conda_file, + conda_env=conda_env, + python_manager=python_manager, + system_python=system_python, + uv_venv=uv_venv, + uv_extras=uv_extras, + uv_all_extras=uv_all_extras, + uv_torch_backend=uv_torch_backend, + datasets=datasets_to_use, + env=env_vars_to_use, + env_secrets=env_secrets_to_use, + dataset_secrets=dataset_secrets_to_use, + priority=priority, + install=install, + no_python=no_python, + replicas=replicas, + leader_selection=leader_selection, + host_networking=host_networking or (bool(replicas) and leader_selection), + propagate_failure=propagate_failure, + propagate_preemption=propagate_preemption, + synchronized_start_timeout=synchronized_start_timeout, + task_timeout=task_timeout, + mounts=mounts_to_use, + weka_buckets=weka_buckets, + hostnames=None if hostnames is None else list(hostnames), + preemptible=preemptible, + retries=retries, + results=results, + runtime_dir=runtime_dir, + exec_method=exec_method, + skip_tcpxo_setup=skip_tcpxo_setup, + default_python_version=default_python_version, + pre_setup=pre_setup, + post_setup=post_setup, + ) + + if save_spec: + if ( + Path(save_spec).is_file() + and not yes + and not prompt.Confirm.ask( + f"[yellow]The file '{save_spec}' already exists. " + f"[i]Are you sure you want to overwrite it?[/][/]" + ) + ): + raise KeyboardInterrupt + spec.to_file(save_spec) + print(f"Experiment spec saved to {save_spec}") + + if not name: + default_name = util.unique_name() + if yes: + name = default_name + else: + name = prompt.Prompt.ask( + "[i]What would you like to call this experiment?[/]", default=util.unique_name() + ) + + if not name: + raise ConfigurationError("Experiment name cannot be empty!") + + if dry_run: + rich.get_console().rule("[b]Dry run[/]") + print( + f"[b]Workspace:[/] {beaker.workspace.url()}\n" + f"[b]Groups:[/] {', '.join([util.group_url(beaker, group) for group in groups])}\n" + f"[b]Commit:[/] {git_config.ref_url}\n" + f"[b]Branch:[/] {git_config.branch_url}\n" + f"[b]Name:[/] {name}\n" + f"[b]Experiment spec:[/]", + spec.to_json(), + ) + return + + name_prefix = name + while True: + try: + workload = beaker.experiment.create(name=name, spec=spec) + break + except BeakerExperimentConflict: + name = ( + name_prefix + + "-" + + random.choice(string.ascii_lowercase) + + random.choice(string.ascii_lowercase) + + random.choice(string.digits) + + random.choice(string.digits) + ) + + print( + f"Experiment '{beaker.user_name}/{workload.experiment.name}' ({workload.experiment.id}) submitted.\n" + f"Experiment URL: {beaker.workload.url(workload)}" + ) + + for group in groups: + print(f"Group '{group.full_name}': {util.group_url(beaker, group)}") + + # Can return right away if timeout is 0. + if timeout == 0: + return + + job: Optional[BeakerJob] = None + try: + job = follow_workload(beaker, workload, timeout=timeout, show_logs=show_logs) + except (TermInterrupt, BeakerJobTimeoutError) as exc: + print_stderr(f"[red][bold]{exc.__class__.__name__}:[/] [i]{exc}[/][/]") + beaker.workload.cancel(workload) + print_stderr("[yellow]Experiment cancelled.[/]") + sys.exit(1) + except KeyboardInterrupt: + print_stderr("[yellow]Caught keyboard interrupt...[/]") + if prompt.Confirm.ask("Would you like to cancel the experiment?"): + beaker.workload.cancel(workload) + print_stderr(f"[red]Experiment stopped:[/] {beaker.workload.url(workload)}") + return + else: + print(f"See the experiment at {beaker.workload.url(workload)}") + print_stderr( + f"[yellow]To cancel the experiment manually, run:\n[i]$ gantry stop {workload.experiment.id}[/][/]" + ) + sys.exit(1) + + util.display_results(beaker, workload, job) + + +def _build_experiment_spec( + *, + task_name: str, + clusters: List[str], + task_resources: BeakerTaskResources, + arguments: List[str], + entrypoint_dataset: str, + git_config: GitRepoState, + budget: Optional[str] = None, + group_names: Optional[List[str]] = None, + description: Optional[str] = None, + beaker_image: Optional[str] = None, + docker_image: Optional[str] = None, + gh_token_secret: Optional[str] = constants.GITHUB_TOKEN_SECRET, + conda_file: Optional[PathOrStr] = None, + conda_env: Optional[str] = None, + python_manager: Optional[Literal["uv", "conda"]] = None, + system_python: bool = False, + uv_venv: Optional[str] = None, + uv_extras: Optional[Sequence[str]] = None, + uv_all_extras: Optional[bool] = None, + uv_torch_backend: Optional[str] = None, + datasets: Optional[List[Tuple[str, Optional[str], str]]] = None, + env: Optional[List[Tuple[str, str]]] = None, + env_secrets: Optional[List[Tuple[str, str]]] = None, + dataset_secrets: Optional[List[Tuple[str, str]]] = None, + priority: Optional[Union[str, BeakerJobPriority]] = None, + install: Optional[str] = None, + no_python: bool = False, + replicas: Optional[int] = None, + leader_selection: bool = False, + host_networking: bool = False, + propagate_failure: Optional[bool] = None, + propagate_preemption: Optional[bool] = None, + synchronized_start_timeout: Optional[str] = None, + task_timeout: Optional[str] = None, + mounts: Optional[List[Tuple[str, str]]] = None, + weka_buckets: Optional[List[Tuple[str, str]]] = None, + hostnames: Optional[List[str]] = None, + preemptible: Optional[bool] = None, + retries: Optional[int] = None, + results: str = constants.RESULTS_DIR, + runtime_dir: str = constants.RUNTIME_DIR, + exec_method: Literal["exec", "bash"] = "exec", + skip_tcpxo_setup: bool = False, + default_python_version: str = get_local_python_version(), + pre_setup: Optional[str] = None, + post_setup: Optional[str] = None, +): + if exec_method not in ("exec", "bash"): + raise ConfigurationError( + f"expected one of 'exec', 'bash' for --exec-method, but got '{exec_method}'." + ) + + task_spec = ( + BeakerTaskSpec.new( + task_name, + beaker_image=beaker_image, + docker_image=docker_image, + result_path=results, + command=["bash", "/gantry/entrypoint.sh"], + arguments=arguments, + resources=task_resources, + priority=priority, + preemptible=preemptible, + replicas=replicas, + leader_selection=leader_selection, + host_networking=host_networking, + propagate_failure=propagate_failure, + propagate_preemption=propagate_preemption, + synchronized_start_timeout=synchronized_start_timeout, + timeout=task_timeout, + ) + .with_env_var(name="GANTRY_VERSION", value=VERSION) + .with_env_var(name="GITHUB_REPO", value=git_config.repo) + .with_env_var(name="GIT_REF", value=git_config.ref) + .with_env_var(name="GANTRY_TASK_NAME", value=task_name) + .with_env_var(name="RESULTS_DIR", value=results) + .with_env_var(name="GANTRY_RUNTIME_DIR", value=runtime_dir) + .with_env_var(name="GANTRY_EXEC_METHOD", value=exec_method) + .with_dataset("/gantry", beaker=entrypoint_dataset) + ) + + if git_config.branch is not None: + task_spec = task_spec.with_env_var(name="GIT_BRANCH", value=git_config.branch) + + if clusters: + task_spec = task_spec.with_constraint(cluster=clusters) + + if hostnames: + task_spec = task_spec.with_constraint(hostname=hostnames) + + if gh_token_secret is not None: + task_spec = task_spec.with_env_var(name="GITHUB_TOKEN", secret=gh_token_secret) + + if skip_tcpxo_setup: + task_spec = task_spec.with_env_var(name="GANTRY_SKIP_TCPXO_SETUP", value="1") + + if no_python: + task_spec = task_spec.with_env_var(name="GANTRY_NO_PYTHON", value="1") + + if ( + python_manager is not None + or system_python + or uv_venv is not None + or uv_all_extras is not None + or uv_extras + or uv_torch_backend is not None + or conda_env is not None + or conda_file is not None + ): + raise ConfigurationError("other python options can't be used with --no-python") + else: + has_project_file = ( + git_config.is_in_tree("pyproject.toml") + or git_config.is_in_tree("setup.py") + or git_config.is_in_tree("setup.cfg") + ) + + task_spec = task_spec.with_env_var( + name="GANTRY_DEFAULT_PYTHON_VERSION", + value=default_python_version, + ) + + if system_python: + task_spec = task_spec.with_env_var( + name="GANTRY_USE_SYSTEM_PYTHON", + value="1", + ) + + if python_manager is None: + if ( + conda_env is not None + or conda_file is not None + or git_config.is_in_tree("environment.yml") + or git_config.is_in_tree("environment.yaml") + ): + python_manager = "conda" + else: + python_manager = "uv" + elif python_manager not in {"uv", "conda"}: + raise ConfigurationError( + f"unknown option for --python-manager: '{python_manager}'. Should be either 'uv' or 'conda'." + ) + + task_spec = task_spec.with_env_var( + name="GANTRY_PYTHON_MANAGER", + value=python_manager, + ) + + if python_manager == "uv": + if conda_env is not None or conda_file is not None: + raise ConfigurationError( + "--conda-* options are only relevant when using the conda python manager (--python-manager=conda)." + ) + + if uv_venv is not None: + if system_python: + raise ConfigurationError( + "--system-python flag is incompatible with --uv-venv option." + ) + + task_spec = task_spec.with_env_var( + name="GANTRY_UV_VENV", + value=uv_venv, + ) + + if uv_all_extras is None: + if not uv_extras and has_project_file: + uv_all_extras = True + else: + uv_all_extras = False + elif uv_extras: + raise ConfigurationError( + "--uv-all-extras/--uv-no-extras is mutually exclusive with --uv-extra" + ) + + if uv_all_extras: + if not has_project_file: + raise ConfigurationError( + "--uv-all-extras is only valid when you have a pyproject.toml, setup.py, or setup.cfg file." + ) + + task_spec = task_spec.with_env_var(name="GANTRY_UV_ALL_EXTRAS", value="1") + + if uv_extras: + if not has_project_file: + raise ConfigurationError( + "--uv-extra is only valid when you have a pyproject.toml, setup.py, or setup.cfg file." + ) + + task_spec = task_spec.with_env_var( + name="GANTRY_UV_EXTRAS", value=" ".join(uv_extras) + ) + + if uv_torch_backend is not None: + task_spec = task_spec.with_env_var(name="UV_TORCH_BACKEND", value=uv_torch_backend) + elif python_manager == "conda": + if ( + uv_venv is not None + or uv_extras + or uv_all_extras is not None + or uv_torch_backend is not None + ): + raise ConfigurationError( + "--uv-* options are only relevant when using the uv python manager (--python-manager=uv)." + ) + + if conda_env is not None: + if system_python: + raise ConfigurationError( + "--system-python flag is incompatible with --conda-env option." + ) + + task_spec = task_spec.with_env_var( + name="GANTRY_CONDA_ENV", + value=conda_env, + ) + + if conda_file is not None: + task_spec = task_spec.with_env_var( + name="GANTRY_CONDA_FILE", + value=str(conda_file), + ) + else: + for path in ("environment.yml", "environment.yaml"): + if git_config.is_in_tree(path): + task_spec = task_spec.with_env_var( + name="GANTRY_CONDA_FILE", + value=path, + ) + break + + if install is not None: + task_spec = task_spec.with_env_var(name="GANTRY_INSTALL_CMD", value=install) + + if pre_setup is not None: + task_spec = task_spec.with_env_var(name="GANTRY_PRE_SETUP_CMD", value=pre_setup) + + if post_setup is not None: + task_spec = task_spec.with_env_var(name="GANTRY_POST_SETUP_CMD", value=post_setup) + + if datasets: + for dataset_id, sub_path, path in datasets: + task_spec = task_spec.with_dataset(path, beaker=dataset_id, sub_path=sub_path) + + for secret, mount_path in dataset_secrets or []: + task_spec = task_spec.with_dataset(mount_path, secret=secret) + + if mounts: + for source, target in mounts: + task_spec = task_spec.with_dataset(target, host_path=source) + + if weka_buckets: + for source, target in weka_buckets: + task_spec = task_spec.with_dataset(target, weka=source) + + for name, val in env or []: + task_spec = task_spec.with_env_var(name=name, value=val) + + for name, secret in env_secrets or []: + task_spec = task_spec.with_env_var(name=name, secret=secret) + + return BeakerExperimentSpec( + description=description, + budget=budget, + tasks=[task_spec], + groups=group_names, + retry=None if not retries else BeakerRetrySpec(allowed_task_retries=retries), + ) + + +def ensure_datasets(beaker: Beaker, *datasets: str) -> List[Tuple[str, Optional[str], str]]: + out = [] + for dataset_str in datasets: + dataset_name: str + path: str + sub_path: Optional[str] = None + if dataset_str.count(":") == 1: + dataset_name, path = dataset_str.split(":") + elif dataset_str.count(":") == 2: + dataset_name, sub_path, path = dataset_str.split(":") + else: + raise ValueError( + f"Bad '--dataset' specification: '{dataset_str}'\n" + f"Datasets should be in the form of 'dataset-name:/mount/location'" + f"or 'dataset-name:sub/path:/mount/location'" + ) + dataset_id = beaker.dataset.get(dataset_name).id + out.append((dataset_id, sub_path, path)) + return out + + +def follow_workload( + beaker: Beaker, + workload: BeakerWorkload, + *, + task: BeakerTask | None = None, + timeout: int = 0, + tail: bool = False, + show_logs: bool = True, +) -> BeakerJob: + """ + Follow a workload until completion while streaming logs to stdout. + + :param task: A specific task in the workload to follow. Defaults to the first task. + :param timeout: The number of seconds to wait for the workload to complete. Raises a timeout + error if it doesn't complete in time. Set to 0 (the default) to wait indefinitely. + :param tail: Start tailing the logs if a job is already running. Otherwise shows all logs. + :param show_logs: Set to ``False`` to avoid streaming the logs. + + :returns: The finalized :class:`~beaker.types.BeakerJob` from the task being followed. + + :raises ~gantry.exceptions.BeakerJobTimeoutError: If ``timeout`` is set to a positive number + and the workload doesn't complete in time. + """ + console = rich.get_console() + start_time = time.monotonic() + preempted_job_ids = set() + + while True: + with console.status("[i]waiting...[/]", spinner="point", speed=0.8) as status: + # Wait for job to be created... + job: BeakerJob | None = None + while job is None: + if ( + j := beaker.workload.get_latest_job(workload, task=task) + ) is not None and j.id not in preempted_job_ids: + job = j + else: + time.sleep(1.0) + + # Wait for job to start... + job = _wait_for_job_to_start( + beaker=beaker, + job=job, + status=status, + start_time=start_time, + timeout=timeout, + show_logs=show_logs, + ) + + # Stream logs... + if show_logs and job.status.HasField("started"): + print() + rich.get_console().rule("Logs") + + for job_log in beaker.job.logs(job, tail_lines=10 if tail else None, follow=True): + console.print(job_log.message.decode(), highlight=False, markup=False) + if timeout > 0 and (time.monotonic() - start_time) > timeout: + raise BeakerJobTimeoutError( + f"Timed out while waiting for job '{job.id}' to finish" + ) + + print() + rich.get_console().rule("End logs") + print() + + # Wait for job to finalize... + while not job.status.HasField("finalized"): + time.sleep(0.5) + job = beaker.job.get(job.id) + + # If job was preempted, we start over... + if _job_preempted(job): + print(f"[yellow]Job '{job.id}' preempted.[/] ") + preempted_job_ids.add(job.id) + continue + + return job diff --git a/venv/lib/python3.10/site-packages/gantry/commands/__init__.py b/venv/lib/python3.10/site-packages/gantry/commands/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..354fe95636afb45d64475dc3277f0d48ffb29725 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/commands/__init__.py @@ -0,0 +1,23 @@ +from .completion import completion +from .config import config +from .find_gpus import find_gpus_cmd +from .follow import follow +from .list import list_cmd +from .logs import logs +from .main import main +from .open import open_cmd +from .run import run +from .stop import stop + +__all__ = [ + "main", + "follow", + "run", + "config", + "stop", + "list_cmd", + "completion", + "logs", + "find_gpus_cmd", + "open_cmd", +] diff --git a/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cf0768e796c73b293cd9f5d0f7259af5ee051d5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/completion.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/completion.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35aaa095c5525ad14f673ebc4dfd20acbd1229da Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/completion.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/config.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56c5b6da3b2813ace99c75d5069c738c652801ab Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/config.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/find_gpus.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/find_gpus.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fdb167b3bf37d1b2a5f0021797b84985c764293 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/find_gpus.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/follow.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/follow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b611549859ed5c0af966c46b07fa7415d63373bc Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/follow.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/list.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/list.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57ad02c4962121ff13ae74afdb08ed8c73bb6fe4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/list.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/logs.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/logs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aaeab3d28437d7fd44046d3c7bdadd39903a31ec Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/logs.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/main.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/main.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77868a6fafe3d10e6a0a849b97fdbcfd1cecba18 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/main.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/open.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/open.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6111895b92b185882175793a939c198043e86361 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/open.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/run.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/run.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f0768c4dfa6d75cb3f9404c4e8904ebabb69535 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/run.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/stop.cpython-310.pyc b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/stop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6caea5ad949987555ac170ba0307aae38a0b1a5b Binary files /dev/null and b/venv/lib/python3.10/site-packages/gantry/commands/__pycache__/stop.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gantry/commands/completion.py b/venv/lib/python3.10/site-packages/gantry/commands/completion.py new file mode 100644 index 0000000000000000000000000000000000000000..c7cbd5d2d6faa8baa096efcbae755957b3d5dc32 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/commands/completion.py @@ -0,0 +1,51 @@ +import os + +from .main import CLICK_COMMAND_DEFAULTS, CLICK_GROUP_DEFAULTS, main + + +@main.group(**CLICK_GROUP_DEFAULTS) +def completion(): + """ + Generate the autocompletion script for gantry for the specified shell. + + See each sub-command's help for details on how to use the generated script. + """ + + +@completion.command(**CLICK_COMMAND_DEFAULTS) +def bash(): + """ + Generate the autocompletion script for bash. + + Save the output somewhere and then source the file: + + $ gantry --quiet completion bash > ~/.gantry-complete.bash && . ~/.gantry-complete.bash + """ + os.environ["_GANTRY_COMPLETE"] = "bash_source" + main() + + +@completion.command(**CLICK_COMMAND_DEFAULTS) +def fish(): + """ + Generate the autocompletion script for fish. + + Execute this once to setup completions: + + $ gantry --quiet completion fish > ~/.config/fish/completions/gantry.fish + """ + os.environ["_GANTRY_COMPLETE"] = "fish_source" + main() + + +@completion.command(**CLICK_COMMAND_DEFAULTS) +def zsh(): + """ + Generate the autocompletion script for zsh. + + Save the output somewhere and then source the file: + + $ gantry --quiet completion bash > ~/.gantry-complete.zsh && . ~/.gantry-complete.zsh + """ + os.environ["_GANTRY_COMPLETE"] = "zsh_source" + main() diff --git a/venv/lib/python3.10/site-packages/gantry/commands/config.py b/venv/lib/python3.10/site-packages/gantry/commands/config.py new file mode 100644 index 0000000000000000000000000000000000000000..ecfbbb02a6763103510c2a9a17f0631c99566db2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/commands/config.py @@ -0,0 +1,64 @@ +from typing import Optional + +import click +from rich import print + +from .. import constants, util +from .main import CLICK_COMMAND_DEFAULTS, CLICK_GROUP_DEFAULTS, main + + +@main.group(**CLICK_GROUP_DEFAULTS) +def config(): + """ + Configure Gantry for a specific Beaker workspace. + """ + + +@config.command(**CLICK_COMMAND_DEFAULTS) # type: ignore +@click.argument("token") +@click.option( + "-w", + "--workspace", + type=str, + help="""The Beaker workspace to use. + If not specified, your default workspace will be used.""", +) +@click.option( + "-s", + "--secret", + type=str, + help="""The name of the Beaker secret to write to.""", + default=constants.GITHUB_TOKEN_SECRET, + show_default=True, +) +@click.option( + "-y", + "--yes", + is_flag=True, + help="""Skip all confirmation prompts.""", +) +def set_gh_token( + token: str, + workspace: Optional[str] = None, + secret: str = constants.GITHUB_TOKEN_SECRET, + yes: bool = False, +): + """ + Set or update Gantry's GitHub token for the workspace. + + You can create a suitable GitHub token by going to https://github.com/settings/tokens/new + and generating a token with the '\N{ballot box with check} repo' scope. + + Example: + + $ gantry config set-gh-token "$GITHUB_TOKEN" + """ + # Initialize Beaker client and validate workspace. + with util.init_client(workspace=workspace, yes=yes) as beaker: + # Write token to secret. + beaker.secret.write(secret, token) + + print( + f"[green]\N{check mark} GitHub token added to workspace " + f"'{beaker.config.default_workspace}' as the secret '{secret}'" + ) diff --git a/venv/lib/python3.10/site-packages/gantry/commands/find_gpus.py b/venv/lib/python3.10/site-packages/gantry/commands/find_gpus.py new file mode 100644 index 0000000000000000000000000000000000000000..11d13597f609f999afad8d99132f70fa1dc81170 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/commands/find_gpus.py @@ -0,0 +1,82 @@ +import click +import rich +from beaker import BeakerSortOrder +from rich import print +from rich.table import Table + +from .. import util +from .main import CLICK_COMMAND_DEFAULTS, main + + +@main.command(name="find-gpus", **CLICK_COMMAND_DEFAULTS) +@click.option( + "-a", + "--all", + "show_all", + is_flag=True, + help="Show all clusters, not just ones with free GPUs.", +) +@click.option( + "-g", + "--gpu-type", + "gpu_types", + type=str, + multiple=True, + help="""Filter by GPU type (e.g. "h100"). Multiple allowed.""", +) +def find_gpus_cmd(show_all: bool = False, gpu_types: tuple[str, ...] = tuple()): + """ + Find free GPUs. + """ + gpu_types = tuple(pattern.lower() for pattern in gpu_types) + + with util.init_client(ensure_workspace=False) as beaker: + table = Table(title="Clusters", show_lines=True) + table.add_column("Name", justify="left", no_wrap=True) + table.add_column("Free GPUs", justify="left", no_wrap=True) + table.add_column("GPU Type", justify="left", no_wrap=True) + table.add_column("Slots", justify="left", no_wrap=True) + + with rich.get_console().status( + "[i]collecting clusters...[/]", spinner="point", speed=0.8 + ) as status: + for cluster in beaker.cluster.list( + sort_field="free_gpus", + sort_order=BeakerSortOrder.descending, + include_cluster_occupancy=True, + ): + status.update(f"[i]collecting clusters...[/] {cluster.name}") + + if not show_all and cluster.cluster_occupancy.slot_counts.available == 0: + break + + gpu_type = util.get_gpu_type(beaker, cluster) + if gpu_types: + if not gpu_type: + continue + + match = gpu_type.lower() + for pattern in gpu_types: + if pattern in match: + gpu_type = util.highlight_pattern(gpu_type, pattern) + break + else: + continue + + gpus_available = cluster.cluster_occupancy.slot_counts.available + gpus_available_style: str + if gpus_available == 0: + gpus_available_style = "red" + elif gpus_available < 8: + gpus_available_style = "yellow" + else: + gpus_available_style = "green" + + table.add_row( + f"[b cyan]{beaker.org_name}/{cluster.name}[/]\n[u i blue]{beaker.cluster.url(cluster)}[/]", + f"[{gpus_available_style}]{gpus_available}[/]", + f"{gpu_type or 'UNKNOWN'}", + f"{cluster.cluster_occupancy.slot_counts.assigned}/{cluster.cluster_occupancy.slot_counts.total}", + ) + + print(table) diff --git a/venv/lib/python3.10/site-packages/gantry/commands/follow.py b/venv/lib/python3.10/site-packages/gantry/commands/follow.py new file mode 100644 index 0000000000000000000000000000000000000000..56832b32a7dfd45d57e100bc683b3c087ccc47ed --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/commands/follow.py @@ -0,0 +1,73 @@ +from typing import Optional + +import click +from beaker import BeakerWorkload +from rich import print + +from .. import util +from ..api import follow_workload +from ..exceptions import ConfigurationError, NotFoundError +from .main import CLICK_COMMAND_DEFAULTS, main + + +@main.command(**CLICK_COMMAND_DEFAULTS) +@click.argument("workload", nargs=1, required=False, type=str) +@click.option( + "-t", "--tail", is_flag=True, help="Only tail the logs as opposed to printing all logs so far." +) +@click.option( + "-l", + "--latest", + is_flag=True, + help="Get the logs from the latest running experiment (non-session) workload.", +) +@click.option( + "-w", + "--workspace", + type=str, + help="""The Beaker workspace to pull experiments from. + If not specified, your default workspace will be used.""", +) +@click.option( + "-a", + "--author", + type=str, + help="Pull the latest experiment workload for a particular author. Defaults to your own account.", +) +def follow( + workload: Optional[str] = None, + tail: bool = False, + latest: bool = False, + workspace: Optional[str] = None, + author: Optional[str] = None, +): + """ + Follow the logs for a running experiment. + """ + with util.init_client(ensure_workspace=False) as beaker: + wl: Optional[BeakerWorkload] = None + if workload is not None: + if latest or workspace is not None or author is not None: + raise ConfigurationError( + "[WORKLOAD] is mutually exclusive with -a/--author, -w/--workspace, and -l/--latest" + ) + wl = beaker.workload.get(workload) + else: + if not latest: + raise ConfigurationError( + "A filter such as -l/--latest is required when no [WORKLOAD] is specified" + ) + + wl = util.get_latest_workload( + beaker, author_name=author, workspace_name=workspace, running=True + ) + if wl is None: + raise NotFoundError("Failed to find an experiment workload to follow") + + print( + f"Following experiment [b cyan]{wl.experiment.name}[/] ({wl.experiment.id}) at {beaker.workload.url(wl)}" + ) + + assert wl is not None + job = follow_workload(beaker, wl, tail=tail) + util.display_results(beaker, wl, job) diff --git a/venv/lib/python3.10/site-packages/gantry/commands/list.py b/venv/lib/python3.10/site-packages/gantry/commands/list.py new file mode 100644 index 0000000000000000000000000000000000000000..e6d3410729a9f87600699ab95c078adeb4bb5cfb --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/commands/list.py @@ -0,0 +1,259 @@ +import concurrent.futures +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timedelta, timezone +from itertools import islice +from typing import Generator, Iterable, List, Optional, Tuple + +import click +import rich +from beaker import ( + Beaker, + BeakerSortOrder, + BeakerTask, + BeakerWorkload, + BeakerWorkloadStatus, + BeakerWorkloadType, +) +from beaker.exceptions import BeakerGroupNotFound +from rich import print +from rich.table import Table + +from .. import util +from ..exceptions import ConfigurationError +from .main import CLICK_COMMAND_DEFAULTS, main + + +class Defaults: + limit = 10 + max_age = 7 + + +@main.command(name="list", **CLICK_COMMAND_DEFAULTS) +@click.option( + "-w", + "--workspace", + type=str, + help="""The Beaker workspace to pull experiments from. + If not specified, your default workspace will be used.""", +) +@click.option("-g", "--group", type=str, help="""The Beaker group to pull experiments from.""") +@click.option( + "-l", + "--limit", + type=int, + default=Defaults.limit, + help=f"Limit the number of experiments to display. Default: {Defaults.limit}", +) +@click.option( + "-a", + "--author", + type=str, + help="Filter by author. Tip: use '--me' instead to show your own experiments.", +) +@click.option( + "--me", + is_flag=True, + help="Only show your own experiments. Mutually exclusive with '--author'.", +) +@click.option( + "-s", + "--status", + type=click.Choice([x.name for x in BeakerWorkloadStatus]), + help="Filter by status. Multiple allowed.", + multiple=True, +) +@click.option( + "--max-age", + type=int, + default=Defaults.max_age, + help=f"Maximum age of experiments, in days. Default: {Defaults.max_age}", +) +@click.option( + "--all", + "show_all", + is_flag=True, + help="Show all experiments, not just onces submitted through Gantry.", +) +def list_cmd( + workspace: Optional[str] = None, + group: Optional[str] = None, + limit: int = Defaults.limit, + author: Optional[str] = None, + me: bool = False, + status: Optional[List[str]] = None, + max_age: int = Defaults.max_age, + show_all: bool = False, +): + """ + List recent experiments within a workspace or group. + This will only show experiments launched with Gantry by default, unless '--all' is specified. + """ + with util.init_client(ensure_workspace=False) as beaker: + table = Table(title="Experiments", show_lines=True) + table.add_column("Name", justify="left", no_wrap=True) + table.add_column("Author", justify="left", style="blue", no_wrap=True) + table.add_column("Created", justify="left", no_wrap=True) + table.add_column("Tasks") + + if me: + if author is not None: + raise ConfigurationError("--me and -a/--author are mutually exclusive.") + else: + author = beaker.user_name + + status_msg = "[i]collecting experiments...[/]" + with rich.get_console().status(status_msg, spinner="point", speed=0.8) as status_: + with ThreadPoolExecutor() as executor: + for wl, tasks in islice( + iter_workloads( + beaker, + executor=executor, + workspace=workspace, + group=group, + author=author, + statuses=status, + max_age=max_age, + show_all=show_all, + limit=None if not show_all else limit, + ), + limit, + ): + status_.update(f"{status_msg} [cyan]{wl.experiment.name}[/]") + + task_status_futures = [] + for task in tasks: + task_status_futures.append(executor.submit(format_task, beaker, wl, task)) + + task_statuses = {} + for task_future in concurrent.futures.as_completed(task_status_futures): + task, task_status = task_future.result() + task_statuses[task.id] = task_status + status_.update(f"{status_msg} [cyan]{wl.experiment.name} ❯ [/]{task.name}") + + table.add_row( + f"[b cyan]{wl.experiment.name}[/]\n[u i blue]{beaker.workload.url(wl)}[/]", + beaker.user.get(wl.experiment.author_id).name, + wl.experiment.created.ToDatetime(timezone.utc) + .astimezone(tz=None) + .strftime("%I:%M %p on %a, %b %-d"), + "\n".join(task_statuses[task.id] for task in tasks), + ) + + print(table) + + +def is_gantry_workload(beaker: Beaker, wl: BeakerWorkload) -> bool: + spec = beaker.experiment.get_spec(wl.experiment) + for task_spec in spec.tasks: + for env_var in task_spec.env_vars or []: + if env_var.name == "GANTRY_VERSION": + return True + return False + + +def iter_workloads( + beaker: Beaker, + *, + executor: ThreadPoolExecutor, + workspace: Optional[str], + group: Optional[str], + author: Optional[str], + statuses: Optional[List[str]], + max_age: int, + show_all: bool, + limit: Optional[int] = None, +) -> Generator[Tuple[BeakerWorkload, Iterable[BeakerTask]], None, None]: + created_after = datetime.now(tz=timezone.utc).astimezone() - timedelta(days=max_age) + author_id = None if author is None else beaker.user.get(author) + workload_statuses = ( + None if not statuses else [BeakerWorkloadStatus.from_any(s) for s in statuses] + ) + + if group is not None: + beaker_group = util.resolve_group( + beaker, group, workspace, fall_back_to_default_workspace=False + ) + if beaker_group is None: + raise BeakerGroupNotFound(group) + + # Will have to sort workloads manually by creation time, so we gather them all first. + workload_futures = [] + for task_metrics in beaker.group.list_task_metrics(beaker_group): + workload_futures.append( + executor.submit(beaker.workload.get, task_metrics.experiment_id) + ) + + workloads = [] + for future in concurrent.futures.as_completed(workload_futures): + wl = future.result() + + # Filter out non-gantry experiments. + if not show_all and not is_gantry_workload(beaker, wl): + continue + + if author_id is not None and wl.experiment.author_id != author_id: + continue + + if workload_statuses is not None and wl.status not in workload_statuses: + continue + + if wl.experiment.created.ToDatetime(timezone.utc) < created_after: + continue + + workloads.append(wl) + + workloads.sort(key=lambda wl: wl.experiment.created.ToMilliseconds(), reverse=True) + for wl in workloads: + yield wl, wl.experiment.tasks + else: + for wl in beaker.workload.list( + workspace=None if workspace is None else beaker.workspace.get(workspace), + author=author_id, + created_after=created_after, + workload_type=BeakerWorkloadType.experiment, + statuses=workload_statuses, + sort_order=BeakerSortOrder.descending, + sort_field="created", + limit=limit, + ): + # Filter out non-gantry experiments. + if not show_all and not is_gantry_workload(beaker, wl): + continue + + yield wl, wl.experiment.tasks + + +def get_status( + beaker: Beaker, wl: BeakerWorkload, task: BeakerTask +) -> Optional[BeakerWorkloadStatus]: + job = beaker.workload.get_latest_job(wl, task=task) + if job is not None: + return BeakerWorkloadStatus.from_any(job.status.status) + else: + return None + + +def format_task(beaker: Beaker, wl: BeakerWorkload, task: BeakerTask) -> tuple[BeakerTask, str]: + style = "i" + status = get_status(beaker, wl, task) + if status in ( + BeakerWorkloadStatus.running, + BeakerWorkloadStatus.succeeded, + BeakerWorkloadStatus.uploading_results, + BeakerWorkloadStatus.ready_to_start, + BeakerWorkloadStatus.initializing, + ): + style += " green" + elif status in ( + BeakerWorkloadStatus.submitted, + BeakerWorkloadStatus.queued, + BeakerWorkloadStatus.canceled, + BeakerWorkloadStatus.stopping, + ): + style += " yellow" + elif status == BeakerWorkloadStatus.failed: + style += " red" + + status_str = "unknown" if status is None else status.name + + return task, f"[i]{task.name}[/] ([{style}]{status_str}[/])" diff --git a/venv/lib/python3.10/site-packages/gantry/commands/logs.py b/venv/lib/python3.10/site-packages/gantry/commands/logs.py new file mode 100644 index 0000000000000000000000000000000000000000..385effdf81627986e3ffb219b992d737abffded0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/commands/logs.py @@ -0,0 +1,81 @@ +from typing import Optional + +import click +from beaker import Beaker, BeakerJob, BeakerTask, BeakerWorkload +from rich import print + +from .. import util +from ..exceptions import ConfigurationError +from .main import CLICK_COMMAND_DEFAULTS, main + + +def _get_job( + beaker: Beaker, wl: BeakerWorkload, task: BeakerTask, run: Optional[int] = None +) -> Optional[BeakerJob]: + if run is None: + return beaker.workload.get_latest_job(wl, task=task) + else: + # NOTE: ascending sort order on creation time is not implemented server-side yet + jobs = list(reversed(list(beaker.job.list(task=task, sort_field="created")))) + try: + return jobs[run - 1] + except IndexError: + raise ConfigurationError(f"run number {run} does not exist") + + +@main.command(**CLICK_COMMAND_DEFAULTS) +@click.argument("workload", nargs=1, type=str) +@click.option("-r", "--replica", type=int, help="""The replica rank to pull logs from.""") +@click.option("--task", "task_name", type=str, help="""The name of task to pull logs from.""") +@click.option("-t", "--tail", type=int, help="""Tail this many lines.""") +@click.option("--run", type=int, help="""The run number to pull logs from.""") +@click.option( + "-f", "--follow", is_flag=True, help="""Continue streaming logs for the duration of the job.""" +) +def logs( + workload: str, + replica: Optional[int] = None, + task_name: Optional[int] = None, + tail: Optional[int] = None, + run: Optional[int] = None, + follow: bool = False, +): + """ + Display the logs for an experiment workload. + """ + if replica is not None and task_name is not None: + raise ConfigurationError("--replica and --task are mutually exclusive") + + if run is not None and run < 1: + raise ConfigurationError("--run must be at least 1") + + with util.init_client(ensure_workspace=False) as beaker: + wl = beaker.workload.get(workload) + tasks = list(wl.experiment.tasks) + + job: Optional[BeakerJob] = None + task: Optional[BeakerTask] = None + if replica is not None: + for task in tasks: + job = _get_job(beaker, wl, task, run=run) + if job is not None and job.system_details.replica_group_details.rank == replica: + break + else: + raise ConfigurationError(f"Invalid replica rank '{replica}'") + elif task_name is not None: + for task in tasks: + if task.name == task_name: + job = _get_job(beaker, wl, task, run=run) + break + else: + raise ConfigurationError(f"Invalid task name '{task_name}'") + else: + task = tasks[0] + job = _get_job(beaker, wl, task, run=run) + + if job is None: + print("[yellow]Experiment has not started yet[/]") + return + + print(f"Showing logs from job '{job.id}' for task '{task.name}'...") + util.display_logs(beaker, job, tail_lines=tail, follow=follow) diff --git a/venv/lib/python3.10/site-packages/gantry/commands/main.py b/venv/lib/python3.10/site-packages/gantry/commands/main.py new file mode 100644 index 0000000000000000000000000000000000000000..b23cb5ebdf2591a519396bd5e2ac81a19a43dabb --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/commands/main.py @@ -0,0 +1,111 @@ +import logging +import os +import signal +import sys +from typing import Optional + +import click +import rich +from beaker.exceptions import BeakerError +from click_help_colors import HelpColorsCommand, HelpColorsGroup +from click_option_group import optgroup +from rich import pretty, traceback +from rich.logging import RichHandler + +from .. import util +from ..exceptions import * +from ..util import print_stderr +from ..version import VERSION + +CLICK_GROUP_DEFAULTS = { + "cls": HelpColorsGroup, + "help_options_color": "green", + "help_headers_color": "yellow", + "context_settings": {"max_content_width": 115}, +} + +CLICK_COMMAND_DEFAULTS = { + "cls": HelpColorsCommand, + "help_options_color": "green", + "help_headers_color": "yellow", + "context_settings": {"max_content_width": 115}, +} + + +def new_optgroup(name: str, help: Optional[str] = None): + return optgroup.group(f"\n ❯❯❯ {name}", help=help) + + +def excepthook(exctype, value, tb): + """ + Used to patch `sys.excepthook` in order to customize handling of uncaught exceptions. + """ + # Ignore in-house error types because we don't need a traceback for those. + if issubclass(exctype, (GantryError, BeakerError)): + print_stderr(f"[red][bold]{exctype.__name__}:[/] [i]{value}[/][/]") + # For interruptions, call the original exception handler. + elif issubclass(exctype, (KeyboardInterrupt, TermInterrupt)): + sys.__excepthook__(exctype, value, tb) + else: + print_stderr(traceback.Traceback.from_exception(exctype, value, tb, suppress=[click])) + + +sys.excepthook = excepthook + + +def handle_sigterm(sig, frame): + del sig, frame + raise TermInterrupt + + +@click.group(**CLICK_GROUP_DEFAULTS) # type: ignore[call-overload] +@click.version_option(version=VERSION) +@click.option( + "--quiet", + is_flag=True, + help="Don't display the gantry logo.", + envvar="GANTRY_QUIET", +) +@click.option( + "--log-level", + type=click.Choice(["debug", "info", "warning", "error"]), + show_choices=True, + show_default=True, + default="warning", + help="The Python log level.", +) +def main(quiet: bool = False, log_level: str = "warning"): + # Configure rich. + if os.environ.get("GANTRY_GITHUB_TESTING"): + # Force a broader terminal when running tests in GitHub Actions. + console_width = 180 + rich.reconfigure(width=console_width, force_terminal=True, force_interactive=False) + pretty.install() + else: + pretty.install() + + # Configure logging. + logging.basicConfig( + level=getattr(logging, log_level.upper()), + format="%(message)s", + handlers=[RichHandler(log_time_format="❯ [GANTRY (local)] [%X]")], + ) + + # Handle SIGTERM just like KeyboardInterrupt + signal.signal(signal.SIGTERM, handle_sigterm) + + if not quiet: + print_stderr( + r''' +[cyan b] o=======[] [/] +[cyan b] __ _ _ _ |_ [] [/] +[cyan b] / _` | __ _ _ _ | |_ _ _ | || | [] [/] +[cyan b] \__, | / _` | | ' \ | _| | '_| \_, | _/ ]_ [/] +[cyan b] |___/ \__,_| |_||_| _\__| _|_|_ _|__/ |_____| [/] +[blue b]_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_| """"| [/] +[blue b] `---------------------------------------------' [/] +''', # noqa: W605 + highlight=False, + ) + + util.check_for_upgrades() diff --git a/venv/lib/python3.10/site-packages/gantry/commands/open.py b/venv/lib/python3.10/site-packages/gantry/commands/open.py new file mode 100644 index 0000000000000000000000000000000000000000..5e1280f87b619d78aea4ee1f6bd2bc7ae28d848c --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/commands/open.py @@ -0,0 +1,70 @@ +import click +from beaker.exceptions import BeakerNotFoundError +from rich import print + +from .. import util +from ..exceptions import NotFoundError +from .main import CLICK_COMMAND_DEFAULTS, main + + +@main.command(name="open", **CLICK_COMMAND_DEFAULTS) +@click.argument( + "identifiers", + nargs=-1, + type=str, +) +def open_cmd(identifiers: tuple[str, ...] = tuple()): + """ + Open the page for a Beaker object in your browser. + """ + with util.init_client(ensure_workspace=False) as beaker: + for identifier in identifiers: + try: + url = beaker.workload.url(beaker.workload.get(identifier)) + print(f"Resolved workload '{identifier}' to {url}") + click.launch(url) + continue + except BeakerNotFoundError: + pass + + try: + url = beaker.workspace.url(beaker.workspace.get(identifier)) + print(f"Resolved workspace '{identifier}' to {url}") + click.launch(url) + continue + except BeakerNotFoundError: + pass + + try: + url = beaker.cluster.url(beaker.cluster.get(identifier)) + print(f"Resolved cluster '{identifier}' to {url}") + click.launch(url) + continue + except BeakerNotFoundError: + pass + + try: + url = beaker.image.url(beaker.image.get(identifier)) + print(f"Resolved image '{identifier}' to {url}") + click.launch(url) + continue + except BeakerNotFoundError: + pass + + try: + url = beaker.dataset.url(beaker.dataset.get(identifier)) + print(f"Resolved dataset '{identifier}' to {url}") + click.launch(url) + continue + except BeakerNotFoundError: + pass + + try: + url = util.group_url(beaker, beaker.group.get(identifier)) + print(f"Resolved group '{identifier}' to {url}") + click.launch(url) + continue + except BeakerNotFoundError: + pass + + raise NotFoundError(f"Beaker resource '{identifier}' not found or does not have a URL") diff --git a/venv/lib/python3.10/site-packages/gantry/commands/run.py b/venv/lib/python3.10/site-packages/gantry/commands/run.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc89a21ed5d9fa335a222ab4ac8d8a99cbd5cfd --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/commands/run.py @@ -0,0 +1,423 @@ +import click +from beaker import BeakerJobPriority +from click_option_group import optgroup + +from .. import constants +from ..api import launch_experiment +from ..exceptions import * +from ..util import get_local_python_version +from .main import CLICK_COMMAND_DEFAULTS, main, new_optgroup + + +@main.command(**CLICK_COMMAND_DEFAULTS) +@click.help_option("--help", help="Show this message and exit.") +@click.argument("args", nargs=-1) +@new_optgroup("Workload settings") +@optgroup.option( + "-n", + "--name", + type=str, + help="""A name to assign to the experiment on Beaker. Defaults to a randomly generated name.""", +) +@optgroup.option("-d", "--description", type=str, help="""A description for the experiment.""") +@optgroup.option( + "-w", + "--workspace", + type=str, + help="""The Beaker workspace to use. + If not specified, your default workspace will be used.""", +) +@optgroup.option( + "-b", "--budget", type=str, help="""The budget account to associate with the experiment.""" +) +@optgroup.option( + "--group", + "group_names", + type=str, + multiple=True, + default=None, + help="""A group to assign the experiment to. Multiple allowed.""", +) +@new_optgroup("Launch settings") +@optgroup.option( + "--show-logs/--no-logs", + default=None, + help="""Whether or not to stream the logs to stdout as the experiment runs.""", +) +@optgroup.option( + "--timeout", + type=int, + default=None, + help="""Time to wait (in seconds) for the experiment to finish. + A timeout of -1 means wait indefinitely. + A timeout of 0 means don't wait at all. + This defaults to 0 unless you set --show-logs, in which case it defaults to -1.""", + show_default=True, +) +@optgroup.option( + "--allow-dirty", + is_flag=True, + help="""Allow submitting the experiment with a dirty working directory.""", +) +@optgroup.option( + "-y", + "--yes", + is_flag=True, + help="""Skip all confirmation prompts.""", +) +@optgroup.option("--dry-run", is_flag=True, help="""Do a dry run only.""") +@optgroup.option( + "--save-spec", + type=click.Path(dir_okay=False, file_okay=True), + help="""A path to save the generated YAML Beaker experiment spec to.""", +) +@new_optgroup("Constraints") +@optgroup.option( + "-c", + "--cluster", + "clusters", + type=str, + multiple=True, + default=None, + help="""The name of a cluster to use or a glob pattern, e.g. --cluster='ai2/*-cirrascale'. + Multiple allowed. + If you don't specify a cluster or the priority, the priority will default to 'preemptible' and + the job will be able to run on any on-premise cluster.""", + show_default=True, +) +@optgroup.option( + "--gpu-type", + "gpu_types", + type=str, + multiple=True, + default=None, + help="""Filter clusters by GPU type (e.g. "--gpu-type=h100"). + Multiple allowed.""", + show_default=True, +) +@optgroup.option( + "--tag", + "tags", + type=str, + multiple=True, + default=None, + help="""Filter clusters by a tag (e.g. "--tag=storage:weka"). + Multiple allowed, in which case only clusters that have all specified tags will be used.""", +) +@optgroup.option( + "--hostname", + "hostnames", + type=str, + multiple=True, + default=None, + help="""Hostname constraints to apply to the experiment spec. This option can be used multiple times to allow + multiple hosts.""", + show_default=True, +) +@new_optgroup("Resources") +@optgroup.option( + "--cpus", + type=float, + help="""The number of logical CPU cores (e.g. 4.0, 0.5) to assign to each task replica.""", +) +@optgroup.option( + "--gpus", + type=int, + help="""The number of GPUs (e.g. 1) to assign to each task replica.""", +) +@optgroup.option( + "--memory", + type=str, + help="""The amount of system memory to assign to each task replica. + This should be specified as a number with unit suffix (e.g. 2.5GiB).""", +) +@optgroup.option( + "--shared-memory", + type=str, + help="""The size of /dev/shm as a number with unit suffix (e.g. 2.5GiB).""", +) +@new_optgroup("Inputs") +@optgroup.option( + "--beaker-image", + type=str, + help=f"""The name or ID of an image on Beaker to use for your experiment. + Mutually exclusive with --docker-image. Defaults to '{constants.DEFAULT_IMAGE}' if neither is set.""", +) +@optgroup.option( + "--docker-image", + type=str, + help="""The name of a public Docker image to use for your experiment. + Mutually exclusive with --beaker-image.""", +) +@optgroup.option( + "--dataset", + "datasets", + type=str, + multiple=True, + help="""An input dataset in the form of 'dataset-name:/mount/location' or + 'dataset-name:sub/path:/mount/location' to attach to your experiment. + You can specify this option more than once to attach multiple datasets.""", +) +@optgroup.option( + "-m", + "--mount", + "mounts", + type=str, + help="""Host directories to mount to the Beaker experiment. Should be in the form '{HOST_SOURCE}:{TARGET}' + similar to the '-v' option with 'docker run'.""", + multiple=True, +) +@optgroup.option( + "--weka", + type=str, + multiple=True, + help="""A weka bucket to mount in the form of 'bucket-name:/mount/location', + e.g. --weka=oe-training-default:/data""", +) +@optgroup.option( + "--env", + "env_vars", + type=str, + help="""Environment variables to add the Beaker experiment. Should be in the form '{NAME}={VALUE}'.""", + multiple=True, +) +@optgroup.option( + "--env-secret", + "--secret-env", + "env_secrets", + type=str, + help="""Environment variables to add the Beaker experiment from Beaker secrets. + Should be in the form '{NAME}={SECRET_NAME}'.""", + multiple=True, +) +@optgroup.option( + "--dataset-secret", + "dataset_secrets", + type=str, + help="""Mount a Beaker secret to a file as a dataset. + Should be in the form '{SECRET_NAME}:{MOUNT_PATH}'.""", + multiple=True, +) +@optgroup.option( + "--ref", + type=str, + help="""The target git ref to use. Defaults to the latest commit.""", +) +@optgroup.option( + "--branch", + type=str, + help="""The target git branch to use. Defaults to the active branch.""", +) +@optgroup.option( + "--gh-token-secret", + type=str, + help="""The name of the Beaker secret that contains your GitHub token.""", + default=constants.GITHUB_TOKEN_SECRET, + show_default=True, +) +@new_optgroup("Outputs") +@optgroup.option( + "--results", + type=str, + default=constants.RESULTS_DIR, + help="""Specify the results directory on the container (an absolute path). + This is where the results dataset will be mounted.""", + show_default=True, +) +@new_optgroup("Task settings") +@optgroup.option( + "-t", + "--task-name", + type=str, + help="""A name to assign to the task on Beaker.""", + default="main", + show_default=True, +) +@optgroup.option( + "--priority", + type=click.Choice([str(p.name) for p in BeakerJobPriority]), + help="The job priority.", +) +@optgroup.option( + "--task-timeout", + type=str, + help="""The Beaker job timeout, e.g. "24h". If a job runs longer than this it will canceled + by Beaker.""", + show_default=True, +) +@optgroup.option( + "--preemptible/--not-preemptible", + is_flag=True, + help="""Mark the job as preemptible or not. If you don't specify at least one cluster then + jobs will default to preemptible.""", + default=None, +) +@optgroup.option( + "--retries", type=int, help="""Specify the number of automatic retries for the experiment.""" +) +@new_optgroup("Multi-node config") +@optgroup.option( + "--replicas", + type=int, + help="""The number of task replicas to run.""", +) +@optgroup.option( + "--leader-selection", + is_flag=True, + help="""Specifies that the first task replica should be the leader and populates each task + with 'BEAKER_LEADER_REPLICA_HOSTNAME' and 'BEAKER_LEADER_REPLICA_NODE_ID' environment variables. + This is only applicable when '--replicas INT' and '--host-networking' are used, + although the '--host-networking' flag can be omitted in this case since it's assumed.""", +) +@optgroup.option( + "--host-networking", + is_flag=True, + help="""Specifies that each task replica should use the host's network. + When used with '--replicas INT', this allows the replicas to communicate with each + other using their hostnames.""", +) +@optgroup.option( + "--propagate-failure", is_flag=True, help="""Stop the experiment if any task fails.""" +) +@optgroup.option( + "--propagate-preemption", is_flag=True, help="""Stop the experiment if any task is preempted.""" +) +@optgroup.option( + "--synchronized-start-timeout", + type=str, + help=""" + If set, jobs in the replicated task will wait this long to start until all other jobs are also ready. + This should be specified as a duration such as '5m', '30s', etc. + """, +) +@optgroup.option( + "--skip-tcpxo-setup", + is_flag=True, + help="""By default Gantry will configure NCCL for TCPXO when running a multi-node job on Augusta + (--replicas > 1), but you can use this flag to skip that step if you need a custom configuration. + If you do use this flag, you'll probably need to follow all of the steps documented here: + + https://beaker-docs.allen.ai/compute/augusta.html#distributed-workloads""", +) +@new_optgroup("Runtime") +@optgroup.option( + "--runtime-dir", + type=str, + default=constants.RUNTIME_DIR, + help="""The runtime directory on the image.""", + show_default=True, +) +@optgroup.option( + "--exec-method", + type=click.Choice(["exec", "bash"]), + default="exec", + help="""Defines how your command+arguments are evaluated and executed at runtime. + 'exec' means gantry will call 'exec "$@"' to execute your command. + 'bash' means gantry will call 'bash -c "$*"' to execute your command. + One reason you might prefer 'bash' over 'exec' is if you have shell variables in your arguments that + you want expanded at runtime.""", + show_default=True, +) +@new_optgroup("Setup hooks") +@optgroup.option( + "--pre-setup", + type=str, + help="""Set a custom command or shell script to run before gantry's setup steps.""", +) +@optgroup.option( + "--post-setup", + type=str, + help="""Set a custom command or shell script to run after gantry's setup steps.""", +) +@new_optgroup("Python settings") +@optgroup.option( + "--python-manager", + type=click.Choice(["uv", "conda"]), + help="""The tool to use to manage Python installations and environments at runtime. + If not specified this will default to 'uv' (recommended) in most cases, unless other '--conda-*' specific options + are given (see below).""", +) +@optgroup.option( + "--default-python-version", + type=str, + default=get_local_python_version(), + help="""The default Python version to use when constructing a new Python environment. + This will be ignored if gantry is instructed to use an existing Python distribution/environment + on the image, such as with the --system-python flag, the --uv-venv option, or the --conda-env option.""", + show_default=True, +) +@optgroup.option( + "--system-python", + is_flag=True, + help="""If set, gantry will try to use the default Python installation on the image. + Though the behavior is a little different when using conda as the Python manager, in which + case gantry will try to use the base conda environment.""", +) +@optgroup.option( + "--install", + type=str, + help="""Override the default Python project installation method with a custom command or shell script, + e.g. '--install "python setup.py install"' or '--install "my-custom-install-script.sh"'.""", +) +@optgroup.option( + "--no-python", + is_flag=True, + help="""If set, gantry will skip setting up a Python environment altogether. + This can be useful if your experiment doesn't need Python or if your image + already contains a complete Python environment.""", +) +@new_optgroup( + "Python uv settings", + "Settings specific to the uv Python manager (--python-manager=uv).", +) +@optgroup.option( + "--uv-venv", + type=str, + help="""A path to a Python virtual environment on the image.""", +) +@optgroup.option( + "--uv-extra", + "uv_extras", + type=str, + multiple=True, + help="""Include optional dependencies for your local project from the specified extra name. + Can be specified multiple times. + If not provided, all extras will be installed unless --uv-no-extras is given.""", +) +@optgroup.option( + "--uv-all-extras/--uv-no-extras", + is_flag=True, + help="""Install your local project with all extra dependencies, or no extra dependencies. + This defaults to true unless --uv-extra is specified.""", + default=None, +) +@optgroup.option( + "--uv-torch-backend", + type=str, + help="""The backend to use when installing packages in the PyTorch ecosystem with uv. + Valid options are 'auto', 'cpu', 'cu128', etc.""", +) +@new_optgroup( + "Python conda settings", + "Settings specific to the conda Python manager (--python-manager=conda).", +) +@optgroup.option( + "--conda-file", + type=click.Path(exists=True, dir_okay=False), + help="""Path to a conda environment file for reconstructing your Python environment. + If not specified, an 'environment.yml'/'environment.yaml' file will be used if it exists.""", +) +@optgroup.option( + "--conda-env", + type=str, + help="""The name or path to an existing conda environment on the image to use.""", +) +def run(*args, **kwargs): + """ + Run an experiment on Beaker. + + Example: + + $ gantry run --yes --show-logs -- python -c 'print("Hello, World!")' + """ + launch_experiment(*args, **kwargs) diff --git a/venv/lib/python3.10/site-packages/gantry/commands/stop.py b/venv/lib/python3.10/site-packages/gantry/commands/stop.py new file mode 100644 index 0000000000000000000000000000000000000000..4bfed669d3802d4f4d3e541db025e4f5b3df7d8d --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/commands/stop.py @@ -0,0 +1,77 @@ +from typing import List, Optional, Sequence + +import click +from beaker import BeakerWorkload +from beaker.exceptions import BeakerWorkloadNotFound +from rich import print, prompt + +from .. import util +from ..exceptions import ConfigurationError, NotFoundError +from .main import CLICK_COMMAND_DEFAULTS, main + + +@main.command(**CLICK_COMMAND_DEFAULTS) +@click.argument("workload", nargs=-1, type=str) +@click.option( + "-l", "--latest", is_flag=True, help="""Stop your latest experiment (non-session) workload.""" +) +@click.option( + "-w", + "--workspace", + type=str, + help="""The Beaker workspace to pull experiments from. + If not specified, your default workspace will be used.""", +) +@click.option("--dry-run", is_flag=True, help="Do a dry-run without stopping any experiments.") +@click.option( + "-y", + "--yes", + is_flag=True, + help="""Skip all confirmation prompts.""", +) +def stop( + workload: Sequence[str], + latest: bool = False, + workspace: Optional[str] = None, + dry_run: bool = False, + yes: bool = False, +): + """ + Stop a running workload. + """ + if workload and latest: + raise ConfigurationError("-l/--latest is mutually exclusive with [WORKLOAD] args") + + beaker = util.init_client(ensure_workspace=False) + + workloads: List[BeakerWorkload] = [] + if workload: + for workload_name in workload: + try: + workloads.append(beaker.workload.get(workload_name)) + except BeakerWorkloadNotFound: + raise NotFoundError(f"Workload '{workload_name}' not found") + elif latest: + wl = util.get_latest_workload(beaker, workspace_name=workspace, running=True) + if wl is None: + print("[yellow]No running workloads to stop[/]") + else: + workloads.append(wl) + + for wl in workloads: + if dry_run: + print(f"[b yellow]Dry run:[/] would stop [b cyan]{wl.experiment.name}[/]") + else: + if not yes and not prompt.Confirm.ask( + f"Stop experiment [b cyan]{wl.experiment.name}[/] at [blue u]{beaker.workload.url(wl)}[/]?" + ): + print("[yellow]Skipping experiment...[/]") + continue + + try: + beaker.workload.cancel(wl) + except (BeakerWorkloadNotFound,): + pass + print( + f"[b green]\N{check mark}[/] [b cyan]{wl.experiment.name}[/] at {beaker.workload.url(wl)} stopped" + ) diff --git a/venv/lib/python3.10/site-packages/gantry/constants.py b/venv/lib/python3.10/site-packages/gantry/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..77ffbbc4d18bf1263632a9bac4e76c49d96d6b22 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/constants.py @@ -0,0 +1,7 @@ +DEFAULT_IMAGE = "petew/gantry" +ENTRYPOINT = "entrypoint.sh" +GITHUB_TOKEN_SECRET = "GITHUB_TOKEN" +RUNTIME_DIR = "/gantry-runtime" +RESULTS_DIR = "/results" +RUNTIME_DIR = "/gantry-runtime" +METRICS_FILE = f"{RESULTS_DIR}/metrics.json" diff --git a/venv/lib/python3.10/site-packages/gantry/entrypoint.sh b/venv/lib/python3.10/site-packages/gantry/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..8d72a9de36a811ec24eb1025df29df6b271f391b --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/entrypoint.sh @@ -0,0 +1,573 @@ +#!/usr/bin/env bash + +function set_shell_defaults { + set +x -eo pipefail +} + +set_shell_defaults + +start_time=$(date +%s) + +RESULTS_DIR="${RESULTS_DIR:-/results}" +mkdir -p "$RESULTS_DIR" + +GANTRY_DIR="${RESULTS_DIR}/.gantry" +mkdir -p "$GANTRY_DIR" + +GANTRY_LOGS_DIR="$GANTRY_DIR/logs" +mkdir -p "$GANTRY_LOGS_DIR" + +GANTRY_RUNTIME_DIR="${GANTRY_RUNTIME_DIR:-/gantry-runtime}" +mkdir -p "$GANTRY_RUNTIME_DIR" +cd "$GANTRY_RUNTIME_DIR" + +RESULTS_DATASET_URL="\e[94m\e[4mhttps://beaker.org/ds/$BEAKER_RESULT_DATASET_ID\e[0m" + +GANTRY_PYTHON_MANAGER="${GANTRY_PYTHON_MANAGER:-uv}" + +################################################################################################### +#################################### Start helper functions... #################################### +################################################################################################### + +function log_debug { + echo -e "\e[1m❯ [GANTRY DEBUG]\e[0m $1" +} + +function log_info { + echo -e "\e[36m\e[1m❯ [GANTRY INFO]\e[0m $1" +} + +function log_warning { + echo -e >&2 "\e[33m\e[1m❯ [GANTRY WARN]\e[0m $1" +} + +function log_error { + echo -e >&2 "\e[31m\e[1m❯ [GANTRY ERROR]\e[0m $1" +} + +function log_header { + local header="### [GANTRY] $1 ###" + local header_border="${header//?/#}" + echo -e "\e[36m\e[1m +$header_border +$header $2 +$header_border +\e[0m" +} + +# usage: with_retries MAX_RETRIES(INT) COMMAND(TEXT) [ARGS(ANY)...] +function with_retries { + local max_retries="$1" + shift 1 + local attempts=0 + + while true; do + "$@" && return 0 + + if ((++attempts >= max_retries)); then + log_error "Retries exceeded for command '$*'. Check results dataset for additional logs: $RESULTS_DATASET_URL" + return 1 + else + local pause_seconds=$((2**(attempts-1))) + if ((pause_seconds > 30)); then + pause_seconds=30 + fi + log_warning "Command '$*' failed on attempt ${attempts}, retrying in ${pause_seconds} seconds..." + sleep "$pause_seconds" + fi + done +} + +log_file_count=0 + +# usage: capture_logs NAME(TEXT) COMMAND(TEXT) [ARGS(ANY)...] +function capture_logs { + log_file_count=$((log_file_count+1)) + + local log_file + log_file="$GANTRY_LOGS_DIR/$(printf '%03d' $log_file_count)_$1.log" + shift 1 + + "$@" > "$log_file" 2>&1 && return 0 + + log_error "Command '$*' failed. Showing logs:" + cat "$log_file" + return 1 +} + +function path_prepend { + for ((i=$#; i>0; i--)); do + ARG=${!i} + if [[ -d "$ARG" ]] && [[ ":$PATH:" != *":$ARG:"* ]]; then + export PATH="$ARG${PATH:+":$PATH"}" + fi + done +} + +function get_latest_release { + if command -v jq &> /dev/null; then + curl -s "https://api.github.com/repos/$1/releases/latest" | jq -r '.tag_name' | cut -d 'v' -f 2 + else + curl -s "https://api.github.com/repos/$1/releases/latest" | grep -i "tag_name" | awk -F '"' '{print $4}' | cut -d 'v' -f 2 + fi +} + +function webi_bootstrap_gh { + curl -sS https://webi.sh/gh | sh +} + +function manual_bootstrap_gh { + local target_dir=~/.local/bin # same place webi would install gh to + local target_arch="386" # or amd64 + + local gh_version + gh_version=$(get_latest_release cli/cli) || return 1 + log_debug "Resolved latest gh release to v${gh_version}" + + local target_name="gh_${gh_version}_linux_${target_arch}" + local download_url="https://github.com/cli/cli/releases/download/v${gh_version}/${target_name}.tar.gz" + + log_debug "Downloading gh release from ${download_url}..." + curl -sLO "$download_url" || return 1 + + log_debug "Extracting release..." + tar -xzf "${target_name}.tar.gz" || return 1 + + mkdir -p "$target_dir" + mv "$target_name/bin/gh" "$target_dir/" || return 1 + rm -rf "$target_name" "${target_name}.tar.gz" + + log_debug "Installed gh to $target_dir" + "$target_dir/gh" --version +} + +function ensure_gh { + if ! command -v gh &> /dev/null; then + log_info "Installing GitHub CLI..." + # NOTE: sometimes webi has issues (https://github.com/webinstall/webi-installers/issues/1003) + # so we fall back to a manual approach if needed. + if ! with_retries 2 capture_logs "webi_bootstrap_gh" webi_bootstrap_gh; then + log_warning "Falling back to manual GitHub CLI install..." + with_retries 5 capture_logs "manual_bootstrap_gh" manual_bootstrap_gh || return 1 + fi + path_prepend ~/.local/bin + log_info "Done. Installed $(gh --version | head -n 1)." + fi +} + +function clone_repo { + if [[ -z "$GIT_BRANCH" ]]; then + if [[ -n "$GITHUB_TOKEN" ]]; then + gh repo clone "$GITHUB_REPO" . && return 0 + else + git clone "https://github.com/$GITHUB_REPO" . && return 0 + fi + else + log_info "Cloning from single branch '$GIT_BRANCH'..." + if [[ -n "$GITHUB_TOKEN" ]]; then + gh repo clone "$GITHUB_REPO" . -- -b "$GIT_BRANCH" --single-branch && return 0 + else + git clone -b "$GIT_BRANCH" --single-branch "https://github.com/$GITHUB_REPO" . && return 0 + fi + fi + + return 1 +} + +function ensure_conda { + if ! command -v conda &> /dev/null; then + log_info "Installing conda..." + + with_retries 5 capture_logs "download_miniconda" curl -fsSL -o ~/miniconda.sh -O https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh || return 1 + chmod +x ~/miniconda.sh + + capture_logs "setup_conda" ~/miniconda.sh -b -p /opt/conda || return 1 + path_prepend "/opt/conda/bin" + + rm ~/miniconda.sh + log_info "Done. Installed $(conda --version)." + fi + + if [[ -z "$GANTRY_CONDA_INITIALIZED" ]]; then + log_info "Configuring $(conda --version) for shell environment..." + # Initialize conda for bash. + # See https://stackoverflow.com/a/58081608/4151392 + eval "$(command conda 'shell.bash' 'hook' 2> /dev/null)" + + # Accept TOS for default channels. + # NOTE: this will fail if the conda version is too old. + if command conda tos &> /dev/null 2>&1; then + capture_logs "conda_tos_accept_main" conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/main + capture_logs "conda_tos_accept_r" conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/r + fi + + GANTRY_CONDA_INITIALIZED="1" + log_info "Done." + fi +} + +function bootstrap_uv { + curl -LsSf https://astral.sh/uv/install.sh | sh +} + +function ensure_uv { + if ! command -v uv &> /dev/null; then + log_info "Installing uv..." + with_retries 5 capture_logs "bootstrap_uv" bootstrap_uv || return 1 + path_prepend ~/.cargo/bin ~/.local/bin + log_info "Done. Installed $(uv --version)." + fi +} + +function ensure_pip { + log_info "Installing/upgrading PIP package manager..." + + # Use 'ensurepip' if necessary to install pip. + if ! command -v pip &> /dev/null; then + capture_logs "install_pip" python -m ensurepip + fi + + # Upgrade pip. + capture_logs "upgrade_pip" pip install --upgrade pip + + # Validate that pip is installed to the active Python environment. + if command -v dirname &> /dev/null; then + python_location=$(dirname "$(which python)") + pip_location=$(dirname "$(which pip)") + if [[ "$python_location" != "$pip_location" ]]; then + log_warning "Install location of PIP ('$pip_location') doesn't match Python location ('$python_location')" + fi + fi + + log_info "Done. Using $(pip --version)." +} + +function run_custom_cmd { + local custom_cmd_purpose=$1 + local custom_cmd=$2 + if [[ -f "$custom_cmd" ]] && [[ "${custom_cmd: -3}" == ".sh" ]]; then + log_info "Sourcing user-defined ${custom_cmd_purpose} script '${custom_cmd}'..." + + # shellcheck disable=SC1090 + source "$custom_cmd" || return 1 + + # Reset shell behavior. + set_shell_defaults + + log_info "Done." + else + log_info "Running user-defined ${custom_cmd_purpose} command: '${custom_cmd}'" + eval "$custom_cmd" || return 1 + log_info "Done." + fi +} + +function uv_install_project { + local project_file=$1 + shift 1 + + log_info "Installing local project..." + capture_logs "uv_pip_install" uv pip install "$@" -r "$project_file" . || return 1 + log_info "Done." +} + +function uv_install_requirements { + log_info "Installing packages from requirements.txt..." + capture_logs "uv_pip_install" uv pip install "$@" -r requirements.txt || return 1 + log_info "Done." +} + +function uv_setup_python { + ensure_uv || return 1 + + GANTRY_UV_FLAGS="" + + if [[ -n "$GANTRY_UV_ALL_EXTRAS" ]]; then + GANTRY_UV_FLAGS="$GANTRY_UV_FLAGS --all-extras" + elif [[ -n "$GANTRY_UV_EXTRAS" ]]; then + for extra_name in $GANTRY_UV_EXTRAS; do + GANTRY_UV_FLAGS="$GANTRY_UV_FLAGS --extra=$extra_name" + done + fi + + if [[ -n "$GANTRY_UV_VENV" ]]; then + if [[ ! -d "$GANTRY_UV_VENV" ]] || [[ ! -f "$GANTRY_UV_VENV/bin/activate" ]]; then + log_error "--uv-venv '$GANTRY_UV_VENV' should be a path to virtual env directory" + return 1 + fi + + log_info "Activating virtual environment at '$GANTRY_UV_VENV'..." + # shellcheck disable=SC1091 + source "$GANTRY_UV_VENV/bin/activate" || return 1 + log_info "Done." + elif [[ -n "$GANTRY_USE_SYSTEM_PYTHON" ]]; then + if ! command -v python &> /dev/null; then + log_error "No system python found. If your image doesn't include a Python distribution you should omit the --system-python flag." + return 1 + fi + + log_info "Using existing $(python --version) installation at '$(which python)'." + GANTRY_UV_FLAGS="$GANTRY_UV_FLAGS --system --break-system-packages" + elif [[ -n "$GANTRY_DEFAULT_PYTHON_VERSION" ]]; then + log_info "Creating virtual environment with Python ${GANTRY_DEFAULT_PYTHON_VERSION}..." + capture_logs "uv_venv_create" uv venv --python="$GANTRY_DEFAULT_PYTHON_VERSION" || return 1 + log_info "Done." + + log_info "Activating virtual environment..." + # shellcheck disable=SC1091 + source .venv/bin/activate || return 1 + log_info "Done." + else + log_info "Creating virtual environment..." + capture_logs "uv_venv_create" uv venv || return 1 + log_info "Done." + + log_info "Activating virtual environment..." + # shellcheck disable=SC1091 + source .venv/bin/activate || return 1 + log_info "Done." + fi + + UV_PYTHON="$(which python)" + export UV_PYTHON + + if [[ -z "$GANTRY_INSTALL_CMD" ]]; then + if [[ -f 'pyproject.toml' ]]; then + # shellcheck disable=SC2086 + uv_install_project pyproject.toml $GANTRY_UV_FLAGS || return 1 + elif [[ -f 'setup.py' ]]; then + # shellcheck disable=SC2086 + uv_install_project setup.py $GANTRY_UV_FLAGS || return 1 + elif [[ -f 'setup.cfg' ]]; then + # shellcheck disable=SC2086 + uv_install_project setup.cfg $GANTRY_UV_FLAGS || return 1 + elif [[ -f 'requirements.txt' ]]; then + # shellcheck disable=SC2086 + uv_install_requirements $GANTRY_UV_FLAGS || return 1 + fi + else + run_custom_cmd "install" "$GANTRY_INSTALL_CMD" || return 1 + fi + + uv pip freeze 2> /dev/null > "$GANTRY_DIR/requirements.txt" +} + +function conda_setup_python { + # Validate some options. + # --conda-file should be a file if given. + if [[ -n "$GANTRY_CONDA_FILE" ]] && [[ ! -f "$GANTRY_CONDA_FILE" ]]; then + log_error "conda environment file '$GANTRY_CONDA_FILE' not found." + return 1 + fi + # If --conda-env looks like a path, it should point to a directory. + if [[ -n "$GANTRY_CONDA_ENV" ]] && [[ "$GANTRY_CONDA_ENV" == */* ]]; then + if [[ ! -d "$GANTRY_CONDA_ENV" ]]; then + log_error "conda environment '$GANTRY_CONDA_ENV' looks like a path but it doesn't exist" + return 1 + fi + fi + + ensure_conda || return 1 + + if [[ -n "$GANTRY_CONDA_ENV" ]]; then + log_info "Activating conda environment '$GANTRY_CONDA_ENV'..." + conda activate "$GANTRY_CONDA_ENV" &> /dev/null || return 1 + log_info "Done." + + if [[ -f "$GANTRY_CONDA_FILE" ]]; then + log_info "Updating environment from conda env file '$GANTRY_CONDA_FILE'..." + capture_logs "conda_env_update" conda env update -f "$GANTRY_CONDA_FILE" || return 1 + log_info "Done." + fi + elif [[ -n "$GANTRY_USE_SYSTEM_PYTHON" ]]; then + # Try using the default 'base' environment. + if conda activate base &> /dev/null; then + log_info "Using default conda base environment." + else + log_error "No conda base environment found (required due to --system-python flag)" + return 1 + fi + + if [[ -f "$GANTRY_CONDA_FILE" ]]; then + log_info "Updating environment from conda env file '$GANTRY_CONDA_FILE'..." + capture_logs "conda_env_update" conda env update -f "$GANTRY_CONDA_FILE" || return 1 + log_info "Done." + fi + elif [[ -f "$GANTRY_CONDA_FILE" ]]; then + # Create from the environment file. + log_info "Initializing environment from conda env file '$GANTRY_CONDA_FILE'..." + capture_logs "conda_env_create" conda env create -n gantry -f "$GANTRY_CONDA_FILE" + conda activate gantry &> /dev/null || return 1 + log_info "Done." + elif [[ -n "$GANTRY_DEFAULT_PYTHON_VERSION" ]]; then + # Create a new empty environment with the default Python version. + log_info "Initializing environment with Python $GANTRY_DEFAULT_PYTHON_VERSION..." + capture_logs "conda_env_create" conda create -y -n gantry "python=$GANTRY_DEFAULT_PYTHON_VERSION" pip + conda activate gantry &> /dev/null || return 1 + log_info "Done." + else + # Create a new empty environment with whatever version of Python conda defaults to. + log_info "Initializing environment..." + capture_logs "conda_env_create" conda create -y -n gantry pip + conda activate gantry &> /dev/null || return 1 + log_info "Done." + fi + + ensure_pip || return 1 + + if [[ -z "$GANTRY_INSTALL_CMD" ]]; then + if [[ -f 'setup.py' ]] || [[ -f 'pyproject.toml' ]] || [[ -f 'setup.cfg' ]]; then + log_info "Installing local project..." + capture_logs "pip_install" pip install . || return 1 + log_info "Done." + elif [[ -f 'requirements.txt' ]]; then + log_info "Installing packages from requirements.txt..." + capture_logs "pip_install" pip install -r requirements.txt || return 1 + log_info "Done." + fi + else + run_custom_cmd "install" "$GANTRY_INSTALL_CMD" || return 1 + fi + + pip freeze > "$GANTRY_DIR/requirements.txt" +} + +function setup_python { + if [[ "$GANTRY_PYTHON_MANAGER" == "uv" ]]; then + uv_setup_python || return 1 + elif [[ "$GANTRY_PYTHON_MANAGER" == "conda" ]]; then + conda_setup_python || return 1 + else + log_error "Unknown python manager '$GANTRY_PYTHON_MANAGER'" + return 1 + fi + + if [[ -z "$PYTHONPATH" ]]; then + PYTHONPATH="$(pwd)" + else + PYTHONPATH="${PYTHONPATH}:$(pwd)" + fi + export PYTHONPATH +} + +#################################################################################################### +########################################## Start setup... ########################################## +#################################################################################################### + +if [[ -n "$GANTRY_PRE_SETUP_CMD" ]]; then + log_header "Running custom pre-setup..." + run_custom_cmd "pre-setup" "$GANTRY_PRE_SETUP_CMD" +fi + +###################################### +log_header "Validating environment..." +###################################### + +for env_var in "GANTRY_EXEC_METHOD" "GITHUB_REPO" "GIT_REF" "RESULTS_DIR" "BEAKER_RESULT_DATASET_ID" "BEAKER_NODE_HOSTNAME" "BEAKER_NODE_ID" "BEAKER_ASSIGNED_GPU_COUNT"; do + if [[ -z "${!env_var+x}" ]]; then + log_error "Required environment variable '$env_var' is empty" + exit 1 + fi +done + +log_info "Shell is $(bash --version | head -n 1)." +log_info "Running on Beaker node '${BEAKER_NODE_HOSTNAME}' (${BEAKER_NODE_ID})" +log_info "Results dataset ${RESULTS_DATASET_URL} mounted to '${RESULTS_DIR}'." + +log_info "Checking for required tools..." +for tool in "git" "curl"; do + if ! command -v "$tool" &> /dev/null; then + log_error "Required tool '$tool' is not installed, please build or use an existing image that comes with '$tool'." + exit 1 + else + log_info "Using $($tool --version | head -n 1)." + fi +done +log_info "Done." + +if [[ -n "$GITHUB_TOKEN" ]]; then + ensure_gh + # Configure git to use the GitHub CLI as a credential helper so that we can clone private repos. + gh auth setup-git +fi + +if [[ -d "/var/lib/tcpxo/lib64" ]] && [[ -n "$BEAKER_REPLICA_COUNT" ]] && [[ -z "$GANTRY_SKIP_TCPXO_SETUP" ]]; then + log_info "Configuring NCCL for GPUDirect-TCPXO..." + log_info "Note: you can skip this step if needed by adding the flag '--skip_tcpxo_setup' to your 'gantry run ...' command." + export NCCL_LIB_DIR="/var/lib/tcpxo/lib64" + export LD_LIBRARY_PATH="/var/lib/tcpxo/lib64:$LD_LIBRARY_PATH" + # shellcheck disable=SC1091 + source /var/lib/tcpxo/lib64/nccl-env-profile.sh + export NCCL_PROTO=Simple,LL128 + export NCCL_TUNER_CONFIG_PATH=/var/lib/tcpxo/lib64/a3plus_tuner_config_ll128.textproto + export NCCL_SHIMNET_GUEST_CONFIG_CHECKER_CONFIG_FILE=/var/lib/tcpxo/lib64/a3plus_guest_config_ll128.textproto + log_info "Done." +fi + +################################### +log_header "Cloning source code..." +################################### + +git config --global advice.detachedHead false + +log_info "Cloning source code..." +with_retries 5 capture_logs "clone_repo" clone_repo +log_info "Done." + +log_info "Checking out '$GIT_REF'..." +capture_logs "git_checkout" git checkout "$GIT_REF" +log_info "Done." + +log_info "Initializing git submodules..." +capture_logs "init_submodules" git submodule update --init --recursive +log_info "Done." + +if [[ -z "$GANTRY_NO_PYTHON" ]]; then + ################################### + log_header "Building Python env..." + ################################### + setup_python + + #################################### + log_header "Python environment info" + #################################### + log_info "Using $(python --version) from '$(which python)'." + if [[ -f "$GANTRY_DIR/requirements.txt" ]]; then + log_info "Packages:" + cat "$GANTRY_DIR/requirements.txt" + fi +elif [[ -n "$GANTRY_INSTALL_CMD" ]]; then + ###################################### + log_header "Running custom install..." + ###################################### + run_custom_cmd "install" "$GANTRY_INSTALL_CMD" +fi + +if [[ -n "$GANTRY_POST_SETUP_CMD" ]]; then + ######################################### + log_header "Running custom post-setup..." + ######################################### + run_custom_cmd "post-setup" "$GANTRY_POST_SETUP_CMD" +fi + +if ((BEAKER_ASSIGNED_GPU_COUNT > 0)) && command -v nvidia-smi &> /dev/null; then + ################################# + log_header "NVIDIA system status" + ################################# + nvidia-smi +fi + +end_time=$(date +%s) +############################################################################## +log_header "Setup complete" "(finished in $((end_time-start_time)) seconds)" +############################################################################## + +# Execute the arguments to this script as commands themselves. +if [[ "$GANTRY_EXEC_METHOD" == "exec" ]]; then + exec "$@" +elif [[ "$GANTRY_EXEC_METHOD" == "bash" ]]; then + bash -c "$*" +else + log_error "Unknown value for --exec-method, got '$GANTRY_EXEC_METHOD'." + exit 1 +fi diff --git a/venv/lib/python3.10/site-packages/gantry/exceptions.py b/venv/lib/python3.10/site-packages/gantry/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..0ab7cc39b81c6036b82a0e0057f9cea14662d015 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/exceptions.py @@ -0,0 +1,52 @@ +class GantryError(Exception): + """ + Base exception for all error types that Gantry might raise. + """ + + +class GitError(GantryError): + pass + + +class DirtyRepoError(GitError): + pass + + +class UnpushedChangesError(GitError): + pass + + +class InvalidRemoteError(GitError): + pass + + +class RemoteBranchNotFoundError(GitError): + pass + + +class ConfigurationError(GantryError): + pass + + +class ExperimentFailedError(GantryError): + pass + + +class EntrypointChecksumError(GantryError): + pass + + +class GitHubTokenSecretNotFound(GantryError): + pass + + +class TermInterrupt(GantryError): + pass + + +class NotFoundError(GantryError): + pass + + +class BeakerJobTimeoutError(GantryError, TimeoutError): + pass diff --git a/venv/lib/python3.10/site-packages/gantry/git_utils.py b/venv/lib/python3.10/site-packages/gantry/git_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cabedafa42d3a09912f54715a8bd20d6763f2b2a --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/git_utils.py @@ -0,0 +1,196 @@ +from __future__ import annotations + +import logging +from dataclasses import dataclass +from functools import cache, cached_property +from pathlib import Path +from typing import cast + +import requests +from git import InvalidGitRepositoryError +from git.cmd import Git +from git.refs import Head, RemoteReference +from git.repo import Repo + +from .aliases import PathOrStr +from .exceptions import * +from .util import print_stderr + +__all__ = ["GitRepoState"] + +log = logging.getLogger(__name__) + + +def _parse_git_remote_url(url: str) -> tuple[str, str]: + """ + Parse a git remote URL into a GitHub (account, repo) pair. + + :raises InvalidRemoteError: If the URL can't be parsed correctly. + """ + try: + account, repo = ( + url.split("https://github.com/")[-1] + .split("git@github.com:")[-1] + .split(".git")[0] + .split("/") + ) + except ValueError: + raise InvalidRemoteError(f"Failed to parse GitHub repo path from remote '{url}'") + return account, repo + + +@cache +def _resolve_repo() -> Repo: + try: + return Repo(".") + except InvalidGitRepositoryError as e: + raise GitError("gantry must be run from the ROOT of a valid git repository!") from e + + +@dataclass +class GitRepoState: + """ + Represents the state of a local git repository. + + .. tip:: + Use :meth:`from_env()` to instantiate this class. + """ + + repo: str + """ + The repository name, e.g. ``"allenai/beaker-gantry"``. + """ + repo_url: str + """ + The repository URL for cloning, e.g. ``"https://github.com/allenai/beaker-gantry"``. + """ + ref: str + """ + The current ref. + """ + branch: str | None = None + """ + The current active branch, if any. + """ + + @property + def is_dirty(self) -> bool: + """ + If the local repository state is dirty (uncommitted changes). + """ + repo = _resolve_repo() + return repo.is_dirty() + + @cached_property + def is_public(self) -> bool: + """ + If the repository is public. + """ + response = requests.get(self.repo_url) + if response.status_code not in {200, 404}: + response.raise_for_status() + return response.status_code == 200 + + @property + def ref_url(self) -> str: + """ + The URL to the current :data:`ref`. + """ + return f"{self.repo_url}/commit/{self.ref}" + + @property + def branch_url(self) -> str | None: + """ + The URL to the current active :data:`branch`. + """ + if self.branch is None: + return None + else: + return f"{self.repo_url}/tree/{self.branch}" + + def is_in_tree(self, path: PathOrStr) -> bool: + """ + Check if a file is in the tree. + """ + try: + path = Path(path).resolve().relative_to(Path("./").resolve()) + except ValueError: + return False + + repo = _resolve_repo() + tree = repo.commit(self.ref).tree + return str(path) in tree + + @classmethod + def from_env(cls, ref: str | None = None, branch: str | None = None) -> GitRepoState: + """ + Instantiate this class from the root of a git repository. + + :raises ~gantry.exceptions.GitError: If this method isn't called from the + root of a valid git repository. + :raises ~gantry.exceptions.UnpushedChangesError: If there are unpushed commits. + :raises ~gantry.exceptions.RemoteBranchNotFoundError: If the local branch is not tracking + a remote branch. + """ + repo = _resolve_repo() + git = Git(".") + + git_ref = ref or str(repo.commit()) + remote = repo.remote() + + active_branch: Head | None = None + if branch is not None: + active_branch = Head(repo, f"refs/heads/{branch}") + else: + try: + active_branch = repo.active_branch + except TypeError: + print_stderr( + "[yellow]Repo is in 'detached HEAD' state which will result in cloning the entire repo at runtime.\n" + "It's recommended to run gantry from a branch instead.[/]" + ) + + remote_branch: RemoteReference | None = None + if active_branch is not None: + remote_branch = active_branch.tracking_branch() + if remote_branch is None: + raise RemoteBranchNotFoundError( + f"Failed to resolve remote tracking branch for local branch '{active_branch.name}'.\n" + f"Please make sure your branch exists on the remote, e.g. 'git push --set-upstream {remote.name}'." + ) + + remote_branches_containing_ref = { + remote_branch_name.strip() + for remote_branch_name in cast( + str, + git.execute(["git", "branch", "-r", "--contains", git_ref], stdout_as_string=True), + ) + .strip() + .split("\n") + } + + branch_name: str | None = None + if remote_branch is not None: + assert remote_branch.name.startswith(remote_branch.remote_name + "/") + remote = repo.remote(remote_branch.remote_name) + branch_name = remote_branch.name.replace(remote_branch.remote_name + "/", "", 1) + if remote_branch.name not in remote_branches_containing_ref: + raise UnpushedChangesError( + f"Current git ref '{git_ref}' does not appear to exist on the remote tracking branch '{remote_branch.name}'!\n" + "Please push your changes and try again." + ) + else: + if not remote_branches_containing_ref: + raise UnpushedChangesError( + f"Current git ref '{git_ref}' does not appear to exist on the remote!\n" + "Please push your changes and try again." + ) + + account, repo_name = _parse_git_remote_url(remote.url) + + return cls( + repo=f"{account}/{repo_name}", + repo_url=f"https://github.com/{account}/{repo_name}", + ref=git_ref, + branch=branch_name, + ) diff --git a/venv/lib/python3.10/site-packages/gantry/py.typed b/venv/lib/python3.10/site-packages/gantry/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/gantry/util.py b/venv/lib/python3.10/site-packages/gantry/util.py new file mode 100644 index 0000000000000000000000000000000000000000..d85e6a78f8e267d761c0480b5808217a8e9e04ce --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/util.py @@ -0,0 +1,521 @@ +import binascii +import json +import platform +import tempfile +import time +from collections import defaultdict +from dataclasses import asdict, dataclass +from datetime import timedelta +from enum import Enum +from fnmatch import fnmatch +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Sequence, cast + +import rich +from beaker import ( + Beaker, + BeakerCancelationCode, + BeakerCluster, + BeakerDataset, + BeakerDatasetFileAlgorithmType, + BeakerGpuType, + BeakerGroup, + BeakerJob, + BeakerSortOrder, + BeakerWorkload, + BeakerWorkloadStatus, + BeakerWorkloadType, + BeakerWorkspace, +) +from beaker.exceptions import ( + BeakerDatasetConflict, + BeakerSecretNotFound, + BeakerWorkspaceNotSet, +) +from rich import print, prompt +from rich.console import Console + +from . import constants +from .exceptions import * +from .version import VERSION + +VERSION_CHECK_INTERVAL = 12 * 3600 # 12 hours +DEFAULT_INTERNAL_CONFIG_LOCATION: Optional[Path] = None +try: + DEFAULT_INTERNAL_CONFIG_LOCATION = Path.home() / ".beaker" / ".beaker-gantry.json" +except RuntimeError: + # Can't locate home directory. + pass + + +class StrEnum(str, Enum): + def __str__(self) -> str: + return self.value + + +@dataclass +class InternalConfig: + version_checked: Optional[float] = None + + @classmethod + def load(cls) -> Optional["InternalConfig"]: + path = DEFAULT_INTERNAL_CONFIG_LOCATION + if path is None: + return None + elif path.is_file(): + with open(path, "r") as f: + return cls(**json.load(f)) + else: + return cls() + + def save(self): + path = DEFAULT_INTERNAL_CONFIG_LOCATION + if path is None: + return None + else: + path.parent.mkdir(exist_ok=True, parents=True) + with open(path, "w") as f: + json.dump(asdict(self), f) + + +def unique_name() -> str: + import uuid + + import petname + + return cast(str, petname.generate()) + "-" + str(uuid.uuid4())[:7] + + +def get_local_python_version() -> str: + return ".".join(platform.python_version_tuple()[:-1]) + + +def stderr_console() -> Console: + return Console(stderr=True) + + +def print_stderr(*args, **kwargs): + stderr_console().print(*args, **kwargs) + + +def print_exception(*args, **kwargs): + stderr_console().print_exception(*args, **kwargs) + + +def get_latest_workload( + beaker: Beaker, + *, + author_name: Optional[str] = None, + workspace_name: Optional[str] = None, + running: bool = False, +) -> Optional[BeakerWorkload]: + workspace = beaker.workspace.get(workspace_name) + + workloads = list( + beaker.workload.list( + workspace=workspace, + finalized=not running, + workload_type=BeakerWorkloadType.experiment, + sort_order=BeakerSortOrder.descending, + sort_field="created", + author=None if author_name is None else beaker.user.get(author_name), + limit=1, + ) + ) + + if workloads: + return workloads[0] + else: + return None + + +def display_logs( + beaker: Beaker, job: BeakerJob, tail_lines: Optional[int] = None, follow: bool = True +) -> BeakerJob: + console = rich.get_console() + print() + rich.get_console().rule("Logs") + for job_log in beaker.job.logs(job, follow=follow, tail_lines=tail_lines): + console.print(job_log.message.decode(), highlight=False, markup=False) + print() + rich.get_console().rule("End logs") + return beaker.job.get(job.id) + + +def get_job_status_str(job: BeakerJob): + status = job.status.status + canceled_code = job.status.canceled_code + if status == BeakerWorkloadStatus.canceled: + if canceled_code == BeakerCancelationCode.sibling_task_failed: + return "canceled due to sibling task failure" + else: + return "canceled" + elif status == BeakerWorkloadStatus.failed: + return f"failed with exit code {job.status.exit_code}" + else: + return str(BeakerWorkloadStatus(status).name) + + +def display_results(beaker: Beaker, workload: BeakerWorkload, job: BeakerJob): + status = job.status.status + if status == BeakerWorkloadStatus.succeeded: + runtime = job.status.exited - job.status.started # type: ignore + results_ds = beaker.dataset.get(job.assignment_details.result_dataset_id) + + print( + f"[b green]\N{check mark}[/] [b cyan]{beaker.user_name}/{workload.experiment.name}[/] ({workload.experiment.id}) completed successfully\n" + f"[b]Experiment:[/] {beaker.workload.url(workload)}\n" + f"[b]Results:[/] {beaker.dataset.url(results_ds)}\n" + f"[b]Runtime:[/] {format_timedelta(runtime)}" + ) + + if job.metrics: + from google.protobuf.json_format import MessageToDict + + print("[b]Metrics:[/]", MessageToDict(job.metrics)) + elif status in (BeakerWorkloadStatus.canceled, BeakerWorkloadStatus.failed): + if len(list(workload.experiment.tasks)) > 1: + show_all_jobs(beaker, workload) + print() + raise ExperimentFailedError( + f"Job {get_job_status_str(job)}, {beaker.workload.url(workload)} for details" + ) + else: + raise ValueError(f"unexpected workload status '{status}'") + + +def show_all_jobs(beaker: Beaker, workload: BeakerWorkload): + print("Tasks:") + task_name: Optional[str] = None + for task in workload.experiment.tasks: + task_name = task.name + job = beaker.workload.get_latest_job(workload, task=task) + assert job is not None + status_str = get_job_status_str(job) + style = "[white]" + if job.status.status == BeakerWorkloadStatus.failed: + style = "[red]" + elif job.status.status == BeakerWorkloadStatus.canceled: + style = "[yellow]" + print(f"❯ {style}'{task_name}'[/] {status_str} - see {beaker.job.url(job)}") + + assert task_name is not None + print( + f"\nYou can show the logs for a particular task by running:\n" + f"[i][blue]gantry[/] [cyan]logs {workload.experiment.id} --tail=1000 --task={task_name}[/][/]" + ) + + +def resolve_group( + beaker: Beaker, + group_name: str, + workspace_name: Optional[str] = None, + fall_back_to_default_workspace: bool = True, +) -> Optional[BeakerGroup]: + workspace: Optional[BeakerWorkspace] = None + if workspace_name is not None or fall_back_to_default_workspace: + workspace = beaker.workspace.get(workspace_name) + + group_owner: Optional[str] = None + if "/" in group_name: + group_owner, group_name = group_name.split("/", 1) + + for group in beaker.group.list(workspace=workspace, name_or_description=group_name): + if group_owner is not None: + if f"{group_owner}/{group_name}" == group.full_name: + return group + elif group_name == group.name: + return group + return None + + +def group_url(beaker: Beaker, group: BeakerGroup) -> str: + # NOTE: work-around for https://github.com/allenai/beaker-web/issues/1109, short group URLs + # don't resolve at the moment. + org_name = beaker.org_name + workspace_name = beaker.workspace.get(group.workspace_id).name.split("/", 1)[-1] + return f"{beaker.config.agent_address}/orgs/{org_name}/workspaces/{workspace_name}/groups/{group.id}" + + +def get_gpu_type(beaker: Beaker, cluster: BeakerCluster) -> str | None: + nodes = list(beaker.node.list(cluster=cluster, limit=1)) + if nodes: + try: + return BeakerGpuType(nodes[0].node_resources.gpu_type).name.replace("_", " ") + except ValueError: + return None + else: + return None + + +def filter_clusters_by_name( + beaker: Beaker, clusters: Iterable[BeakerCluster], patterns: Sequence[str] +) -> List[BeakerCluster]: + matches = set() + matches_by_pattern: Dict[str, int] = defaultdict(int) + final_clusters = [] + for cl in clusters: + cl_aliases = list(cl.aliases) + [cl.name] + for pattern in patterns: + og_pattern = pattern + if "/" in pattern: + org, pattern = pattern.split("/", 1) + else: + org = beaker.org_name + + if cl.organization_name != org: + continue + + if "*" in pattern: + if not any([fnmatch(alias, pattern) for alias in cl_aliases]): + continue + elif not any([alias == pattern for alias in cl_aliases]): + continue + + matches_by_pattern[og_pattern] += 1 + if cl.id not in matches: + matches.add(cl.id) + final_clusters.append(cl) + + for pattern in patterns: + if matches_by_pattern[pattern] == 0: + raise ConfigurationError(f"'{pattern}' didn't match any allowed clusters") + + return final_clusters + + +def filter_clusters_by_tags( + beaker: Beaker, + clusters: Iterable[BeakerCluster], + tags: Sequence[str], +) -> List[BeakerCluster]: + del beaker + final_clusters = [] + for cl in clusters: + cl_tags = set(cl.tags) + if all([tag in cl_tags for tag in tags]): + final_clusters.append(cl) + return final_clusters + + +def filter_clusters_by_gpu_type( + beaker: Beaker, + clusters: Iterable[BeakerCluster], + gpu_types: Sequence[str], +) -> List[BeakerCluster]: + final_clusters = [] + for cl in clusters: + cl_gpu_type = get_gpu_type(beaker, cl) + if not cl_gpu_type: + continue + for pattern in gpu_types: + if pattern.lower() in cl_gpu_type.lower(): + final_clusters.append(cl) + break + return final_clusters + + +def ensure_entrypoint_dataset(beaker: Beaker) -> BeakerDataset: + import hashlib + from importlib.resources import read_binary + + import gantry + + workspace = beaker.workspace.get() + + # Get hash of the local entrypoint source file. + sha256_hash = hashlib.sha256() + contents = read_binary(gantry, constants.ENTRYPOINT) + sha256_hash.update(contents) + + entrypoint_dataset_name = f"gantry-v{VERSION}-{workspace.id}-{sha256_hash.hexdigest()[:6]}" + + def get_dataset() -> Optional[BeakerDataset]: + matching_datasets = list( + beaker.dataset.list( + workspace=workspace, name_or_description=entrypoint_dataset_name, results=False + ) + ) + if matching_datasets: + return matching_datasets[0] + else: + return None + + # Ensure gantry entrypoint dataset exists. + gantry_entrypoint_dataset = get_dataset() + if gantry_entrypoint_dataset is None: + # Create it. + print(f"Creating entrypoint dataset '{entrypoint_dataset_name}'") + try: + with tempfile.TemporaryDirectory() as tmpdirname: + tmpdir = Path(tmpdirname) + entrypoint_path = tmpdir / constants.ENTRYPOINT + with open(entrypoint_path, "wb") as entrypoint_file: + entrypoint_file.write(contents) + gantry_entrypoint_dataset = beaker.dataset.create( + entrypoint_dataset_name, entrypoint_path + ) + except BeakerDatasetConflict: # could be in a race with another `gantry` process. + time.sleep(1.0) + gantry_entrypoint_dataset = get_dataset() + + if gantry_entrypoint_dataset is None: + raise RuntimeError(f"Failed to resolve entrypoint dataset '{entrypoint_dataset_name}'") + + # Verify contents. + ds_files = list(beaker.dataset.list_files(gantry_entrypoint_dataset)) + for retry in range(1, 4): + ds_files = list(beaker.dataset.list_files(gantry_entrypoint_dataset)) + if len(ds_files) >= 1: + break + else: + time.sleep(1.5**retry) + + if len(ds_files) != 1: + raise EntrypointChecksumError( + f"Entrypoint dataset {beaker.dataset.url(gantry_entrypoint_dataset)} is missing the " + f"required entrypoint file. Please run again." + ) + + if ds_files[0].HasField("digest"): + digest = ds_files[0].digest + expected_value = binascii.hexlify(digest.value).decode() + hasher = BeakerDatasetFileAlgorithmType(digest.algorithm).hasher() + hasher.update(contents) + actual_value = binascii.hexlify(hasher.digest()).decode() + if actual_value != expected_value: + raise EntrypointChecksumError( + f"Checksum failed for entrypoint dataset {beaker.dataset.url(gantry_entrypoint_dataset)}\n" + f"This could be a bug, or it could mean someone has tampered with the dataset.\n" + f"If you're sure no one has tampered with it, you can delete the dataset from " + f"the Beaker dashboard and try again.\n" + f"Actual digest:\n{digest}" + ) + + return gantry_entrypoint_dataset + + +def ensure_github_token_secret( + beaker: Beaker, secret_name: str = constants.GITHUB_TOKEN_SECRET +) -> str: + try: + beaker.secret.get(secret_name) + except BeakerSecretNotFound: + raise GitHubTokenSecretNotFound( + f"GitHub token secret '{secret_name}' not found in Beaker workspace!\n" + f"You can create a suitable GitHub token by going to https://github.com/settings/tokens/new " + f"and generating a token with '\N{ballot box with check} repo' scope.\n" + f"Then upload your token as a Beaker secret using the Beaker CLI or Python client." + ) + return secret_name + + +def format_timedelta(td: "timedelta") -> str: + def format_value_and_unit(value: int, unit: str) -> str: + if value == 1: + return f"{value} {unit}" + else: + return f"{value} {unit}s" + + parts = [] + seconds = int(td.total_seconds()) + days, seconds = divmod(seconds, 86400) + hours, seconds = divmod(seconds, 3600) + minutes, seconds = divmod(seconds, 60) + if days: + parts.append(format_value_and_unit(days, "day")) + if hours: + parts.append(format_value_and_unit(hours, "hour")) + if minutes: + parts.append(format_value_and_unit(minutes, "minute")) + if seconds: + parts.append(format_value_and_unit(seconds, "second")) + return ", ".join(parts) + + +def check_for_upgrades(force: bool = False): + config = InternalConfig.load() + if ( + not force + and config is not None + and config.version_checked is not None + and (time.time() - config.version_checked <= VERSION_CHECK_INTERVAL) + ): + return + + import packaging.version + import requests + + try: + response = requests.get( + "https://pypi.org/simple/beaker-gantry", + headers={"Accept": "application/vnd.pypi.simple.v1+json"}, + timeout=2, + ) + if response.ok: + latest_version = packaging.version.parse(response.json()["versions"][-1]) + current_version = packaging.version.parse(VERSION) + if latest_version > current_version and ( + not latest_version.is_prerelease or current_version.is_prerelease + ): + print_stderr( + f":warning: [yellow]You're using [b]gantry v{VERSION}[/], " + f"but a newer version ([b]v{latest_version}[/]) is available: " + f"https://github.com/allenai/beaker-gantry/releases/tag/v{latest_version}[/]\n" + f"[yellow i]You can upgrade by running:[/] pip install --upgrade beaker-gantry beaker-py\n", + ) + if config is not None: + config.version_checked = time.time() + config.save() + except (requests.exceptions.Timeout, requests.exceptions.ConnectionError): + pass + + +def init_client( + workspace: Optional[str] = None, + yes: bool = False, + ensure_workspace: bool = True, +) -> Beaker: + Beaker.MAX_RETRIES = 10_000 # effectively retry forever + Beaker.BACKOFF_MAX = 32 + + beaker = ( + Beaker.from_env() if workspace is None else Beaker.from_env(default_workspace=workspace) + ) + + if ensure_workspace and workspace is None: + try: + default_workspace = beaker.workspace.get() + if not yes and not prompt.Confirm.ask( + f"Using default workspace [b cyan]{default_workspace.name}[/]. [i]Is that correct?[/]" + ): + raise KeyboardInterrupt + except BeakerWorkspaceNotSet: + raise ConfigurationError( + "'--workspace' option is required since you don't have a default workspace set" + ) + return beaker + + +def highlight_pattern(s: str, pattern: str) -> str: + match = s.lower() + pattern = pattern.lower() + start_offset = 0 + while (match_start := match.find(pattern, start_offset)) > -1: + match_str = f"[b green]{pattern.upper()}[/]" + s = s[:match_start] + match_str + s[match_start + len(pattern) :] + start_offset = match_start + len(match_str) + match = s.lower() + return s + + +def replace_tags(contents: bytes) -> bytes: + tag_start = contents.find(b"${{") + while tag_start != -1: + tag_end = contents.find(b"}}") + 2 + tag = contents[tag_start:tag_end] + constant_name = tag.split(b" ")[1].decode() + contents = contents.replace(tag, getattr(constants, constant_name).encode()) # type: ignore + tag_start = contents.find(b"${{", tag_end) + assert b"${{" not in contents + return contents diff --git a/venv/lib/python3.10/site-packages/gantry/version.py b/venv/lib/python3.10/site-packages/gantry/version.py new file mode 100644 index 0000000000000000000000000000000000000000..ea9d6945b459283475935a36a159a5b298462718 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gantry/version.py @@ -0,0 +1 @@ +VERSION = "3.0.0" diff --git a/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/METADATA b/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..11b025408db184aa76fbf2c73b7ac52c6a48de8d --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/METADATA @@ -0,0 +1,75 @@ +Metadata-Version: 2.4 +Name: google-api-core +Version: 2.25.1 +Summary: Google API client core library +Author-email: Google LLC +License: Apache 2.0 +Project-URL: Documentation, https://googleapis.dev/python/google-api-core/latest/ +Project-URL: Repository, https://github.com/googleapis/python-api-core +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +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.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Operating System :: OS Independent +Classifier: Topic :: Internet +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: googleapis-common-protos<2.0.0,>=1.56.2 +Requires-Dist: protobuf!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<7.0.0,>=3.19.5 +Requires-Dist: proto-plus<2.0.0,>=1.22.3 +Requires-Dist: proto-plus<2.0.0,>=1.25.0; python_version >= "3.13" +Requires-Dist: google-auth<3.0.0,>=2.14.1 +Requires-Dist: requests<3.0.0,>=2.18.0 +Provides-Extra: async-rest +Requires-Dist: google-auth[aiohttp]<3.0.0,>=2.35.0; extra == "async-rest" +Provides-Extra: grpc +Requires-Dist: grpcio<2.0.0,>=1.33.2; extra == "grpc" +Requires-Dist: grpcio<2.0.0,>=1.49.1; python_version >= "3.11" and extra == "grpc" +Requires-Dist: grpcio-status<2.0.0,>=1.33.2; extra == "grpc" +Requires-Dist: grpcio-status<2.0.0,>=1.49.1; python_version >= "3.11" and extra == "grpc" +Provides-Extra: grpcgcp +Requires-Dist: grpcio-gcp<1.0.0,>=0.2.2; extra == "grpcgcp" +Provides-Extra: grpcio-gcp +Requires-Dist: grpcio-gcp<1.0.0,>=0.2.2; extra == "grpcio-gcp" +Dynamic: license-file + +Core Library for Google Client Libraries +======================================== + +|pypi| |versions| + +This library is not meant to stand-alone. Instead it defines +common helpers used by all Google API clients. For more information, see the +`documentation`_. + +.. |pypi| image:: https://img.shields.io/pypi/v/google-api_core.svg + :target: https://pypi.org/project/google-api_core/ +.. |versions| image:: https://img.shields.io/pypi/pyversions/google-api_core.svg + :target: https://pypi.org/project/google-api_core/ +.. _documentation: https://googleapis.dev/python/google-api-core/latest + + +Supported Python Versions +------------------------- +Python >= 3.7 + + +Unsupported Python Versions +--------------------------- + +Python == 2.7, Python == 3.5, Python == 3.6. + +The last version of this library compatible with Python 2.7 and 3.5 is +`google-api-core==1.31.1`. + +The last version of this library compatible with Python 3.6 is +`google-api-core==2.8.2`. diff --git a/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/RECORD b/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..9175a1b90f84f8ed04080b3a2dbcec31ea5f2df5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/RECORD @@ -0,0 +1,125 @@ +google/api_core/__init__.py,sha256=bCgLRZtOkaVlSxTPG_o1x4V0w5FJAWREIlnq3kCfqeY,782 +google/api_core/__pycache__/__init__.cpython-310.pyc,, +google/api_core/__pycache__/_rest_streaming_base.cpython-310.pyc,, +google/api_core/__pycache__/bidi.cpython-310.pyc,, +google/api_core/__pycache__/client_info.cpython-310.pyc,, +google/api_core/__pycache__/client_logging.cpython-310.pyc,, +google/api_core/__pycache__/client_options.cpython-310.pyc,, +google/api_core/__pycache__/datetime_helpers.cpython-310.pyc,, +google/api_core/__pycache__/exceptions.cpython-310.pyc,, +google/api_core/__pycache__/extended_operation.cpython-310.pyc,, +google/api_core/__pycache__/general_helpers.cpython-310.pyc,, +google/api_core/__pycache__/grpc_helpers.cpython-310.pyc,, +google/api_core/__pycache__/grpc_helpers_async.cpython-310.pyc,, +google/api_core/__pycache__/iam.cpython-310.pyc,, +google/api_core/__pycache__/operation.cpython-310.pyc,, +google/api_core/__pycache__/operation_async.cpython-310.pyc,, +google/api_core/__pycache__/page_iterator.cpython-310.pyc,, +google/api_core/__pycache__/page_iterator_async.cpython-310.pyc,, +google/api_core/__pycache__/path_template.cpython-310.pyc,, +google/api_core/__pycache__/protobuf_helpers.cpython-310.pyc,, +google/api_core/__pycache__/rest_helpers.cpython-310.pyc,, +google/api_core/__pycache__/rest_streaming.cpython-310.pyc,, +google/api_core/__pycache__/rest_streaming_async.cpython-310.pyc,, +google/api_core/__pycache__/retry_async.cpython-310.pyc,, +google/api_core/__pycache__/timeout.cpython-310.pyc,, +google/api_core/__pycache__/universe.cpython-310.pyc,, +google/api_core/__pycache__/version.cpython-310.pyc,, +google/api_core/__pycache__/version_header.cpython-310.pyc,, +google/api_core/_rest_streaming_base.py,sha256=AlkPe71v0kRUeWP5yn6N1KbxCxKhr-vfQOCgoF6x8ZE,4351 +google/api_core/bidi.py,sha256=uF3Zmgy76WhUtnesEJAKnVlsIOaGMM6Iihoivg9K8Ls,28685 +google/api_core/client_info.py,sha256=A1yzixILdp55Rk8Hu1m7QGlnOh6CGMWhKLNi9TUotRU,4092 +google/api_core/client_logging.py,sha256=o7VrcpJ5yqIfdpBDGKTIIVaqIfl5Ppr_AxiOfyKIGTk,5023 +google/api_core/client_options.py,sha256=3wXyTuP91oqIopt-ZuMqrGO5mP2nZKB-PcxXIHAfOjs,6566 +google/api_core/datetime_helpers.py,sha256=5gFi7n0r-xVImQdj6rQKNwk58m2LcMF9WliXGHbBsDA,9034 +google/api_core/exceptions.py,sha256=5VXhbkcGCrfjo6tzP4hCVh6vakqGM7kZSewVj6pCS8M,21150 +google/api_core/extended_operation.py,sha256=r9xSOblNF35lwn2hrrjUQ-f3JDoo0a4Z8xwOy_VkvL0,8632 +google/api_core/future/__init__.py,sha256=7sToxNNu9c_xqcpmO8dbrcSLOOxplnYOOSXjOX9QIXw,702 +google/api_core/future/__pycache__/__init__.cpython-310.pyc,, +google/api_core/future/__pycache__/_helpers.cpython-310.pyc,, +google/api_core/future/__pycache__/async_future.cpython-310.pyc,, +google/api_core/future/__pycache__/base.cpython-310.pyc,, +google/api_core/future/__pycache__/polling.cpython-310.pyc,, +google/api_core/future/_helpers.py,sha256=jA6m2L1aqlOJA-9NdC1BDosPksZQ7FmLLYWDOrsQOPc,1248 +google/api_core/future/async_future.py,sha256=7rOK0tzud8MCoUwO9AjF-3OQDtELwhtp2ONltSB3GEI,5355 +google/api_core/future/base.py,sha256=SHyudamSWR7EyUsYaQ-XrGGkLeYClSfXfsHIHSqDIYI,1763 +google/api_core/future/polling.py,sha256=0HUw1bp7ZLgEqMtwsvxIXNMHQbHgsP6TpmpVrMbjJ2I,14349 +google/api_core/gapic_v1/__init__.py,sha256=r6kCwKznSXPTYRdz4C384fscefaw_rXP2bzJdnzEVnw,988 +google/api_core/gapic_v1/__pycache__/__init__.cpython-310.pyc,, +google/api_core/gapic_v1/__pycache__/client_info.cpython-310.pyc,, +google/api_core/gapic_v1/__pycache__/config.cpython-310.pyc,, +google/api_core/gapic_v1/__pycache__/config_async.cpython-310.pyc,, +google/api_core/gapic_v1/__pycache__/method.cpython-310.pyc,, +google/api_core/gapic_v1/__pycache__/method_async.cpython-310.pyc,, +google/api_core/gapic_v1/__pycache__/routing_header.cpython-310.pyc,, +google/api_core/gapic_v1/client_info.py,sha256=FhmeHuSgFIxCCXaFPb4QdpoBzR4FVTy2997fkXorXbM,2421 +google/api_core/gapic_v1/config.py,sha256=5isOOYPSZCXpDcJDJiwmTxGTUo0RjxJJvW2yjqBR4BI,6300 +google/api_core/gapic_v1/config_async.py,sha256=_jrB5Yv6rxxSU6KwzOxWQ-G_x5mXilpSFAgnQ_6ktrU,1728 +google/api_core/gapic_v1/method.py,sha256=SnMqRoKKCRph9xpnQvQ29SGjCd9WVpHEPK60X-uPyWM,9494 +google/api_core/gapic_v1/method_async.py,sha256=L8BHV3SkvKTDqVSonDuUY1OIRMPEqfsOsTitYRQ_UwQ,2090 +google/api_core/gapic_v1/routing_header.py,sha256=kJKOYpNS2mgSZa4Qt8Ib2Q5ONfNwpJwbNloVJ8e2wMs,3093 +google/api_core/general_helpers.py,sha256=ZrYwDg7VTgtaQlFk_fCeFTKYZD62JMQdZRhbQhbQL_c,681 +google/api_core/grpc_helpers.py,sha256=3TPU35tMy43rZ9pvo7OmwQkZFqVPRQ2ViqolzE6-W88,24787 +google/api_core/grpc_helpers_async.py,sha256=LZvldkW8d0Lz-N1xITFpsE8TO0ej0jilUu7R4U2cf3Q,12966 +google/api_core/iam.py,sha256=BGz63HtOP5_5oH9Zs93RP0Y6Qshty2eOhFEYj_CoE64,13213 +google/api_core/operation.py,sha256=mHWay2vrNbEliv5YWFzyXBywbQdy_VPW98BALh514PA,13198 +google/api_core/operation_async.py,sha256=XdunwVY6aKA-K0OK-5_dYbqjbvF1DLTYUUL4IOztld4,8046 +google/api_core/operations_v1/__init__.py,sha256=ncvxAGOrunbMNRoQ9n1Io1p1nRN_LV5DutV52UidV8k,1638 +google/api_core/operations_v1/__pycache__/__init__.cpython-310.pyc,, +google/api_core/operations_v1/__pycache__/abstract_operations_base_client.cpython-310.pyc,, +google/api_core/operations_v1/__pycache__/abstract_operations_client.cpython-310.pyc,, +google/api_core/operations_v1/__pycache__/operations_async_client.cpython-310.pyc,, +google/api_core/operations_v1/__pycache__/operations_client.cpython-310.pyc,, +google/api_core/operations_v1/__pycache__/operations_client_config.cpython-310.pyc,, +google/api_core/operations_v1/__pycache__/operations_rest_client_async.cpython-310.pyc,, +google/api_core/operations_v1/__pycache__/pagers.cpython-310.pyc,, +google/api_core/operations_v1/__pycache__/pagers_async.cpython-310.pyc,, +google/api_core/operations_v1/__pycache__/pagers_base.cpython-310.pyc,, +google/api_core/operations_v1/abstract_operations_base_client.py,sha256=JoAlWWxuj_TpbAv9GCBt6_BMhflvIoR-rg9TPSOJ3is,14861 +google/api_core/operations_v1/abstract_operations_client.py,sha256=j_ulCLJpyqGh1SY8z5kss9iYBfOwE_XXCTqwQAKpyeI,16073 +google/api_core/operations_v1/operations_async_client.py,sha256=1BENex2y2ovlCHlXR4v5Cfiqk2o36DBWEzPyCCCudbU,14794 +google/api_core/operations_v1/operations_client.py,sha256=-fmbRv_2L_5cJv70WfybRw9EUyLlHB-wTbC-n0Iq4Fg,15274 +google/api_core/operations_v1/operations_client_config.py,sha256=v7B0FiVc5p9HhnpPY1_3FIomFdA-J-4lilomeoC9SkQ,2285 +google/api_core/operations_v1/operations_rest_client_async.py,sha256=qMYVo08Y0jfSU53dmHSDvO7_UL3x8DzJgpvnwAaTyyE,14616 +google/api_core/operations_v1/pagers.py,sha256=WYXqIGNIMbQX-2OUbiqz3ZXScvI_iOxKjxkN6bTP1YQ,2463 +google/api_core/operations_v1/pagers_async.py,sha256=SdFB-eXtOjZCHWICgViao6txHJqgs7vhsso6HT_npOo,2624 +google/api_core/operations_v1/pagers_base.py,sha256=qlizIpOdU-JVeQIMaPRIBmkcsghDX2FQYz5VH3-l9s0,2652 +google/api_core/operations_v1/transports/__init__.py,sha256=Ng5VDMks97QNfbkhFSRKmvNwUv3_IQmLUszCGTeJYvE,1457 +google/api_core/operations_v1/transports/__pycache__/__init__.cpython-310.pyc,, +google/api_core/operations_v1/transports/__pycache__/base.cpython-310.pyc,, +google/api_core/operations_v1/transports/__pycache__/rest.cpython-310.pyc,, +google/api_core/operations_v1/transports/__pycache__/rest_asyncio.cpython-310.pyc,, +google/api_core/operations_v1/transports/base.py,sha256=ygeocDSNgUA-DN-0Orx5ii4c6jUqmFZ17KmXlbsAFrM,11419 +google/api_core/operations_v1/transports/rest.py,sha256=qywh6vNSLPqP7Ieov5EJkN-THleZZt8qK0y5iCC91NQ,20599 +google/api_core/operations_v1/transports/rest_asyncio.py,sha256=t6ub6RgxKqPfRYO5ahy4l6vVqY2EvIKYuJSiT7TYPNw,24822 +google/api_core/page_iterator.py,sha256=FXMfqbhlVYAEVjpojytYAiUluVNYAVSC41MdfAhHAX4,20330 +google/api_core/page_iterator_async.py,sha256=TbuXorRhP1wcQTD3raBJhWgSJP1JwJO_nCKJphCbVdw,10294 +google/api_core/path_template.py,sha256=Lyqqw8OECuw5O7y9x1BJvfNbYEbmx4lnTGqc6opSyHk,11685 +google/api_core/protobuf_helpers.py,sha256=ct_P2z6iYNvum0FZ5Uj-96qf83Q_99TP1qcGwvlO_9c,12448 +google/api_core/py.typed,sha256=q8dgH9l1moUXiufHBVjqI0MuJy4Be9a3rNH8Zl_sICA,78 +google/api_core/rest_helpers.py,sha256=2DsInZiHv0sLd9dfLIbEL2vDJQIybWgxlkxnNFahPnI,3529 +google/api_core/rest_streaming.py,sha256=AwduJ7tYa0_iBhFEqCY696NVmNGWWCm6g4wnTqoVjS4,2209 +google/api_core/rest_streaming_async.py,sha256=5GuzrfYFHfR22d9guOtXvZ1E-VHCCusJyWKVRxOcFuE,3340 +google/api_core/retry/__init__.py,sha256=WhgtLBQO2oK-AehH_AHbGbfWo1IdG5ahUGrs3aFGw0o,2088 +google/api_core/retry/__pycache__/__init__.cpython-310.pyc,, +google/api_core/retry/__pycache__/retry_base.cpython-310.pyc,, +google/api_core/retry/__pycache__/retry_streaming.cpython-310.pyc,, +google/api_core/retry/__pycache__/retry_streaming_async.cpython-310.pyc,, +google/api_core/retry/__pycache__/retry_unary.cpython-310.pyc,, +google/api_core/retry/__pycache__/retry_unary_async.cpython-310.pyc,, +google/api_core/retry/retry_base.py,sha256=e1Asrsjp8Joj__GS9n0tiMeseYN5HWocHK2cbThyPHU,12890 +google/api_core/retry/retry_streaming.py,sha256=sw6Bx7w9G1lK8KCAYn2pw0hZ12sPQAD9h4otC2BXIuQ,11032 +google/api_core/retry/retry_streaming_async.py,sha256=gYs5KWzQ9RHb05ciPuoptOm5VWCOS7fliNG006Ndveg,14517 +google/api_core/retry/retry_unary.py,sha256=X8wIBzhKMpf3PlOmMgotIgg21Hvv16hUb3f8d20hnDc,13517 +google/api_core/retry/retry_unary_async.py,sha256=7PANk3jx6dBKKUZKd3yb2TFPBYO9l7uXg4QmBxmwhQQ,9594 +google/api_core/retry_async.py,sha256=_r0ROYeQqdATtRMx-q_6o4bPmqFzPyjr_oV3lfloDSM,1514 +google/api_core/timeout.py,sha256=heil0E6scuyFkMvymbR2bA33ZmJSavH_SmRNK9kpqcM,10279 +google/api_core/universe.py,sha256=k_K5J0I3kKQiM2yEHvxeqAWxXEQZKJ2SfDlMAH-rQ08,2952 +google/api_core/version.py,sha256=zk-6uopTPf5QfJCWtvMpBtM20LATfAG9g3zNecJwnew,598 +google/api_core/version_header.py,sha256=uEFXosCp8UH7XhznG5GQseTYtWNoJHXRPA557DWsUxA,1046 +google_api_core-2.25.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +google_api_core-2.25.1.dist-info/METADATA,sha256=WMMMUaM35tO_wBQMWaXs4L9ztzoXlF9avR39jYYtNOQ,3009 +google_api_core-2.25.1.dist-info/RECORD,, +google_api_core-2.25.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +google_api_core-2.25.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +google_api_core-2.25.1.dist-info/top_level.txt,sha256=_1QvSJIhFAGfxb79D6DhB7SUw2X6T4rwnz_LLrbcD3c,7 diff --git a/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/WHEEL b/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/licenses/LICENSE @@ -0,0 +1,202 @@ + + 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. diff --git a/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb429113e0f9a73019fd799e8052093fea7f0c8b --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_api_core-2.25.1.dist-info/top_level.txt @@ -0,0 +1 @@ +google diff --git a/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/LICENSE b/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/LICENSE @@ -0,0 +1,201 @@ + 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. diff --git a/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/METADATA b/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..45a2da4278422c06e9b4c2e7bb9008256b7e055c --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/METADATA @@ -0,0 +1,167 @@ +Metadata-Version: 2.1 +Name: google-auth +Version: 2.40.3 +Summary: Google Authentication Library +Home-page: https://github.com/googleapis/google-auth-library-python +Author: Google Cloud Platform +Author-email: googleapis-packages@google.com +License: Apache 2.0 +Keywords: google auth oauth client +Classifier: Programming Language :: Python :: 3 +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.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: POSIX +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: OS Independent +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.7 +License-File: LICENSE +Requires-Dist: cachetools<6.0,>=2.0.0 +Requires-Dist: pyasn1-modules>=0.2.1 +Requires-Dist: rsa<5,>=3.1.4 +Provides-Extra: aiohttp +Requires-Dist: aiohttp<4.0.0,>=3.6.2; extra == "aiohttp" +Requires-Dist: requests<3.0.0,>=2.20.0; extra == "aiohttp" +Provides-Extra: enterprise_cert +Requires-Dist: cryptography; extra == "enterprise-cert" +Requires-Dist: pyopenssl; extra == "enterprise-cert" +Provides-Extra: pyjwt +Requires-Dist: pyjwt>=2.0; extra == "pyjwt" +Requires-Dist: cryptography>=38.0.3; extra == "pyjwt" +Requires-Dist: cryptography<39.0.0; python_version < "3.8" and extra == "pyjwt" +Provides-Extra: pyopenssl +Requires-Dist: pyopenssl>=20.0.0; extra == "pyopenssl" +Requires-Dist: cryptography>=38.0.3; extra == "pyopenssl" +Requires-Dist: cryptography<39.0.0; python_version < "3.8" and extra == "pyopenssl" +Provides-Extra: reauth +Requires-Dist: pyu2f>=0.1.5; extra == "reauth" +Provides-Extra: requests +Requires-Dist: requests<3.0.0,>=2.20.0; extra == "requests" +Provides-Extra: testing +Requires-Dist: grpcio; extra == "testing" +Requires-Dist: flask; extra == "testing" +Requires-Dist: freezegun; extra == "testing" +Requires-Dist: mock; extra == "testing" +Requires-Dist: oauth2client; extra == "testing" +Requires-Dist: pyjwt>=2.0; extra == "testing" +Requires-Dist: cryptography>=38.0.3; extra == "testing" +Requires-Dist: pytest; extra == "testing" +Requires-Dist: pytest-cov; extra == "testing" +Requires-Dist: pytest-localserver; extra == "testing" +Requires-Dist: pyopenssl>=20.0.0; extra == "testing" +Requires-Dist: pyu2f>=0.1.5; extra == "testing" +Requires-Dist: responses; extra == "testing" +Requires-Dist: urllib3; extra == "testing" +Requires-Dist: packaging; extra == "testing" +Requires-Dist: aiohttp<4.0.0,>=3.6.2; extra == "testing" +Requires-Dist: requests<3.0.0,>=2.20.0; extra == "testing" +Requires-Dist: aioresponses; extra == "testing" +Requires-Dist: pytest-asyncio; extra == "testing" +Requires-Dist: pyopenssl<24.3.0; extra == "testing" +Requires-Dist: aiohttp<3.10.0; extra == "testing" +Requires-Dist: cryptography<39.0.0; python_version < "3.8" and extra == "testing" +Provides-Extra: urllib3 +Requires-Dist: urllib3; extra == "urllib3" +Requires-Dist: packaging; extra == "urllib3" + +Google Auth Python Library +========================== + +|pypi| + +This library simplifies using Google's various server-to-server authentication +mechanisms to access Google APIs. + +.. |pypi| image:: https://img.shields.io/pypi/v/google-auth.svg + :target: https://pypi.python.org/pypi/google-auth + +Installing +---------- + +You can install using `pip`_:: + + $ pip install google-auth + +.. _pip: https://pip.pypa.io/en/stable/ + +For more information on setting up your Python development environment, please refer to `Python Development Environment Setup Guide`_ for Google Cloud Platform. + +.. _`Python Development Environment Setup Guide`: https://cloud.google.com/python/docs/setup + +Extras +------ + +google-auth has few extras that you can install. For example:: + + $ pip install google-auth[pyopenssl] + +Note that the extras pyopenssl and enterprise_cert should not be used together because they use conflicting versions of `cryptography`_. + +.. _`cryptography`: https://cryptography.io/en/latest/ + +Supported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^ +Python >= 3.7 + +**NOTE**: +Python 3.7 was marked as `unsupported`_ by the python community in June 2023. +We recommend that all developers upgrade to Python 3.8 and newer as soon as +they can. Support for Python 3.7 will be removed from this library after +January 1 2024. Previous releases that support Python 3.7 will continue to be available +for download, but releases after January 1 2024 will only target Python 3.8 and +newer. + +.. _unsupported: https://devguide.python.org/versions/#unsupported-versions + +Unsupported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- Python == 2.7: The last version of this library with support for Python 2.7 + was `google.auth == 1.34.0`. + +- Python 3.5: The last version of this library with support for Python 3.5 + was `google.auth == 1.23.0`. + +- Python 3.6: The last version of this library with support for Python 3.6 + was `google.auth == 2.22.0`. + +Documentation +------------- + +Google Auth Python Library has usage and reference documentation at https://googleapis.dev/python/google-auth/latest/index.html. + +Current Maintainers +------------------- +- googleapis-auth@google.com + +Authors +------- + +- `@theacodes `_ (Thea Flowers) +- `@dhermes `_ (Danny Hermes) +- `@lukesneeringer `_ (Luke Sneeringer) +- `@busunkim96 `_ (Bu Sun Kim) + +Contributing +------------ + +Contributions to this library are always welcome and highly encouraged. + +See `CONTRIBUTING.rst`_ for more information on how to get started. + +.. _CONTRIBUTING.rst: https://github.com/googleapis/google-auth-library-python/blob/main/CONTRIBUTING.rst + +License +------- + +Apache 2.0 - See `the LICENSE`_ for more information. + +.. _the LICENSE: https://github.com/googleapis/google-auth-library-python/blob/main/LICENSE diff --git a/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/RECORD b/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..b863e1af67424728ad9786ba4a9f5df20953b65b --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/RECORD @@ -0,0 +1,152 @@ +google/auth/__init__.py,sha256=wg5MWwRk8nfJFMmUMU2gLirrPdGe9NMwqLkdSwdFwE8,1639 +google/auth/__pycache__/__init__.cpython-310.pyc,, +google/auth/__pycache__/_cloud_sdk.cpython-310.pyc,, +google/auth/__pycache__/_credentials_async.cpython-310.pyc,, +google/auth/__pycache__/_credentials_base.cpython-310.pyc,, +google/auth/__pycache__/_default.cpython-310.pyc,, +google/auth/__pycache__/_default_async.cpython-310.pyc,, +google/auth/__pycache__/_exponential_backoff.cpython-310.pyc,, +google/auth/__pycache__/_helpers.cpython-310.pyc,, +google/auth/__pycache__/_jwt_async.cpython-310.pyc,, +google/auth/__pycache__/_oauth2client.cpython-310.pyc,, +google/auth/__pycache__/_refresh_worker.cpython-310.pyc,, +google/auth/__pycache__/_service_account_info.cpython-310.pyc,, +google/auth/__pycache__/api_key.cpython-310.pyc,, +google/auth/__pycache__/app_engine.cpython-310.pyc,, +google/auth/__pycache__/aws.cpython-310.pyc,, +google/auth/__pycache__/credentials.cpython-310.pyc,, +google/auth/__pycache__/downscoped.cpython-310.pyc,, +google/auth/__pycache__/environment_vars.cpython-310.pyc,, +google/auth/__pycache__/exceptions.cpython-310.pyc,, +google/auth/__pycache__/external_account.cpython-310.pyc,, +google/auth/__pycache__/external_account_authorized_user.cpython-310.pyc,, +google/auth/__pycache__/iam.cpython-310.pyc,, +google/auth/__pycache__/identity_pool.cpython-310.pyc,, +google/auth/__pycache__/impersonated_credentials.cpython-310.pyc,, +google/auth/__pycache__/jwt.cpython-310.pyc,, +google/auth/__pycache__/metrics.cpython-310.pyc,, +google/auth/__pycache__/pluggable.cpython-310.pyc,, +google/auth/__pycache__/version.cpython-310.pyc,, +google/auth/_cloud_sdk.py,sha256=u7tbE3KdHBCzZK8ka47xG3CHHtF0DhFDjmPSgz8lwXg,5212 +google/auth/_credentials_async.py,sha256=bHB28wMULOIEMmYqKEOU06A4co7uIXPcnfVC_TaA6KY,6802 +google/auth/_credentials_base.py,sha256=KxdCZyoFyvrfWhJbNnuYkpUhxs0bmbxYvcH8-xp5hUs,2692 +google/auth/_default.py,sha256=Nw4JKiNrObBbRSki2ov99WTTTA10iVyJlBLeuQE_V2s,28687 +google/auth/_default_async.py,sha256=r4bFozWfioQa4lIEC-psuRsLiVhnJbuW-uQ0daj7s3Q,11575 +google/auth/_exponential_backoff.py,sha256=qxA9ek80rBkoARx0Egl2b1MlYU0D-pQNVqgCmUh-lgU,5372 +google/auth/_helpers.py,sha256=1j2IZY5pltpQ3a0JsKM_kF_re7Xv1Fcaqrl-NJTKulo,16584 +google/auth/_jwt_async.py,sha256=5mGab5CkdnBMkQkS4mtNkwFkktp1jBw6G1sYQk8bYKY,5972 +google/auth/_oauth2client.py,sha256=hPxcl_8q6Oxr0hOHPUWaWObxI85Pv-0q6kZhRUrT5oY,5855 +google/auth/_refresh_worker.py,sha256=7apJkFsD9oL1yz1K7O8v-YN3f3TdNBiJdd7_Wmq6zpE,3375 +google/auth/_service_account_info.py,sha256=KGruc_OxS7O7_EADD4JEIjjz_-5Xa1_rlgk1t0p1nvk,2816 +google/auth/aio/__init__.py,sha256=e3ToAxXNHhqJLBgW8B66650xdqrTCZDLcwP2p5DhCPM,869 +google/auth/aio/__pycache__/__init__.cpython-310.pyc,, +google/auth/aio/__pycache__/_helpers.cpython-310.pyc,, +google/auth/aio/__pycache__/credentials.cpython-310.pyc,, +google/auth/aio/_helpers.py,sha256=glCa_-GYxDrcPBFt80LBhMz_V7vLjxAEEWfOZB8lwT0,2334 +google/auth/aio/credentials.py,sha256=lXY0_SJ9c36Mzp47fN4a8JT5HfNzFQtIIwsZEwzoDR4,5273 +google/auth/aio/transport/__init__.py,sha256=8dQWHpube1IeWw02q6AvMRTM5V_2iN4y3UMLenbmUUQ,4692 +google/auth/aio/transport/__pycache__/__init__.cpython-310.pyc,, +google/auth/aio/transport/__pycache__/aiohttp.cpython-310.pyc,, +google/auth/aio/transport/__pycache__/sessions.cpython-310.pyc,, +google/auth/aio/transport/aiohttp.py,sha256=sg3bdyCsoJ0N0v7Ww8qoJFr0qcF6TKhEmNw5dRb6R9I,6979 +google/auth/aio/transport/sessions.py,sha256=RcRHfkeo_ppEY1o8ts8aJqw76y54I8D0P8QT7yFq4aI,10388 +google/auth/api_key.py,sha256=PeieTYceHJIFCo0zQo1EA9NEDL_Ie6S78qmD-6Ig17s,2583 +google/auth/app_engine.py,sha256=LuEaoWM1UwcIUJ6OrLza0tTpqJBXbtzZ3XjN0C-6Wvk,6121 +google/auth/aws.py,sha256=2V5NLhboorkPLLwnA87VuyH9imruake6qhyHKV_rVYM,34568 +google/auth/compute_engine/__init__.py,sha256=BqeTka-oyHFATkys3SGKRlOyWQ8mVV0vVaP2hOwV4Qw,910 +google/auth/compute_engine/__pycache__/__init__.cpython-310.pyc,, +google/auth/compute_engine/__pycache__/_metadata.cpython-310.pyc,, +google/auth/compute_engine/__pycache__/credentials.cpython-310.pyc,, +google/auth/compute_engine/_metadata.py,sha256=IWloMOeSYNcJ40mfWstGx19kUR4_FK2pOVhRiT6d6zg,12860 +google/auth/compute_engine/credentials.py,sha256=5jGYgrb0fjc0jb_bcOTHr4PxZ2A-dPRzgAgFu0Ky8BA,19076 +google/auth/credentials.py,sha256=l0g0iATMCpJnJXU5aE6YD850yBnZpshdYyDrYzhmE40,18700 +google/auth/crypt/__init__.py,sha256=xxBMOPuzD-XOxPvzkleLa2oj4u-9FSjnFmUN3PBk00s,3324 +google/auth/crypt/__pycache__/__init__.cpython-310.pyc,, +google/auth/crypt/__pycache__/_cryptography_rsa.cpython-310.pyc,, +google/auth/crypt/__pycache__/_helpers.cpython-310.pyc,, +google/auth/crypt/__pycache__/_python_rsa.cpython-310.pyc,, +google/auth/crypt/__pycache__/base.cpython-310.pyc,, +google/auth/crypt/__pycache__/es256.cpython-310.pyc,, +google/auth/crypt/__pycache__/rsa.cpython-310.pyc,, +google/auth/crypt/_cryptography_rsa.py,sha256=o2QTRkfDRLtEBiq-fbpbTWypvxaxUDwzlx2NpXG9o0w,5158 +google/auth/crypt/_helpers.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +google/auth/crypt/_python_rsa.py,sha256=L0kgvPXVdEGhajzxLRIgdk2T9rY0nlThrSlSz8Hc8XY,6123 +google/auth/crypt/base.py,sha256=3CJrnQsppR6h-WnTRqSrt1hPEQVkHcwNIVJ_B5M00hY,4190 +google/auth/crypt/es256.py,sha256=hXyeia3g6_TZf-UYdZVzFKgbPrLlgSuR1mMvYKSYqbg,6251 +google/auth/crypt/rsa.py,sha256=QI17aKQsX3gdbJkBef-zsm-X_YBjBollCaoA65Am-WI,1109 +google/auth/downscoped.py,sha256=KmmC8lbBWUFUsIYt1VpcbTXs3yYJYXteH19qdZQgobA,21793 +google/auth/environment_vars.py,sha256=ML9aFh5gwRStBDjn8BQSQHyWsA-OcMn-RB5FRMM8qOw,3297 +google/auth/exceptions.py,sha256=8oEeB_1UirJIyBoglQRpCFjCOcxcTaLr6EpBrrxjeEs,3193 +google/auth/external_account.py,sha256=v-Qln5KsbXYlO2xPlIxeGMBY5iA4Atj2cP-KgbF2CpY,25977 +google/auth/external_account_authorized_user.py,sha256=-garTidaTqA8XNOPdBxJl6tfx-ub_-dr7WPVKEI2eAs,13987 +google/auth/iam.py,sha256=DQcJ127yejPqQa20jwzrGfiWffiWioAYkxZI4cQAUm8,4674 +google/auth/identity_pool.py,sha256=JGMRr4edwIOybi969upW-n9g6u3bPvjy5oYt3bkzVoI,22554 +google/auth/impersonated_credentials.py,sha256=E5dkf_2P8-q476IaxIqzXRHZhJTEU0sYsBTB9bAPq3s,24971 +google/auth/jwt.py,sha256=1m_arp5x-4I5UTDaK9y50PSlKnUhnSKFyJW95k3-7cQ,31096 +google/auth/metrics.py,sha256=wx3m95QQCF885wYvPL4T01CHOdCBN5JvFCtbOakd98Q,5614 +google/auth/pluggable.py,sha256=peGQ4izmkZ3Fna7fjhBhQVXjtDBcHK12uEAteMyJ8s0,17322 +google/auth/py.typed,sha256=l05_LTgi3oy-einKBrw66s6aavgzG2o-SekKPOY3ayM,74 +google/auth/transport/__init__.py,sha256=vTdWUDBCXWF6wk3Xzu7L5I1lbtGYTxONi-IKYOmDdFM,3654 +google/auth/transport/__pycache__/__init__.cpython-310.pyc,, +google/auth/transport/__pycache__/_aiohttp_requests.cpython-310.pyc,, +google/auth/transport/__pycache__/_custom_tls_signer.cpython-310.pyc,, +google/auth/transport/__pycache__/_http_client.cpython-310.pyc,, +google/auth/transport/__pycache__/_mtls_helper.cpython-310.pyc,, +google/auth/transport/__pycache__/_requests_base.cpython-310.pyc,, +google/auth/transport/__pycache__/grpc.cpython-310.pyc,, +google/auth/transport/__pycache__/mtls.cpython-310.pyc,, +google/auth/transport/__pycache__/requests.cpython-310.pyc,, +google/auth/transport/__pycache__/urllib3.cpython-310.pyc,, +google/auth/transport/_aiohttp_requests.py,sha256=DdtN_5zXWm7ewsvejOfMfa9_KSYXFX8upLdGL_qKDCI,14820 +google/auth/transport/_custom_tls_signer.py,sha256=ilLlKFNognkvOWcnlYAWmUIUo9YhSrTSAKLa05zQ8Do,9989 +google/auth/transport/_http_client.py,sha256=_xiN4rF9SMT0cHwzvj0jRRXkkHxGG2IyOBOHxB-I1Ag,3798 +google/auth/transport/_mtls_helper.py,sha256=rhJ-QDEWeoiLGguwtMjruy6ObR89oqwtZ382sW1g3uM,14739 +google/auth/transport/_requests_base.py,sha256=4y0tTMR_hPGeAmBSyCU6_moh99ZxJZ4CF79E2s-t7TA,1657 +google/auth/transport/grpc.py,sha256=o6wDBMWKlTybwsE8CUdEcoEA2t_vdjRvQTGU9vcJPcc,13931 +google/auth/transport/mtls.py,sha256=C1Ox7fB0DSEdNkIJ7q5ofrQ-_I_cj1JOJ8o5_Zzgb24,3968 +google/auth/transport/requests.py,sha256=V2hL_RpEj2mVjy3-8iYTvAhJnzm5JuMPGIGxOwvcbaE,22513 +google/auth/transport/urllib3.py,sha256=kRH_Rd_4KuCcKKoZ_b92c-6d42R5CGeH5EuWtiYOhjM,16491 +google/auth/version.py,sha256=nnzHzJaLYzj7zp5qHqgHVhV4FwiPu5dmAVmCvKWVTek,598 +google/oauth2/__init__.py,sha256=IdFKxhIzlqNIalPgeB2P5hP6KkoxcpNk61hp7P2B85w,1196 +google/oauth2/__pycache__/__init__.cpython-310.pyc,, +google/oauth2/__pycache__/_client.cpython-310.pyc,, +google/oauth2/__pycache__/_client_async.cpython-310.pyc,, +google/oauth2/__pycache__/_credentials_async.cpython-310.pyc,, +google/oauth2/__pycache__/_id_token_async.cpython-310.pyc,, +google/oauth2/__pycache__/_reauth_async.cpython-310.pyc,, +google/oauth2/__pycache__/_service_account_async.cpython-310.pyc,, +google/oauth2/__pycache__/challenges.cpython-310.pyc,, +google/oauth2/__pycache__/credentials.cpython-310.pyc,, +google/oauth2/__pycache__/gdch_credentials.cpython-310.pyc,, +google/oauth2/__pycache__/id_token.cpython-310.pyc,, +google/oauth2/__pycache__/reauth.cpython-310.pyc,, +google/oauth2/__pycache__/service_account.cpython-310.pyc,, +google/oauth2/__pycache__/sts.cpython-310.pyc,, +google/oauth2/__pycache__/utils.cpython-310.pyc,, +google/oauth2/__pycache__/webauthn_handler.cpython-310.pyc,, +google/oauth2/__pycache__/webauthn_handler_factory.cpython-310.pyc,, +google/oauth2/__pycache__/webauthn_types.cpython-310.pyc,, +google/oauth2/_client.py,sha256=XOtqZf3J9U5zW9x5v6zPSKeF_YlRNdYlqfzOZPepxdc,17338 +google/oauth2/_client_async.py,sha256=gBB74HOw_UVT6i-84T4N_39YnyajYwP5Ih1Kmtsjeu8,10129 +google/oauth2/_credentials_async.py,sha256=hUrucQkcYuYlyCdHMci8tzaVncnjQlFc2sAfNu5Dt8k,4474 +google/oauth2/_id_token_async.py,sha256=o_DViJoWMGlL3zwTbW2unGDBfY569D_VMB4l7bx-Qpw,10115 +google/oauth2/_reauth_async.py,sha256=C6k3f4T0aoVWItl8shYjOl5ngaoTJw3zKVhqHAeBXU0,11696 +google/oauth2/_service_account_async.py,sha256=5-HBGWoHhbWpCRbd34YiopQepEsEf8gSiuMlSm5hN84,5131 +google/oauth2/challenges.py,sha256=__yS2EcWXlgdLLP4inbk0QjJuyXnztpT9r2DCuXvieI,10404 +google/oauth2/credentials.py,sha256=AqPdW8ymp1EnmiTgwyLdRxjaj2kISjHPw4Yh0JZUleI,24913 +google/oauth2/gdch_credentials.py,sha256=CY6iPnPuc2OCIe1Zujwg1Mu9QSl1iGJqGOy6TkUleHw,9007 +google/oauth2/id_token.py,sha256=G41ugqrEkj0VqP3hAFLH6IzmFqPZv81WkU6_lviKb4Q,13497 +google/oauth2/py.typed,sha256=I0muXRRdbdpJoZ_VyheisiTTYcmjTAitQpNvuuh6fMw,76 +google/oauth2/reauth.py,sha256=p9ybxvFyaSMM85jL2veKMM-DVb4TtrDVPNqsLeDPmyk,12845 +google/oauth2/service_account.py,sha256=PyKtS9QfflVfIgdyRju1I1VFr8V3A57IGzxUSAYGmgA,32232 +google/oauth2/sts.py,sha256=GjpFEvByl3EzyGt2v1kev6rvP7_uSQ3eTlpBK9vUhSc,6699 +google/oauth2/utils.py,sha256=4crAdpKbDtobpQfXJc3uF6Zm6F3IzffvRSo-9h_515w,6315 +google/oauth2/webauthn_handler.py,sha256=6hYiSDIFXlLwghsYf13ceDiOWdLYn6Dh7-YwSqTbLaA,2743 +google/oauth2/webauthn_handler_factory.py,sha256=soE5cokZ3pLNbBo1HC6F1N-N-I-ir-DGlD0trGPCpBs,429 +google/oauth2/webauthn_types.py,sha256=IHdqUe-EWOU-CmyLnHLniqc7vGHZ8HpavB0dcjn7Zl8,5386 +google_auth-2.40.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +google_auth-2.40.3.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +google_auth-2.40.3.dist-info/METADATA,sha256=ZtXNUVjkBEE6jjbKrauFnfn_SNpLHGH12AAzeLXYhTk,6203 +google_auth-2.40.3.dist-info/RECORD,, +google_auth-2.40.3.dist-info/WHEEL,sha256=OpXWERl2xLPRHTvd2ZXo_iluPEQd8uSbYkJ53NAER_Y,109 +google_auth-2.40.3.dist-info/top_level.txt,sha256=BWmDiI8eoKfseZ5-MI2AW66GLJLNH4Lz23AXXTrIlyQ,23 diff --git a/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/WHEEL b/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ee810efb31c37815a70827942976bfcba5b5d2bc --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.3.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..64f26a32e6269f22ba603fede491e460b08a91d8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_auth-2.40.3.dist-info/top_level.txt @@ -0,0 +1,3 @@ +google +scripts +testing diff --git a/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/LICENSE b/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/LICENSE @@ -0,0 +1,201 @@ + 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. diff --git a/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..cdf15e5479825f7e03eefd9b8c9d18cf05e3f247 --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/METADATA @@ -0,0 +1,62 @@ +Metadata-Version: 2.1 +Name: google-auth-httplib2 +Version: 0.2.0 +Summary: Google Authentication Library: httplib2 transport +Home-page: https://github.com/GoogleCloudPlatform/google-auth-library-python-httplib2 +Author: Google Cloud Platform +Author-email: googleapis-packages@google.com +License: Apache 2.0 +Keywords: google auth oauth client +Classifier: Programming Language :: Python :: 3 +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.12 +Classifier: Development Status :: 3 - Alpha +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: POSIX +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: OS Independent +Classifier: Topic :: Internet :: WWW/HTTP +License-File: LICENSE +Requires-Dist: google-auth +Requires-Dist: httplib2 >=0.19.0 + +``httplib2`` Transport for Google Auth +====================================== + +|pypi| + +This library provides an `httplib2`_ transport for `google-auth`_. + +.. note:: ``httplib`` has lots of problems such as lack of threadsafety + and insecure usage of TLS. Using it is highly discouraged. This + library is intended to help existing users of ``oauth2client`` migrate to + ``google-auth``. + +.. |pypi| image:: https://img.shields.io/pypi/v/google-auth-httplib2.svg + :target: https://pypi.python.org/pypi/google-auth-httplib2 + +.. _httplib2: https://github.com/httplib2/httplib2 +.. _google-auth: https://github.com/GoogleCloudPlatform/google-auth-library-python/ + +Installing +---------- + +You can install using `pip`_:: + + $ pip install google-auth-httplib2 + +.. _pip: https://pip.pypa.io/en/stable/ + +License +------- + +Apache 2.0 - See `the LICENSE`_ for more information. + +.. _the LICENSE: https://github.com/GoogleCloudPlatform/google-auth-library-python/blob/main/LICENSE diff --git a/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f13d4988d6c5f0fa66a7a03d9da10a0ae83b31bf --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/RECORD @@ -0,0 +1,8 @@ +__pycache__/google_auth_httplib2.cpython-310.pyc,, +google_auth_httplib2-0.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +google_auth_httplib2-0.2.0.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +google_auth_httplib2-0.2.0.dist-info/METADATA,sha256=KbbX6r2o-hWv_6Mr3PkYxa96q59OBXu2mF9WJ8MMlJk,2179 +google_auth_httplib2-0.2.0.dist-info/RECORD,, +google_auth_httplib2-0.2.0.dist-info/WHEEL,sha256=P2T-6epvtXQ2cBOE_U1K4_noqlJFN3tj15djMgEu4NM,110 +google_auth_httplib2-0.2.0.dist-info/top_level.txt,sha256=xQr4X91CsNWr1mw3rrOH8mKnYLOW_Uhr5U7moYxkq4E,21 +google_auth_httplib2.py,sha256=Z-VdVWlB8Rcrwn4Q2MU9SHHJ5HZkPYHfDu8xHKsBeQI,10211 diff --git a/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..f31e450fda2866f274547bb723d784248069898a --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.3) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f8b63c266a006ff9f89d5a998d7cb9e836bec45e --- /dev/null +++ b/venv/lib/python3.10/site-packages/google_auth_httplib2-0.2.0.dist-info/top_level.txt @@ -0,0 +1 @@ +google_auth_httplib2 diff --git a/venv/lib/python3.10/site-packages/gradio_client/CHANGELOG.md b/venv/lib/python3.10/site-packages/gradio_client/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..bbd69d3fee83122c2415fde0506998ecfc3f41cf --- /dev/null +++ b/venv/lib/python3.10/site-packages/gradio_client/CHANGELOG.md @@ -0,0 +1,1111 @@ +# gradio_client + +## 1.11.0 + +### Features + +- [#11567](https://github.com/gradio-app/gradio/pull/11567) [`150ed18`](https://github.com/gradio-app/gradio/commit/150ed18b856e34d5a96a9e17bd5ad510e11872a6) - Stream Progress Updates to MCP clients. Thanks @freddyaboulton! + +## 1.10.4 + +### Fixes + +- [#11041](https://github.com/gradio-app/gradio/pull/11041) [`474aa30`](https://github.com/gradio-app/gradio/commit/474aa30979c14793e00852ad2f4ef6c12a41b900) - Attach cookies to client after first request (to support multiple-replica setups with cookie-based affinity). Thanks @abidlabs! + +## 1.10.3 + +### Fixes + +- [#11347](https://github.com/gradio-app/gradio/pull/11347) [`fdce3a0`](https://github.com/gradio-app/gradio/commit/fdce3a094fe1278ae83fe2f8b134b4c268506cfe) - Fix `gr.api()` to support more types, including optional params. Thanks @abidlabs! + +## 1.10.2 + +### Fixes + +- [#11215](https://github.com/gradio-app/gradio/pull/11215) [`2186ae3`](https://github.com/gradio-app/gradio/commit/2186ae3f4d6f8ac83883c359aed88a5b72746b5d) - Allow httpx_kwargs to contain cookies. Thanks @santibreo! + +## 1.10.1 + +### Features + +- [#11185](https://github.com/gradio-app/gradio/pull/11185) [`e64b83b`](https://github.com/gradio-app/gradio/commit/e64b83bf42a813d9269e519189523f8390a72ec4) - Evaluate index variable in argument description. Thanks @emmanuel-ferdman! + +### Fixes + +- [#11172](https://github.com/gradio-app/gradio/pull/11172) [`b618571`](https://github.com/gradio-app/gradio/commit/b618571ed17a8cece4bf9f1f55ed2e8bf7b59c46) - Fix python client SSE decoding issue. Thanks @freddyaboulton! + +## 1.10.0 + +### Features + +- [#10984](https://github.com/gradio-app/gradio/pull/10984) [`8dab577`](https://github.com/gradio-app/gradio/commit/8dab5771c7d952c76f325681dbf364119c91b0b1) - Let Gradio apps also be MCP Servers. Thanks @abidlabs! + +## 1.9.1 + +### Fixes + +- [#11093](https://github.com/gradio-app/gradio/pull/11093) [`cb322df`](https://github.com/gradio-app/gradio/commit/cb322df1f4df858590e760a82f6410f3b6db899b) - Update client.py to always send file data, even for files without extensions. Thanks @edmcman! + +## 1.9.0 + +### Features + +- [#11043](https://github.com/gradio-app/gradio/pull/11043) [`62a0080`](https://github.com/gradio-app/gradio/commit/62a00806e198c4c76bc132255d4b78c7aa329157) - Pass any visible error modals from a Gradio app downstream to the app that has `gr.load`-ed it. Thanks @abidlabs! + +## 1.8.0 + +### Features + +- [#10809](https://github.com/gradio-app/gradio/pull/10809) [`99b69df`](https://github.com/gradio-app/gradio/commit/99b69df1c000da092373440800fc08abe6ae9e20) - Trigger python client release. Thanks @freddyaboulton! + +## 1.7.2 + +### Features + +- [#10664](https://github.com/gradio-app/gradio/pull/10664) [`0b1f729`](https://github.com/gradio-app/gradio/commit/0b1f72941fd50298562102e39f4feafaa16f5968) - Allow websocket version 15. Thanks @freddyaboulton! +- Test + +## 1.7.1 + +### Fixes + +- [#10580](https://github.com/gradio-app/gradio/pull/10580) [`4e70d74`](https://github.com/gradio-app/gradio/commit/4e70d74068b77ebb3d285aa78e9202fff76337a2) - Fix `gr.load()` for `gr.ChatInterface(save_history=True)` and any Gradio app where the upstream app includes a `gr.State` as input. Thanks @abidlabs! + +## 1.7.0 + +### Features + +- [#10470](https://github.com/gradio-app/gradio/pull/10470) [`3465fdb`](https://github.com/gradio-app/gradio/commit/3465fdb19087471598ca07c93bc4ff3e1b6b2abf) - Format backend with latest `ruff`. Thanks @abidlabs! +- [#10435](https://github.com/gradio-app/gradio/pull/10435) [`ef66fe5`](https://github.com/gradio-app/gradio/commit/ef66fe52b22448a5125a314581f2ec6c73c24145) - Sidebar Component. Thanks @dawoodkhan82! + +## 1.6.0 + +### Features + +- [#10352](https://github.com/gradio-app/gradio/pull/10352) [`6a7cfc4`](https://github.com/gradio-app/gradio/commit/6a7cfc4264822209148ad07d8f38a0550bdb32b7) - Compatibility between Client and ZeroGPU. Thanks @abidlabs! + +## 1.5.4 + +### Fixes + +- [#10332](https://github.com/gradio-app/gradio/pull/10332) [`e742dcc`](https://github.com/gradio-app/gradio/commit/e742dcccb376692c9ddd5a6c251080e7c5936574) - Allow users to add a custom API route. Thanks @aliabid94! + +## 1.5.3 + +### Features + +- [#10221](https://github.com/gradio-app/gradio/pull/10221) [`506bd28`](https://github.com/gradio-app/gradio/commit/506bd2884a9790fb6f8dbf5684576e80d2b8ee64) - Update Guides related to deploying Gradio chatbots to Discord, Slack, and website widgets. Thanks @abidlabs! + +### Fixes + +- [#10238](https://github.com/gradio-app/gradio/pull/10238) [`3f19210`](https://github.com/gradio-app/gradio/commit/3f192100d6997751d0246b396a4fd8eaa86a826b) - Declare exports in __all__ for type checking. Thanks @dustalov! + +## 1.5.2 + +### Features + +- [#10196](https://github.com/gradio-app/gradio/pull/10196) [`c9ba9a4`](https://github.com/gradio-app/gradio/commit/c9ba9a447596a9ccdd21955adb3b34b15cac7ade) - Use the modern lower-case Python types in the API typing information. Thanks @abidlabs! +- [#10193](https://github.com/gradio-app/gradio/pull/10193) [`424365b`](https://github.com/gradio-app/gradio/commit/424365bdbd0b805e3b2d0c44ccc0f47201b1d96a) - JSON type fix in Client and and typing fix for `/chat` endpoint in `gr.ChatInterface`. Thanks @abidlabs! + +## 1.5.1 + +### Fixes + +- [#10090](https://github.com/gradio-app/gradio/pull/10090) [`5ea3cb5`](https://github.com/gradio-app/gradio/commit/5ea3cb51a39ba01fda7f65ff31e59955e1d12cea) - Update `requirements.txt` for `gradio` and `gradio_client`. Thanks @abidlabs! + +## 1.5.0 + +### Features + +- [#10017](https://github.com/gradio-app/gradio/pull/10017) [`a95fda1`](https://github.com/gradio-app/gradio/commit/a95fda1f85e80ce8423f4373bb238422b9b7aa32) - fix small bug when join src & api_prefix. Thanks @Chandler-Bing! + +## 1.4.3 + +### Fixes + +- [#9913](https://github.com/gradio-app/gradio/pull/9913) [`d81f430`](https://github.com/gradio-app/gradio/commit/d81f430fd50546001b76c0ae5fded32c6d3093f7) - fix: Fix filename stripping to preserve extensions. Thanks @TakaSoap! + +## 1.4.2 + +### Fixes + +- [#9754](https://github.com/gradio-app/gradio/pull/9754) [`36a5076`](https://github.com/gradio-app/gradio/commit/36a50769095081a0e77f04f513d47a2e9d4531ba) - Update client.py: raise error on 429 get_config. Thanks @Pendrokar! + +## 1.4.1 + +### Fixes + +- [#9678](https://github.com/gradio-app/gradio/pull/9678) [`a25a26e`](https://github.com/gradio-app/gradio/commit/a25a26e208c3f3675ba857a889553c7ccc95e866) - Fix: `file_types` checking bug. Thanks @jasongzy! + +## 1.4.0-beta.5 + +### Features + +- [#9589](https://github.com/gradio-app/gradio/pull/9589) [`477f45c`](https://github.com/gradio-app/gradio/commit/477f45cb43be957684eb392e3d62c09490c22391) - Only move files to the cache that have a meta key. Thanks @freddyaboulton! + +## 1.4.0-beta.4 + +### Features + +- [#9550](https://github.com/gradio-app/gradio/pull/9550) [`b0fedd7`](https://github.com/gradio-app/gradio/commit/b0fedd7ef718c0df797ec277db7e773543a70a4d) - Fix most flaky Python tests in `5.0-dev` branch. Thanks @abidlabs! +- [#9483](https://github.com/gradio-app/gradio/pull/9483) [`8dc7c12`](https://github.com/gradio-app/gradio/commit/8dc7c12389311b60efcde1b9d3e3668a34d2dc00) - Send Streaming data over Websocket if possible. Also support base64 output format for images. Thanks @freddyaboulton! +- [#9522](https://github.com/gradio-app/gradio/pull/9522) [`3b71ed2`](https://github.com/gradio-app/gradio/commit/3b71ed21b7e2ecb67eb68fb946d25565169cb4df) - Api info fix. Thanks @freddyaboulton! + +## 1.4.0-beta.3 + +### Fixes + +- [#9431](https://github.com/gradio-app/gradio/pull/9431) [`7065e11`](https://github.com/gradio-app/gradio/commit/7065e11e465fcdfe14688bd6ca2aeed0a25fcc36) - Check for `file_types` parameter in the backend. Thanks @dawoodkhan82! + +## 1.4.0-beta.2 + +### Features + +- [#9339](https://github.com/gradio-app/gradio/pull/9339) [`4c8c6f2`](https://github.com/gradio-app/gradio/commit/4c8c6f2fe603081941c5fdc43f48a0632b9f31ad) - Ssr part 2. Thanks @pngwn! + +## 1.4.0-beta.1 + +### Features + +- [#9200](https://github.com/gradio-app/gradio/pull/9200) [`2e179d3`](https://github.com/gradio-app/gradio/commit/2e179d35be6ed60a5a6bfc7303178d63e41781ad) - prefix api routes. Thanks @pngwn! + +## 1.4.0-beta.0 + +### Features + +- [#9140](https://github.com/gradio-app/gradio/pull/9140) [`c054ec8`](https://github.com/gradio-app/gradio/commit/c054ec85e49ab102b15afd305583ee394151d16c) - Drop python 3.8 and 3.9. Thanks @abidlabs! +- [#8941](https://github.com/gradio-app/gradio/pull/8941) [`97a7bf6`](https://github.com/gradio-app/gradio/commit/97a7bf66a79179d1b91a3199d68e5c11216ca500) - Streaming inputs for 5.0. Thanks @freddyaboulton! + +## 1.3.0 + +### Features + +- [#8968](https://github.com/gradio-app/gradio/pull/8968) [`38b3682`](https://github.com/gradio-app/gradio/commit/38b3682c3a9b40fb4070f665d94711c43c6fe40e) - Improvements to FRP client download and usage. Thanks @abidlabs! +- [#9059](https://github.com/gradio-app/gradio/pull/9059) [`981731a`](https://github.com/gradio-app/gradio/commit/981731acb7da3e78555abeb20f47f3a8a5f0d861) - Fix flaky tests and tests on Windows. Thanks @abidlabs! + +## 1.2.0 + +### Features + +- [#8862](https://github.com/gradio-app/gradio/pull/8862) [`ac132e3`](https://github.com/gradio-app/gradio/commit/ac132e3cbc8dbc7bec3d607d52bef347e90feb41) - Support the use of custom authentication mechanism, timeouts, and other `httpx` parameters in Python Client. Thanks @valgai! +- [#8948](https://github.com/gradio-app/gradio/pull/8948) [`f7fbd2c`](https://github.com/gradio-app/gradio/commit/f7fbd2c23795d97071296463779d41bd0e937164) - Bump websockets version max for gradio-client. Thanks @evanscho! + +## 1.1.1 + +### Features + +- [#8757](https://github.com/gradio-app/gradio/pull/8757) [`6073736`](https://github.com/gradio-app/gradio/commit/60737366517f48d1a37ffce15425783a2887f305) - Document `FileData` class in docs. Thanks @hannahblair! + +## 1.1.0 + +### Fixes + +- [#8505](https://github.com/gradio-app/gradio/pull/8505) [`2943d6d`](https://github.com/gradio-app/gradio/commit/2943d6d68847314885dc6c5c0247083116017ca0) - Add Timer component. Thanks @aliabid94! + +## 1.0.2 + +### Features + +- [#8516](https://github.com/gradio-app/gradio/pull/8516) [`de6aa2b`](https://github.com/gradio-app/gradio/commit/de6aa2b67668605b65ad92842b2c798afa2c6d8a) - Add helper classes to docs. Thanks @aliabd! + +## 1.0.1 + +### Features + +- [#8481](https://github.com/gradio-app/gradio/pull/8481) [`41a4493`](https://github.com/gradio-app/gradio/commit/41a449383a34b7d6e4c83cfbf61c222fd5501206) - fix client flaky tests. Thanks @abidlabs! + +## 1.0.0 + +### Highlights + +#### Clients 1.0 Launch! ([#8468](https://github.com/gradio-app/gradio/pull/8468) [`7cc0a0c`](https://github.com/gradio-app/gradio/commit/7cc0a0c1abea585c3f50ffb1ff78d2b08ddbdd92)) + +We're excited to unveil the first major release of the Gradio clients. +We've made it even easier to turn any Gradio application into a production endpoint thanks to the clients' **ergonomic**, **transparent**, and **portable** design. + +#### Ergonomic API 💆 + +**Stream From a Gradio app in 5 lines** + +Use the `submit` method to get a job you can iterate over: + +```python +from gradio_client import Client + +client = Client("gradio/llm_stream") + +for result in client.submit("What's the best UI framework in Python?"): + print(result) +``` + +```ts +import { Client } from "@gradio/client"; + +const client = await Client.connect("gradio/llm_stream") +const job = client.submit("/predict", {"text": "What's the best UI framework in Python?"}) + +for await (const msg of job) console.log(msg.data) +``` + +**Use the same keyword arguments as the app** + + +```python +from gradio_client import Client + +client = Client("http://127.0.0.1:7860/") +result = client.predict( + message="Hello!!", + system_prompt="You are helpful AI.", + tokens=10, + api_name="/chat" +) +print(result) +``` + +```ts +import { Client } from "@gradio/client"; + +const client = await Client.connect("http://127.0.0.1:7860/"); +const result = await client.predict("/chat", { + message: "Hello!!", + system_prompt: "Hello!!", + tokens: 10, +}); + +console.log(result.data); +``` + +**Better Error Messages** + +If something goes wrong in the upstream app, the client will raise the same exception as the app provided that `show_error=True` in the original app's `launch()` function, or it's a `gr.Error` exception. + +#### Transparent Design 🪟 + +Anything you can do in the UI, you can do with the client: +* 🔒 Authentication +* 🛑 Job Cancelling +* ℹ️ Access Queue Position and API +* 📕 View the API information + +Here's an example showing how to display the queue position of a pending job: + +```python +from gradio_client import Client + +client = Client("gradio/diffusion_model") + +job = client.submit("A cute cat") +while not job.done(): + status = job.status() + print(f"Current in position {status.rank} out of {status.queue_size}") +``` + +#### Portable Design ⛺️ + +The client can run from pretty much any python and javascript environment (node, deno, the browser, Service Workers). + +Here's an example using the client from a Flask server using gevent: + +```python +from gevent import monkey +monkey.patch_all() + +from gradio_client import Client +from flask import Flask, send_file +import time + +app = Flask(__name__) + +imageclient = Client("gradio/diffusion_model") + +@app.route("/gen") +def gen(): + result = imageclient.predict( + "A cute cat", + api_name="/predict" + ) + return send_file(result) + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=5000) +``` + +#### 1.0 Migration Guide and Breaking Changes + +**Python** +- The `serialize` argument of the `Client` class was removed. Has no effect. +- The `upload_files` argument of the `Client` was removed. +- All filepaths must be wrapped in the `handle_file` method. Example: +```python +from gradio_client import Client, handle_file + +client = Client("gradio/image_captioner") +client.predict(handle_file("cute_cat.jpg")) +``` +- The `output_dir` argument was removed. It is not specified in the `download_files` argument. + + +**Javascript** +The client has been redesigned entirely. It was refactored from a function into a class. An instance can now be constructed by awaiting the `connect` method. + +```js +const app = await Client.connect("gradio/whisper") +``` +The app variable has the same methods as the python class (`submit`, `predict`, `view_api`, `duplicate`). + + + +#### Additional Changes + +- [#8243](https://github.com/gradio-app/gradio/pull/8243) - Set orig_name in python client file uploads. +- [#8264](https://github.com/gradio-app/gradio/pull/8264) - Make exceptions in the Client more specific. +- [#8247](https://github.com/gradio-app/gradio/pull/8247) - Fix api recorder. +- [#8276](https://github.com/gradio-app/gradio/pull/8276) - Fix bug where client could not connect to apps that had self signed certificates. +- [#8245](https://github.com/gradio-app/gradio/pull/8245) - Cancel server progress from the python client. +- [#8200](https://github.com/gradio-app/gradio/pull/8200) - Support custom components in gr.load +- [#8182](https://github.com/gradio-app/gradio/pull/8182) - Convert sse calls in client from async to sync. +- [#7732](https://github.com/gradio-app/gradio/pull/7732) - Adds support for kwargs and default arguments in the python client, and improves how parameter information is displayed in the "view API" page. +- [#7888](https://github.com/gradio-app/gradio/pull/7888) - Cache view_api info in server and python client. +- [#7575](https://github.com/gradio-app/gradio/pull/7575) - Files should now be supplied as `file(...)` in the Client, and some fixes to `gr.load()` as well. +- [#8401](https://github.com/gradio-app/gradio/pull/8401) - Add CDN installation to JS docs. +- [#8299](https://github.com/gradio-app/gradio/pull/8299) - Allow JS Client to work with authenticated spaces 🍪. +- [#8408](https://github.com/gradio-app/gradio/pull/8408) - Connect heartbeat if state created in render. Also fix config cleanup bug #8407. +- [#8258](https://github.com/gradio-app/gradio/pull/8258) - Improve URL handling in JS Client. +- [#8322](https://github.com/gradio-app/gradio/pull/8322) - ensure the client correctly handles all binary data. +- [#8296](https://github.com/gradio-app/gradio/pull/8296) - always create a jwt when connecting to a space if a hf_token is present. +- [#8285](https://github.com/gradio-app/gradio/pull/8285) - use the correct query param to pass the jwt to the heartbeat event. +- [#8272](https://github.com/gradio-app/gradio/pull/8272) - ensure client works for private spaces. +- [#8197](https://github.com/gradio-app/gradio/pull/8197) - Add support for passing keyword args to `data` in JS client. +- [#8252](https://github.com/gradio-app/gradio/pull/8252) - Client node fix. +- [#8209](https://github.com/gradio-app/gradio/pull/8209) - Rename `eventSource_Factory` and `fetch_implementation`. +- [#8109](https://github.com/gradio-app/gradio/pull/8109) - Implement JS Client tests. +- [#8211](https://github.com/gradio-app/gradio/pull/8211) - remove redundant event source logic. +- [#8179](https://github.com/gradio-app/gradio/pull/8179) - rework upload to be a class method + pass client into each component. +- [#8181](https://github.com/gradio-app/gradio/pull/8181) - Ensure connectivity to private HF spaces with SSE protocol. +- [#8169](https://github.com/gradio-app/gradio/pull/8169) - Only connect to heartbeat if needed. +- [#8118](https://github.com/gradio-app/gradio/pull/8118) - Add eventsource polyfill for Node.js and browser environments. +- [#7646](https://github.com/gradio-app/gradio/pull/7646) - Refactor JS Client. +- [#7974](https://github.com/gradio-app/gradio/pull/7974) - Fix heartbeat in the js client to be Lite compatible. +- [#7926](https://github.com/gradio-app/gradio/pull/7926) - Fixes streaming event race condition. + + Thanks @freddyaboulton! + +### Features + +- [#8444](https://github.com/gradio-app/gradio/pull/8444) [`2cd02ff`](https://github.com/gradio-app/gradio/commit/2cd02ff3b7c57cd69635d111ff25643eba30b9b0) - Remove deprecated parameters from Python Client. Thanks @abidlabs! + +## 0.17.0 + +### Features + +- [#8243](https://github.com/gradio-app/gradio/pull/8243) [`55f664f`](https://github.com/gradio-app/gradio/commit/55f664f2979a49acc29a73cde16c6ebdfcc91db2) - Add event listener support to render blocks. Thanks @aliabid94! +- [#8409](https://github.com/gradio-app/gradio/pull/8409) [`8028c33`](https://github.com/gradio-app/gradio/commit/8028c33bbc5a324a5e9e8b28906443db28683d79) - Render decorator documentation. Thanks @aliabid94! + +### Fixes + +- [#8371](https://github.com/gradio-app/gradio/pull/8371) [`a373b0e`](https://github.com/gradio-app/gradio/commit/a373b0edd36613a9a6a25a1a2893edd6533a7291) - Set orig_name in python client file uploads. Thanks @freddyaboulton! + +## 0.16.4 + +### Fixes + +- [#8247](https://github.com/gradio-app/gradio/pull/8247) [`8f46556`](https://github.com/gradio-app/gradio/commit/8f46556b38e35cffbadac74ff80445dceea3bcf5) - Fix api recorder. Thanks @abidlabs! + +## 0.16.3 + +### Features + +- [#8264](https://github.com/gradio-app/gradio/pull/8264) [`a9e1a8a`](https://github.com/gradio-app/gradio/commit/a9e1a8ac5633c5336fea1c63d7f66a9883e7e6e1) - Make exceptions in the Client more specific. Thanks @abidlabs! + +### Fixes + +- [#8276](https://github.com/gradio-app/gradio/pull/8276) [`0bf3d1a`](https://github.com/gradio-app/gradio/commit/0bf3d1a992db2753c1a55452b569027190f26ef6) - Fix bug where client could not connect to apps that had self signed certificates. Thanks @freddyaboulton! + +## 0.16.2 + +### Fixes + +- [#8245](https://github.com/gradio-app/gradio/pull/8245) [`c562a3d`](https://github.com/gradio-app/gradio/commit/c562a3d9a440c8f94ca070bd07b8d4121d6ab7b3) - Cancel server progress from the python client. Thanks @freddyaboulton! + +## 0.16.1 + +### Highlights + +#### Support custom components in gr.load ([#8200](https://github.com/gradio-app/gradio/pull/8200) [`72039be`](https://github.com/gradio-app/gradio/commit/72039be93acda856d92ceac7f21f1ec1a054fae2)) + +It is now possible to load a demo with a custom component with `gr.load`. + +The custom component must be installed in your system and imported in your python session. + +```python +import gradio as gr +import gradio_pdf + +demo = gr.load("freddyaboulton/gradiopdf", src="spaces") + +if __name__ == "__main__": + demo.launch() +``` + +image + + Thanks @freddyaboulton! + +### Fixes + +- [#8182](https://github.com/gradio-app/gradio/pull/8182) [`39791eb`](https://github.com/gradio-app/gradio/commit/39791eb186d3a4ce82c8c27979a28311c37a4067) - Convert sse calls in client from async to sync. Thanks @abidlabs! + +## 0.16.0 + +### Highlights + +#### Setting File Upload Limits ([#7909](https://github.com/gradio-app/gradio/pull/7909) [`2afca65`](https://github.com/gradio-app/gradio/commit/2afca6541912b37dc84f447c7ad4af21607d7c72)) + +We have added a `max_file_size` size parameter to `launch()` that limits to size of files uploaded to the server. This limit applies to each individual file. This parameter can be specified as a string or an integer (corresponding to the size in bytes). + +The following code snippet sets a max file size of 5 megabytes. + +```python +import gradio as gr + +demo = gr.Interface(lambda x: x, "image", "image") + +demo.launch(max_file_size="5mb") +# or +demo.launch(max_file_size=5 * gr.FileSize.MB) +``` + +![max_file_size_upload](https://github.com/gradio-app/gradio/assets/41651716/7547330c-a082-4901-a291-3f150a197e45) + + +#### Error states can now be cleared + +When a component encounters an error, the error state shown in the UI can now be cleared by clicking on the `x` icon in the top right of the component. This applies to all types of errors, whether it's raised in the UI or the server. + +![error_modal_calculator](https://github.com/gradio-app/gradio/assets/41651716/16cb071c-accd-45a6-9c18-0dea27d4bd98) + + Thanks @freddyaboulton! + +### Features + +- [#8100](https://github.com/gradio-app/gradio/pull/8100) [`cbdfbdf`](https://github.com/gradio-app/gradio/commit/cbdfbdfc973fa67665911fb5d8cb005a025b0e58) - upgrade `ruff` test dependency to `ruff==0.4.1`. Thanks @abidlabs! + +## 0.15.1 + +### Features + +- [#7850](https://github.com/gradio-app/gradio/pull/7850) [`2bae1cf`](https://github.com/gradio-app/gradio/commit/2bae1cfbd41ed8ae3eea031a64899611a22a1821) - Adds an "API Recorder" to the view API page, some internal methods have been made async. Thanks @abidlabs! + +## 0.15.0 + +### Highlights + +#### Automatically delete state after user has disconnected from the webpage ([#7829](https://github.com/gradio-app/gradio/pull/7829) [`6a4bf7a`](https://github.com/gradio-app/gradio/commit/6a4bf7abe29059dbdc6a342e0366fdaa2e4120ee)) + +Gradio now automatically deletes `gr.State` variables stored in the server's RAM when users close their browser tab. +The deletion will happen 60 minutes after the server detected a disconnect from the user's browser. +If the user connects again in that timeframe, their state will not be deleted. + +Additionally, Gradio now includes a `Blocks.unload()` event, allowing you to run arbitrary cleanup functions when users disconnect (this does not have a 60 minute delay). +You can think of the `unload` event as the opposite of the `load` event. + + +```python +with gr.Blocks() as demo: + gr.Markdown( +"""# State Cleanup Demo +🖼️ Images are saved in a user-specific directory and deleted when the users closes the page via demo.unload. +""") + with gr.Row(): + with gr.Column(scale=1): + with gr.Row(): + img = gr.Image(label="Generated Image", height=300, width=300) + with gr.Row(): + gen = gr.Button(value="Generate") + with gr.Row(): + history = gr.Gallery(label="Previous Generations", height=500, columns=10) + state = gr.State(value=[], delete_callback=lambda v: print("STATE DELETED")) + + demo.load(generate_random_img, [state], [img, state, history]) + gen.click(generate_random_img, [state], [img, state, history]) + demo.unload(delete_directory) + + +demo.launch(auth=lambda user,pwd: True, + auth_message="Enter any username and password to continue") +``` + + Thanks @freddyaboulton! + +### Fixes + +- [#7888](https://github.com/gradio-app/gradio/pull/7888) [`946487c`](https://github.com/gradio-app/gradio/commit/946487cf8e477cbf8d6fad4e772ff574a21782c3) - Cache view_api info in server and python client. Thanks @freddyaboulton! + +## 0.14.0 + +### Features + +- [#7800](https://github.com/gradio-app/gradio/pull/7800) [`b0a3ea9`](https://github.com/gradio-app/gradio/commit/b0a3ea951c06d4f3ff2755b567629fe988a3e30d) - Small fix to client.view_api() in the case of default file values. Thanks @abidlabs! +- [#7732](https://github.com/gradio-app/gradio/pull/7732) [`2efb05e`](https://github.com/gradio-app/gradio/commit/2efb05ed99a8a3575aab0a6c14a8d8b91f4e9ed7) - Adds support for kwargs and default arguments in the python client, and improves how parameter information is displayed in the "view API" page. Thanks @abidlabs! + +## 0.13.0 + +### Features + +- [#7691](https://github.com/gradio-app/gradio/pull/7691) [`84f81fe`](https://github.com/gradio-app/gradio/commit/84f81fec9287b041203a141bbf2852720f7d199c) - Closing stream from the backend. Thanks @aliabid94! + +### Fixes + +- [#7718](https://github.com/gradio-app/gradio/pull/7718) [`6390d0b`](https://github.com/gradio-app/gradio/commit/6390d0bf6c2be0aefa56102dd029f25161bfebc3) - Add support for python client connecting to gradio apps running with self-signed SSL certificates. Thanks @abidlabs! +- [#7706](https://github.com/gradio-app/gradio/pull/7706) [`bc61ff6`](https://github.com/gradio-app/gradio/commit/bc61ff6b1603eedf3111f1b5c3d2751629902d98) - Several fixes to `gr.load`. Thanks @abidlabs! + +## 0.12.0 + +### Fixes + +- [#7575](https://github.com/gradio-app/gradio/pull/7575) [`d0688b3`](https://github.com/gradio-app/gradio/commit/d0688b3c25feabb4fc7dfa0ab86086b3af7eb337) - Files should now be supplied as `file(...)` in the Client, and some fixes to `gr.load()` as well. Thanks @abidlabs! +- [#7618](https://github.com/gradio-app/gradio/pull/7618) [`0ae1e44`](https://github.com/gradio-app/gradio/commit/0ae1e4486c06e06bb7a4bad45d58d14f1f8d1b94) - Control which files get moved to cache with gr.set_static_paths. Thanks @freddyaboulton! + +## 0.11.0 + +### Features + +- [#7407](https://github.com/gradio-app/gradio/pull/7407) [`375bfd2`](https://github.com/gradio-app/gradio/commit/375bfd28d2def576b4e1c12e0a60127b7419e826) - Fix server_messages.py to use the patched BaseModel class for Wasm env. Thanks [@aliabid94](https://github.com/aliabid94)! + +### Fixes + +- [#7555](https://github.com/gradio-app/gradio/pull/7555) [`fc4c2db`](https://github.com/gradio-app/gradio/commit/fc4c2dbd994c49e37296978da1cb85e424080d1c) - Allow Python Client to upload/download files when connecting to Gradio apps with auth enabled. Thanks [@abidlabs](https://github.com/abidlabs)! + +## 0.10.1 + +### Features + +- [#7495](https://github.com/gradio-app/gradio/pull/7495) [`ddd4d3e`](https://github.com/gradio-app/gradio/commit/ddd4d3e4d3883fb7540d1df240fb08202fc77705) - Enable Ruff S101. Thanks [@abidlabs](https://github.com/abidlabs)! +- [#7443](https://github.com/gradio-app/gradio/pull/7443) [`b7a97f2`](https://github.com/gradio-app/gradio/commit/b7a97f29b84a72678a717db03d2932ed6caae6ce) - Update `httpx` to `httpx>=0.24.1` in `requirements.txt`. Thanks [@abidlabs](https://github.com/abidlabs)! + +## 0.10.0 + +### Features + +- [#7183](https://github.com/gradio-app/gradio/pull/7183) [`49d9c48`](https://github.com/gradio-app/gradio/commit/49d9c48537aa706bf72628e3640389470138bdc6) - [WIP] Refactor file normalization to be in the backend and remove it from the frontend of each component. Thanks [@abidlabs](https://github.com/abidlabs)! +- [#7377](https://github.com/gradio-app/gradio/pull/7377) [`6dfd40f`](https://github.com/gradio-app/gradio/commit/6dfd40fc6b2fa461490d2370ab91fcda7e07c0da) - Make set_documentation_group a no-op. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! +- [#7334](https://github.com/gradio-app/gradio/pull/7334) [`b95d0d0`](https://github.com/gradio-app/gradio/commit/b95d0d043c739926af986e573200af92732bbc01) - Allow setting custom headers in Python Client. Thanks [@abidlabs](https://github.com/abidlabs)! + +### Fixes + +- [#7350](https://github.com/gradio-app/gradio/pull/7350) [`7302a6e`](https://github.com/gradio-app/gradio/commit/7302a6e151dac553c17833be64d4639ee4cf97aa) - Fix `gr.load` for file-based Spaces. Thanks [@abidlabs](https://github.com/abidlabs)! + +## 0.9.0 + +### Features + +- [#7062](https://github.com/gradio-app/gradio/pull/7062) [`0fddd0f`](https://github.com/gradio-app/gradio/commit/0fddd0f971761bff3ef6ccc7ab9deb1891cd80d0) - Determine documentation group automatically. Thanks [@akx](https://github.com/akx)! +- [#7102](https://github.com/gradio-app/gradio/pull/7102) [`68a54a7`](https://github.com/gradio-app/gradio/commit/68a54a7a310d8d7072fdae930bf1cfdf12c45a7f) - Improve chatbot streaming performance with diffs. Thanks [@aliabid94](https://github.com/aliabid94)!/n Note that this PR changes the API format for generator functions, which would be a breaking change for any clients reading the EventStream directly +- [#7116](https://github.com/gradio-app/gradio/pull/7116) [`3c8c4ac`](https://github.com/gradio-app/gradio/commit/3c8c4ac2db284e1cb503c397205a79a6dcc27e23) - Document the `gr.ParamViewer` component, and fix component preprocessing/postprocessing docstrings. Thanks [@abidlabs](https://github.com/abidlabs)! +- [#7061](https://github.com/gradio-app/gradio/pull/7061) [`05d8a3c`](https://github.com/gradio-app/gradio/commit/05d8a3c8030b733bd47250f5db6f89f230f9a707) - Update ruff to 0.1.13, enable more rules, fix issues. Thanks [@akx](https://github.com/akx)! + +### Fixes + +- [#7178](https://github.com/gradio-app/gradio/pull/7178) [`9f23b0b`](https://github.com/gradio-app/gradio/commit/9f23b0bc54b4ef63c056b309370df52ec2c2a43c) - Optimize client view_api method. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! +- [#7322](https://github.com/gradio-app/gradio/pull/7322) [`b25e95e`](https://github.com/gradio-app/gradio/commit/b25e95e164e80d66203ef71ce6bdb67ceb6b24df) - Fix `processing_utils.save_url_to_cache()` to follow redirects when accessing the URL. Thanks [@whitphx](https://github.com/whitphx)! + +## 0.8.1 + +### Features + +- [#7075](https://github.com/gradio-app/gradio/pull/7075) [`1fc8a94`](https://github.com/gradio-app/gradio/commit/1fc8a941384775f587a6ef30365960f43353cb0d) - fix lint. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! +- [#7054](https://github.com/gradio-app/gradio/pull/7054) [`64c65d8`](https://github.com/gradio-app/gradio/commit/64c65d821983961111297a969946d87e2fc4105d) - Add encoding to open/writing files on the deploy_discord function. Thanks [@WilliamHarer](https://github.com/WilliamHarer)! + +## 0.8.0 + +### Fixes + +- [#6846](https://github.com/gradio-app/gradio/pull/6846) [`48d6534`](https://github.com/gradio-app/gradio/commit/48d6534b40f80e7e70a4061f97d9f2e23ba77fe1) - Add `show_api` parameter to events, and fix `gr.load()`. Also makes some minor improvements to the "view API" page when running on Spaces. Thanks [@abidlabs](https://github.com/abidlabs)! +- [#6767](https://github.com/gradio-app/gradio/pull/6767) [`7bb561a`](https://github.com/gradio-app/gradio/commit/7bb561a294ca41d1044927cb34d8645c4175cae0) - Rewriting parts of the README and getting started guides for 4.0. Thanks [@abidlabs](https://github.com/abidlabs)! + +## 0.7.3 + +### Fixes + +- [#6693](https://github.com/gradio-app/gradio/pull/6693) [`34f9431`](https://github.com/gradio-app/gradio/commit/34f943101bf7dd6b8a8974a6131c1ed7c4a0dac0) - Python client properly handles hearbeat and log messages. Also handles responses longer than 65k. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! + +## 0.7.2 + +### Features + +- [#6598](https://github.com/gradio-app/gradio/pull/6598) [`7cbf96e`](https://github.com/gradio-app/gradio/commit/7cbf96e0bdd12db7ecac7bf99694df0a912e5864) - Issue 5245: consolidate usage of requests and httpx. Thanks [@cswamy](https://github.com/cswamy)! +- [#6704](https://github.com/gradio-app/gradio/pull/6704) [`24e0481`](https://github.com/gradio-app/gradio/commit/24e048196e8f7bd309ef5c597d4ffc6ca4ed55d0) - Hotfix: update `huggingface_hub` dependency version. Thanks [@abidlabs](https://github.com/abidlabs)! +- [#6543](https://github.com/gradio-app/gradio/pull/6543) [`8a70e83`](https://github.com/gradio-app/gradio/commit/8a70e83db9c7751b46058cdd2514e6bddeef6210) - switch from black to ruff formatter. Thanks [@DarhkVoyd](https://github.com/DarhkVoyd)! + +### Fixes + +- [#6556](https://github.com/gradio-app/gradio/pull/6556) [`d76bcaa`](https://github.com/gradio-app/gradio/commit/d76bcaaaf0734aaf49a680f94ea9d4d22a602e70) - Fix api event drops. Thanks [@aliabid94](https://github.com/aliabid94)! + +## 0.7.1 + +### Fixes + +- [#6602](https://github.com/gradio-app/gradio/pull/6602) [`b8034a1`](https://github.com/gradio-app/gradio/commit/b8034a1e72c3aac649ee0ad9178ffdbaaa60fc61) - Fix: Gradio Client work with private Spaces. Thanks [@abidlabs](https://github.com/abidlabs)! + +## 0.7.0 + +### Features + +- [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - Add json schema unit tests. Thanks [@pngwn](https://github.com/pngwn)! +- [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - Image v4. Thanks [@pngwn](https://github.com/pngwn)! +- [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - Custom components. Thanks [@pngwn](https://github.com/pngwn)! +- [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - Swap websockets for SSE. Thanks [@pngwn](https://github.com/pngwn)! + +## 0.7.0-beta.2 + +### Features + +- [#6094](https://github.com/gradio-app/gradio/pull/6094) [`c476bd5a5`](https://github.com/gradio-app/gradio/commit/c476bd5a5b70836163b9c69bf4bfe068b17fbe13) - Image v4. Thanks [@pngwn](https://github.com/pngwn)! +- [#6069](https://github.com/gradio-app/gradio/pull/6069) [`bf127e124`](https://github.com/gradio-app/gradio/commit/bf127e1241a41401e144874ea468dff8474eb505) - Swap websockets for SSE. Thanks [@aliabid94](https://github.com/aliabid94)! + +## 0.7.0-beta.1 + +### Features + +- [#6082](https://github.com/gradio-app/gradio/pull/6082) [`037e5af33`](https://github.com/gradio-app/gradio/commit/037e5af3363c5b321b95efc955ee8d6ec0f4504e) - WIP: Fix docs. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! +- [#5970](https://github.com/gradio-app/gradio/pull/5970) [`0c571c044`](https://github.com/gradio-app/gradio/commit/0c571c044035989d6fe33fc01fee63d1780635cb) - Add json schema unit tests. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! +- [#6073](https://github.com/gradio-app/gradio/pull/6073) [`abff6fb75`](https://github.com/gradio-app/gradio/commit/abff6fb758bd310053a23c938bf1dd8fbdc5d333) - Fix remaining xfail tests in backend. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! + +## 0.7.0-beta.0 + +### Features + +- [#5498](https://github.com/gradio-app/gradio/pull/5498) [`85ba6de13`](https://github.com/gradio-app/gradio/commit/85ba6de136a45b3e92c74e410bb27e3cbe7138d7) - Simplify how files are handled in components in 4.0. Thanks [@pngwn](https://github.com/pngwn)! +- [#5498](https://github.com/gradio-app/gradio/pull/5498) [`85ba6de13`](https://github.com/gradio-app/gradio/commit/85ba6de136a45b3e92c74e410bb27e3cbe7138d7) - Rename gradio_component to gradio component. Thanks [@pngwn](https://github.com/pngwn)! + +## 0.6.1 + +### Fixes + +- [#5811](https://github.com/gradio-app/gradio/pull/5811) [`1d5b15a2d`](https://github.com/gradio-app/gradio/commit/1d5b15a2d24387154f2cfb40a36de25b331471d3) - Assert refactor in external.py. Thanks [@harry-urek](https://github.com/harry-urek)! + +## 0.6.0 + +### Highlights + +#### new `FileExplorer` component ([#5672](https://github.com/gradio-app/gradio/pull/5672) [`e4a307ed6`](https://github.com/gradio-app/gradio/commit/e4a307ed6cde3bbdf4ff2f17655739addeec941e)) + +Thanks to a new capability that allows components to communicate directly with the server _without_ passing data via the value, we have created a new `FileExplorer` component. + +This component allows you to populate the explorer by passing a glob, but only provides the selected file(s) in your prediction function. + +Users can then navigate the virtual filesystem and select files which will be accessible in your predict function. This component will allow developers to build more complex spaces, with more flexible input options. + +![output](https://github.com/pngwn/MDsveX/assets/12937446/ef108f0b-0e84-4292-9984-9dc66b3e144d) + +For more information check the [`FileExplorer` documentation](https://gradio.app/docs/fileexplorer). + + Thanks [@aliabid94](https://github.com/aliabid94)! + +## 0.5.3 + +### Features + +- [#5721](https://github.com/gradio-app/gradio/pull/5721) [`84e03fe50`](https://github.com/gradio-app/gradio/commit/84e03fe506e08f1f81bac6d504c9fba7924f2d93) - Adds copy buttons to website, and better descriptions to API Docs. Thanks [@aliabd](https://github.com/aliabd)! + +## 0.5.2 + +### Features + +- [#5653](https://github.com/gradio-app/gradio/pull/5653) [`ea0e00b20`](https://github.com/gradio-app/gradio/commit/ea0e00b207b4b90a10e9d054c4202d4e705a29ba) - Prevent Clients from accessing API endpoints that set `api_name=False`. Thanks [@abidlabs](https://github.com/abidlabs)! + +## 0.5.1 + +### Features + +- [#5514](https://github.com/gradio-app/gradio/pull/5514) [`52f783175`](https://github.com/gradio-app/gradio/commit/52f7831751b432411e109bd41add4ab286023a8e) - refactor: Use package.json for version management. Thanks [@DarhkVoyd](https://github.com/DarhkVoyd)! + +## 0.5.0 + +### Highlights + +#### Enable streaming audio in python client ([#5248](https://github.com/gradio-app/gradio/pull/5248) [`390624d8`](https://github.com/gradio-app/gradio/commit/390624d8ad2b1308a5bf8384435fd0db98d8e29e)) + +The `gradio_client` now supports streaming file outputs 🌊 + +No new syntax! Connect to a gradio demo that supports streaming file outputs and call `predict` or `submit` as you normally would. + +```python +import gradio_client as grc +client = grc.Client("gradio/stream_audio_out") + +# Get the entire generated audio as a local file +client.predict("/Users/freddy/Pictures/bark_demo.mp4", api_name="/predict") + +job = client.submit("/Users/freddy/Pictures/bark_demo.mp4", api_name="/predict") + +# Get the entire generated audio as a local file +job.result() + +# Each individual chunk +job.outputs() +``` + + Thanks [@freddyaboulton](https://github.com/freddyaboulton)! + +### Fixes + +- [#5295](https://github.com/gradio-app/gradio/pull/5295) [`7b8fa8aa`](https://github.com/gradio-app/gradio/commit/7b8fa8aa58f95f5046b9add64b40368bd3f1b700) - Allow caching examples with streamed output. Thanks [@aliabid94](https://github.com/aliabid94)! + +## 0.4.0 + +### Highlights + +#### Client.predict will now return the final output for streaming endpoints ([#5057](https://github.com/gradio-app/gradio/pull/5057) [`35856f8b`](https://github.com/gradio-app/gradio/commit/35856f8b54548cae7bd3b8d6a4de69e1748283b2)) + +### This is a breaking change (for gradio_client only)! + +Previously, `Client.predict` would only return the first output of an endpoint that streamed results. This was causing confusion for developers that wanted to call these streaming demos via the client. + +We realize that developers using the client don't know the internals of whether a demo streams or not, so we're changing the behavior of predict to match developer expectations. + +Using `Client.predict` will now return the final output of a streaming endpoint. This will make it even easier to use gradio apps via the client. + + Thanks [@freddyaboulton](https://github.com/freddyaboulton)! + +### Features + +- [#5076](https://github.com/gradio-app/gradio/pull/5076) [`2745075a`](https://github.com/gradio-app/gradio/commit/2745075a26f80e0e16863d483401ff1b6c5ada7a) - Add deploy_discord to docs. Thanks [@freddyaboulton](https://github.com/freddyaboulton)! + +### Fixes + +- [#5061](https://github.com/gradio-app/gradio/pull/5061) [`136adc9c`](https://github.com/gradio-app/gradio/commit/136adc9ccb23e5cb4d02d2e88f23f0b850041f98) - Ensure `gradio_client` is backwards compatible with `gradio==3.24.1`. Thanks [@abidlabs](https://github.com/abidlabs)! + +## 0.3.0 + +### Highlights + +#### Create Discord Bots from Gradio Apps 🤖 ([#4960](https://github.com/gradio-app/gradio/pull/4960) [`46e4ef67`](https://github.com/gradio-app/gradio/commit/46e4ef67d287dd68a91473b73172b29cbad064bc)) + +We're excited to announce that Gradio can now automatically create a discord bot from any `gr.ChatInterface` app. + +It's as easy as importing `gradio_client`, connecting to the app, and calling `deploy_discord`! + +_🦙 Turning Llama 2 70b into a discord bot 🦙_ + +```python +import gradio_client as grc +grc.Client("ysharma/Explore_llamav2_with_TGI").deploy_discord(to_id="llama2-70b-discord-bot") +``` + + + +#### Getting started with template spaces + +To help get you started, we have created an organization on Hugging Face called [gradio-discord-bots](https://huggingface.co/gradio-discord-bots) with template spaces you can use to turn state of the art LLMs powered by Gradio to discord bots. + +Currently we have template spaces for: + +- [Llama-2-70b-chat-hf](https://huggingface.co/spaces/gradio-discord-bots/Llama-2-70b-chat-hf) powered by a FREE Hugging Face Inference Endpoint! +- [Llama-2-13b-chat-hf](https://huggingface.co/spaces/gradio-discord-bots/Llama-2-13b-chat-hf) powered by Hugging Face Inference Endpoints. +- [Llama-2-13b-chat-hf](https://huggingface.co/spaces/gradio-discord-bots/llama-2-13b-chat-transformers) powered by Hugging Face transformers. +- [falcon-7b-instruct](https://huggingface.co/spaces/gradio-discord-bots/falcon-7b-instruct) powered by Hugging Face Inference Endpoints. +- [gpt-3.5-turbo](https://huggingface.co/spaces/gradio-discord-bots/gpt-35-turbo), powered by openai. Requires an OpenAI key. + +But once again, you can deploy ANY `gr.ChatInterface` app exposed on the internet! So don't hesitate to try it on your own Chatbots. + +❗️ Additional Note ❗️: Technically, any gradio app that exposes an api route that takes in a single string and outputs a single string can be deployed to discord. But `gr.ChatInterface` apps naturally lend themselves to discord's chat functionality so we suggest you start with those. + +Thanks [@freddyaboulton](https://github.com/freddyaboulton)! + +### New Features: + +- Endpoints that return layout components are now properly handled in the `submit` and `view_api` methods. Output layout components are not returned by the API but all other components are (excluding `gr.State`). By [@freddyaboulton](https://github.com/freddyaboulton) in [PR 4871](https://github.com/gradio-app/gradio/pull/4871) + +### Bug Fixes: + +No changes to highlight + +### Breaking Changes: + +No changes to highlight. + +### Full Changelog: + +No changes to highlight. + +# 0.2.9 + +### New Features: + +No changes to highlight + +### Bug Fixes: + +- Fix bug determining the api name when a demo has `api_name=False` by [@freddyboulton](https://github.com/freddyaboulton) in [PR 4886](https://github.com/gradio-app/gradio/pull/4886) + +### Breaking Changes: + +No changes to highlight. + +### Full Changelog: + +- Pinned dependencies to major versions to reduce the likelihood of a broken `gradio_client` due to changes in downstream dependencies by [@abidlabs](https://github.com/abidlabs) in [PR 4885](https://github.com/gradio-app/gradio/pull/4885) + +# 0.2.8 + +### New Features: + +- Support loading gradio apps where `api_name=False` by [@abidlabs](https://github.com/abidlabs) in [PR 4683](https://github.com/gradio-app/gradio/pull/4683) + +### Bug Fixes: + +- Fix bug where space duplication would error if the demo has cpu-basic hardware by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 4583](https://github.com/gradio-app/gradio/pull/4583) +- Fixes and optimizations to URL/download functions by [@akx](https://github.com/akx) in [PR 4695](https://github.com/gradio-app/gradio/pull/4695) + +### Breaking Changes: + +No changes to highlight. + +### Full Changelog: + +No changes to highlight. + +# 0.2.7 + +### New Features: + +- The output directory for files downloaded via the Client can now be set by the `output_dir` parameter in `Client` by [@abidlabs](https://github.com/abidlabs) in [PR 4501](https://github.com/gradio-app/gradio/pull/4501) + +### Bug Fixes: + +- The output directory for files downloaded via the Client are now set to a temporary directory by default (instead of the working directory in some cases) by [@abidlabs](https://github.com/abidlabs) in [PR 4501](https://github.com/gradio-app/gradio/pull/4501) + +### Breaking Changes: + +No changes to highlight. + +### Full Changelog: + +No changes to highlight. + +# 0.2.6 + +### New Features: + +No changes to highlight. + +### Bug Fixes: + +- Fixed bug file deserialization didn't preserve all file extensions by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 4440](https://github.com/gradio-app/gradio/pull/4440) +- Fixed bug where mounted apps could not be called via the client by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 4435](https://github.com/gradio-app/gradio/pull/4435) + +### Breaking Changes: + +No changes to highlight. + +### Full Changelog: + +No changes to highlight. + +# 0.2.5 + +### New Features: + +No changes to highlight. + +### Bug Fixes: + +- Fixes parameter names not showing underscores by [@abidlabs](https://github.com/abidlabs) in [PR 4230](https://github.com/gradio-app/gradio/pull/4230) +- Fixes issue in which state was not handled correctly if `serialize=False` by [@abidlabs](https://github.com/abidlabs) in [PR 4230](https://github.com/gradio-app/gradio/pull/4230) + +### Breaking Changes: + +No changes to highlight. + +### Full Changelog: + +No changes to highlight. + +# 0.2.4 + +### Bug Fixes: + +- Fixes missing serialization classes for several components: `Barplot`, `Lineplot`, `Scatterplot`, `AnnotatedImage`, `Interpretation` by [@abidlabs](https://github.com/abidlabs) in [PR 4167](https://github.com/gradio-app/gradio/pull/4167) + +### Documentation Changes: + +No changes to highlight. + +### Testing and Infrastructure Changes: + +No changes to highlight. + +### Breaking Changes: + +No changes to highlight. + +### Full Changelog: + +No changes to highlight. + +### Contributors Shoutout: + +No changes to highlight. + +# 0.2.3 + +### New Features: + +No changes to highlight. + +### Bug Fixes: + +- Fix example inputs for `gr.File(file_count='multiple')` output components by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 4153](https://github.com/gradio-app/gradio/pull/4153) + +### Documentation Changes: + +No changes to highlight. + +### Testing and Infrastructure Changes: + +No changes to highlight. + +### Breaking Changes: + +No changes to highlight. + +### Full Changelog: + +No changes to highlight. + +### Contributors Shoutout: + +No changes to highlight. + +# 0.2.2 + +### New Features: + +No changes to highlight. + +### Bug Fixes: + +- Only send request to `/info` route if demo version is above `3.28.3` by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 4109](https://github.com/gradio-app/gradio/pull/4109) + +### Other Changes: + +- Fix bug in test from gradio 3.29.0 refactor by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 4138](https://github.com/gradio-app/gradio/pull/4138) + +### Breaking Changes: + +No changes to highlight. + +# 0.2.1 + +### New Features: + +No changes to highlight. + +### Bug Fixes: + +Removes extraneous `State` component info from the `Client.view_api()` method by [@abidlabs](https://github.com/freddyaboulton) in [PR 4107](https://github.com/gradio-app/gradio/pull/4107) + +### Documentation Changes: + +No changes to highlight. + +### Testing and Infrastructure Changes: + +Separates flaky tests from non-flaky tests by [@abidlabs](https://github.com/freddyaboulton) in [PR 4107](https://github.com/gradio-app/gradio/pull/4107) + +### Breaking Changes: + +No changes to highlight. + +### Full Changelog: + +No changes to highlight. + +### Contributors Shoutout: + +No changes to highlight. + +# 0.1.4 + +### New Features: + +- Progress Updates from `gr.Progress()` can be accessed via `job.status().progress_data` by @freddyaboulton](https://github.com/freddyaboulton) in [PR 3924](https://github.com/gradio-app/gradio/pull/3924) + +### Bug Fixes: + +- Fixed bug where unnamed routes where displayed with `api_name` instead of `fn_index` in `view_api` by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 3972](https://github.com/gradio-app/gradio/pull/3972) + +### Documentation Changes: + +No changes to highlight. + +### Testing and Infrastructure Changes: + +No changes to highlight. + +### Breaking Changes: + +No changes to highlight. + +### Full Changelog: + +No changes to highlight. + +### Contributors Shoutout: + +No changes to highlight. + +# 0.1.3 + +### New Features: + +No changes to highlight. + +### Bug Fixes: + +- Fixed bug where `Video` components in latest gradio were not able to be deserialized by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 3860](https://github.com/gradio-app/gradio/pull/3860) + +### Documentation Changes: + +No changes to highlight. + +### Testing and Infrastructure Changes: + +No changes to highlight. + +### Breaking Changes: + +No changes to highlight. + +### Full Changelog: + +No changes to highlight. + +### Contributors Shoutout: + +No changes to highlight. + +# 0.1.2 + +First public release of the Gradio Client library! The `gradio_client` Python library that makes it very easy to use any Gradio app as an API. + +As an example, consider this [Hugging Face Space that transcribes audio files](https://huggingface.co/spaces/abidlabs/whisper) that are recorded from the microphone. + +![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/whisper-screenshot.jpg) + +Using the `gradio_client` library, we can easily use the Gradio as an API to transcribe audio files programmatically. + +Here's the entire code to do it: + +```python +from gradio_client import Client + +client = Client("abidlabs/whisper") +client.predict("audio_sample.wav") + +>> "This is a test of the whisper speech recognition model." +``` + +Read more about how to use the `gradio_client` library here: https://gradio.app/getting-started-with-the-python-client/ \ No newline at end of file diff --git a/venv/lib/python3.10/site-packages/gradio_client/__init__.py b/venv/lib/python3.10/site-packages/gradio_client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..037264eeba8203f86e986ae23fe0814409b3f779 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gradio_client/__init__.py @@ -0,0 +1,11 @@ +from gradio_client.client import Client +from gradio_client.data_classes import FileData +from gradio_client.utils import __version__, file, handle_file + +__all__ = [ + "Client", + "file", + "handle_file", + "FileData", + "__version__", +] diff --git a/venv/lib/python3.10/site-packages/gradio_client/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4ad2f07665f1b3ced419157c391a8f4ae78fa74 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gradio_client/__pycache__/client.cpython-310.pyc b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/client.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf6f34767753b64fff452bcf3c7493b6f1799f89 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/client.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gradio_client/__pycache__/compatibility.cpython-310.pyc b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/compatibility.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e869ef7b033f4d399ef0ee6bf234f7a2ccd1d09a Binary files /dev/null and b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/compatibility.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gradio_client/__pycache__/data_classes.cpython-310.pyc b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/data_classes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4842f74153d6593c6117df4997d365f01c5ba59 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/data_classes.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gradio_client/__pycache__/documentation.cpython-310.pyc b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/documentation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..942c4f508dff70c6e277a2a729d2291dae23f423 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/documentation.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gradio_client/__pycache__/exceptions.cpython-310.pyc b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..914d51045d4d2bdc02950a1bef9f0cebb414fa83 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/exceptions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gradio_client/__pycache__/serializing.cpython-310.pyc b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/serializing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ef7211ca15a15a7f40ef8fcfb5d0cbe16d86f60 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/serializing.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gradio_client/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efd3297496f10feb37268452902636a112bcc387 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gradio_client/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gradio_client/cli/__init__.py b/venv/lib/python3.10/site-packages/gradio_client/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0c796253489147f941b78b5bb04a82935a72edab --- /dev/null +++ b/venv/lib/python3.10/site-packages/gradio_client/cli/__init__.py @@ -0,0 +1,3 @@ +from gradio_client.cli import deploy_discord + +__all__ = ["deploy_discord"] diff --git a/venv/lib/python3.10/site-packages/gradio_client/cli/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/gradio_client/cli/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5862ab50c3f751603e6df5d7fab5ac6f0276cd35 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gradio_client/cli/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gradio_client/cli/__pycache__/deploy_discord.cpython-310.pyc b/venv/lib/python3.10/site-packages/gradio_client/cli/__pycache__/deploy_discord.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcd42233fad23ff6405310cb9c1bdb5f3711a558 Binary files /dev/null and b/venv/lib/python3.10/site-packages/gradio_client/cli/__pycache__/deploy_discord.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gradio_client/cli/deploy_discord.py b/venv/lib/python3.10/site-packages/gradio_client/cli/deploy_discord.py new file mode 100644 index 0000000000000000000000000000000000000000..e653007428a6b02d33c80d3d7d82b8b43551bc34 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gradio_client/cli/deploy_discord.py @@ -0,0 +1,47 @@ +from typing import Annotated, Optional + +from typer import Option + +from gradio_client import Client + + +def main( + src: Annotated[ + Optional[str], + Option( + help="The space id or url or gradio app you want to deploy as a gradio bot." + ), + ] = None, + discord_bot_token: Annotated[ + str, Option(help="Discord bot token. Get one on the discord website.") + ] = None, + api_names: Annotated[ + list[str], Option(help="Api names to turn into discord bots") + ] = None, + to_id: Annotated[ + Optional[str], Option(help="Name of the space used to host the discord bot") + ] = None, + hf_token: Annotated[ + Optional[str], + Option( + help=( + "Hugging Face token. Can be ommitted if you are logged in via huggingface_hub cli. " + "Must be provided if upstream space is private." + ) + ), + ] = None, + private: Annotated[ + bool, Option(help="Whether the discord bot space is private.") + ] = False, +): + for i, name in enumerate(api_names): + if "," in name: + api_names[i] = tuple(name.split(",")) + + Client(src).deploy_discord( + discord_bot_token=discord_bot_token, + api_names=api_names, + to_id=to_id, + hf_token=hf_token, + private=private, + ) diff --git a/venv/lib/python3.10/site-packages/gradio_client/client.py b/venv/lib/python3.10/site-packages/gradio_client/client.py new file mode 100644 index 0000000000000000000000000000000000000000..6617eba7f286c018e7d6ef8f4ffa49b915f1b440 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gradio_client/client.py @@ -0,0 +1,1729 @@ +"""The main Client class for the Python client.""" + +from __future__ import annotations + +import asyncio +import concurrent.futures +import hashlib +import json +import math +import os +import re +import secrets +import shutil +import tempfile +import threading +import time +import urllib.parse +import uuid +import warnings +from collections.abc import AsyncGenerator, Callable +from concurrent.futures import Future +from dataclasses import dataclass +from datetime import datetime +from functools import partial +from pathlib import Path +from threading import Lock +from typing import Any, Literal, cast + +import httpx +import huggingface_hub +from huggingface_hub import CommitOperationAdd, SpaceHardware, SpaceStage +from huggingface_hub.utils import ( + RepositoryNotFoundError, + build_hf_headers, + send_telemetry, +) +from packaging import version + +from gradio_client import utils +from gradio_client.compatibility import EndpointV3Compatibility +from gradio_client.data_classes import ParameterInfo +from gradio_client.documentation import document +from gradio_client.exceptions import AppError, AuthenticationError +from gradio_client.utils import ( + Communicator, + JobStatus, + Message, + QueueError, + ServerMessage, + Status, + StatusUpdate, + Update, +) + +DEFAULT_TEMP_DIR = os.environ.get("GRADIO_TEMP_DIR") or str( + Path(tempfile.gettempdir()) / "gradio" +) + + +@document("predict", "submit", "view_api", "duplicate", "deploy_discord") +class Client: + """ + The main Client class for the Python client. This class is used to connect to a remote Gradio app and call its API endpoints. + + Example: + from gradio_client import Client + + client = Client("abidlabs/whisper-large-v2") # connecting to a Hugging Face Space + client.predict("test.mp4", api_name="/predict") + >> What a nice recording! # returns the result of the remote API call + + client = Client("https://bec81a83-5b5c-471e.gradio.live") # connecting to a temporary Gradio share URL + job = client.submit("hello", api_name="/predict") # runs the prediction in a background thread + job.result() + >> 49 # returns the result of the remote API call (blocking call) + """ + + def __init__( + self, + src: str, + hf_token: str | Literal[False] | None = False, + max_workers: int = 40, + verbose: bool = True, + auth: tuple[str, str] | None = None, + httpx_kwargs: dict[str, Any] | None = None, + *, + headers: dict[str, str] | None = None, + download_files: str | Path | Literal[False] = DEFAULT_TEMP_DIR, + ssl_verify: bool = True, + _skip_components: bool = True, # internal parameter to skip values certain components (e.g. State) that do not need to be displayed to users. + analytics_enabled: bool = True, + ): + """ + Parameters: + src: either the name of the Hugging Face Space to load, (e.g. "abidlabs/whisper-large-v2") or the full URL (including "http" or "https") of the hosted Gradio app to load (e.g. "http://mydomain.com/app" or "https://bec81a83-5b5c-471e.gradio.live/"). + hf_token: optional Hugging Face token to use to access private Spaces. By default, no token is sent to the server. Set `hf_token=None` to use the locally saved token if there is one (warning: only provide a token if you are loading a trusted private Space as the token can be read by the Space you are loading). Find your tokens here: https://huggingface.co/settings/tokens. + max_workers: maximum number of thread workers that can be used to make requests to the remote Gradio app simultaneously. + verbose: whether the client should print statements to the console. + headers: additional headers to send to the remote Gradio app on every request. By default only the HF authorization and user-agent headers are sent. This parameter will override the default headers if they have the same keys. + download_files: directory where the client should download output files on the local machine from the remote API. By default, uses the value of the GRADIO_TEMP_DIR environment variable which, if not set by the user, is a temporary directory on your machine. If False, the client does not download files and returns a FileData dataclass object with the filepath on the remote machine instead. + ssl_verify: if False, skips certificate validation which allows the client to connect to Gradio apps that are using self-signed certificates. + httpx_kwargs: additional keyword arguments to pass to `httpx.Client`, `httpx.stream`, `httpx.get` and `httpx.post`. This can be used to set timeouts, proxies, http auth, etc. + analytics_enabled: Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True. + """ + self.verbose = verbose + self.hf_token = hf_token + self.download_files = download_files + self._skip_components = _skip_components + self.headers = build_hf_headers( + token=hf_token, + library_name="gradio_client", + library_version=utils.__version__, + ) + if headers: + self.headers.update(headers) + self.ssl_verify = ssl_verify + self.space_id = None + self.httpx_kwargs = {} if httpx_kwargs is None else httpx_kwargs + self.cookies: dict[str, str] = dict( + (self.httpx_kwargs.pop("cookies", {})) or {} + ) + if isinstance(self.download_files, (str, Path)): + if not os.path.exists(self.download_files): + os.makedirs(self.download_files, exist_ok=True) + if not os.path.isdir(self.download_files): + raise ValueError(f"Path: {self.download_files} is not a directory.") + self.output_dir = str(self.download_files) + else: + self.output_dir = DEFAULT_TEMP_DIR + + if src.startswith("http://") or src.startswith("https://"): + _src = src if src.endswith("/") else src + "/" + else: + _src = self._space_name_to_src(src) + if _src is None: + raise ValueError( + f"Could not find Space: {src}. If it is a private Space, please provide an hf_token." + ) + self.space_id = src + self.src = _src + state = self._get_space_state() + if state == SpaceStage.BUILDING: + if self.verbose: + print("Space is still building. Please wait...") + while self._get_space_state() == SpaceStage.BUILDING: + time.sleep(2) # so we don't get rate limited by the API + pass + if state in utils.INVALID_RUNTIME: + raise ValueError( + f"The current space is in the invalid state: {state}. " + "Please contact the owner to fix this." + ) + if self.verbose: + print(f"Loaded as API: {self.src} ✔") + + if auth is not None: + self._login(auth) + + self.config = self._get_config() + self.protocol: Literal["ws", "sse", "sse_v1", "sse_v2", "sse_v2.1"] = ( + self.config.get("protocol", "ws") + ) + api_prefix: str = self.config.get("api_prefix", "") + self.api_prefix = api_prefix.lstrip("/") + "/" + self.src_prefixed = ( + urllib.parse.urljoin(self.src, self.api_prefix).rstrip("/") + "/" + ) + self.api_url = urllib.parse.urljoin(self.src_prefixed, utils.API_URL) + self.sse_url = urllib.parse.urljoin( + self.src_prefixed, + utils.SSE_URL_V0 if self.protocol == "sse" else utils.SSE_URL, + ) + self.heartbeat_url = urllib.parse.urljoin( + self.src_prefixed, utils.HEARTBEAT_URL + ) + self.sse_data_url = urllib.parse.urljoin( + self.src_prefixed, + utils.SSE_DATA_URL_V0 if self.protocol == "sse" else utils.SSE_DATA_URL, + ) + self.ws_url = urllib.parse.urljoin( + self.src_prefixed.replace("http", "ws", 1), utils.WS_URL + ) + self.upload_url = urllib.parse.urljoin(self.src_prefixed, utils.UPLOAD_URL) + self.reset_url = urllib.parse.urljoin(self.src_prefixed, utils.RESET_URL) + self.app_version = version.parse(self.config.get("version", "2.0")) + self._info = self._get_api_info() + self.session_hash = str(uuid.uuid4()) + + endpoint_class = ( + Endpoint if self.protocol.startswith("sse") else EndpointV3Compatibility + ) + self.endpoints = { + dependency.get("id", fn_index): endpoint_class( + self, dependency.get("id", fn_index), dependency, self.protocol + ) + for fn_index, dependency in enumerate(self.config["dependencies"]) + } + + # Create a pool of threads to handle the requests + self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) + + self.analytics_enabled = ( + analytics_enabled or os.getenv("GRADIO_ANALYTICS_ENABLED", "True") == "True" + ) + if self.analytics_enabled: + threading.Thread(target=self._telemetry_thread, daemon=True).start() + self._refresh_heartbeat = threading.Event() + self._kill_heartbeat = threading.Event() + + self.heartbeat = threading.Thread(target=self._stream_heartbeat, daemon=True) + self.heartbeat.start() + + self.stream_open = False + self.streaming_future: Future | None = None + self.pending_messages_per_event: dict[str, list[Message | None]] = {} + self.pending_event_ids: set[str] = set() + + def close(self): + self._kill_heartbeat.set() + self.heartbeat.join(timeout=1) + + def _stream_heartbeat(self): + while True: + url = self.heartbeat_url.format(session_hash=self.session_hash) + try: + httpx_kwargs = self.httpx_kwargs.copy() + httpx_kwargs.setdefault("timeout", 20) + with httpx.stream( + "GET", + url, + headers=self.headers, + cookies=self.cookies, + verify=self.ssl_verify, + **httpx_kwargs, + ) as response: + for _ in response.iter_lines(): + if self._refresh_heartbeat.is_set(): + self._refresh_heartbeat.clear() + break + if self._kill_heartbeat.is_set(): + return + except httpx.TransportError: + return + + def stream_messages( + self, protocol: Literal["sse_v1", "sse_v2", "sse_v2.1", "sse_v3"] + ) -> None: + try: + httpx_kwargs = self.httpx_kwargs.copy() + httpx_kwargs.setdefault("timeout", httpx.Timeout(timeout=None)) + with httpx.Client( + verify=self.ssl_verify, + **httpx_kwargs, + ) as client: + with client.stream( + "GET", + self.sse_url, + params={"session_hash": self.session_hash}, + headers=self.headers, + cookies=self.cookies, + ) as response: + buffer = b"" + for chunk in response.iter_bytes(): + buffer += chunk + while b"\n\n" in buffer: + line, buffer = buffer.split(b"\n\n", 1) + line = line.decode("utf-8").rstrip("\n") + if not len(line): + continue + if line.startswith("data:"): + resp = json.loads(line[5:]) + if resp["msg"] == ServerMessage.heartbeat: + continue + elif ( + resp.get("message", "") + == ServerMessage.server_stopped + ): + for ( + pending_messages + ) in self.pending_messages_per_event.values(): + pending_messages.append(resp) + return + elif resp["msg"] == ServerMessage.close_stream: + self.stream_open = False + return + event_id = resp["event_id"] + if event_id not in self.pending_messages_per_event: + self.pending_messages_per_event[event_id] = [] + self.pending_messages_per_event[event_id].append(resp) + if resp["msg"] == ServerMessage.process_completed: + self.pending_event_ids.remove(event_id) + if ( + len(self.pending_event_ids) == 0 + and protocol != "sse_v3" + ): + self.stream_open = False + return + else: + raise ValueError(f"Unexpected SSE line: '{line}'") + except BaseException as e: + # If the job is cancelled the stream will close so we + # should not raise this httpx exception that comes from the + # stream abruply closing + if isinstance(e, httpx.RemoteProtocolError): + return + import traceback + + traceback.print_exc() + raise e + + def send_data(self, data, hash_data, protocol, request_headers): + headers = self.add_zero_gpu_headers(self.headers) + if request_headers is not None: + headers = {**request_headers, **headers} + req = httpx.post( + self.sse_data_url, + json={**data, **hash_data}, + headers=headers, + cookies=self.cookies, + verify=self.ssl_verify, + **self.httpx_kwargs, + ) + if req.status_code == 503: + raise QueueError("Queue is full! Please try again.") + req.raise_for_status() + resp = req.json() + event_id = resp["event_id"] + + if not self.stream_open: + self.stream_open = True + + def open_stream(): + return self.stream_messages(protocol) + + def close_stream(_): + self.stream_open = False + for _, pending_messages in self.pending_messages_per_event.items(): + pending_messages.append(None) + + if self.streaming_future is None or self.streaming_future.done(): + self.streaming_future = self.executor.submit(open_stream) + self.streaming_future.add_done_callback(close_stream) + + return event_id + + @classmethod + def duplicate( + cls, + from_id: str, + to_id: str | None = None, + hf_token: str | Literal[False] | None = False, + private: bool = True, + hardware: Literal[ + "cpu-basic", + "cpu-upgrade", + "t4-small", + "t4-medium", + "a10g-small", + "a10g-large", + "a100-large", + ] + | SpaceHardware + | None = None, + secrets: dict[str, str] | None = None, + sleep_timeout: int = 5, + max_workers: int = 40, + verbose: bool = True, + ): + """ + Duplicates a Hugging Face Space under your account and returns a Client object + for the new Space. No duplication is created if the Space already exists in your + account (to override this, provide a new name for the new Space using `to_id`). + To use this method, you must provide an `hf_token` or be logged in via the Hugging + Face Hub CLI. + + The new Space will be private by default and use the same hardware as the original + Space. This can be changed by using the `private` and `hardware` parameters. For + hardware upgrades (beyond the basic CPU tier), you may be required to provide + billing information on Hugging Face: https://huggingface.co/settings/billing + + Parameters: + from_id: The name of the Hugging Face Space to duplicate in the format "{username}/{space_id}", e.g. "gradio/whisper". + to_id: The name of the new Hugging Face Space to create, e.g. "abidlabs/whisper-duplicate". If not provided, the new Space will be named "{your_HF_username}/{space_id}". + hf_token: optional Hugging Face token to use to duplicating private Spaces. By default, no token is sent to the server. Set `hf_token=None` to use the locally saved token if there is one. Find your tokens here: https://huggingface.co/settings/tokens. + private: Whether the new Space should be private (True) or public (False). Defaults to True. + hardware: The hardware tier to use for the new Space. Defaults to the same hardware tier as the original Space. Options include "cpu-basic", "cpu-upgrade", "t4-small", "t4-medium", "a10g-small", "a10g-large", "a100-large", subject to availability. + secrets: A dictionary of (secret key, secret value) to pass to the new Space. Defaults to None. Secrets are only used when the Space is duplicated for the first time, and are not updated if the duplicated Space already exists. + sleep_timeout: The number of minutes after which the duplicate Space will be puased if no requests are made to it (to minimize billing charges). Defaults to 5 minutes. + max_workers: The maximum number of thread workers that can be used to make requests to the remote Gradio app simultaneously. + verbose: Whether the client should print statements to the console. + Example: + import os + from gradio_client import Client + HF_TOKEN = os.environ.get("HF_TOKEN") + client = Client.duplicate("abidlabs/whisper", hf_token=HF_TOKEN) + client.predict("audio_sample.wav") + >> "This is a test of the whisper speech recognition model." + """ + try: + original_info = huggingface_hub.get_space_runtime(from_id, token=hf_token) + except RepositoryNotFoundError as rnfe: + raise ValueError( + f"Could not find Space: {from_id}. If it is a private Space, please provide an `hf_token`." + ) from rnfe + if to_id: + if "/" in to_id: + to_id = to_id.split("/")[1] + space_id = huggingface_hub.get_full_repo_name(to_id, token=hf_token) + else: + space_id = huggingface_hub.get_full_repo_name( + from_id.split("/")[1], token=hf_token + ) + try: + huggingface_hub.get_space_runtime(space_id, token=hf_token) + if verbose: + print( + f"Using your existing Space: {utils.SPACE_URL.format(space_id)} 🤗" + ) + if secrets is not None: + warnings.warn( + "Secrets are only used when the Space is duplicated for the first time, and are not updated if the duplicated Space already exists." + ) + except RepositoryNotFoundError: + if verbose: + print(f"Creating a duplicate of {from_id} for your own use... 🤗") + huggingface_hub.duplicate_space( + from_id=from_id, + to_id=space_id, + token=hf_token, + exist_ok=True, + private=private, + ) + if secrets is not None: + for key, value in secrets.items(): + huggingface_hub.add_space_secret( + space_id, key, value, token=hf_token + ) + if verbose: + print(f"Created new Space: {utils.SPACE_URL.format(space_id)}") + current_info = huggingface_hub.get_space_runtime(space_id, token=hf_token) + current_hardware = ( + current_info.hardware or huggingface_hub.SpaceHardware.CPU_BASIC + ) + hardware = hardware or original_info.hardware + if current_hardware != hardware: + huggingface_hub.request_space_hardware(space_id, hardware, token=hf_token) # type: ignore + print( + f"-------\nNOTE: this Space uses upgraded hardware: {hardware}... see billing info at https://huggingface.co/settings/billing\n-------" + ) + # Setting a timeout only works if the hardware is not basic + # so set it here after the hardware has been requested + if hardware != huggingface_hub.SpaceHardware.CPU_BASIC: + utils.set_space_timeout( + space_id, hf_token=hf_token, timeout_in_seconds=sleep_timeout * 60 + ) + if verbose: + print("") + client = cls( + space_id, hf_token=hf_token, max_workers=max_workers, verbose=verbose + ) + return client + + def _get_space_state(self): + if not self.space_id: + return None + info = huggingface_hub.get_space_runtime(self.space_id, token=self.hf_token) + return info.stage + + def predict( + self, + *args, + api_name: str | None = None, + fn_index: int | None = None, + headers: dict[str, str] | None = None, + **kwargs, + ) -> Any: + """ + Calls the Gradio API and returns the result (this is a blocking call). Arguments can be provided as positional arguments or as keyword arguments (latter is recommended). + + Parameters: + args: The positional arguments to pass to the remote API endpoint. The order of the arguments must match the order of the inputs in the Gradio app. + api_name: The name of the API endpoint to call starting with a leading slash, e.g. "/predict". Does not need to be provided if the Gradio app has only one named API endpoint. + fn_index: As an alternative to api_name, this parameter takes the index of the API endpoint to call, e.g. 0. Both api_name and fn_index can be provided, but if they conflict, api_name will take precedence. + kwargs: The keyword arguments to pass to the remote API endpoint. + headers: Additional headers to send to the remote Gradio app on this request. This parameter will overrides the headers provided in the Client constructor if they have the same keys. + Returns: + The result of the API call. Will be a Tuple if the API has multiple outputs. + Example: + from gradio_client import Client + client = Client(src="gradio/calculator") + client.predict(5, "add", 4, api_name="/predict") + >> 9.0 + """ + self._infer_fn_index(api_name, fn_index) + return self.submit( + *args, api_name=api_name, fn_index=fn_index, headers=headers, **kwargs + ).result() + + def new_helper( + self, fn_index: int, headers: dict[str, str] | None = None + ) -> Communicator: + return Communicator( + Lock(), + JobStatus(), + self.endpoints[fn_index].process_predictions, + self.reset_url, + request_headers=headers, + ) + + def submit( + self, + *args, + api_name: str | None = None, + fn_index: int | None = None, + headers: dict[str, str] | None = None, + result_callbacks: Callable | list[Callable] | None = None, + **kwargs, + ) -> Job: + """ + Creates and returns a Job object which calls the Gradio API in a background thread. The job can be used to retrieve the status and result of the remote API call. + Arguments can be provided as positional arguments or as keyword arguments (latter is recommended). + + Parameters: + args: The arguments to pass to the remote API. The order of the arguments must match the order of the inputs in the Gradio app. + api_name: The name of the API endpoint to call starting with a leading slash, e.g. "/predict". Does not need to be provided if the Gradio app has only one named API endpoint. + fn_index: As an alternative to api_name, this parameter takes the index of the API endpoint to call, e.g. 0. Both api_name and fn_index can be provided, but if they conflict, api_name will take precedence. + result_callbacks: A callback function, or list of callback functions, to be called when the result is ready. If a list of functions is provided, they will be called in order. The return values from the remote API are provided as separate parameters into the callback. If None, no callback will be called. + kwargs: The keyword arguments to pass to the remote API endpoint. + headers: Additional headers to send to the remote Gradio app on this request. This parameter will overrides the headers provided in the Client constructor if they have the same keys. + Returns: + A Job object that can be used to retrieve the status and result of the remote API call. + Example: + from gradio_client import Client + client = Client(src="gradio/calculator") + job = client.submit(5, "add", 4, api_name="/predict") + job.status() + >> + job.result() # blocking call + >> 9.0 + """ + inferred_fn_index = self._infer_fn_index(api_name, fn_index) + + endpoint = self.endpoints[inferred_fn_index] + + if isinstance(endpoint, Endpoint): + args = utils.construct_args(endpoint.parameters_info, args, kwargs) + + helper = None + if endpoint.protocol in ( + "ws", + "sse", + "sse_v1", + "sse_v2", + "sse_v2.1", + "sse_v3", + ): + helper = self.new_helper(inferred_fn_index, headers=headers) + end_to_end_fn = endpoint.make_end_to_end_fn(helper) + else: + end_to_end_fn = cast(EndpointV3Compatibility, endpoint).make_end_to_end_fn( + None + ) + future = self.executor.submit(end_to_end_fn, *args) + + cancel_fn = endpoint.make_cancel(helper) + + job = Job( + future, + communicator=helper, + verbose=self.verbose, + space_id=self.space_id, + _cancel_fn=cancel_fn, + ) + + if result_callbacks: + if isinstance(result_callbacks, Callable): + result_callbacks = [result_callbacks] + + def create_fn(callback) -> Callable: + def fn(future): + if isinstance(future.result(), tuple): + callback(*future.result()) + else: + callback(future.result()) + + return fn + + for callback in result_callbacks: + job.add_done_callback(create_fn(callback)) + + return job + + def _get_api_info(self): + api_info_url = urllib.parse.urljoin(self.src_prefixed, utils.RAW_API_INFO_URL) + if self.app_version > version.Version("3.36.1"): + r = httpx.get( + api_info_url, + headers=self.headers, + cookies=self.cookies, + verify=self.ssl_verify, + **self.httpx_kwargs, + ) + if r.is_success: + info = r.json() + else: + raise ValueError(f"Could not fetch api info for {self.src}: {r.text}") + else: + fetch = httpx.post( + utils.SPACE_FETCHER_URL, + json={ + "config": json.dumps(self.config), + "serialize": False, + }, + headers=self.headers, + cookies=self.cookies, + verify=self.ssl_verify, + **self.httpx_kwargs, + ) + if fetch.is_success: + info = fetch.json()["api"] + else: + raise ValueError( + f"Could not fetch api info for {self.src}: {fetch.text}" + ) + info["named_endpoints"] = { + a: e for a, e in info["named_endpoints"].items() if e.pop("show_api", True) + } + info["unnamed_endpoints"] = { + a: e + for a, e in info["unnamed_endpoints"].items() + if e.pop("show_api", True) + } + return info + + def view_api( + self, + all_endpoints: bool | None = None, + print_info: bool = True, + return_format: Literal["dict", "str"] | None = None, + ) -> dict | str | None: + """ + Prints the usage info for the API. If the Gradio app has multiple API endpoints, the usage info for each endpoint will be printed separately. If return_format="dict" the info is returned in dictionary format, as shown in the example below. + + Parameters: + all_endpoints: If True, prints information for both named and unnamed endpoints in the Gradio app. If False, will only print info about named endpoints. If None (default), will print info about named endpoints, unless there aren't any -- in which it will print info about unnamed endpoints. + print_info: If True, prints the usage info to the console. If False, does not print the usage info. + return_format: If None, nothing is returned. If "str", returns the same string that would be printed to the console. If "dict", returns the usage info as a dictionary that can be programmatically parsed, and *all endpoints are returned in the dictionary* regardless of the value of `all_endpoints`. The format of the dictionary is in the docstring of this method. + Example: + from gradio_client import Client + client = Client(src="gradio/calculator") + client.view_api(return_format="dict") + >> { + 'named_endpoints': { + '/predict': { + 'parameters': [ + { + 'label': 'num1', + 'python_type': 'int | float', + 'type_description': 'numeric value', + 'component': 'Number', + 'example_input': '5' + }, + { + 'label': 'operation', + 'python_type': 'str', + 'type_description': 'string value', + 'component': 'Radio', + 'example_input': 'add' + }, + { + 'label': 'num2', + 'python_type': 'int | float', + 'type_description': 'numeric value', + 'component': 'Number', + 'example_input': '5' + }, + ], + 'returns': [ + { + 'label': 'output', + 'python_type': 'int | float', + 'type_description': 'numeric value', + 'component': 'Number', + }, + ] + }, + '/flag': { + 'parameters': [ + ... + ], + 'returns': [ + ... + ] + } + } + } + 'unnamed_endpoints': { + 2: { + 'parameters': [ + ... + ], + 'returns': [ + ... + ] + } + } + } + } + + """ + num_named_endpoints = len(self._info["named_endpoints"]) + num_unnamed_endpoints = len(self._info["unnamed_endpoints"]) + if num_named_endpoints == 0 and all_endpoints is None: + all_endpoints = True + + human_info = "Client.predict() Usage Info\n---------------------------\n" + human_info += f"Named API endpoints: {num_named_endpoints}\n" + + for api_name, endpoint_info in self._info["named_endpoints"].items(): + human_info += self._render_endpoints_info(api_name, endpoint_info) + + if all_endpoints: + human_info += f"\nUnnamed API endpoints: {num_unnamed_endpoints}\n" + for fn_index, endpoint_info in self._info["unnamed_endpoints"].items(): + # When loading from json, the fn_indices are read as strings + # because json keys can only be strings + human_info += self._render_endpoints_info(int(fn_index), endpoint_info) + elif num_unnamed_endpoints > 0: + human_info += f"\nUnnamed API endpoints: {num_unnamed_endpoints}, to view, run Client.view_api(all_endpoints=True)\n" + + if print_info: + print(human_info) + if return_format == "str": + return human_info + elif return_format == "dict": + return self._info + + def reset_session(self) -> None: + self.session_hash = str(uuid.uuid4()) + self._refresh_heartbeat.set() + + def add_zero_gpu_headers(self, headers: dict[str, str]) -> dict[str, str]: + """ + Adds the x-ip-token header to the headers dictionary to pass it to a Zero-GPU Space. This allows a user's + ZeroGPU quota to be tracked and used by the underlying Space. For the x-ip-token header to be present, + this method needs to be called when a Gradio app's LocalContext is defined. i.e. this method + cannot be called when the Gradio Client is instantiated, but must be called from inside a Gradio app's + prediction function. + """ + if not self.space_id: + return headers + try: + from gradio.context import LocalContext + except ( + ImportError + ): # this is not running within a Gradio app as Gradio is not installed + return headers + request = LocalContext.request.get() + if request and hasattr(request, "headers") and "x-ip-token" in request.headers: + headers["x-ip-token"] = request.headers["x-ip-token"] + return headers + + def _render_endpoints_info( + self, + name_or_index: str | int, + endpoints_info: dict[str, list[ParameterInfo]], + ) -> str: + parameter_info = endpoints_info["parameters"] + parameter_names = [ + p.get("parameter_name") or p["label"] for p in parameter_info + ] + parameter_names = [utils.sanitize_parameter_names(p) for p in parameter_names] + rendered_parameters = ", ".join(parameter_names) + if rendered_parameters: + rendered_parameters = rendered_parameters + ", " + return_values = [p["label"] for p in endpoints_info["returns"]] + return_values = [utils.sanitize_parameter_names(r) for r in return_values] + rendered_return_values = ", ".join(return_values) + if len(return_values) > 1: + rendered_return_values = f"({rendered_return_values})" + + if isinstance(name_or_index, str): + final_param = f'api_name="{name_or_index}"' + elif isinstance(name_or_index, int): + final_param = f"fn_index={name_or_index}" + else: + raise ValueError("name_or_index must be a string or integer") + + human_info = f"\n - predict({rendered_parameters}{final_param}) -> {rendered_return_values}\n" + human_info += " Parameters:\n" + if parameter_info: + for info in parameter_info: + desc = ( + f" ({info['python_type']['description']})" + if info["python_type"].get("description") + else "" + ) + default_value = info.get("parameter_default") + default_value = utils.traverse( + default_value, + lambda x: f'handle_file("{x["url"]}")', + utils.is_file_obj_with_meta, + ) + default_info = ( + "(required)" + if not info.get("parameter_has_default", False) + else f"(not required, defaults to: {default_value})" + ) + type_ = info["python_type"]["type"] + if info.get("parameter_has_default", False) and default_value is None: + type_ += " | None" + human_info += f" - [{info['component']}] {utils.sanitize_parameter_names(info.get('parameter_name') or info['label'])}: {type_} {default_info} {desc} \n" + else: + human_info += " - None\n" + human_info += " Returns:\n" + if endpoints_info["returns"]: + for info in endpoints_info["returns"]: + desc = ( + f" ({info['python_type']['description']})" + if info["python_type"].get("description") + else "" + ) + type_ = info["python_type"]["type"] + human_info += f" - [{info['component']}] {utils.sanitize_parameter_names(info['label'])}: {type_}{desc} \n" + else: + human_info += " - None\n" + + return human_info + + def __repr__(self): + return self.view_api(print_info=False, return_format="str") + + def __str__(self): + return self.view_api(print_info=False, return_format="str") + + def _telemetry_thread(self) -> None: + # Disable telemetry by setting the env variable HF_HUB_DISABLE_TELEMETRY=1 + data = { + "src": self.src, + } + try: + send_telemetry( + topic="py_client/initiated", + library_name="gradio_client", + library_version=utils.__version__, + user_agent=data, + ) + except Exception: + pass + + def _infer_fn_index(self, api_name: str | None, fn_index: int | None) -> int: + inferred_fn_index = None + if api_name is not None: + for i, d in enumerate(self.config["dependencies"]): + config_api_name = d.get("api_name") + if config_api_name is None or config_api_name is False: + continue + if "/" + config_api_name == api_name: + inferred_fn_index = d.get("id", i) + break + else: + error_message = f"Cannot find a function with `api_name`: {api_name}." + if not api_name.startswith("/"): + error_message += " Did you mean to use a leading slash?" + raise ValueError(error_message) + elif fn_index is not None: + inferred_fn_index = fn_index + if ( + inferred_fn_index not in self.endpoints + or not self.endpoints[inferred_fn_index].is_valid + ): + raise ValueError(f"Invalid function index: {fn_index}.") + else: + valid_endpoints = [ + e + for e in self.endpoints.values() + if e.is_valid + and e.api_name is not None + and e.backend_fn is not None + and e.show_api + ] + if len(valid_endpoints) == 1: + inferred_fn_index = valid_endpoints[0].fn_index + else: + raise ValueError( + "This Gradio app might have multiple endpoints. Please specify an `api_name` or `fn_index`" + ) + return inferred_fn_index + + def __del__(self): + if hasattr(self, "executor"): + self.executor.shutdown(wait=True) + + def _space_name_to_src(self, space) -> str | None: + return huggingface_hub.space_info(space, token=self.hf_token).host # type: ignore + + def _login(self, auth: tuple[str, str]): + """ + Logs in to `utils.LOGIN_URL` using provided `auth` credentials. + Warning: This method overwrites `self.cookies`. + """ + resp = httpx.post( + urllib.parse.urljoin(self.src, utils.LOGIN_URL), + data={"username": auth[0], "password": auth[1]}, + verify=self.ssl_verify, + **self.httpx_kwargs, + ) + if not resp.is_success: + if resp.status_code == 401: + raise AuthenticationError( + f"Could not login to {self.src}. Invalid credentials." + ) + else: + raise ValueError(f"Could not login to {self.src}.") + self.cookies = { + name: value for name, value in resp.cookies.items() if value is not None + } + + def _get_config(self) -> dict: + r = httpx.get( + urllib.parse.urljoin(self.src, utils.CONFIG_URL), + headers=self.headers, + cookies=self.cookies, + verify=self.ssl_verify, + **self.httpx_kwargs, + ) + if r.is_success: + # Cookies are sometimes needed to correctly route requests if the Gradio app is + # running on multiple replicas e.g. using cookie session-affinity in Kubernetes. + # This approach attaches cookies from the first response to subsequent requests + # without overriding existing cookies. + new_cookies = { + name: value + for name, value in r.cookies.items() + if value is not None and name not in self.cookies + } + self.cookies.update(new_cookies) + return r.json() + elif r.status_code == 401: + raise AuthenticationError( + f"Could not load {self.src} as credentials were not provided. Please login." + ) + elif r.status_code == 429: + raise utils.TooManyRequestsError( + "Too many requests to the API, please try again later." + ) from None + else: # to support older versions of Gradio + r = httpx.get( + self.src, + headers=self.headers, + cookies=self.cookies, + verify=self.ssl_verify, + **self.httpx_kwargs, + ) + if not r.is_success: + raise ValueError(f"Could not fetch config for {self.src}") + # some basic regex to extract the config + result = re.search(r"window.gradio_config = (.*?);[\s]*", r.text) + try: + config = json.loads(result.group(1)) # type: ignore + except AttributeError as ae: + raise ValueError( + f"Could not get Gradio config from: {self.src}" + ) from ae + if "allow_flagging" in config: + raise ValueError( + "Gradio 2.x is not supported by this client. Please upgrade your Gradio app to Gradio 3.x or higher." + ) + return config + + def deploy_discord( + self, + discord_bot_token: str | None = None, + api_names: list[str | tuple[str, str]] | None = None, + to_id: str | None = None, + hf_token: str | Literal[False] | None = False, + private: bool = False, + ): + """ + Deploy the upstream app as a discord bot. Currently only supports gr.ChatInterface. + Parameters: + discord_bot_token: This is the "password" needed to be able to launch the bot. Users can get a token by creating a bot app on the discord website. If run the method without specifying a token, the space will explain how to get one. See here: https://huggingface.co/spaces/freddyaboulton/test-discord-bot-v1. + api_names: The api_names of the app to turn into bot commands. This parameter currently has no effect as ChatInterface only has one api_name ('/chat'). + to_id: The name of the space hosting the discord bot. If None, the name will be gradio-discord-bot-{random-substring} + hf_token: HF api token with write priviledges in order to upload the files to HF space. Can be ommitted if logged in via the HuggingFace CLI, unless the upstream space is private. Obtain from: https://huggingface.co/settings/token + private: Whether the space hosting the discord bot is private. The visibility of the discord bot itself is set via the discord website. See https://huggingface.co/spaces/freddyaboulton/test-discord-bot-v1 + """ + warnings.warn( + "This method is deprecated and may be removed in the future. Please see the documentation on how to create a discord bot with Gradio: https://www.gradio.app/guides/creating-a-discord-bot-from-a-gradio-app" + ) + if self.config["mode"] == "chat_interface" and not api_names: + api_names = [("chat", "chat")] + + valid_list = isinstance(api_names, list) and ( + isinstance(n, str) + or ( + isinstance(n, tuple) and isinstance(n[0], str) and isinstance(n[1], str) + ) + for n in api_names + ) + if api_names is None or not valid_list: + raise ValueError( + f"Each entry in api_names must be either a string or a tuple of strings. Received {api_names}" + ) + if len(api_names) != 1: + raise ValueError("Currently only one api_name can be deployed to discord.") + + for i, name in enumerate(api_names): + if isinstance(name, str): + api_names[i] = (name, name) + + fn = next( + ( + ep + for ep in self.endpoints.values() + if ep.api_name == f"/{api_names[0][0]}" + ), + None, + ) + if not fn: + raise ValueError( + f"api_name {api_names[0][0]} not present in {self.space_id or self.src}" + ) + inputs = [inp for inp in fn.input_component_types if not inp.skip] + outputs = [inp for inp in fn.input_component_types if not inp.skip] + if not inputs == ["textbox"] and outputs == ["textbox"]: + raise ValueError( + "Currently only api_names with a single textbox as input and output are supported. " + f"Received {inputs} and {outputs}" + ) + + is_private = False + if self.space_id: + is_private = huggingface_hub.space_info(self.space_id).private + if is_private and not hf_token: + raise ValueError( + f"Since {self.space_id} is private, you must explicitly pass in hf_token " + "so that it can be added as a secret in the discord bot space." + ) + + if to_id: + if "/" in to_id: + to_id = to_id.split("/")[1] + space_id = huggingface_hub.get_full_repo_name(to_id, token=hf_token) + else: + if self.space_id: + space_id = f"{self.space_id.split('/')[1]}-gradio-discord-bot" + else: + space_id = f"gradio-discord-bot-{secrets.token_hex(4)}" + space_id = huggingface_hub.get_full_repo_name(space_id, token=hf_token) + + api = huggingface_hub.HfApi() + + try: + huggingface_hub.space_info(space_id) + first_upload = False + except huggingface_hub.utils.RepositoryNotFoundError: + first_upload = True + + huggingface_hub.create_repo( + space_id, + repo_type="space", + space_sdk="gradio", + token=hf_token, + exist_ok=True, + private=private, + ) + if first_upload: + huggingface_hub.metadata_update( + repo_id=space_id, + repo_type="space", + metadata={"tags": ["gradio-discord-bot"]}, + ) + + with open( + str(Path(__file__).parent / "templates" / "discord_chat.py"), + encoding="utf-8", + ) as f: + app = f.read() + app = app.replace("<>", self.src) + app = app.replace("<>", api_names[0][0]) + app = app.replace("<>", api_names[0][1]) + + with tempfile.NamedTemporaryFile( + mode="w", delete=False, encoding="utf-8" + ) as app_file: + with tempfile.NamedTemporaryFile(mode="w", delete=False) as requirements: + app_file.write(app) + requirements.write("\n".join(["discord.py==2.3.1"])) + + operations = [ + CommitOperationAdd(path_in_repo="app.py", path_or_fileobj=app_file.name), + CommitOperationAdd( + path_in_repo="requirements.txt", path_or_fileobj=requirements.name + ), + ] + + api.create_commit( + repo_id=space_id, + commit_message="Deploy Discord Bot", + repo_type="space", + operations=operations, + token=hf_token, + ) + + if discord_bot_token: + huggingface_hub.add_space_secret( + space_id, "DISCORD_TOKEN", discord_bot_token, token=hf_token + ) + if is_private: + huggingface_hub.add_space_secret( + space_id, + "HF_TOKEN", + hf_token, # type: ignore + token=hf_token, + ) + + url = f"https://huggingface.co/spaces/{space_id}" + print(f"See your discord bot here! {url}") + return url + + +@dataclass +class ComponentApiType: + skip: bool + value_is_file: bool + is_state: bool + + +@dataclass +class ReplaceMe: + index: int + + +class Endpoint: + """Helper class for storing all the information about a single API endpoint.""" + + def __init__( + self, client: Client, fn_index: int, dependency: dict, protocol: str = "sse_v1" + ): + self.client: Client = client + self.fn_index = fn_index + self.dependency = dependency + api_name = dependency.get("api_name") + self.api_name: str | Literal[False] | None = ( + "/" + api_name if isinstance(api_name, str) else api_name + ) + self._info = self.client._info + self.protocol = protocol + self.input_component_types = [ + self._get_component_type(id_) for id_ in dependency["inputs"] + ] + self.output_component_types = [ + self._get_component_type(id_) for id_ in dependency["outputs"] + ] + self.parameters_info = self._get_parameters_info() + self.root_url = self.client.src_prefixed + + # Disallow hitting endpoints that the Gradio app has disabled + self.is_valid = self.api_name is not False + self.backend_fn = dependency.get("backend_fn") + self.show_api = dependency.get("show_api") + + def _get_component_type(self, component_id: int): + component = next( + i for i in self.client.config["components"] if i["id"] == component_id + ) + skip_api = component.get("skip_api", component["type"] in utils.SKIP_COMPONENTS) + return ComponentApiType( + skip_api, + self.value_is_file(component), + component["type"] == "state", + ) + + def _get_parameters_info(self) -> list[ParameterInfo] | None: + if self.api_name in self._info["named_endpoints"]: + return self._info["named_endpoints"][self.api_name]["parameters"] + return None + + @staticmethod + def value_is_file(component: dict) -> bool: + # This is still hacky as it does not tell us which part of the payload is a file. + # If a component has a complex payload, part of which is a file, this will simply + # return True, which means that all parts of the payload will be uploaded as files + # if they are valid file paths. We will deprecate this 1.0. + if "api_info" not in component: + return False + return utils.value_is_file(component["api_info"]) + + def __repr__(self): + return f"Endpoint src: {self.client.src}, api_name: {self.api_name}, fn_index: {self.fn_index}" + + def __str__(self): + return self.__repr__() + + def make_end_to_end_fn(self, helper: Communicator): + _predict = self.make_predict(helper) + + def _inner(*data): + if not self.is_valid: + raise utils.InvalidAPIEndpointError() + + if self.client._skip_components: + data = self.insert_empty_state(*data) + data = self.process_input_files(*data) + predictions = _predict(*data) + predictions = self.process_predictions(*predictions) + + # Append final output only if not already present + # for consistency between generators and not generators + if helper: + with helper.lock: + if not helper.job.outputs: + helper.job.outputs.append(predictions) + return predictions + + return _inner + + def make_cancel( + self, + helper: Communicator | None, + ): + if helper is None: + return + if self.client.app_version > version.Version("4.29.0"): + url = urllib.parse.urljoin(self.client.src_prefixed, utils.CANCEL_URL) + + # The event_id won't be set on the helper until later + # so need to create the data in a function that's run at cancel time + def post_data(): + return { + "fn_index": self.fn_index, + "session_hash": self.client.session_hash, + "event_id": helper.event_id, + } + + cancel_msg = None + cancellable = True + else: + candidates: list[tuple[int, list[int]]] = [] + for i, dep in enumerate(self.client.config["dependencies"]): + if self.fn_index in dep["cancels"]: + candidates.append( + (i, [d for d in dep["cancels"] if d != self.fn_index]) + ) + + fn_index, other_cancelled = ( + min(candidates, key=lambda x: len(x[1])) if candidates else (None, None) + ) + cancellable = fn_index is not None + cancel_msg = None + if cancellable and other_cancelled: + other_api_names = [ + "/" + self.client.config["dependencies"][i].get("api_name") + for i in other_cancelled + ] + cancel_msg = ( + f"Cancelled this job will also cancel any jobs for {', '.join(other_api_names)} " + "that are currently running." + ) + elif not cancellable: + cancel_msg = ( + "Cancelling this job will not stop the server from running. " + "To fix this, an event must be added to the upstream app that explicitly cancels this one or " + "the upstream app must be running Gradio 4.29.0 and greater." + ) + + def post_data(): + return { + "data": [], + "fn_index": fn_index, + "session_hash": self.client.session_hash, + } + + url = self.client.api_url + + def _cancel(): + if cancel_msg: + warnings.warn(cancel_msg) + if cancellable: + httpx.post( + url, + json=post_data(), + headers=self.client.headers, + cookies=self.client.cookies, + verify=self.client.ssl_verify, + **self.client.httpx_kwargs, + ) + + return _cancel + + def make_predict(self, helper: Communicator): + def _predict(*data) -> tuple: + data = { + "data": data, + "fn_index": self.fn_index, + "session_hash": self.client.session_hash, + } + + hash_data = { + "fn_index": self.fn_index, + "session_hash": self.client.session_hash, + } + + if self.protocol == "sse": + result = self._sse_fn_v0(data, hash_data, helper) # type: ignore + elif self.protocol in ("sse_v1", "sse_v2", "sse_v2.1", "sse_v3"): + event_id = self.client.send_data( + data, hash_data, self.protocol, helper.request_headers + ) + self.client.pending_event_ids.add(event_id) + self.client.pending_messages_per_event[event_id] = [] + helper.event_id = event_id + result = self._sse_fn_v1plus(helper, event_id, self.protocol) + else: + raise ValueError(f"Unsupported protocol: {self.protocol}") + + if "error" in result: + if result["error"] is None: + raise AppError( + "The upstream Gradio app has raised an exception but has not enabled " + "verbose error reporting. To enable, set show_error=True in launch()." + ) + else: + message = result.pop("error") + raise AppError(message=message, **result) + + try: + output = result["data"] + except KeyError as ke: + is_public_space = ( + self.client.space_id + and not huggingface_hub.space_info(self.client.space_id).private + ) + if "error" in result and "429" in result["error"] and is_public_space: + raise utils.TooManyRequestsError( + f"Too many requests to the API, please try again later. To avoid being rate-limited, " + f"please duplicate the Space using Client.duplicate({self.client.space_id}) " + f"and pass in your Hugging Face token." + ) from None + elif "error" in result: + raise ValueError(result["error"]) from None + raise KeyError( + f"Could not find 'data' key in response. Response received: {result}" + ) from ke + return tuple(output) + + return _predict + + def insert_empty_state(self, *data) -> tuple: + data = list(data) + for i, input_component_type in enumerate(self.input_component_types): + if input_component_type.is_state: + data.insert(i, None) + return tuple(data) + + def process_input_files(self, *data) -> tuple: + data_ = [] + for i, d in enumerate(data): + d = utils.traverse( + d, + partial(self._upload_file, data_index=i), + utils.is_file_obj_with_meta, + ) + data_.append(d) + return tuple(data_) + + def process_predictions(self, *predictions): + # If self.download_file is True, we assume that that the user is using the Client directly (as opposed + # within gr.load) and therefore, download any files generated by the server and skip values for + # components that the user likely does not want to see (e.g. gr.State, gr.Tab). + if self.client.download_files: + predictions = self.download_files(*predictions) + if self.client._skip_components: + predictions = self.remove_skipped_components(*predictions) + predictions = self.reduce_singleton_output(*predictions) + return predictions + + def download_files(self, *data) -> tuple: + data_ = list(data) + if self.client.protocol == "sse_v2.1": + data_ = utils.traverse( + data_, self._download_file, utils.is_file_obj_with_meta + ) + else: + data_ = utils.traverse(data_, self._download_file, utils.is_file_obj) + return tuple(data_) + + def remove_skipped_components(self, *data) -> tuple: + """""" + data = [ + d + for d, oct in zip(data, self.output_component_types, strict=False) + if not oct.skip + ] + return tuple(data) + + def reduce_singleton_output(self, *data) -> Any: + if self.client._skip_components: + effective_output_components = [ + o for o in self.output_component_types if not o.skip + ] + else: + effective_output_components = self.output_component_types + if len(effective_output_components) == 1: + return data[0] + else: + return data + + def _upload_file(self, f: dict, data_index: int) -> dict[str, str]: + file_path = f["path"] + orig_name = Path(file_path) + if not utils.is_http_url_like(file_path): + component_id = self.dependency["inputs"][data_index] + component_config = next( + ( + c + for c in self.client.config["components"] + if c["id"] == component_id + ), + {}, + ) + max_file_size = self.client.config.get("max_file_size", None) + max_file_size = math.inf if max_file_size is None else max_file_size + if os.path.getsize(file_path) > max_file_size: + raise ValueError( + f"File {file_path} exceeds the maximum file size of {max_file_size} bytes " + f"set in {component_config.get('label', '') + ''} component." + ) + with open(file_path, "rb") as f_: + files = [("files", (orig_name.name, f_))] + r = httpx.post( + self.client.upload_url, + headers=self.client.headers, + cookies=self.client.cookies, + verify=self.client.ssl_verify, + files=files, + **self.client.httpx_kwargs, + ) + r.raise_for_status() + result = r.json() + file_path = result[0] + # Only return orig_name if has a suffix because components + # use the suffix of the original name to determine format to save it to in cache. + return { + "path": file_path, + "orig_name": utils.strip_invalid_filename_characters(orig_name.name), + "meta": {"_type": "gradio.FileData"}, + } + + def _download_file(self, x: dict) -> str: + url_path = self.root_url + "file=" + x["path"] + if self.client.output_dir is not None: + os.makedirs(self.client.output_dir, exist_ok=True) + + sha = hashlib.sha256() + temp_dir = Path(tempfile.gettempdir()) / secrets.token_hex(20) + temp_dir.mkdir(exist_ok=True, parents=True) + + with httpx.stream( + "GET", + url_path, + headers=self.client.headers, + cookies=self.client.cookies, + verify=self.client.ssl_verify, + follow_redirects=True, + **self.client.httpx_kwargs, + ) as response: + response.raise_for_status() + with open(temp_dir / Path(url_path).name, "wb") as f: + for chunk in response.iter_bytes(chunk_size=128 * sha.block_size): + sha.update(chunk) + f.write(chunk) + + directory = Path(self.client.output_dir) / sha.hexdigest() + directory.mkdir(exist_ok=True, parents=True) + dest = directory / Path(url_path).name + shutil.move(temp_dir / Path(url_path).name, dest) + return str(dest.resolve()) + + def _sse_fn_v0(self, data: dict, hash_data: dict, helper: Communicator): + with httpx.Client( + timeout=httpx.Timeout(timeout=None), + verify=self.client.ssl_verify, + **self.client.httpx_kwargs, + ) as client: + return utils.get_pred_from_sse_v0( + client, + data, + hash_data, + helper, + self.client.sse_url, + self.client.sse_data_url, + self.client.headers, + self.client.cookies, + self.client.ssl_verify, + self.client.executor, + ) + + def _sse_fn_v1plus( + self, + helper: Communicator, + event_id: str, + protocol: Literal["sse_v1", "sse_v2", "sse_v2.1", "sse_v3"], + ): + return utils.get_pred_from_sse_v1plus( + helper, + self.client.headers, + self.client.cookies, + self.client.pending_messages_per_event, + event_id, + protocol, + self.client.ssl_verify, + self.client.executor, + ) + + +@document("result", "outputs", "status") +class Job(Future): + """ + A Job is a wrapper over the Future class that represents a prediction call that has been + submitted by the Gradio client. This class is not meant to be instantiated directly, but rather + is created by the Client.submit() method. + + A Job object includes methods to get the status of the prediction call, as well to get the outputs + of the prediction call. Job objects are also iterable, and can be used in a loop to get the outputs + of prediction calls as they become available for generator endpoints. + """ + + def __init__( + self, + future: Future, + communicator: Communicator | None = None, + verbose: bool = True, + space_id: str | None = None, + _cancel_fn: Callable[[], None] | None = None, + ): + """ + Parameters: + future: The future object that represents the prediction call, created by the Client.submit() method + communicator: The communicator object that is used to communicate between the client and the background thread running the job + verbose: Whether to print any status-related messages to the console + space_id: The space ID corresponding to the Client object that created this Job object + """ + self.future = future + self.communicator = communicator + self._counter = 0 + self.verbose = verbose + self.space_id = space_id + self.cancel_fn = _cancel_fn + + def __iter__(self) -> Job: + return self + + def __next__(self) -> tuple | Any: + if not self.communicator: + raise StopIteration() + + while True: + with self.communicator.lock: + if len(self.communicator.job.outputs) >= self._counter + 1: + o = self.communicator.job.outputs[self._counter] + self._counter += 1 + return o + if ( + self.communicator.job.latest_status.code == Status.FINISHED + and self._counter >= len(self.communicator.job.outputs) + ): + raise StopIteration() + time.sleep(0.001) + + async def __aiter__(self) -> AsyncGenerator[Update, None]: + """Async iterator that yields all updates from the communicator.updates queue.""" + if not self.communicator: + return + + while True: + get = self.communicator.updates.get() + try: + update = await asyncio.wait_for(get, timeout=0.5) + yield update + except asyncio.TimeoutError: + if self.done(): + return + continue + + def result(self, timeout: float | None = None) -> Any: + """ + Return the result of the call that the future represents. Raises CancelledError: If the future was cancelled, TimeoutError: If the future didn't finish executing before the given timeout, and Exception: If the call raised then that exception will be raised. + + Parameters: + timeout: The number of seconds to wait for the result if the future isn't done. If None, then there is no limit on the wait time. + Returns: + The result of the call that the future represents. For generator functions, it will return the final iteration. + Example: + from gradio_client import Client + calculator = Client(src="gradio/calculator") + job = calculator.submit("foo", "add", 4, fn_index=0) + job.result(timeout=5) + >> 9 + """ + return super().result(timeout=timeout) + + def outputs(self) -> list[tuple | Any]: + """ + Returns a list containing the latest outputs from the Job. + + If the endpoint has multiple output components, the list will contain + a tuple of results. Otherwise, it will contain the results without storing them + in tuples. + + For endpoints that are queued, this list will contain the final job output even + if that endpoint does not use a generator function. + + Example: + from gradio_client import Client + client = Client(src="gradio/count_generator") + job = client.submit(3, api_name="/count") + while not job.done(): + time.sleep(0.1) + job.outputs() + >> ['0', '1', '2'] + """ + if not self.communicator: + return [] + else: + with self.communicator.lock: + return self.communicator.job.outputs + + def status(self) -> StatusUpdate: + """ + Returns the latest status update from the Job in the form of a StatusUpdate + object, which contains the following fields: code, rank, queue_size, success, time, eta, and progress_data. + + progress_data is a list of updates emitted by the gr.Progress() tracker of the event handler. Each element + of the list has the following fields: index, length, unit, progress, desc. If the event handler does not have + a gr.Progress() tracker, the progress_data field will be None. + + Example: + from gradio_client import Client + client = Client(src="gradio/calculator") + job = client.submit(5, "add", 4, api_name="/predict") + job.status() + >> + job.status().eta + >> 43.241 # seconds + """ + time = datetime.now() + cancelled = False + if self.communicator: + with self.communicator.lock: + cancelled = self.communicator.should_cancel + if cancelled: + return StatusUpdate( + code=Status.CANCELLED, + rank=0, + queue_size=None, + success=False, + time=time, + eta=None, + progress_data=None, + ) + if self.done(): + if not self.future._exception: # type: ignore + return StatusUpdate( + code=Status.FINISHED, + rank=0, + queue_size=None, + success=True, + time=time, + eta=None, + progress_data=None, + ) + else: + return StatusUpdate( + code=Status.FINISHED, + rank=0, + queue_size=None, + success=False, + time=time, + eta=None, + progress_data=None, + ) + elif not self.communicator: + return StatusUpdate( + code=Status.PROCESSING, + rank=0, + queue_size=None, + success=None, + time=time, + eta=None, + progress_data=None, + ) + else: + with self.communicator.lock: + eta = self.communicator.job.latest_status.eta + if self.verbose and self.space_id and eta and eta > 30: + print( + f"Due to heavy traffic on this app, the prediction will take approximately {int(eta)} seconds." + f"For faster predictions without waiting in queue, you may duplicate the space using: Client.duplicate({self.space_id})" + ) + return self.communicator.job.latest_status + + def cancel(self) -> bool: + """Cancels the job as best as possible. + + If the app you are connecting to has the gradio queue enabled, the job + will be cancelled locally as soon as possible. For apps that do not use the + queue, the job cannot be cancelled if it's been sent to the local executor + (for the time being). + + Note: In general, this DOES not stop the process from running in the upstream server + except for the following situations: + + 1. If the job is queued upstream, it will be removed from the queue and the server will not run the job + 2. If the job has iterative outputs, the job will finish as soon as the current iteration finishes running + 3. If the job has not been picked up by the queue yet, the queue will not pick up the job + """ + if self.communicator: + with self.communicator.lock: + self.communicator.should_cancel = True + if self.cancel_fn: + self.cancel_fn() + return True + return self.future.cancel() + + def __getattr__(self, name): + """Forwards any properties to the Future class.""" + return getattr(self.future, name) diff --git a/venv/lib/python3.10/site-packages/gradio_client/compatibility.py b/venv/lib/python3.10/site-packages/gradio_client/compatibility.py new file mode 100644 index 0000000000000000000000000000000000000000..8348cf0c191a8f494ee0b425a87d416ee04d770d --- /dev/null +++ b/venv/lib/python3.10/site-packages/gradio_client/compatibility.py @@ -0,0 +1,341 @@ +"""This module contains the EndpointV3Compatibility class, which is used to connect to Gradio apps running 3.x.x versions of Gradio.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal + +import httpx +import huggingface_hub +import websockets +from packaging import version + +from gradio_client import serializing, utils +from gradio_client.exceptions import SerializationSetupError +from gradio_client.utils import ( + Communicator, +) + +if TYPE_CHECKING: + from gradio_client import Client + + +class EndpointV3Compatibility: + """Endpoint class for connecting to v3 endpoints. Backwards compatibility.""" + + def __init__(self, client: Client, fn_index: int, dependency: dict, *_args): + self.client: Client = client + self.fn_index = fn_index + self.dependency = dependency + api_name = dependency.get("api_name") + self.api_name: str | Literal[False] | None = ( + "/" + api_name if isinstance(api_name, str) else api_name + ) + self.use_ws = self._use_websocket(self.dependency) + self.protocol = "ws" if self.use_ws else "http" + self.input_component_types = [] + self.output_component_types = [] + self.root_url = client.src + "/" if not client.src.endswith("/") else client.src + try: + # Only a real API endpoint if backend_fn is True (so not just a frontend function), serializers are valid, + # and api_name is not False (meaning that the developer has explicitly disabled the API endpoint) + self.serializers, self.deserializers = self._setup_serializers() + self.is_valid = self.dependency["backend_fn"] and self.api_name is not False + except SerializationSetupError: + self.is_valid = False + self.backend_fn = dependency.get("backend_fn") + self.show_api = True + + def __repr__(self): + return f"Endpoint src: {self.client.src}, api_name: {self.api_name}, fn_index: {self.fn_index}" + + def __str__(self): + return self.__repr__() + + def make_end_to_end_fn(self, helper: Communicator | None = None): + _predict = self.make_predict(helper) + + def _inner(*data): + if not self.is_valid: + raise utils.InvalidAPIEndpointError() + data = self.insert_state(*data) + data = self.serialize(*data) + predictions = _predict(*data) + predictions = self.process_predictions(*predictions) + # Append final output only if not already present + # for consistency between generators and not generators + if helper: + with helper.lock: + if not helper.job.outputs: + helper.job.outputs.append(predictions) + return predictions + + return _inner + + def make_cancel(self, helper: Communicator | None = None): # noqa: ARG002 (needed so that both endpoints classes have the same api) + return None + + def make_predict(self, helper: Communicator | None = None): + def _predict(*data) -> tuple: + data = json.dumps( + { + "data": data, + "fn_index": self.fn_index, + "session_hash": self.client.session_hash, + } + ) + hash_data = json.dumps( + { + "fn_index": self.fn_index, + "session_hash": self.client.session_hash, + } + ) + if self.use_ws: + result = utils.synchronize_async(self._ws_fn, data, hash_data, helper) + if "error" in result: + raise ValueError(result["error"]) + else: + response = httpx.post( + self.client.api_url, + headers=self.client.headers, + json=data, + verify=self.client.ssl_verify, + **self.client.httpx_kwargs, + ) + result = json.loads(response.content.decode("utf-8")) + try: + output = result["data"] + except KeyError as ke: + is_public_space = ( + self.client.space_id + and not huggingface_hub.space_info(self.client.space_id).private + ) + if "error" in result and "429" in result["error"] and is_public_space: + raise utils.TooManyRequestsError( + f"Too many requests to the API, please try again later. To avoid being rate-limited, " + f"please duplicate the Space using Client.duplicate({self.client.space_id}) " + f"and pass in your Hugging Face token." + ) from None + elif "error" in result: + raise ValueError(result["error"]) from None + raise KeyError( + f"Could not find 'data' key in response. Response received: {result}" + ) from ke + return tuple(output) + + return _predict + + def _predict_resolve(self, *data) -> Any: + """Needed for gradio.load(), which has a slightly different signature for serializing/deserializing""" + outputs = self.make_predict()(*data) + if len(self.dependency["outputs"]) == 1: + return outputs[0] + return outputs + + def _upload( + self, file_paths: list[str | list[str]] + ) -> list[str | list[str]] | list[dict[str, Any] | list[dict[str, Any]]]: + if not file_paths: + return [] + # Put all the filepaths in one file + # but then keep track of which index in the + # original list they came from so we can recreate + # the original structure + files = [] + indices = [] + for i, fs in enumerate(file_paths): + if not isinstance(fs, list): + fs = [fs] + for f in fs: + files.append(("files", (Path(f).name, open(f, "rb")))) # noqa: SIM115 + indices.append(i) + r = httpx.post( + self.client.upload_url, + headers=self.client.headers, + files=files, + verify=self.client.ssl_verify, + **self.client.httpx_kwargs, + ) + if r.status_code != 200: + uploaded = file_paths + else: + uploaded = [] + result = r.json() + for i, fs in enumerate(file_paths): + if isinstance(fs, list): + output = [o for ix, o in enumerate(result) if indices[ix] == i] + res = [ + { + "is_file": True, + "name": o, + "orig_name": Path(f).name, + "data": None, + } + for f, o in zip(fs, output, strict=False) + ] + else: + o = next(o for ix, o in enumerate(result) if indices[ix] == i) + res = { + "is_file": True, + "name": o, + "orig_name": Path(fs).name, + "data": None, + } + uploaded.append(res) + return uploaded + + def _add_uploaded_files_to_data( + self, + files: list[str | list[str]] | list[dict[str, Any] | list[dict[str, Any]]], + data: list[Any], + ) -> None: + """Helper function to modify the input data with the uploaded files.""" + file_counter = 0 + for i, t in enumerate(self.input_component_types): + if t in ["file", "uploadbutton"]: + data[i] = files[file_counter] + file_counter += 1 + + def insert_state(self, *data) -> tuple: + data = list(data) + for i, input_component_type in enumerate(self.input_component_types): + if input_component_type == utils.STATE_COMPONENT: + data.insert(i, None) + return tuple(data) + + def remove_skipped_components(self, *data) -> tuple: + data = [ + d + for d, oct in zip(data, self.output_component_types, strict=False) + if oct not in utils.SKIP_COMPONENTS + ] + return tuple(data) + + def reduce_singleton_output(self, *data) -> Any: + if ( + len( + [ + oct + for oct in self.output_component_types + if oct not in utils.SKIP_COMPONENTS + ] + ) + == 1 + ): + return data[0] + else: + return data + + def serialize(self, *data) -> tuple: + if len(data) != len(self.serializers): + raise ValueError( + f"Expected {len(self.serializers)} arguments, got {len(data)}" + ) + + files = [ + f + for f, t in zip(data, self.input_component_types, strict=False) + if t in ["file", "uploadbutton"] + ] + uploaded_files = self._upload(files) + data = list(data) + self._add_uploaded_files_to_data(uploaded_files, data) + o = tuple( + [s.serialize(d) for s, d in zip(self.serializers, data, strict=False)] + ) + return o + + def deserialize(self, *data) -> tuple: + if len(data) != len(self.deserializers): + raise ValueError( + f"Expected {len(self.deserializers)} outputs, got {len(data)}" + ) + outputs = tuple( + [ + s.deserialize( + d, + save_dir=self.client.output_dir, + hf_token=self.client.hf_token, + root_url=self.root_url, + ) + for s, d in zip(self.deserializers, data, strict=False) + ] + ) + return outputs + + def process_predictions(self, *predictions): + if self.client.download_files: + predictions = self.deserialize(*predictions) + predictions = self.remove_skipped_components(*predictions) + predictions = self.reduce_singleton_output(*predictions) + return predictions + + def _setup_serializers( + self, + ) -> tuple[list[serializing.Serializable], list[serializing.Serializable]]: + inputs = self.dependency["inputs"] + serializers = [] + + for i in inputs: + for component in self.client.config["components"]: + if component["id"] == i: + component_name = component["type"] + self.input_component_types.append(component_name) + if component.get("serializer"): + serializer_name = component["serializer"] + if serializer_name not in serializing.SERIALIZER_MAPPING: + raise SerializationSetupError( + f"Unknown serializer: {serializer_name}, you may need to update your gradio_client version." + ) + serializer = serializing.SERIALIZER_MAPPING[serializer_name] + elif component_name in serializing.COMPONENT_MAPPING: + serializer = serializing.COMPONENT_MAPPING[component_name] + else: + raise SerializationSetupError( + f"Unknown component: {component_name}, you may need to update your gradio_client version." + ) + serializers.append(serializer()) # type: ignore + + outputs = self.dependency["outputs"] + deserializers = [] + for i in outputs: + for component in self.client.config["components"]: + if component["id"] == i: + component_name = component["type"] + self.output_component_types.append(component_name) + if component.get("serializer"): + serializer_name = component["serializer"] + if serializer_name not in serializing.SERIALIZER_MAPPING: + raise SerializationSetupError( + f"Unknown serializer: {serializer_name}, you may need to update your gradio_client version." + ) + deserializer = serializing.SERIALIZER_MAPPING[serializer_name] + elif component_name in utils.SKIP_COMPONENTS: + deserializer = serializing.SimpleSerializable + elif component_name in serializing.COMPONENT_MAPPING: + deserializer = serializing.COMPONENT_MAPPING[component_name] + else: + raise SerializationSetupError( + f"Unknown component: {component_name}, you may need to update your gradio_client version." + ) + deserializers.append(deserializer()) # type: ignore + + return serializers, deserializers + + def _use_websocket(self, dependency: dict) -> bool: + queue_enabled = self.client.config.get("enable_queue", False) + queue_uses_websocket = version.parse( + self.client.config.get("version", "2.0") + ) >= version.Version("3.2") + dependency_uses_queue = dependency.get("queue", False) is not False + return queue_enabled and queue_uses_websocket and dependency_uses_queue + + async def _ws_fn(self, data, hash_data, helper: Communicator): + async with websockets.connect( # type: ignore + self.client.ws_url, + open_timeout=10, + extra_headers=self.client.headers, + max_size=1024 * 1024 * 1024, + ) as websocket: + return await utils.get_pred_from_ws(websocket, data, hash_data, helper) diff --git a/venv/lib/python3.10/site-packages/gradio_client/data_classes.py b/venv/lib/python3.10/site-packages/gradio_client/data_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..267be1ebc8174838ae783d727438798f5e5a70fb --- /dev/null +++ b/venv/lib/python3.10/site-packages/gradio_client/data_classes.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from typing import Any, TypedDict + +from typing_extensions import NotRequired + + +class FileData(TypedDict): + name: str | None # filename + data: str | None # base64 encoded data + size: NotRequired[int | None] # size in bytes + is_file: NotRequired[ + bool + ] # whether the data corresponds to a file or base64 encoded data + orig_name: NotRequired[str] # original filename + mime_type: NotRequired[str] + is_stream: NotRequired[bool] + + +class ParameterInfo(TypedDict): + label: str + parameter_name: str + parameter_has_default: NotRequired[bool] + parameter_default: NotRequired[Any] + type: dict + python_type: dict + component: str + example_input: Any diff --git a/venv/lib/python3.10/site-packages/gradio_client/documentation.py b/venv/lib/python3.10/site-packages/gradio_client/documentation.py new file mode 100644 index 0000000000000000000000000000000000000000..f21234ed650ca4090209e9bd78cd26224cfdce7b --- /dev/null +++ b/venv/lib/python3.10/site-packages/gradio_client/documentation.py @@ -0,0 +1,354 @@ +"""Contains methods that generate documentation for Gradio functions and classes.""" + +from __future__ import annotations + +import dataclasses +import inspect +import warnings +from collections import defaultdict +from collections.abc import Callable +from functools import lru_cache + +classes_to_document = defaultdict(list) +classes_inherit_documentation = {} + + +def set_documentation_group(m): # noqa: ARG001 + """A no-op for backwards compatibility of custom components published prior to 4.16.0""" + pass + + +def extract_instance_attr_doc(cls, attr): + code = inspect.getsource(cls.__init__) + lines = [line.strip() for line in code.split("\n")] + i = None + for i, line in enumerate(lines): # noqa: B007 + if line.startswith("self." + attr + ":") or line.startswith( + "self." + attr + " =" + ): + break + if i is None: + raise NameError(f"Could not find {attr} in {cls.__name__}") + start_line = lines.index('"""', i) + end_line = lines.index('"""', start_line + 1) + for j in range(i + 1, start_line): + if lines[j].startswith("self."): + raise ValueError( + f"Found another attribute before docstring for {attr} in {cls.__name__}: " + + lines[j] + + "\n start:" + + lines[i] + ) + doc_string = " ".join(lines[start_line + 1 : end_line]) + return doc_string + + +_module_prefixes = [ + ("gradio._simple_templates", "component"), + ("gradio.block", "block"), + ("gradio.chat", "chatinterface"), + ("gradio.component", "component"), + ("gradio.events", "helpers"), + ("gradio.data_classes", "helpers"), + ("gradio.exceptions", "helpers"), + ("gradio.external", "helpers"), + ("gradio.flag", "flagging"), + ("gradio.helpers", "helpers"), + ("gradio.interface", "interface"), + ("gradio.layout", "layout"), + ("gradio.route", "routes"), + ("gradio.theme", "themes"), + ("gradio_client.", "py-client"), + ("gradio.utils", "helpers"), + ("gradio.renderable", "renderable"), +] + + +@lru_cache(maxsize=10) +def _get_module_documentation_group(modname) -> str: + for prefix, group in _module_prefixes: + if modname.startswith(prefix): + return group + raise ValueError(f"No known documentation group for module {modname!r}") + + +def document(*fns, inherit=False, documentation_group=None): + """ + Defines the @document decorator which adds classes or functions to the Gradio + documentation at www.gradio.app/docs. + + Usage examples: + - Put @document() above a class to document the class and its constructor. + - Put @document("fn1", "fn2") above a class to also document methods fn1 and fn2. + - Put @document("*fn3") with an asterisk above a class to document the instance attribute methods f3. + """ + _documentation_group = documentation_group + + def inner_doc(cls): + functions = list(fns) + if hasattr(cls, "EVENTS"): + functions += cls.EVENTS + if inherit: + classes_inherit_documentation[cls] = None + + documentation_group = _documentation_group # avoid `nonlocal` reassignment + if _documentation_group is None: + try: + modname = inspect.getmodule(cls).__name__ # type: ignore + if modname.startswith("gradio.") or modname.startswith( + "gradio_client." + ): + documentation_group = _get_module_documentation_group(modname) + else: + # Then this is likely a custom Gradio component that we do not include in the documentation + pass + except Exception as exc: + warnings.warn(f"Could not get documentation group for {cls}: {exc}") + classes_to_document[documentation_group].append((cls, functions)) + return cls + + return inner_doc + + +def document_fn(fn: Callable, cls) -> tuple[str, list[dict], dict, str | None]: + """ + Generates documentation for any function. + Parameters: + fn: Function to document + Returns: + description: General description of fn + parameters: A list of dicts for each parameter, storing data for the parameter name, annotation and doc + return: A dict storing data for the returned annotation and doc + example: Code for an example use of the fn + """ + doc_str = inspect.getdoc(fn) or "" + doc_lines = doc_str.split("\n") + signature = inspect.signature(fn) + description, parameters, returns, examples = [], {}, [], [] + mode = "description" + for line in doc_lines: + line = line.rstrip() + if line == "Parameters:": + mode = "parameter" + elif line.startswith("Example:"): + mode = "example" + if "(" in line and ")" in line: + c = line.split("(")[1].split(")")[0] + if c != cls.__name__: + mode = "ignore" + elif line == "Returns:": + mode = "return" + else: + if mode == "description": + description.append(line if line.strip() else "
") + continue + if not (line.startswith(" ") or line.strip() == ""): + print(line) + if not (line.startswith(" ") or line.strip() == ""): + raise SyntaxError( + f"Documentation format for {fn.__name__} has format error in line: {line}" + ) + line = line[4:] + if mode == "parameter": + colon_index = line.index(": ") + if colon_index < -1: + raise SyntaxError( + f"Documentation format for {fn.__name__} has format error in line: {line}" + ) + parameter = line[:colon_index] + parameter_doc = line[colon_index + 2 :] + parameters[parameter] = parameter_doc + elif mode == "return": + returns.append(line) + elif mode == "example": + examples.append(line) + description_doc = " ".join(description) + parameter_docs = [] + for param_name, param in signature.parameters.items(): + if param_name.startswith("_"): + continue + if param_name == "self": + continue + if param_name in ["kwargs", "args"] and param_name not in parameters: + continue + parameter_doc = { + "name": param_name, + "annotation": param.annotation, + "doc": parameters.get(param_name), + } + if param_name in parameters: + del parameters[param_name] + if param.default != inspect.Parameter.empty: + default = param.default + if isinstance(default, str): + default = '"' + default + '"' + if default.__class__.__module__ != "builtins": + default = f"{default.__class__.__name__}()" + parameter_doc["default"] = default + elif parameter_doc["doc"] is not None: + if "kwargs" in parameter_doc["doc"]: + parameter_doc["kwargs"] = True + if "args" in parameter_doc["doc"]: + parameter_doc["args"] = True + parameter_docs.append(parameter_doc) + if parameters: + raise ValueError( + f"Documentation format for {fn.__name__} documents " + f"nonexistent parameters: {', '.join(parameters.keys())}. " + f"Valid parameters: {', '.join(signature.parameters.keys())}" + ) + if len(returns) == 0: + return_docs = {} + elif len(returns) == 1: + return_docs = {"annotation": signature.return_annotation, "doc": returns[0]} + else: + return_docs = {} + # raise ValueError("Does not support multiple returns yet.") + examples_doc = "\n".join(examples) if len(examples) > 0 else None + return description_doc, parameter_docs, return_docs, examples_doc + + +def document_cls(cls): + doc_str = inspect.getdoc(cls) + if doc_str is None: + return "", {}, "" + tags = {} + description_lines = [] + mode = "description" + for line in doc_str.split("\n"): + line = line.rstrip() + if line.endswith(":") and " " not in line: + mode = line[:-1].lower() + tags[mode] = [] + elif line.split(" ")[0].endswith(":") and not line.startswith(" "): + tag = line[: line.index(":")].lower() + value = line[line.index(":") + 2 :] + tags[tag] = value + elif mode == "description": + description_lines.append(line if line.strip() else "
") + else: + if not (line.startswith(" ") or not line.strip()): + raise SyntaxError( + f"Documentation format for {cls.__name__} has format error in line: {line}" + ) + tags[mode].append(line[4:]) + if "example" in tags: + example = "\n".join(tags["example"]) + del tags["example"] + else: + example = None + for key, val in tags.items(): + if isinstance(val, list): + tags[key] = "
".join(val) + description = " ".join(description_lines).replace("\n", "
") + return description, tags, example + + +def generate_documentation(): + documentation = {} + for mode, class_list in classes_to_document.items(): + documentation[mode] = [] + for cls, fns in class_list: + fn_to_document = ( + cls + if inspect.isfunction(cls) or dataclasses.is_dataclass(cls) + else cls.__init__ + ) + _, parameter_doc, return_doc, _ = document_fn(fn_to_document, cls) + if ( + hasattr(cls, "preprocess") + and callable(cls.preprocess) # type: ignore + and hasattr(cls, "postprocess") + and callable(cls.postprocess) # type: ignore + ): + preprocess_doc = document_fn(cls.preprocess, cls) # type: ignore + postprocess_doc = document_fn(cls.postprocess, cls) # type: ignore + preprocess_doc, postprocess_doc = ( + { + "parameter_doc": preprocess_doc[1], + "return_doc": preprocess_doc[2], + }, + { + "parameter_doc": postprocess_doc[1], + "return_doc": postprocess_doc[2], + }, + ) + cls_description, cls_tags, cls_example = document_cls(cls) + cls_documentation = { + "class": cls, + "name": cls.__name__, + "description": cls_description, + "tags": cls_tags, + "parameters": parameter_doc, + "returns": return_doc, + "example": cls_example, + "fns": [], + } + if ( + hasattr(cls, "preprocess") + and callable(cls.preprocess) # type: ignore + and hasattr(cls, "postprocess") + and callable(cls.postprocess) # type: ignore + ): + cls_documentation["preprocess"] = preprocess_doc # type: ignore + cls_documentation["postprocess"] = postprocess_doc # type: ignore + for fn_name in fns: + instance_attribute_fn = fn_name.startswith("*") + if instance_attribute_fn: + fn_name = fn_name[1:] + # Instance attribute fns are classes + # whose __call__ method determines their behavior + fn = getattr(cls(), fn_name).__call__ + else: + fn = getattr(cls, fn_name) + if not callable(fn): + description_doc = str(fn) + parameter_docs = {} + return_docs = {} + examples_doc = "" + override_signature = f"gr.{cls.__name__}.{fn_name}" + else: + ( + description_doc, + parameter_docs, + return_docs, + examples_doc, + ) = document_fn(fn, cls) + if fn_name in getattr(cls, "EVENTS", []): + parameter_docs = parameter_docs[1:] + override_signature = None + if instance_attribute_fn: + description_doc = extract_instance_attr_doc(cls, fn_name) + cls_documentation["fns"].append( + { + "fn": fn, + "name": fn_name, + "description": description_doc, + "tags": {}, + "parameters": parameter_docs, + "returns": return_docs, + "example": examples_doc, + "override_signature": override_signature, + } + ) + documentation[mode].append(cls_documentation) + if cls in classes_inherit_documentation: + classes_inherit_documentation[cls] = cls_documentation["fns"] + for mode, class_list in classes_to_document.items(): + for i, (cls, _) in enumerate(class_list): + for super_class, fns in classes_inherit_documentation.items(): + if ( + inspect.isclass(cls) + and issubclass(cls, super_class) + and cls != super_class + ): + for inherited_fn in fns: + inherited_fn = dict(inherited_fn) + try: + inherited_fn["description"] = extract_instance_attr_doc( + cls, inherited_fn["name"] + ) + except ValueError: + pass + documentation[mode][i]["fns"].append(inherited_fn) + return documentation diff --git a/venv/lib/python3.10/site-packages/gradio_client/exceptions.py b/venv/lib/python3.10/site-packages/gradio_client/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f62f88e848e2e16a741b4478e92c73bed24ec88d --- /dev/null +++ b/venv/lib/python3.10/site-packages/gradio_client/exceptions.py @@ -0,0 +1,37 @@ +class SerializationSetupError(ValueError): + """Raised when a serializers cannot be set up correctly.""" + + pass + + +class AuthenticationError(ValueError): + """Raised when the client is unable to authenticate itself to a Gradio app due to invalid or missing credentials.""" + + pass + + +class AppError(ValueError): + """Raised when the upstream Gradio app throws an error because of the value submitted by the client.""" + + def __init__( + self, + message: str = "Error raised.", + duration: float | None = 10, + visible: bool = True, + title: str = "Error", + print_exception: bool = True, + ): + """ + Parameters: + message: The error message to be displayed to the user. Can be HTML, which will be rendered in the modal. + duration: The duration in seconds to display the error message. If None or 0, the error message will be displayed until the user closes it. + visible: Whether the error message should be displayed in the UI. + title: The title to be displayed to the user at the top of the error modal. + print_exception: Whether to print traceback of the error to the console when the error is raised. + """ + self.title = title + self.message = message + self.duration = duration + self.visible = visible + self.print_exception = print_exception + super().__init__(self.message) diff --git a/venv/lib/python3.10/site-packages/gradio_client/media_data.py b/venv/lib/python3.10/site-packages/gradio_client/media_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c815d1981935dedf38aab68a2ab35f0a83aaba39 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gradio_client/media_data.py @@ -0,0 +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mUgQXVkaW8gTGlicmFyeVRQRTEAAAAOAAAAS2V2aW4gTWFjTGVvZFRDT04AAAAKAAAAQ2luZW1hdGlj", +} + +BASE64_AUDIO_DUPLICATE = { + "path": "test/test_files/audio_sample.wav", + "data": "data:audio/wav;base64,UklGRuI/AABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0Ydw+AACO/w//5P6R/9D/SgDJAGIAegA3ALkAPAC8/zEA4/+G/8X/3//f/+n/jv+d/87/mP+p/7v/jv/C/ygAogB+AOQAHADX/1EAQwCz//T/kv/B/oD/rf8VABUAKAA3ANv/4P/o/8T/5/8o/6P/dgDDADcBUwCu/w3/+f5Z/5L/YQCfAMsAaAGxAXgAg//m/lT+Rf6k/lQA8wAXAR0BtwD1AF4Amf8g/xX/Tf/8/rb/FQDc/6sA6wAJAeIABQEyADn/af7D/b7+Mv8nALwAdAFAAooBswAKAEz/4v66/nb/KAAlAEoAQwBIAM//qf85AGAAeP+z/5f/n/8rAOL/MwBkAMsACwHxANUAjP8B/w7/2/7X/vj+TgDp/0MA5wDRAOMA5v+Q/+n/1/+C/zL/qf/y/yMAhQBEAEAAyf9A/23/JQCZ/5EArgDkAGMAmP/o/9b+Hv9O/8f/mQCdAIwAYwDX/3T/5v7//8r/PQCNAMIAvADq/4//SP8yAMP/1v/t/67/AgBaADwAAQD+/4YAZQDmAHAAgf+S/0D/D/94/7oA1QDaAMoAQgEFAX0A+v+S/i3+lP4o/ycACQBlAMQALAHxAJb/ZQBV/4T/z/8HAMUADgEuASQANwCCAD8A2/9e/wz/O/8u//T/+////ysATABVACABbQAwAMX/tf44/93+vf8IAHEAJAGnATYBoQCn/3j/VP65/vz///83AE8AeQDD//X/b/9RAMz/vwBmANP/dQAaAKT/vP/X/57/xP9B/1H/Bv+nAPgALwF3AY8BFQDe/9f+tv73/qT+hgBPAPcAOgAoAC8Akv/C/3YAaP/3/1//d/+6/6b/TQCAAPMAtgC5AN7/dv/s/fj+Ov/6/+8AfAGQAagB1g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EqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAABKwAAASsAAAEqAAAAOHN0Y28AAAAAAAAACgAAACwAADXXAABrgQAAwYwAARKNAAFhWwABztsAAiToAAKY1gADEjk=", +} +BASE64_FILE = { + "path": "test/test_files/sample_file.pdf", + "data": "data:@file/pdf;base64,JVBERi0xLjQKJdPr6eEKMSAwIG9iago8PC9UaXRsZSAoVW50aXRsZWQgZG9jdW1lbnQpCi9Qcm9kdWNlciAoU2tpYS9QREYgbTk3IEdvb2dsZSBEb2NzIFJlbmRlcmVyKT4+CmVuZG9iagozIDAgb2JqCjw8L2NhIDEKL0JNIC9Ob3JtYWw+PgplbmRvYmoKNSAwIG9iago8PC9GaWx0ZXIgL0ZsYXRlR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ec\xff\xa0\xa0\xe5\xcc\xbf\xcf\x9f\x87\x0f\xef\xef\x7f\x7f\x7f\xef\x0f\x0f\xdf\x1f\x1f\xff&&_\x9f\x9f\xffYY\xbf??5\xa5\xc2\xff\xff\xff\xac\x16\x19\xb2&\x00\xf8\x13\x10\xc2& \xdf`PP\x84\x9b\xf8\x03\x00\xb5\x0b\x0c\xdf\x0f\x00>\x9a\xb5\x87BM\x7f`P\xd2\xa5\x8f\xcc\x19\x00\xa5,\x00\xec\xd9\xcf\xe5\x0c\x00\xeb\t\x00\xff\xd9\xd9\xc7\x0c\x0c\x0f\x0f\x0f\xffyy~MZ\xfb\t\x08\xe5M@\xfb__\xff33\xcf\x90x\xf2\xe5\xdf\xc3\x06\x06\xbf\t\x08\xff\xb3\xb3\xd9\xb2\x9f\xff\x06\x06\xac)\x00\xff\xc6\xc6\x0c\t\x08\xf9\xf2\xef\xc9s`\xb8#\x00\x9f/\x00\xff__\xff\x8c\x8c\xc5\x1c\x00\xdf33\xffpp\xcf\x19\x19\xc0\x13\x10\xbf\x90x\xf7YY\xff\xf6\xf6\xe7??\xd7&&\xefLL2& \xdf\xbf\xaf\xbf\xbf\xbf???\xc5M@cn\x81_\x00\x00___\xcb00\xd8\x13\x00YC8\x80\x80\x80\xf3RRsVH\xc490\x10\x10\x10\x917@\xf2\x06\x00\xcf@@\xca\x86pooo\xa3!&\xc1\x1d\x18\xcf//\x1f\x1f\x1f\xdf\x00\x00\xd2\x16\x00\xcb\x90x\xbf\x1f\x00\x19\x13\x10\xf3\xd0\xd0\xe399&\x1d\x18Yy\x8e\x8f\x8f\x8f\xff\xa9\xa9\xcb\x13\x13\xbf00SF@\xb6& >\x1d\x18\xfb\xdd\xdd@@@\x99\x93\x90\xff\xbc\xbc\x7fPP\xaf\xaf\xaf\xc6VHzsp\x93& \xb7pp\xb3\x86ptPP|pp\xafOO\xd0\xd0\xd0\xef\xef\xefL90\xbc\xa9\xa0o0(\xeb\xb0\xb0\xff\xe0\xe0\xff\xd0\xd0\x870(K0(\xc9|h\x9f__lct\xebFF\xcf\xcf\xcf\xe0\xe0\xe0b& \xff },(@0(\xa9\x93\x88\xa6|h\x1f\xdf\xdf\xd5\xac\x97\xe2\xc5\xb7\xc7`POOO\x9cyhppp\xff\x80\x80\xff\x96\x96\xd7``\xcc\x99\x7f,\xb0\xcf\xbf\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00\x00\xffff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\xa8\x00,\x00\x00\x00\x00=\x00D\x00\x00\x08\xff\x00Q\t\x1cH\xb0\xa0\xc1\x83\x08\x13*\\\xc8\xb0\xa1\xc0\x1b\x07\x0c8\x9cHq\xa1\x89\x14\xa72F\xac\xc8\xb1\xa2\t\x1f\x19Cj\x94\xd8\xb1$B\x03\x07D\xaa\x1ci\xb2%*#3V\xcad\xe9\xb2\xa2\x9d 3s\x9e\xdaX\x93!"\x8c:\x83\xf2\xeci\xf0c\xd0\xa3!\x87\x12E\x89\xb4iR\x92.a:\x9d\xfa\xb4\xe5\x0c\x9cT\xb3\xee\x84:\xf1\x06P\xad`\x95*4\n\xb6l\xd5\x84\x06>\x99]\x1b\xb2\xc5\x9c\x83F\xda\xb0\x9d{\xe4\x84\x00\x83W\xe7\xaeM\xe2f\xd4\xa8\xbb\x03\xbd\xea5kE\x88_\xbf\x80\x0fy\x1a\\\xb6\x08\x92\xc3\x87\x01\x070\xe5\x00\x02\xe3\xa9-\x80\xc4\x80\x1cY\xe0dS\x94-_\x0ezd3\xe7\xce\xa8>\x83\x0e=Zf\x92\x13\xa7Gm\x18 \xe1\xaf\xe7\xd5\xb8+\xb7\xceX8\xf6(\xda\xa2D\xd9N\x8d\xbb\xb8n\xc6\x8e}\x8f\xfa\x12<\xf8\xf0\xcf\x11\x1a\x14\x07}|mf\xdf\x00\x9elP\xd1\\\xb8dSaJ\x95\xffz }zu\xadiLs\xa6\xb0&8\x80\x01\xdd\x9f\x9b\x8a ^<\xf9\xe9\xac\xa9:\x82\x1d{\x83\x84\xe6\xef\xc5\xf7\x1d}\xf5\xd9W\x9eq\xa2\x1d\x95\x84a\xb1\xa9\xb0\x01\x00\xdd\x05\xd8\x9c|\x04\x16X\x8a\x02\x0b0\x80\x9f\x0b=\xe8\x94\\l\x1et \n\x00\x10\x02\x08\xdf\x84\x03ZX \x86\x1a\x16W\x03\x87+]\xe7[\x06\x00\x96\xe8\xde\x89\xce\xa5\xa8\xe2\x8a\x19N\xf7b\x87\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x90\xf2\x01\x08#\x10t\x80$\xc5\x99\xc1-\xc7?\x14\xff@\xc6\xdal\x8f\xe2\x04)b0\xb1\t)}\x84\x12J&\x04\x05\x02\xc5\x18\xb8\xd9P\xc0\x0f\x1c\x93`5h\x81_\xb0H(j\x98\xacD( \xc0`P\xc5\x8f\x83\xa6\xc1\xb6;l1\x9d\x06\x1bk\x9d4\x18:(\x1e\n\x15&sR\xb7A9\xc0Q\xf1 \x18X\x00Z\xdf<\x84\xa0:h$H^\x1cgC\\\xa0\xdc\x10\x9a\xc8\xae8\x11gdQ\x07\x01\x07!\x10\n\x11W| {\xef\xa6\x90\xb0m\x01"T B\x01<\xa8\xed\xba_X|pE\x1e\xa7\xc9\xe0D\x19\xce\xcb\xbe\x04\xf5\x08\x11\x80@\x02\xf1+\xce}\t!\xecP\xc1\x0ed\xb8\xdc\xf9\x86\xa0\x88\x8aQA\x06\x90\xc1\x02\xfc\xf2G\x83\x1c4\xc4~\xf8\xcb\x1f\xf7^v\x98D\x98\x0c\x07\xca\x1b\xc5\x05\xba\x90\xbfP`Bt\x14\x81`\x07\'\xc8/\xbf\xc8@\toC\x01)\x9c\x00\xbb\x0e\xd2\xcd$"\x94\xa0\xef\xf0\xe3\x978\xe0l\x02^ \x05\x07\xf3\x97\x00\x04\xd0\xaf%1t\xde\x0b|X\xb0\x820\x8db\x0f\xa4`\xc2\x04\x16@\x8a\x0e\xce\x8f(\x02\t\xa2\xec\x86X\xc4\xb5\x15"\x898\xc4A\xfc\x1a\x08\xc5\x82HQqT\xc4\xdc("A\n<\x08\x02\x05\x94\x90\x1d\r@\xd8E\x83|1\x14T\xbc\x80\x0e>@\n\x14\x88An\xa0\xbb]\x1b\x13\xf2F\xd9Y\xc2dg\xe8\xe1\x1e\x1d\xd2\xc7P\xa0\x10\x07\x84\xf8\xe1 \x1fx\xbf\xfc\x11\xa1\x12\x90XdG\x82\xb8FI\x02q\t/\xb4\xa4&[\x12\x10\x00;', + "png", +) +ARRAY_TO_BASE64_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MoTl0BX2cCGebfo65VudMsPmck2TgYwPlV8d6yRNXRoDFT848XlaLMyf/PnrX43TAI62Un+qJ7VOWhHkAUzuhncX5OtoDMAQTOj9arj0CFahJ/XPH50KqtAQ2zTEBstlE1doCIXZtL3VmLwzHIme/OhyZAMff2Q73fOuTK5MOUVw+xl6kaHDkejopEddpTT/0IXGNSXo/Wowus3nLXUU1TGE5VhRQL6O1gXUp34olOze3kp9W0+urK4dA6K3bqeTVUr5T1rkh1sqVCIrRxoDpW/rTBOnuDdia4+n3YFp90ZsTeT8H/TLKvgILFchJoN8A7owDEEoNtKPj7srNMQFfd3fPDMAfnG4pWfSg0ii/+2tlOJ4p6i4WkuSpi55NZHZlOIWkqc+W1+Zbjd14HeeGWFbrVKO6euE0SIzkEpr1zaNyP/RKk2dvrVTKD6JiHxeXLp+061S/lZf9x3Ltbe3ezyeUCj0D7Np3TOTXHzJkasJXbMpufgKc5euF9wRA3mE5SwWi8Ph6O3tHRwc/Ofve0XvsUyurG1s2dXYIjqURZN1PVYmV+qaTLsaW0T1wVYjTx2onXDX/t1dGRH5wQD8GwBgtVoBEMJDnBhaoviKcefUb6gUi0fbA4dbsunnqhIUnufVqnRZzuIr3l2KPry6Joh5nnc4HM31ZLJY22TKWXwSKfj9KolxL4tEBb1LX6cwm8aCfL9jpKamhiAIn8/XZ+0ytxoLKr5yunPq42HnH58cuCxsazXE2KdnaxtbdE2m4qBpKen9wZz6nj8OfcdyapVyxHHZ1HW80OKTSBne15TQhyPRgIw4aD6xJ/PDrdJStvdjM/WlF59Eyvw+8kZsbX7ydtjPlaX4JLKV761vZf4H0dLrJY2D0p4AAAAASUVORK5CYII=" +) +BASE64_MODEL3D = { + "path": "Box.gltf", + "data": "data:;base64,ewogICAgImFzc2V0IjogewogICAgICAgICJnZW5lcmF0b3IiOiAiQ09MTEFEQTJHTFRGIiwKICAgICAgICAidmVyc2lvbiI6ICIyLjAiCiAgICB9LAogICAgInNjZW5lIjogMCwKICAgICJzY2VuZXMiOiBbCiAgICAgICAgewogICAgICAgICAgICAibm9kZXMiOiBbCiAgICAgICAgICAgICAgICAwCiAgICAgICAgICAgIF0KICAgICAgICB9CiAgICBdLAogICAgIm5vZGVzIjogWwogICAgICAgIHsKICAgICAgICAgICAgImNoaWxkcmVuIjogWwogICAgICAgICAgICAgICAgMQogICAgICAgICAgICBdLAogICAgICAgICAgICAibWF0cml4IjogWwogICAgICAgICAgICAgICAgMS4wLAogICAgICAgICAgICAgICAgMC4wLAogICAgICAgICAgICAgICAgMC4wLAogICAgICAgICAgICAgICAgMC4wLAogICAgICAgICAgICAgICAgMC4wLAogICAgICAgICAgICAgICAgMC4wLAogICAgICAgICAgICAgICAgLTEuMCwKICAgICAgICAgICAgICAgIDAuMCwKICAgICAgICAgICAgICAgIDAuMCwKICAgICAgICAgICAgICAgIDEuMCwKICAgICAgICAgICAgICAgIDAuMCwKICAgICAgICAgICAgICAgIDAuMCwKICAgICAgICAgICAgICAgIDAuMCwKICAgICAgICAgICAgICAgIDAuMCwKICAgICAgICAgICAgICAgIDAuMCwKICAgICAgICAgICAgICAgIDEuMAogICAgICAgICAgICBdCiAgICAgICAgfSwKICAgICAgICB7CiAgICAgICAgICAgICJtZXNoIjogMAogICAgICAgIH0KICAgIF0sCiAgICAibWVzaGVzIjogWwogICAgICAgIHsKICAgICAgICAgICAgInByaW1pdGl2ZXMiOiBbCiAgICAgICAgICAgICAgICB7CiAgICAgICAgICAgICAgICAgICAgImF0dHJpYnV0ZXMiOiB7CiAgICAgICAgICAgICAgICAgICAgICAgICJOT1JNQUwiOiAxLAogICAgICAgICAgICAgICAgICAgICAgICAiUE9TSVRJT04iOiAyCiAgICAgICAgICAgICAgICAgICAgfSwKICAgICAgICAgICAgICAgICAgICAiaW5kaWNlcyI6IDAsCiAgICAgICAgICAgICAgICAgICAgIm1vZGUiOiA0LAogICAgICAgICAgICAgICAgICAgICJtYXRlcmlhbCI6IDAKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgXSwKICAgICAgICAgICAgIm5hbWUiOiAiTWVzaCIKICAgICAgICB9CiAgICBdLAogICAgImFjY2Vzc29ycyI6IFsKICAgICAgICB7CiAgICAgICAgICAgICJidWZmZXJWaWV3IjogMCwKICAgICAgICAgICAgImJ5dGVPZmZzZXQiOiAwLAogICAgICAgICAgICAiY29tcG9uZW50VHlwZSI6IDUxMjMsCiAgICAgICAgICAgICJjb3VudCI6IDM2LAogICAgICAgICAgICAibWF4IjogWwogICAgICAgICAgICAgICAgMjMKICAgICAgICAgICAgXSwKICAgICAgICAgICAgIm1pbiI6IFsKICAgICAgICAgICAgICAgIDAKICAgICAgICAgICAgXSwKICAgICAgICAgICAgInR5cGUiOiAiU0NBTEFSIgogICAgICAgIH0sCiAgICAgICAgewogICAgICAgICAgICAiYnVmZmVyVmlldyI6IDEsCiAgICAgICAgICAgICJieXRlT2Zmc2V0IjogMCwKICAgICAgICAgICAgImNvbXBvbmVudFR5cGUiOiA1MTI2LAogICAgICAgICAgICAiY291bnQiOiAyNCwKICAgICAgICAgICAgIm1heCI6IFsKICAgICAgICAgICAgICAgIDEuMCwKICAgICAgICAgICAgICAgIDEuMCwKICAgICAgICAgICAgICAgIDEuMAogICAgICAgICAgICBdLAogICAgICAgICAgICAibWluIjogWwogICAgICAgICAgICAgICAgLTEuMCwKICAgICAgICAgICAgICAgIC0xLjAsCiAgICAgICAgICAgICAgICAtMS4wCiAgICAgICAgICAgIF0sCiAgICAgICAgICAgICJ0eXBlIjogIlZFQzMiCiAgICAgICAgfSwKICAgICAgICB7CiAgICAgICAgICAgICJidWZmZXJWaWV3IjogMSwKICAgICAgICAgICAgImJ5dGVPZmZzZXQiOiAyODgsCiAgICAgICAgICAgICJjb21wb25lbnRUeXBlIjogNTEyNiwKICAgICAgICAgICAgImNvdW50IjogMjQsCiAgICAgICAgICAgICJtYXgiOiBbCiAgICAgICAgICAgICAgICAwLjUsCiAgICAgICAgICAgICAgICAwLjUsCiAgICAgICAgICAgICAgICAwLjUKICAgICAgICAgICAgXSwKICAgICAgICAgICAgIm1pbiI6IFsKICAgICAgICAgICAgICAgIC0wLjUsCiAgICAgICAgICAgICAgICAtMC41LAogICAgICAgICAgICAgICAgLTAuNQogICAgICAgICAgICBdLAogICAgICAgICAgICAidHlwZSI6ICJWRUMzIgogICAgICAgIH0KICAgIF0sCiAgICAibWF0ZXJpYWxzIjogWwogICAgICAgIHsKICAgICAgICAgICAgInBick1ldGFsbGljUm91Z2huZXNzIjogewogICAgICAgICAgICAgICAgImJhc2VDb2xvckZhY3RvciI6IFsKICAgICAgICAgICAgICAgICAgICAwLjgwMDAwMDAxMTkyMDkyOSwKICAgICAgICAgICAgICAgICAgICAwLjAsCiAgICAgICAgICAgICAgICAgICAgMC4wLAogICAgICAgICAgICAgICAgICAgIDEuMAogICAgICAgICAgICAgICAgXSwKICAgICAgICAgICAgICAgICJtZXRhbGxpY0ZhY3RvciI6IDAuMAogICAgICAgICAgICB9LAogICAgICAgICAgICAibmFtZSI6ICJSZWQiCiAgICAgICAgfQogICAgXSwKICAgICJidWZmZXJWaWV3cyI6IFsKICAgICAgICB7CiAgICAgICAgICAgICJidWZmZXIiOiAwLAogICAgICAgICAgICAiYnl0ZU9mZnNldCI6IDU3NiwKICAgICAgICAgICAgImJ5dGVMZW5ndGgiOiA3MiwKICAgICAgICAgICAgInRhcmdldCI6IDM0OTYzCiAgICAgICAgfSwKICAgICAgICB7CiAgICAgICAgICAgICJidWZmZXIiOiAwLAogICAgICAgICAgICAiYnl0ZU9mZnNldCI6IDAsCiAgICAgICAgICAgICJieXRlTGVuZ3RoIjogNTc2LAogICAgICAgICAgICAiYnl0ZVN0cmlkZSI6IDEyLAogICAgICAgICAgICAidGFyZ2V0IjogMzQ5NjIKICAgICAgICB9CiAgICBdLAogICAgImJ1ZmZlcnMiOiBbCiAgICAgICAgewogICAgICAgICAgICAiYnl0ZUxlbmd0aCI6IDY0OCwKICAgICAgICAgICAgInVyaSI6ICJkYXRhOmFwcGxpY2F0aW9uL29jdGV0L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QUFBQy9BQUFBUHdBQUFEOEFBQUMvQUFBQkFBSUFBd0FDQUFFQUJBQUZBQVlBQndBR0FBVUFDQUFKQUFvQUN3QUtBQWtBREFBTkFBNEFEd0FPQUEwQUVBQVJBQklBRXdBU0FCRUFGQUFWQUJZQUZ3QVdBQlVBIgogICAgICAgIH0KICAgIF0KfQo=", +} +SUM_PIXELS_INTERPRETATION = { + "scores": [ + [ + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 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, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.9217332561281606, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.8478093032233159, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + 0.7775525960239336, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.28228141285466124, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.7110596409959468, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.5717043041883806, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.17004439297432927, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.6232387569967188, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.349160393746381, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + 0.37415556842308434, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + [ + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.4147847905809689, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.21617448369040726, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.4393939393939394, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + 0.8667245705462266, + ], + ] + ], + "alternative_outputs": [ + [ + [1793106], + [1795539], + [1797837], + [1800021], + [1815417], + [1802088], + [1806420], + [1824192], + [1818906], + [1804818], + [1813338], + [1812561], + [1811298], + [1817472], + [1810533], + [1797249], + ] + ], +} +SUM_PIXELS_SHAP_INTERPRETATION = { + "scores": [ + [ + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.36599426908032084, + 0.0, + 0.0, + 0.0, + 0.0, + 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, + 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, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.9044030984144017, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.5780729041010304, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.03706410007949775, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.4724172299368354, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + 0.5148839775509372, + ], + ] + ], + "alternative_outputs": [[]], +} + +FILE_TEMPLATE_CONTEXT = { + "file_count": "single", + "value": { + "path": "sample_file.pdf", + "size": 10558, + "data": "data:application/pdf;base64,JVBERi0xLjQKJdPr6eEKMSAwIG9iago8PC9UaXRsZSAoVW50aXRsZWQgZG9jdW1lbnQpCi9Qcm9kdWNlciAoU2tpYS9QREYgbTk3IEdvb2dsZSBEb2NzIFJlbmRlcmVyKT4+CmVuZG9iagozIDAgb2JqCjw8L2NhIDEKL0JNIC9Ob3JtYWw+PgplbmRvYmoKNSAwIG9iago8PC9GaWx0ZXIgL0ZsYXRlRGVjb2RlCi9MZW5ndGggMjM2Pj4gc3RyZWFtCnicjZDfakMhDMbvfYpcD2bzTxNhFFZYe90h7AG2tTDoYO37w9S1O1A4cIyo5Bc/80mALR6pLVYY3k/hJ/RMJh6J82d4e4Dvlo2WRu1tb6UEPV538Hc4H8NqJ3C8DAWnDIQpd4lD2LdYomzcZ9O+Km1qWG0VSCRKG+xQD4FuTZeWdTcR0CiZiqtAPYXOGKOhEBnUD3hC5M0a6lcoObInwdIErsAHcI+F3cknsB3ANFJCU54Byf6B8AAvdZi9s8WokcXNFrvLEj0n0gXu5Hm8TJyiK6nm+54Ipd3IXnQiae5H5vyxTf724RdvlHTtCmVuZHN0cmVhbQplbmRvYmoKMiAwIG9iago8PC9UeXBlIC9QYWdlCi9SZXNvdXJjZXMgPDwvUHJvY1NldCBbL1BERiAvVGV4dCAvSW1hZ2VCIC9JbWFnZUMgL0ltYWdlSV0KL0V4dEdTdGF0ZSA8PC9HMyAzIDAgUj4+Ci9Gb250IDw8L0Y0IDQgMCBSPj4+PgovTWVkaWFCb3ggWzAgMCA2MTIgNzkyXQovQ29udGVudHMgNSAwIFIKL1N0cnVjdFBhcmVudHMgMAovUGFyZW50IDYgMCBSPj4KZW5kb2JqCjYgMCBvYmoKPDwvVHlwZSAvUGFnZXMKL0NvdW50IDEKL0tpZHMgWzIgMCBSXT4+CmVuZG9iago3IDAgb2JqCjw8L1R5cGUgL0NhdGFsb2cK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wNzYwIDAwMDAwIG4gCjAwMDAwMDkyMzkgMDAwMDAgbiAKMDAwMDAwOTQ2NiAwMDAwMCBuIAowMDAwMDA5Nzc0IDAwMDAwIG4gCnRyYWlsZXIKPDwvU2l6ZSAxMgovUm9vdCA3IDAgUgovSW5mbyAxIDAgUj4+CnN0YXJ0eHJlZgoxMDI0MgolJUVPRg==", + }, + "path": "file", + "label": None, + "show_label": True, + "style": {}, + "elem_id": None, + "interactive": None, + "visible": True, +} +BASE64_MICROPHONE = { + "path": "/var/folders/t1/j7cmtcgd0mx43jh9nj_r9mmw0000gn/T/audiovb4gqjpc.wav", + "data": "data:audio/wav;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQRChYECGFOAZwH/////////FUmpZpkq17GDD0JATYCGQ2hyb21lV0GGQ2hyb21lFlSua7+uvdeBAXPFh1upJLeC6SCDgQKGhkFfT1BVU2Oik09wdXNIZWFkAQEAAIC7AAAAAADhjbWERzuAAJ+BAWJkgSAfQ7Z1Af/////////ngQCjQdyBAACA+4PMpH/n1EPs4MPlDak5Fzh3pT23QOozrpMIemMucj6646WZTq/qWAjImUB4j/aEtJ08SjAyqjqFq+2zZ5BmqSKaDZJtE8pZRnh7pd/ez05WinXc/FkOyULyhFtAKY7v5MAAAAAAAAAAAAAAAAAAAKADzFGuPnjkNLV2iu/mGqmEkZOFkTDa9XGu/V+C8YKNhgXB0voRMsMX5rHf2WcKpFvpWqoiFsq5scEBbG0cNIjdGoU+Z3Scu5r9OMpyp0ETCKhFwi+D/g/ukqguM4i4rX7bjr3/IZCXAiOQ40t44c3thLsE9d7N/U6uePnhBMMh4hOCoQEL9bQcJHJpEL8EJsRPhIMhSZI9/aBmdmUAb56PS8k6qVyW57IMTYbCOJ9d0wjC1rwuLwUWeX6YCLfpX3T2QXdSsjThYFKwgsJm4i33Piwe/liwLaUeKfa4XjbkP5zsHX4C78gpFRf77q3Pg5bvCukbN416f+vQiBunXlcZ/RSdUXg9phF/TftxJ8NOk+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9DHzLTbNcLhaCarJtahWNcISO0Q6H8KZ9tQMmWrsRuWKH97m+ktIn+W9VmjHOt0zTpl9vDEEghmDumuTbPih1BuT2XdpmdSFAkE0aL7c94+DmMh4ty1NCNe5U9XxGmAJE2X6SJ+/8RIwb0q2qi4cXGtErOJcs1iJIyzNY3sUfwwuhRgh5aoILHvb7op6CUSra6naxswSnyrUIf31ixyPM89TdWunmnNxCESOmc0dxr8YezmShtH9vMi4iK3xqp5loO8B3o1AJv1cmQXfmSFZSS6TlO9QNjm0IaTf4nkqKPIuJ7dJz00sBH5h9zUaMOwnWw7dBV7JtHFUtfuMt5ON3rWQDGOOOSNb4lbDRfb+NukSx6pQpe7Jhi1AZgldTrc0KiJN+e++k3oMeJi1TcOKjQWqBC3yA+4N6dDwMxHNO+IQBmpdfP0txPhVzIcgigTgvKU5Z5B1UsRKL9ntO264vpfXb5qIKZxsTL5gRb8cr9SYTeqZALPPTiPyGprMmcMYuymH6kpdtssAZlmkq4Fkqn0MpsUuusampz8fBVqvkLCLFskN9a3CSKYFYtq5xs2tOY4ZbQOZ233nmPWjtAdzO0TB8XKDJp0uSQqZL8Nxi8qDxe/jPJ3BsNvZ45GD/a1d586VN6+tJnhpq2kUi1JGbjYm748Pqn2jbshfpzO8yxTafKk8YdMTvOZUTJDspa9HGPxojq/Kre4L3WNpEFtsvcB9voh213Jgifb5VIHZtq4wfBeIRSdF2sI+CEpWGXpuLHN1oOiprwIrq5LpEHhHGxQIiDYSiIk/gYzGadEuyUOq8o2B1k5oULZE+dho02hlKtK0cCWv5QADlyz/QhXPZkiwqzgzCRJDGj/1y02xNbBb4ZFanAXgtm/l7fg==", +} diff --git a/venv/lib/python3.10/site-packages/gradio_client/package.json b/venv/lib/python3.10/site-packages/gradio_client/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f2fe692f3a2bdf1fa3dff1fcb00ad376ac550615 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gradio_client/package.json @@ -0,0 +1,8 @@ +{ + "name": "gradio_client", + "version": "1.11.0", + "description": "", + "python": "true", + "main_changeset": true, + "private": true +} diff --git a/venv/lib/python3.10/site-packages/gradio_client/serializing.py b/venv/lib/python3.10/site-packages/gradio_client/serializing.py new file mode 100644 index 0000000000000000000000000000000000000000..bd0d98e6f65b41c87a7958d0ddc42113f38b8443 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gradio_client/serializing.py @@ -0,0 +1,602 @@ +"""Included for backwards compatibility with 3.x spaces/apps.""" + +from __future__ import annotations + +import json +import os +import secrets +import tempfile +import uuid +from pathlib import Path +from typing import Any + +from gradio_client import media_data, utils +from gradio_client.data_classes import FileData + +with open(Path(__file__).parent / "types.json") as f: + serializer_types = json.load(f) + + +class Serializable: + def serialized_info(self): + """ + The typing information for this component as a dictionary whose values are a list of 2 strings: [Python type, language-agnostic description]. + Keys of the dictionary are: raw_input, raw_output, serialized_input, serialized_output + """ + return self.api_info() + + def api_info(self) -> dict[str, list[str]]: + """ + The typing information for this component as a dictionary whose values are a list of 2 strings: [Python type, language-agnostic description]. + Keys of the dictionary are: raw_input, raw_output, serialized_input, serialized_output + """ + raise NotImplementedError() + + def example_inputs(self) -> dict[str, Any]: + """ + The example inputs for this component as a dictionary whose values are example inputs compatible with this component. + Keys of the dictionary are: raw, serialized + """ + raise NotImplementedError() + + # For backwards compatibility + def input_api_info(self) -> tuple[str, str]: + api_info = self.api_info() + types = api_info.get("serialized_input", [api_info["info"]["type"]] * 2) # type: ignore + return (types[0], types[1]) + + # For backwards compatibility + def output_api_info(self) -> tuple[str, str]: + api_info = self.api_info() + types = api_info.get("serialized_output", [api_info["info"]["type"]] * 2) # type: ignore + return (types[0], types[1]) + + def serialize(self, x: Any, load_dir: str | Path = "", allow_links: bool = False): + """ + Convert data from human-readable format to serialized format for a browser. + """ + return x + + def deserialize( + self, + x: Any, + save_dir: str | Path | None = None, + root_url: str | None = None, + hf_token: str | None = None, + ): + """ + Convert data from serialized format for a browser to human-readable format. + """ + return x + + +class SimpleSerializable(Serializable): + """General class that does not perform any serialization or deserialization.""" + + def api_info(self) -> dict[str, bool | dict]: + return { + "info": serializer_types["SimpleSerializable"], + "serialized_info": False, + } + + def example_inputs(self) -> dict[str, Any]: + return { + "raw": None, + "serialized": None, + } + + +class StringSerializable(Serializable): + """Expects a string as input/output but performs no serialization.""" + + def api_info(self) -> dict[str, bool | dict]: + return { + "info": serializer_types["StringSerializable"], + "serialized_info": False, + } + + def example_inputs(self) -> dict[str, Any]: + return { + "raw": "Howdy!", + "serialized": "Howdy!", + } + + +class ListStringSerializable(Serializable): + """Expects a list of strings as input/output but performs no serialization.""" + + def api_info(self) -> dict[str, bool | dict]: + return { + "info": serializer_types["ListStringSerializable"], + "serialized_info": False, + } + + def example_inputs(self) -> dict[str, Any]: + return { + "raw": ["Howdy!", "Merhaba"], + "serialized": ["Howdy!", "Merhaba"], + } + + +class BooleanSerializable(Serializable): + """Expects a boolean as input/output but performs no serialization.""" + + def api_info(self) -> dict[str, bool | dict]: + return { + "info": serializer_types["BooleanSerializable"], + "serialized_info": False, + } + + def example_inputs(self) -> dict[str, Any]: + return { + "raw": True, + "serialized": True, + } + + +class NumberSerializable(Serializable): + """Expects a number (int/float) as input/output but performs no serialization.""" + + def api_info(self) -> dict[str, bool | dict]: + return { + "info": serializer_types["NumberSerializable"], + "serialized_info": False, + } + + def example_inputs(self) -> dict[str, Any]: + return { + "raw": 5, + "serialized": 5, + } + + +class ImgSerializable(Serializable): + """Expects a base64 string as input/output which is serialized to a filepath.""" + + def serialized_info(self): + return { + "type": "string", + "description": "filepath on your computer (or URL) of image", + } + + def api_info(self) -> dict[str, bool | dict]: + return {"info": serializer_types["ImgSerializable"], "serialized_info": True} + + def example_inputs(self) -> dict[str, Any]: + return { + "raw": media_data.BASE64_IMAGE, + "serialized": "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png", + } + + def serialize( + self, + x: str | None, + load_dir: str | Path = "", + allow_links: bool = False, + ) -> str | None: + """ + Convert from human-friendly version of a file (string filepath) to a serialized + representation (base64). + Parameters: + x: String path to file to serialize + load_dir: Path to directory containing x + """ + if not x: + return None + if utils.is_http_url_like(x): + return utils.encode_url_to_base64(x) + return utils.encode_file_to_base64(Path(load_dir) / x) + + def deserialize( + self, + x: str | None, + save_dir: str | Path | None = None, + root_url: str | None = None, + hf_token: str | None = None, + ) -> str | None: + """ + Convert from serialized representation of a file (base64) to a human-friendly + version (string filepath). Optionally, save the file to the directory specified by save_dir + Parameters: + x: Base64 representation of image to deserialize into a string filepath + save_dir: Path to directory to save the deserialized image to + root_url: Ignored + hf_token: Ignored + """ + if x is None or x == "": + return None + file = utils.decode_base64_to_file(x, dir=save_dir) + return file.name + + +class FileSerializable(Serializable): + """Expects a dict with base64 representation of object as input/output which is serialized to a filepath.""" + + def __init__(self) -> None: + self.stream = None + self.stream_name = None + super().__init__() + + def serialized_info(self): + return self._single_file_serialized_info() + + def _single_file_api_info(self): + return { + "info": serializer_types["SingleFileSerializable"], + "serialized_info": True, + } + + def _single_file_serialized_info(self): + return { + "type": "string", + "description": "filepath on your computer (or URL) of file", + } + + def _multiple_file_serialized_info(self): + return { + "type": "array", + "description": "List of filepath(s) or URL(s) to files", + "items": { + "type": "string", + "description": "filepath on your computer (or URL) of file", + }, + } + + def _multiple_file_api_info(self): + return { + "info": serializer_types["MultipleFileSerializable"], + "serialized_info": True, + } + + def api_info(self) -> dict[str, dict | bool]: + return self._single_file_api_info() + + def example_inputs(self) -> dict[str, Any]: + return self._single_file_example_inputs() + + def _single_file_example_inputs(self) -> dict[str, Any]: + return { + "raw": {"is_file": False, "data": media_data.BASE64_FILE}, + "serialized": "https://github.com/gradio-app/gradio/raw/main/test/test_files/sample_file.pdf", + } + + def _multiple_file_example_inputs(self) -> dict[str, Any]: + return { + "raw": [{"is_file": False, "data": media_data.BASE64_FILE}], + "serialized": [ + "https://github.com/gradio-app/gradio/raw/main/test/test_files/sample_file.pdf" + ], + } + + def _serialize_single( + self, + x: str | FileData | None, + load_dir: str | Path = "", + allow_links: bool = False, + ) -> FileData | None: + if x is None or isinstance(x, dict): + return x + if utils.is_http_url_like(x): + filename = x + size = None + else: + filename = str(Path(load_dir) / x) + size = Path(filename).stat().st_size + return { + "name": filename or None, + "data": None + if allow_links + else utils.encode_url_or_file_to_base64(filename), + "orig_name": Path(filename).name, + "size": size, + } + + def _setup_stream(self, url, hf_token): + return utils.download_byte_stream(url, hf_token) + + def _deserialize_single( + self, + x: str | FileData | None, + save_dir: str | None = None, + root_url: str | None = None, + hf_token: str | None = None, + ) -> str | None: + if x is None: + return None + if isinstance(x, str): + file_name = utils.decode_base64_to_file(x, dir=save_dir).name + elif isinstance(x, dict): + if x.get("is_file"): + filepath = x.get("name") + if filepath is None: + raise ValueError(f"The 'name' field is missing in {x}") + if root_url is not None: + file_name = utils.download_tmp_copy_of_file( + root_url + "file=" + filepath, + hf_token=hf_token, + dir=save_dir, + ) + else: + file_name = utils.create_tmp_copy_of_file(filepath, dir=save_dir) + elif x.get("is_stream"): + if not (x["name"] and root_url and save_dir): + raise ValueError( + "name and root_url and save_dir must all be present" + ) + if not self.stream or self.stream_name != x["name"]: + self.stream = self._setup_stream( + root_url + "stream/" + x["name"], hf_token=hf_token + ) + self.stream_name = x["name"] + chunk = next(self.stream) + path = Path(save_dir or tempfile.gettempdir()) / secrets.token_hex(20) + path.mkdir(parents=True, exist_ok=True) + path = path / x.get("orig_name", "output") + path.write_bytes(chunk) + file_name = str(path) + else: + data = x.get("data") + if data is None: + raise ValueError(f"The 'data' field is missing in {x}") + file_name = utils.decode_base64_to_file(data, dir=save_dir).name + else: + raise ValueError( + f"A FileSerializable component can only deserialize a string or a dict, not a {type(x)}: {x}" + ) + return file_name + + def serialize( + self, + x: str | FileData | None | list[str | FileData | None], + load_dir: str | Path = "", + allow_links: bool = False, + ) -> FileData | None | list[FileData | None]: + """ + Convert from human-friendly version of a file (string filepath) to a + serialized representation (base64) + Parameters: + x: String path to file to serialize + load_dir: Path to directory containing x + allow_links: Will allow path returns instead of raw file content + """ + if x is None or x == "": + return None + if isinstance(x, list): + return [self._serialize_single(f, load_dir, allow_links) for f in x] + else: + return self._serialize_single(x, load_dir, allow_links) + + def deserialize( + self, + x: str | FileData | None | list[str | FileData | None], + save_dir: Path | str | None = None, + root_url: str | None = None, + hf_token: str | None = None, + ) -> str | None | list[str | None]: + """ + Convert from serialized representation of a file (base64) to a human-friendly + version (string filepath). Optionally, save the file to the directory specified by `save_dir` + Parameters: + x: Base64 representation of file to deserialize into a string filepath + save_dir: Path to directory to save the deserialized file to + root_url: If this component is loaded from an external Space, this is the URL of the Space. + hf_token: If this component is loaded from an external private Space, this is the access token for the Space + """ + if x is None: + return None + if isinstance(save_dir, Path): + save_dir = str(save_dir) + if isinstance(x, list): + return [ + self._deserialize_single( + f, save_dir=save_dir, root_url=root_url, hf_token=hf_token + ) + for f in x + ] + else: + return self._deserialize_single( + x, save_dir=save_dir, root_url=root_url, hf_token=hf_token + ) + + +class VideoSerializable(FileSerializable): + def serialized_info(self): + return { + "type": "string", + "description": "filepath on your computer (or URL) of video file", + } + + def api_info(self) -> dict[str, dict | bool]: + return {"info": serializer_types["FileSerializable"], "serialized_info": True} + + def example_inputs(self) -> dict[str, Any]: + return { + "raw": {"is_file": False, "data": media_data.BASE64_VIDEO}, + "serialized": "https://github.com/gradio-app/gradio/raw/main/test/test_files/video_sample.mp4", + } + + def serialize( + self, x: str | None, load_dir: str | Path = "", allow_links: bool = False + ) -> tuple[FileData | None, None]: + return (super().serialize(x, load_dir, allow_links), None) # type: ignore + + def deserialize( + self, + x: tuple[FileData | None, FileData | None] | None, + save_dir: Path | str | None = None, + root_url: str | None = None, + hf_token: str | None = None, + ) -> str | tuple[str | None, str | None] | None: + """ + Convert from serialized representation of a file (base64) to a human-friendly + version (string filepath). Optionally, save the file to the directory specified by `save_dir` + """ + if isinstance(x, (tuple, list)): + if len(x) != 2: + raise ValueError(f"Expected tuple of length 2. Received: {x}") + x_as_list = [x[0], x[1]] + else: + raise ValueError(f"Expected tuple of length 2. Received: {x}") + deserialized_file = super().deserialize(x_as_list, save_dir, root_url, hf_token) # type: ignore + if isinstance(deserialized_file, list): + return deserialized_file[0] # ignore subtitles + + +class JSONSerializable(Serializable): + def serialized_info(self): + return {"type": "string", "description": "filepath to JSON file"} + + def api_info(self) -> dict[str, dict | bool]: + return {"info": serializer_types["JSONSerializable"], "serialized_info": True} + + def example_inputs(self) -> dict[str, Any]: + return { + "raw": {"a": 1, "b": 2}, + "serialized": None, + } + + def serialize( + self, + x: str | None, + load_dir: str | Path = "", + allow_links: bool = False, + ) -> dict | list | None: + """ + Convert from a a human-friendly version (string path to json file) to a + serialized representation (json string) + Parameters: + x: String path to json file to read to get json string + load_dir: Path to directory containing x + """ + if x is None or x == "": + return None + return utils.file_to_json(Path(load_dir) / x) + + def deserialize( + self, + x: str | dict | list, + save_dir: str | Path | None = None, + root_url: str | None = None, + hf_token: str | None = None, + ) -> str | None: + """ + Convert from serialized representation (json string) to a human-friendly + version (string path to json file). Optionally, save the file to the directory specified by `save_dir` + Parameters: + x: Json string + save_dir: Path to save the deserialized json file to + root_url: Ignored + hf_token: Ignored + """ + if x is None: + return None + return utils.dict_or_str_to_json_file(x, dir=save_dir).name + + +class GallerySerializable(Serializable): + def serialized_info(self): + return { + "type": "string", + "description": "path to directory with images and a file associating images with captions called captions.json", + } + + def api_info(self) -> dict[str, dict | bool]: + return { + "info": serializer_types["GallerySerializable"], + "serialized_info": True, + } + + def example_inputs(self) -> dict[str, Any]: + return { + "raw": [media_data.BASE64_IMAGE] * 2, + "serialized": [ + "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png", + ] + * 2, + } + + def serialize( + self, x: str | None, load_dir: str | Path = "", allow_links: bool = False + ) -> list[list[str | None]] | None: + if x is None or x == "": + return None + files = [] + captions_file = Path(x) / "captions.json" + with captions_file.open("r") as captions_json: + captions = json.load(captions_json) + for file_name, caption in captions.items(): + img = FileSerializable().serialize(file_name, allow_links=allow_links) + files.append([img, caption]) + return files + + def deserialize( + self, + x: list[list[str | None]] | None, + save_dir: str = "", + root_url: str | None = None, + hf_token: str | None = None, + ) -> None | str: + if x is None: + return None + gallery_path = Path(save_dir) / str(uuid.uuid4()) + gallery_path.mkdir(exist_ok=True, parents=True) + captions = {} + for img_data in x: + if isinstance(img_data, (list, tuple)): + img_data, caption = img_data + else: + caption = None + name = FileSerializable().deserialize( + img_data, gallery_path, root_url=root_url, hf_token=hf_token + ) + captions[name] = caption + captions_file = gallery_path / "captions.json" + with captions_file.open("w") as captions_json: + json.dump(captions, captions_json) + return os.path.abspath(gallery_path) + + +SERIALIZER_MAPPING = {} +for cls in Serializable.__subclasses__(): + SERIALIZER_MAPPING[cls.__name__] = cls + for subcls in cls.__subclasses__(): + SERIALIZER_MAPPING[subcls.__name__] = subcls + +SERIALIZER_MAPPING["Serializable"] = SimpleSerializable +SERIALIZER_MAPPING["File"] = FileSerializable +SERIALIZER_MAPPING["UploadButton"] = FileSerializable + +COMPONENT_MAPPING: dict[str, type] = { + "textbox": StringSerializable, + "number": NumberSerializable, + "slider": NumberSerializable, + "checkbox": BooleanSerializable, + "checkboxgroup": ListStringSerializable, + "radio": StringSerializable, + "dropdown": SimpleSerializable, + "image": ImgSerializable, + "video": FileSerializable, + "audio": FileSerializable, + "file": FileSerializable, + "dataframe": JSONSerializable, + "timeseries": JSONSerializable, + "fileexplorer": JSONSerializable, + "state": SimpleSerializable, + "button": StringSerializable, + "uploadbutton": FileSerializable, + "colorpicker": StringSerializable, + "label": JSONSerializable, + "highlightedtext": JSONSerializable, + "json": JSONSerializable, + "html": StringSerializable, + "gallery": GallerySerializable, + "chatbot": JSONSerializable, + "model3d": FileSerializable, + "plot": JSONSerializable, + "barplot": JSONSerializable, + "lineplot": JSONSerializable, + "scatterplot": JSONSerializable, + "markdown": StringSerializable, + "code": StringSerializable, + "annotatedimage": JSONSerializable, +} diff --git a/venv/lib/python3.10/site-packages/gradio_client/templates/__pycache__/discord_chat.cpython-310.pyc b/venv/lib/python3.10/site-packages/gradio_client/templates/__pycache__/discord_chat.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb476728758ad0a72d4a6c4f2fadc9487275aada Binary files /dev/null and b/venv/lib/python3.10/site-packages/gradio_client/templates/__pycache__/discord_chat.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/gradio_client/templates/discord_chat.py b/venv/lib/python3.10/site-packages/gradio_client/templates/discord_chat.py new file mode 100644 index 0000000000000000000000000000000000000000..bae4bfbf4fe6c5808b91503bc2b955cc38226470 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gradio_client/templates/discord_chat.py @@ -0,0 +1,193 @@ +import asyncio +import os +import threading +from threading import Event +from typing import Optional + +import discord +import gradio as gr +from discord import Permissions +from discord.ext import commands +from discord.utils import oauth_url + +import gradio_client as grc +from gradio_client.utils import QueueError + +event = Event() + +DISCORD_TOKEN = os.getenv("DISCORD_TOKEN") + + +async def wait(job): + while not job.done(): + await asyncio.sleep(0.2) + + +def get_client(session: Optional[str] = None) -> grc.Client: + client = grc.Client("<>", hf_token=os.getenv("HF_TOKEN")) + if session: + client.session_hash = session + return client + + +def truncate_response(response: str) -> str: + ending = "...\nTruncating response to 2000 characters due to discord api limits." + if len(response) > 2000: + return response[: 2000 - len(ending)] + ending + else: + return response + + +intents = discord.Intents.default() +intents.message_content = True +bot = commands.Bot(command_prefix="/", intents=intents) + + +@bot.event +async def on_ready(): + print(f"Logged in as {bot.user} (ID: {bot.user.id})") + synced = await bot.tree.sync() + print(f"Synced commands: {', '.join([s.name for s in synced])}.") + event.set() + print("------") + + +thread_to_client = {} +thread_to_user = {} + + +@bot.hybrid_command( + name="<>", + description="Enter some text to chat with the bot! Like this: /<> Hello, how are you?", +) +async def chat(ctx, prompt: str): + if ctx.author.id == bot.user.id: + return + try: + message = await ctx.send("Creating thread...") + + thread = await message.create_thread(name=prompt) + loop = asyncio.get_running_loop() + client = await loop.run_in_executor(None, get_client, None) + job = client.submit(prompt, api_name="/<>") + await wait(job) + + try: + job.result() + response = job.outputs()[-1] + await thread.send(truncate_response(response)) + thread_to_client[thread.id] = client + thread_to_user[thread.id] = ctx.author.id + except QueueError: + await thread.send( + "The gradio space powering this bot is really busy! Please try again later!" + ) + + except Exception as e: + print(f"{e}") + + +async def continue_chat(message): + """Continues a given conversation based on chathistory""" + try: + client = thread_to_client[message.channel.id] + prompt = message.content + job = client.submit(prompt, api_name="/<>") + await wait(job) + try: + job.result() + response = job.outputs()[-1] + await message.reply(truncate_response(response)) + except QueueError: + await message.reply( + "The gradio space powering this bot is really busy! Please try again later!" + ) + + except Exception as e: + print(f"Error: {e}") + + +@bot.event +async def on_message(message): + """Continue the chat""" + try: + if not message.author.bot: + if message.channel.id in thread_to_user: + if thread_to_user[message.channel.id] == message.author.id: + await continue_chat(message) + else: + await bot.process_commands(message) + + except Exception as e: + print(f"Error: {e}") + + +# running in thread +def run_bot(): + if not DISCORD_TOKEN: + print("DISCORD_TOKEN NOT SET") + event.set() + else: + bot.run(DISCORD_TOKEN) + + +threading.Thread(target=run_bot).start() + +event.wait() + +if not DISCORD_TOKEN: + welcome_message = """ + + ## You have not specified a DISCORD_TOKEN, which means you have not created a bot account. Please follow these steps: + + ### 1. Go to https://discord.com/developers/applications and click 'New Application' + + ### 2. Give your bot a name 🤖 + + ![](https://gradio-builds.s3.amazonaws.com/demo-files/discordbots/BotName.png) + + ## 3. In Settings > Bot, click the 'Reset Token' button to get a new token. Write it down and keep it safe 🔐 + + ![](https://gradio-builds.s3.amazonaws.com/demo-files/discordbots/ResetToken.png) + + ## 4. Optionally make the bot public if you want anyone to be able to add it to their servers + + ## 5. Scroll down and enable 'Message Content Intent' under 'Priviledged Gateway Intents' + + ![](https://gradio-builds.s3.amazonaws.com/demo-files/discordbots/MessageContentIntent.png) + + ## 6. Save your changes! + + ## 7. The token from step 3 is the DISCORD_TOKEN. Rerun the deploy_discord command, e.g client.deploy_discord(discord_bot_token=DISCORD_TOKEN, ...), or add the token as a space secret manually. +""" +else: + permissions = Permissions(326417525824) + url = oauth_url(bot.user.id, permissions=permissions) + welcome_message = f""" + ## Add this bot to your server by clicking this link: + + {url} + + ## How to use it? + + The bot can be triggered via `/<>` followed by your text prompt. + + This will create a thread with the bot's response to your text prompt. + You can reply in the thread (without `/<>`) to continue the conversation. + In the thread, the bot will only reply to the original author of the command. + + ⚠️ Note ⚠️: Please make sure this bot's command does have the same name as another command in your server. + + ⚠️ Note ⚠️: Bot commands do not work in DMs with the bot as of now. + """ + + +with gr.Blocks() as demo: + gr.Markdown( + f""" + # Discord bot of <> + {welcome_message} + """ + ) + +demo.launch() diff --git a/venv/lib/python3.10/site-packages/gradio_client/types.json b/venv/lib/python3.10/site-packages/gradio_client/types.json new file mode 100644 index 0000000000000000000000000000000000000000..2fc1d425b4568bb38def2517449b428858410759 --- /dev/null +++ b/venv/lib/python3.10/site-packages/gradio_client/types.json @@ -0,0 +1,199 @@ +{ + "SimpleSerializable": { + "type": {}, + "description": "any valid value" + }, + "StringSerializable": { + "type": "string" + }, + "ListStringSerializable": { + "type": "array", + "items": { + "type": "string" + } + }, + "BooleanSerializable": { + "type": "boolean" + }, + "NumberSerializable": { + "type": "number" + }, + "ImgSerializable": { + "type": "string", + "description": "base64 representation of an image" + }, + "FileSerializable": { + "oneOf": [ + { + "type": "string", + "description": "filepath on your computer (or URL) of file" + }, + { + "type": "object", + "properties": { + "name": { "type": "string", "description": "name of file" }, + "data": { + "type": "string", + "description": "base64 representation of file" + }, + "size": { + "type": "integer", + "description": "size of image in bytes" + }, + "is_file": { + "type": "boolean", + "description": "true if the file has been uploaded to the server" + }, + "orig_name": { + "type": "string", + "description": "original name of the file" + } + }, + "required": ["name", "data"] + }, + { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "description": "filepath on your computer (or URL) of file" + }, + { + "type": "object", + "properties": { + "name": { "type": "string", "description": "name of file" }, + "data": { + "type": "string", + "description": "base64 representation of file" + }, + "size": { + "type": "integer", + "description": "size of image in bytes" + }, + "is_file": { + "type": "boolean", + "description": "true if the file has been uploaded to the server" + }, + "orig_name": { + "type": "string", + "description": "original name of the file" + } + }, + "required": ["name", "data"] + } + ] + } + } + ] + }, + "SingleFileSerializable": { + "oneOf": [ + { + "type": "string", + "description": "filepath on your computer (or URL) of file" + }, + { + "type": "object", + "properties": { + "name": { "type": "string", "description": "name of file" }, + "data": { + "type": "string", + "description": "base64 representation of file" + }, + "size": { + "type": "integer", + "description": "size of image in bytes" + }, + "is_file": { + "type": "boolean", + "description": "true if the file has been uploaded to the server" + }, + "orig_name": { + "type": "string", + "description": "original name of the file" + } + }, + "required": ["name", "data"] + } + ] + }, + "MultipleFileSerializable": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "description": "filepath on your computer (or URL) of file" + }, + { + "type": "object", + "properties": { + "name": { "type": "string", "description": "name of file" }, + "data": { + "type": "string", + "description": "base64 representation of file" + }, + "size": { + "type": "integer", + "description": "size of image in bytes" + }, + "is_file": { + "type": "boolean", + "description": "true if the file has been uploaded to the server" + }, + "orig_name": { + "type": "string", + "description": "original name of the file" + } + }, + "required": ["name", "data"] + } + ] + } + }, + "JSONSerializable": { + "type": {}, + "description": "any valid json" + }, + "GallerySerializable": { + "type": "array", + "items": { + "type": "array", + "items": false, + "maxSize": 2, + "minSize": 2, + "prefixItems": [ + { + "type": "object", + "properties": { + "name": { "type": "string", "description": "name of file" }, + "data": { + "type": "string", + "description": "base64 representation of file" + }, + "size": { + "type": "integer", + "description": "size of image in bytes" + }, + "is_file": { + "type": "boolean", + "description": "true if the file has been uploaded to the server" + }, + "orig_name": { + "type": "string", + "description": "original name of the file" + } + }, + "required": ["name", "data"] + }, + { + "oneOf": [ + { "type": "string", "description": "caption of image" }, + { "type": "null" } + ] + } + ] + } + } +} diff --git a/venv/lib/python3.10/site-packages/gradio_client/utils.py b/venv/lib/python3.10/site-packages/gradio_client/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cd9b5dbd0fc31cff14476a1ac534e6ec88e37cca --- /dev/null +++ b/venv/lib/python3.10/site-packages/gradio_client/utils.py @@ -0,0 +1,1351 @@ +from __future__ import annotations + +import asyncio +import base64 +import concurrent.futures +import copy +import inspect +import json +import mimetypes +import os +import pkgutil +import secrets +import shutil +import tempfile +import time +import warnings +from collections.abc import Callable, Coroutine +from dataclasses import dataclass, field +from datetime import datetime +from enum import Enum +from pathlib import Path +from threading import Lock +from typing import ( + TYPE_CHECKING, + Any, + Literal, + NewType, + Optional, + TypedDict, + Union, + get_args, + get_origin, + get_type_hints, +) + +import fsspec.asyn +import httpx +import huggingface_hub +from huggingface_hub import SpaceStage +from websockets.legacy.protocol import WebSocketCommonProtocol + +if TYPE_CHECKING: + from gradio_client.data_classes import ParameterInfo + +API_URL = "api/predict/" +SSE_URL_V0 = "queue/join" +SSE_DATA_URL_V0 = "queue/data" +SSE_URL = "queue/data" +SSE_DATA_URL = "queue/join" +WS_URL = "queue/join" +UPLOAD_URL = "upload" +LOGIN_URL = "login" +CONFIG_URL = "config" +API_INFO_URL = "info?all_endpoints=True" +RAW_API_INFO_URL = "info?serialize=False" +SPACE_FETCHER_URL = "https://gradio-space-api-fetcher-v2.hf.space/api" +RESET_URL = "reset" +SPACE_URL = "https://hf.space/{}" +HEARTBEAT_URL = "heartbeat/{session_hash}" +CANCEL_URL = "cancel" + +STATE_COMPONENT = "state" +INVALID_RUNTIME = [ + SpaceStage.NO_APP_FILE, + SpaceStage.CONFIG_ERROR, + SpaceStage.BUILD_ERROR, + SpaceStage.RUNTIME_ERROR, + SpaceStage.PAUSED, +] + + +class Message(TypedDict, total=False): + msg: str + output: dict[str, Any] + event_id: str + rank: int + rank_eta: float + queue_size: int + success: bool + progress_data: list[dict] + log: str + level: str + + +def get_package_version() -> str: + try: + package_json_data = ( + pkgutil.get_data(__name__, "package.json").decode("utf-8").strip() # type: ignore + ) + package_data = json.loads(package_json_data) + version = package_data.get("version", "") + return version + except Exception: + return "" + + +__version__ = get_package_version() + + +class TooManyRequestsError(Exception): + """Raised when the API returns a 429 status code.""" + + pass + + +class QueueError(Exception): + """Raised when the queue is full or there is an issue adding a job to the queue.""" + + pass + + +class InvalidAPIEndpointError(Exception): + """Raised when the API endpoint is invalid.""" + + pass + + +class SpaceDuplicationError(Exception): + """Raised when something goes wrong with a Space Duplication.""" + + pass + + +class ServerMessage(str, Enum): + send_hash = "send_hash" + queue_full = "queue_full" + estimation = "estimation" + send_data = "send_data" + process_starts = "process_starts" + process_generating = "process_generating" + process_completed = "process_completed" + log = "log" + progress = "progress" + heartbeat = "heartbeat" + server_stopped = "Server stopped unexpectedly." + unexpected_error = "unexpected_error" + close_stream = "close_stream" + process_streaming = "process_streaming" + + +class Status(Enum): + """Status codes presented to client users.""" + + STARTING = "STARTING" + JOINING_QUEUE = "JOINING_QUEUE" + QUEUE_FULL = "QUEUE_FULL" + IN_QUEUE = "IN_QUEUE" + SENDING_DATA = "SENDING_DATA" + PROCESSING = "PROCESSING" + ITERATING = "ITERATING" + PROGRESS = "PROGRESS" + FINISHED = "FINISHED" + CANCELLED = "CANCELLED" + LOG = "LOG" + + @staticmethod + def ordering(status: Status) -> int: + """Order of messages. Helpful for testing.""" + order = [ + Status.STARTING, + Status.JOINING_QUEUE, + Status.QUEUE_FULL, + Status.IN_QUEUE, + Status.SENDING_DATA, + Status.PROCESSING, + Status.PROGRESS, + Status.ITERATING, + Status.FINISHED, + Status.CANCELLED, + ] + return order.index(status) + + def __lt__(self, other: Status): + return self.ordering(self) < self.ordering(other) + + @staticmethod + def msg_to_status(msg: str) -> Status: + """Map the raw message from the backend to the status code presented to users.""" + return { + ServerMessage.send_hash: Status.JOINING_QUEUE, + ServerMessage.queue_full: Status.QUEUE_FULL, + ServerMessage.estimation: Status.IN_QUEUE, + ServerMessage.send_data: Status.SENDING_DATA, + ServerMessage.process_starts: Status.PROCESSING, + ServerMessage.process_generating: Status.ITERATING, + ServerMessage.process_completed: Status.FINISHED, + ServerMessage.progress: Status.PROGRESS, + ServerMessage.log: Status.LOG, + ServerMessage.server_stopped: Status.FINISHED, + }[msg] # type: ignore + + +@dataclass +class ProgressUnit: + index: Optional[int] + length: Optional[int] + unit: Optional[str] + progress: Optional[float] + desc: Optional[str] + + @classmethod + def from_msg(cls, data: list[dict]) -> list[ProgressUnit]: + return [ + cls( + index=d.get("index"), + length=d.get("length"), + unit=d.get("unit"), + progress=d.get("progress"), + desc=d.get("desc"), + ) + for d in data + ] + + +@dataclass +class StatusUpdate: + """Update message sent from the worker thread to the Job on the main thread.""" + + code: Status + rank: int | None + queue_size: int | None + eta: float | None + success: bool | None + time: datetime | None + progress_data: list[ProgressUnit] | None + log: tuple[str, str] | None = None + type: Literal["status", "output"] = "status" + + +@dataclass +class OutputUpdate: + """Update message sent from the worker thread to the Job on the main thread.""" + + outputs: list[Any] + success: bool + type: Literal["output"] = "output" + final: bool = False + + +Update = NewType("Update", StatusUpdate | OutputUpdate) + + +def create_initial_status_update(): + return StatusUpdate( + code=Status.STARTING, + rank=None, + queue_size=None, + eta=None, + success=None, + time=datetime.now(), + progress_data=None, + ) + + +@dataclass +class JobStatus: + """The job status. + + Keeps track of the latest status update and intermediate outputs (not yet implements). + """ + + latest_status: StatusUpdate = field(default_factory=create_initial_status_update) + outputs: list[Any] = field(default_factory=list) + + +@dataclass +class Communicator: + """Helper class to help communicate between the worker thread and main thread.""" + + lock: Lock + job: JobStatus + prediction_processor: Callable[..., tuple] + reset_url: str + should_cancel: bool = False + event_id: str | None = None + thread_complete: bool = False + request_headers: dict[str, str] | None = None + updates: asyncio.Queue[Update] = field(default_factory=asyncio.Queue) + + +######################## +# Network utils +######################## + + +def is_http_url_like(possible_url) -> bool: + """ + Check if the given value is a string that looks like an HTTP(S) URL. + """ + if not isinstance(possible_url, str): + return False + return possible_url.startswith(("http://", "https://")) + + +def probe_url(possible_url: str) -> bool: + """ + Probe the given URL to see if it responds with a 200 status code (to HEAD, then to GET). + """ + headers = {"User-Agent": "gradio (https://gradio.app/; gradio-team@huggingface.co)"} + try: + with httpx.Client() as client: + head_request = httpx.head(possible_url, headers=headers) + if head_request.status_code == 405: + return client.get(possible_url, headers=headers).is_success + return head_request.is_success + except Exception: + return False + + +def is_valid_url(possible_url: str) -> bool: + """ + Check if the given string is a valid URL. + """ + warnings.warn( + "is_valid_url should not be used. " + "Use is_http_url_like() and probe_url(), as suitable, instead.", + ) + return is_http_url_like(possible_url) and probe_url(possible_url) + + +async def get_pred_from_ws( + websocket: WebSocketCommonProtocol, + data: str, + hash_data: str, + helper: Communicator | None = None, +) -> dict[str, Any]: + completed = False + resp = {} + while not completed: + # Receive message in the background so that we can + # cancel even while running a long pred + task = asyncio.create_task(websocket.recv()) + while not task.done(): + if helper: + with helper.lock: + if helper.should_cancel: + # Need to reset the iterator state since the client + # will not reset the session + async with httpx.AsyncClient() as http: + reset = http.post( + helper.reset_url, json=json.loads(hash_data) + ) + # Retrieve cancel exception from task + # otherwise will get nasty warning in console + task.cancel() + await asyncio.gather(task, reset, return_exceptions=True) + raise concurrent.futures.CancelledError() + # Need to suspend this coroutine so that task actually runs + await asyncio.sleep(0.01) + msg = task.result() + resp = json.loads(msg) + if helper: + with helper.lock: + has_progress = "progress_data" in resp + status_update = StatusUpdate( + code=Status.msg_to_status(resp["msg"]), + queue_size=resp.get("queue_size"), + rank=resp.get("rank", None), + success=resp.get("success"), + time=datetime.now(), + eta=resp.get("rank_eta"), + progress_data=ProgressUnit.from_msg(resp["progress_data"]) + if has_progress + else None, + ) + output = resp.get("output", {}).get("data", []) + if output and status_update.code != Status.FINISHED: + try: + result = helper.prediction_processor(*output) + except Exception as e: + result = [e] + helper.job.outputs.append(result) + helper.job.latest_status = status_update + if resp["msg"] == "queue_full": + raise QueueError("Queue is full! Please try again.") + if resp["msg"] == "send_hash": + await websocket.send(hash_data) + elif resp["msg"] == "send_data": + await websocket.send(data) + completed = resp["msg"] == "process_completed" + return resp["output"] + + +def get_pred_from_sse_v0( + client: httpx.Client, + data: dict, + hash_data: dict, + helper: Communicator, + sse_url: str, + sse_data_url: str, + headers: dict[str, str], + cookies: dict[str, str] | None, + ssl_verify: bool, + executor: concurrent.futures.ThreadPoolExecutor, +) -> dict[str, Any] | None: + helper.thread_complete = False + future_cancel = executor.submit( + check_for_cancel, helper, headers, cookies, ssl_verify + ) + future_sse = executor.submit( + stream_sse_v0, + client, + data, + hash_data, + helper, + sse_url, + sse_data_url, + headers, + cookies, + ) + done, _ = concurrent.futures.wait( + [future_cancel, future_sse], # type: ignore + return_when=concurrent.futures.FIRST_COMPLETED, + ) + helper.thread_complete = True + + if len(done) != 1: + raise ValueError(f"Did not expect {len(done)} tasks to be done.") + for future in done: + return future.result() + + +def get_pred_from_sse_v1plus( + helper: Communicator, + headers: dict[str, str], + cookies: dict[str, str] | None, + pending_messages_per_event: dict[str, list[Message | None]], + event_id: str, + protocol: Literal["sse_v1", "sse_v2", "sse_v2.1"], + ssl_verify: bool, + executor: concurrent.futures.ThreadPoolExecutor, +) -> dict[str, Any] | None: + helper.thread_complete = False + future_cancel = executor.submit( + check_for_cancel, helper, headers, cookies, ssl_verify + ) + future_sse = executor.submit( + stream_sse_v1plus, helper, pending_messages_per_event, event_id, protocol + ) + done, _ = concurrent.futures.wait( + [future_cancel, future_sse], # type: ignore + return_when=concurrent.futures.FIRST_COMPLETED, + ) + helper.thread_complete = True + + if len(done) != 1: + raise ValueError(f"Did not expect {len(done)} tasks to be done.") + for future in done: + exception = future.exception() + if exception: + raise exception + return future.result() + + +def check_for_cancel( + helper: Communicator, + headers: dict[str, str], + cookies: dict[str, str] | None, + ssl_verify: bool, +): + while True: + time.sleep(0.05) + with helper.lock: + if helper.should_cancel: + break + if helper.thread_complete: + raise concurrent.futures.CancelledError() + if helper.event_id: + httpx.post( + helper.reset_url, + json={"event_id": helper.event_id}, + headers=headers, + cookies=cookies, + verify=ssl_verify, + ) + raise concurrent.futures.CancelledError() + + +def stream_sse_v0( + client: httpx.Client, + data: dict, + hash_data: dict, + helper: Communicator, + sse_url: str, + sse_data_url: str, + headers: dict[str, str], + cookies: dict[str, str] | None, +) -> dict[str, Any]: + try: + with client.stream( + "GET", + sse_url, + params=hash_data, + headers=headers, + cookies=cookies, + ) as response: + for line in response.iter_lines(): + line = line.rstrip("\n") + if len(line) == 0: + continue + if line.startswith("data:"): + resp = json.loads(line[5:]) + if resp["msg"] in [ServerMessage.log, ServerMessage.heartbeat]: + continue + with helper.lock: + has_progress = "progress_data" in resp + status_update = StatusUpdate( + code=Status.msg_to_status(resp["msg"]), + queue_size=resp.get("queue_size"), + rank=resp.get("rank", None), + success=resp.get("success"), + time=datetime.now(), + eta=resp.get("rank_eta"), + progress_data=ProgressUnit.from_msg(resp["progress_data"]) + if has_progress + else None, + ) + output = resp.get("output", {}).get("data", []) + if output and status_update.code != Status.FINISHED: + try: + result = helper.prediction_processor(*output) + except Exception as e: + result = [e] + helper.job.outputs.append(result) + helper.job.latest_status = status_update + if helper.thread_complete: + raise concurrent.futures.CancelledError() + if resp["msg"] == "queue_full": + raise QueueError("Queue is full! Please try again.") + elif resp["msg"] == "send_data": + event_id = resp["event_id"] + helper.event_id = event_id + req = client.post( + sse_data_url, + json={"event_id": event_id, **data, **hash_data}, + headers=headers, + cookies=cookies, + ) + req.raise_for_status() + elif resp["msg"] == "process_completed": + return resp["output"] + else: + raise ValueError(f"Unexpected message: {line}") + raise ValueError("Did not receive process_completed message.") + except concurrent.futures.CancelledError: + raise + + +def stream_sse_v1plus( + helper: Communicator, + pending_messages_per_event: dict[str, list[Message | None]], + event_id: str, + protocol: Literal["sse_v1", "sse_v2", "sse_v2.1", "sse_v3"], +) -> dict[str, Any]: + try: + pending_messages = pending_messages_per_event[event_id] + pending_responses_for_diffs = None + + while True: + if len(pending_messages) > 0: + msg = pending_messages.pop(0) + else: + time.sleep(0.05) + continue + + if msg is None or helper.thread_complete: + raise concurrent.futures.CancelledError() + + with helper.lock: + log_message = None + if msg["msg"] == ServerMessage.log: + log = msg.get("log") + level = msg.get("level") + if log and level: + log_message = (log, level) + status_update = StatusUpdate( + code=Status.msg_to_status(msg["msg"]), + queue_size=msg.get("queue_size"), + rank=msg.get("rank", None), + success=msg.get("success"), + time=datetime.now(), + eta=msg.get("rank_eta"), + progress_data=ProgressUnit.from_msg(msg["progress_data"]) + if "progress_data" in msg + else None, + log=log_message, + ) + output = msg.get("output", {}).get("data", []) + if msg["msg"] == ServerMessage.process_generating and protocol in [ + "sse_v2", + "sse_v2.1", + "sse_v3", + ]: + if pending_responses_for_diffs is None: + pending_responses_for_diffs = list(output) + else: + for i, value in enumerate(output): + prev_output = pending_responses_for_diffs[i] + new_output = apply_diff(prev_output, value) + pending_responses_for_diffs[i] = new_output + output[i] = new_output + + if output and status_update.code != Status.FINISHED: + try: + result = helper.prediction_processor(*output) + except Exception as e: + result = [e] + helper.job.outputs.append(result) + helper.updates.put_nowait( + OutputUpdate(outputs=result, success=msg.get("success", True)) + ) + helper.job.latest_status = status_update + helper.updates.put_nowait(status_update) + if msg["msg"] == ServerMessage.process_completed: + del pending_messages_per_event[event_id] + if not msg.get("success", True): + # Create a new copy of the error dict so we + # can preserve the error message (it gets popped later) + output = dict(msg["output"].items()) + else: + output = msg["output"] + helper.updates.put_nowait( + OutputUpdate( + outputs=output, + final=True, + success=msg.get("success", True), + ) + ) + return msg["output"] + elif msg["msg"] == ServerMessage.server_stopped: + raise ValueError("Server stopped.") + + except concurrent.futures.CancelledError: + raise + + +def apply_diff(obj, diff): + obj = copy.deepcopy(obj) + + def apply_edit(target, path, action, value): + if len(path) == 0: + if action == "replace": + return value + elif action == "append": + return target + value + else: + raise ValueError(f"Unsupported action: {action}") + + current = target + for i in range(len(path) - 1): + current = current[path[i]] + + last_path = path[-1] + if action == "replace": + current[last_path] = value + elif action == "append": + current[last_path] += value + elif action == "add": + if isinstance(current, list): + current.insert(int(last_path), value) + else: + current[last_path] = value + elif action == "delete": + if isinstance(current, list): + del current[int(last_path)] + else: + del current[last_path] + else: + raise ValueError(f"Unknown action: {action}") + + return target + + for action, path, value in diff: + obj = apply_edit(obj, path, action, value) + + return obj + + +######################## +# Data processing utils +######################## + + +def create_tmp_copy_of_file(file_path: str, dir: str | None = None) -> str: + directory = Path(dir or tempfile.gettempdir()) / secrets.token_hex(20) + directory.mkdir(exist_ok=True, parents=True) + dest = directory / Path(file_path).name + shutil.copy2(file_path, dest) + return str(dest.resolve()) + + +def download_tmp_copy_of_file( + url_path: str, hf_token: str | None = None, dir: str | None = None +) -> str: + """Kept for backwards compatibility for 3.x spaces.""" + if dir is not None: + os.makedirs(dir, exist_ok=True) + headers = {"Authorization": "Bearer " + hf_token} if hf_token else {} + directory = Path(dir or tempfile.gettempdir()) / secrets.token_hex(20) + directory.mkdir(exist_ok=True, parents=True) + file_path = directory / Path(url_path).name + + with httpx.stream( + "GET", url_path, headers=headers, follow_redirects=True + ) as response: + response.raise_for_status() + with open(file_path, "wb") as f: + for chunk in response.iter_raw(): + f.write(chunk) + return str(file_path.resolve()) + + +def get_mimetype(filename: str) -> str | None: + if filename.endswith(".vtt"): + return "text/vtt" + mimetype = mimetypes.guess_type(filename)[0] + if mimetype is not None: + mimetype = mimetype.replace("x-wav", "wav").replace("x-flac", "flac") + return mimetype + + +def get_extension(encoding: str) -> str | None: + encoding = encoding.replace("audio/wav", "audio/x-wav") + type = mimetypes.guess_type(encoding)[0] + if type == "audio/flac": # flac is not supported by mimetypes + return "flac" + elif type is None: + return None + extension = mimetypes.guess_extension(type) + if extension is not None and extension.startswith("."): + extension = extension[1:] + return extension + + +def is_valid_file(file_path: str, file_types: list[str]) -> bool: + mime_type = get_mimetype(file_path) + for file_type in file_types: + if file_type == "file": + return True + if file_type.startswith("."): + file_type = file_type.lstrip(".").lower() + file_ext = Path(file_path).suffix.lstrip(".").lower() + if file_type == file_ext: + return True + elif mime_type is not None and mime_type.startswith(f"{file_type}/"): + return True + return False + + +def encode_file_to_base64(f: str | Path): + with open(f, "rb") as file: + encoded_string = base64.b64encode(file.read()) + base64_str = str(encoded_string, "utf-8") + mimetype = get_mimetype(str(f)) + return ( + "data:" + + (mimetype if mimetype is not None else "") + + ";base64," + + base64_str + ) + + +def encode_url_to_base64(url: str): + resp = httpx.get(url) + resp.raise_for_status() + encoded_string = base64.b64encode(resp.content) + base64_str = str(encoded_string, "utf-8") + mimetype = get_mimetype(url) + return ( + "data:" + (mimetype if mimetype is not None else "") + ";base64," + base64_str + ) + + +def encode_url_or_file_to_base64(path: str | Path): + path = str(path) + if is_http_url_like(path): + return encode_url_to_base64(path) + return encode_file_to_base64(path) + + +def download_byte_stream(url: str, hf_token=None): + arr = bytearray() + headers = {"Authorization": "Bearer " + hf_token} if hf_token else {} + with httpx.stream("GET", url, headers=headers) as r: + for data in r.iter_bytes(): + arr += data + yield data + yield arr + + +def decode_base64_to_binary(encoding: str) -> tuple[bytes, str | None]: + extension = get_extension(encoding) + data = encoding.rsplit(",", 1)[-1] + return base64.b64decode(data), extension + + +def strip_invalid_filename_characters(filename: str, max_bytes: int = 200) -> str: + """ + Strips invalid characters from a filename and ensures it does not exceed the maximum byte length + Invalid characters are any characters that are not alphanumeric or one of the following: . _ - , + The filename may include an extension (in which case it is preserved exactly as is), or could be just a name without an extension. + """ + name, ext = os.path.splitext(filename) + name = "".join([char for char in name if char.isalnum() or char in "._-, "]) + filename = name + ext + filename_len = len(filename.encode()) + if filename_len > max_bytes: + while filename_len > max_bytes: + if len(name) == 0: + break + name = name[:-1] + filename = name + ext + filename_len = len(filename.encode()) + return filename + + +def sanitize_parameter_names(original_name: str) -> str: + """Cleans up a Python parameter name to make the API info more readable.""" + return ( + "".join([char for char in original_name if char.isalnum() or char in " _"]) + .replace(" ", "_") + .lower() + ) + + +def decode_base64_to_file( + encoding: str, + file_path: str | None = None, + dir: str | Path | None = None, + prefix: str | None = None, +): + directory = Path(dir or tempfile.gettempdir()) / secrets.token_hex(20) + directory.mkdir(exist_ok=True, parents=True) + data, extension = decode_base64_to_binary(encoding) + if file_path is not None and prefix is None: + filename = Path(file_path).name + prefix = filename + if "." in filename: + prefix = filename[0 : filename.index(".")] + extension = filename[filename.index(".") + 1 :] + + if prefix is not None: + prefix = strip_invalid_filename_characters(prefix) + + if extension is None: + file_obj = tempfile.NamedTemporaryFile( + delete=False, prefix=prefix, dir=directory + ) + else: + file_obj = tempfile.NamedTemporaryFile( + delete=False, + prefix=prefix, + suffix="." + extension, + dir=directory, + ) + file_obj.write(data) + file_obj.flush() + return file_obj + + +def dict_or_str_to_json_file(jsn: str | dict | list, dir: str | Path | None = None): + if dir is not None: + os.makedirs(dir, exist_ok=True) + + file_obj = tempfile.NamedTemporaryFile( + delete=False, suffix=".json", dir=dir, mode="w+" + ) + if isinstance(jsn, str): + jsn = json.loads(jsn) + json.dump(jsn, file_obj) + file_obj.flush() + return file_obj + + +def file_to_json(file_path: str | Path) -> dict | list: + with open(file_path) as f: + return json.load(f) + + +########################### +# HuggingFace Hub API Utils +########################### +def set_space_timeout( + space_id: str, + hf_token: str | None = None, + timeout_in_seconds: int = 300, +): + headers = huggingface_hub.utils.build_hf_headers( + token=hf_token, + library_name="gradio_client", + library_version=__version__, + ) + try: + httpx.post( + f"https://huggingface.co/api/spaces/{space_id}/sleeptime", + json={"seconds": timeout_in_seconds}, + headers=headers, + ) + except httpx.HTTPStatusError as e: + raise SpaceDuplicationError( + f"Could not set sleep timeout on duplicated Space. Please visit {SPACE_URL.format(space_id)} " + "to set a timeout manually to reduce billing charges." + ) from e + + +######################## +# Misc utils +######################## + + +def synchronize_async(func: Callable, *args, **kwargs) -> Any: + """ + Runs async functions in sync scopes. Can be used in any scope. + + Example: + if inspect.iscoroutinefunction(block_fn.fn): + predictions = utils.synchronize_async(block_fn.fn, *processed_input) + + Args: + func: + *args: + **kwargs: + """ + return fsspec.asyn.sync(fsspec.asyn.get_loop(), func, *args, **kwargs) # type: ignore + + +class APIInfoParseError(ValueError): + pass + + +def get_type(schema: dict): + if "const" in schema: + return "const" + if "enum" in schema: + return "enum" + elif "type" in schema: + return schema["type"] + elif schema.get("$ref"): + return "$ref" + elif schema.get("oneOf"): + return "oneOf" + elif schema.get("anyOf"): + return "anyOf" + elif schema.get("allOf"): + return "allOf" + elif "type" not in schema: + return {} + else: + raise APIInfoParseError(f"Cannot parse type for {schema}") + + +FILE_DATA_FORMATS = [ + "Dict(path: str | None (Path to a local file), url: str | None (Publicly available url or base64 encoded image), size: int | None (Size of image in bytes), orig_name: str | None (Original filename), mime_type: str | None (mime type of image), is_stream: bool (Can always be set to False), meta: Dict())", + "dict(path: str | None (Path to a local file), url: str | None (Publicly available url or base64 encoded image), size: int | None (Size of image in bytes), orig_name: str | None (Original filename), mime_type: str | None (mime type of image), is_stream: bool (Can always be set to False), meta: dict())", + "Dict(path: str, url: str | None, size: int | None, orig_name: str | None, mime_type: str | None)", + "Dict(path: str, url: str | None, size: int | None, orig_name: str | None, mime_type: str | None, is_stream: bool)", + "Dict(path: str, url: str | None, size: int | None, orig_name: str | None, mime_type: str | None, is_stream: bool, meta: Dict())", + "dict(path: str, url: str | None, size: int | None, orig_name: str | None, mime_type: str | None, is_stream: bool, meta: dict())", + "dict(path: str, url: str | None, size: int | None, orig_name: str | None, mime_type: str | None, is_stream: bool, meta: dict(_type: Literal[gradio.FileData]))", +] + +CURRENT_FILE_DATA_FORMAT = FILE_DATA_FORMATS[-1] + + +def json_schema_to_python_type(schema: Any) -> str: + type_ = _json_schema_to_python_type(schema, schema.get("$defs")) + return type_.replace(CURRENT_FILE_DATA_FORMAT, "filepath") + + +def _json_schema_to_python_type(schema: Any, defs) -> str: + """Convert the json schema into a python type hint""" + if schema == {}: + return "Any" + type_ = get_type(schema) + if type_ == {}: + if "json" in schema.get("description", {}): + return "str | float | bool | list | dict" + else: + return "Any" + elif type_ == "$ref": + return _json_schema_to_python_type(defs[schema["$ref"].split("/")[-1]], defs) + elif type_ == "null": + return "None" + elif type_ == "const": + return f"Literal[{schema['const']}]" + elif type_ == "enum": + return ( + "Literal[" + ", ".join(["'" + str(v) + "'" for v in schema["enum"]]) + "]" + ) + elif type_ == "integer": + return "int" + elif type_ == "string": + return "str" + elif type_ == "boolean": + return "bool" + elif type_ == "number": + return "float" + elif type_ == "array": + items = schema.get("items", []) + if "prefixItems" in items: + elements = ", ".join( + [_json_schema_to_python_type(i, defs) for i in items["prefixItems"]] + ) + return f"tuple[{elements}]" + elif "prefixItems" in schema: + elements = ", ".join( + [_json_schema_to_python_type(i, defs) for i in schema["prefixItems"]] + ) + return f"tuple[{elements}]" + else: + elements = _json_schema_to_python_type(items, defs) + return f"list[{elements}]" + elif type_ == "object": + + def get_desc(v): + return f" ({v.get('description')})" if v.get("description") else "" + + props = schema.get("properties", {}) + + des = [ + f"{n}: {_json_schema_to_python_type(v, defs)}{get_desc(v)}" + for n, v in props.items() + if n != "$defs" + ] + + if "additionalProperties" in schema: + additional_properties = schema["additionalProperties"] + if isinstance(additional_properties, bool) and additional_properties: + des += ["str, Any"] + else: + des += [ + f"str, {_json_schema_to_python_type(additional_properties, defs)}" + ] + des = ", ".join(des) + return f"dict({des})" + elif type_ in ["oneOf", "anyOf"]: + desc = " | ".join([_json_schema_to_python_type(i, defs) for i in schema[type_]]) + return desc + elif type_ == "allOf": + data = ", ".join(_json_schema_to_python_type(i, defs) for i in schema[type_]) + desc = f"All[{data}]" + return desc + else: + raise APIInfoParseError(f"Cannot parse schema {schema}") + + +def python_type_to_json_schema(type_hint: Any) -> dict: + try: + return _python_type_to_json_schema(type_hint) + except Exception: + return {} + + +def _python_type_to_json_schema(type_hint: Any) -> dict: + """Convert a Python type hint to a JSON schema.""" + if type_hint is type(None): + return {"type": "null"} + if type_hint is Any: + return {} + if type_hint is str: + return {"type": "string"} + if type_hint is int: + return {"type": "integer"} + if type_hint is float: + return {"type": "number"} + if type_hint is bool: + return {"type": "boolean"} + if type_hint is dict: + return {"type": "object", "additionalProperties": {}} + if type_hint is list: + return {"type": "array", "items": {}} + if type_hint is tuple: + return {"type": "array"} + if type_hint is set or type_hint is frozenset: + return {"type": "array", "uniqueItems": True} + if type_hint is bytes or type_hint is bytearray: + return {"type": "string", "format": "byte"} + + origin = get_origin(type_hint) + + if origin is Literal: + literal_values = get_args(type_hint) + if len(literal_values) == 1: + return {"const": literal_values[0]} + return {"enum": list(literal_values)} + + if ( + origin is Union + or (hasattr(origin, "__name__") and origin.__name__ == "UnionType") + or str(origin) == "|" + ): + types = get_args(type_hint) + if len(types) == 2 and type(None) in types: + other_type = next(t for t in types if t is not type(None)) + schema = _python_type_to_json_schema(other_type) + return {"oneOf": [{"type": "null"}, schema]} + return {"anyOf": [_python_type_to_json_schema(t) for t in types]} + + if origin is list: + args = get_args(type_hint) + if not args: + return {"type": "array", "items": {}} + item_type = args[0] + return {"type": "array", "items": _python_type_to_json_schema(item_type)} + if origin is tuple: + types = get_args(type_hint) + if not types: + return {"type": "array"} + if len(types) == 2 and types[1] is ...: + return {"type": "array", "items": _python_type_to_json_schema(types[0])} + return { + "type": "array", + "prefixItems": [_python_type_to_json_schema(t) for t in types], + "minItems": len(types), + "maxItems": len(types), + } + if origin is set or origin is frozenset: + args = get_args(type_hint) + if not args: + return {"type": "array", "uniqueItems": True} + item_type = args[0] + return { + "type": "array", + "uniqueItems": True, + "items": _python_type_to_json_schema(item_type), + } + + if origin is dict: + args = get_args(type_hint) + if not args: + return {"type": "object", "additionalProperties": {}} + key_type, value_type = args + if key_type is not str: + raise ValueError("JSON Schema only supports string keys in objects") + schema = { + "type": "object", + "additionalProperties": _python_type_to_json_schema(value_type), + } + return schema + + if inspect.isclass(type_hint) and issubclass(type_hint, Enum): + enum_values = [item.value for item in type_hint] + return {"enum": enum_values} + + if inspect.isclass(type_hint) and hasattr(type_hint, "__annotations__"): + properties = {} + required = [] + + hints = get_type_hints(type_hint) + for field_name, field_type in hints.items(): + properties[field_name] = _python_type_to_json_schema(field_type) + if hasattr(type_hint, "__total__"): + if type_hint.__total__: + required.append(field_name) + elif ( + not hasattr(type_hint, "__dataclass_fields__") + or not type_hint.__dataclass_fields__[field_name].default + ): + required.append(field_name) + + schema = {"type": "object", "properties": properties} + if required: + schema["required"] = required + return schema + + return {} + + +def traverse(json_obj: Any, func: Callable, is_root: Callable[..., bool]) -> Any: + """ + Traverse a JSON object and apply a function to each element that satisfies the is_root condition. + """ + if is_root(json_obj): + return func(json_obj) + elif isinstance(json_obj, dict): + new_obj = {} + for key, value in json_obj.items(): + new_obj[key] = traverse(value, func, is_root) + return new_obj + elif isinstance(json_obj, (list, tuple)): + new_obj = [] + for item in json_obj: + new_obj.append(traverse(item, func, is_root)) + return new_obj + else: + return json_obj + + +async def async_traverse( + json_obj: Any, + func: Callable[..., Coroutine[Any, Any, Any]], + is_root: Callable[..., bool], +) -> Any: + """ + Traverse a JSON object and apply a async function to each element that satisfies the is_root condition. + """ + if is_root(json_obj): + return await func(json_obj) + elif isinstance(json_obj, dict): + new_obj = {} + for key, value in json_obj.items(): + new_obj[key] = await async_traverse(value, func, is_root) + return new_obj + elif isinstance(json_obj, (list, tuple)): + new_obj = [] + for item in json_obj: + new_obj.append(await async_traverse(item, func, is_root)) + return new_obj + else: + return json_obj + + +def value_is_file(api_info: dict) -> bool: + info = _json_schema_to_python_type(api_info, api_info.get("$defs")) + return any(file_data_format in info for file_data_format in FILE_DATA_FORMATS) + + +def is_filepath(s) -> bool: + """ + Check if the given value is a valid str or Path filepath on the local filesystem, e.g. "path/to/file". + """ + return isinstance(s, (str, Path)) and Path(s).exists() and Path(s).is_file() + + +def is_file_obj(d) -> bool: + """ + Check if the given value is a valid FileData object dictionary in versions of Gradio<=4.20, e.g. + { + "path": "path/to/file", + } + """ + return isinstance(d, dict) and "path" in d and isinstance(d["path"], str) + + +def is_file_obj_with_meta(d) -> bool: + """ + Check if the given value is a valid FileData object dictionary in newer versions of Gradio + where the file objects include a specific "meta" key, e.g. + { + "path": "path/to/file", + "meta": {"_type: "gradio.FileData"} + } + """ + return ( + isinstance(d, dict) + and "path" in d + and isinstance(d["path"], str) + and "meta" in d + and d["meta"].get("_type", "") == "gradio.FileData" + ) + + +def is_file_obj_with_url(d) -> bool: + """ + Check if the given value is a valid FileData object dictionary in newer versions of Gradio + where the file objects include a specific "meta" key, and ALSO include a "url" key, e.g. + { + "path": "path/to/file", + "url": "/file=path/to/file", + "meta": {"_type: "gradio.FileData"} + } + """ + return is_file_obj_with_meta(d) and "url" in d and isinstance(d["url"], str) + + +SKIP_COMPONENTS = { + "state", + "row", + "column", + "tabs", + "tab", + "tabitem", + "box", + "form", + "accordion", + "group", + "interpretation", + "dataset", + "sidebar", +} + + +def handle_file(filepath_or_url: str | Path): + s = str(filepath_or_url) + data = {"path": s, "meta": {"_type": "gradio.FileData"}} + if is_http_url_like(s): + return {**data, "orig_name": s.split("/")[-1], "url": s} + elif Path(s).exists(): + return {**data, "orig_name": Path(s).name} + else: + raise ValueError( + f"File {s} does not exist on local filesystem and is not a valid URL." + ) + + +def file(filepath_or_url: str | Path): + warnings.warn( + "file() is deprecated and will be removed in a future version. Use handle_file() instead." + ) + return handle_file(filepath_or_url) + + +def construct_args( + parameters_info: list[ParameterInfo] | None, args: tuple, kwargs: dict +) -> list: + class _Keywords(Enum): + NO_VALUE = "NO_VALUE" # Used as a sentinel to determine if nothing is provided as a parameter for an argument + + _args = list(args) + if parameters_info is None: + if kwargs: + raise ValueError( + "This endpoint does not support key-word arguments Please click on 'view API' in the footer of the Gradio app to see usage." + ) + return _args + num_args = len(args) + _args = _args + [_Keywords.NO_VALUE] * (len(parameters_info) - num_args) + + kwarg_arg_mapping = {} + kwarg_names = [] + for index, param_info in enumerate(parameters_info): + if "parameter_name" in param_info: + kwarg_arg_mapping[param_info["parameter_name"]] = index + kwarg_names.append(param_info["parameter_name"]) + else: + kwarg_names.append(f"argument {index}") + if ( + param_info.get("parameter_has_default", False) + and _args[index] == _Keywords.NO_VALUE + ): + _args[index] = param_info.get("parameter_default") + + for key, value in kwargs.items(): + if key in kwarg_arg_mapping: + if kwarg_arg_mapping[key] < num_args: + raise TypeError( + f"Parameter `{key}` is already set as a positional argument. Please click on 'view API' in the footer of the Gradio app to see usage." + ) + else: + _args[kwarg_arg_mapping[key]] = value + else: + raise TypeError( + f"Parameter `{key}` is not a valid key-word argument. Please click on 'view API' in the footer of the Gradio app to see usage." + ) + + if _Keywords.NO_VALUE in _args: + raise TypeError( + f"No value provided for required argument: {kwarg_names[_args.index(_Keywords.NO_VALUE)]}" + ) + + return _args diff --git a/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8a2f639061cc4a203f7109d8335d28076442c61d --- /dev/null +++ b/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/METADATA @@ -0,0 +1,202 @@ +Metadata-Version: 2.4 +Name: h11 +Version: 0.16.0 +Summary: A pure-Python, bring-your-own-I/O implementation of HTTP/1.1 +Home-page: https://github.com/python-hyper/h11 +Author: Nathaniel J. Smith +Author-email: njs@pobox.com +License: MIT +Classifier: Development Status :: 3 - Alpha +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +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: Topic :: Internet :: WWW/HTTP +Classifier: Topic :: System :: Networking +Requires-Python: >=3.8 +License-File: LICENSE.txt +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: requires-python +Dynamic: summary + +h11 +=== + +.. image:: https://travis-ci.org/python-hyper/h11.svg?branch=master + :target: https://travis-ci.org/python-hyper/h11 + :alt: Automated test status + +.. image:: https://codecov.io/gh/python-hyper/h11/branch/master/graph/badge.svg + :target: https://codecov.io/gh/python-hyper/h11 + :alt: Test coverage + +.. image:: https://readthedocs.org/projects/h11/badge/?version=latest + :target: http://h11.readthedocs.io/en/latest/?badge=latest + :alt: Documentation Status + +This is a little HTTP/1.1 library written from scratch in Python, +heavily inspired by `hyper-h2 `_. + +It's a "bring-your-own-I/O" library; h11 contains no IO code +whatsoever. This means you can hook h11 up to your favorite network +API, and that could be anything you want: synchronous, threaded, +asynchronous, or your own implementation of `RFC 6214 +`_ -- h11 won't judge you. +(Compare this to the current state of the art, where every time a `new +network API `_ comes along then someone +gets to start over reimplementing the entire HTTP protocol from +scratch.) Cory Benfield made an `excellent blog post describing the +benefits of this approach +`_, or if you like video +then here's his `PyCon 2016 talk on the same theme +`_. + +This also means that h11 is not immediately useful out of the box: +it's a toolkit for building programs that speak HTTP, not something +that could directly replace ``requests`` or ``twisted.web`` or +whatever. But h11 makes it much easier to implement something like +``requests`` or ``twisted.web``. + +At a high level, working with h11 goes like this: + +1) First, create an ``h11.Connection`` object to track the state of a + single HTTP/1.1 connection. + +2) When you read data off the network, pass it to + ``conn.receive_data(...)``; you'll get back a list of objects + representing high-level HTTP "events". + +3) When you want to send a high-level HTTP event, create the + corresponding "event" object and pass it to ``conn.send(...)``; + this will give you back some bytes that you can then push out + through the network. + +For example, a client might instantiate and then send a +``h11.Request`` object, then zero or more ``h11.Data`` objects for the +request body (e.g., if this is a POST), and then a +``h11.EndOfMessage`` to indicate the end of the message. Then the +server would then send back a ``h11.Response``, some ``h11.Data``, and +its own ``h11.EndOfMessage``. If either side violates the protocol, +you'll get a ``h11.ProtocolError`` exception. + +h11 is suitable for implementing both servers and clients, and has a +pleasantly symmetric API: the events you send as a client are exactly +the ones that you receive as a server and vice-versa. + +`Here's an example of a tiny HTTP client +`_ + +It also has `a fine manual `_. + +FAQ +--- + +*Whyyyyy?* + +I wanted to play with HTTP in `Curio +`__ and `Trio +`__, which at the time didn't have any +HTTP libraries. So I thought, no big deal, Python has, like, a dozen +different implementations of HTTP, surely I can find one that's +reusable. I didn't find one, but I did find Cory's call-to-arms +blog-post. So I figured, well, fine, if I have to implement HTTP from +scratch, at least I can make sure no-one *else* has to ever again. + +*Should I use it?* + +Maybe. You should be aware that it's a very young project. But, it's +feature complete and has an exhaustive test-suite and complete docs, +so the next step is for people to try using it and see how it goes +:-). If you do then please let us know -- if nothing else we'll want +to talk to you before making any incompatible changes! + +*What are the features/limitations?* + +Roughly speaking, it's trying to be a robust, complete, and non-hacky +implementation of the first "chapter" of the HTTP/1.1 spec: `RFC 7230: +HTTP/1.1 Message Syntax and Routing +`_. That is, it mostly focuses on +implementing HTTP at the level of taking bytes on and off the wire, +and the headers related to that, and tries to be anal about spec +conformance. It doesn't know about higher-level concerns like URL +routing, conditional GETs, cross-origin cookie policies, or content +negotiation. But it does know how to take care of framing, +cross-version differences in keep-alive handling, and the "obsolete +line folding" rule, so you can focus your energies on the hard / +interesting parts for your application, and it tries to support the +full specification in the sense that any useful HTTP/1.1 conformant +application should be able to use h11. + +It's pure Python, and has no dependencies outside of the standard +library. + +It has a test suite with 100.0% coverage for both statements and +branches. + +Currently it supports Python 3 (testing on 3.8-3.12) and PyPy 3. +The last Python 2-compatible version was h11 0.11.x. +(Originally it had a Cython wrapper for `http-parser +`_ and a beautiful nested state +machine implemented with ``yield from`` to postprocess the output. But +I had to take these out -- the new *parser* needs fewer lines-of-code +than the old *parser wrapper*, is written in pure Python, uses no +exotic language syntax, and has more features. It's sad, really; that +old state machine was really slick. I just need a few sentences here +to mourn that.) + +I don't know how fast it is. I haven't benchmarked or profiled it yet, +so it's probably got a few pointless hot spots, and I've been trying +to err on the side of simplicity and robustness instead of +micro-optimization. But at the architectural level I tried hard to +avoid fundamentally bad decisions, e.g., I believe that all the +parsing algorithms remain linear-time even in the face of pathological +input like slowloris, and there are no byte-by-byte loops. (I also +believe that it maintains bounded memory usage in the face of +arbitrary/pathological input.) + +The whole library is ~800 lines-of-code. You can read and understand +the whole thing in less than an hour. Most of the energy invested in +this so far has been spent on trying to keep things simple by +minimizing special-cases and ad hoc state manipulation; even though it +is now quite small and simple, I'm still annoyed that I haven't +figured out how to make it even smaller and simpler. (Unfortunately, +HTTP does not lend itself to simplicity.) + +The API is ~feature complete and I don't expect the general outlines +to change much, but you can't judge an API's ergonomics until you +actually document and use it, so I'd expect some changes in the +details. + +*How do I try it?* + +.. code-block:: sh + + $ pip install h11 + $ git clone git@github.com:python-hyper/h11 + $ cd h11/examples + $ python basic-client.py + +and go from there. + +*License?* + +MIT + +*Code of conduct?* + +Contributors are requested to follow our `code of conduct +`_ in +all project spaces. diff --git a/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..43bafd33bdd5a47bcd27930886cfd95e3fd92562 --- /dev/null +++ b/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/RECORD @@ -0,0 +1,29 @@ +h11-0.16.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +h11-0.16.0.dist-info/METADATA,sha256=KPMmCYrAn8unm48YD5YIfIQf4kViFct7hyqcfVzRnWQ,8348 +h11-0.16.0.dist-info/RECORD,, +h11-0.16.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91 +h11-0.16.0.dist-info/licenses/LICENSE.txt,sha256=N9tbuFkm2yikJ6JYZ_ELEjIAOuob5pzLhRE4rbjm82E,1124 +h11-0.16.0.dist-info/top_level.txt,sha256=F7dC4jl3zeh8TGHEPaWJrMbeuoWbS379Gwdi-Yvdcis,4 +h11/__init__.py,sha256=iO1KzkSO42yZ6ffg-VMgbx_ZVTWGUY00nRYEWn-s3kY,1507 +h11/__pycache__/__init__.cpython-310.pyc,, +h11/__pycache__/_abnf.cpython-310.pyc,, +h11/__pycache__/_connection.cpython-310.pyc,, +h11/__pycache__/_events.cpython-310.pyc,, +h11/__pycache__/_headers.cpython-310.pyc,, +h11/__pycache__/_readers.cpython-310.pyc,, +h11/__pycache__/_receivebuffer.cpython-310.pyc,, +h11/__pycache__/_state.cpython-310.pyc,, +h11/__pycache__/_util.cpython-310.pyc,, +h11/__pycache__/_version.cpython-310.pyc,, +h11/__pycache__/_writers.cpython-310.pyc,, +h11/_abnf.py,sha256=ybixr0xsupnkA6GFAyMubuXF6Tc1lb_hF890NgCsfNc,4815 +h11/_connection.py,sha256=k9YRVf6koZqbttBW36xSWaJpWdZwa-xQVU9AHEo9DuI,26863 +h11/_events.py,sha256=I97aXoal1Wu7dkL548BANBUCkOIbe-x5CioYA9IBY14,11792 +h11/_headers.py,sha256=P7D-lBNxHwdLZPLimmYwrPG-9ZkjElvvJZJdZAgSP-4,10412 +h11/_readers.py,sha256=a4RypORUCC3d0q_kxPuBIM7jTD8iLt5X91TH0FsduN4,8590 +h11/_receivebuffer.py,sha256=xrspsdsNgWFxRfQcTXxR8RrdjRXXTK0Io5cQYWpJ1Ws,5252 +h11/_state.py,sha256=_5LG_BGR8FCcFQeBPH-TMHgm_-B-EUcWCnQof_9XjFE,13231 +h11/_util.py,sha256=LWkkjXyJaFlAy6Lt39w73UStklFT5ovcvo0TkY7RYuk,4888 +h11/_version.py,sha256=GVSsbPSPDcOuF6ptfIiXnVJoaEm3ygXbMnqlr_Giahw,686 +h11/_writers.py,sha256=oFKm6PtjeHfbj4RLX7VB7KDc1gIY53gXG3_HR9ltmTA,5081 +h11/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7 diff --git a/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1eb3c49d99559863120cfb8433fc8738fba43ba9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (78.1.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/licenses/LICENSE.txt b/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..8f080eae848f759c9173bfc0c79506357ebe5090 --- /dev/null +++ b/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/licenses/LICENSE.txt @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Nathaniel J. Smith and other contributors + +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/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..0d24def711344ec6f4da2108f7d5c9261eb35f8b --- /dev/null +++ b/venv/lib/python3.10/site-packages/h11-0.16.0.dist-info/top_level.txt @@ -0,0 +1 @@ +h11 diff --git a/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/LICENSE b/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3bfef5bae9b48c334acf426d5b7f21bc1913aab9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/LICENSE @@ -0,0 +1,26 @@ +Portions of this software are licensed as follows: + +* All content that resides under the "enterprise/" directory of this repository, if that directory exists, is licensed under the license defined in "enterprise/LICENSE". +* Content outside of the above mentioned directories or restrictions above is available under the MIT license as defined below. +--- +MIT License + +Copyright (c) 2023 Berri AI + +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/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/METADATA b/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ae332c184c3829c8a5ed8fedd2a3fb92bb01ee35 --- /dev/null +++ b/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/METADATA @@ -0,0 +1,515 @@ +Metadata-Version: 2.1 +Name: litellm +Version: 1.74.3 +Summary: Library to easily interface with LLM API providers +License: MIT +Author: BerriAI +Requires-Python: >=3.8, !=2.7.*, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, !=3.6.*, !=3.7.* +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +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 +Provides-Extra: caching +Provides-Extra: extra-proxy +Provides-Extra: proxy +Provides-Extra: utils +Requires-Dist: PyJWT (>=2.8.0,<3.0.0) ; extra == "proxy" +Requires-Dist: aiohttp (>=3.10) +Requires-Dist: apscheduler (>=3.10.4,<4.0.0) ; extra == "proxy" +Requires-Dist: azure-identity (>=1.15.0,<2.0.0) ; extra == "extra-proxy" +Requires-Dist: azure-keyvault-secrets (>=4.8.0,<5.0.0) ; extra == "extra-proxy" +Requires-Dist: backoff ; extra == "proxy" +Requires-Dist: boto3 (==1.34.34) ; extra == "proxy" +Requires-Dist: click +Requires-Dist: cryptography (>=43.0.1,<44.0.0) ; extra == "proxy" +Requires-Dist: diskcache (>=5.6.1,<6.0.0) ; extra == "caching" +Requires-Dist: fastapi (>=0.115.5,<0.116.0) ; extra == "proxy" +Requires-Dist: fastapi-sso (>=0.16.0,<0.17.0) ; extra == "proxy" +Requires-Dist: google-cloud-kms (>=2.21.3,<3.0.0) ; extra == "extra-proxy" +Requires-Dist: gunicorn (>=23.0.0,<24.0.0) ; extra == "proxy" +Requires-Dist: httpx (>=0.23.0) +Requires-Dist: importlib-metadata (>=6.8.0) +Requires-Dist: jinja2 (>=3.1.2,<4.0.0) +Requires-Dist: jsonschema (>=4.22.0,<5.0.0) +Requires-Dist: litellm-enterprise (==0.1.12) ; extra == "proxy" +Requires-Dist: litellm-proxy-extras (==0.2.10) ; extra == "proxy" +Requires-Dist: mcp (==1.10.0) ; (python_version >= "3.10") and (extra == "proxy") +Requires-Dist: numpydoc ; extra == "utils" +Requires-Dist: openai (>=1.68.2) +Requires-Dist: orjson (>=3.9.7,<4.0.0) ; extra == "proxy" +Requires-Dist: prisma (==0.11.0) ; extra == "extra-proxy" +Requires-Dist: pydantic (>=2.5.0,<3.0.0) +Requires-Dist: pynacl (>=1.5.0,<2.0.0) ; extra == "proxy" +Requires-Dist: python-dotenv (>=0.2.0) +Requires-Dist: python-multipart (>=0.0.18,<0.0.19) ; extra == "proxy" +Requires-Dist: pyyaml (>=6.0.1,<7.0.0) ; extra == "proxy" +Requires-Dist: redisvl (>=0.4.1,<0.5.0) ; (python_version >= "3.9" and python_version < "3.14") and (extra == "extra-proxy") +Requires-Dist: resend (>=0.8.0,<0.9.0) ; extra == "extra-proxy" +Requires-Dist: rich (==13.7.1) ; extra == "proxy" +Requires-Dist: rq ; extra == "proxy" +Requires-Dist: tiktoken (>=0.7.0) +Requires-Dist: tokenizers +Requires-Dist: uvicorn (>=0.29.0,<0.30.0) ; extra == "proxy" +Requires-Dist: uvloop (>=0.21.0,<0.22.0) ; (sys_platform != "win32") and (extra == "proxy") +Requires-Dist: websockets (>=13.1.0,<14.0.0) ; extra == "proxy" +Project-URL: Documentation, https://docs.litellm.ai +Project-URL: Homepage, https://litellm.ai +Project-URL: Repository, https://github.com/BerriAI/litellm +Project-URL: documentation, https://docs.litellm.ai +Project-URL: homepage, https://litellm.ai +Project-URL: repository, https://github.com/BerriAI/litellm +Description-Content-Type: text/markdown + +

+ 🚅 LiteLLM +

+

+

+ Deploy to Render + + Deploy on Railway + +

+

Call all LLM APIs using the OpenAI format [Bedrock, Huggingface, VertexAI, TogetherAI, Azure, OpenAI, Groq etc.] +
+

+

LiteLLM Proxy Server (LLM Gateway) | Hosted Proxy (Preview) | Enterprise Tier

+

+ + PyPI Version + + + Y Combinator W23 + + + Whatsapp + + + Discord + + + Slack + +

+ +LiteLLM manages: + +- Translate inputs to provider's `completion`, `embedding`, and `image_generation` endpoints +- [Consistent output](https://docs.litellm.ai/docs/completion/output), text responses will always be available at `['choices'][0]['message']['content']` +- Retry/fallback logic across multiple deployments (e.g. Azure/OpenAI) - [Router](https://docs.litellm.ai/docs/routing) +- Set Budgets & Rate limits per project, api key, model [LiteLLM Proxy Server (LLM Gateway)](https://docs.litellm.ai/docs/simple_proxy) + +[**Jump to LiteLLM Proxy (LLM Gateway) Docs**](https://github.com/BerriAI/litellm?tab=readme-ov-file#openai-proxy---docs)
+[**Jump to Supported LLM Providers**](https://github.com/BerriAI/litellm?tab=readme-ov-file#supported-providers-docs) + +🚨 **Stable Release:** Use docker images with the `-stable` tag. These have undergone 12 hour load tests, before being published. [More information about the release cycle here](https://docs.litellm.ai/docs/proxy/release_cycle) + +Support for more providers. Missing a provider or LLM Platform, raise a [feature request](https://github.com/BerriAI/litellm/issues/new?assignees=&labels=enhancement&projects=&template=feature_request.yml&title=%5BFeature%5D%3A+). + +# Usage ([**Docs**](https://docs.litellm.ai/docs/)) + +> [!IMPORTANT] +> LiteLLM v1.0.0 now requires `openai>=1.0.0`. Migration guide [here](https://docs.litellm.ai/docs/migration) +> LiteLLM v1.40.14+ now requires `pydantic>=2.0.0`. No changes required. + + + Open In Colab + + +```shell +pip install litellm +``` + +```python +from litellm import completion +import os + +## set ENV variables +os.environ["OPENAI_API_KEY"] = "your-openai-key" +os.environ["ANTHROPIC_API_KEY"] = "your-anthropic-key" + +messages = [{ "content": "Hello, how are you?","role": "user"}] + +# openai call +response = completion(model="openai/gpt-4o", messages=messages) + +# anthropic call +response = completion(model="anthropic/claude-sonnet-4-20250514", messages=messages) +print(response) +``` + +### Response (OpenAI Format) + +```json +{ + "id": "chatcmpl-1214900a-6cdd-4148-b663-b5e2f642b4de", + "created": 1751494488, + "model": "claude-sonnet-4-20250514", + "object": "chat.completion", + "system_fingerprint": null, + "choices": [ + { + "finish_reason": "stop", + "index": 0, + "message": { + "content": "Hello! I'm doing well, thank you for asking. I'm here and ready to help with whatever you'd like to discuss or work on. How are you doing today?", + "role": "assistant", + "tool_calls": null, + "function_call": null + } + } + ], + "usage": { + "completion_tokens": 39, + "prompt_tokens": 13, + "total_tokens": 52, + "completion_tokens_details": null, + "prompt_tokens_details": { + "audio_tokens": null, + "cached_tokens": 0 + }, + "cache_creation_input_tokens": 0, + "cache_read_input_tokens": 0 + } +} +``` + +Call any model supported by a provider, with `model=/`. There might be provider-specific details here, so refer to [provider docs for more information](https://docs.litellm.ai/docs/providers) + +## Async ([Docs](https://docs.litellm.ai/docs/completion/stream#async-completion)) + +```python +from litellm import acompletion +import asyncio + +async def test_get_response(): + user_message = "Hello, how are you?" + messages = [{"content": user_message, "role": "user"}] + response = await acompletion(model="openai/gpt-4o", messages=messages) + return response + +response = asyncio.run(test_get_response()) +print(response) +``` + +## Streaming ([Docs](https://docs.litellm.ai/docs/completion/stream)) + +liteLLM supports streaming the model response back, pass `stream=True` to get a streaming iterator in response. +Streaming is supported for all models (Bedrock, Huggingface, TogetherAI, Azure, OpenAI, etc.) + +```python +from litellm import completion +response = completion(model="openai/gpt-4o", messages=messages, stream=True) +for part in response: + print(part.choices[0].delta.content or "") + +# claude sonnet 4 +response = completion('anthropic/claude-sonnet-4-20250514', messages, stream=True) +for part in response: + print(part) +``` + +### Response chunk (OpenAI Format) + +```json +{ + "id": "chatcmpl-fe575c37-5004-4926-ae5e-bfbc31f356ca", + "created": 1751494808, + "model": "claude-sonnet-4-20250514", + "object": "chat.completion.chunk", + "system_fingerprint": null, + "choices": [ + { + "finish_reason": null, + "index": 0, + "delta": { + "provider_specific_fields": null, + "content": "Hello", + "role": "assistant", + "function_call": null, + "tool_calls": null, + "audio": null + }, + "logprobs": null + } + ], + "provider_specific_fields": null, + "stream_options": null, + "citations": null +} +``` + +## Logging Observability ([Docs](https://docs.litellm.ai/docs/observability/callbacks)) + +LiteLLM exposes pre defined callbacks to send data to Lunary, MLflow, Langfuse, DynamoDB, s3 Buckets, Helicone, Promptlayer, Traceloop, Athina, Slack + +```python +from litellm import completion + +## set env variables for logging tools (when using MLflow, no API key set up is required) +os.environ["LUNARY_PUBLIC_KEY"] = "your-lunary-public-key" +os.environ["HELICONE_API_KEY"] = "your-helicone-auth-key" +os.environ["LANGFUSE_PUBLIC_KEY"] = "" +os.environ["LANGFUSE_SECRET_KEY"] = "" +os.environ["ATHINA_API_KEY"] = "your-athina-api-key" + +os.environ["OPENAI_API_KEY"] = "your-openai-key" + +# set callbacks +litellm.success_callback = ["lunary", "mlflow", "langfuse", "athina", "helicone"] # log input/output to lunary, langfuse, supabase, athina, helicone etc + +#openai call +response = completion(model="openai/gpt-4o", messages=[{"role": "user", "content": "Hi 👋 - i'm openai"}]) +``` + +# LiteLLM Proxy Server (LLM Gateway) - ([Docs](https://docs.litellm.ai/docs/simple_proxy)) + +Track spend + Load Balance across multiple projects + +[Hosted Proxy (Preview)](https://docs.litellm.ai/docs/hosted) + +The proxy provides: + +1. [Hooks for auth](https://docs.litellm.ai/docs/proxy/virtual_keys#custom-auth) +2. [Hooks for logging](https://docs.litellm.ai/docs/proxy/logging#step-1---create-your-custom-litellm-callback-class) +3. [Cost tracking](https://docs.litellm.ai/docs/proxy/virtual_keys#tracking-spend) +4. [Rate Limiting](https://docs.litellm.ai/docs/proxy/users#set-rate-limits) + +## 📖 Proxy Endpoints - [Swagger Docs](https://litellm-api.up.railway.app/) + + +## Quick Start Proxy - CLI + +```shell +pip install 'litellm[proxy]' +``` + +### Step 1: Start litellm proxy + +```shell +$ litellm --model huggingface/bigcode/starcoder + +#INFO: Proxy running on http://0.0.0.0:4000 +``` + +### Step 2: Make ChatCompletions Request to Proxy + + +> [!IMPORTANT] +> 💡 [Use LiteLLM Proxy with Langchain (Python, JS), OpenAI SDK (Python, JS) Anthropic SDK, Mistral SDK, LlamaIndex, Instructor, Curl](https://docs.litellm.ai/docs/proxy/user_keys) + +```python +import openai # openai v1.0.0+ +client = openai.OpenAI(api_key="anything",base_url="http://0.0.0.0:4000") # set proxy to base_url +# request sent to model set on litellm proxy, `litellm --model` +response = client.chat.completions.create(model="gpt-3.5-turbo", messages = [ + { + "role": "user", + "content": "this is a test request, write a short poem" + } +]) + +print(response) +``` + +## Proxy Key Management ([Docs](https://docs.litellm.ai/docs/proxy/virtual_keys)) + +Connect the proxy with a Postgres DB to create proxy keys + +```bash +# Get the code +git clone https://github.com/BerriAI/litellm + +# Go to folder +cd litellm + +# Add the master key - you can change this after setup +echo 'LITELLM_MASTER_KEY="sk-1234"' > .env + +# Add the litellm salt key - you cannot change this after adding a model +# It is used to encrypt / decrypt your LLM API Key credentials +# We recommend - https://1password.com/password-generator/ +# password generator to get a random hash for litellm salt key +echo 'LITELLM_SALT_KEY="sk-1234"' >> .env + +source .env + +# Start +docker-compose up +``` + + +UI on `/ui` on your proxy server +![ui_3](https://github.com/BerriAI/litellm/assets/29436595/47c97d5e-b9be-4839-b28c-43d7f4f10033) + +Set budgets and rate limits across multiple projects +`POST /key/generate` + +### Request + +```shell +curl 'http://0.0.0.0:4000/key/generate' \ +--header 'Authorization: Bearer sk-1234' \ +--header 'Content-Type: application/json' \ +--data-raw '{"models": ["gpt-3.5-turbo", "gpt-4", "claude-2"], "duration": "20m","metadata": {"user": "ishaan@berri.ai", "team": "core-infra"}}' +``` + +### Expected Response + +```shell +{ + "key": "sk-kdEXbIqZRwEeEiHwdg7sFA", # Bearer token + "expires": "2023-11-19T01:38:25.838000+00:00" # datetime object +} +``` + +## Supported Providers ([Docs](https://docs.litellm.ai/docs/providers)) + +| Provider | [Completion](https://docs.litellm.ai/docs/#basic-usage) | [Streaming](https://docs.litellm.ai/docs/completion/stream#streaming-responses) | [Async Completion](https://docs.litellm.ai/docs/completion/stream#async-completion) | [Async Streaming](https://docs.litellm.ai/docs/completion/stream#async-streaming) | [Async Embedding](https://docs.litellm.ai/docs/embedding/supported_embedding) | [Async Image Generation](https://docs.litellm.ai/docs/image_generation) | +|-------------------------------------------------------------------------------------|---------------------------------------------------------|---------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------|-------------------------------------------------------------------------------|-------------------------------------------------------------------------| +| [openai](https://docs.litellm.ai/docs/providers/openai) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| [Meta - Llama API](https://docs.litellm.ai/docs/providers/meta_llama) | ✅ | ✅ | ✅ | ✅ | | | +| [azure](https://docs.litellm.ai/docs/providers/azure) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| [AI/ML API](https://docs.litellm.ai/docs/providers/aiml) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| [aws - sagemaker](https://docs.litellm.ai/docs/providers/aws_sagemaker) | ✅ | ✅ | ✅ | ✅ | ✅ | | +| [aws - bedrock](https://docs.litellm.ai/docs/providers/bedrock) | ✅ | ✅ | ✅ | ✅ | ✅ | | +| [google - vertex_ai](https://docs.litellm.ai/docs/providers/vertex) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| [google - palm](https://docs.litellm.ai/docs/providers/palm) | ✅ | ✅ | ✅ | ✅ | | | +| [google AI Studio - gemini](https://docs.litellm.ai/docs/providers/gemini) | ✅ | ✅ | ✅ | ✅ | | | +| [mistral ai api](https://docs.litellm.ai/docs/providers/mistral) | ✅ | ✅ | ✅ | ✅ | ✅ | | +| [cloudflare AI Workers](https://docs.litellm.ai/docs/providers/cloudflare_workers) | ✅ | ✅ | ✅ | ✅ | | | +| [cohere](https://docs.litellm.ai/docs/providers/cohere) | ✅ | ✅ | ✅ | ✅ | ✅ | | +| [anthropic](https://docs.litellm.ai/docs/providers/anthropic) | ✅ | ✅ | ✅ | ✅ | | | +| [empower](https://docs.litellm.ai/docs/providers/empower) | ✅ | ✅ | ✅ | ✅ | +| [huggingface](https://docs.litellm.ai/docs/providers/huggingface) | ✅ | ✅ | ✅ | ✅ | ✅ | | +| [replicate](https://docs.litellm.ai/docs/providers/replicate) | ✅ | ✅ | ✅ | ✅ | | | +| [together_ai](https://docs.litellm.ai/docs/providers/togetherai) | ✅ | ✅ | ✅ | ✅ | | | +| [openrouter](https://docs.litellm.ai/docs/providers/openrouter) | ✅ | ✅ | ✅ | ✅ | | | +| [ai21](https://docs.litellm.ai/docs/providers/ai21) | ✅ | ✅ | ✅ | ✅ | | | +| [baseten](https://docs.litellm.ai/docs/providers/baseten) | ✅ | ✅ | ✅ | ✅ | | | +| [vllm](https://docs.litellm.ai/docs/providers/vllm) | ✅ | ✅ | ✅ | ✅ | | | +| [nlp_cloud](https://docs.litellm.ai/docs/providers/nlp_cloud) | ✅ | ✅ | ✅ | ✅ | | | +| [aleph alpha](https://docs.litellm.ai/docs/providers/aleph_alpha) | ✅ | ✅ | ✅ | ✅ | | | +| [petals](https://docs.litellm.ai/docs/providers/petals) | ✅ | ✅ | ✅ | ✅ | | | +| [ollama](https://docs.litellm.ai/docs/providers/ollama) | ✅ | ✅ | ✅ | ✅ | ✅ | | +| [deepinfra](https://docs.litellm.ai/docs/providers/deepinfra) | ✅ | ✅ | ✅ | ✅ | | | +| [perplexity-ai](https://docs.litellm.ai/docs/providers/perplexity) | ✅ | ✅ | ✅ | ✅ | | | +| [Groq AI](https://docs.litellm.ai/docs/providers/groq) | ✅ | ✅ | ✅ | ✅ | | | +| [Deepseek](https://docs.litellm.ai/docs/providers/deepseek) | ✅ | ✅ | ✅ | ✅ | | | +| [anyscale](https://docs.litellm.ai/docs/providers/anyscale) | ✅ | ✅ | ✅ | ✅ | | | +| [IBM - watsonx.ai](https://docs.litellm.ai/docs/providers/watsonx) | ✅ | ✅ | ✅ | ✅ | ✅ | | +| [voyage ai](https://docs.litellm.ai/docs/providers/voyage) | | | | | ✅ | | +| [xinference [Xorbits Inference]](https://docs.litellm.ai/docs/providers/xinference) | | | | | ✅ | | +| [FriendliAI](https://docs.litellm.ai/docs/providers/friendliai) | ✅ | ✅ | ✅ | ✅ | | | +| [Galadriel](https://docs.litellm.ai/docs/providers/galadriel) | ✅ | ✅ | ✅ | ✅ | | | +| [Novita AI](https://novita.ai/models/llm?utm_source=github_litellm&utm_medium=github_readme&utm_campaign=github_link) | ✅ | ✅ | ✅ | ✅ | | | +| [Featherless AI](https://docs.litellm.ai/docs/providers/featherless_ai) | ✅ | ✅ | ✅ | ✅ | | | +| [Nebius AI Studio](https://docs.litellm.ai/docs/providers/nebius) | ✅ | ✅ | ✅ | ✅ | ✅ | | + +[**Read the Docs**](https://docs.litellm.ai/docs/) + +## Contributing + +Interested in contributing? Contributions to LiteLLM Python SDK, Proxy Server, and LLM integrations are both accepted and highly encouraged! + +**Quick start:** `git clone` → `make install-dev` → `make format` → `make lint` → `make test-unit` + +See our comprehensive [Contributing Guide (CONTRIBUTING.md)](CONTRIBUTING.md) for detailed instructions. + +# Enterprise +For companies that need better security, user management and professional support + +[Talk to founders](https://calendly.com/d/4mp-gd3-k5k/litellm-1-1-onboarding-chat) + +This covers: +- ✅ **Features under the [LiteLLM Commercial License](https://docs.litellm.ai/docs/proxy/enterprise):** +- ✅ **Feature Prioritization** +- ✅ **Custom Integrations** +- ✅ **Professional Support - Dedicated discord + slack** +- ✅ **Custom SLAs** +- ✅ **Secure access with Single Sign-On** + +# Contributing + +We welcome contributions to LiteLLM! Whether you're fixing bugs, adding features, or improving documentation, we appreciate your help. + +## Quick Start for Contributors + +```bash +git clone https://github.com/BerriAI/litellm.git +cd litellm +make install-dev # Install development dependencies +make format # Format your code +make lint # Run all linting checks +make test-unit # Run unit tests +``` + +For detailed contributing guidelines, see [CONTRIBUTING.md](CONTRIBUTING.md). + +## Code Quality / Linting + +LiteLLM follows the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html). + +Our automated checks include: +- **Black** for code formatting +- **Ruff** for linting and code quality +- **MyPy** for type checking +- **Circular import detection** +- **Import safety checks** + +Run all checks locally: +```bash +make lint # Run all linting (matches CI) +make format-check # Check formatting only +``` + +All these checks must pass before your PR can be merged. + + +# Support / talk with founders + +- [Schedule Demo 👋](https://calendly.com/d/4mp-gd3-k5k/berriai-1-1-onboarding-litellm-hosted-version) +- [Community Discord 💭](https://discord.gg/wuPM9dRgDw) +- [Community Slack 💭](https://join.slack.com/share/enQtOTE0ODczMzk2Nzk4NC01YjUxNjY2YjBlYTFmNDRiZTM3NDFiYTM3MzVkODFiMDVjOGRjMmNmZTZkZTMzOWQzZGQyZWIwYjQ0MWExYmE3) +- Our numbers 📞 +1 (770) 8783-106 / ‭+1 (412) 618-6238‬ +- Our emails ✉️ ishaan@berri.ai / krrish@berri.ai + +# Why did we build this + +- **Need for simplicity**: Our code started to get extremely complicated managing & translating calls between Azure, OpenAI and Cohere. + +# Contributors + + + + + + + + + + + + + + + +## Run in Developer mode +### Services +1. Setup .env file in root +2. Run dependant services `docker-compose up db prometheus` + +### Backend +1. (In root) create virtual environment `python -m venv .venv` +2. Activate virtual environment `source .venv/bin/activate` +3. Install dependencies `pip install -e ".[all]"` +4. Start proxy backend `uvicorn litellm.proxy.proxy_server:app --host localhost --port 4000 --reload` + +### Frontend +1. Navigate to `ui/litellm-dashboard` +2. Install dependencies `npm install` +3. Run `npm run dev` to start the dashboard + diff --git a/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/RECORD b/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..5c467c9db2745f90d6c5b1e0118a5d310c14c943 --- /dev/null +++ b/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/RECORD @@ -0,0 +1,1838 @@ +../../../bin/litellm,sha256=D3FFMbtd5vTMDW3T_QJ8jfD-H1W6-IavkIjlqKDeDqU,288 +../../../bin/litellm-proxy,sha256=66lzLH7QZh4sgrtk6bNJF7lvUlIW2wQKaQZFL3wH6gE,291 +litellm-1.74.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +litellm-1.74.3.dist-info/LICENSE,sha256=sXDWv46INd01fgEWgdsCj01R4vsOqJIFj1bgH7ObgnM,1419 +litellm-1.74.3.dist-info/METADATA,sha256=KsOopPMlYr042b17Ie9X9WbmBvYftpQly8YlMBZwnqc,40264 +litellm-1.74.3.dist-info/RECORD,, +litellm-1.74.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +litellm-1.74.3.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88 +litellm-1.74.3.dist-info/entry_points.txt,sha256=6FlGhEboBbpwJLYKVWZmqmdexOJFGgyNGDl9PWM_rwg,89 +litellm/__init__.py,sha256=udU6F4k0OOkoO-C-GKVVdsiue5-cvVKPVD3Uk6jNtsM,46822 +litellm/__pycache__/__init__.cpython-310.pyc,, +litellm/__pycache__/_logging.cpython-310.pyc,, +litellm/__pycache__/_redis.cpython-310.pyc,, +litellm/__pycache__/_service_logger.cpython-310.pyc,, +litellm/__pycache__/_version.cpython-310.pyc,, +litellm/__pycache__/budget_manager.cpython-310.pyc,, +litellm/__pycache__/constants.cpython-310.pyc,, +litellm/__pycache__/cost_calculator.cpython-310.pyc,, +litellm/__pycache__/exceptions.cpython-310.pyc,, +litellm/__pycache__/main.cpython-310.pyc,, +litellm/__pycache__/router.cpython-310.pyc,, +litellm/__pycache__/scheduler.cpython-310.pyc,, +litellm/__pycache__/timeout.cpython-310.pyc,, +litellm/__pycache__/utils.cpython-310.pyc,, +litellm/_logging.py,sha256=ihsLCr87ViZrDuNwPg2Wtu2Srbx89iRBwhtFxpQ95IU,5190 +litellm/_redis.py,sha256=qkdL_CWStepYwDf_3UVhFdmd8fScdKGtFHRLLMD7WV0,14504 +litellm/_service_logger.py,sha256=jsBSCSUiX35RAGj815KXy9B9zb79x8-fdyh14uh99Wo,11546 +litellm/_version.py,sha256=PGgsdOglcnWeG6t49ysrg8Vswv24lMyxdNuPxlwU2UE,126 +litellm/anthropic_interface/__init__.py,sha256=AQ67PAfuKg42pyoKUzh7ei_I2nLbMS3oFeLxYtywauM,108 +litellm/anthropic_interface/__pycache__/__init__.cpython-310.pyc,, +litellm/anthropic_interface/messages/__init__.py,sha256=6nqXfVdDIQpojb4liJ2PsSfq3_RABXTxf07wBHMyPPA,4626 +litellm/anthropic_interface/messages/__pycache__/__init__.cpython-310.pyc,, +litellm/anthropic_interface/readme.md,sha256=ZJqo4HzPIVT6X2pBiE83z9e7HxxWmWK31twFbbhEDPc,2592 +litellm/assistants/__pycache__/main.cpython-310.pyc,, +litellm/assistants/__pycache__/utils.cpython-310.pyc,, +litellm/assistants/main.py,sha256=Tvvwns_W5ibfK9-iGoJA396fSQOEZETj44EcjCMez6I,52774 +litellm/assistants/utils.py,sha256=im5D0fBkAgfQwt9MdPX1XJLp-JSuvdyISjh1s0X3VaY,5779 +litellm/batch_completion/Readme.md,sha256=2Wp90GJazbdovGZSEG7jUhXVTYV5FanzGukCKKrb7o0,636 +litellm/batch_completion/__pycache__/main.cpython-310.pyc,, +litellm/batch_completion/main.py,sha256=J2lRZV_UiyHSJ9I5J_A5a4NEXKBeWLEUKny4f9hKnJk,10463 +litellm/batches/__pycache__/batch_utils.cpython-310.pyc,, +litellm/batches/__pycache__/main.cpython-310.pyc,, +litellm/batches/batch_utils.py,sha256=7EkFbCY3ka2iT-pvrVwazmQ-KamO2RO8isDFkpvGT4I,7117 +litellm/batches/main.py,sha256=B0qH8iu6Oc7DfOlDOGC6Qq4vJN2AB7N6mkrNYXbNhwo,28932 +litellm/budget_manager.py,sha256=t-YTwtpWA9H4M3ooqdESAtZ-aAOzsDYt94avY4HV9b8,8462 +litellm/caching/Readme.md,sha256=hJjbsXpvJuMX4VPE331cMp7fHnafVji2ij9Qf_nMWcA,894 +litellm/caching/__init__.py,sha256=1ODCp1gCZyXrHt1JM1ZVVSpXHPAHV1DRVQpu8qpqsPI,381 +litellm/caching/__pycache__/__init__.cpython-310.pyc,, +litellm/caching/__pycache__/_internal_lru_cache.cpython-310.pyc,, +litellm/caching/__pycache__/base_cache.cpython-310.pyc,, +litellm/caching/__pycache__/caching.cpython-310.pyc,, +litellm/caching/__pycache__/caching_handler.cpython-310.pyc,, +litellm/caching/__pycache__/disk_cache.cpython-310.pyc,, +litellm/caching/__pycache__/dual_cache.cpython-310.pyc,, +litellm/caching/__pycache__/in_memory_cache.cpython-310.pyc,, +litellm/caching/__pycache__/llm_caching_handler.cpython-310.pyc,, +litellm/caching/__pycache__/qdrant_semantic_cache.cpython-310.pyc,, +litellm/caching/__pycache__/redis_cache.cpython-310.pyc,, +litellm/caching/__pycache__/redis_cluster_cache.cpython-310.pyc,, +litellm/caching/__pycache__/redis_semantic_cache.cpython-310.pyc,, +litellm/caching/__pycache__/s3_cache.cpython-310.pyc,, +litellm/caching/_internal_lru_cache.py,sha256=yVMtXSglvmxFJMY6HlJmh1jAKHQtnXkJRijYOPekzPs,794 +litellm/caching/base_cache.py,sha256=kTmPeVoTK_F59IY_M69ZOPYBLQVeDtu9mN8Bi7BUeYc,1409 +litellm/caching/caching.py,sha256=GWteq1QLSq5t-WEcqAQDb1VI6c6Kk-i_q5iMF2sKs9I,32275 +litellm/caching/caching_handler.py,sha256=qgMYOvOceBlvQcGcJEl1NrR3JmEYTzqFG0YW2Z-sxY4,36179 +litellm/caching/disk_cache.py,sha256=_GKPXwM_FYMfLA-Z7rNor4yz_PMfwMHudBAxLWwHMvs,3054 +litellm/caching/dual_cache.py,sha256=goiYoO-8INrCB8X8zRoBEjO6EA-X9WWjAv02IarxYAo,16465 +litellm/caching/in_memory_cache.py,sha256=R_86IG2dkWZvzdFwmJxmIqOe_rEFeg88SI9XbJnCxk8,9011 +litellm/caching/llm_caching_handler.py,sha256=8koNvaEtkJ1ppSTuM3xrjsKkhc-hCCV8vYsLQVUk9sg,1305 +litellm/caching/qdrant_semantic_cache.py,sha256=1KgSC_SeAdqCTG4E-G52l3W2NRBkLdcBGZSGVIw7w6c,15345 +litellm/caching/redis_cache.py,sha256=k0_gpfB5h5tDDgtfWGwxDnjdqQyQxMoGE10pG1VJYRI,47361 +litellm/caching/redis_cluster_cache.py,sha256=_rRO21mendWanAlaHXJeo44mpS0sgeHonV7AUmE2LwA,1949 +litellm/caching/redis_semantic_cache.py,sha256=WL4OjbFx4HTn0diGAdchuw75h9RhkrfIHWSDof6hxY8,16880 +litellm/caching/s3_cache.py,sha256=pukLeS3QvvJ2HgvyU0H6NgHIdTTda0Cx8UeFHltZUUc,5501 +litellm/completion_extras/README.md,sha256=VAYvWGd49Pl2iFm4p0G6Q0sbkqQCBeCtXcQj263S-lc,124 +litellm/completion_extras/__init__.py,sha256=9hTkRTVPHt9xteV1eRkJCcn7zL94LnLWxcg84X8kwG0,103 +litellm/completion_extras/__pycache__/__init__.cpython-310.pyc,, +litellm/completion_extras/litellm_responses_transformation/__init__.py,sha256=kqAAEyncJHvvHgcsnyhDBSdIg9aj6qwkZ-FwR2WQvxo,78 +litellm/completion_extras/litellm_responses_transformation/__pycache__/__init__.cpython-310.pyc,, +litellm/completion_extras/litellm_responses_transformation/__pycache__/handler.cpython-310.pyc,, +litellm/completion_extras/litellm_responses_transformation/__pycache__/transformation.cpython-310.pyc,, +litellm/completion_extras/litellm_responses_transformation/handler.py,sha256=cdRafdfNrpgwBtVU57twE5C2De4_BsvjI3iqE_FDSpg,7861 +litellm/completion_extras/litellm_responses_transformation/transformation.py,sha256=cMUcIJlzjEDtZ8N0bMYJWTu5M2ShU-EeD4dMwLUciAY,26365 +litellm/constants.py,sha256=H1g6O6-2e3P6DLmCadwFH0ELrthpRBobotKBLEKjliE,33307 +litellm/cost.json,sha256=GJEXQcWy9ZvA5DhsPlWnolw-0gK_JG6PQRC67EO6VmQ,108 +litellm/cost_calculator.py,sha256=j_Nmk5TGwKSZZFum10E6_eDCcADuGuPVWMv-9pYLH10,57587 +litellm/endpoints/speech/speech_to_completion_bridge/__pycache__/handler.cpython-310.pyc,, +litellm/endpoints/speech/speech_to_completion_bridge/__pycache__/transformation.cpython-310.pyc,, +litellm/endpoints/speech/speech_to_completion_bridge/handler.py,sha256=yLoSxEV9V7FWz4uQIJclz73oEXx1nwWwUHSKOsOn8xE,4424 +litellm/endpoints/speech/speech_to_completion_bridge/transformation.py,sha256=ppdwVjQrFM8oKGGgLumI6e4V91a7MiH7xt03rSzKUWM,4619 +litellm/exceptions.py,sha256=Z1-JwM0Ec0MmV_6nFNhVmmKPInZQ_ZiGBftWs9_uZzs,29878 +litellm/experimental_mcp_client/Readme.md,sha256=r3ZHZKSGcsZS5JktPuxpZWWvYLD5EvVK1oIZIW2lxRE,103 +litellm/experimental_mcp_client/__init__.py,sha256=PoWVHZDDHIChYzHXTpxvYX2UrV6Rn0NWwn9woKDxLTk,102 +litellm/experimental_mcp_client/__pycache__/__init__.cpython-310.pyc,, +litellm/experimental_mcp_client/__pycache__/client.cpython-310.pyc,, +litellm/experimental_mcp_client/__pycache__/tools.cpython-310.pyc,, +litellm/experimental_mcp_client/client.py,sha256=2czz5IRJA36eGdP4NAvooS2OQOIZUb2b7t6IW6LjKtA,7919 +litellm/experimental_mcp_client/tools.py,sha256=RtCDYzk-4iqgBg4NhdOQAV7cK90dgN_2VVfeEOCjzs8,3657 +litellm/files/__pycache__/main.cpython-310.pyc,, +litellm/files/main.py,sha256=xXwkhT4utDm_FKnTTgreiolyd4_7t-9YOxXZjciZAlw,33438 +litellm/fine_tuning/__pycache__/main.cpython-310.pyc,, +litellm/fine_tuning/main.py,sha256=KQUxAsiBIhtGBs4moaaPOtUw59pe8AiRVCyg-dy9-sc,28804 +litellm/google_genai/Readme.md,sha256=BetnqQ4scR1C0dbhejgOQfa9Z_z1H24IkAFmxyEjMzo,2906 +litellm/google_genai/__init__.py,sha256=RGCA0bOKaXd42fKuITz0P2urjI9hclFamZxwzwqp9Ec,405 +litellm/google_genai/__pycache__/__init__.cpython-310.pyc,, +litellm/google_genai/__pycache__/main.cpython-310.pyc,, +litellm/google_genai/__pycache__/streaming_iterator.cpython-310.pyc,, +litellm/google_genai/adapters/__init__.py,sha256=sQqhwl8-Ggds4MOMQaKofQ4VoQPVKKlToZSQVOvI5Ec,619 +litellm/google_genai/adapters/__pycache__/__init__.cpython-310.pyc,, +litellm/google_genai/adapters/__pycache__/handler.cpython-310.pyc,, +litellm/google_genai/adapters/__pycache__/transformation.cpython-310.pyc,, +litellm/google_genai/adapters/handler.py,sha256=vCAHp08RSEeK2OxSJkEbkUy5yu69YYZdOyM3nxgyouo,5429 +litellm/google_genai/adapters/transformation.py,sha256=ePHGtOuok6sQHtdC--fHQT4m-PYLLgYUnKmx9ISKU_g,25996 +litellm/google_genai/main.py,sha256=ROh6mxmo7c5pdbVfq3faxGZMItFDLpiMx4jhUBSqfmQ,18910 +litellm/google_genai/streaming_iterator.py,sha256=WY8xfCQrexN8jyGU8xFxiwK6CfcGcdhwdw109aiB9NU,5304 +litellm/images/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +litellm/images/__pycache__/__init__.cpython-310.pyc,, +litellm/images/__pycache__/main.cpython-310.pyc,, +litellm/images/__pycache__/utils.cpython-310.pyc,, +litellm/images/main.py,sha256=GSLFB4JUbCesDLxxIyNe5hNwmHL4howUQGqCUauDQ7Y,28126 +litellm/images/utils.py,sha256=0r7UMkecFrqrideqOiW29aGZJQup9xBNpgVeqmwqN04,5303 +litellm/integrations/Readme.md,sha256=0o2TAoAm8ZsLm53-RBLqjpgrUz3ZAhoxwQi6SbMfaV0,137 +litellm/integrations/SlackAlerting/Readme.md,sha256=3mGDy5ZhJOFnGn58w0uthsFyBF1dFbqy78q54uRc80g,2447 +litellm/integrations/SlackAlerting/__pycache__/batching_handler.cpython-310.pyc,, +litellm/integrations/SlackAlerting/__pycache__/budget_alert_types.cpython-310.pyc,, +litellm/integrations/SlackAlerting/__pycache__/hanging_request_check.cpython-310.pyc,, +litellm/integrations/SlackAlerting/__pycache__/slack_alerting.cpython-310.pyc,, +litellm/integrations/SlackAlerting/__pycache__/utils.cpython-310.pyc,, +litellm/integrations/SlackAlerting/batching_handler.py,sha256=g0Ayl1SIKF7odWT9fLGnYLJCxEEbxR8ASEdLzUEpqKs,2250 +litellm/integrations/SlackAlerting/budget_alert_types.py,sha256=bR8ZiXtDl7SMaz9EUBs8uV6VsaucQZjHGlmN6dxK9gw,2501 +litellm/integrations/SlackAlerting/hanging_request_check.py,sha256=kOMs8TLJPDGxioLPPyGjEwj0texEBpbEBJbbS0GZ0SI,6216 +litellm/integrations/SlackAlerting/slack_alerting.py,sha256=565V0v7r9x1ecL4G2pXExwmL4LtoChlpb5NhsZyGpzw,65968 +litellm/integrations/SlackAlerting/utils.py,sha256=Zu9-4RX2Cn4UWgTfRvt6aNIa3JkiRBHGdm9wZWzBHlI,3436 +litellm/integrations/__init__.py,sha256=Il5Q9ATdX8yXqVxtP_nYqUhExzxPC_qk_WXQ_4h0exg,16 +litellm/integrations/__pycache__/__init__.cpython-310.pyc,, +litellm/integrations/__pycache__/additional_logging_utils.cpython-310.pyc,, +litellm/integrations/__pycache__/anthropic_cache_control_hook.cpython-310.pyc,, +litellm/integrations/__pycache__/argilla.cpython-310.pyc,, +litellm/integrations/__pycache__/athina.cpython-310.pyc,, +litellm/integrations/__pycache__/braintrust_logging.cpython-310.pyc,, +litellm/integrations/__pycache__/custom_batch_logger.cpython-310.pyc,, +litellm/integrations/__pycache__/custom_guardrail.cpython-310.pyc,, +litellm/integrations/__pycache__/custom_logger.cpython-310.pyc,, +litellm/integrations/__pycache__/custom_prompt_management.cpython-310.pyc,, +litellm/integrations/__pycache__/custom_sso_handler.cpython-310.pyc,, +litellm/integrations/__pycache__/dynamodb.cpython-310.pyc,, +litellm/integrations/__pycache__/email_alerting.cpython-310.pyc,, +litellm/integrations/__pycache__/galileo.cpython-310.pyc,, +litellm/integrations/__pycache__/greenscale.cpython-310.pyc,, +litellm/integrations/__pycache__/helicone.cpython-310.pyc,, +litellm/integrations/__pycache__/humanloop.cpython-310.pyc,, +litellm/integrations/__pycache__/lago.cpython-310.pyc,, +litellm/integrations/__pycache__/langsmith.cpython-310.pyc,, +litellm/integrations/__pycache__/langtrace.cpython-310.pyc,, +litellm/integrations/__pycache__/literal_ai.cpython-310.pyc,, +litellm/integrations/__pycache__/logfire_logger.cpython-310.pyc,, +litellm/integrations/__pycache__/lunary.cpython-310.pyc,, +litellm/integrations/__pycache__/mlflow.cpython-310.pyc,, +litellm/integrations/__pycache__/openmeter.cpython-310.pyc,, +litellm/integrations/__pycache__/opentelemetry.cpython-310.pyc,, +litellm/integrations/__pycache__/prometheus.cpython-310.pyc,, +litellm/integrations/__pycache__/prometheus_services.cpython-310.pyc,, +litellm/integrations/__pycache__/prompt_layer.cpython-310.pyc,, +litellm/integrations/__pycache__/prompt_management_base.cpython-310.pyc,, +litellm/integrations/__pycache__/s3.cpython-310.pyc,, +litellm/integrations/__pycache__/s3_v2.cpython-310.pyc,, +litellm/integrations/__pycache__/sqs.cpython-310.pyc,, +litellm/integrations/__pycache__/supabase.cpython-310.pyc,, +litellm/integrations/__pycache__/test_httpx.cpython-310.pyc,, +litellm/integrations/__pycache__/traceloop.cpython-310.pyc,, +litellm/integrations/__pycache__/weights_biases.cpython-310.pyc,, +litellm/integrations/_types/__pycache__/open_inference.cpython-310.pyc,, +litellm/integrations/_types/open_inference.py,sha256=Z7PxXw0cY-JuhW8LdtmMMWxHJSCOdn22gYn-saK9usc,10079 +litellm/integrations/additional_logging_utils.py,sha256=j2mpmj1YqNQY6b066mENmSpbk5XcCXnIzQ_lh0FIu6Q,927 +litellm/integrations/agentops/__init__.py,sha256=y9KrQbr5Fir7xyIA8x7Q-yqIWNsERQFH4z_Vot5vgCY,55 +litellm/integrations/agentops/__pycache__/__init__.cpython-310.pyc,, +litellm/integrations/agentops/__pycache__/agentops.cpython-310.pyc,, +litellm/integrations/agentops/agentops.py,sha256=WhnI8wDQmGJ-HAXrjupw1GemONM2hhtGoUpY6ns-XqU,3741 +litellm/integrations/anthropic_cache_control_hook.py,sha256=yqG-8b9UwXaSPA5_S1kGVfbgyd8VC62QVLOQOLNCJtU,5872 +litellm/integrations/argilla.py,sha256=jmvamrrENHyGLHJZGLEwSDu59YDFe-VHJXz8Js45UFE,14289 +litellm/integrations/arize/__pycache__/_utils.cpython-310.pyc,, +litellm/integrations/arize/__pycache__/arize.cpython-310.pyc,, +litellm/integrations/arize/__pycache__/arize_phoenix.cpython-310.pyc,, +litellm/integrations/arize/_utils.py,sha256=NCAbCdIXI_a-O7Mf0NzI2CCW94zuA9Jb7Ufk0iw6_sE,10174 +litellm/integrations/arize/arize.py,sha256=X6hjz0CnJu7KrsC6zf10TE_YNlNcerIJ5suB-blmufw,4734 +litellm/integrations/arize/arize_phoenix.py,sha256=Jsp9RXJihmWkTgvQ7rn17Ye3q03yt7FZlPQAE1NQQ7E,2810 +litellm/integrations/athina.py,sha256=rDW9YPu86OEyZYBPTYu05qQqq1PmuB_7V73Gu-6AZEA,3785 +litellm/integrations/azure_storage/__pycache__/azure_storage.cpython-310.pyc,, +litellm/integrations/azure_storage/azure_storage.py,sha256=fcWBeY5TpR5uRaLE9v6FTICz4WSlRXlTrIInG7ofSQM,15724 +litellm/integrations/braintrust_logging.py,sha256=bX68-qH5PiHAZSuRx-SABrQTh2w-7JSUYwbMK2sTbfI,18280 +litellm/integrations/custom_batch_logger.py,sha256=55tkUy_OfiBLTeiCsKqu8gX55H0EdDRxjx8JGYJk85A,1847 +litellm/integrations/custom_guardrail.py,sha256=8A3-hWa4M9CZ0CKt2psDbTPxjW8fgu0OfHvISFlHO10,17213 +litellm/integrations/custom_logger.py,sha256=kP-iveopWL-JORDaL97yMod5g1JB6AGkuk-qjZKoRHo,15085 +litellm/integrations/custom_prompt_management.py,sha256=E58vLS3PdLp5cd8PPvgva4YmbL_ahWvPDmTTqn3NqcY,1965 +litellm/integrations/custom_sso_handler.py,sha256=DEkfYnQBHH248Ogb9qgk4DVM8p5aOFE6o7lH8GofR10,921 +litellm/integrations/datadog/__pycache__/datadog.cpython-310.pyc,, +litellm/integrations/datadog/__pycache__/datadog_llm_obs.cpython-310.pyc,, +litellm/integrations/datadog/datadog.py,sha256=XxZZoXAnHCd-40JcFyjyZqeKoaBUj5iOgq3Bu3pZRkM,20329 +litellm/integrations/datadog/datadog_llm_obs.py,sha256=rBo48PcAgmmfxZLmQlAvkbaxZ0iXqQK2wFrI-uZKXjI,9689 +litellm/integrations/deepeval/__init__.py,sha256=J8rgUP_fAJ-_8sqhaRXSGNEt8C8LwCVjUhRWauNGUvE,67 +litellm/integrations/deepeval/__pycache__/__init__.cpython-310.pyc,, +litellm/integrations/deepeval/__pycache__/api.cpython-310.pyc,, +litellm/integrations/deepeval/__pycache__/deepeval.cpython-310.pyc,, +litellm/integrations/deepeval/__pycache__/types.cpython-310.pyc,, +litellm/integrations/deepeval/__pycache__/utils.cpython-310.pyc,, +litellm/integrations/deepeval/api.py,sha256=9YgMxZMDFuzNYChv3V59RM7KX96y6ELrrSubhU56-VM,3768 +litellm/integrations/deepeval/deepeval.py,sha256=zAPlUnUZ4vtu9fO29r9614t61Vh6Pik97qlfyFMtiPw,6311 +litellm/integrations/deepeval/types.py,sha256=8mC4U-c0-q_vs7prTB2CW6qg7Qk9fo2jWBijq9TJJvQ,2132 +litellm/integrations/deepeval/utils.py,sha256=2T9vPFhkW0vxWjUR5OXmN33GGKs7WRPWBRcJW3QsXXA,606 +litellm/integrations/dynamodb.py,sha256=fvWlURS4CkTzA7Or3YhF6DgyvYOJEaRFUANWOpJcuxs,3168 +litellm/integrations/email_alerting.py,sha256=zpa6OiqL-HhhWuuyJB067RH1AI9aIykAwQM06rlWJq0,4413 +litellm/integrations/email_templates/__pycache__/email_footer.cpython-310.pyc,, +litellm/integrations/email_templates/__pycache__/key_created_email.cpython-310.pyc,, +litellm/integrations/email_templates/__pycache__/templates.cpython-310.pyc,, +litellm/integrations/email_templates/__pycache__/user_invitation_email.cpython-310.pyc,, +litellm/integrations/email_templates/email_footer.py,sha256=iyt-NCAW86n9OgKsVsLfTS1hUw11s58XiXvzlSu0r0M,371 +litellm/integrations/email_templates/key_created_email.py,sha256=5Z2CNpk4MXgpHU6RawSi6AHUGYZgjQ7CrhVU-s3VUhw,6537 +litellm/integrations/email_templates/templates.py,sha256=aLw_bBXNBImuTN5u7w6Z4_WKBWU_p1zKOOi48-nWhuY,2277 +litellm/integrations/email_templates/user_invitation_email.py,sha256=WEOVy4j6zPhHMUPfKHGLcCBeyw0x08oGoeFhfcRTIuk,5271 +litellm/integrations/galileo.py,sha256=aU-9T0gUq3Tv10KHoYvCdCBDyfuuMIdBfisOkF50cA8,5739 +litellm/integrations/gcs_bucket/Readme.md,sha256=Hh-Zc0Zl7qnWHw4B54advTgJgpGaJHMgXQCAX-zvBWU,591 +litellm/integrations/gcs_bucket/__pycache__/gcs_bucket.cpython-310.pyc,, +litellm/integrations/gcs_bucket/__pycache__/gcs_bucket_base.cpython-310.pyc,, +litellm/integrations/gcs_bucket/gcs_bucket.py,sha256=9iu_81y5nm3pidzAYN7yjKiZ5y3ShvUnfEXfrybV3qU,8810 +litellm/integrations/gcs_bucket/gcs_bucket_base.py,sha256=SIgHfJ9h_kjm9mhMMU1ova-fxQ7TP5HFLSg45dMm2XY,12974 +litellm/integrations/gcs_pubsub/__pycache__/pub_sub.cpython-310.pyc,, +litellm/integrations/gcs_pubsub/pub_sub.py,sha256=7EvwxD0RuC29b8Es1DzI0746CLZZAC9pS5udUXukVq8,7024 +litellm/integrations/greenscale.py,sha256=w1oMxbACBwkdHKTTvbQ6hPaRrOjZq9ZlDavFHoJ-4Kw,2698 +litellm/integrations/helicone.py,sha256=c6OAL23Bc-rqgadcG6Ru8J7uLeDOkLGBm_emC6q-WYU,7014 +litellm/integrations/humanloop.py,sha256=vKis0uPqM5EtvX1AQFs6RXpVvs0l4BLPLnX0H37QknM,6775 +litellm/integrations/lago.py,sha256=rGl7FGsNF3ZC1O0z8c1aAp2C_SkYUiLDbUviXPmWBZQ,6984 +litellm/integrations/langfuse/__pycache__/langfuse.cpython-310.pyc,, +litellm/integrations/langfuse/__pycache__/langfuse_handler.cpython-310.pyc,, +litellm/integrations/langfuse/__pycache__/langfuse_otel.cpython-310.pyc,, +litellm/integrations/langfuse/__pycache__/langfuse_prompt_management.cpython-310.pyc,, +litellm/integrations/langfuse/langfuse.py,sha256=usXMOj_V4a6h9o1muoI58WnVumIWtIy5PqydVQCCQLM,40525 +litellm/integrations/langfuse/langfuse_handler.py,sha256=imVTJS4uDmR0a3590jR8htt0cIp97pa-aVoE5PFFww8,6830 +litellm/integrations/langfuse/langfuse_otel.py,sha256=NHjk_UJMRVG-8woH8cQWFMktICZIf8pqbamzS720ub0,4391 +litellm/integrations/langfuse/langfuse_prompt_management.py,sha256=ZP1JX2ZJrXrBsnarWgclM00PMvNEpchI4ZO3ap_PZ8M,10893 +litellm/integrations/langsmith.py,sha256=7MgjbhisCNDm9MR-nchreoTHpQ6r5Um7QLEPBh-243g,18364 +litellm/integrations/langtrace.py,sha256=AW1CHaNbJg6iVbcXPH6twG7kCqdEgOfhVwGbm859SHQ,4069 +litellm/integrations/literal_ai.py,sha256=9Fe7nAUe8OpEyxlL_Jd5ZU0lIUmSlKAL2rZg5EvLxJc,11761 +litellm/integrations/logfire_logger.py,sha256=JqxsohxGDBeSkmvA3qTDj_Q9Ha3shB-KH5nzE2m-Mnk,6164 +litellm/integrations/lunary.py,sha256=9yV4PlTNA2i4GL84N33aX71z718SFgqcu-o3mNBV1jY,5375 +litellm/integrations/mlflow.py,sha256=8c5vl7p-j6rFyLywNOE889PhhHse9_sfnr4EJi8-s-I,10719 +litellm/integrations/openmeter.py,sha256=bbdmy6hwU1uyiDgq4DaI9sGUObWGJSCLlSSNKCQvMFk,4441 +litellm/integrations/opentelemetry.py,sha256=29eCetLz9Ug2XRqF1Qqpk6GmrshaJK5y8E9UQ9lyoMw,45595 +litellm/integrations/opik/__pycache__/opik.cpython-310.pyc,, +litellm/integrations/opik/__pycache__/utils.cpython-310.pyc,, +litellm/integrations/opik/opik.py,sha256=4nt-PSx8ylXBnkAzWP5T_Avbw1_ZecwOu6zlenmdF_Q,12606 +litellm/integrations/opik/utils.py,sha256=dk4kyk8SCJlkftNvgkSyQWpYj_SqhF6XxAwm-f6joRA,3314 +litellm/integrations/prometheus.py,sha256=v1NE8kg0ro2vUCliorfQRWTNXY8hMBiaIMXdz5rKD1Y,89228 +litellm/integrations/prometheus_helpers/__pycache__/prometheus_api.cpython-310.pyc,, +litellm/integrations/prometheus_helpers/prometheus_api.py,sha256=8C3POSOnBbPIB0lOwcZtIV8WKVIlw_Coqfwe4A8XID4,4585 +litellm/integrations/prometheus_services.py,sha256=dgFAR1b9DEiczfuigzBTXTcV70e3RX_aihbpTxaHuUY,10974 +litellm/integrations/prompt_layer.py,sha256=BsWn3Y3tCsC5lOkQApS3HTA82yN0YLifatZi8PflH6o,3597 +litellm/integrations/prompt_management_base.py,sha256=c3sAsR66NXq07J56yR4G194tIih1D_V6songBnnnoKc,4390 +litellm/integrations/s3.py,sha256=spokdszh3VjHOTn75tmmWD3iAV_mT8N2YHR9QCX89xA,7442 +litellm/integrations/s3_v2.py,sha256=HzCoBJfYoQkDKItIulmpZvGDckZiKssiK03qCloXIvU,18035 +litellm/integrations/sqs.py,sha256=JoEPvynvvIz4p_r7C8nppN-LpfqPufPzJdcjJfJxl0U,10264 +litellm/integrations/supabase.py,sha256=zo80T4fZPMAtxx24NTvq3jAhRdAvJOuVZ12hP5iWL1M,4325 +litellm/integrations/test_httpx.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +litellm/integrations/traceloop.py,sha256=xckhA4T0JHmvIUqDjaN92DDLalx9WuMRkAjm9JIlyjE,5862 +litellm/integrations/vector_store_integrations/__pycache__/base_vector_store.cpython-310.pyc,, +litellm/integrations/vector_store_integrations/__pycache__/bedrock_vector_store.cpython-310.pyc,, +litellm/integrations/vector_store_integrations/base_vector_store.py,sha256=Lp19LzRZppzU0kwnutgYSI8fNuwm-cxNp080QWZS25o,139 +litellm/integrations/vector_store_integrations/bedrock_vector_store.py,sha256=7GoBqswN3LG4HZbeGn-S0t4yBZxm2NWqyuQWOnCJ4Jk,16261 +litellm/integrations/vector_stores/__pycache__/bedrock_vector_store.cpython-310.pyc,, +litellm/integrations/vector_stores/bedrock_vector_store.py,sha256=7GoBqswN3LG4HZbeGn-S0t4yBZxm2NWqyuQWOnCJ4Jk,16261 +litellm/integrations/weights_biases.py,sha256=Lsufv_OAEGcjInC_ERuu4LEWbKxSpbVVFlOvIvLLLzQ,7832 +litellm/litellm_core_utils/README.md,sha256=b-mx4-xwl-cNsqEbYnscz7J8Uaid2sUeals3EIac7EA,629 +litellm/litellm_core_utils/__pycache__/asyncify.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/core_helpers.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/credential_accessor.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/custom_logger_registry.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/dd_tracing.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/default_encoding.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/dot_notation_indexing.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/duration_parser.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/exception_mapping_utils.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/fallback_utils.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/get_litellm_params.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/get_llm_provider_logic.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/get_model_cost_map.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/get_supported_openai_params.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/health_check_utils.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/initialize_dynamic_callback_params.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/json_validation_rule.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/litellm_logging.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/llm_request_utils.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/logging_callback_manager.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/logging_utils.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/mock_functions.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/model_param_helper.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/realtime_streaming.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/redact_messages.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/response_header_helpers.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/rules.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/safe_json_dumps.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/safe_json_loads.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/sensitive_data_masker.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/streaming_chunk_builder_utils.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/streaming_handler.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/thread_pool_executor.cpython-310.pyc,, +litellm/litellm_core_utils/__pycache__/token_counter.cpython-310.pyc,, +litellm/litellm_core_utils/asyncify.py,sha256=5VZgongo61YQ6E_2lla_o7j0O9qhv5mxOsqQg8g1IQM,4001 +litellm/litellm_core_utils/audio_utils/__pycache__/utils.cpython-310.pyc,, +litellm/litellm_core_utils/audio_utils/audio_health_check.wav,sha256=a0MTxznJoHv2ypdRPFJ7XNv8-AQc8DeJd-8TKKz9ZsA,29184 +litellm/litellm_core_utils/audio_utils/utils.py,sha256=G6n6qipKZz0eCPfTQ6e3qauSS4ZvAt6spfjw3jhWXSI,4724 +litellm/litellm_core_utils/core_helpers.py,sha256=-b5PYCwiDVLonKkhD8gsvp9dOJO180Y78-93wx7yaKc,5942 +litellm/litellm_core_utils/credential_accessor.py,sha256=IttjgpAVHJoguZKFm7AwCHWWBrGtqykt73hQmyzwBVM,1265 +litellm/litellm_core_utils/custom_logger_registry.py,sha256=tY1GAmlKgC9mZwVWPGLoe7AksHGU9sGY6uyvrn5FB0o,5404 +litellm/litellm_core_utils/dd_tracing.py,sha256=d865RDub7zrvaZa2QBcn-ukt_cd7jlGuSWanPfbbivY,1865 +litellm/litellm_core_utils/default_encoding.py,sha256=aSr2QhSlQDOkzYN-UMNhzc97KGnWQPEnycfCLDg6gRI,709 +litellm/litellm_core_utils/dot_notation_indexing.py,sha256=Mcde8nS_k7EUM1jB9X54RAtv5Z0f_Q71FuQfLlBfGck,1574 +litellm/litellm_core_utils/duration_parser.py,sha256=k2_Oa3pHkq4C6xJxIu61ImURHb15j4kFCXeM9FoWgys,12549 +litellm/litellm_core_utils/exception_mapping_utils.py,sha256=eQ_AmgtDXEM5c4BrzVmldZzSpu6UTttUc8VCB55aqNI,120660 +litellm/litellm_core_utils/fallback_utils.py,sha256=6wLyryRpNiwQ6Oo9b1sKHN5gWXSSbn0EBNoa8lzw8Ss,2558 +litellm/litellm_core_utils/get_litellm_params.py,sha256=bXEOYLDmZ4V9Uw22L9_MQ2XLFKb0YMTL9-43tpL6ksw,4548 +litellm/litellm_core_utils/get_llm_provider_logic.py,sha256=S6AH0vylmpDhBP6NPD6-hIL0WtaHen7UCtrplwWCPLE,29432 +litellm/litellm_core_utils/get_model_cost_map.py,sha256=fSsE9EUL9v0SbHeYLLre7E0SfZVZVyaJ3H_USPmAmt0,1304 +litellm/litellm_core_utils/get_supported_openai_params.py,sha256=eZ0EZvKAWcqnKlgBCW4-J8z66maszRStF2fl5odkb_w,12953 +litellm/litellm_core_utils/health_check_utils.py,sha256=ACpzkZ9-LfiSbmajjV5l-4WN1nx1JtxnjDbToqsego0,924 +litellm/litellm_core_utils/initialize_dynamic_callback_params.py,sha256=iO3iJ8bjtE8rINTghw-69jfDG2wYOq_8pl7DB8cgRX8,1225 +litellm/litellm_core_utils/json_validation_rule.py,sha256=XJOTIAYp-1ZIfCe_IPXKV1m58z0cFlUxj-0FL_uV_BA,4285 +litellm/litellm_core_utils/litellm_logging.py,sha256=rVpVpMoDuhV0wv72QUoNQGqi6aHg8FvTvPB7k5FUAcY,195667 +litellm/litellm_core_utils/llm_cost_calc/__pycache__/tool_call_cost_tracking.cpython-310.pyc,, +litellm/litellm_core_utils/llm_cost_calc/__pycache__/utils.cpython-310.pyc,, +litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py,sha256=iZHZIlXZJBAg7vHyHpqnntCMk-6c9F10BRCqdOs8PfU,24163 +litellm/litellm_core_utils/llm_cost_calc/utils.py,sha256=PYSq57ABPkvVC0hdn8wZoZFI4IyHWSJCRdf9KNWfaFY,13103 +litellm/litellm_core_utils/llm_request_utils.py,sha256=Uv1UfjI47-pGU1zZkrURYfhSewkOPZXBaMzB8weF21A,2612 +litellm/litellm_core_utils/llm_response_utils/__pycache__/convert_dict_to_response.cpython-310.pyc,, +litellm/litellm_core_utils/llm_response_utils/__pycache__/get_api_base.cpython-310.pyc,, +litellm/litellm_core_utils/llm_response_utils/__pycache__/get_formatted_prompt.cpython-310.pyc,, +litellm/litellm_core_utils/llm_response_utils/__pycache__/get_headers.cpython-310.pyc,, +litellm/litellm_core_utils/llm_response_utils/__pycache__/response_metadata.cpython-310.pyc,, +litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py,sha256=0qQqrG6tGLUAhaSRJrPQ94MB0ypKtfGE2JyT--LMNS4,29966 +litellm/litellm_core_utils/llm_response_utils/get_api_base.py,sha256=tvOIL56dqmOCA5Dm7TGiDxpifPXXs-Bisp479Vp5zh4,4206 +litellm/litellm_core_utils/llm_response_utils/get_formatted_prompt.py,sha256=MXCLiT9DFm0hxMTeNOreeOMeDA0l5dMXzyCMDULAWmA,1653 +litellm/litellm_core_utils/llm_response_utils/get_headers.py,sha256=gS6fqwEu2l0Av5bnVOpPaMBawhaJfkmdNrgGe8teBiM,1966 +litellm/litellm_core_utils/llm_response_utils/response_metadata.py,sha256=B81FecHQ3sk1uG76LAS6gH_o_bCCfJ58sg8Tv40eCec,4656 +litellm/litellm_core_utils/logging_callback_manager.py,sha256=fIiFADOU2X8bck6cUx0Gxy6wqzdM72FHFwpy6GemvaQ,12873 +litellm/litellm_core_utils/logging_utils.py,sha256=Qac-HTgrNt_1MvuCfHQ6Gsk0fWNQJB-CduYzRRyfjR0,5111 +litellm/litellm_core_utils/mock_functions.py,sha256=ectb1tuczOsEQmvr0YDFc-JOoEa0OYmmDSK4MLojv4Y,699 +litellm/litellm_core_utils/model_param_helper.py,sha256=rgxDoX7-lm3w9AOMjOhlpvs1_gd23dxiY45JovuUVHw,6074 +litellm/litellm_core_utils/prompt_templates/__pycache__/common_utils.cpython-310.pyc,, +litellm/litellm_core_utils/prompt_templates/__pycache__/factory.cpython-310.pyc,, +litellm/litellm_core_utils/prompt_templates/__pycache__/image_handling.cpython-310.pyc,, +litellm/litellm_core_utils/prompt_templates/common_utils.py,sha256=UD7liKu01UniTGCMvm87bPPX196dvOjc0SN0FkFesbg,26572 +litellm/litellm_core_utils/prompt_templates/factory.py,sha256=m_vRSKAtsqfibuOH_8c3-yQK-2WEKpAzr87hDW0Grh0,156168 +litellm/litellm_core_utils/prompt_templates/image_handling.py,sha256=gy6R_4KuRMAJp__iDqeUSKUqhqyMhgjzr_T69ULn2X0,2458 +litellm/litellm_core_utils/realtime_streaming.py,sha256=ii5Ps_5YfRL3XC1S-sxWRrdGwynMSRiC1w2-jp2-WFY,8882 +litellm/litellm_core_utils/redact_messages.py,sha256=n6Ej4pytssCIUTlQlVq9zi_DrE4p2TsJz9XtOyX1_To,7126 +litellm/litellm_core_utils/response_header_helpers.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +litellm/litellm_core_utils/rules.py,sha256=LQFmbsIjwVNUcdd4SfMOwc0x7Y6dIgxYVsDdaBS3fT4,2055 +litellm/litellm_core_utils/safe_json_dumps.py,sha256=3ghybDa_bs2DJa89B9kVtadgvwB28QAWGbLCX7YCpAE,1922 +litellm/litellm_core_utils/safe_json_loads.py,sha256=L8F2PK4ugSRI41Y0CsW3p0Zo_Uz35AuZJcBiDxRkHp8,341 +litellm/litellm_core_utils/sensitive_data_masker.py,sha256=kTyCL2F0kDpsOxavw81fsUdjGTWnC0HXm1Wyl44gnBA,2669 +litellm/litellm_core_utils/specialty_caches/__pycache__/dynamic_logging_cache.cpython-310.pyc,, +litellm/litellm_core_utils/specialty_caches/dynamic_logging_cache.py,sha256=bY63-7lhxR7yDCd4y3T6lQ7mJNRKyrVnQWENhyBY6k4,2929 +litellm/litellm_core_utils/streaming_chunk_builder_utils.py,sha256=DiCujdsYmUV6e8LlQeX2_ZZp2ofqkI-Qtm1wXzMsFXM,23782 +litellm/litellm_core_utils/streaming_handler.py,sha256=-TQ9irooe-YU1YZJGsNnioHs__QPdk5quLEuXMoeQos,83214 +litellm/litellm_core_utils/thread_pool_executor.py,sha256=cbp9njlImGgO9XsON-jhX6o1DFJLJ5aNcjbz1XaTYkk,154 +litellm/litellm_core_utils/token_counter.py,sha256=_DZe36ILZbelMPh8gZyhXMODHd0zxewzNVprEX1d4WQ,25949 +litellm/litellm_core_utils/tokenizers/9b5ad71b2ce5302211f9c61530b329a4922fc6a4,sha256=Ijkht27pm96ZW3_3OFE-7xAPtR0YyTWXoRO8_-hlsqc,1681126 +litellm/litellm_core_utils/tokenizers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +litellm/litellm_core_utils/tokenizers/__pycache__/__init__.cpython-310.pyc,, +litellm/litellm_core_utils/tokenizers/anthropic_tokenizer.json,sha256=wkFzffJLTn98mvT9zuKaDKkD3LKIqLdTvDRqMJKRF2c,1774213 +litellm/litellm_core_utils/tokenizers/ec7223a39ce59f226a68acc30dc1af2788490e15,sha256=lLXKff9NAHZ7wlb90bJ-Wxc2HXuKX5aFR_nyPrcNIGk,836186 +litellm/litellm_core_utils/tokenizers/fb374d419588a4632f3f557e76b4b70aebbca790,sha256=RGqVOMtsNI41FhINfAiwn1fDZJXirP_-WaW_iwz7Gi0,3613922 +litellm/llms/README.md,sha256=x2anx-Tu0i6IWe5LBXshaGGeGXNLScIEl4dQybJ35a4,453 +litellm/llms/__init__.py,sha256=XtxylHXE_Nq0-04aWsm-aAXo3IxQjhOctuu9xuIcIYk,1201 +litellm/llms/__pycache__/__init__.cpython-310.pyc,, +litellm/llms/__pycache__/base.cpython-310.pyc,, +litellm/llms/__pycache__/baseten.cpython-310.pyc,, +litellm/llms/__pycache__/custom_llm.cpython-310.pyc,, +litellm/llms/__pycache__/maritalk.cpython-310.pyc,, +litellm/llms/__pycache__/ollama_chat.cpython-310.pyc,, +litellm/llms/__pycache__/volcengine.cpython-310.pyc,, +litellm/llms/ai21/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/ai21/chat/transformation.py,sha256=A6SMbp06N-El32NrhjS9dM0o5R4VtC4Yc0xv7NPRlKI,1913 +litellm/llms/aiohttp_openai/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/aiohttp_openai/chat/transformation.py,sha256=py-4q9sAOE3r7XO-a5w9048xFbEuo5hQlEvA3qniGU8,2635 +litellm/llms/anthropic/__init__.py,sha256=r33GJt69DYnwY9T9HUwytDSW_LdiuErHUgiJBAVy7nM,456 +litellm/llms/anthropic/__pycache__/__init__.cpython-310.pyc,, +litellm/llms/anthropic/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/anthropic/__pycache__/cost_calculation.cpython-310.pyc,, +litellm/llms/anthropic/batches/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/anthropic/batches/transformation.py,sha256=c6f_dFv2JtBZVvV9rdJGxbblYiQSIrIWutzCZh2ouV8,2633 +litellm/llms/anthropic/chat/__init__.py,sha256=p3BuzPEGkpYEHdTEg20fNa45yKOsvjvjMY7VtwumOB8,68 +litellm/llms/anthropic/chat/__pycache__/__init__.cpython-310.pyc,, +litellm/llms/anthropic/chat/__pycache__/handler.cpython-310.pyc,, +litellm/llms/anthropic/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/anthropic/chat/handler.py,sha256=r7pRR0kPFUvl85fbk0EiXy6IqfG7-9NM-7KRAUEfYp0,32369 +litellm/llms/anthropic/chat/transformation.py,sha256=a_yHXwhl7AtRrTl6wtvndlAe6_Asn8e1WyqY5B7DMi8,42360 +litellm/llms/anthropic/common_utils.py,sha256=pjECJFg9uR8wYNlFoa9Xc48phzRdc09QWUjjKesO9pU,9249 +litellm/llms/anthropic/completion/__pycache__/handler.cpython-310.pyc,, +litellm/llms/anthropic/completion/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/anthropic/completion/handler.py,sha256=Bf6BzJOujAbLmCFQI6M0TnVdDJq2_fEd77KUSz_rp_E,151 +litellm/llms/anthropic/completion/transformation.py,sha256=g746Zl386wa3oxXH1-bHXMWpqRn5QT1cF8cML3kse3w,10736 +litellm/llms/anthropic/cost_calculation.py,sha256=ayC2nqgCuuR-UjqER2e4uCbVjTheIqel-bKsL-EfQdU,1893 +litellm/llms/anthropic/experimental_pass_through/adapters/__init__.py,sha256=fTk6jD_IZZ3N_LTwHjOWFDFWbSzkGBwntOIC5itCWGU,107 +litellm/llms/anthropic/experimental_pass_through/adapters/__pycache__/__init__.cpython-310.pyc,, +litellm/llms/anthropic/experimental_pass_through/adapters/__pycache__/handler.cpython-310.pyc,, +litellm/llms/anthropic/experimental_pass_through/adapters/__pycache__/streaming_iterator.cpython-310.pyc,, +litellm/llms/anthropic/experimental_pass_through/adapters/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/anthropic/experimental_pass_through/adapters/handler.py,sha256=Ey9P1IMFVbRAO6KRiMmM5yRO72R9f94RlMvTcl3yivM,9263 +litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py,sha256=eghlPia_ss-yTWnjuO48TBg2NgDPVqGpYAfZiXoYkHY,15698 +litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py,sha256=JSgGGSyBJG-pXWyWYFCmsauAx7RuvDryB3_zDDCfjGs,22639 +litellm/llms/anthropic/experimental_pass_through/messages/__pycache__/handler.cpython-310.pyc,, +litellm/llms/anthropic/experimental_pass_through/messages/__pycache__/streaming_iterator.cpython-310.pyc,, +litellm/llms/anthropic/experimental_pass_through/messages/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/anthropic/experimental_pass_through/messages/__pycache__/utils.cpython-310.pyc,, +litellm/llms/anthropic/experimental_pass_through/messages/handler.py,sha256=18vkRtYgYgTK5_13LvioMIinij3_6LEegaC5tSelKpQ,7929 +litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py,sha256=jSwXv_EQZWbQtJ-aQCj4gHp8qp--P6IvVYambzEoJuA,4121 +litellm/llms/anthropic/experimental_pass_through/messages/transformation.py,sha256=_tFogZKNCXfUO_ZXdZEviSsx-7iwMIjB30rnYheuU5E,5012 +litellm/llms/anthropic/experimental_pass_through/messages/utils.py,sha256=Fbs-WFSVhvlmQZSlXeoVXjcxxmoDps8krq0bgLNlmBA,2505 +litellm/llms/azure/__pycache__/assistants.cpython-310.pyc,, +litellm/llms/azure/__pycache__/audio_transcriptions.cpython-310.pyc,, +litellm/llms/azure/__pycache__/azure.cpython-310.pyc,, +litellm/llms/azure/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/azure/__pycache__/cost_calculation.cpython-310.pyc,, +litellm/llms/azure/assistants.py,sha256=fZ9e_PI_TsE5nq8eeUnIBKYUXiRS29-X1i-4FQea9ek,33245 +litellm/llms/azure/audio_transcriptions.py,sha256=14ldZPpLaMFul2SMHPZHupw2wmF0eIz70dl0lXPsIwU,7303 +litellm/llms/azure/azure.py,sha256=QtNyDRx6mOiPTQwh9sGNInbW8yzu5c1GKnNSFov7jxA,49660 +litellm/llms/azure/batches/__pycache__/handler.cpython-310.pyc,, +litellm/llms/azure/batches/handler.py,sha256=y8iDfFex_JVIIeqWQSgfroX3BHtdLsfMvJMsNWqiZKQ,7257 +litellm/llms/azure/chat/__pycache__/gpt_transformation.cpython-310.pyc,, +litellm/llms/azure/chat/__pycache__/o_series_handler.cpython-310.pyc,, +litellm/llms/azure/chat/__pycache__/o_series_transformation.cpython-310.pyc,, +litellm/llms/azure/chat/gpt_transformation.py,sha256=RtczKKCErvvfnTEsVbWNI_plJ6P26BuZCOSsBjdmsIw,12570 +litellm/llms/azure/chat/o_series_handler.py,sha256=uEDInGLLlw0LXCFWiOyrKAIP09R-Sknj0F8ygwYR2ZU,2358 +litellm/llms/azure/chat/o_series_transformation.py,sha256=YXCV0MGENRdZnya3K9uN94PYgjNCP2ZbIuHyyIvkzX4,4346 +litellm/llms/azure/common_utils.py,sha256=-4Wz7i8WpHSCr3A8DEvaiJ8NBC1yTB2od0Ay-xVJLes,25192 +litellm/llms/azure/completion/__pycache__/handler.cpython-310.pyc,, +litellm/llms/azure/completion/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/azure/completion/handler.py,sha256=zVjQQLo2gdiPW-SALV9BRtre9lRGD1EDSP2Tq5tVdVY,14297 +litellm/llms/azure/completion/transformation.py,sha256=sqflnFxPxJyqCOAcnApocEUd1HQyPAL-0a_An864hO4,2501 +litellm/llms/azure/cost_calculation.py,sha256=L0YNJ_YoiCGsDQXUgalSDYHyMcBnTH7-SAWPVUO1WVw,2345 +litellm/llms/azure/files/__pycache__/handler.cpython-310.pyc,, +litellm/llms/azure/files/handler.py,sha256=JtLUlgGhCzgQuKjFCqTXQ46MrkEJqtzdfBl6hll2IGY,10238 +litellm/llms/azure/fine_tuning/__pycache__/handler.cpython-310.pyc,, +litellm/llms/azure/fine_tuning/handler.py,sha256=1LN1WpXWEdq7IYTy-pwJRLrmCpeGST5fSyovHrmgs68,1384 +litellm/llms/azure/image_edit/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/azure/image_edit/transformation.py,sha256=D8kaOVnkFiu6zyUBIKK69BtHKc0fytWxgfaTEsTDJAs,2785 +litellm/llms/azure/image_generation/__init__.py,sha256=zgfuS_3t_ZmYiEsu74g8KfEwZnQYlodaxTPzcoTYcnI,1065 +litellm/llms/azure/image_generation/__pycache__/__init__.cpython-310.pyc,, +litellm/llms/azure/image_generation/__pycache__/dall_e_2_transformation.cpython-310.pyc,, +litellm/llms/azure/image_generation/__pycache__/dall_e_3_transformation.cpython-310.pyc,, +litellm/llms/azure/image_generation/__pycache__/gpt_transformation.cpython-310.pyc,, +litellm/llms/azure/image_generation/dall_e_2_transformation.py,sha256=N7o9W5qtdx_MjxTkXQ765B03iqUJdp1wJo70LNKILSI,217 +litellm/llms/azure/image_generation/dall_e_3_transformation.py,sha256=DGB7a7dmMw7AawmsR3oRJRbDkXto9cbTBOIPd5NVvYg,217 +litellm/llms/azure/image_generation/gpt_transformation.py,sha256=C84QBTapyTIvxW2zqvHAzNPSTEK4dI_YbtCjvvntNWQ,211 +litellm/llms/azure/realtime/__pycache__/handler.cpython-310.pyc,, +litellm/llms/azure/realtime/handler.py,sha256=OglK6PYmh7cm1_amJKvF_goc9Ehg6731NqrBZqS3k7I,2659 +litellm/llms/azure/responses/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/azure/responses/transformation.py,sha256=2ape0tyrugEJLcLkud83nJEqgh-VLoycXPliUR4eRnI,6676 +litellm/llms/azure/vector_stores/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/azure/vector_stores/transformation.py,sha256=bD0RQdMcBQTNxIOzetYaKcY5u4PEHpOcDvRQWHrObT4,846 +litellm/llms/azure_ai/README.md,sha256=BpCiNpixdtsvcCxvj1IKEsZDYweh2gQMucXXy1FwHTE,49 +litellm/llms/azure_ai/chat/__pycache__/handler.cpython-310.pyc,, +litellm/llms/azure_ai/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/azure_ai/chat/handler.py,sha256=mxrppFXYhGzKvNdyU5k0fScX5DLVWKls_bHfVM_imyY,47 +litellm/llms/azure_ai/chat/transformation.py,sha256=03DBlyTTLErQ6tE4ywGRa30RbNGe0ZyruqhgrIgbCZs,11759 +litellm/llms/azure_ai/embed/__init__.py,sha256=xmXUrnf9zhaSALBJczyupQbNFrrRM7Y9JeXd53obHrk,38 +litellm/llms/azure_ai/embed/__pycache__/__init__.cpython-310.pyc,, +litellm/llms/azure_ai/embed/__pycache__/cohere_transformation.cpython-310.pyc,, +litellm/llms/azure_ai/embed/__pycache__/handler.cpython-310.pyc,, +litellm/llms/azure_ai/embed/cohere_transformation.py,sha256=Gxa0IkES0LrdqPpJqdhqN_iRQiU0NLtTU1EWi9EufOI,3620 +litellm/llms/azure_ai/embed/handler.py,sha256=Pv8_Mns00gvxOCwf9VsfUZ0uKf1EvriSZswKGCd5yC8,10061 +litellm/llms/azure_ai/rerank/__pycache__/handler.cpython-310.pyc,, +litellm/llms/azure_ai/rerank/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/azure_ai/rerank/handler.py,sha256=gQUHLh4Dt4C6-tiSBmlkCDbB9-WlpTXns3P4mqQZ8s4,143 +litellm/llms/azure_ai/rerank/transformation.py,sha256=trEh1LsCc0wcw21U13ziLvAbFohV9OnzdsvVuk0l3QU,3209 +litellm/llms/base.py,sha256=1vqxTZwW4NAdFHCwXTxuimG5CkTMVaH5vyeJiH4t_So,2736 +litellm/llms/base_llm/__init__.py,sha256=a0y2F4u7IdQson8ekrB4-PQA_ef_ltMxBc5MRKwu_IY,575 +litellm/llms/base_llm/__pycache__/__init__.cpython-310.pyc,, +litellm/llms/base_llm/__pycache__/base_model_iterator.cpython-310.pyc,, +litellm/llms/base_llm/__pycache__/base_utils.cpython-310.pyc,, +litellm/llms/base_llm/anthropic_messages/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/base_llm/anthropic_messages/transformation.py,sha256=qbU0-uW01sZApSXVk2S3l874ASUXASckoQAi0VJds7Q,3602 +litellm/llms/base_llm/audio_transcription/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/base_llm/audio_transcription/transformation.py,sha256=IQmF7F81wIKysgubh9KdtMpF2W9revW6x19OiQZGXxU,5161 +litellm/llms/base_llm/base_model_iterator.py,sha256=GMfyYfIN90Z4ViC0MfX2H4DzPZm3AttP55WPWJzYeAQ,6811 +litellm/llms/base_llm/base_utils.py,sha256=GS31U8j-JWye6e823D-WM2LYAH2npgnxubg2wSR265Q,6350 +litellm/llms/base_llm/bridges/__pycache__/completion_transformation.cpython-310.pyc,, +litellm/llms/base_llm/bridges/completion_transformation.py,sha256=tcMfYxJsj4WrPdxD6vacmg_hXOrsGUQNZPas370e8Pw,1719 +litellm/llms/base_llm/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/base_llm/chat/transformation.py,sha256=KOHZw_WaEzN7pUmfuh4y9ZpBXpI2cn5tMA7MGuV-fnQ,13645 +litellm/llms/base_llm/completion/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/base_llm/completion/transformation.py,sha256=WHykEcTcclVg8lpXJE-Cq-mZ9TPNZAUhjfdAVVv4SgE,2179 +litellm/llms/base_llm/embedding/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/base_llm/embedding/transformation.py,sha256=1h8WwqLfZ6bypgqnkE-g6xytsn3Gk1hlNNRoJEUV1a0,2469 +litellm/llms/base_llm/files/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/base_llm/files/transformation.py,sha256=z4iN5USM4Jh-oYaB_j6FXEe-AUr9Mbsk0zQWThXbANs,4212 +litellm/llms/base_llm/google_genai/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/base_llm/google_genai/transformation.py,sha256=uMibItI3ThRX5RWH4uLw-eA7txcQdQGkREpUXKOvmDk,5717 +litellm/llms/base_llm/image_edit/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/base_llm/image_edit/transformation.py,sha256=EHpNIgGfCA_f6IXsJoUVPdFU1N65KtEfAB-HkdXP7xU,3136 +litellm/llms/base_llm/image_generation/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/base_llm/image_generation/transformation.py,sha256=OBRf_RsqKvpOMzE-TXRIVk1Y13dJtId0aEcojW_BWwM,2677 +litellm/llms/base_llm/image_variations/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/base_llm/image_variations/transformation.py,sha256=bjBk10Ed9bhL28AJcBj7uwmfRXnFfwjPRMB3iQCJyJ0,3601 +litellm/llms/base_llm/passthrough/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/base_llm/passthrough/transformation.py,sha256=H3lHuvrJ5JTlCqgLtYr81f4FM-4WajslXeQyWExrqBI,4767 +litellm/llms/base_llm/realtime/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/base_llm/realtime/transformation.py,sha256=cmGk1aNfObS-4E4AoMd91lmNCJr2zRNxoL3mcN0_KPc,2320 +litellm/llms/base_llm/rerank/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/base_llm/rerank/transformation.py,sha256=QgvA7ndy0kkqJM2K_QmwkCI2QnmvFRs1BVi1X7sBwBM,3786 +litellm/llms/base_llm/responses/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/base_llm/responses/transformation.py,sha256=6DIRcjs1hOYYUGRyoSiKIIEFvkA09k7UjPXV4QHZlW0,6063 +litellm/llms/base_llm/vector_store/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/base_llm/vector_store/transformation.py,sha256=kO9ZyULuSUSam7y2PgsY65UFwAxrSc-BXmoCNTy6ug8,2434 +litellm/llms/baseten.py,sha256=Cwrb4-kqjVqKMdJceziNd3iCFs6MqRw6fbqEHJb7L3s,6054 +litellm/llms/bedrock/__pycache__/base_aws_llm.cpython-310.pyc,, +litellm/llms/bedrock/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/bedrock/__pycache__/cost_calculation.cpython-310.pyc,, +litellm/llms/bedrock/base_aws_llm.py,sha256=yOf61lNBobnNXd6uuUq1mO3ft8s8eDctVSYK9z2LVxQ,30114 +litellm/llms/bedrock/chat/__init__.py,sha256=Izse3_i2OeVD3IMA5JrUqZJzk8mmSzagJ1FuiERqrmc,911 +litellm/llms/bedrock/chat/__pycache__/__init__.cpython-310.pyc,, +litellm/llms/bedrock/chat/__pycache__/converse_handler.cpython-310.pyc,, +litellm/llms/bedrock/chat/__pycache__/converse_transformation.cpython-310.pyc,, +litellm/llms/bedrock/chat/__pycache__/invoke_handler.cpython-310.pyc,, +litellm/llms/bedrock/chat/converse_handler.py,sha256=fUKiLh5eCsur4xzyWzhQWEv5V6iELLZvCnDBLQ_8WIk,16469 +litellm/llms/bedrock/chat/converse_like/__pycache__/handler.cpython-310.pyc,, +litellm/llms/bedrock/chat/converse_like/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/bedrock/chat/converse_like/handler.py,sha256=mblVD0ugiiAIgDBGM43XjjWddPAp4M1FFsvlhf0BP7A,137 +litellm/llms/bedrock/chat/converse_like/transformation.py,sha256=n-hBfAFHQRWUJWzmCVfhIdCtg6TFyMwNdR6PnwSxrHY,112 +litellm/llms/bedrock/chat/converse_transformation.py,sha256=ch3LFaCrn8jXz7lxJV9c8-4hFNL1MTVLXpaGszg18SY,40007 +litellm/llms/bedrock/chat/invoke_agent/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/bedrock/chat/invoke_agent/transformation.py,sha256=YGB7fk95qQLahLB5b3XuW3yC2tLyic5xNnjVf7BMNg4,19254 +litellm/llms/bedrock/chat/invoke_handler.py,sha256=q9Sw9zS5VctB97zYDD5FhpUtgeGI_xSb4AB7fyAwYUU,67738 +litellm/llms/bedrock/chat/invoke_transformations/__pycache__/amazon_ai21_transformation.cpython-310.pyc,, +litellm/llms/bedrock/chat/invoke_transformations/__pycache__/amazon_cohere_transformation.cpython-310.pyc,, +litellm/llms/bedrock/chat/invoke_transformations/__pycache__/amazon_deepseek_transformation.cpython-310.pyc,, +litellm/llms/bedrock/chat/invoke_transformations/__pycache__/amazon_llama_transformation.cpython-310.pyc,, +litellm/llms/bedrock/chat/invoke_transformations/__pycache__/amazon_mistral_transformation.cpython-310.pyc,, +litellm/llms/bedrock/chat/invoke_transformations/__pycache__/amazon_nova_transformation.cpython-310.pyc,, +litellm/llms/bedrock/chat/invoke_transformations/__pycache__/amazon_titan_transformation.cpython-310.pyc,, +litellm/llms/bedrock/chat/invoke_transformations/__pycache__/anthropic_claude2_transformation.cpython-310.pyc,, +litellm/llms/bedrock/chat/invoke_transformations/__pycache__/anthropic_claude3_transformation.cpython-310.pyc,, +litellm/llms/bedrock/chat/invoke_transformations/__pycache__/base_invoke_transformation.cpython-310.pyc,, +litellm/llms/bedrock/chat/invoke_transformations/amazon_ai21_transformation.py,sha256=3n3_I9KkHHkGYQji9UENbIX8LJbIkzMSUunE78XwC6E,3509 +litellm/llms/bedrock/chat/invoke_transformations/amazon_cohere_transformation.py,sha256=k6gmSncpnzHsUwjcsHNph8q35LmtO8cuYgJYDAK-FLw,2215 +litellm/llms/bedrock/chat/invoke_transformations/amazon_deepseek_transformation.py,sha256=QHz_lvIbftaAKfvMcnLoI7K-45Xttls4NEs2izQclY4,4959 +litellm/llms/bedrock/chat/invoke_transformations/amazon_llama_transformation.py,sha256=IcKMFKZ2yES7Jin1XFjaXtrpK03KzIR9DqpaQ1etH70,2383 +litellm/llms/bedrock/chat/invoke_transformations/amazon_mistral_transformation.py,sha256=JarAIy0ZzkZbVKz9dgRS9jecwQiEiYuf_MBErU9UPG8,3891 +litellm/llms/bedrock/chat/invoke_transformations/amazon_nova_transformation.py,sha256=_2KnlIfeLY9g8_VqKvu9hfntMmvAwkRW6lu5PTDECEc,3847 +litellm/llms/bedrock/chat/invoke_transformations/amazon_titan_transformation.py,sha256=Oa7ImD0QFvegOFiZbMkNJRU-E5eyRtn1Ag4uNHscrKk,3715 +litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude2_transformation.py,sha256=zriroWSlXJFOdEa1u53kuXgzXT58avVRGIYsKKNjexE,2884 +litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py,sha256=3ckUBtY7apR7e6m0QCDLim0t0FXO1Cl4U7B4r2veB40,3179 +litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py,sha256=b0ud_1xrx2pKHWL8wny3YOOSu6LVzWbET3es6xvUdP4,24288 +litellm/llms/bedrock/common_utils.py,sha256=sbdqCYu8BGRa9h8Ypc55inHuAWPuhRQ8IN8U_mFYrjg,17473 +litellm/llms/bedrock/cost_calculation.py,sha256=WG4d94W8p0euQGsYeShUe61wsN4VDgyyIQNmXa5CK7I,630 +litellm/llms/bedrock/embed/__pycache__/amazon_titan_g1_transformation.cpython-310.pyc,, +litellm/llms/bedrock/embed/__pycache__/amazon_titan_multimodal_transformation.cpython-310.pyc,, +litellm/llms/bedrock/embed/__pycache__/amazon_titan_v2_transformation.cpython-310.pyc,, +litellm/llms/bedrock/embed/__pycache__/cohere_transformation.cpython-310.pyc,, +litellm/llms/bedrock/embed/__pycache__/embedding.cpython-310.pyc,, +litellm/llms/bedrock/embed/amazon_titan_g1_transformation.py,sha256=SCEkAW_ES8hj1-Q1caf3rkdFa1F-gd7Msxi1VtulJxY,2649 +litellm/llms/bedrock/embed/amazon_titan_multimodal_transformation.py,sha256=QtgPfSQsjrF-ZWxa7OMKm_2DaScrMJ6ilEoa0ryf9rU,2877 +litellm/llms/bedrock/embed/amazon_titan_v2_transformation.py,sha256=AEDVYQKr4_oTxfAJe1sDP6TWhelgwTBvdRX0U9RtUK0,3233 +litellm/llms/bedrock/embed/cohere_transformation.py,sha256=5gw1AYxVtAH2efSceKsU_wlhiueSZ8SgvrAH6cUBZuI,1468 +litellm/llms/bedrock/embed/embedding.py,sha256=Ha0leHWXgRa5ELLLwspFOvOp9d0yYT7G6MpZqzEu7zE,17312 +litellm/llms/bedrock/image/__pycache__/amazon_nova_canvas_transformation.cpython-310.pyc,, +litellm/llms/bedrock/image/__pycache__/amazon_stability1_transformation.cpython-310.pyc,, +litellm/llms/bedrock/image/__pycache__/amazon_stability3_transformation.cpython-310.pyc,, +litellm/llms/bedrock/image/__pycache__/cost_calculator.cpython-310.pyc,, +litellm/llms/bedrock/image/__pycache__/image_handler.cpython-310.pyc,, +litellm/llms/bedrock/image/amazon_nova_canvas_transformation.py,sha256=qGMxPrd0JVDUpQ-qrUDEAPJn1rczWb6DYx2mva6OOoE,6441 +litellm/llms/bedrock/image/amazon_stability1_transformation.py,sha256=dVVShM509R5U4WJsNdTwGBBk6FaUM0Cwm5IgmPfP_CI,3824 +litellm/llms/bedrock/image/amazon_stability3_transformation.py,sha256=pTrv2SroV343sRYEboBibYeegC2A5wEaQeuKsywWbXA,3029 +litellm/llms/bedrock/image/cost_calculator.py,sha256=Knql7BVu41E1cJwnRhpWpljMYQ3x7DglE4xbFrMnYjo,1364 +litellm/llms/bedrock/image/image_handler.py,sha256=kE7a4iwQ37Gxcxpq7-NriTMSf6kypQ55xL7z9qNRbXE,11139 +litellm/llms/bedrock/messages/invoke_transformations/__pycache__/anthropic_claude3_transformation.cpython-310.pyc,, +litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py,sha256=anj4enSD9mMhkNtn2a_Q10sK3mrQq4IofbVnT6hqjgc,7381 +litellm/llms/bedrock/messages/readme.md,sha256=1IWYRwgr8XkfipFTe1zxFa7JZU5IAz-i_gizI7l59yE,124 +litellm/llms/bedrock/passthrough/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/bedrock/passthrough/transformation.py,sha256=F6Wt4G5nVjZT8SK7jPvIfROJPTlqg9NY4_aYl7SD3D4,6629 +litellm/llms/bedrock/rerank/__pycache__/handler.cpython-310.pyc,, +litellm/llms/bedrock/rerank/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/bedrock/rerank/handler.py,sha256=3CrbkLD-888FV5Er6y2nKHY03_VZ29DMJoQ6KsVXyOQ,6162 +litellm/llms/bedrock/rerank/transformation.py,sha256=1C8xxlqAGG6PslTxgiNk2tkSYE93gnf7GAxjXC9tctc,4083 +litellm/llms/bytez/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/bytez/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/bytez/chat/transformation.py,sha256=FOSeERD8LUVt_pqDU9mGg1cZV_I9fiB-PnAPtqFCXDc,15204 +litellm/llms/bytez/common_utils.py,sha256=Et5-TX-l9nA7rQFxjQIY9Tt6M397po7TjFVh8osJ4GM,686 +litellm/llms/cerebras/__pycache__/chat.cpython-310.pyc,, +litellm/llms/cerebras/chat.py,sha256=fIStTfCazOzXAkBTGi0oBZLJ1ErhQ_Iylh2jjgNKUH4,2343 +litellm/llms/clarifai/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/clarifai/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/clarifai/chat/transformation.py,sha256=iBswCEielET2MahpQMYK0ORuNTXIYBshLGW5ZVKEikw,8235 +litellm/llms/clarifai/common_utils.py,sha256=DTlbfWCV42r9EddhDTfJvEvo81FmYOB9-V8jSV_SL4A,235 +litellm/llms/cloudflare/chat/__pycache__/handler.cpython-310.pyc,, +litellm/llms/cloudflare/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/cloudflare/chat/handler.py,sha256=2FjIbC2-XtjGXlK-9PBBpV4BbB-OFGIrlq0tu_R8wf4,138 +litellm/llms/cloudflare/chat/transformation.py,sha256=QDBjXHvdJb935agKt6HyuOqrW3iuUsrAy1fmnv-2Y88,6893 +litellm/llms/codestral/completion/__pycache__/handler.cpython-310.pyc,, +litellm/llms/codestral/completion/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/codestral/completion/handler.py,sha256=GK9AtdQ_ADQZoF2noHdP4zoa2z7SohXxbBkklgF4vJU,14052 +litellm/llms/codestral/completion/transformation.py,sha256=NY43gldr3tY2bodLuAfWb5rPxOj66VmDghwAlJxzzvA,4124 +litellm/llms/cohere/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/cohere/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/cohere/chat/__pycache__/v2_transformation.cpython-310.pyc,, +litellm/llms/cohere/chat/transformation.py,sha256=y3BHsCmYj6LBwWC_S1TOjVYBMyzNhY5f0rcbyEHBSpw,14628 +litellm/llms/cohere/chat/v2_transformation.py,sha256=Pkl7s95rXVy8ICbY46aHz7T6IMI_-wJajpyrWIu72UU,14032 +litellm/llms/cohere/common_utils.py,sha256=jXZVQebKLRqoSzz4sbHfpg2q1dCOGKub8thunDWlRMk,4748 +litellm/llms/cohere/completion/__pycache__/handler.cpython-310.pyc,, +litellm/llms/cohere/completion/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/cohere/completion/handler.py,sha256=Jyypoaooxe1QzKNgx5pXJH0BCM1qnaYacwC0zl0b_BM,148 +litellm/llms/cohere/completion/transformation.py,sha256=moKeMcYaEHbry-TI7P14DUlg0iI2zigqFV8YQG71EBw,9884 +litellm/llms/cohere/embed/__pycache__/handler.cpython-310.pyc,, +litellm/llms/cohere/embed/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/cohere/embed/__pycache__/v1_transformation.cpython-310.pyc,, +litellm/llms/cohere/embed/handler.py,sha256=SnztVlY0B8da0ld-qCW6hI1y5vBhhij0uEBtECq87HU,5141 +litellm/llms/cohere/embed/transformation.py,sha256=wBSjzD3FDVw0QaOmyCXNyMap55pFkyDXjTrCPmBmI-E,7741 +litellm/llms/cohere/embed/v1_transformation.py,sha256=hKK0tCF_QQCKfrQjhea9oFnHfWlERoK3lyQMKGJoqaw,4469 +litellm/llms/cohere/rerank/__pycache__/handler.cpython-310.pyc,, +litellm/llms/cohere/rerank/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/cohere/rerank/handler.py,sha256=4h3LHYuSQ5iwlCuu6HXU5Vf52RHL9CiRjJnkCCZyRjg,141 +litellm/llms/cohere/rerank/transformation.py,sha256=ZhyUsHdRKUMprlN9T7sSn4T8a2voysI6-vYWQwBnjEg,5211 +litellm/llms/cohere/rerank_v2/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/cohere/rerank_v2/transformation.py,sha256=bAot45X1A3DGFXlKnmhOkaHZfUfoXs-cCafObHqBAyo,2876 +litellm/llms/custom_httpx/__pycache__/aiohttp_handler.cpython-310.pyc,, +litellm/llms/custom_httpx/__pycache__/aiohttp_transport.cpython-310.pyc,, +litellm/llms/custom_httpx/__pycache__/async_client_cleanup.cpython-310.pyc,, +litellm/llms/custom_httpx/__pycache__/http_handler.cpython-310.pyc,, +litellm/llms/custom_httpx/__pycache__/httpx_handler.cpython-310.pyc,, +litellm/llms/custom_httpx/__pycache__/llm_http_handler.cpython-310.pyc,, +litellm/llms/custom_httpx/aiohttp_handler.py,sha256=eSCgrR_cKRqn9iwDVDLpEJ-gupwkg1SqnMMXcCyMynA,20522 +litellm/llms/custom_httpx/aiohttp_transport.py,sha256=-qJ81I-xCGybbtiU-pABEOBBmcW9wKZD6_wBmK-cHwI,9490 +litellm/llms/custom_httpx/async_client_cleanup.py,sha256=1lfLKDE5gUw4V4pRgwpIHyqBsKDBxjzxA3vxq9NcFcs,3062 +litellm/llms/custom_httpx/http_handler.py,sha256=PRu4XkHAwmakcMdKhVKAI_Sft7-AelvA5PNZ6qFyYsI,35672 +litellm/llms/custom_httpx/httpx_handler.py,sha256=Cop6E2edYCSGptRIdx4Y48Tkt38bbnNTcWuysKHlQz4,1296 +litellm/llms/custom_httpx/llm_http_handler.py,sha256=J0UC6n30H7HvCsY1I_bVlS4mbTSx4N3cIcL4b2KAdtM,112930 +litellm/llms/custom_llm.py,sha256=WNcSkL2RPqgXrv4EyYZ-1IxuKMJuVSkIYQ9FGZ65t7g,6201 +litellm/llms/dashscope/__pycache__/cost_calculator.cpython-310.pyc,, +litellm/llms/dashscope/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/dashscope/chat/transformation.py,sha256=O0eNUA3NZKQJ5pN_DbW5ZwOUBetaHKk8QxmGrbqQ724,2626 +litellm/llms/dashscope/cost_calculator.py,sha256=G5UbaPLQ7wKBmFxd73yTvDwzs_3UsMdYvsUQeO6HnrM,587 +litellm/llms/databricks/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/databricks/__pycache__/cost_calculator.cpython-310.pyc,, +litellm/llms/databricks/__pycache__/streaming_utils.cpython-310.pyc,, +litellm/llms/databricks/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/databricks/chat/transformation.py,sha256=jMYJEyPVDV9Xn74ysfQLdOVtFNHNqg0k4Rf608QNTWs,21434 +litellm/llms/databricks/common_utils.py,sha256=F9EkB96lIMpxLagRLGwgu6UHPGqZAeqbWDqYoBvNuTM,4270 +litellm/llms/databricks/cost_calculator.py,sha256=YpzCFgAf0UyTJPIG_nkLMzkMC1VXC9fbsPU5J0C4bms,2418 +litellm/llms/databricks/embed/__pycache__/handler.cpython-310.pyc,, +litellm/llms/databricks/embed/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/databricks/embed/handler.py,sha256=lfb_OFvmY9EO0SXuR3XI6GJiHbhb8ZONwHPxqwgFzPM,1437 +litellm/llms/databricks/embed/transformation.py,sha256=HRf1ixwYD3vVVecfTl55DOoqkizPxw32v1mcx21VyEA,1464 +litellm/llms/databricks/streaming_utils.py,sha256=K3okW4cjTVfTfAWb92ILInpo-ZTpru3BrQ-2i-CkzB4,6228 +litellm/llms/datarobot/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/datarobot/chat/transformation.py,sha256=xnlRe5P0_CGZVxA5AtetphwV2LhSBKA7bcaQckPyRM4,3091 +litellm/llms/deepgram/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/deepgram/audio_transcription/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/deepgram/audio_transcription/transformation.py,sha256=l7BaQ-V2fFAAjx2WHEF3tTPSW9m7VX60phmkqj_d7io,6835 +litellm/llms/deepgram/common_utils.py,sha256=BW32Pllv5QIydRNaqgy4VcMbceyjsQEzc_bvGQ5OSPs,125 +litellm/llms/deepinfra/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/deepinfra/chat/transformation.py,sha256=BxAivmUA9T_qzuUj97FdX3uyG4gc65NyxKRFTYhx_aU,4574 +litellm/llms/deepseek/__pycache__/cost_calculator.cpython-310.pyc,, +litellm/llms/deepseek/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/deepseek/chat/transformation.py,sha256=TSbfqpLgO7de3MNYVInQydu3vb2Wl7ohAnKZG-2mnEI,2575 +litellm/llms/deepseek/cost_calculator.py,sha256=G5UbaPLQ7wKBmFxd73yTvDwzs_3UsMdYvsUQeO6HnrM,587 +litellm/llms/deprecated_providers/__pycache__/aleph_alpha.cpython-310.pyc,, +litellm/llms/deprecated_providers/__pycache__/palm.cpython-310.pyc,, +litellm/llms/deprecated_providers/aleph_alpha.py,sha256=eMVFefcntg8gYdG3ZSa4JJ6SKFAZEqxg1oKM5Y65RSk,12725 +litellm/llms/deprecated_providers/palm.py,sha256=M8svKiK2X4f4XHBQ5CfNeRQJFe_jZp-fQvySxVPj5Sg,6898 +litellm/llms/elevenlabs/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/elevenlabs/audio_transcription/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/elevenlabs/audio_transcription/transformation.py,sha256=-I8isQhmbtklwTOYXZIyls-7WEOKmQxpEyYrWfwU33Y,6811 +litellm/llms/elevenlabs/common_utils.py,sha256=_3K1T4XwQzL8t4BDQlqlliJ7OBlbJvEP2DwBMbi49gY,127 +litellm/llms/empower/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/empower/chat/transformation.py,sha256=6OU1pbPxSgUPi5nnwT7kqsQxFvpmSPXB_zMYBRtXRQA,218 +litellm/llms/featherless_ai/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/featherless_ai/chat/transformation.py,sha256=6h5oCAH28VUYYLAKH2VVZotX7VyT5GOyY1WV72tIxUA,4713 +litellm/llms/fireworks_ai/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/fireworks_ai/__pycache__/cost_calculator.cpython-310.pyc,, +litellm/llms/fireworks_ai/audio_transcription/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/fireworks_ai/audio_transcription/transformation.py,sha256=XHgTNDpMk7Y5dn37Nf2zjQUCO75ZE0jwuuJ0SD_ldM8,563 +litellm/llms/fireworks_ai/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/fireworks_ai/chat/transformation.py,sha256=HNLjIU3E3taao97fJOngsEOwzvLtre6GB7XnoPD91rI,15568 +litellm/llms/fireworks_ai/common_utils.py,sha256=4XZ-T7kbnb6zYVVtDMslFRSIlXNGwuXDYogBE-7rpT4,1536 +litellm/llms/fireworks_ai/completion/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/fireworks_ai/completion/transformation.py,sha256=NjT7Ix95Sd8xTqZRCA3hbuIDEITjhDCXNNlZKdy54RE,1873 +litellm/llms/fireworks_ai/cost_calculator.py,sha256=JAlyi9TLwLOu5NJVT4eE-9ekSevP5aaPW8mjYk6pY6k,2830 +litellm/llms/fireworks_ai/embed/__pycache__/fireworks_ai_transformation.cpython-310.pyc,, +litellm/llms/fireworks_ai/embed/fireworks_ai_transformation.py,sha256=6OUlynAaBy8esuYBidFiTUoaNUO80aHjiFebTrTj7RI,1435 +litellm/llms/friendliai/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/friendliai/chat/transformation.py,sha256=T6wkm9hjUHrgriAFen5dYPKZaBiQnXOXQA_VlKo8bY8,217 +litellm/llms/galadriel/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/galadriel/chat/transformation.py,sha256=9lvISZw10MtuT24KENxn_kz5NIGwJ8GW8dK4FHdZaT0,215 +litellm/llms/gemini/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/gemini/__pycache__/cost_calculator.cpython-310.pyc,, +litellm/llms/gemini/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/gemini/chat/transformation.py,sha256=6aZz9QPdb0U8O2y5OMxw-gNrZAWZ2e8R9iBII3DZSMo,5881 +litellm/llms/gemini/common_utils.py,sha256=ajrY7FvXoVf3m4UDlcyGHcrVEpjnCpQga3ZaUxYZBXI,5011 +litellm/llms/gemini/context_caching/README.md,sha256=WwbxrsX-ykf1cWnXG_KLIP25hH2k5Pqz34AOlIjjev4,79 +litellm/llms/gemini/cost_calculator.py,sha256=pDFtINN-xA_N3FNqiSjfcWKzFc6VtTDrKH8lqm71oDo,1675 +litellm/llms/gemini/files/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/gemini/files/transformation.py,sha256=Kbr4OmInZOFUTLErzZ4_c1Q7OG7nK8-riLQFy4775uM,5430 +litellm/llms/gemini/google_genai/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/gemini/google_genai/transformation.py,sha256=-oeQfNjT6siGELdkEbIkrRNo5q2SqQ-2fjAmpPqlsFk,9714 +litellm/llms/gemini/realtime/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/gemini/realtime/transformation.py,sha256=tQn0Q3xW8H8G_qX29_qCpnynNJjvTqf8pVbcI0Y3Dds,39373 +litellm/llms/github/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/github/chat/transformation.py,sha256=XUbXYUEuku9bA_gJr4rAuFh0Gm1NfxQhZcEoLnhdrLY,209 +litellm/llms/github_copilot/__pycache__/authenticator.cpython-310.pyc,, +litellm/llms/github_copilot/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/github_copilot/authenticator.py,sha256=wKVF_hWtfthMkv6dPqbbZMulNcyqak_BGYXZ1wF-azk,12408 +litellm/llms/github_copilot/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/github_copilot/chat/transformation.py,sha256=Zcot88wc53UzKbcf5VJ3xBFE9XVAhmoloJLG5su82vA,1190 +litellm/llms/github_copilot/common_utils.py,sha256=JD9tSUHGL9ZNtU4vw-qZhRByElU9hjIBnu0XyBdoBig,982 +litellm/llms/groq/chat/__pycache__/handler.cpython-310.pyc,, +litellm/llms/groq/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/groq/chat/handler.py,sha256=gDy2fUHk98NbeoNyuulC3Zi5cgGrzg0esHWleNWVDvM,2485 +litellm/llms/groq/chat/transformation.py,sha256=_KUqfPZFgEiIbQDlCYEGfnzZpXHLEeeuLFEF7py6uB8,9205 +litellm/llms/groq/stt/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/groq/stt/transformation.py,sha256=5Wmi6gQ-7nAC8gj5Gi0zCzHkTecOWVIbxX6plYaRUtk,3350 +litellm/llms/hosted_vllm/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/hosted_vllm/chat/transformation.py,sha256=26JPuCzlElJqVDII1sy1RLKLNf44FyL64Kfa4xRNY7M,5390 +litellm/llms/hosted_vllm/embedding/README.md,sha256=7GMIybyYxTTaBu8aYHmGYNvNX2Nyvt5173dY4QoYeHw,226 +litellm/llms/huggingface/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/huggingface/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/huggingface/chat/transformation.py,sha256=6soqhy3iagbTQmYLil6ML5nihdhVi1gFVsbeD8w83K8,5967 +litellm/llms/huggingface/common_utils.py,sha256=C8K-IkEGaVhdjSr6WcAIAIRHgKBgiMIPL__PglqVLh8,3071 +litellm/llms/huggingface/embedding/__pycache__/handler.cpython-310.pyc,, +litellm/llms/huggingface/embedding/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/huggingface/embedding/handler.py,sha256=vYnsladdrqLqZxKHUiAlZWk-mmG13oZhusWPkYRrQv0,13761 +litellm/llms/huggingface/embedding/transformation.py,sha256=ZvsyGtlQUEq-5_nxJeIHPwJaKT4No9FZuhoOkdL9yKg,23746 +litellm/llms/huggingface/huggingface_llms_metadata/hf_conversational_models.txt,sha256=-KennA-85KE2N-dTyR2TG4v30NvWc6IAE6zCIEngjZQ,76183 +litellm/llms/huggingface/huggingface_llms_metadata/hf_text_generation_models.txt,sha256=7ntr_Gx6l8TQXpbWFycf-NnI3HdqagxvN2usENNEkHU,1288308 +litellm/llms/huggingface/rerank/__pycache__/handler.cpython-310.pyc,, +litellm/llms/huggingface/rerank/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/huggingface/rerank/handler.py,sha256=4buKBfpb5W0eB0lCQPCAABmsdMfYf2YVsS1IZaqCorY,146 +litellm/llms/huggingface/rerank/transformation.py,sha256=U9AV62C6YXRbHjMs0IJsL1mICCvmxufjcZtyh3VfVDY,10815 +litellm/llms/infinity/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/infinity/common_utils.py,sha256=0-6GNg2yPtSV8UYxaxrW3xcEOyTeAmdgUPFYk2Za-jo,835 +litellm/llms/infinity/embedding/__pycache__/handler.cpython-310.pyc,, +litellm/llms/infinity/embedding/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/infinity/embedding/handler.py,sha256=JDwB0TAqwCKLraKzQ865ZQuRZJDojAQqwdCHkTrZ0H0,146 +litellm/llms/infinity/embedding/transformation.py,sha256=85ObpHaoTtQUoKX0IcktsQw78wRmno5yaRCNbusQ7IM,4648 +litellm/llms/infinity/rerank/__pycache__/handler.cpython-310.pyc,, +litellm/llms/infinity/rerank/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/infinity/rerank/handler.py,sha256=dCXb7WA6esPZhOkE-Foah9oNVHLxH_RWdbHAhiRqlr0,143 +litellm/llms/infinity/rerank/transformation.py,sha256=uY26_o77Y9cKb4Yn2kA5rbVG2hLKLbr7eWaS7b7ygAM,4083 +litellm/llms/jina_ai/embedding/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/jina_ai/embedding/transformation.py,sha256=nm8kP0d5h7L1u2NUICoXmsUoCSglrCOYHS6xo7vJspo,2300 +litellm/llms/jina_ai/rerank/__pycache__/handler.cpython-310.pyc,, +litellm/llms/jina_ai/rerank/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/jina_ai/rerank/handler.py,sha256=6cgBW53IkFSEhqvzvEe2sjJ6UY_DWGOwq6nROh_lksQ,55 +litellm/llms/jina_ai/rerank/transformation.py,sha256=Z8HLKnXe92KvIoHtQvth7BIlbooZBcNer2GyfB3uV0c,4674 +litellm/llms/litellm_proxy/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/litellm_proxy/chat/transformation.py,sha256=MfeRcmzi-tHf8yZOpANZ5sN-yhq-0gKCUPy1TiC_LYI,5243 +litellm/llms/llamafile/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/llamafile/chat/transformation.py,sha256=ekDSVL87y2L_5pJ-dfTN_6zsleWtSjmoee5sPovzi6w,2043 +litellm/llms/lm_studio/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/lm_studio/chat/transformation.py,sha256=2DIZgc6NAeCmsSO2vYEtmNLUV3sJHWccQFBvjauMHhg,1895 +litellm/llms/lm_studio/embed/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/lm_studio/embed/transformation.py,sha256=7LDd4xQLu1Owri3MRhtamdFLtV5B0wzKVug2qCkMoH4,1254 +litellm/llms/maritalk.py,sha256=bcUTOIQKFWLx7IPkgJoG2zhRemGi5GAbZo7CKIxPwk0,2000 +litellm/llms/meta_llama/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/meta_llama/chat/transformation.py,sha256=r-FVoEQlFlX3UyZgAO8rBVTkxit8XYOdrkeCJ9N1J54,1538 +litellm/llms/mistral/__pycache__/embedding.cpython-310.pyc,, +litellm/llms/mistral/__pycache__/mistral_embedding_transformation.cpython-310.pyc,, +litellm/llms/mistral/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/mistral/chat/transformation.py,sha256=AwM0AcJWLeXhy3b1TQ5nQ40z1POuNShFH9eJLjm_-XE,18074 +litellm/llms/mistral/embedding.py,sha256=xEXBD5O4HEXI7MUtl-B_PH9_RMlze5-zobTWimVLsC4,77 +litellm/llms/mistral/mistral_embedding_transformation.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +litellm/llms/nebius/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/nebius/chat/transformation.py,sha256=j2R3xFWFC0ww2SbC21JdXVwQ73RL7LWvltvEJmG0OR8,849 +litellm/llms/nebius/embedding/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/nebius/embedding/transformation.py,sha256=1dtFZWXsvvAbxDVc3ZCgr7wFadD7-v0LksWvW94eEwc,88 +litellm/llms/nlp_cloud/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/nlp_cloud/chat/__pycache__/handler.cpython-310.pyc,, +litellm/llms/nlp_cloud/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/nlp_cloud/chat/handler.py,sha256=8GuIlJ6UiJ_Z8Yz5TiCei0gklEw2QaZSzw0YLQyIrxE,3617 +litellm/llms/nlp_cloud/chat/transformation.py,sha256=IDqMDSjPi7LQ7vbYKx5TRkdQKdJySH4GS9sQ01PbIww,7979 +litellm/llms/nlp_cloud/common_utils.py,sha256=RR62KdUDDNgHLiHGAhXHEe5Q0ujk2Nn57pr8gdb7ywI,395 +litellm/llms/novita/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/novita/chat/transformation.py,sha256=gO_5eejpp_hG8OUvscA-dauNlv6SCrrsDIzEzP0zOiY,1042 +litellm/llms/nscale/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/nscale/chat/transformation.py,sha256=T8ieDupDhJITrY-c5u-e_6eDOw4tzoLubpmg95eU2n0,1662 +litellm/llms/nvidia_nim/__pycache__/embed.cpython-310.pyc,, +litellm/llms/nvidia_nim/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/nvidia_nim/chat/transformation.py,sha256=RmXuSLXE7eh3VmC4SZo47LgIJ94fglntOPnCYNhycs4,3877 +litellm/llms/nvidia_nim/embed.py,sha256=hxKt3iYATHnLR4OKS71WMycxcpvQEnigSpzWFgd58IU,2303 +litellm/llms/ollama/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/ollama/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/ollama/chat/transformation.py,sha256=82ock3I6RiI78oZtp5_hDr4WJ2bpAulo9euvzneV_ZI,20291 +litellm/llms/ollama/common_utils.py,sha256=x-9E2RkTZNh08gDo5hBMdzKNVJiwj5krwMVZZx-Oku4,4194 +litellm/llms/ollama/completion/__pycache__/handler.cpython-310.pyc,, +litellm/llms/ollama/completion/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/ollama/completion/handler.py,sha256=2y39FzFG0cQgyPCvmCiz1FYLj6xUh9jqYF75rhxVwPs,3551 +litellm/llms/ollama/completion/transformation.py,sha256=6tKQWPfSSPdhTWhpRgA5dkGs0_-ZVq29uBHx1np7p_4,18718 +litellm/llms/ollama_chat.py,sha256=p4nWizdTWMoi6CfEebbHKVj0X_PwZHtp8ANSrWuMkrI,16290 +litellm/llms/oobabooga/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/oobabooga/chat/__pycache__/oobabooga.cpython-310.pyc,, +litellm/llms/oobabooga/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/oobabooga/chat/oobabooga.py,sha256=lSr2lIVHFFdBh1TJRJ-fV9cPuO7STKiKHKRkZtJV5W4,4396 +litellm/llms/oobabooga/chat/transformation.py,sha256=-y4AnlLUsm0ivoI54EWo8rCWDW1sMQ6QtQq1DfmSDYo,3302 +litellm/llms/oobabooga/common_utils.py,sha256=MrXF6OmsD5YDWdDV9ppAfPZCyBYaWLdFqjG04IvrMhw,396 +litellm/llms/openai/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/openai/__pycache__/cost_calculation.cpython-310.pyc,, +litellm/llms/openai/__pycache__/openai.cpython-310.pyc,, +litellm/llms/openai/chat/__pycache__/gpt_audio_transformation.cpython-310.pyc,, +litellm/llms/openai/chat/__pycache__/gpt_transformation.cpython-310.pyc,, +litellm/llms/openai/chat/__pycache__/o_series_handler.cpython-310.pyc,, +litellm/llms/openai/chat/__pycache__/o_series_transformation.cpython-310.pyc,, +litellm/llms/openai/chat/gpt_audio_transformation.py,sha256=uLFogco8_hU4BW_66XM5axvzlOnmHfvX8WYwF0xGNqY,1336 +litellm/llms/openai/chat/gpt_transformation.py,sha256=Anzue_UaRiv40nD9cZqHVIvmJPWeHzlzi4Bi6dIGSs0,26141 +litellm/llms/openai/chat/o_series_handler.py,sha256=mxrppFXYhGzKvNdyU5k0fScX5DLVWKls_bHfVM_imyY,47 +litellm/llms/openai/chat/o_series_transformation.py,sha256=mQpr49AxolkNR390iAigtaIT6hz0BYYhGhbLgd4HtzI,6328 +litellm/llms/openai/common_utils.py,sha256=_QmK81-DdX19gzGh2Y0R4xm5pzovKzJdamuxuIxbp0A,7961 +litellm/llms/openai/completion/__pycache__/handler.cpython-310.pyc,, +litellm/llms/openai/completion/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/openai/completion/__pycache__/utils.cpython-310.pyc,, +litellm/llms/openai/completion/handler.py,sha256=9UVqJ1N3QGPRRq75d2vjtwsDdHwF766fnInPGJtUQOE,11853 +litellm/llms/openai/completion/transformation.py,sha256=jr12TSvCf4Rup-_jHbCzBoBSMzc422L4fwr4n1uJIsM,6126 +litellm/llms/openai/completion/utils.py,sha256=HXTL8Fpu4x-NaAjjDr4hBo7gyMsn3Gup-xOie6f1euk,1770 +litellm/llms/openai/cost_calculation.py,sha256=VJKcnhSZMqetnuAm-MklTyptElQHlvO8hn4dlBWVoEo,4747 +litellm/llms/openai/fine_tuning/__pycache__/handler.cpython-310.pyc,, +litellm/llms/openai/fine_tuning/handler.py,sha256=RBgsdfqYSobHEa2hsJ1KwJ0dtZW3SGeEY7HunX78c2w,10519 +litellm/llms/openai/image_edit/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/openai/image_edit/transformation.py,sha256=IJvIH4q8C5_AlYOxvZELPqqH2D5EFKy7O6La9c0CY0w,4787 +litellm/llms/openai/image_generation/__init__.py,sha256=TMkNek_YINf0l0iMBuu91Q5i4gnuy1DYEiiMqYsIIko,749 +litellm/llms/openai/image_generation/__pycache__/__init__.cpython-310.pyc,, +litellm/llms/openai/image_generation/__pycache__/dall_e_2_transformation.cpython-310.pyc,, +litellm/llms/openai/image_generation/__pycache__/dall_e_3_transformation.cpython-310.pyc,, +litellm/llms/openai/image_generation/__pycache__/gpt_transformation.cpython-310.pyc,, +litellm/llms/openai/image_generation/dall_e_2_transformation.py,sha256=v-Ot3C8Uv5jyGvO7NyA39JOE5x5vWprD5RgYE9Wkx6s,1287 +litellm/llms/openai/image_generation/dall_e_3_transformation.py,sha256=1ZkCkHlvSXeYZ7tiDp7rN1urtjp9kvdpKbG3l6tfFqI,1296 +litellm/llms/openai/image_generation/gpt_transformation.py,sha256=kgjJM_b6uynjY5HHE7T8wqyw91Ff_N7Cgskzrf7KbGU,1442 +litellm/llms/openai/image_variations/__pycache__/handler.cpython-310.pyc,, +litellm/llms/openai/image_variations/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/openai/image_variations/handler.py,sha256=6XBEHm1VkOn-Y8SMSfEypBb5Y5II_vGYJy6NQ_vi_u0,8590 +litellm/llms/openai/image_variations/transformation.py,sha256=9UBfFG8v4VHSywmmO0p8HqWFq3_sKvLTXpA-YQEvWIc,2520 +litellm/llms/openai/openai.py,sha256=hRB8rw7ggzACqm1Gk1xSxIAYGJKQncF5gfcN7KYzxtU,102706 +litellm/llms/openai/realtime/__pycache__/handler.cpython-310.pyc,, +litellm/llms/openai/realtime/handler.py,sha256=Em4Up5Happ3vZ0ICq3eir5Y4r3-lVBYkycPEUzzuTPg,2978 +litellm/llms/openai/responses/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/openai/responses/transformation.py,sha256=M7ItoqhvXVKAmedVYun-207qdu4OHATMsBSXyeJcUAI,11856 +litellm/llms/openai/transcriptions/__pycache__/gpt_transformation.cpython-310.pyc,, +litellm/llms/openai/transcriptions/__pycache__/handler.cpython-310.pyc,, +litellm/llms/openai/transcriptions/__pycache__/whisper_transformation.cpython-310.pyc,, +litellm/llms/openai/transcriptions/gpt_transformation.py,sha256=QYELxY0D7cLeDLpjw6139uPS3brGUzwH7Hkf9GZf_PE,1005 +litellm/llms/openai/transcriptions/handler.py,sha256=KSmpxWBgOaRx3yTtcwo1qHgfNJYwGr12FexUVmscHSI,8258 +litellm/llms/openai/transcriptions/whisper_transformation.py,sha256=Vp58xlSh4HHLjMtZu5TQ0psOlUeeNnxhZPdzvn-eIC0,2824 +litellm/llms/openai/vector_stores/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/openai/vector_stores/transformation.py,sha256=xitUFrTZ1IpIeHJoR3OfHDDvS-tqZWOkd3MGWsm3qhE,4803 +litellm/llms/openai_like/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/openai_like/chat/__pycache__/handler.cpython-310.pyc,, +litellm/llms/openai_like/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/openai_like/chat/handler.py,sha256=1kLE89OncjZUPITPUOLd45amnVR3uf4GlLcJXmqKgYk,13935 +litellm/llms/openai_like/chat/transformation.py,sha256=Wmf9Esm9_tW9MN-gQNoOB3N_oTAbLZhBRsHJwPC0lso,5294 +litellm/llms/openai_like/common_utils.py,sha256=1G-vshKyZ2KzLgJnix6g4rzyc1mEgqm87e9bVOMROgo,2133 +litellm/llms/openai_like/embedding/__pycache__/handler.cpython-310.pyc,, +litellm/llms/openai_like/embedding/handler.py,sha256=NgKv-Bty4G9x-XPSBTaR1eE-mToF8JxqSb7Qe-i56ZA,4935 +litellm/llms/openrouter/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/openrouter/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/openrouter/chat/transformation.py,sha256=2l0GxwIatwS7pOtxRqwWQ8JRrK4xJ_sahbNuFumjXlA,4783 +litellm/llms/openrouter/common_utils.py,sha256=r4ROh6GTDu2yB__fE1TdGdfGWGfiqdeU4IVzBq3G8ao,127 +litellm/llms/perplexity/__pycache__/cost_calculator.cpython-310.pyc,, +litellm/llms/perplexity/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/perplexity/chat/transformation.py,sha256=0oS36oZ3HmdfsTDVQ9Fa-Bt8Mc6w3UYwjz5EGFk4RcY,6724 +litellm/llms/perplexity/cost_calculator.py,sha256=_3Qu62P2A5wrqVNbzCjEUpqlef5Rb5HqYVXEZk7hGII,3691 +litellm/llms/petals/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/petals/common_utils.py,sha256=auMO32Q5e6y1Fa6XWR82kQM0_0o5KbAErPp4yfp-m3o,334 +litellm/llms/petals/completion/__pycache__/handler.cpython-310.pyc,, +litellm/llms/petals/completion/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/petals/completion/handler.py,sha256=oyD3F27-dOQmhPnpWX7RZRbztsenu-aa9buCy_wAkiI,4630 +litellm/llms/petals/completion/transformation.py,sha256=7VHNOljCbnDze8KBUpc1usyamCMEVOs8hq3SaOI1l0U,4777 +litellm/llms/predibase/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/predibase/chat/__pycache__/handler.cpython-310.pyc,, +litellm/llms/predibase/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/predibase/chat/handler.py,sha256=B5OkEstbfleb8HXcoV3E4PC50szfg74EWf-_ZgeXRbM,16602 +litellm/llms/predibase/chat/transformation.py,sha256=sNw7cwDAqaFfapFQQwE9mbkCqvfZH3ysuYZNKSnJ1fM,6815 +litellm/llms/predibase/common_utils.py,sha256=dfCFrZhTJipgRDI3UqQFOwow-oYxBiRqR5B9cJhiP4I,603 +litellm/llms/replicate/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/replicate/chat/__pycache__/handler.cpython-310.pyc,, +litellm/llms/replicate/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/replicate/chat/handler.py,sha256=YGXa5yxNfUTVzEea3Wp9wXGz7liNmnW_gymkNhuaShc,11119 +litellm/llms/replicate/chat/transformation.py,sha256=u0ElPKmPz9kpoD_Ih4goAQ__Lau-xllE1efSGgtHtb4,12400 +litellm/llms/replicate/common_utils.py,sha256=vfRWRfmkBl3M1oRgoOhAgZeVf_3pSP7DWKqCxIu_Ty8,389 +litellm/llms/sagemaker/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/sagemaker/chat/__pycache__/handler.cpython-310.pyc,, +litellm/llms/sagemaker/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/sagemaker/chat/handler.py,sha256=hTXPrd1wkFtSq9oPpIMiETovMqG5dZz1Af71U7q2EeY,7002 +litellm/llms/sagemaker/chat/transformation.py,sha256=GXY4Zl3hTmvRm2Yne6d3e7b9_LC_wP10w5uKd1iSKuI,7151 +litellm/llms/sagemaker/common_utils.py,sha256=yhGU2O5zcRxwHLCHUTFucFlhf2uhQPXTD1ERSy82Sds,8730 +litellm/llms/sagemaker/completion/__pycache__/handler.cpython-310.pyc,, +litellm/llms/sagemaker/completion/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/sagemaker/completion/handler.py,sha256=AVRDmFrmLF30xFh8pDHeN1_NbpRrfz7je07cNrzMSUk,26127 +litellm/llms/sagemaker/completion/transformation.py,sha256=LgOc6rxL_frRyhM6W0iqDP5y__Ww3RjUBuqX65NTfeQ,10466 +litellm/llms/sambanova/__pycache__/chat.cpython-310.pyc,, +litellm/llms/sambanova/chat.py,sha256=lrPZC4hJcgjPZVAAu-gjfZt5Wu7Hem_jyjHpYfD0EHI,2771 +litellm/llms/snowflake/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/snowflake/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/snowflake/chat/transformation.py,sha256=RfNZBeWDWiCJhsdIepP8jAz7EG2rWY3z2TEjDzg2ios,5423 +litellm/llms/snowflake/common_utils.py,sha256=BnKwR359N2vgfJ6akSSMoj-2BRkrR5kjo4HCocZbgWc,1018 +litellm/llms/together_ai/__pycache__/chat.cpython-310.pyc,, +litellm/llms/together_ai/__pycache__/cost_calculator.cpython-310.pyc,, +litellm/llms/together_ai/__pycache__/embed.cpython-310.pyc,, +litellm/llms/together_ai/chat.py,sha256=2d2nM1PvOPejNb4wZZsYHzwBbKnMxOrsjny97t9FIEM,2066 +litellm/llms/together_ai/completion/__pycache__/handler.cpython-310.pyc,, +litellm/llms/together_ai/completion/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/together_ai/completion/handler.py,sha256=Sey5xhMPY0x5muY8Ex1n8TgPQVwc3-z_YFRggE_lZlU,47 +litellm/llms/together_ai/completion/transformation.py,sha256=Yg2mZVRqTzKSvemv4IvxsklzXeCyVAMHYS2GC5FcBMw,2048 +litellm/llms/together_ai/cost_calculator.py,sha256=p4cv7oOwGcJAqPFy4RUaP036bmTu3YCc4Hufjq1kl90,3053 +litellm/llms/together_ai/embed.py,sha256=9tgu5GlbQU8f-Sj07dKy_vt3esNSZDidViTA0htg-ZE,181 +litellm/llms/together_ai/rerank/__pycache__/handler.cpython-310.pyc,, +litellm/llms/together_ai/rerank/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/together_ai/rerank/handler.py,sha256=A6gGNLj-VX2OxE9E2-ZwAmVPjEmG_yRNiISOAQz8Ljw,2855 +litellm/llms/together_ai/rerank/transformation.py,sha256=_qk8IMYXS0gC8xCFCz6p9Cgf1eptvX8jq--d1A2Id-Q,2023 +litellm/llms/topaz/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/topaz/common_utils.py,sha256=A2PhhAsS2lLK8IxJTqP8eiifuhBpghm2YreDmgr8gK4,1711 +litellm/llms/topaz/image_variations/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/topaz/image_variations/transformation.py,sha256=kN0rsJEBE6w1KmM5dD7oNbgk8uPJm8kGJ6Ni6U4_8D4,5785 +litellm/llms/triton/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/triton/common_utils.py,sha256=kWIRjRKDOQOpuc_ZhepJ3oFcmTeXEJqf8skJfCUmBXo,401 +litellm/llms/triton/completion/__pycache__/handler.cpython-310.pyc,, +litellm/llms/triton/completion/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/triton/completion/handler.py,sha256=duNlWMGNsEyWjeqvKjDd0bKjFECnr9haEgsxdi1t2Lo,145 +litellm/llms/triton/completion/transformation.py,sha256=xNnsmPfZlhrQ7jtwl9B8aQq_ky_fFbuqGW6WGxxAi5k,11211 +litellm/llms/triton/embedding/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/triton/embedding/transformation.py,sha256=Omwr2aBrMzmk4Yx8Y2SYK0ODvoy-NM8JzWwANc3gLCI,3622 +litellm/llms/vertex_ai/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/vertex_ai/__pycache__/cost_calculator.cpython-310.pyc,, +litellm/llms/vertex_ai/__pycache__/vertex_ai_non_gemini.cpython-310.pyc,, +litellm/llms/vertex_ai/__pycache__/vertex_llm_base.cpython-310.pyc,, +litellm/llms/vertex_ai/batches/Readme.md,sha256=IbnuiX6lS93XHrGJ_4v9VBjRi-SJeaGfsrDTRg3fkCw,212 +litellm/llms/vertex_ai/batches/__pycache__/handler.cpython-310.pyc,, +litellm/llms/vertex_ai/batches/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/vertex_ai/batches/handler.py,sha256=JlUu03w2aaIBp68ghgloR2Foxd_P1ICo_hwTIwuwwgI,7250 +litellm/llms/vertex_ai/batches/transformation.py,sha256=6PKSZGkyXxaaebSZc8zWXzQ_XhVy0N2VMRnMM9NY-9g,6953 +litellm/llms/vertex_ai/common_utils.py,sha256=xhVmF1LwYVQdIitPO-pB2ATFwJoaYIomaaaB-gEGbJs,20692 +litellm/llms/vertex_ai/context_caching/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/vertex_ai/context_caching/__pycache__/vertex_ai_context_caching.cpython-310.pyc,, +litellm/llms/vertex_ai/context_caching/transformation.py,sha256=qbD4riQg_X5DED2gQ7a_zrxLfuttQzogMkbZexF5Fec,3618 +litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py,sha256=YY_lxmPCokpCT3NwXK7y_S-KRd5d13gGy59cBICJwxE,14520 +litellm/llms/vertex_ai/cost_calculator.py,sha256=YPB8r6XKHeTpNvGkR8Bul3GE-YE08YVMrDmGraGguBs,9134 +litellm/llms/vertex_ai/files/__pycache__/handler.cpython-310.pyc,, +litellm/llms/vertex_ai/files/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/vertex_ai/files/handler.py,sha256=OweYTqDPaQ6wP47R5_HWz1NN9oDrWI90p4KVaaSQ6sU,3750 +litellm/llms/vertex_ai/files/transformation.py,sha256=4Z8ZNie1iirOrpI6K3_fDda_qqT0op6wp37cQP0i7Ww,18398 +litellm/llms/vertex_ai/fine_tuning/__pycache__/handler.cpython-310.pyc,, +litellm/llms/vertex_ai/fine_tuning/handler.py,sha256=j1gunUix0HPj0nbsm4t3vDt_YXvQVLrsCu3hU4XwfMk,14472 +litellm/llms/vertex_ai/gemini/__pycache__/cost_calculator.cpython-310.pyc,, +litellm/llms/vertex_ai/gemini/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/vertex_ai/gemini/__pycache__/vertex_and_google_ai_studio_gemini.cpython-310.pyc,, +litellm/llms/vertex_ai/gemini/cost_calculator.py,sha256=4ZWWg86cBg1psXKPs7Rb-R-5Re4erxjl8c8KPxIm2Vc,1311 +litellm/llms/vertex_ai/gemini/transformation.py,sha256=1oLa5SVPVtS-d4qIqPtSYpE93EBFxtZKQkdgeUfGIKo,21723 +litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py,sha256=kN6z4IUlyJDQurxl_EWL0NpSxJuDD8-4rg31PESy-rI,80892 +litellm/llms/vertex_ai/gemini_embeddings/__pycache__/batch_embed_content_handler.cpython-310.pyc,, +litellm/llms/vertex_ai/gemini_embeddings/__pycache__/batch_embed_content_transformation.cpython-310.pyc,, +litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_handler.py,sha256=LJFGEE5Mgt7P2j1Aem5oFSP4uxu4M_7A_F8tvxfubFE,5666 +litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_transformation.py,sha256=e49WCU0QgqyVu1rUXbx-5aV3zmRUM_TEE3fEPQN94tI,2325 +litellm/llms/vertex_ai/google_genai/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/vertex_ai/google_genai/transformation.py,sha256=W_mSgCtM5Lu3a8gmfxdkaZPBI171XJbKiclQfW2BgOw,431 +litellm/llms/vertex_ai/image_generation/__pycache__/cost_calculator.cpython-310.pyc,, +litellm/llms/vertex_ai/image_generation/__pycache__/image_generation_handler.cpython-310.pyc,, +litellm/llms/vertex_ai/image_generation/cost_calculator.py,sha256=t5Ih1CAVh2UbJ4w2FZNljWofMaldLBoEtVfxWGaDMs8,600 +litellm/llms/vertex_ai/image_generation/image_generation_handler.py,sha256=Glagqc8VD5s2jQVJvd0pfkXMGLkv3k10EdS0RM24wvQ,9072 +litellm/llms/vertex_ai/multimodal_embeddings/__pycache__/embedding_handler.cpython-310.pyc,, +litellm/llms/vertex_ai/multimodal_embeddings/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/vertex_ai/multimodal_embeddings/embedding_handler.py,sha256=J7JXo9XZRIb7ibP-6O8pf0fBPxuQvhKn__2Td5lEdWA,6287 +litellm/llms/vertex_ai/multimodal_embeddings/transformation.py,sha256=1uSa5if9cvoEZ1pjCNOi8Q8WlMLcSIjJP_8ANvp8QY0,10897 +litellm/llms/vertex_ai/text_to_speech/__pycache__/text_to_speech_handler.cpython-310.pyc,, +litellm/llms/vertex_ai/text_to_speech/text_to_speech_handler.py,sha256=hUu6s8aGa_HPwT4CsyTLniXZqc_uEtzL_MffZxgamhk,7723 +litellm/llms/vertex_ai/vertex_ai_non_gemini.py,sha256=7vHTSIXzbagLg7B1jvgiaxjzk3sGxbUYAlmJZ2lTDgg,29597 +litellm/llms/vertex_ai/vertex_ai_partner_models/__init__.py,sha256=5WDyQ8M1RK8x0nSBw6CNbDJEB7cuODincyrLJYW1XPw,866 +litellm/llms/vertex_ai/vertex_ai_partner_models/__pycache__/__init__.cpython-310.pyc,, +litellm/llms/vertex_ai/vertex_ai_partner_models/__pycache__/main.cpython-310.pyc,, +litellm/llms/vertex_ai/vertex_ai_partner_models/ai21/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/vertex_ai/vertex_ai_partner_models/ai21/transformation.py,sha256=cvNsKwK-E2_0IBtDu2kTD98tHYQmCNR6ZpYK9JsNDzQ,1711 +litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py,sha256=e_Bg-mrUuOFh0D7GgWEVahV6SRWR0jyGBG3v6jIk-XQ,3211 +litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py,sha256=zvoZkjhkuHGpp0ZorvbAI_re5WywjteUc5_3lHiullg,4086 +litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py,sha256=nDicAulQI8BuWFoYAAy_WdM1qodUrKZ2DBvNv9-aoxw,4192 +litellm/llms/vertex_ai/vertex_ai_partner_models/main.py,sha256=Bx5ivMNhSLz30uqsnDd4cbOyAjE642D6ekrdYtOOLGw,8908 +litellm/llms/vertex_ai/vertex_embeddings/__pycache__/embedding_handler.cpython-310.pyc,, +litellm/llms/vertex_ai/vertex_embeddings/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/vertex_ai/vertex_embeddings/__pycache__/types.cpython-310.pyc,, +litellm/llms/vertex_ai/vertex_embeddings/embedding_handler.py,sha256=u4QxfvD-wxBwE_FJVi1g_zERdlT9OvXIJtYd4l7lOsY,8551 +litellm/llms/vertex_ai/vertex_embeddings/transformation.py,sha256=m1EJLA0rjGRCqawnuRHSL3G7jn4AWlIXgObNeFlylMw,9386 +litellm/llms/vertex_ai/vertex_embeddings/types.py,sha256=X6gjNP0IwvVewSy4LlFD_Ec92GN7ukn8rpf6KuOb9i4,1856 +litellm/llms/vertex_ai/vertex_llm_base.py,sha256=jPoXZNLxpqmFjfz4gjtBczhj-PSLCLn_-jdcor4m2i4,19393 +litellm/llms/vertex_ai/vertex_model_garden/__pycache__/main.cpython-310.pyc,, +litellm/llms/vertex_ai/vertex_model_garden/main.py,sha256=6eRL6aevquWdxttXq6fasqnfbeojoL-XdSrO1uH0Xb8,5137 +litellm/llms/vllm/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/vllm/common_utils.py,sha256=f1edBBtBrzH_ElAwuCKf-nFGgWiGx9slCygLtTRuV_4,2428 +litellm/llms/vllm/completion/__pycache__/handler.cpython-310.pyc,, +litellm/llms/vllm/completion/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/vllm/completion/handler.py,sha256=-R02bpmQFkpjwF9Xsr5fCp7sWpj1qzXug1c2wfOi50Y,5975 +litellm/llms/vllm/completion/transformation.py,sha256=xt7YaCOsexESEH-XxtTFslOZVjU9QmYWaaIr6PDFXC4,352 +litellm/llms/vllm/passthrough/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/vllm/passthrough/transformation.py,sha256=GqtDxyuNgnhcM3--DZMZU-m2WwLKBr106xvuihAAqPg,943 +litellm/llms/volcengine.py,sha256=Y8DulwUwCPlbWX5XAwC8WjMwZbQOLMvz5tMrOly2RWk,2736 +litellm/llms/voyage/embedding/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/voyage/embedding/transformation.py,sha256=D7J-PHNI8F6dY1wLR3aYsN3JrkcDi7ouX1WHx0emtx4,4655 +litellm/llms/watsonx/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/watsonx/chat/__pycache__/handler.cpython-310.pyc,, +litellm/llms/watsonx/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/watsonx/chat/handler.py,sha256=zW_gPUb6493a5Q_wpnq5yxdceRBaN3iqMIVeVaypuOw,3089 +litellm/llms/watsonx/chat/transformation.py,sha256=cey046KjXwvbQBzHH06JMttT9eZk6Zu9naMZSdI5G2k,4517 +litellm/llms/watsonx/common_utils.py,sha256=Pmd7n-cH6Vkp_5MUeQ0VHnqB-JERub8k53SX1UjxHBE,10380 +litellm/llms/watsonx/completion/__pycache__/handler.cpython-310.pyc,, +litellm/llms/watsonx/completion/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/watsonx/completion/handler.py,sha256=6usOrXnld_3oMppUeZsLSgHbSsVQyKwf-ItbXP8kF_g,69 +litellm/llms/watsonx/completion/transformation.py,sha256=bUcP4GJZ5JljUYA6qp4PR4QYZr3jG5gaSAdce2XqkDY,14340 +litellm/llms/watsonx/embed/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/watsonx/embed/transformation.py,sha256=yxfzjb9H3auW_RaV73koXLFWQhddv5uF8kPam6icfKI,3435 +litellm/llms/xai/__pycache__/common_utils.cpython-310.pyc,, +litellm/llms/xai/chat/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/xai/chat/transformation.py,sha256=LicDVaR_BzCdQyxfAphhjLxqLYCLmIWxY_Q99Ew-1wY,5506 +litellm/llms/xai/common_utils.py,sha256=2Q632FPL5pd1_puRFYz0f_bNvi0wBPFed9jLz3peIc8,2762 +litellm/llms/xinference/image_generation/__init__.py,sha256=KeMIwvqLqfJeQWwQ7GJtfnvSik02mphi2sEtG36wxcI,348 +litellm/llms/xinference/image_generation/__pycache__/__init__.cpython-310.pyc,, +litellm/llms/xinference/image_generation/__pycache__/transformation.cpython-310.pyc,, +litellm/llms/xinference/image_generation/transformation.py,sha256=tpPUGmKx5IvLMs0_mVNDso71BQo7KlDcM6zbY23CxII,1475 +litellm/main.py,sha256=6WdqKjBPp51P2_KziUlVKj8vvyajg-TDUcnro_AeX3g,231041 +litellm/model_prices_and_context_window_backup.json,sha256=_FQHZQDLgo0mwiyGSoXwbFh_bU9xpfq5Da2vCf6Agis,570204 +litellm/mypy.ini,sha256=OJMr9ZbxsY5yhdNwEzEfcsBnGknt3DagwWQrVlJGbWE,290 +litellm/passthrough/README.md,sha256=VmR5kFLONXTqvISdUiyNAlc6CYaYZ6k4v83IDC1fpWo,2534 +litellm/passthrough/__init__.py,sha256=VBw0A6NvFOSdu0RRjKrcg5A-r7vA59DjXMEFEYGuauc,206 +litellm/passthrough/__pycache__/__init__.cpython-310.pyc,, +litellm/passthrough/__pycache__/main.cpython-310.pyc,, +litellm/passthrough/__pycache__/utils.cpython-310.pyc,, +litellm/passthrough/main.py,sha256=SM-NiVikwHTciscgz6A4Jxm-660KN3OWOSaj2RzbwA0,11348 +litellm/passthrough/utils.py,sha256=Q_BD0OV5eUEo_b07W_BW9b6ChClUT1UIq33lzg71NnE,1423 +litellm/proxy/.gitignore,sha256=v2ZocUpppVuVfYJh1Bd1JpjpYSLxifJdClMEo0oOdT0,17 +litellm/proxy/README.md,sha256=UYsgc2W0DfQtQGpUJOunMDsTpowp_zzAlNG16XOcJTA,1353 +litellm/proxy/__init__.py,sha256=Il5Q9ATdX8yXqVxtP_nYqUhExzxPC_qk_WXQ_4h0exg,16 +litellm/proxy/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/__pycache__/_logging.cpython-310.pyc,, +litellm/proxy/__pycache__/_types.cpython-310.pyc,, +litellm/proxy/__pycache__/caching_routes.cpython-310.pyc,, +litellm/proxy/__pycache__/common_request_processing.cpython-310.pyc,, +litellm/proxy/__pycache__/custom_auth_auto.cpython-310.pyc,, +litellm/proxy/__pycache__/custom_prompt_management.cpython-310.pyc,, +litellm/proxy/__pycache__/custom_sso.cpython-310.pyc,, +litellm/proxy/__pycache__/custom_validate.cpython-310.pyc,, +litellm/proxy/__pycache__/health_check.cpython-310.pyc,, +litellm/proxy/__pycache__/lambda.cpython-310.pyc,, +litellm/proxy/__pycache__/litellm_pre_call_utils.cpython-310.pyc,, +litellm/proxy/__pycache__/mcp_tools.cpython-310.pyc,, +litellm/proxy/__pycache__/post_call_rules.cpython-310.pyc,, +litellm/proxy/__pycache__/prisma_migration.cpython-310.pyc,, +litellm/proxy/__pycache__/proxy_cli.cpython-310.pyc,, +litellm/proxy/__pycache__/proxy_server.cpython-310.pyc,, +litellm/proxy/__pycache__/route_llm_request.cpython-310.pyc,, +litellm/proxy/__pycache__/utils.cpython-310.pyc,, +litellm/proxy/_experimental/__pycache__/post_call_rules.cpython-310.pyc,, +litellm/proxy/_experimental/mcp_server/__pycache__/cost_calculator.cpython-310.pyc,, +litellm/proxy/_experimental/mcp_server/__pycache__/db.cpython-310.pyc,, +litellm/proxy/_experimental/mcp_server/__pycache__/mcp_server_manager.cpython-310.pyc,, +litellm/proxy/_experimental/mcp_server/__pycache__/rest_endpoints.cpython-310.pyc,, +litellm/proxy/_experimental/mcp_server/__pycache__/server.cpython-310.pyc,, +litellm/proxy/_experimental/mcp_server/__pycache__/sse_transport.cpython-310.pyc,, +litellm/proxy/_experimental/mcp_server/__pycache__/tool_registry.cpython-310.pyc,, +litellm/proxy/_experimental/mcp_server/__pycache__/utils.cpython-310.pyc,, +litellm/proxy/_experimental/mcp_server/auth/__pycache__/litellm_auth_handler.cpython-310.pyc,, +litellm/proxy/_experimental/mcp_server/auth/__pycache__/user_api_key_auth_mcp.cpython-310.pyc,, +litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py,sha256=Q8v_8nH_noReYNFMqHvgTfbk9RoDTnFvpMoWi9ujYCw,883 +litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py,sha256=Xp5JbEJN2CFV1SHdEhykFmMhE8YOw7Q3MgRh6b_a5oc,16595 +litellm/proxy/_experimental/mcp_server/cost_calculator.py,sha256=kzP2_6qA-DsNIySHv2ESIfyunhrEsTEDk07gcoGUCJA,2768 +litellm/proxy/_experimental/mcp_server/db.py,sha256=DPJ4yM9N2wupgu8yDCsYsDJcknFt_oecNe5U7D19rxE,7867 +litellm/proxy/_experimental/mcp_server/mcp_server_manager.py,sha256=qmpqyk2e4w-aZfHOQ82TFo7aVMBes1NOGqgcfnjsbmE,20752 +litellm/proxy/_experimental/mcp_server/rest_endpoints.py,sha256=jxVWhjitD7nlyNo2Qr1oFZ5BJEfz862X9-9nx1HliP8,8671 +litellm/proxy/_experimental/mcp_server/server.py,sha256=hmGm5MhKvf-moBzFWo5Z3LBjdLCbL7UnW7VZL7rQaSM,24838 +litellm/proxy/_experimental/mcp_server/sse_transport.py,sha256=5Gf9sBiPli_VaIC2NJjYN5O_o2a8tg9A15uzb_Iy30s,6180 +litellm/proxy/_experimental/mcp_server/tool_registry.py,sha256=DFt5YCed1_3ZOnQ9yoJAyzbrsujUqB9MzExq6ojgbvk,3228 +litellm/proxy/_experimental/mcp_server/utils.py,sha256=8rLocH4ZDKn03zPtl5JvsJo9jopPoW9IIsatTQjT2Z0,3002 +litellm/proxy/_experimental/out/_next/static/chunks/101-d73ce49080d4c1cd.js,sha256=tgJp_ye9Xyyu_r8Zq81qnsh2GjAuBHdafZ3LBB7FrVw,162516 +litellm/proxy/_experimental/out/_next/static/chunks/117-a0da667066d322b6.js,sha256=qNUcXx_NYhNqbtgahKnrIuV67OD1xrsz8Pev6RYXNCk,124100 +litellm/proxy/_experimental/out/_next/static/chunks/13b76428-ebdf3012af0e4489.js,sha256=QVJOg2NW5huLCFnsmrvUPHVSa8zRfhrwnvg4Vph3Ulw,59303 +litellm/proxy/_experimental/out/_next/static/chunks/175-dd2199f3cc968303.js,sha256=nT7ZcUHX7_ur5VoewP2R85Dlw_5TNac_0RRkf2oTV4s,660262 +litellm/proxy/_experimental/out/_next/static/chunks/250-b971d983c18cd31a.js,sha256=5VYErmAznkc-V3s2OjhPylL0I9aXuUKK5p1Vg7TLyw4,86883 +litellm/proxy/_experimental/out/_next/static/chunks/298-50b259229b9ee9c1.js,sha256=aa7vfIqTcqNGgB_N20Ax-RoGj0Z91KLsq9yJFVDw6VY,51641 +litellm/proxy/_experimental/out/_next/static/chunks/3014691f-b7b79b78e27792f3.js,sha256=4ETJ2eRbeVM6gstCpDnquThAnyw6oa0bkpJNYCGJk5k,711 +litellm/proxy/_experimental/out/_next/static/chunks/362-9467dd80c4a5b451.js,sha256=HgWcYNxlaB7JHpLerFcTRrlkvRNHuYZWkm9b_Si0ifc,1633583 +litellm/proxy/_experimental/out/_next/static/chunks/402-239a4ed70dc393da.js,sha256=DX6Y3RrQf6B6qjTLohbqn2cwGiOaG-tVgbWS4909-T4,329275 +litellm/proxy/_experimental/out/_next/static/chunks/699-2c51ca18af778c8f.js,sha256=S3cwKVE6y-7z_i6Xqi_vQaqVCLEvFvvCwybtnrzdIFc,7478 +litellm/proxy/_experimental/out/_next/static/chunks/729-26dfe044103c200b.js,sha256=OchYCx-6qM79gBEmBBc5eCCvyAY582Ch8b22DLKJ9yE,25202 +litellm/proxy/_experimental/out/_next/static/chunks/899-3ae2f19f8593c388.js,sha256=OY4fznyKCqeMQPuJZ4Kwp2WOhOYWL7rpVMcvgjdyB_M,49892 +litellm/proxy/_experimental/out/_next/static/chunks/app/_not-found/page-3b0daafcbe368586.js,sha256=FVXglwXR4zvyY1rzGgR74k-Ll-lZcOEBjs2lxHRZ-g8,1751 +litellm/proxy/_experimental/out/_next/static/chunks/app/layout-25a743106e1c9456.js,sha256=CVKV5zydnRGoHlt1X1aP_CiyUA-a_Sv3-QBB8BBtgbg,425 +litellm/proxy/_experimental/out/_next/static/chunks/app/model_hub/page-790cc3958e4c7989.js,sha256=7-5GHBs7lOzrVsUhmRTpJcaMThI4sCRzN3p9-2PMHco,537 +litellm/proxy/_experimental/out/_next/static/chunks/app/model_hub_table/page-a6dbc07ffdf91e51.js,sha256=g1hxjPbIZEoDulYFvGqcoDOfJ4rEoZct26qwkOUCdxI,536 +litellm/proxy/_experimental/out/_next/static/chunks/app/onboarding/page-1d66189e6879e9b2.js,sha256=0U4C0nOhUl5i2cgAMdL9nEKAauEPQgwxCgSCAlT_mpc,3958 +litellm/proxy/_experimental/out/_next/static/chunks/app/page-b87a1a582e784114.js,sha256=07R83u8J0v_FVgC07oZzoad8EL0KLGTzrIaaPg6Y1VI,740857 +litellm/proxy/_experimental/out/_next/static/chunks/fd9d1056-205af899b895cbac.js,sha256=_pOUuvMP6W79SuhX2lFzzSr-j38Lyc_d3CKWumBBk88,172836 +litellm/proxy/_experimental/out/_next/static/chunks/framework-b370f160bb96059c.js,sha256=ikw-wVuyV_hCSeg6hXlhMBokMbd8sTUcAQTfUlQPq_8,140039 +litellm/proxy/_experimental/out/_next/static/chunks/main-7e39698e9e999d78.js,sha256=zlJcDGMcXuKTGRfq1GeGljSRQj6QwlZ6lEppwVunYQU,116823 +litellm/proxy/_experimental/out/_next/static/chunks/main-app-475d6efe4080647d.js,sha256=fkUmQy8TrEWpzsJ7XSJCuLpw4bTq77EO3Ijxa62eFm4,468 +litellm/proxy/_experimental/out/_next/static/chunks/pages/_app-15e2daefa259f0b5.js,sha256=czAxvvVE7rp90Snsx0rMg8Vc2W968H3QyRE_CVynE_Y,284 +litellm/proxy/_experimental/out/_next/static/chunks/pages/_error-28b803cb2479b966.js,sha256=14QByZ2qNj-M-_zFTtp5gaOpNolae8jFh05D0V7yKWo,250 +litellm/proxy/_experimental/out/_next/static/chunks/polyfills-42372ed130431b0a.js,sha256=CXPB1kyIrcjjyVBBDLWLKI9yEY1ZZbeASUON648vloM,112594 +litellm/proxy/_experimental/out/_next/static/chunks/webpack-a426aae3231a8df1.js,sha256=WLI8GFuQRFBANazbtEJaQHxrBOQf8ZMmYMFerE94eCY,3858 +litellm/proxy/_experimental/out/_next/static/css/31b7f215e119031e.css,sha256=JkQZSK9uOMMbkhzvz_dWi42rqqlnPOup5vQKygDR24Q,2300 +litellm/proxy/_experimental/out/_next/static/css/9bac0afa9d50dc23.css,sha256=R7x2U8ITi0eyAek2u8MQEAlj1mUaJB2r9w7ePh4T4z4,450945 +litellm/proxy/_experimental/out/_next/static/iJ5kjJ7CT1kw0EAhrt4kc/_buildManifest.js,sha256=y8M4vrnoLfkifLYZNnI88j-bE5fEP2RnFWgMpNd47Sg,224 +litellm/proxy/_experimental/out/_next/static/iJ5kjJ7CT1kw0EAhrt4kc/_ssgManifest.js,sha256=Z49s4suAsf5y_GfnQSvm4qtq2ggxEbZPfEDTXjy6XgA,80 +litellm/proxy/_experimental/out/_next/static/media/26a46d62cd723877-s.woff2,sha256=lOXII-cuccwg9L-imwQ08iYAQJZdnQZsDny13Jn_1sM,18820 +litellm/proxy/_experimental/out/_next/static/media/55c55f0601d81cf3-s.woff2,sha256=zhKUdvQpmyFbVbHu0vxDJLRr2yZB4R1Z4kgbdEpH0RQ,25908 +litellm/proxy/_experimental/out/_next/static/media/581909926a08bbc8-s.woff2,sha256=6sXLry_RZ9cH4ezy5o4q8jK-nPyVJXQWRBfzKllMXvw,19072 +litellm/proxy/_experimental/out/_next/static/media/8e9860b6e62d6359-s.woff2,sha256=oo6208y1NK4MlMqZk3HfAkqrYLCMPIpXIO6eMvoPqqI,85272 +litellm/proxy/_experimental/out/_next/static/media/97e0cb1ae144a2a9-s.woff2,sha256=PSMwBhtNmlpSF4kzHs5Rp1X9plNe2ybXQJtxBSizzQ0,11220 +litellm/proxy/_experimental/out/_next/static/media/df0a9ae256c0569c-s.woff2,sha256=jbAP9Gxnsizai-2GWs9wd2UcrI0oQdW0CYBVa0iWGTE,10280 +litellm/proxy/_experimental/out/_next/static/media/e4af272ccee01ff0-s.p.woff2,sha256=yUB2RZPQ_l1Za-MnynVYhV4BgDn7eFCaohkh_TZEw-Q,48432 +litellm/proxy/_experimental/out/assets/audit-logs-preview.png,sha256=lCcHDtsECm0GSKDqbIdpMDv9V75fcVCh0ONryCIyZhQ,240654 +litellm/proxy/_experimental/out/assets/logos/aim_logo.jpeg,sha256=gHVw2hPsPu1jnngXJtJgIT2CFru11IIscfcpKsuGX2s,3754 +litellm/proxy/_experimental/out/assets/logos/anthropic.svg,sha256=7G6ybx5PKo831xWobQrplQhIBHDGsoRvXt95Ok45I7w,381 +litellm/proxy/_experimental/out/assets/logos/arize.png,sha256=9T-B-fjArLRchbdE_-Vpm13vTcVl1rhuzCfALaovB7E,14249 +litellm/proxy/_experimental/out/assets/logos/assemblyai_small.png,sha256=Y8kw7Yj1OvAboYW4FC59FiAUAmkcxNMUQO3sYCkM3Mk,414 +litellm/proxy/_experimental/out/assets/logos/aws.svg,sha256=8qgeYZ-EnJ0JOlutRyG3NTwudM8vOXf8WF8dHZpZ-pI,2590 +litellm/proxy/_experimental/out/assets/logos/bedrock.svg,sha256=kXcK_2QL5E4p00pEb1nm-cHSYZbhYqoHQ_KuT2CbVBA,2268 +litellm/proxy/_experimental/out/assets/logos/braintrust.png,sha256=fBBorXCNdXEeOcLlOQHaHQ7e4j151k9LUG54b989oIU,10428 +litellm/proxy/_experimental/out/assets/logos/cerebras.svg,sha256=98_uWhwHAQJ0HrDnaD0CKXkEVtLDCLSd_2TRcQ3-YEc,8238 +litellm/proxy/_experimental/out/assets/logos/cohere.svg,sha256=yYay3GJsUCIbDyWv3VGXcfBptHYvcvMyuByJmzGlwyY,742 +litellm/proxy/_experimental/out/assets/logos/databricks.svg,sha256=lOTTGQb42XVcYn_xGxoOwKWGoiIVY6W3gyyfTl9oxvc,528 +litellm/proxy/_experimental/out/assets/logos/datadog.png,sha256=N93E1dEia45vVbSLSO4_kDVwVhH0j-eK4EEXB_7ltS8,5213 +litellm/proxy/_experimental/out/assets/logos/deepgram.png,sha256=pw03wmmKQUgNaD0D68wVdwFJJOvYtQlELMh4dptH3Sc,1224 +litellm/proxy/_experimental/out/assets/logos/deepseek.svg,sha256=eT3iTUkd3gY7ms2qQhLn_ACqsA92pcKZugjs1iwJQsk,2360 +litellm/proxy/_experimental/out/assets/logos/elevenlabs.png,sha256=5CICsWhyJeBcAmGUfsfokU1vu9r3IsmV4gauwJlnQt4,35410 +litellm/proxy/_experimental/out/assets/logos/fireworks.svg,sha256=8cR4K4a8A6NjI_1orWzDdsay6-V7cBzJWOvWuNN-_9Y,592 +litellm/proxy/_experimental/out/assets/logos/google.svg,sha256=i2lCUcTYjnrJ8HJfUCs-8_ulcpHG6UCMoV2N905xpic,728 +litellm/proxy/_experimental/out/assets/logos/groq.svg,sha256=24JNwcmDMj5IvOSJQNd9DObhqgEsTGncI6m8m_J4EUo,619 +litellm/proxy/_experimental/out/assets/logos/lago.svg,sha256=pHzKylc9QctwWpDBNehCRDM1PO53bGdS2TDpgArsKYI,6351 +litellm/proxy/_experimental/out/assets/logos/lakeraai.jpeg,sha256=kHY7--Qp-NvjZuyKesXe_jn0L_3YegH6adpU-ByRGNs,2617 +litellm/proxy/_experimental/out/assets/logos/langfuse.png,sha256=NEhtppv2DqnAw7fSi1eQ7ILwIsXzr5wMrCGtEMjWH9Y,10860 +litellm/proxy/_experimental/out/assets/logos/langsmith.png,sha256=rEX3FdUoF-07PshEOauDNE2PpcGjMWyCwV6eqib17Rw,5495 +litellm/proxy/_experimental/out/assets/logos/litellm.jpg,sha256=ZnPgg_2nBqNuMuqW2ZSrWNISVaK6HiSuNB4e5xttQto,24694 +litellm/proxy/_experimental/out/assets/logos/llm_guard.png,sha256=MQqQbaVHVf_0Ny9JZhMjw1A1l1DKrGtSbmlsfg1hROc,48665 +litellm/proxy/_experimental/out/assets/logos/mcp_logo.png,sha256=SFF46c4iQoLUxJlV9eIVETJKQbykXmUrD2hU9HPW4C0,3902 +litellm/proxy/_experimental/out/assets/logos/microsoft_azure.svg,sha256=jqZYpbjcySrb-DumDfTXIJtg_xMx1kuGydLd6W62v8Q,7385 +litellm/proxy/_experimental/out/assets/logos/mistral.svg,sha256=ci90sonZVIa0NmL-JPqIOzM3ASlvYYQGzQ7VAimRcLY,655 +litellm/proxy/_experimental/out/assets/logos/nvidia_triton.png,sha256=HEpnsibXGWy3rDR5ukQVxWPtXsJkoP6vtXICyiMM_-k,5704 +litellm/proxy/_experimental/out/assets/logos/ollama.svg,sha256=m-lH7K_YLOPuGagOSM5GHR-bNgdJETfj3f0iHhTiRA8,8614 +litellm/proxy/_experimental/out/assets/logos/openai_small.svg,sha256=1JTcN5MCmWpOZqCMpGuir1mb9x6LWaij-i_fV7CH1OA,1658 +litellm/proxy/_experimental/out/assets/logos/openmeter.png,sha256=zQCieeyRVIX6CQdDIqXAkiQyu-7EVDSQNLz3VbbRrAQ,1114 +litellm/proxy/_experimental/out/assets/logos/openrouter.svg,sha256=sn4BPonpOVIfQu_1PW5chM5AjRao6xr1Xe1zW7T3YQI,1096 +litellm/proxy/_experimental/out/assets/logos/otel.png,sha256=lVvT4CVA8fYMqUqREQ2vLRckMMzs-u59LSz41kF67lY,1949 +litellm/proxy/_experimental/out/assets/logos/perplexity-ai.svg,sha256=uY3kJNkb_685NsUhJ5_8oJ9xREiWx5dXmmriIpGpXnE,1272 +litellm/proxy/_experimental/out/assets/logos/presidio.png,sha256=3hH3hXUYKqpqHCW8p4bJs1d62GB8mVCq50S088K9dW4,62523 +litellm/proxy/_experimental/out/assets/logos/sambanova.svg,sha256=K5PwPyWYfBfXwtHhYe8zHZtqH5jAHp-P5blb9LjMdwA,18217 +litellm/proxy/_experimental/out/assets/logos/secret_detect.png,sha256=cQCsmCW3jalm7npMAq6xN6aP52xbMg9aEGkMoAJcfjg,15590 +litellm/proxy/_experimental/out/assets/logos/togetherai.svg,sha256=7trowWe77_hoAMaqOzdPpkyagAIP26aaRSKVKpFOrFc,560 +litellm/proxy/_experimental/out/assets/logos/xai.svg,sha256=TGhaYixZxpnoJOIWypiVgM8SEF5Ik1LLIBcsfIr5kMM,937 +litellm/proxy/_experimental/out/favicon.ico,sha256=Ikbq6HOjEekHeOnx68AzqSl19Y5YPKwdQv7FyKK6Q8M,15406 +litellm/proxy/_experimental/out/index.html,sha256=_FXvCHCx5a5onKwXtEbVYROZDzAW9i1eHDLWgfPIet0,5460 +litellm/proxy/_experimental/out/index.txt,sha256=HyKyyDqhmJ49Mj5aKczXNZteRCzWqEejf0g795ALUrg,3139 +litellm/proxy/_experimental/out/model_hub.txt,sha256=VWeBtjwOiiYjyUHYs0Z6AqXq2Yu_cZWmMPjOZ6h8_po,3251 +litellm/proxy/_experimental/out/model_hub_table.html,sha256=NocskltMvX16mF5STR6R3H3D-KTqJ62EOJDKJJctQrY,5644 +litellm/proxy/_experimental/out/model_hub_table.txt,sha256=y8OvpHYC9aeQd91eCIfDVfXSEa5Aj83JAMMDoUkGh2I,3274 +litellm/proxy/_experimental/out/next.svg,sha256=VZld-tbstJRaHoVt3KA8XhaqW_E_0htN9qdK55NXvPw,1375 +litellm/proxy/_experimental/out/onboarding.html,sha256=y7ugy0Y3VuPJjQpxfJUpZZ9fotyE4w60Vfc_eWEmDSI,5575 +litellm/proxy/_experimental/out/onboarding.txt,sha256=Hv6LAt-uzWbWMN0dvzzOQDOCE4Vd3sV6u0zTw8XgZxc,3214 +litellm/proxy/_experimental/out/vercel.svg,sha256=P6XNdXtBjhivxo3eutVfRDIG5BAyeSHdsr8b5zFliIA,629 +litellm/proxy/_experimental/post_call_rules.py,sha256=0tMsQ8ViObIH2wJcEfdWt9CZ2FAkj6HoBIrAr59VvFc,170 +litellm/proxy/_logging.py,sha256=3zwPYBRv2EL1OB8Tk7_O6qU6lXCL2zSBNshe7rfyZbU,1055 +litellm/proxy/_new_new_secret_config.yaml,sha256=B0z7vBkykOHQ6rRL1D9jztY2Xs-tXbu38frs1LaEmHc,494 +litellm/proxy/_new_secret_config.yaml,sha256=CeYZyRkqi_M75ua3Wi7Mk91usk4kbSO0GWlRRnjOUWU,611 +litellm/proxy/_super_secret_config.yaml,sha256=go-txuGiBfjn8vrxTYrB9Sto_BRWjnMiTrStJcSh5Xw,3480 +litellm/proxy/_types.py,sha256=3AQZpDHNYLLYF2RDxIOvBGvfa5Xb7DVkMI3oI7wb4zU,104739 +litellm/proxy/analytics_endpoints/__pycache__/analytics_endpoints.cpython-310.pyc,, +litellm/proxy/analytics_endpoints/analytics_endpoints.py,sha256=4V1VxUkJqtw1UpMepoI8TL3WRRwc-TRy0eXMOmgNedY,3324 +litellm/proxy/anthropic_endpoints/__pycache__/endpoints.cpython-310.pyc,, +litellm/proxy/anthropic_endpoints/endpoints.py,sha256=RUbQ7yLcXlV_RKivKZoLmxaQXgMZE2ak92vHoX-3CXQ,7679 +litellm/proxy/auth/__pycache__/auth_checks.cpython-310.pyc,, +litellm/proxy/auth/__pycache__/auth_checks_organization.cpython-310.pyc,, +litellm/proxy/auth/__pycache__/auth_exception_handler.cpython-310.pyc,, +litellm/proxy/auth/__pycache__/auth_utils.cpython-310.pyc,, +litellm/proxy/auth/__pycache__/handle_jwt.cpython-310.pyc,, +litellm/proxy/auth/__pycache__/litellm_license.cpython-310.pyc,, +litellm/proxy/auth/__pycache__/model_checks.cpython-310.pyc,, +litellm/proxy/auth/__pycache__/oauth2_check.cpython-310.pyc,, +litellm/proxy/auth/__pycache__/oauth2_proxy_hook.cpython-310.pyc,, +litellm/proxy/auth/__pycache__/rds_iam_token.cpython-310.pyc,, +litellm/proxy/auth/__pycache__/route_checks.cpython-310.pyc,, +litellm/proxy/auth/__pycache__/user_api_key_auth.cpython-310.pyc,, +litellm/proxy/auth/auth_checks.py,sha256=-xU7VyWXCIouW14OwBmLAu2CcrsqGX-dm4hxgUJ44tg,54502 +litellm/proxy/auth/auth_checks_organization.py,sha256=LDXOnn9gQ7D4zbhJF6ah6Mo4Gc9xv26VsSpPF-JxkTw,6460 +litellm/proxy/auth/auth_exception_handler.py,sha256=aWUlZQDdxRS9khmhaFLYXKoormaeM9MZGCPKXlUlwsM,4392 +litellm/proxy/auth/auth_utils.py,sha256=MzKGkT-KqptbzcWBnK3Up1SOIMs-Cf3h20LvwA7Gc9I,19382 +litellm/proxy/auth/handle_jwt.py,sha256=O2IaIO-SheN20bqt8PxwkwUxVqxiXlHG022vXpSM6TE,40044 +litellm/proxy/auth/litellm_license.py,sha256=Mv3DFjM-v9W9hMnDO_4qtT-n_b1MZG50UTorju9ZGEs,7303 +litellm/proxy/auth/model_checks.py,sha256=NCOSlBsUTEMeDSE1AZLLTtE66FEh89xIzzbBeBYbHRo,9532 +litellm/proxy/auth/oauth2_check.py,sha256=LDRdfyp9LQJbIpJbs1K2HwgxIKWVGO5YFRgUuFJhHXM,2934 +litellm/proxy/auth/oauth2_proxy_hook.py,sha256=ViXMvTdDop5g86dYIOG6SsIY7vBf_UBapCBAJUk7nq0,1708 +litellm/proxy/auth/public_key.pem,sha256=KlTCQCWViTHUwzzxCu9KyFCX8YTdnIfGJlx7jiotak4,451 +litellm/proxy/auth/rds_iam_token.py,sha256=05khLciCp396xRXivrDwE-BThiurxiLeBogHEFpjQ5w,6494 +litellm/proxy/auth/route_checks.py,sha256=SaMXvxCAuSnSqG-43oVwsHVUMcNWo6iMcIvZbvrCR4I,12236 +litellm/proxy/auth/user_api_key_auth.py,sha256=NqWepLpyiOr-FLD8nV2aYkb2TNvnCxArU_efETrtWRs,51083 +litellm/proxy/batches_endpoints/__pycache__/endpoints.cpython-310.pyc,, +litellm/proxy/batches_endpoints/endpoints.py,sha256=LnOtwJ19bpgoMItjN1ICSWZSjc3sVyLd9S3Q7h7a3hc,18805 +litellm/proxy/cached_logo.jpg,sha256=1zH55lRC5bPLvLNPxg-JY3WJvlwZMNlmwx2sjQDDCx0,50535 +litellm/proxy/caching_routes.py,sha256=tFPwHofmBXA487GOjmNS-6gP3AWZWtdYL1HufWL0oEg,8327 +litellm/proxy/client/README.md,sha256=mWdWlwkADMjdcdwhySp30YjkpAgbj6k7Z4Q137avog8,10171 +litellm/proxy/client/__init__.py,sha256=OTCUY4an0SqoamdaoiTP5sjYa8g_rj7WDh81fxe4ox0,444 +litellm/proxy/client/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/client/__pycache__/chat.cpython-310.pyc,, +litellm/proxy/client/__pycache__/client.cpython-310.pyc,, +litellm/proxy/client/__pycache__/credentials.cpython-310.pyc,, +litellm/proxy/client/__pycache__/exceptions.cpython-310.pyc,, +litellm/proxy/client/__pycache__/health.cpython-310.pyc,, +litellm/proxy/client/__pycache__/http_client.cpython-310.pyc,, +litellm/proxy/client/__pycache__/keys.cpython-310.pyc,, +litellm/proxy/client/__pycache__/model_groups.cpython-310.pyc,, +litellm/proxy/client/__pycache__/models.cpython-310.pyc,, +litellm/proxy/client/__pycache__/users.cpython-310.pyc,, +litellm/proxy/client/chat.py,sha256=ZvGNps3lLnbkZjVAqmEFMfxIohBYPOQdJwyM2DkTWQw,3996 +litellm/proxy/client/cli/README.md,sha256=tedXh66iHxfWQ27iZDP9eaSmK6tgRfPcXHl-57ljZAc,11976 +litellm/proxy/client/cli/__init__.py,sha256=SZGkzpjktHXBdFoRByyPGpfXw-xtnFm3VBc_gzs7Zuc,86 +litellm/proxy/client/cli/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/client/cli/__pycache__/interface.cpython-310.pyc,, +litellm/proxy/client/cli/__pycache__/main.cpython-310.pyc,, +litellm/proxy/client/cli/commands/__init__.py,sha256=qNhF-vYv3SqMMy3TykGtJW8u3BzcpMkEvzyskPlz0SY,48 +litellm/proxy/client/cli/commands/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/client/cli/commands/__pycache__/auth.cpython-310.pyc,, +litellm/proxy/client/cli/commands/__pycache__/chat.cpython-310.pyc,, +litellm/proxy/client/cli/commands/__pycache__/credentials.cpython-310.pyc,, +litellm/proxy/client/cli/commands/__pycache__/http.cpython-310.pyc,, +litellm/proxy/client/cli/commands/__pycache__/keys.cpython-310.pyc,, +litellm/proxy/client/cli/commands/__pycache__/models.cpython-310.pyc,, +litellm/proxy/client/cli/commands/__pycache__/users.cpython-310.pyc,, +litellm/proxy/client/cli/commands/auth.py,sha256=naZGQouvtts_fV5xvW7bVGm50q6DAolt7FywkcbGhUA,6072 +litellm/proxy/client/cli/commands/chat.py,sha256=WqF4ZThZ6EZxJ4tQriViqb2PzQqiDanto5eWEysKz0E,2778 +litellm/proxy/client/cli/commands/credentials.py,sha256=dlj3t81TD2lMGCjm-BeEu17Y603istdtf_gqGzFq_Rw,3497 +litellm/proxy/client/cli/commands/http.py,sha256=FfrOwjTW1V-ydDoWoQrES0J2ROTmsVKH1pNor0x8-Ys,2698 +litellm/proxy/client/cli/commands/keys.py,sha256=NoOlwHFUFu3bJq0y9WYU51IYL1wWEqdv0M0CQvmVBWY,5994 +litellm/proxy/client/cli/commands/models.py,sha256=gsmQtIpaRhRneP2eN8ZQ0lVEueAYryymVrdlp4Yrpgs,15476 +litellm/proxy/client/cli/commands/users.py,sha256=Vtqz4q-hOpDYc7ondToRCGkUKFarhM6Si8OGFL-i2Gc,2769 +litellm/proxy/client/cli/interface.py,sha256=OK-f9vDxUR2SpUlZWpXoEcyjL7y2IzThq5275oiXKWA,6420 +litellm/proxy/client/cli/main.py,sha256=8ORt-zp9cEhmC9RDoh3S_5x3PdO-quf1Ik7H7HXOsds,3207 +litellm/proxy/client/client.py,sha256=72Bd5IQIk9KJ-IqiMrdvtS2-atRwH6q0KaIIGdoiu64,1560 +litellm/proxy/client/credentials.py,sha256=0bQi1jlcLsuL2zR0Ir6bOAvz4zcA4eP7FRyniCKbCeg,6480 +litellm/proxy/client/exceptions.py,sha256=kZUV_LWkmwb2ZwLJ8brGC0YXib4amuBGlVMqI3_78Y0,653 +litellm/proxy/client/health.py,sha256=cKyeW-6AJTkAbZ3FfLQuJk2L0vinYE40DChHidKFeWo,1506 +litellm/proxy/client/http_client.py,sha256=j4NcvbIal2a5J7UB2TLKv9akVrowbpgZWvMTsTKLpr4,3364 +litellm/proxy/client/keys.py,sha256=aDv6LLNb_Y5EbwklhbgIsJWfNL3lf4oqwapcCZyszGg,9871 +litellm/proxy/client/model_groups.py,sha256=53iLN_a3M2P-lGX_BzGqGNuLjU1ZSEFMfV4Ad5366go,2271 +litellm/proxy/client/models.py,sha256=pJHLgKfWCwozzJ0pEdyEIR1c8MK-y4I7zl1vf0ARfoQ,11204 +litellm/proxy/client/users.py,sha256=4_U2KvfiCJuUAXQa4MAOYJDXiyrI0m3B2VT8TZmwrsQ,2318 +litellm/proxy/common_request_processing.py,sha256=EqswrPTOOsCjIMg5rVJyRVEDZLZlC92lgnzyN4pS-ho,29372 +litellm/proxy/common_utils/__pycache__/admin_ui_utils.cpython-310.pyc,, +litellm/proxy/common_utils/__pycache__/banner.cpython-310.pyc,, +litellm/proxy/common_utils/__pycache__/callback_utils.cpython-310.pyc,, +litellm/proxy/common_utils/__pycache__/debug_utils.cpython-310.pyc,, +litellm/proxy/common_utils/__pycache__/encrypt_decrypt_utils.cpython-310.pyc,, +litellm/proxy/common_utils/__pycache__/http_parsing_utils.cpython-310.pyc,, +litellm/proxy/common_utils/__pycache__/load_config_utils.cpython-310.pyc,, +litellm/proxy/common_utils/__pycache__/openai_endpoint_utils.cpython-310.pyc,, +litellm/proxy/common_utils/__pycache__/proxy_state.cpython-310.pyc,, +litellm/proxy/common_utils/__pycache__/reset_budget_job.cpython-310.pyc,, +litellm/proxy/common_utils/__pycache__/swagger_utils.cpython-310.pyc,, +litellm/proxy/common_utils/__pycache__/timezone_utils.cpython-310.pyc,, +litellm/proxy/common_utils/admin_ui_utils.py,sha256=5-sbjOrQiueKMltq2hN4Z_bhCRGKFeSxfAr74wbkp98,6568 +litellm/proxy/common_utils/banner.py,sha256=gwCxhL9QcKBmrQ2d0FqqWfHozkMQEaLuQrqfpegK2fg,1051 +litellm/proxy/common_utils/callback_utils.py,sha256=K_JiTZMrO3_7au4gyUi_Pl94-nGIlqtevCOyN3o79Uw,14790 +litellm/proxy/common_utils/debug_utils.py,sha256=3M1Zib0P8EOAawdZ-wlfBZgUPqjJ1GRg2hISs6odYBA,9731 +litellm/proxy/common_utils/encrypt_decrypt_utils.py,sha256=Y_gUN3kEBTPwx1PvZtxOlUWc9WD_SK-CSWN8tBglhJQ,3037 +litellm/proxy/common_utils/html_forms/__pycache__/cli_sso_success.cpython-310.pyc,, +litellm/proxy/common_utils/html_forms/__pycache__/jwt_display_template.cpython-310.pyc,, +litellm/proxy/common_utils/html_forms/__pycache__/ui_login.cpython-310.pyc,, +litellm/proxy/common_utils/html_forms/cli_sso_success.py,sha256=TolvdezukT-CsVuX1MkQHCntXqklntoyf466hH5FY6c,6973 +litellm/proxy/common_utils/html_forms/jwt_display_template.py,sha256=btUd4MctIolE8qPAQtvSqazaF_cGoTDCjaqsC5LzeIA,8948 +litellm/proxy/common_utils/html_forms/ui_login.py,sha256=6FYnojCaeZyskLwqXAjkM8k02gdzY5a4qay2GiBMnq0,6843 +litellm/proxy/common_utils/http_parsing_utils.py,sha256=URbnFGAJiNelxyYLC_hbTl0DgsYkPDVT8E5DJZCDrzk,8402 +litellm/proxy/common_utils/load_config_utils.py,sha256=x3yVd6eVEtM1uX8H1kirzNZZqVPZ-HG8f_1aE3KuuDY,2468 +litellm/proxy/common_utils/openai_endpoint_utils.py,sha256=RfZHVnRLPUO6utK-C0a4UY-Dik7YVCs47sep_56WCGc,1240 +litellm/proxy/common_utils/proxy_state.py,sha256=H41iDfLOKTu1renuqH9xGYsxJzR-JxxSMDBCnoEml6w,1078 +litellm/proxy/common_utils/reset_budget_job.py,sha256=aa5sWRKQ0ij9k7ZM20KUnKfpkkkUpIPNsWeB7dF2Gbg,24312 +litellm/proxy/common_utils/swagger_utils.py,sha256=6m2QWns4I2bXjr1QXsJFZQJogagpUJo4gZZEklBJ2nA,1322 +litellm/proxy/common_utils/timezone_utils.py,sha256=3KAxBaq5GWIpykjHMdBM-o0zEVPgWzhnbANzlEHSsu4,991 +litellm/proxy/config_management_endpoints/__pycache__/pass_through_endpoints.cpython-310.pyc,, +litellm/proxy/config_management_endpoints/pass_through_endpoints.py,sha256=YviUGQxoJnFuL7zQppiEtUmueLcyPK7S-vyKZeTHeUE,702 +litellm/proxy/credential_endpoints/__pycache__/endpoints.cpython-310.pyc,, +litellm/proxy/credential_endpoints/endpoints.py,sha256=VZF7bO9Rm3F-gJEsEbYEez1xG4miHKZ3Y2CfxM6psOg,11831 +litellm/proxy/custom_auth_auto.py,sha256=hF6CDxwvH6U8I2l5yOP-e9Gzsu_51s4ydxIal3yWqjI,543 +litellm/proxy/custom_hooks/__pycache__/custom_ui_sso_hook.cpython-310.pyc,, +litellm/proxy/custom_hooks/custom_ui_sso_hook.py,sha256=MCDv7fsprUE-SlzmqiSZ_6hrWdPzXlQuOru_8QRnNJw,1118 +litellm/proxy/custom_prompt_management.py,sha256=XXc0i7r3daY-6fNHnhrUfTa-rgXToZGtrh8_KsWVfDw,1553 +litellm/proxy/custom_sso.py,sha256=9HmCfTfWwB94bOHdlQMTuRTivx9a7CXPbWoCaIP17Mw,1504 +litellm/proxy/custom_validate.py,sha256=8suWa_bUBr08ghRSwgQq9PYp7_wqHx-g9C0SjdRJJ8I,128 +litellm/proxy/db/__pycache__/base_client.cpython-310.pyc,, +litellm/proxy/db/__pycache__/check_migration.cpython-310.pyc,, +litellm/proxy/db/__pycache__/create_views.cpython-310.pyc,, +litellm/proxy/db/__pycache__/db_spend_update_writer.cpython-310.pyc,, +litellm/proxy/db/__pycache__/dynamo_db.cpython-310.pyc,, +litellm/proxy/db/__pycache__/exception_handler.cpython-310.pyc,, +litellm/proxy/db/__pycache__/log_db_metrics.cpython-310.pyc,, +litellm/proxy/db/__pycache__/prisma_client.cpython-310.pyc,, +litellm/proxy/db/base_client.py,sha256=JAg-ghx1qLNuxSRSn0B6Y_BB7a1ZIINNuvjOTJ_aByQ,1129 +litellm/proxy/db/check_migration.py,sha256=3s-2cLmwG4Fh7VHNsx6kzcK8fqKSrOG4wdQEufiw-hU,3580 +litellm/proxy/db/create_views.py,sha256=pCnxdjWMRjgE-IfG3SkpEzDRhGZ3MSUQ20xnn6UBzyE,7226 +litellm/proxy/db/db_spend_update_writer.py,sha256=-gVxUYOtgGL11J8E_-ks0oc8NuyV3tClGnt232hxYdg,52206 +litellm/proxy/db/db_transaction_queue/__pycache__/base_update_queue.cpython-310.pyc,, +litellm/proxy/db/db_transaction_queue/__pycache__/daily_spend_update_queue.cpython-310.pyc,, +litellm/proxy/db/db_transaction_queue/__pycache__/pod_lock_manager.cpython-310.pyc,, +litellm/proxy/db/db_transaction_queue/__pycache__/redis_update_buffer.cpython-310.pyc,, +litellm/proxy/db/db_transaction_queue/__pycache__/spend_log_cleanup.cpython-310.pyc,, +litellm/proxy/db/db_transaction_queue/__pycache__/spend_update_queue.cpython-310.pyc,, +litellm/proxy/db/db_transaction_queue/base_update_queue.py,sha256=2OqWs98YmeBJNGKucXFd-REkrwmNlrRDH3NdLyAOSA0,1744 +litellm/proxy/db/db_transaction_queue/daily_spend_update_queue.py,sha256=BZsjRpJwZ8Eg_SyOnZvfBqR7P0tAMqm3GUGxbHodn8U,6086 +litellm/proxy/db/db_transaction_queue/pod_lock_manager.py,sha256=FoB0RjSRnDjm-v-nGSp7Ur6xX1udV31SP5bwypomVqQ,6765 +litellm/proxy/db/db_transaction_queue/redis_update_buffer.py,sha256=-afba13naQgA_3QzXlfLDWYhrbNyNxxXhoCi7QMXN18,15375 +litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py,sha256=6Kl51iZkUDnxGwmzRwvxmuTZoCeHuy63x5Jtz0fQv9A,6395 +litellm/proxy/db/db_transaction_queue/spend_update_queue.py,sha256=cY-jp2bQ0V0GEeHR0rkFm872AX29qswTpXOuAJUtlng,8424 +litellm/proxy/db/dynamo_db.py,sha256=7HcN0JzzRKtwsmiqFFz_K6k3MABoICX65ChYkAxd1Gw,2935 +litellm/proxy/db/exception_handler.py,sha256=JWt2nWV1vC1MDz5hc8t516kSjtbJaIBf5F7q7P9J4rM,2053 +litellm/proxy/db/log_db_metrics.py,sha256=rDxyy9-QVasgetHonVJ2WXOWgw8FYgqTOa2wCPiK0iY,4821 +litellm/proxy/db/prisma_client.py,sha256=v1i_SAs8TMt5FW54Sy4Onr2I2oCAFerOt_lllCJ4zUI,7431 +litellm/proxy/discovery_endpoints/README.md,sha256=ZUudvy8B7yZS9kE5g0VG-xruPyoTneFJLDXXriOJR8E,386 +litellm/proxy/discovery_endpoints/__init__.py,sha256=KVOcpEvUtgnJ6hLmYvMmprtNoCGruf2qpCt5TOxc3gs,121 +litellm/proxy/discovery_endpoints/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/discovery_endpoints/__pycache__/ui_discovery_endpoints.cpython-310.pyc,, +litellm/proxy/discovery_endpoints/ui_discovery_endpoints.py,sha256=wRd710I2640hfY6rSN40e6VjveJCqgTnG2U0O7biJTM,636 +litellm/proxy/example_config_yaml/__pycache__/custom_auth.cpython-310.pyc,, +litellm/proxy/example_config_yaml/__pycache__/custom_auth_basic.cpython-310.pyc,, +litellm/proxy/example_config_yaml/__pycache__/custom_callbacks.cpython-310.pyc,, +litellm/proxy/example_config_yaml/__pycache__/custom_callbacks1.cpython-310.pyc,, +litellm/proxy/example_config_yaml/__pycache__/custom_guardrail.cpython-310.pyc,, +litellm/proxy/example_config_yaml/__pycache__/custom_handler.cpython-310.pyc,, +litellm/proxy/example_config_yaml/_health_check_test_config.yaml,sha256=DcUpvUly3ASBh57fdv51uZ5Nr7a3o7f7j1sQebILtjQ,512 +litellm/proxy/example_config_yaml/aliases_config.yaml,sha256=mN_iQHMZBv6CWXLF3BAOc-sdRrLKcFnWRbJIDXePXcA,1225 +litellm/proxy/example_config_yaml/azure_config.yaml,sha256=swb4kZv8EN6IfTW8G_uOFqjzXtcMxUpbf7Lz7G_GHS8,747 +litellm/proxy/example_config_yaml/bad_schema.prisma,sha256=QrtfMf8OePRSjR47IUsuIz_MVrrCkGOvGZ3gRL7zmoY,10498 +litellm/proxy/example_config_yaml/custom_auth.py,sha256=TFoYFOLW7m4n8fu1gO7kbA_P6n1sDthcdU-HGZb7Wog,1484 +litellm/proxy/example_config_yaml/custom_auth_basic.py,sha256=NEDMiRTQ2p5Ld6tHHL87blkPVA-I1i6yIi1WwvQfIPc,377 +litellm/proxy/example_config_yaml/custom_callbacks.py,sha256=-Vbqj9faOSsgiKFeG3KFgUEjLqcHjQ31b5fsT5OqXaU,2269 +litellm/proxy/example_config_yaml/custom_callbacks1.py,sha256=eew7xLt0c05t823p8n4BNz8FOJya2jVWEc44JYHiUWA,2044 +litellm/proxy/example_config_yaml/custom_guardrail.py,sha256=lHHZyFREZ2Kh3XaQ4pzW813KUbEcERsMbRA_CNs_Pso,3815 +litellm/proxy/example_config_yaml/custom_handler.py,sha256=n5-aScxHCLITANajO7rPfLcx2ta8nlYhLtYaMX9qUvw,855 +litellm/proxy/example_config_yaml/disable_schema_update.yaml,sha256=uSLK9oMDTI6gms5hX-zzNa0V2yRMgLVz5ZJEvySFwKY,459 +litellm/proxy/example_config_yaml/enterprise_config.yaml,sha256=TTfqDyoES3Col0-E6UxC6-HMu84ABuezuWGSFzUFTKI,358 +litellm/proxy/example_config_yaml/langfuse_config.yaml,sha256=jkBz0zM8bUEBb_gmHi5P0TuFyC0WYlyGa37-WVRdsAo,181 +litellm/proxy/example_config_yaml/load_balancer.yaml,sha256=hz5tnS6TvE8P-qU3pZ-SspqMB280EtrSwMZvjEca3sg,886 +litellm/proxy/example_config_yaml/multi_instance_simple_config.yaml,sha256=RkHqPFEki5LGqBaDtF2qutReGLnaERNGhiv5iAt5Gas,269 +litellm/proxy/example_config_yaml/oai_misc_config.yaml,sha256=rUMks26ziow75JxdZwMoZ96grII-UELVkOFLDlijaEA,2074 +litellm/proxy/example_config_yaml/opentelemetry_config.yaml,sha256=u7-6jPVmj2Yca7nTeu1ykDZzzdtGKcGj3v5Y557Fc00,192 +litellm/proxy/example_config_yaml/otel_test_config.yaml,sha256=Ba3Hh6fvOVYzHwqiHmdAYrhBtUVU0UgT-DnmmCe7P5c,2639 +litellm/proxy/example_config_yaml/pass_through_config.yaml,sha256=QH6iaaZNm-rJCjyffoH1sR5xwTLp6iP6JmDJSVQuYAM,1019 +litellm/proxy/example_config_yaml/simple_config.yaml,sha256=OBODVvCc0814U8-YTmiwT7C4UkSjLN51Bd0HxDenTVg,88 +litellm/proxy/example_config_yaml/spend_tracking_config.yaml,sha256=upaHRnAZa9BsZmOurRZPyNCWyrfv2gutcvTFFzLoBac,340 +litellm/proxy/example_config_yaml/store_model_db_config.yaml,sha256=YxPerk168RsyXsG3U26GatRHYmPevGnx2a_xrbcckxQ,249 +litellm/proxy/fine_tuning_endpoints/__pycache__/endpoints.cpython-310.pyc,, +litellm/proxy/fine_tuning_endpoints/endpoints.py,sha256=IWqNo2PAp26M8IItTTEJQk3iHqXoruNJF95_HtohPxI,23522 +litellm/proxy/google_endpoints/__pycache__/endpoints.cpython-310.pyc,, +litellm/proxy/google_endpoints/endpoints.py,sha256=_glaXUZco-iez_8wLuLwYdOTVZm6ik4oX0DDUTEGfEs,5374 +litellm/proxy/guardrails/__pycache__/guardrail_endpoints.cpython-310.pyc,, +litellm/proxy/guardrails/__pycache__/guardrail_helpers.cpython-310.pyc,, +litellm/proxy/guardrails/__pycache__/guardrail_initializers.cpython-310.pyc,, +litellm/proxy/guardrails/__pycache__/guardrail_registry.cpython-310.pyc,, +litellm/proxy/guardrails/__pycache__/init_guardrails.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_endpoints.py,sha256=WzHueBizTgBASgJpoAsFFPLO9XutZn6l3Hp4e4DOaYM,33313 +litellm/proxy/guardrails/guardrail_helpers.py,sha256=ybo0vTWumNKVPLbPAgTZNv7bd_UAtMbwx7HTdzcC1Q8,4277 +litellm/proxy/guardrails/guardrail_hooks/__pycache__/bedrock_guardrails.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/__pycache__/custom_guardrail.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/__pycache__/lakera_ai.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/__pycache__/lakera_ai_v2.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/__pycache__/presidio.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/aim/__init__.py,sha256=ZGCW68O2Y3UoqykJow9tn770hCBzYXwbjgyEAaPG8QE,964 +litellm/proxy/guardrails/guardrail_hooks/aim/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/aim/__pycache__/aim.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/aim/aim.py,sha256=QiVa_w3-0zRhE57w3FJLa57NdqiNGu_attsUdkwtXEo,13188 +litellm/proxy/guardrails/guardrail_hooks/aporia_ai/__init__.py,sha256=RLY81F07SSjfDfjuuAJj1YS0jhy5gGa28rafuTz_Rr4,920 +litellm/proxy/guardrails/guardrail_hooks/aporia_ai/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/aporia_ai/__pycache__/aporia_ai.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/aporia_ai/aporia_ai.py,sha256=SVPsu6hGOenPC57zMrSWfjYTD2pX8CjHA3pqw1b9ulQ,7871 +litellm/proxy/guardrails/guardrail_hooks/azure/__init__.py,sha256=8hFWWLZrvVmHoxXzaMo1LMfep4IGtQJidetXTh4C1os,2701 +litellm/proxy/guardrails/guardrail_hooks/azure/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/azure/__pycache__/base.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/azure/__pycache__/prompt_shield.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/azure/__pycache__/text_moderation.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/azure/base.py,sha256=D8RStkthqPuEZSZvHpFPNCrj7GgvpHVH6XH2IK-Z6hk,1633 +litellm/proxy/guardrails/guardrail_hooks/azure/prompt_shield.py,sha256=DVULawTX1ual40MLJaFlmVJ--ixtkTKqM2sYr5PyjWE,6811 +litellm/proxy/guardrails/guardrail_hooks/azure/text_moderation.py,sha256=9FL_4AuaskXpc-8saWmXyVKW565gl2U3hho2bD3BOSo,10758 +litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py,sha256=BtU-5KDfr_1Z6_Y_EMxC0LKhHO2506xfoB_erHsMjzY,33574 +litellm/proxy/guardrails/guardrail_hooks/custom_guardrail.py,sha256=ex4B46JSKG7pFEkUlcDd3sa6Y1t8271N2swVGJwaG7E,3843 +litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/__init__.py,sha256=kFD5aELpGnr13SB6Y72dwr9fMAjjY3YEF56VIedGgls,1186 +litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/__pycache__/guardrails_ai.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/guardrails_ai.py,sha256=S12-59VRmstdT7N3UfIIvCtaW5V3IZmdAW5Fyu7yMaI,8060 +litellm/proxy/guardrails/guardrail_hooks/lakera_ai.py,sha256=79XVG6cXe-snZwlCIysPcpo-FedrluNAUOIUhQDeLYA,13227 +litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py,sha256=MSaoBbEr9wSfu54uQFleZybG7isWqeNezr2dJ3tp7Ng,13136 +litellm/proxy/guardrails/guardrail_hooks/lasso/__init__.py,sha256=_f34fb9-kYgd5-YEHZPG8KNHrCNhbWHDe5Zz0wnEnUc,1016 +litellm/proxy/guardrails/guardrail_hooks/lasso/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/lasso/__pycache__/lasso.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/lasso/lasso.py,sha256=c_jU6XFSdC9LVUVruwYR2ydJTZG2tJvR3vk7_1r8eak,7425 +litellm/proxy/guardrails/guardrail_hooks/openai/__init__.py,sha256=Lv6qO0sfaRq6GdnvncdvpOSLPO67uJ4jiJDWUDvLniM,1365 +litellm/proxy/guardrails/guardrail_hooks/openai/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/openai/__pycache__/base.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/openai/__pycache__/moderations.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/openai/base.py,sha256=gs-SIIp7Hb2HU2YwPN9FxWAICWB0ksovKTSgB7D9u9M,1635 +litellm/proxy/guardrails/guardrail_hooks/openai/moderations.py,sha256=9HCybTGFcGo8k8fOdlfZjVPD0hTK-7su6hwPVZVRM_U,15007 +litellm/proxy/guardrails/guardrail_hooks/pangea/__init__.py,sha256=603CAuwSlGCNB-gu7TImc2R8X60WfUERCqAvXaRcst0,1123 +litellm/proxy/guardrails/guardrail_hooks/pangea/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/pangea/__pycache__/pangea.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/pangea/pangea.py,sha256=LbSfp8ylWwH2-PHuk4LXxTyPK2yBwnTYg_zBn8V-aCQ,15070 +litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/__init__.py,sha256=58N0BhRXy2zH9U-FzH4kq7Z2cf6NhbkP-EYFKmjOJDY,1357 +litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/__pycache__/panw_prisma_airs.cpython-310.pyc,, +litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/panw_prisma_airs.py,sha256=1AUIz3FsZQ-DIYFUPVo3dKwW2DoCG_irXxWQncNJtE0,11640 +litellm/proxy/guardrails/guardrail_hooks/presidio.py,sha256=vm-bU7LJWGcS93cgTMcVnJV99QpdYAS4ODEzyPBeWlc,26868 +litellm/proxy/guardrails/guardrail_initializers.py,sha256=6hSQY2HI8QdFF2hQW40FlNTR9BLnwVcvkpI7M6L6L1Q,5412 +litellm/proxy/guardrails/guardrail_registry.py,sha256=0zFpZPMOUPLTAmniAsByOrAadDiVOqupo07LejG4rhU,20334 +litellm/proxy/guardrails/init_guardrails.py,sha256=If41gFI3HinWfPSqMwv3fa7hSjXeQ9i18mJdgd2Fs6I,3355 +litellm/proxy/health_check.py,sha256=dc3P8EoCAEzEJAvaeT0zt3dygUx19S-beJRHw8wUzyg,5458 +litellm/proxy/health_endpoints/__pycache__/_health_endpoints.cpython-310.pyc,, +litellm/proxy/health_endpoints/_health_endpoints.py,sha256=CbJpd5n3r5_J7RGjhGOF_fCMZYLKFziexfQoTn6_7wM,33534 +litellm/proxy/hooks/__init__.py,sha256=6Lr9_ILkzScuiDXiClt5ZwUmVSiJUAvi-1B73bqKrBw,1532 +litellm/proxy/hooks/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/hooks/__pycache__/azure_content_safety.cpython-310.pyc,, +litellm/proxy/hooks/__pycache__/batch_redis_get.cpython-310.pyc,, +litellm/proxy/hooks/__pycache__/cache_control_check.cpython-310.pyc,, +litellm/proxy/hooks/__pycache__/dynamic_rate_limiter.cpython-310.pyc,, +litellm/proxy/hooks/__pycache__/key_management_event_hooks.cpython-310.pyc,, +litellm/proxy/hooks/__pycache__/max_budget_limiter.cpython-310.pyc,, +litellm/proxy/hooks/__pycache__/model_max_budget_limiter.cpython-310.pyc,, +litellm/proxy/hooks/__pycache__/parallel_request_limiter.cpython-310.pyc,, +litellm/proxy/hooks/__pycache__/parallel_request_limiter_v3.cpython-310.pyc,, +litellm/proxy/hooks/__pycache__/prompt_injection_detection.cpython-310.pyc,, +litellm/proxy/hooks/__pycache__/proxy_track_cost_callback.cpython-310.pyc,, +litellm/proxy/hooks/__pycache__/user_management_event_hooks.cpython-310.pyc,, +litellm/proxy/hooks/azure_content_safety.py,sha256=M-wkBrQLlPiud30WrRtRK2ZAE3OfHICIAToFCPL3DnE,5640 +litellm/proxy/hooks/batch_redis_get.py,sha256=fZJRZ5GcXHlZV0kkuoloAWZkDP2NTcUlmYQt87Q2UdM,5990 +litellm/proxy/hooks/cache_control_check.py,sha256=yfLKzT3fYycXvAGCXFK8mWoCDnZcXJTQA7wP51nzr2M,2117 +litellm/proxy/hooks/dynamic_rate_limiter.py,sha256=-yYFOvuVa8dWmvgec0fS2UKhNZarKkBbjnvH_TWaT-M,12019 +litellm/proxy/hooks/example_presidio_ad_hoc_recognizer.json,sha256=VZLbOsMKjmQRdigSjZ3Rn5PJiizWV0If4_kGq_gH9DE,756 +litellm/proxy/hooks/key_management_event_hooks.py,sha256=EjwVbWN6F00DMnKX0vySlJMJgHiAM5ZmUOJbjhabNTo,15394 +litellm/proxy/hooks/max_budget_limiter.py,sha256=u5So9u4OylxmracwpoKsWc98tee5ZcSX_4AEHiBeXhI,1637 +litellm/proxy/hooks/model_max_budget_limiter.py,sha256=eGSUEe1LFzV2hnHo56LXC0p4po2Ud0r2ifVy55ZNsLg,7876 +litellm/proxy/hooks/parallel_request_limiter.py,sha256=0W_Qnz6-PQYvtjgE-vU5j-GtMEQc0dGLUSbnxevYZVM,35438 +litellm/proxy/hooks/parallel_request_limiter_v3.py,sha256=ArvhOJxrBprQY3p1lkwJo8uSGA5JOvr3nNGYns79EH4,29600 +litellm/proxy/hooks/prompt_injection_detection.py,sha256=E4F1GwNeaFrNWpHDhgZD0pAWGINZixUxy1mleKwySgg,10493 +litellm/proxy/hooks/proxy_track_cost_callback.py,sha256=0l3X7g6RGKWKti2WeqRmv1ENjpV1c6ghlSV6mKPZxUQ,10834 +litellm/proxy/hooks/user_management_event_hooks.py,sha256=DoE9NDfIKRJ8t5VXrz30wJHPKpgAH0uYQsZMA8VHozc,7864 +litellm/proxy/image_endpoints/__init__.py,sha256=cBWHXwOJGQJePBX_lp1VeF4pYH0YFHiCaK6NKdTVcms,72 +litellm/proxy/image_endpoints/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/image_endpoints/__pycache__/endpoints.cpython-310.pyc,, +litellm/proxy/image_endpoints/endpoints.py,sha256=92ZEjBViZI4M_9QV2lAs0OoWdFKM4k14mUwwhzuK5q8,9440 +litellm/proxy/lambda.py,sha256=h_06oqJhK3tkvnKOmxe7VLtPuIJIsosJE07BFXzF7sQ,107 +litellm/proxy/litellm.log,sha256=v1tfU4eZ1YyprW2WOggdujksqsVCdYr_gyt7_j1M9Ro,32373 +litellm/proxy/litellm_pre_call_utils.py,sha256=zAMYehi8BFyYwXJJWYLa6lDcub3AZuBf3mYZfs_0vb0,37337 +litellm/proxy/llamaguard_prompt.txt,sha256=tCel8OPpD7IybjAulUqEg4QhJBdXKGThiv6J4DoKJFk,3300 +litellm/proxy/logo.jpg,sha256=ZnPgg_2nBqNuMuqW2ZSrWNISVaK6HiSuNB4e5xttQto,24694 +litellm/proxy/management_endpoints/__pycache__/budget_management_endpoints.cpython-310.pyc,, +litellm/proxy/management_endpoints/__pycache__/callback_management_endpoints.cpython-310.pyc,, +litellm/proxy/management_endpoints/__pycache__/common_daily_activity.cpython-310.pyc,, +litellm/proxy/management_endpoints/__pycache__/common_utils.cpython-310.pyc,, +litellm/proxy/management_endpoints/__pycache__/customer_endpoints.cpython-310.pyc,, +litellm/proxy/management_endpoints/__pycache__/internal_user_endpoints.cpython-310.pyc,, +litellm/proxy/management_endpoints/__pycache__/key_management_endpoints.cpython-310.pyc,, +litellm/proxy/management_endpoints/__pycache__/mcp_management_endpoints.cpython-310.pyc,, +litellm/proxy/management_endpoints/__pycache__/model_management_endpoints.cpython-310.pyc,, +litellm/proxy/management_endpoints/__pycache__/organization_endpoints.cpython-310.pyc,, +litellm/proxy/management_endpoints/__pycache__/sso_helper_utils.cpython-310.pyc,, +litellm/proxy/management_endpoints/__pycache__/tag_management_endpoints.cpython-310.pyc,, +litellm/proxy/management_endpoints/__pycache__/team_callback_endpoints.cpython-310.pyc,, +litellm/proxy/management_endpoints/__pycache__/team_endpoints.cpython-310.pyc,, +litellm/proxy/management_endpoints/__pycache__/types.cpython-310.pyc,, +litellm/proxy/management_endpoints/__pycache__/ui_sso.cpython-310.pyc,, +litellm/proxy/management_endpoints/budget_management_endpoints.py,sha256=x1GlucFqW9seowrdMmMfDi0RuLaoXBnE0CSwi-gSgF0,9962 +litellm/proxy/management_endpoints/callback_management_endpoints.py,sha256=uAKj-QhutRofeKklTOx2ghLFFE-CwpJ5z4II1lMgoMU,720 +litellm/proxy/management_endpoints/common_daily_activity.py,sha256=e_svdluvvYQgj_7jRlyBaptLC-U-8KCYoO_VAU8At7w,15753 +litellm/proxy/management_endpoints/common_utils.py,sha256=SlBxfSYL8hOg6AD_xAH5xBblSzPuUJ15FqS0nuW4m-g,3779 +litellm/proxy/management_endpoints/customer_endpoints.py,sha256=mbeNRQamWc5C2kysJQ0IRvv92FpbIKmX4Zu0t2zkNAA,23612 +litellm/proxy/management_endpoints/internal_user_endpoints.py,sha256=XxbGUiInXJM5X0PofwqnHzcAyz5uNOoywRL_Y1tRM4g,60481 +litellm/proxy/management_endpoints/key_management_endpoints.py,sha256=p4-fyzkpkWaooD8KLEEA-F3leXwtQj3K61AWYvp6Xxs,118573 +litellm/proxy/management_endpoints/mcp_management_endpoints.py,sha256=uLfgGzRL_Z-d6Ax30ENdIDIDFGK8uvDCZB01g_3tmmI,21112 +litellm/proxy/management_endpoints/model_management_endpoints.py,sha256=M99jzk-Mm3dMgepx29agq5lMI1sGMeMaMtDEVGGGcWs,38289 +litellm/proxy/management_endpoints/organization_endpoints.py,sha256=p00wLUyOQJE845-g6RbIoJp60JWWREChWXUMkqobqGs,32628 +litellm/proxy/management_endpoints/scim/README_SCIM.md,sha256=IOHah2hqxQ0Pgg2fGdANto_2t6NIqOPppV6a4WuQ-SY,2990 +litellm/proxy/management_endpoints/scim/__pycache__/scim_transformations.cpython-310.pyc,, +litellm/proxy/management_endpoints/scim/__pycache__/scim_v2.cpython-310.pyc,, +litellm/proxy/management_endpoints/scim/scim_transformations.py,sha256=ia5rFRRYfYEo0uqSWlrGG9iSteu4pRDSLThw5PwmAYY,5670 +litellm/proxy/management_endpoints/scim/scim_v2.py,sha256=LLejPGNLhl9OaXXQm1hBbOVKFhECO57f7zKQz8wDBtQ,38425 +litellm/proxy/management_endpoints/sso_helper_utils.py,sha256=PpSrVsjn9RVfoRn3RWExlrHVoIGn5aMHq0KtXYyby5s,721 +litellm/proxy/management_endpoints/tag_management_endpoints.py,sha256=fTfHtQEuWycpmpYDEx6eQD-uo7C89WotgC5nLfgDqf4,15397 +litellm/proxy/management_endpoints/team_callback_endpoints.py,sha256=Oe7g9R3UBnjsI5UMfewzVsP0Fv5bOMP4Kugzu2UTamY,15557 +litellm/proxy/management_endpoints/team_endpoints.py,sha256=-tQUHT6OiUfvW2S30g9FtOL3Ub2rznAh3muV9ej2W8M,100130 +litellm/proxy/management_endpoints/types.py,sha256=hMQffPXPNdFFtsG8H9BWkCKp_eKO7FWFG_-qQflEBTc,225 +litellm/proxy/management_endpoints/ui_sso.py,sha256=AsU5yEaBVzbW8Oc_88zhTo_558Zw7vmP9whk0DsrSiw,74061 +litellm/proxy/management_helpers/__pycache__/audit_logs.cpython-310.pyc,, +litellm/proxy/management_helpers/__pycache__/object_permission_utils.cpython-310.pyc,, +litellm/proxy/management_helpers/__pycache__/team_member_permission_checks.cpython-310.pyc,, +litellm/proxy/management_helpers/__pycache__/user_invitation.cpython-310.pyc,, +litellm/proxy/management_helpers/__pycache__/utils.cpython-310.pyc,, +litellm/proxy/management_helpers/audit_logs.py,sha256=JsTyyDNHIJyAdedNBrFrh74UwRujwolODLbYVx-qyCk,3251 +litellm/proxy/management_helpers/object_permission_utils.py,sha256=A7Yxbi7PCjTq3wnk2h9wvTs4fTmVyB7oXug9Fbf4-nk,4910 +litellm/proxy/management_helpers/team_member_permission_checks.py,sha256=dXwAktQQD7HLKci2tLeAoZ39gVQ4QVR_jlG1bCtZaDg,6176 +litellm/proxy/management_helpers/user_invitation.py,sha256=etAAJo92DO55udBVRBnqUqN0nCnQjVvD4kAYeLSyQJU,1640 +litellm/proxy/management_helpers/utils.py,sha256=gIs4O087W8cNiCL8DKxbgmdjPj15mUs2Vw6V_lJspv4,14295 +litellm/proxy/mcp_tools.py,sha256=Z4PnnbVZ6qrV6QO0ZgQcdz5RRxBiIkz5mPJUwHmeYcU,1036 +litellm/proxy/middleware/__pycache__/prometheus_auth_middleware.cpython-310.pyc,, +litellm/proxy/middleware/prometheus_auth_middleware.py,sha256=H4Y9UNFAOfhC15YfdaMpqyM057UEKEDNtdvv_Fw-PG8,2200 +litellm/proxy/model_config.yaml,sha256=RDjUCXHG9kZoeJLqCDyApT5F-sYyyK3PpH1io6j352A,320 +litellm/proxy/openai_files_endpoints/__pycache__/common_utils.cpython-310.pyc,, +litellm/proxy/openai_files_endpoints/__pycache__/files_endpoints.cpython-310.pyc,, +litellm/proxy/openai_files_endpoints/common_utils.py,sha256=scIClKxaHriAbZfo6-r27mPGlzmtL67k6m7GPZMI8io,2148 +litellm/proxy/openai_files_endpoints/files_endpoints.py,sha256=kEUmYQ7zp4nZNtFNicUmp_lhjHEBmBVqGXwsM-jbxgA,34130 +litellm/proxy/openapi.json,sha256=MJrfO9l1MFZmvPnXC77LzUJojMwTkAiFU4whrntKA-4,7163 +litellm/proxy/pass_through_endpoints/__pycache__/common_utils.cpython-310.pyc,, +litellm/proxy/pass_through_endpoints/__pycache__/llm_passthrough_endpoints.cpython-310.pyc,, +litellm/proxy/pass_through_endpoints/__pycache__/pass_through_endpoints.cpython-310.pyc,, +litellm/proxy/pass_through_endpoints/__pycache__/passthrough_endpoint_router.cpython-310.pyc,, +litellm/proxy/pass_through_endpoints/__pycache__/streaming_handler.cpython-310.pyc,, +litellm/proxy/pass_through_endpoints/__pycache__/success_handler.cpython-310.pyc,, +litellm/proxy/pass_through_endpoints/common_utils.py,sha256=1gVWXbDvjuiZ2qMjRT396rGFsDICeVOoxYZvoMXOKNA,501 +litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py,sha256=WO5EUjRdFMyTk1dhQNeUqBDGH4Hctys_IHMMXYI9vnk,37551 +litellm/proxy/pass_through_endpoints/llm_provider_handlers/__pycache__/anthropic_passthrough_logging_handler.cpython-310.pyc,, +litellm/proxy/pass_through_endpoints/llm_provider_handlers/__pycache__/assembly_passthrough_logging_handler.cpython-310.pyc,, +litellm/proxy/pass_through_endpoints/llm_provider_handlers/__pycache__/base_passthrough_logging_handler.cpython-310.pyc,, +litellm/proxy/pass_through_endpoints/llm_provider_handlers/__pycache__/cohere_passthrough_logging_handler.cpython-310.pyc,, +litellm/proxy/pass_through_endpoints/llm_provider_handlers/__pycache__/vertex_passthrough_logging_handler.cpython-310.pyc,, +litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py,sha256=iwNvrR5rvoHNCWeYKVeO_kjHgtwodsB4vvGDTo2nz0g,7932 +litellm/proxy/pass_through_endpoints/llm_provider_handlers/assembly_passthrough_logging_handler.py,sha256=_QaQmJdi_aF8AF9We3gMhLe2HU95YXxkzyExWPWSVeo,11416 +litellm/proxy/pass_through_endpoints/llm_provider_handlers/base_passthrough_logging_handler.py,sha256=z2Z8uuP5vOnQY4JWJrJVODxald8hVmozblpVMKkPktQ,7610 +litellm/proxy/pass_through_endpoints/llm_provider_handlers/cohere_passthrough_logging_handler.py,sha256=aesCJ1jBxrhrA9iowZv5QreXXXGL54kq5mTJQVmSCrs,2270 +litellm/proxy/pass_through_endpoints/llm_provider_handlers/vertex_passthrough_logging_handler.py,sha256=Ca8rnCzqnSwUUyqyj52dg4vKS2kuPRbXAmryPI9puOY,13124 +litellm/proxy/pass_through_endpoints/pass_through_endpoints.py,sha256=Nf3onV9N2_AW_yNXvWk1nSqDxG1S2bQoFtwUPpEz8ec,51541 +litellm/proxy/pass_through_endpoints/passthrough_endpoint_router.py,sha256=01k8vlmXi3Lxxy5m5o-LXrSJjufxwoewXb2R-dm75kE,7172 +litellm/proxy/pass_through_endpoints/streaming_handler.py,sha256=mZMnIgkymlJ4xggJnbOsV743bxJ68m8U8zRJEtxfinU,6296 +litellm/proxy/pass_through_endpoints/success_handler.py,sha256=wwAOQtxqLtFMVu0WRvtvgBbnVe1LbSlu8jGJyp0LE9U,11073 +litellm/proxy/post_call_rules.py,sha256=bbnqX3BXhKjvbRN6LdZIwndKMCh88i4a9BXkTzsaHVk,359 +litellm/proxy/prisma_migration.py,sha256=hdG-gU7K8TatUypeIZNE1mWkSoEx7c4DvT8UYeFdMWA,3853 +litellm/proxy/proxy_cli.py,sha256=oqStIC7mXoqysYJd1vEiqXwasdQKait2Uczzo8Olrbs,28537 +litellm/proxy/proxy_config.yaml,sha256=thBaKXf5ezAE0qhCCFbE_dltyEO6rE9g0xXflFM1m5k,460 +litellm/proxy/proxy_server.py,sha256=xOA8IJeeiFlKDIEPFBbAI65zhh-1vUyXYhEDBJ0WEU4,322703 +litellm/proxy/public_endpoints/__init__.py,sha256=NleKkLOwFM6WJB8hqsoSoPq0b16wysEiW25VStkYuGA,59 +litellm/proxy/public_endpoints/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/public_endpoints/__pycache__/public_endpoints.cpython-310.pyc,, +litellm/proxy/public_endpoints/public_endpoints.py,sha256=fztkNSvoebbQY0HvajG2ni2o3hnUhpcuZJPK8T0OyXA,1846 +litellm/proxy/rerank_endpoints/__pycache__/endpoints.cpython-310.pyc,, +litellm/proxy/rerank_endpoints/endpoints.py,sha256=ZUXgvKP2UVvVYYk9UrgkDLEaE4y3WDWO4fnP9IF_V04,4189 +litellm/proxy/response_api_endpoints/__pycache__/endpoints.cpython-310.pyc,, +litellm/proxy/response_api_endpoints/endpoints.py,sha256=DPTM0TRfjoxfyxfCa8c5g64zbnjZ5PqgYUTqs6yqzpU,8769 +litellm/proxy/route_llm_request.py,sha256=oLmgtIgiqm36nfuDvJJnysKxsNYPbESe_nde8nxHdjU,5489 +litellm/proxy/schema.prisma,sha256=ziqIOtWuMJ26s6pZl2751ZBPh88WB72rY8hkkLCJ2r4,20695 +litellm/proxy/spend_tracking/__pycache__/spend_management_endpoints.cpython-310.pyc,, +litellm/proxy/spend_tracking/__pycache__/spend_tracking_utils.cpython-310.pyc,, +litellm/proxy/spend_tracking/spend_management_endpoints.py,sha256=FMk-rfHq4szNyt99Sa16XaA-EPqKKSH_r0Txh9-1WC8,98571 +litellm/proxy/spend_tracking/spend_tracking_utils.py,sha256=upT-3TWEA5PCgddxEyJLS0HJvVyfAQCppm_diDdHOhc,20540 +litellm/proxy/start.sh,sha256=qFUFqvhcEIMyL3Bp9vtAtLvY0zjyLw6lHTocHqpLE5w,32 +litellm/proxy/swagger/favicon.png,sha256=0W9yz1onc-ukmcx_PbGSPG9fc96ZD3OeOgWAaq_sFbc,5043 +litellm/proxy/swagger/swagger-ui-bundle.js,sha256=xQuUu8TwI5Qyb7eu0fT7aTs2d_Sz0zRODWExgIy_KB8,1426050 +litellm/proxy/swagger/swagger-ui.css,sha256=jzPZlgJTFwSdSphk9CHqsrKiR4cvOIAm-pTGVJEyWec,152072 +litellm/proxy/types_utils/README.md,sha256=WSVas5L_WUcH_Ef0H3dEoYHFGfaBVQ6ODzFq-wdnMqY,36 +litellm/proxy/types_utils/__pycache__/utils.cpython-310.pyc,, +litellm/proxy/types_utils/utils.py,sha256=uhWj_8_zB8Fmoe_lwwfAcSuIu2mlQsREaThA5VRnGPo,2212 +litellm/proxy/ui_crud_endpoints/__init__.py,sha256=ByvXjaib_5HMEjTRr8zt6NsziB_IGS2rnYRB-Csvd4Q,112 +litellm/proxy/ui_crud_endpoints/__pycache__/__init__.cpython-310.pyc,, +litellm/proxy/ui_crud_endpoints/__pycache__/proxy_setting_endpoints.cpython-310.pyc,, +litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py,sha256=ikAoraZOskrjuRJUqtCdBU6BGd5l-vvo_5mG2Ltg7Ps,15973 +litellm/proxy/utils.py,sha256=miVe4UdaFZHsVIPRqdQOrYZVQMCYalr3tYkpiecu7Vg,124703 +litellm/proxy/vertex_ai_endpoints/__pycache__/langfuse_endpoints.cpython-310.pyc,, +litellm/proxy/vertex_ai_endpoints/langfuse_endpoints.py,sha256=3CkiX26Ud9t867anA0wJOAggxT7dUCUFaQC2Q4nVi7E,4417 +litellm/py.typed,sha256=bKPUECNwNtN5PZk1JYgrtM4QFbfIniqsIVGDL0oKMuQ,129 +litellm/realtime_api/README.md,sha256=rDlor8w3E0Dt74wXuwgPvS_hns4vDDC_TY-Vf5aYgRA,65 +litellm/realtime_api/__pycache__/main.cpython-310.pyc,, +litellm/realtime_api/main.py,sha256=eFTGHtBwOVNyNfvq4Wd12gtMlTGAVKDJGfqcIy_4RSQ,5759 +litellm/rerank_api/__pycache__/main.cpython-310.pyc,, +litellm/rerank_api/__pycache__/rerank_utils.cpython-310.pyc,, +litellm/rerank_api/main.py,sha256=xoe0na5RFvSks5KBZGDOEwGKNO9rEVj_rvXyvQNJ2VQ,14443 +litellm/rerank_api/rerank_utils.py,sha256=iwKTpiOWpG26kiDbjXjj52qF9GftzHZRLJneyHrli1g,1782 +litellm/responses/__pycache__/main.cpython-310.pyc,, +litellm/responses/__pycache__/streaming_iterator.cpython-310.pyc,, +litellm/responses/__pycache__/utils.cpython-310.pyc,, +litellm/responses/litellm_completion_transformation/__pycache__/handler.cpython-310.pyc,, +litellm/responses/litellm_completion_transformation/__pycache__/streaming_iterator.cpython-310.pyc,, +litellm/responses/litellm_completion_transformation/__pycache__/transformation.cpython-310.pyc,, +litellm/responses/litellm_completion_transformation/handler.py,sha256=MiPHIakmOv1Zzkcx9S7I8zNhkCMVbNCQ-EFy7amDxQU,4976 +litellm/responses/litellm_completion_transformation/streaming_iterator.py,sha256=xeF92SYsVc8eUeCETSDQaEF5vNnlwICc9YM8q-uRCsM,6856 +litellm/responses/litellm_completion_transformation/transformation.py,sha256=DZ_JunCUBz8Al0OS46acDEbHhLh8F9T-3seADD4VN5s,31482 +litellm/responses/main.py,sha256=mDaCce3Hl2WjZFV3HnxZqFgcbKtLHVBIxGBUyofhdlw,31057 +litellm/responses/streaming_iterator.py,sha256=iqFffKlM882i_W-3Y6Jb0Myd7R3kcJjCuGK3k0Mc20g,11177 +litellm/responses/utils.py,sha256=sazMBg_3MmuV-g6SOkQ7YjyZwMPrMkVKs4vL3PgeV4o,9634 +litellm/router.py,sha256=Ji6RhtOTxcA8QKtWpkFRtU-199XhiLxrA65RyyfepIY,269930 +litellm/router_strategy/__pycache__/base_routing_strategy.cpython-310.pyc,, +litellm/router_strategy/__pycache__/budget_limiter.cpython-310.pyc,, +litellm/router_strategy/__pycache__/least_busy.cpython-310.pyc,, +litellm/router_strategy/__pycache__/lowest_cost.cpython-310.pyc,, +litellm/router_strategy/__pycache__/lowest_latency.cpython-310.pyc,, +litellm/router_strategy/__pycache__/lowest_tpm_rpm.cpython-310.pyc,, +litellm/router_strategy/__pycache__/lowest_tpm_rpm_v2.cpython-310.pyc,, +litellm/router_strategy/__pycache__/simple_shuffle.cpython-310.pyc,, +litellm/router_strategy/__pycache__/tag_based_routing.cpython-310.pyc,, +litellm/router_strategy/base_routing_strategy.py,sha256=1-Dt4l3OTRuCt2KVt7NN0MPfraUhluyGsmpdvNc5Scg,10383 +litellm/router_strategy/budget_limiter.py,sha256=fx_Kcos_Eo4VwszUXyjqxuFYcyxLMc0oZ8DEQIpu0_8,34246 +litellm/router_strategy/least_busy.py,sha256=l1HaDaRqfHnd4H8Ftn0kgOIte8zVwJqOFxuFIX7ZnvE,9709 +litellm/router_strategy/lowest_cost.py,sha256=Eu8OS8N-h5dhDv2ih0tqW5y5mp1hiCvnpy7kZOt4P7Y,12584 +litellm/router_strategy/lowest_latency.py,sha256=o8rOkNaTDnyIQMBpQE8FibFeaOYLOMb_PBBmQNd7vcI,23239 +litellm/router_strategy/lowest_tpm_rpm.py,sha256=D8dlcEytu9v8Uvc6RdrxmrVIksQ0ucUnv6uwBPCG8XM,9320 +litellm/router_strategy/lowest_tpm_rpm_v2.py,sha256=vk3cRxE47C6MtT6iVMw41Mi0q-kA8slI3afqPg-5Vqo,27450 +litellm/router_strategy/simple_shuffle.py,sha256=w54uAE7wans0FX4SwqFoCMGfbjubasLLoYjyEvZz_B8,4245 +litellm/router_strategy/tag_based_routing.py,sha256=EP85NBvKJHUFxuJCeItKefFOcv07brXGnfXVpqQHYTc,4890 +litellm/router_utils/__pycache__/add_retry_fallback_headers.cpython-310.pyc,, +litellm/router_utils/__pycache__/batch_utils.cpython-310.pyc,, +litellm/router_utils/__pycache__/client_initalization_utils.cpython-310.pyc,, +litellm/router_utils/__pycache__/clientside_credential_handler.cpython-310.pyc,, +litellm/router_utils/__pycache__/common_utils.cpython-310.pyc,, +litellm/router_utils/__pycache__/cooldown_cache.cpython-310.pyc,, +litellm/router_utils/__pycache__/cooldown_callbacks.cpython-310.pyc,, +litellm/router_utils/__pycache__/cooldown_handlers.cpython-310.pyc,, +litellm/router_utils/__pycache__/fallback_event_handlers.cpython-310.pyc,, +litellm/router_utils/__pycache__/get_retry_from_policy.cpython-310.pyc,, +litellm/router_utils/__pycache__/handle_error.cpython-310.pyc,, +litellm/router_utils/__pycache__/pattern_match_deployments.cpython-310.pyc,, +litellm/router_utils/__pycache__/prompt_caching_cache.cpython-310.pyc,, +litellm/router_utils/__pycache__/response_headers.cpython-310.pyc,, +litellm/router_utils/add_retry_fallback_headers.py,sha256=4E2Tw715u22nRLwJtLDx2B3EdK1u3GIn7pYj65QBwg8,1963 +litellm/router_utils/batch_utils.py,sha256=506ER0Fljw8uqGRs3NiIuFfjRYJvmi9uTHKN7x4PD-Y,3142 +litellm/router_utils/client_initalization_utils.py,sha256=Uvh_1DIkV1IRR2H0Hbs1J_j2agGZfmpfdjL_JQqZ_d4,1307 +litellm/router_utils/clientside_credential_handler.py,sha256=QiKTTeg5VFjphUiTQM_S3NE0OVWtqzZpxdiUwPxiokU,938 +litellm/router_utils/common_utils.py,sha256=G8kYFB5TpopB2OoJHYRW3nCb3MBSCEVPCUyLK3HqsKw,2455 +litellm/router_utils/cooldown_cache.py,sha256=WpXFgaSuLRBpi43Mlp1ZS9ZXmXS69cOqgajJ1SBiHtM,6599 +litellm/router_utils/cooldown_callbacks.py,sha256=_lroen28lLbUq75D9kUmnXVWv85H4A2pdPSe4UqkANs,3106 +litellm/router_utils/cooldown_handlers.py,sha256=NcGJ-IvzhrEGfwQw8Lpa2Ns3Uu082d0kJ5-qS2sHYGQ,14893 +litellm/router_utils/fallback_event_handlers.py,sha256=PG0MTeKG5VGazPz5KTTLvxDxBQsqZwRS2BsdwMP9sak,11686 +litellm/router_utils/get_retry_from_policy.py,sha256=RDoTzl7_6aMaqkvxN4FxCi3m01-Lkb204iDJOwFwWpw,2254 +litellm/router_utils/handle_error.py,sha256=fV2Hj0bw9zI_pwtEg9yu49LPItgIABYqVU_5nh1kqyo,3080 +litellm/router_utils/pattern_match_deployments.py,sha256=lB9C9D1Tzfs3WuF87PJBa9Ik3-MnzL8bfS7oG8yTuzM,8798 +litellm/router_utils/pre_call_checks/__pycache__/prompt_caching_deployment_check.cpython-310.pyc,, +litellm/router_utils/pre_call_checks/__pycache__/responses_api_deployment_check.cpython-310.pyc,, +litellm/router_utils/pre_call_checks/prompt_caching_deployment_check.py,sha256=5Aq1ZwvTiGh7sXLiDSyA0WfBuoUSNc9YjfRE5JHOaPU,3675 +litellm/router_utils/pre_call_checks/responses_api_deployment_check.py,sha256=7Fu3qV04sH4ie4G2NeT7RO2263myAjyiqUCQU7QK7W8,1684 +litellm/router_utils/prompt_caching_cache.py,sha256=6kOsRGIVBXtzTjpbdBDTltQ5VmDhJduunaJ3YHpjOT8,5755 +litellm/router_utils/response_headers.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +litellm/router_utils/router_callbacks/__pycache__/track_deployment_metrics.cpython-310.pyc,, +litellm/router_utils/router_callbacks/track_deployment_metrics.py,sha256=93Ys2NamfsELx4eNXx0yyYWMrJkNdGdmSeSJ2rDFYeA,2121 +litellm/scheduler.py,sha256=vUlPEn7vQeIhbCzbhdnIptlHUOOaq84hxfcwSqwQSLo,4562 +litellm/secret_managers/Readme.md,sha256=6r8syZ7qgTWqM68lzcicfv3TtUYWDNMps4ph0thavwo,120 +litellm/secret_managers/__pycache__/aws_secret_manager.cpython-310.pyc,, +litellm/secret_managers/__pycache__/aws_secret_manager_v2.cpython-310.pyc,, +litellm/secret_managers/__pycache__/base_secret_manager.cpython-310.pyc,, +litellm/secret_managers/__pycache__/get_azure_ad_token_provider.cpython-310.pyc,, +litellm/secret_managers/__pycache__/google_kms.cpython-310.pyc,, +litellm/secret_managers/__pycache__/google_secret_manager.cpython-310.pyc,, +litellm/secret_managers/__pycache__/hashicorp_secret_manager.cpython-310.pyc,, +litellm/secret_managers/__pycache__/main.cpython-310.pyc,, +litellm/secret_managers/aws_secret_manager.py,sha256=tQs4Z1FLuakA9vdAMGYbA1XiP3VXjV3aawi0OY1npLM,4648 +litellm/secret_managers/aws_secret_manager_v2.py,sha256=asYDJVkYVH7BZjhV9xuhhb_Gswb3yWj2Wq1oOhqijFk,12606 +litellm/secret_managers/base_secret_manager.py,sha256=XqsJd5ZbMaC7AzCrjNv1PjYlSZjkLguSKwcvpJ6heP0,6222 +litellm/secret_managers/get_azure_ad_token_provider.py,sha256=dSayYWJD93xbz8YFpA6m8pCsudd0_0LsCKFN_xVdHdE,2662 +litellm/secret_managers/google_kms.py,sha256=8VgSLAThq_ylEZ_8AWcIuSD_S5QQzwwAk4TFETjz9bM,1292 +litellm/secret_managers/google_secret_manager.py,sha256=T2I8FozRMGGfUuIGRerjP-xvM_35N8S4yMYWe5kr9eE,4886 +litellm/secret_managers/hashicorp_secret_manager.py,sha256=z0oweGnrzq97ce7XwX_QPlQmByUvUm0lOSx3lkWM-nQ,12044 +litellm/secret_managers/main.py,sha256=nyXWbocsThV_fB9nUYRk7_j-iFsMdEnDoOSPgkvv_zU,15703 +litellm/timeout.py,sha256=0PmQsBdydAjV3NP6YCipt-aSMlwNTf31o_BmnCz-92I,4314 +litellm/types/__pycache__/adapter.cpython-310.pyc,, +litellm/types/__pycache__/caching.cpython-310.pyc,, +litellm/types/__pycache__/completion.cpython-310.pyc,, +litellm/types/__pycache__/embedding.cpython-310.pyc,, +litellm/types/__pycache__/files.cpython-310.pyc,, +litellm/types/__pycache__/fine_tuning.cpython-310.pyc,, +litellm/types/__pycache__/guardrails.cpython-310.pyc,, +litellm/types/__pycache__/mcp.cpython-310.pyc,, +litellm/types/__pycache__/realtime.cpython-310.pyc,, +litellm/types/__pycache__/rerank.cpython-310.pyc,, +litellm/types/__pycache__/router.cpython-310.pyc,, +litellm/types/__pycache__/scheduler.cpython-310.pyc,, +litellm/types/__pycache__/services.cpython-310.pyc,, +litellm/types/__pycache__/tag_management.cpython-310.pyc,, +litellm/types/__pycache__/utils.cpython-310.pyc,, +litellm/types/__pycache__/vector_stores.cpython-310.pyc,, +litellm/types/adapter.py,sha256=VLUBbZaxxVWPTzOVbks1x4xSm1icGSW3b7abid_I3y0,222 +litellm/types/caching.py,sha256=I5omh6a8j8Xnfems4e4PUVRiG9Y7Gtkbs95ObV9DCfM,2140 +litellm/types/completion.py,sha256=wiu4Are1ZbIwZLYGKZHC4Vq0ZXOreUCws0lNFysPmsU,5945 +litellm/types/embedding.py,sha256=-I4LM4kGCRwNtw0SiSngM8OePTRnrIjIiwNfwGY2slg,615 +litellm/types/files.py,sha256=UtvxVnYJ_vd9RVyPAsGjugOAai7dkEmE9JdvKL5vhrM,7277 +litellm/types/fine_tuning.py,sha256=9TQhXzi6Ze7XovufB9ezIVPrRbRJTmW40MU067-bHjc,165 +litellm/types/google_genai/__init__.py,sha256=va-MBe1jWWPaAsUp0jjhRcbTrvYvlVyu1O3lPs_8pko,266 +litellm/types/google_genai/__pycache__/__init__.cpython-310.pyc,, +litellm/types/google_genai/__pycache__/main.cpython-310.pyc,, +litellm/types/google_genai/main.py,sha256=1VtVZiaOssfCr5by7jsmETU751fYvu_98Vwn-kx3F9g,1118 +litellm/types/guardrails.py,sha256=EktOUqXA6uw-DuBLCeYcqIVjyAUld3t7CCOHnami37Y,15734 +litellm/types/images/__pycache__/main.cpython-310.pyc,, +litellm/types/images/main.py,sha256=EDg7SmjSZzn-18JBMeX84vKqiCxhwoPle0l6HzAHVlo,963 +litellm/types/integrations/__pycache__/anthropic_cache_control_hook.cpython-310.pyc,, +litellm/types/integrations/__pycache__/argilla.cpython-310.pyc,, +litellm/types/integrations/__pycache__/arize.cpython-310.pyc,, +litellm/types/integrations/__pycache__/arize_phoenix.cpython-310.pyc,, +litellm/types/integrations/__pycache__/base_health_check.cpython-310.pyc,, +litellm/types/integrations/__pycache__/datadog.cpython-310.pyc,, +litellm/types/integrations/__pycache__/datadog_llm_obs.cpython-310.pyc,, +litellm/types/integrations/__pycache__/gcs_bucket.cpython-310.pyc,, +litellm/types/integrations/__pycache__/langfuse.cpython-310.pyc,, +litellm/types/integrations/__pycache__/langfuse_otel.cpython-310.pyc,, +litellm/types/integrations/__pycache__/langsmith.cpython-310.pyc,, +litellm/types/integrations/__pycache__/pagerduty.cpython-310.pyc,, +litellm/types/integrations/__pycache__/prometheus.cpython-310.pyc,, +litellm/types/integrations/__pycache__/s3_v2.cpython-310.pyc,, +litellm/types/integrations/__pycache__/slack_alerting.cpython-310.pyc,, +litellm/types/integrations/anthropic_cache_control_hook.py,sha256=eLI13LcUCS03f1UgbTUFvZ3bAoKzzdsnSsOkVNbcARQ,579 +litellm/types/integrations/argilla.py,sha256=5ZI_6BDBdTJjkj4hFM41WXWnKSERIqc0x9XwXfyg688,441 +litellm/types/integrations/arize.py,sha256=r9bIi9BVLi6dVsBa6plPSTTYa8DIQ0SWy_0tNeLGWa4,325 +litellm/types/integrations/arize_phoenix.py,sha256=5b0_FsQKKSCJd5E5JzJvVZqde_09mVdDcb_n5NxhmBc,237 +litellm/types/integrations/base_health_check.py,sha256=hA0anYpSWRm5MAnEwenbi_DNQ9hl9DY_LIr6gr5eCGc,174 +litellm/types/integrations/datadog.py,sha256=sLyvciVKrVkoCc2nxWQbO7hfBf6EYHUjCm-CxCAwWsY,730 +litellm/types/integrations/datadog_llm_obs.py,sha256=Ho3eyAPrModsOzzHYNEHZedlFg1uD6sRauPOYR9-Mt0,1340 +litellm/types/integrations/gcs_bucket.py,sha256=iMI8OC97CyojKgHwrqEI8qbwyk8f62tjRRhfxyad3IU,718 +litellm/types/integrations/langfuse.py,sha256=62eGBD0cDR9wjSPBBPqFGjz-_gtUYF26pf6PDcCU4jc,188 +litellm/types/integrations/langfuse_otel.py,sha256=-lDstx0X9Y8Bepv7QeyiRT0zDydF07ICs9bhg_Q8aTM,411 +litellm/types/integrations/langsmith.py,sha256=fF6YZSqHUoxicOXU1-lnWc6TceXB9PIkpp5_rjzkzZA,1771 +litellm/types/integrations/pagerduty.py,sha256=BKgwbaKqRRwvtoqSISh1aCoYOrgMqda0mLWbleQ1rso,1934 +litellm/types/integrations/prometheus.py,sha256=pmFV_5FuN5iFgFhtC64ZtTvjUtPJcX-EPLzzWcr6eGY,15425 +litellm/types/integrations/rag/__pycache__/bedrock_knowledgebase.cpython-310.pyc,, +litellm/types/integrations/rag/bedrock_knowledgebase.py,sha256=JyVvUg8KCGZizerpqMQSdOUJuudW7PgwmsIUNOR7TjQ,4301 +litellm/types/integrations/s3_v2.py,sha256=rMeq8SBY7Q27KS5VlfEyNmc-pb4QbQGqzpOxAFT40ds,250 +litellm/types/integrations/slack_alerting.py,sha256=LhqBIYmG_bFusUvVQ2bJp5llS9plL8lKxFog3J2cV80,6551 +litellm/types/litellm_core_utils/__pycache__/streaming_chunk_builder_utils.cpython-310.pyc,, +litellm/types/litellm_core_utils/streaming_chunk_builder_utils.py,sha256=KxJJNqHHjtFVWLYPxQ-9VZQi8mV4AQXUc4LLp8wFOg8,469 +litellm/types/llms/__pycache__/anthropic.cpython-310.pyc,, +litellm/types/llms/__pycache__/azure.cpython-310.pyc,, +litellm/types/llms/__pycache__/azure_ai.cpython-310.pyc,, +litellm/types/llms/__pycache__/base.cpython-310.pyc,, +litellm/types/llms/__pycache__/bedrock.cpython-310.pyc,, +litellm/types/llms/__pycache__/bedrock_invoke_agents.cpython-310.pyc,, +litellm/types/llms/__pycache__/cohere.cpython-310.pyc,, +litellm/types/llms/__pycache__/custom_http.cpython-310.pyc,, +litellm/types/llms/__pycache__/custom_llm.cpython-310.pyc,, +litellm/types/llms/__pycache__/databricks.cpython-310.pyc,, +litellm/types/llms/__pycache__/gemini.cpython-310.pyc,, +litellm/types/llms/__pycache__/mistral.cpython-310.pyc,, +litellm/types/llms/__pycache__/ollama.cpython-310.pyc,, +litellm/types/llms/__pycache__/openai.cpython-310.pyc,, +litellm/types/llms/__pycache__/openrouter.cpython-310.pyc,, +litellm/types/llms/__pycache__/rerank.cpython-310.pyc,, +litellm/types/llms/__pycache__/triton.cpython-310.pyc,, +litellm/types/llms/__pycache__/vertex_ai.cpython-310.pyc,, +litellm/types/llms/__pycache__/watsonx.cpython-310.pyc,, +litellm/types/llms/anthropic.py,sha256=PW8jS0NvoLJMcbyxXK-RGF25eYPfzfg0nD6-tjjMFN0,11246 +litellm/types/llms/anthropic_messages/__pycache__/anthropic_request.cpython-310.pyc,, +litellm/types/llms/anthropic_messages/__pycache__/anthropic_response.cpython-310.pyc,, +litellm/types/llms/anthropic_messages/anthropic_request.py,sha256=TB_wJ4kOTedKX3QyTqSosJeSyYdnnlrAn_H-F_eUcUg,277 +litellm/types/llms/anthropic_messages/anthropic_response.py,sha256=9e6pMhMC50yVdYw2u8YrzP-9E6mZEqz-SK77U97w7Fo,2438 +litellm/types/llms/azure.py,sha256=QY-yJZhS_KA3kCUll-OAgBVzCMUQRJsWcisk9Uyg2X0,98 +litellm/types/llms/azure_ai.py,sha256=Au_E0qNwhfjNk_yciLEV0Ctj26TjadnZ9oSKcivnuCc,456 +litellm/types/llms/base.py,sha256=NTi5gg64DtBdw5AGyql83M5JbZgxJCGdyHcSBU4S4wc,2387 +litellm/types/llms/bedrock.py,sha256=k7GsZitwhC9ZzX4QKAFa4gh9iRAjfwYgUZwkWa5uLVQ,13143 +litellm/types/llms/bedrock_invoke_agents.py,sha256=u30jKcceZnZ3rlnJ4xgcoN9HRs7768PwPo8apW_hX4Q,3602 +litellm/types/llms/cohere.py,sha256=Ao4gg6N41MVlGp4P6LDRDhJiWuXCf5AomUFS2GQiQco,2399 +litellm/types/llms/custom_http.py,sha256=16TRcR2WMH2d_5y8H0sAkOap-ybHTXzq-sjbUeq16z0,678 +litellm/types/llms/custom_llm.py,sha256=BQiianU1zrlBtLpjB6zaXe5-xeVZrsRZNb25go4gnqI,220 +litellm/types/llms/databricks.py,sha256=AgUyf-e0kZ3SSjtBqY87KhTPXEbNSgHbPIVEqzv0fiM,1849 +litellm/types/llms/gemini.py,sha256=npts9BAJ9xHiCsJv4ASwNsSAFVrRjlnWxbIL53t4BAY,4924 +litellm/types/llms/mistral.py,sha256=aG_foFrP40lc8fAjkEYpHhbTyKgy_RsdyuobUrupaBs,292 +litellm/types/llms/ollama.py,sha256=E0-uFnQ_e5_rjC9EiG6ML-r59jfT7Xiy6axkLm5aZLM,588 +litellm/types/llms/openai.py,sha256=hTi5zFmRQHqaYuy49o68Cx61qXFVz4d_yU7ffqioFN8,49468 +litellm/types/llms/openrouter.py,sha256=YuHph6I-gufzvQz4mBbdnqzRNZHegBrVNZdP_xFmby8,206 +litellm/types/llms/rerank.py,sha256=jAC4Iy6qoXJHSYx3YtW97Khk04c7VrzTRg2D7OKPkWc,365 +litellm/types/llms/triton.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +litellm/types/llms/vertex_ai.py,sha256=SxWZw-8nikHrUSdu5eOSb9HroQe5MPPrWi50SjIG9uk,14374 +litellm/types/llms/watsonx.py,sha256=-2Cg1ob-c94FHLZx6F04t7d0lR2-5NXDFmMEqABLrHw,1040 +litellm/types/mcp.py,sha256=1xcJ1DHGpBLb60pclp3mqd0bHhmTIFJQmllo8Q_3Q-8,1980 +litellm/types/mcp_server/__pycache__/mcp_server_manager.cpython-310.pyc,, +litellm/types/mcp_server/__pycache__/tool_registry.cpython-310.pyc,, +litellm/types/mcp_server/mcp_server_manager.py,sha256=JmdCB6fPwDTYVLa978KbctfYvhKRzfu7zyR5-SKTq4g,938 +litellm/types/mcp_server/tool_registry.py,sha256=s2pVQGvEyBNo6179dwk7hVqSfjmSKkJRsBJiBbLiwF0,725 +litellm/types/passthrough_endpoints/__pycache__/assembly_ai.cpython-310.pyc,, +litellm/types/passthrough_endpoints/__pycache__/pass_through_endpoints.cpython-310.pyc,, +litellm/types/passthrough_endpoints/__pycache__/vertex_ai.cpython-310.pyc,, +litellm/types/passthrough_endpoints/assembly_ai.py,sha256=M_P5ngm2j4M6O_TkDYfyNDnh9-5gemlv1euZZEnSmNM,73 +litellm/types/passthrough_endpoints/pass_through_endpoints.py,sha256=25mVgpWrHY5xFSc2BPpdcxLhPkvk9ctPOc8fVW9Z2Cs,874 +litellm/types/passthrough_endpoints/vertex_ai.py,sha256=ZsTmBHBtNxfxfhASFbA_xz9yagjhe6_4rR8ZhwTxN04,557 +litellm/types/proxy/README.md,sha256=BiSieFeLSxJOdzoRZ7tBfNdT01rD7gFr6WP93PklFus,133 +litellm/types/proxy/__pycache__/ui_sso.cpython-310.pyc,, +litellm/types/proxy/discovery_endpoints/__pycache__/ui_discovery_endpoints.cpython-310.pyc,, +litellm/types/proxy/discovery_endpoints/ui_discovery_endpoints.py,sha256=0qLCpiGZKOCsl80dPVAcJGehdtz9aOtNexFIeWt8j8A,161 +litellm/types/proxy/guardrails/guardrail_hooks/__pycache__/aim.cpython-310.pyc,, +litellm/types/proxy/guardrails/guardrail_hooks/__pycache__/aporia_ai.cpython-310.pyc,, +litellm/types/proxy/guardrails/guardrail_hooks/__pycache__/base.cpython-310.pyc,, +litellm/types/proxy/guardrails/guardrail_hooks/__pycache__/bedrock_guardrails.cpython-310.pyc,, +litellm/types/proxy/guardrails/guardrail_hooks/__pycache__/guardrails_ai.cpython-310.pyc,, +litellm/types/proxy/guardrails/guardrail_hooks/__pycache__/lakera_ai_v2.cpython-310.pyc,, +litellm/types/proxy/guardrails/guardrail_hooks/__pycache__/lasso.cpython-310.pyc,, +litellm/types/proxy/guardrails/guardrail_hooks/__pycache__/pangea.cpython-310.pyc,, +litellm/types/proxy/guardrails/guardrail_hooks/__pycache__/panw_prisma_airs.cpython-310.pyc,, +litellm/types/proxy/guardrails/guardrail_hooks/__pycache__/presidio.cpython-310.pyc,, +litellm/types/proxy/guardrails/guardrail_hooks/aim.py,sha256=xrLc3YrmAT_P7AhfPp2hCyUp8FU5uPPliFxIxyXYlJo,650 +litellm/types/proxy/guardrails/guardrail_hooks/aporia_ai.py,sha256=BnphLksXrhkMC1o7Xm0z4qnJIfq4bW54me8M1LQpJrQ,630 +litellm/types/proxy/guardrails/guardrail_hooks/azure/__pycache__/azure_prompt_shield.cpython-310.pyc,, +litellm/types/proxy/guardrails/guardrail_hooks/azure/__pycache__/azure_text_moderation.cpython-310.pyc,, +litellm/types/proxy/guardrails/guardrail_hooks/azure/__pycache__/base.cpython-310.pyc,, +litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_prompt_shield.py,sha256=zVnM_0wLgDO2ZN1MKwgJrhSZX9nNjj_jEr0-osq87xA,897 +litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_text_moderation.py,sha256=lRiT-d45Y8xYkxW85tHRZwQLmuHZDN78pjUk9ZrQaHo,3462 +litellm/types/proxy/guardrails/guardrail_hooks/azure/base.py,sha256=9Su07F1YzipZJVy9K3kbornQdiNfTP4yAKYV5lJG61s,692 +litellm/types/proxy/guardrails/guardrail_hooks/base.py,sha256=0BmxGiAFCuNAKD31YsdNYhfniMluqd2OBKzVaBwFhcs,489 +litellm/types/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py,sha256=Rc2n1AFuo3t5xiww_PDZI4L28EVWj-MmCVS2NWeQD2w,3695 +litellm/types/proxy/guardrails/guardrail_hooks/guardrails_ai.py,sha256=wA9pkAOw_A4pQkzvE2SufU1LQOUtUhdFwXWQsCcdvX0,648 +litellm/types/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py,sha256=Ybwr2NrYNEb4MLRaE7YSSF_dljKmobjcmpc5nb7_vWQ,1160 +litellm/types/proxy/guardrails/guardrail_hooks/lasso.py,sha256=7enwMf3vhzHWKm1tSPvDMZwWXJqDdBahd_tyXKqL-IY,1197 +litellm/types/proxy/guardrails/guardrail_hooks/openai/__pycache__/openai_moderation.cpython-310.pyc,, +litellm/types/proxy/guardrails/guardrail_hooks/openai/openai_moderation.py,sha256=qHyBKGziEdxJBXzG_Sb7P52DgTFUJ1wkUIwH0bHZoaM,1172 +litellm/types/proxy/guardrails/guardrail_hooks/pangea.py,sha256=qQLNss8WLont981kYEMAXyTzIacJZ4VnMlJIgPAf6g0,1075 +litellm/types/proxy/guardrails/guardrail_hooks/panw_prisma_airs.py,sha256=GUYwdtmc44Odg4d3ajGX8tVkR3efz17yF9OZj_D7TNo,888 +litellm/types/proxy/guardrails/guardrail_hooks/presidio.py,sha256=wEW-dgroChlyZhQIdug__FnIPqfh89tsIkVaiMtPfqA,622 +litellm/types/proxy/management_endpoints/__pycache__/common_daily_activity.cpython-310.pyc,, +litellm/types/proxy/management_endpoints/__pycache__/internal_user_endpoints.cpython-310.pyc,, +litellm/types/proxy/management_endpoints/__pycache__/model_management_endpoints.cpython-310.pyc,, +litellm/types/proxy/management_endpoints/__pycache__/scim_v2.cpython-310.pyc,, +litellm/types/proxy/management_endpoints/__pycache__/team_endpoints.cpython-310.pyc,, +litellm/types/proxy/management_endpoints/__pycache__/ui_sso.cpython-310.pyc,, +litellm/types/proxy/management_endpoints/common_daily_activity.py,sha256=N17BsL8oXD15eEFby9IJvTwjI0yfMdgpXoWE-jR46oo,3706 +litellm/types/proxy/management_endpoints/internal_user_endpoints.py,sha256=WaDpPy4ISTVgN2FMnPIvYkBjmOT5aa8vDvYVeWAASMU,417 +litellm/types/proxy/management_endpoints/model_management_endpoints.py,sha256=EMlT2DEspYg0Bqa-i18yJo9HXU4c0R2lWbADSXOOY1M,165 +litellm/types/proxy/management_endpoints/scim_v2.py,sha256=ivi8_MDjfRTtI7NENW4uC9Pyjhs9HQPTDPpy8GdyNQA,2480 +litellm/types/proxy/management_endpoints/team_endpoints.py,sha256=xjQq11wnpURNM0i-ijySLAJ8ylJvfG0ZHtyNqdsevKk,1044 +litellm/types/proxy/management_endpoints/ui_sso.py,sha256=skAi3fLMzELPuI3YfhBX21bzNRHQSillgK5jMkYg1tU,5249 +litellm/types/proxy/public_endpoints/__pycache__/public_endpoints.cpython-310.pyc,, +litellm/types/proxy/public_endpoints/public_endpoints.py,sha256=mN2Fp7nj6i3ss135SOjS88NNExyBrjsY_o2z6CA18E0,236 +litellm/types/proxy/ui_sso.py,sha256=Mc_RahHGhUjGFY3JYvyNKWqWzUmmrYRmI0r-Vw0dXig,418 +litellm/types/realtime.py,sha256=BJImFi3OZWGLgiAlZurHkaj2BPGkesSLPuy78AdeKe0,1690 +litellm/types/rerank.py,sha256=UR3Rs0h_kTYtSEHHt6xp1i4g_E3tBoXDdMlGqXbJcxU,2035 +litellm/types/responses/__pycache__/main.cpython-310.pyc,, +litellm/types/responses/main.py,sha256=RA_3iTJYldRUIElLqatqrF3pNq11Rbw28301ZEvhSqc,1963 +litellm/types/router.py,sha256=bEbElUtJ2cWN3AepERJ3N3j_PWNnefozPX-CB6MK2VU,26243 +litellm/types/scheduler.py,sha256=g5ZYA6KD-Nr1QVOoctmfRObylqfr8pzrka0AOQx8k8s,99 +litellm/types/secret_managers/__pycache__/get_azure_ad_token_provider.cpython-310.pyc,, +litellm/types/secret_managers/__pycache__/main.cpython-310.pyc,, +litellm/types/secret_managers/get_azure_ad_token_provider.py,sha256=CYqKX8CBHTYUjLQZFDuKaw4bQOFpfSeC-fSD4ADQx7E,228 +litellm/types/secret_managers/main.py,sha256=JP-TlYSiIMNWsaW7sfEjBUFuTU1xyioorWPjwI0My4M,1219 +litellm/types/services.py,sha256=DIXHb8MHLHCDVA0Wa_DTKpl_WKt7DxrXJGRFZ8_c6lU,4177 +litellm/types/tag_management.py,sha256=ly2n5taPEGk4O-71Hb3fi9ynd4NWpkS15ncs9yVT9JE,1048 +litellm/types/utils.py,sha256=E5kgSFesxJ22t0hY7XsQYiAj65avjp9gX5QeAgbiMaY,79078 +litellm/types/vector_stores.py,sha256=UhH7nIzldUHVzifd5a-JvnKRav02uKXq09ex2CP_OVU,5914 +litellm/utils.py,sha256=QBFd0GQ-2NjCrei2nqUkTkhaf8T7MCCnGGaxdX7TjI4,286347 +litellm/vector_stores/__init__.py,sha256=QE-5X7RgVakRbO2J3bK7jgLWfoEP5VzJGkhZ1Fd_hBk,184 +litellm/vector_stores/__pycache__/__init__.cpython-310.pyc,, +litellm/vector_stores/__pycache__/main.cpython-310.pyc,, +litellm/vector_stores/__pycache__/utils.cpython-310.pyc,, +litellm/vector_stores/__pycache__/vector_store_registry.cpython-310.pyc,, +litellm/vector_stores/main.py,sha256=Ts-LVH0JrjzRbm8L8Z9bfC801cQvtwyWvmLQG2dAopo,15875 +litellm/vector_stores/utils.py,sha256=IaxWE8s4kHT3LOmUP51QfAiKMMqgsKw7g4pvQqZjCBQ,1767 +litellm/vector_stores/vector_store_registry.py,sha256=ySQosbtN4ok6XM4k4Pl98NNkAfZ8ol1oqftlw-Sf_-0,10317 diff --git a/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/REQUESTED b/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/WHEEL b/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..8b9b3a1bf3a91ed02f801f5487f2988a9aa4c454 --- /dev/null +++ b/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: poetry-core 1.9.1 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/entry_points.txt b/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..82847896b1b0d9586f299888d259340cd90ffe7c --- /dev/null +++ b/venv/lib/python3.10/site-packages/litellm-1.74.3.dist-info/entry_points.txt @@ -0,0 +1,4 @@ +[console_scripts] +litellm=litellm:run_server +litellm-proxy=litellm.proxy.client.cli:cli + diff --git a/venv/lib/python3.10/site-packages/llvmlite/__init__.py b/venv/lib/python3.10/site-packages/llvmlite/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f830f73f998d625e9d6fc345e2508164a3a62d91 --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/__init__.py @@ -0,0 +1,10 @@ +from ._version import get_versions +__version__ = get_versions()['version'] +del get_versions + +# FIXME: Remove me once typed pointers are no longer supported. +def _opaque_pointers_enabled(): + import os + return os.environ.get('LLVMLITE_ENABLE_OPAQUE_POINTERS', '0') == '1' +opaque_pointers_enabled = _opaque_pointers_enabled() +del _opaque_pointers_enabled diff --git a/venv/lib/python3.10/site-packages/llvmlite/_version.py b/venv/lib/python3.10/site-packages/llvmlite/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..04dd6c994aacfa8125b24a5fc2e93ee470c7aa00 --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/_version.py @@ -0,0 +1,11 @@ + +# This file was generated by 'versioneer.py' (0.14) from +# revision-control system data, or from the parent directory name of an +# unpacked source archive. Distribution tarballs contain a pre-generated copy +# of this file. + +version_version = '0.44.0' +version_full = '2c67a6b8deaaa21cf23e6cb59cf66905b63281ba' +def get_versions(default={}, verbose=False): + return {'version': version_version, 'full': version_full} + diff --git a/venv/lib/python3.10/site-packages/llvmlite/binding/context.py b/venv/lib/python3.10/site-packages/llvmlite/binding/context.py new file mode 100644 index 0000000000000000000000000000000000000000..192ebd8372588ef28319d4f06266ef9bef5936a0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/binding/context.py @@ -0,0 +1,39 @@ +from llvmlite.binding import ffi + +# FIXME: Remove me once typed pointers are no longer supported. +from llvmlite import opaque_pointers_enabled +from ctypes import c_bool + + +def create_context(): + return ContextRef( + ffi.lib.LLVMPY_ContextCreate(opaque_pointers_enabled)) + + +def get_global_context(): + return GlobalContextRef( + ffi.lib.LLVMPY_GetGlobalContext(opaque_pointers_enabled)) + + +class ContextRef(ffi.ObjectRef): + def __init__(self, context_ptr): + super(ContextRef, self).__init__(context_ptr) + + def _dispose(self): + ffi.lib.LLVMPY_ContextDispose(self) + + +class GlobalContextRef(ContextRef): + def _dispose(self): + pass + + +# FIXME: Remove argtypes once typed pointers are no longer supported. +ffi.lib.LLVMPY_GetGlobalContext.argtypes = [c_bool] +ffi.lib.LLVMPY_GetGlobalContext.restype = ffi.LLVMContextRef + +# FIXME: Remove argtypes once typed pointers are no longer supported. +ffi.lib.LLVMPY_ContextCreate.argtypes = [c_bool] +ffi.lib.LLVMPY_ContextCreate.restype = ffi.LLVMContextRef + +ffi.lib.LLVMPY_ContextDispose.argtypes = [ffi.LLVMContextRef] diff --git a/venv/lib/python3.10/site-packages/llvmlite/binding/dylib.py b/venv/lib/python3.10/site-packages/llvmlite/binding/dylib.py new file mode 100644 index 0000000000000000000000000000000000000000..e22542c496b7baadc002333f28e14a91e63a359a --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/binding/dylib.py @@ -0,0 +1,45 @@ +from ctypes import c_void_p, c_char_p, c_bool, POINTER + +from llvmlite.binding import ffi +from llvmlite.binding.common import _encode_string + + +def address_of_symbol(name): + """ + Get the in-process address of symbol named *name*. + An integer is returned, or None if the symbol isn't found. + """ + return ffi.lib.LLVMPY_SearchAddressOfSymbol(_encode_string(name)) + + +def add_symbol(name, address): + """ + Register the *address* of global symbol *name*. This will make + it usable (e.g. callable) from LLVM-compiled functions. + """ + ffi.lib.LLVMPY_AddSymbol(_encode_string(name), c_void_p(address)) + + +def load_library_permanently(filename): + """ + Load an external library + """ + with ffi.OutputString() as outerr: + if ffi.lib.LLVMPY_LoadLibraryPermanently( + _encode_string(filename), outerr): + raise RuntimeError(str(outerr)) + +# ============================================================================ +# FFI + + +ffi.lib.LLVMPY_AddSymbol.argtypes = [ + c_char_p, + c_void_p, +] + +ffi.lib.LLVMPY_SearchAddressOfSymbol.argtypes = [c_char_p] +ffi.lib.LLVMPY_SearchAddressOfSymbol.restype = c_void_p + +ffi.lib.LLVMPY_LoadLibraryPermanently.argtypes = [c_char_p, POINTER(c_char_p)] +ffi.lib.LLVMPY_LoadLibraryPermanently.restype = c_bool diff --git a/venv/lib/python3.10/site-packages/llvmlite/binding/ffi.py b/venv/lib/python3.10/site-packages/llvmlite/binding/ffi.py new file mode 100644 index 0000000000000000000000000000000000000000..3464cb9c7eb9043c3d3120fb1f36d3f2c880f75a --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/binding/ffi.py @@ -0,0 +1,395 @@ +import sys +import ctypes +import threading +import importlib.resources as _impres + +from llvmlite.binding.common import _decode_string, _is_shutting_down +from llvmlite.utils import get_library_name + + +def _make_opaque_ref(name): + newcls = type(name, (ctypes.Structure,), {}) + return ctypes.POINTER(newcls) + + +LLVMContextRef = _make_opaque_ref("LLVMContext") +LLVMModuleRef = _make_opaque_ref("LLVMModule") +LLVMValueRef = _make_opaque_ref("LLVMValue") +LLVMTypeRef = _make_opaque_ref("LLVMType") +LLVMExecutionEngineRef = _make_opaque_ref("LLVMExecutionEngine") +LLVMPassManagerBuilderRef = _make_opaque_ref("LLVMPassManagerBuilder") +LLVMPassManagerRef = _make_opaque_ref("LLVMPassManager") +LLVMTargetDataRef = _make_opaque_ref("LLVMTargetData") +LLVMTargetLibraryInfoRef = _make_opaque_ref("LLVMTargetLibraryInfo") +LLVMTargetRef = _make_opaque_ref("LLVMTarget") +LLVMTargetMachineRef = _make_opaque_ref("LLVMTargetMachine") +LLVMMemoryBufferRef = _make_opaque_ref("LLVMMemoryBuffer") +LLVMAttributeListIterator = _make_opaque_ref("LLVMAttributeListIterator") +LLVMElementIterator = _make_opaque_ref("LLVMElementIterator") +LLVMAttributeSetIterator = _make_opaque_ref("LLVMAttributeSetIterator") +LLVMGlobalsIterator = _make_opaque_ref("LLVMGlobalsIterator") +LLVMFunctionsIterator = _make_opaque_ref("LLVMFunctionsIterator") +LLVMBlocksIterator = _make_opaque_ref("LLVMBlocksIterator") +LLVMArgumentsIterator = _make_opaque_ref("LLVMArgumentsIterator") +LLVMInstructionsIterator = _make_opaque_ref("LLVMInstructionsIterator") +LLVMOperandsIterator = _make_opaque_ref("LLVMOperandsIterator") +LLVMIncomingBlocksIterator = _make_opaque_ref("LLVMIncomingBlocksIterator") +LLVMTypesIterator = _make_opaque_ref("LLVMTypesIterator") +LLVMObjectCacheRef = _make_opaque_ref("LLVMObjectCache") +LLVMObjectFileRef = _make_opaque_ref("LLVMObjectFile") +LLVMSectionIteratorRef = _make_opaque_ref("LLVMSectionIterator") +LLVMOrcLLJITRef = _make_opaque_ref("LLVMOrcLLJITRef") +LLVMOrcDylibTrackerRef = _make_opaque_ref("LLVMOrcDylibTrackerRef") + +LLVMPipelineTuningOptionsRef = _make_opaque_ref("LLVMPipeLineTuningOptions") +LLVMModulePassManagerRef = _make_opaque_ref("LLVMModulePassManager") +LLVMFunctionPassManagerRef = _make_opaque_ref("LLVMFunctionPassManager") +LLVMPassBuilderRef = _make_opaque_ref("LLVMPassBuilder") + + +class _LLVMLock: + """A Lock to guarantee thread-safety for the LLVM C-API. + + This class implements __enter__ and __exit__ for acquiring and releasing + the lock as a context manager. + + Also, callbacks can be attached so that every time the lock is acquired + and released the corresponding callbacks will be invoked. + """ + def __init__(self): + # The reentrant lock is needed for callbacks that re-enter + # the Python interpreter. + self._lock = threading.RLock() + self._cblist = [] + + def register(self, acq_fn, rel_fn): + """Register callbacks that are invoked immediately after the lock is + acquired (``acq_fn()``) and immediately before the lock is released + (``rel_fn()``). + """ + self._cblist.append((acq_fn, rel_fn)) + + def unregister(self, acq_fn, rel_fn): + """Remove the registered callbacks. + """ + self._cblist.remove((acq_fn, rel_fn)) + + def __enter__(self): + self._lock.acquire() + # Invoke all callbacks + for acq_fn, rel_fn in self._cblist: + acq_fn() + + def __exit__(self, *exc_details): + # Invoke all callbacks + for acq_fn, rel_fn in self._cblist: + rel_fn() + self._lock.release() + + +class _suppress_cleanup_errors: + def __init__(self, context): + self._context = context + + def __enter__(self): + return self._context.__enter__() + + def __exit__(self, exc_type, exc_value, traceback): + try: + return self._context.__exit__(exc_type, exc_value, traceback) + except PermissionError: + pass # Resource dylibs can't be deleted on Windows. + + +class _lib_wrapper(object): + """Wrap libllvmlite with a lock such that only one thread may access it at + a time. + + This class duck-types a CDLL. + """ + __slots__ = ['_lib_handle', '_fntab', '_lock'] + + def __init__(self): + self._lib_handle = None + self._fntab = {} + self._lock = _LLVMLock() + + def _load_lib(self): + try: + with _suppress_cleanup_errors(_importlib_resources_path( + __name__.rpartition(".")[0], + get_library_name())) as lib_path: + self._lib_handle = ctypes.CDLL(str(lib_path)) + # Check that we can look up expected symbols. + _ = self._lib_handle.LLVMPY_GetVersionInfo() + except (OSError, AttributeError) as e: + # OSError may be raised if the file cannot be opened, or is not + # a shared library. + # AttributeError is raised if LLVMPY_GetVersionInfo does not + # exist. + raise OSError("Could not find/load shared object file") from e + + @property + def _lib(self): + # Not threadsafe. + if not self._lib_handle: + self._load_lib() + return self._lib_handle + + def __getattr__(self, name): + try: + return self._fntab[name] + except KeyError: + # Lazily wraps new functions as they are requested + cfn = getattr(self._lib, name) + wrapped = _lib_fn_wrapper(self._lock, cfn) + self._fntab[name] = wrapped + return wrapped + + @property + def _name(self): + """The name of the library passed in the CDLL constructor. + + For duck-typing a ctypes.CDLL + """ + return self._lib._name + + @property + def _handle(self): + """The system handle used to access the library. + + For duck-typing a ctypes.CDLL + """ + return self._lib._handle + + +class _lib_fn_wrapper(object): + """Wraps and duck-types a ctypes.CFUNCTYPE to provide + automatic locking when the wrapped function is called. + + TODO: we can add methods to mark the function as threadsafe + and remove the locking-step on call when marked. + """ + __slots__ = ['_lock', '_cfn'] + + def __init__(self, lock, cfn): + self._lock = lock + self._cfn = cfn + + @property + def argtypes(self): + return self._cfn.argtypes + + @argtypes.setter + def argtypes(self, argtypes): + self._cfn.argtypes = argtypes + + @property + def restype(self): + return self._cfn.restype + + @restype.setter + def restype(self, restype): + self._cfn.restype = restype + + def __call__(self, *args, **kwargs): + with self._lock: + return self._cfn(*args, **kwargs) + + +def _importlib_resources_path_repl(package, resource): + """Replacement implementation of `import.resources.path` to avoid + deprecation warning following code at importlib_resources/_legacy.py + as suggested by https://importlib-resources.readthedocs.io/en/latest/using.html#migrating-from-legacy + + Notes on differences from importlib.resources implementation: + + The `_common.normalize_path(resource)` call is skipped because it is an + internal API and it is unnecessary for the use here. What it does is + ensuring `resource` is a str and that it does not contain path separators. + """ # noqa E501 + return _impres.as_file(_impres.files(package) / resource) + + +_importlib_resources_path = (_importlib_resources_path_repl + if sys.version_info[:2] >= (3, 10) + else _impres.path) + + +lib = _lib_wrapper() + + +def register_lock_callback(acq_fn, rel_fn): + """Register callback functions for lock acquire and release. + *acq_fn* and *rel_fn* are callables that take no arguments. + """ + lib._lock.register(acq_fn, rel_fn) + + +def unregister_lock_callback(acq_fn, rel_fn): + """Remove the registered callback functions for lock acquire and release. + The arguments are the same as used in `register_lock_callback()`. + """ + lib._lock.unregister(acq_fn, rel_fn) + + +class _DeadPointer(object): + """ + Dummy class to make error messages more helpful. + """ + + +class OutputString(object): + """ + Object for managing the char* output of LLVM APIs. + """ + _as_parameter_ = _DeadPointer() + + @classmethod + def from_return(cls, ptr): + """Constructing from a pointer returned from the C-API. + The pointer must be allocated with LLVMPY_CreateString. + + Note + ---- + Because ctypes auto-converts *restype* of *c_char_p* into a python + string, we must use *c_void_p* to obtain the raw pointer. + """ + return cls(init=ctypes.cast(ptr, ctypes.c_char_p)) + + def __init__(self, owned=True, init=None): + self._ptr = init if init is not None else ctypes.c_char_p(None) + self._as_parameter_ = ctypes.byref(self._ptr) + self._owned = owned + + def close(self): + if self._ptr is not None: + if self._owned: + lib.LLVMPY_DisposeString(self._ptr) + self._ptr = None + del self._as_parameter_ + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def __del__(self, _is_shutting_down=_is_shutting_down): + # Avoid errors trying to rely on globals and modules at interpreter + # shutdown. + if not _is_shutting_down(): + if self.close is not None: + self.close() + + def __str__(self): + if self._ptr is None: + return "" + s = self._ptr.value + assert s is not None + return _decode_string(s) + + def __bool__(self): + return bool(self._ptr) + + __nonzero__ = __bool__ + + @property + def bytes(self): + """Get the raw bytes of content of the char pointer. + """ + return self._ptr.value + + +def ret_string(ptr): + """To wrap string return-value from C-API. + """ + if ptr is not None: + return str(OutputString.from_return(ptr)) + + +def ret_bytes(ptr): + """To wrap bytes return-value from C-API. + """ + if ptr is not None: + return OutputString.from_return(ptr).bytes + + +class ObjectRef(object): + """ + A wrapper around a ctypes pointer to a LLVM object ("resource"). + """ + _closed = False + _as_parameter_ = _DeadPointer() + # Whether this object pointer is owned by another one. + _owned = False + + def __init__(self, ptr): + if ptr is None: + raise ValueError("NULL pointer") + self._ptr = ptr + self._as_parameter_ = ptr + self._capi = lib + + def close(self): + """ + Close this object and do any required clean-up actions. + """ + try: + if not self._closed and not self._owned: + self._dispose() + finally: + self.detach() + + def detach(self): + """ + Detach the underlying LLVM resource without disposing of it. + """ + if not self._closed: + del self._as_parameter_ + self._closed = True + self._ptr = None + + def _dispose(self): + """ + Dispose of the underlying LLVM resource. Should be overriden + by subclasses. Automatically called by close(), __del__() and + __exit__() (unless the resource has been detached). + """ + + @property + def closed(self): + """ + Whether this object has been closed. A closed object can't + be used anymore. + """ + return self._closed + + def __enter__(self): + assert hasattr(self, "close") + if self._closed: + raise RuntimeError("%s instance already closed" % (self.__class__,)) + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def __del__(self, _is_shutting_down=_is_shutting_down): + if not _is_shutting_down(): + if self.close is not None: + self.close() + + def __bool__(self): + return bool(self._ptr) + + def __eq__(self, other): + if not hasattr(other, "_ptr"): + return False + return ctypes.addressof(self._ptr[0]) == \ + ctypes.addressof(other._ptr[0]) + + __nonzero__ = __bool__ + + # XXX useful? + def __hash__(self): + return hash(ctypes.cast(self._ptr, ctypes.c_void_p).value) diff --git a/venv/lib/python3.10/site-packages/llvmlite/binding/module.py b/venv/lib/python3.10/site-packages/llvmlite/binding/module.py new file mode 100644 index 0000000000000000000000000000000000000000..dcbb1faa6545718f9226133ccef42b03a098fd37 --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/binding/module.py @@ -0,0 +1,349 @@ +from ctypes import (c_char_p, byref, POINTER, c_bool, create_string_buffer, + c_size_t, string_at) + +from llvmlite.binding import ffi +from llvmlite.binding.linker import link_modules +from llvmlite.binding.common import _decode_string, _encode_string +from llvmlite.binding.value import ValueRef, TypeRef +from llvmlite.binding.context import get_global_context + + +def parse_assembly(llvmir, context=None): + """ + Create Module from a LLVM IR string + """ + if context is None: + context = get_global_context() + llvmir = _encode_string(llvmir) + strbuf = c_char_p(llvmir) + with ffi.OutputString() as errmsg: + mod = ModuleRef( + ffi.lib.LLVMPY_ParseAssembly(context, strbuf, errmsg), + context) + if errmsg: + mod.close() + raise RuntimeError("LLVM IR parsing error\n{0}".format(errmsg)) + return mod + + +def parse_bitcode(bitcode, context=None): + """ + Create Module from a LLVM *bitcode* (a bytes object). + """ + if context is None: + context = get_global_context() + buf = c_char_p(bitcode) + bufsize = len(bitcode) + with ffi.OutputString() as errmsg: + mod = ModuleRef(ffi.lib.LLVMPY_ParseBitcode( + context, buf, bufsize, errmsg), context) + if errmsg: + mod.close() + raise RuntimeError( + "LLVM bitcode parsing error\n{0}".format(errmsg)) + return mod + + +class ModuleRef(ffi.ObjectRef): + """ + A reference to a LLVM module. + """ + + def __init__(self, module_ptr, context): + super(ModuleRef, self).__init__(module_ptr) + self._context = context + + def __str__(self): + with ffi.OutputString() as outstr: + ffi.lib.LLVMPY_PrintModuleToString(self, outstr) + return str(outstr) + + def as_bitcode(self): + """ + Return the module's LLVM bitcode, as a bytes object. + """ + ptr = c_char_p(None) + size = c_size_t(-1) + ffi.lib.LLVMPY_WriteBitcodeToString(self, byref(ptr), byref(size)) + if not ptr: + raise MemoryError + try: + assert size.value >= 0 + return string_at(ptr, size.value) + finally: + ffi.lib.LLVMPY_DisposeString(ptr) + + def _dispose(self): + self._capi.LLVMPY_DisposeModule(self) + + def get_function(self, name): + """ + Get a ValueRef pointing to the function named *name*. + NameError is raised if the symbol isn't found. + """ + p = ffi.lib.LLVMPY_GetNamedFunction(self, _encode_string(name)) + if not p: + raise NameError(name) + return ValueRef(p, 'function', dict(module=self)) + + def get_global_variable(self, name): + """ + Get a ValueRef pointing to the global variable named *name*. + NameError is raised if the symbol isn't found. + """ + p = ffi.lib.LLVMPY_GetNamedGlobalVariable(self, _encode_string(name)) + if not p: + raise NameError(name) + return ValueRef(p, 'global', dict(module=self)) + + def get_struct_type(self, name): + """ + Get a TypeRef pointing to a structure type named *name*. + NameError is raised if the struct type isn't found. + """ + p = ffi.lib.LLVMPY_GetNamedStructType(self, _encode_string(name)) + if not p: + raise NameError(name) + return TypeRef(p) + + def verify(self): + """ + Verify the module IR's correctness. RuntimeError is raised on error. + """ + with ffi.OutputString() as outmsg: + if ffi.lib.LLVMPY_VerifyModule(self, outmsg): + raise RuntimeError(str(outmsg)) + + @property + def name(self): + """ + The module's identifier. + """ + return _decode_string(ffi.lib.LLVMPY_GetModuleName(self)) + + @name.setter + def name(self, value): + ffi.lib.LLVMPY_SetModuleName(self, _encode_string(value)) + + @property + def source_file(self): + """ + The module's original source file name + """ + return _decode_string(ffi.lib.LLVMPY_GetModuleSourceFileName(self)) + + @property + def data_layout(self): + """ + This module's data layout specification, as a string. + """ + # LLVMGetDataLayout() points inside a std::string managed by LLVM. + with ffi.OutputString(owned=False) as outmsg: + ffi.lib.LLVMPY_GetDataLayout(self, outmsg) + return str(outmsg) + + @data_layout.setter + def data_layout(self, strrep): + ffi.lib.LLVMPY_SetDataLayout(self, + create_string_buffer( + strrep.encode('utf8'))) + + @property + def triple(self): + """ + This module's target "triple" specification, as a string. + """ + # LLVMGetTarget() points inside a std::string managed by LLVM. + with ffi.OutputString(owned=False) as outmsg: + ffi.lib.LLVMPY_GetTarget(self, outmsg) + return str(outmsg) + + @triple.setter + def triple(self, strrep): + ffi.lib.LLVMPY_SetTarget(self, + create_string_buffer( + strrep.encode('utf8'))) + + def link_in(self, other, preserve=False): + """ + Link the *other* module into this one. The *other* module will + be destroyed unless *preserve* is true. + """ + if preserve: + other = other.clone() + link_modules(self, other) + + @property + def global_variables(self): + """ + Return an iterator over this module's global variables. + The iterator will yield a ValueRef for each global variable. + + Note that global variables don't include functions + (a function is a "global value" but not a "global variable" in + LLVM parlance) + """ + it = ffi.lib.LLVMPY_ModuleGlobalsIter(self) + return _GlobalsIterator(it, dict(module=self)) + + @property + def functions(self): + """ + Return an iterator over this module's functions. + The iterator will yield a ValueRef for each function. + """ + it = ffi.lib.LLVMPY_ModuleFunctionsIter(self) + return _FunctionsIterator(it, dict(module=self)) + + @property + def struct_types(self): + """ + Return an iterator over the struct types defined in + the module. The iterator will yield a TypeRef. + """ + it = ffi.lib.LLVMPY_ModuleTypesIter(self) + return _TypesIterator(it, dict(module=self)) + + def clone(self): + return ModuleRef(ffi.lib.LLVMPY_CloneModule(self), self._context) + + +class _Iterator(ffi.ObjectRef): + + kind = None + + def __init__(self, ptr, parents): + ffi.ObjectRef.__init__(self, ptr) + self._parents = parents + assert self.kind is not None + + def __next__(self): + vp = self._next() + if vp: + return ValueRef(vp, self.kind, self._parents) + else: + raise StopIteration + + next = __next__ + + def __iter__(self): + return self + + +class _GlobalsIterator(_Iterator): + + kind = 'global' + + def _dispose(self): + self._capi.LLVMPY_DisposeGlobalsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_GlobalsIterNext(self) + + +class _FunctionsIterator(_Iterator): + + kind = 'function' + + def _dispose(self): + self._capi.LLVMPY_DisposeFunctionsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_FunctionsIterNext(self) + + +class _TypesIterator(_Iterator): + + kind = 'type' + + def _dispose(self): + self._capi.LLVMPY_DisposeTypesIter(self) + + def __next__(self): + vp = self._next() + if vp: + return TypeRef(vp) + else: + raise StopIteration + + def _next(self): + return ffi.lib.LLVMPY_TypesIterNext(self) + + next = __next__ + + +# ============================================================================= +# Set function FFI + +ffi.lib.LLVMPY_ParseAssembly.argtypes = [ffi.LLVMContextRef, + c_char_p, + POINTER(c_char_p)] +ffi.lib.LLVMPY_ParseAssembly.restype = ffi.LLVMModuleRef + +ffi.lib.LLVMPY_ParseBitcode.argtypes = [ffi.LLVMContextRef, + c_char_p, c_size_t, + POINTER(c_char_p)] +ffi.lib.LLVMPY_ParseBitcode.restype = ffi.LLVMModuleRef + +ffi.lib.LLVMPY_DisposeModule.argtypes = [ffi.LLVMModuleRef] + +ffi.lib.LLVMPY_PrintModuleToString.argtypes = [ffi.LLVMModuleRef, + POINTER(c_char_p)] +ffi.lib.LLVMPY_WriteBitcodeToString.argtypes = [ffi.LLVMModuleRef, + POINTER(c_char_p), + POINTER(c_size_t)] + +ffi.lib.LLVMPY_GetNamedFunction.argtypes = [ffi.LLVMModuleRef, + c_char_p] +ffi.lib.LLVMPY_GetNamedFunction.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_VerifyModule.argtypes = [ffi.LLVMModuleRef, + POINTER(c_char_p)] +ffi.lib.LLVMPY_VerifyModule.restype = c_bool + +ffi.lib.LLVMPY_GetDataLayout.argtypes = [ffi.LLVMModuleRef, POINTER(c_char_p)] +ffi.lib.LLVMPY_SetDataLayout.argtypes = [ffi.LLVMModuleRef, c_char_p] + +ffi.lib.LLVMPY_GetTarget.argtypes = [ffi.LLVMModuleRef, POINTER(c_char_p)] +ffi.lib.LLVMPY_SetTarget.argtypes = [ffi.LLVMModuleRef, c_char_p] + +ffi.lib.LLVMPY_GetNamedGlobalVariable.argtypes = [ffi.LLVMModuleRef, c_char_p] +ffi.lib.LLVMPY_GetNamedGlobalVariable.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_GetNamedStructType.argtypes = [ffi.LLVMModuleRef, c_char_p] +ffi.lib.LLVMPY_GetNamedStructType.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_ModuleGlobalsIter.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_ModuleGlobalsIter.restype = ffi.LLVMGlobalsIterator + +ffi.lib.LLVMPY_DisposeGlobalsIter.argtypes = [ffi.LLVMGlobalsIterator] + +ffi.lib.LLVMPY_GlobalsIterNext.argtypes = [ffi.LLVMGlobalsIterator] +ffi.lib.LLVMPY_GlobalsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_ModuleFunctionsIter.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_ModuleFunctionsIter.restype = ffi.LLVMFunctionsIterator + +ffi.lib.LLVMPY_ModuleTypesIter.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_ModuleTypesIter.restype = ffi.LLVMTypesIterator + +ffi.lib.LLVMPY_DisposeFunctionsIter.argtypes = [ffi.LLVMFunctionsIterator] + +ffi.lib.LLVMPY_DisposeTypesIter.argtypes = [ffi.LLVMTypesIterator] + +ffi.lib.LLVMPY_FunctionsIterNext.argtypes = [ffi.LLVMFunctionsIterator] +ffi.lib.LLVMPY_FunctionsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_TypesIterNext.argtypes = [ffi.LLVMTypesIterator] +ffi.lib.LLVMPY_TypesIterNext.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_CloneModule.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_CloneModule.restype = ffi.LLVMModuleRef + +ffi.lib.LLVMPY_GetModuleName.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_GetModuleName.restype = c_char_p + +ffi.lib.LLVMPY_SetModuleName.argtypes = [ffi.LLVMModuleRef, c_char_p] + +ffi.lib.LLVMPY_GetModuleSourceFileName.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_GetModuleSourceFileName.restype = c_char_p diff --git a/venv/lib/python3.10/site-packages/llvmlite/binding/newpassmanagers.py b/venv/lib/python3.10/site-packages/llvmlite/binding/newpassmanagers.py new file mode 100644 index 0000000000000000000000000000000000000000..c7082965ee83ada7e352baa8bc663941e5e70b21 --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/binding/newpassmanagers.py @@ -0,0 +1,357 @@ +from ctypes import c_bool, c_int, c_size_t +from enum import IntFlag +from llvmlite.binding import ffi + + +def create_new_module_pass_manager(): + return ModulePassManager() + + +def create_new_function_pass_manager(): + return FunctionPassManager() + + +def create_pass_builder(tm, pto): + return PassBuilder(tm, pto) + + +def create_pipeline_tuning_options(speed_level=2, size_level=0): + return PipelineTuningOptions(speed_level, size_level) + + +class RefPruneSubpasses(IntFlag): + PER_BB = 0b0001 # noqa: E221 + DIAMOND = 0b0010 # noqa: E221 + FANOUT = 0b0100 # noqa: E221 + FANOUT_RAISE = 0b1000 + ALL = PER_BB | DIAMOND | FANOUT | FANOUT_RAISE + + +class ModulePassManager(ffi.ObjectRef): + + def __init__(self, ptr=None): + if ptr is None: + ptr = ffi.lib.LLVMPY_CreateNewModulePassManager() + super().__init__(ptr) + + def run(self, module, pb): + ffi.lib.LLVMPY_RunNewModulePassManager(self, module, pb) + + def add_verifier(self): + ffi.lib.LLVMPY_AddVerifierPass(self) + + def add_aa_eval_pass(self): + ffi.lib.LLVMPY_AddAAEvalPass_module(self) + + def add_simplify_cfg_pass(self): + ffi.lib.LLVMPY_AddSimplifyCFGPass_module(self) + + def add_loop_unroll_pass(self): + ffi.lib.LLVMPY_AddLoopUnrollPass_module(self) + + def add_loop_rotate_pass(self): + ffi.lib.LLVMPY_AddLoopRotatePass_module(self) + + def add_instruction_combine_pass(self): + ffi.lib.LLVMPY_AddInstructionCombinePass_module(self) + + def add_jump_threading_pass(self, threshold=-1): + ffi.lib.LLVMPY_AddJumpThreadingPass_module(self, threshold) + + def _dispose(self): + ffi.lib.LLVMPY_DisposeNewModulePassManger(self) + + # Non-standard LLVM passes + def add_refprune_pass(self, subpasses_flags=RefPruneSubpasses.ALL, + subgraph_limit=1000): + """Add Numba specific Reference count pruning pass. + + Parameters + ---------- + subpasses_flags : RefPruneSubpasses + A bitmask to control the subpasses to be enabled. + subgraph_limit : int + Limit the fanout pruners to working on a subgraph no bigger than + this number of basic-blocks to avoid spending too much time in very + large graphs. Default is 1000. Subject to change in future + versions. + """ + iflags = RefPruneSubpasses(subpasses_flags) + ffi.lib.LLVMPY_AddRefPrunePass_module(self, iflags, subgraph_limit) + + +class FunctionPassManager(ffi.ObjectRef): + + def __init__(self, ptr=None): + if ptr is None: + ptr = ffi.lib.LLVMPY_CreateNewFunctionPassManager() + super().__init__(ptr) + + def run(self, fun, pb): + ffi.lib.LLVMPY_RunNewFunctionPassManager(self, fun, pb) + + def add_aa_eval_pass(self): + ffi.lib.LLVMPY_AddAAEvalPass_function(self) + + def add_simplify_cfg_pass(self): + ffi.lib.LLVMPY_AddSimplifyCFGPass_function(self) + + def add_loop_unroll_pass(self): + ffi.lib.LLVMPY_AddLoopUnrollPass_function(self) + + def add_loop_rotate_pass(self): + ffi.lib.LLVMPY_AddLoopRotatePass_function(self) + + def add_instruction_combine_pass(self): + ffi.lib.LLVMPY_AddInstructionCombinePass_function(self) + + def add_jump_threading_pass(self, threshold=-1): + ffi.lib.LLVMPY_AddJumpThreadingPass_function(self, threshold) + + def _dispose(self): + ffi.lib.LLVMPY_DisposeNewFunctionPassManger(self) + + # Non-standard LLVM passes + def add_refprune_pass(self, subpasses_flags=RefPruneSubpasses.ALL, + subgraph_limit=1000): + """Add Numba specific Reference count pruning pass. + + Parameters + ---------- + subpasses_flags : RefPruneSubpasses + A bitmask to control the subpasses to be enabled. + subgraph_limit : int + Limit the fanout pruners to working on a subgraph no bigger than + this number of basic-blocks to avoid spending too much time in very + large graphs. Default is 1000. Subject to change in future + versions. + """ + iflags = RefPruneSubpasses(subpasses_flags) + ffi.lib.LLVMPY_AddRefPrunePass_function(self, iflags, subgraph_limit) + + +class PipelineTuningOptions(ffi.ObjectRef): + + def __init__(self, speed_level=2, size_level=0): + self._speed_level = None + self._size_level = None + self.speed_level = speed_level + self.size_level = size_level + super().__init__(ffi.lib.LLVMPY_CreatePipelineTuningOptions()) + + @property + def speed_level(self): + return self._speed_level + + @speed_level.setter + def speed_level(self, value): + if not 0 <= value <= 3: + raise ValueError( + "Optimization level for speed should be 0, 1, 2, or 3") + self._speed_level = value + + @property + def size_level(self): + return self._size_level + + @size_level.setter + def size_level(self, value): + if not 0 <= value <= 2: + raise ValueError("Optimization level for size should be 0, 1, or 2") + if value != 0 and self.speed_level != 2: + raise ValueError( + "Optimization for size should be encoded with speed level == 2") + self._size_level = value + + @property + def loop_interleaving(self): + return ffi.lib.LLVMPY_PTOGetLoopInterleaving(self) + + @loop_interleaving.setter + def loop_interleaving(self, value): + ffi.lib.LLVMPY_PTOSetLoopInterleaving(self, value) + + @property + def loop_vectorization(self): + return ffi.lib.LLVMPY_PTOGetLoopVectorization(self) + + @loop_vectorization.setter + def loop_vectorization(self, value): + ffi.lib.LLVMPY_PTOSetLoopVectorization(self, value) + + @property + def slp_vectorization(self): + return ffi.lib.LLVMPY_PTOGetSLPVectorization(self) + + @slp_vectorization.setter + def slp_vectorization(self, value): + ffi.lib.LLVMPY_PTOSetSLPVectorization(self, value) + + @property + def loop_unrolling(self): + return ffi.lib.LLVMPY_PTOGetLoopUnrolling(self) + + @loop_unrolling.setter + def loop_unrolling(self, value): + ffi.lib.LLVMPY_PTOSetLoopUnrolling(self, value) + + # // FIXME: Available from llvm16 + # @property + # def inlining_threshold(self): + # return ffi.lib.LLVMPY_PTOGetInlinerThreshold(self) + + # @inlining_threshold.setter + # def inlining_threshold(self, value): + # ffi.lib.LLVMPY_PTOSetInlinerThreshold(self, value) + + def _dispose(self): + ffi.lib.LLVMPY_DisposePipelineTuningOptions(self) + + +class PassBuilder(ffi.ObjectRef): + + def __init__(self, tm, pto): + super().__init__(ffi.lib.LLVMPY_CreatePassBuilder(tm, pto)) + self._pto = pto + self._tm = tm + + def getModulePassManager(self): + return ModulePassManager( + ffi.lib.LLVMPY_buildPerModuleDefaultPipeline( + self, self._pto.speed_level, self._pto.size_level) + ) + + def getFunctionPassManager(self): + return FunctionPassManager( + ffi.lib.LLVMPY_buildFunctionSimplificationPipeline( + self, self._pto.speed_level, self._pto.size_level) + ) + + def _dispose(self): + ffi.lib.LLVMPY_DisposePassBuilder(self) + + +# ============================================================================ +# FFI + +# ModulePassManager + +ffi.lib.LLVMPY_CreateNewModulePassManager.restype = ffi.LLVMModulePassManagerRef + +ffi.lib.LLVMPY_RunNewModulePassManager.argtypes = [ + ffi.LLVMModulePassManagerRef, ffi.LLVMModuleRef, + ffi.LLVMPassBuilderRef,] + +ffi.lib.LLVMPY_AddVerifierPass.argtypes = [ffi.LLVMModulePassManagerRef,] +ffi.lib.LLVMPY_AddAAEvalPass_module.argtypes = [ffi.LLVMModulePassManagerRef,] +ffi.lib.LLVMPY_AddSimplifyCFGPass_module.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_AddLoopUnrollPass_module.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_AddLoopRotatePass_module.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_AddInstructionCombinePass_module.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_AddJumpThreadingPass_module.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_DisposeNewModulePassManger.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_AddRefPrunePass_module.argtypes = [ + ffi.LLVMModulePassManagerRef, c_int, c_size_t, +] + +# FunctionPassManager + +ffi.lib.LLVMPY_CreateNewFunctionPassManager.restype = \ + ffi.LLVMFunctionPassManagerRef + +ffi.lib.LLVMPY_RunNewFunctionPassManager.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ffi.LLVMValueRef, + ffi.LLVMPassBuilderRef,] + +ffi.lib.LLVMPY_AddAAEvalPass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_AddSimplifyCFGPass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_AddLoopUnrollPass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_AddLoopRotatePass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_AddInstructionCombinePass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_AddJumpThreadingPass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef, c_int,] + +ffi.lib.LLVMPY_DisposeNewFunctionPassManger.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_AddRefPrunePass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef, c_int, c_size_t, +] + +# PipelineTuningOptions + +ffi.lib.LLVMPY_CreatePipelineTuningOptions.restype = \ + ffi.LLVMPipelineTuningOptionsRef + +ffi.lib.LLVMPY_PTOGetLoopInterleaving.restype = c_bool +ffi.lib.LLVMPY_PTOGetLoopInterleaving.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef,] + +ffi.lib.LLVMPY_PTOSetLoopInterleaving.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef, c_bool] + +ffi.lib.LLVMPY_PTOGetLoopVectorization.restype = c_bool +ffi.lib.LLVMPY_PTOGetLoopVectorization.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef,] + +ffi.lib.LLVMPY_PTOSetLoopVectorization.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef, c_bool] + +ffi.lib.LLVMPY_PTOGetSLPVectorization.restype = c_bool +ffi.lib.LLVMPY_PTOGetSLPVectorization.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef,] + +ffi.lib.LLVMPY_PTOSetSLPVectorization.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef, c_bool] + +ffi.lib.LLVMPY_PTOGetLoopUnrolling.restype = c_bool +ffi.lib.LLVMPY_PTOGetLoopUnrolling.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef,] + +ffi.lib.LLVMPY_PTOSetLoopUnrolling.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef, c_bool] + +ffi.lib.LLVMPY_DisposePipelineTuningOptions.argtypes = \ + [ffi.LLVMPipelineTuningOptionsRef,] + +# PassBuilder + +ffi.lib.LLVMPY_CreatePassBuilder.restype = ffi.LLVMPassBuilderRef +ffi.lib.LLVMPY_CreatePassBuilder.argtypes = [ffi.LLVMTargetMachineRef, + ffi.LLVMPipelineTuningOptionsRef,] + +ffi.lib.LLVMPY_DisposePassBuilder.argtypes = [ffi.LLVMPassBuilderRef,] + +# Pipeline builders + +ffi.lib.LLVMPY_buildPerModuleDefaultPipeline.restype = \ + ffi.LLVMModulePassManagerRef +ffi.lib.LLVMPY_buildPerModuleDefaultPipeline.argtypes = [ + ffi.LLVMPassBuilderRef, c_int, c_int] + +ffi.lib.LLVMPY_buildFunctionSimplificationPipeline.restype = \ + ffi.LLVMFunctionPassManagerRef +ffi.lib.LLVMPY_buildFunctionSimplificationPipeline.argtypes = [ + ffi.LLVMPassBuilderRef, c_int, c_int] diff --git a/venv/lib/python3.10/site-packages/llvmlite/binding/transforms.py b/venv/lib/python3.10/site-packages/llvmlite/binding/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..82c5dc157a54d7cb1730dadb9b453cc684640cbf --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/binding/transforms.py @@ -0,0 +1,151 @@ +from ctypes import c_uint, c_bool +from llvmlite.binding import ffi +from llvmlite.binding import passmanagers + + +def create_pass_manager_builder(): + return PassManagerBuilder() + + +class PassManagerBuilder(ffi.ObjectRef): + __slots__ = () + + def __init__(self, ptr=None): + if ptr is None: + ptr = ffi.lib.LLVMPY_PassManagerBuilderCreate() + ffi.ObjectRef.__init__(self, ptr) + + @property + def opt_level(self): + """ + The general optimization level as an integer between 0 and 3. + """ + return ffi.lib.LLVMPY_PassManagerBuilderGetOptLevel(self) + + @opt_level.setter + def opt_level(self, level): + ffi.lib.LLVMPY_PassManagerBuilderSetOptLevel(self, level) + + @property + def size_level(self): + """ + Whether and how much to optimize for size. An integer between 0 and 2. + """ + return ffi.lib.LLVMPY_PassManagerBuilderGetSizeLevel(self) + + @size_level.setter + def size_level(self, size): + ffi.lib.LLVMPY_PassManagerBuilderSetSizeLevel(self, size) + + @property + def inlining_threshold(self): + """ + The integer threshold for inlining a function into another. The higher, + the more likely inlining a function is. This attribute is write-only. + """ + raise NotImplementedError("inlining_threshold is write-only") + + @inlining_threshold.setter + def inlining_threshold(self, threshold): + ffi.lib.LLVMPY_PassManagerBuilderUseInlinerWithThreshold( + self, threshold) + + @property + def disable_unroll_loops(self): + """ + If true, disable loop unrolling. + """ + return ffi.lib.LLVMPY_PassManagerBuilderGetDisableUnrollLoops(self) + + @disable_unroll_loops.setter + def disable_unroll_loops(self, disable=True): + ffi.lib.LLVMPY_PassManagerBuilderSetDisableUnrollLoops(self, disable) + + @property + def loop_vectorize(self): + """ + If true, allow vectorizing loops. + """ + return ffi.lib.LLVMPY_PassManagerBuilderGetLoopVectorize(self) + + @loop_vectorize.setter + def loop_vectorize(self, enable=True): + return ffi.lib.LLVMPY_PassManagerBuilderSetLoopVectorize(self, enable) + + @property + def slp_vectorize(self): + """ + If true, enable the "SLP vectorizer", which uses a different algorithm + from the loop vectorizer. Both may be enabled at the same time. + """ + return ffi.lib.LLVMPY_PassManagerBuilderGetSLPVectorize(self) + + @slp_vectorize.setter + def slp_vectorize(self, enable=True): + return ffi.lib.LLVMPY_PassManagerBuilderSetSLPVectorize(self, enable) + + def _populate_module_pm(self, pm): + ffi.lib.LLVMPY_PassManagerBuilderPopulateModulePassManager(self, pm) + + def _populate_function_pm(self, pm): + ffi.lib.LLVMPY_PassManagerBuilderPopulateFunctionPassManager(self, pm) + + def populate(self, pm): + if isinstance(pm, passmanagers.ModulePassManager): + self._populate_module_pm(pm) + elif isinstance(pm, passmanagers.FunctionPassManager): + self._populate_function_pm(pm) + else: + raise TypeError(pm) + + def _dispose(self): + self._capi.LLVMPY_PassManagerBuilderDispose(self) + + +# ============================================================================ +# FFI + +ffi.lib.LLVMPY_PassManagerBuilderCreate.restype = ffi.LLVMPassManagerBuilderRef + +ffi.lib.LLVMPY_PassManagerBuilderDispose.argtypes = [ + ffi.LLVMPassManagerBuilderRef, +] + +ffi.lib.LLVMPY_PassManagerBuilderPopulateModulePassManager.argtypes = [ + ffi.LLVMPassManagerBuilderRef, + ffi.LLVMPassManagerRef, +] + +ffi.lib.LLVMPY_PassManagerBuilderPopulateFunctionPassManager.argtypes = [ + ffi.LLVMPassManagerBuilderRef, + ffi.LLVMPassManagerRef, +] + +# Unsigned int PassManagerBuilder properties + +for _func in (ffi.lib.LLVMPY_PassManagerBuilderSetOptLevel, + ffi.lib.LLVMPY_PassManagerBuilderSetSizeLevel, + ffi.lib.LLVMPY_PassManagerBuilderUseInlinerWithThreshold, + ): + _func.argtypes = [ffi.LLVMPassManagerBuilderRef, c_uint] + +for _func in (ffi.lib.LLVMPY_PassManagerBuilderGetOptLevel, + ffi.lib.LLVMPY_PassManagerBuilderGetSizeLevel, + ): + _func.argtypes = [ffi.LLVMPassManagerBuilderRef] + _func.restype = c_uint + +# Boolean PassManagerBuilder properties + +for _func in (ffi.lib.LLVMPY_PassManagerBuilderSetDisableUnrollLoops, + ffi.lib.LLVMPY_PassManagerBuilderSetLoopVectorize, + ffi.lib.LLVMPY_PassManagerBuilderSetSLPVectorize, + ): + _func.argtypes = [ffi.LLVMPassManagerBuilderRef, c_bool] + +for _func in (ffi.lib.LLVMPY_PassManagerBuilderGetDisableUnrollLoops, + ffi.lib.LLVMPY_PassManagerBuilderGetLoopVectorize, + ffi.lib.LLVMPY_PassManagerBuilderGetSLPVectorize, + ): + _func.argtypes = [ffi.LLVMPassManagerBuilderRef] + _func.restype = c_bool diff --git a/venv/lib/python3.10/site-packages/llvmlite/ir/__init__.py b/venv/lib/python3.10/site-packages/llvmlite/ir/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b7a0737b2d5325d5c40a8953520a260c013ed48f --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/ir/__init__.py @@ -0,0 +1,11 @@ +""" +This subpackage implements the LLVM IR classes in pure python +""" + +from .types import * +from .values import * +from .module import * +from .builder import * +from .instructions import * +from .transforms import * +from .context import Context, global_context diff --git a/venv/lib/python3.10/site-packages/llvmlite/ir/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/llvmlite/ir/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a7bb409167b97f3abe68db4b642765a492ef84f Binary files /dev/null and b/venv/lib/python3.10/site-packages/llvmlite/ir/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/llvmlite/ir/__pycache__/_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/llvmlite/ir/__pycache__/_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5980e387ca51b77506140babc16fec78bc421dc Binary files /dev/null and b/venv/lib/python3.10/site-packages/llvmlite/ir/__pycache__/_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/llvmlite/ir/__pycache__/builder.cpython-310.pyc b/venv/lib/python3.10/site-packages/llvmlite/ir/__pycache__/builder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b250bb2a5b4a685c345768d35dda5a77a866aef Binary files /dev/null and b/venv/lib/python3.10/site-packages/llvmlite/ir/__pycache__/builder.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/llvmlite/ir/__pycache__/context.cpython-310.pyc b/venv/lib/python3.10/site-packages/llvmlite/ir/__pycache__/context.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a69c3c18d93a2b7d253c66d5704f178ff6857ef Binary files /dev/null and b/venv/lib/python3.10/site-packages/llvmlite/ir/__pycache__/context.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/llvmlite/ir/__pycache__/instructions.cpython-310.pyc b/venv/lib/python3.10/site-packages/llvmlite/ir/__pycache__/instructions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4500756c1f6b2737482d13f226e241c9c4baf7de Binary files /dev/null and b/venv/lib/python3.10/site-packages/llvmlite/ir/__pycache__/instructions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/llvmlite/ir/_utils.py b/venv/lib/python3.10/site-packages/llvmlite/ir/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8287d77afb84f750be00ef0b001a175507c59da4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/ir/_utils.py @@ -0,0 +1,80 @@ +from collections import defaultdict + + +class DuplicatedNameError(NameError): + pass + + +class NameScope(object): + def __init__(self): + self._useset = set(['']) + self._basenamemap = defaultdict(int) + + def is_used(self, name): + return name in self._useset + + def register(self, name, deduplicate=False): + if deduplicate: + name = self.deduplicate(name) + elif self.is_used(name): + raise DuplicatedNameError(name) + self._useset.add(name) + return name + + def deduplicate(self, name): + basename = name + while self.is_used(name): + ident = self._basenamemap[basename] + 1 + self._basenamemap[basename] = ident + name = "{0}.{1}".format(basename, ident) + return name + + def get_child(self): + return type(self)(parent=self) + + +class _StrCaching(object): + + def _clear_string_cache(self): + try: + del self.__cached_str + except AttributeError: + pass + + def __str__(self): + try: + return self.__cached_str + except AttributeError: + s = self.__cached_str = self._to_string() + return s + + +class _StringReferenceCaching(object): + + def get_reference(self): + try: + return self.__cached_refstr + except AttributeError: + s = self.__cached_refstr = self._get_reference() + return s + + +class _HasMetadata(object): + + def set_metadata(self, name, node): + """ + Attach unnamed metadata *node* to the metadata slot *name* of this + value. + """ + self.metadata[name] = node + + def _stringify_metadata(self, leading_comma=False): + if self.metadata: + buf = [] + if leading_comma: + buf.append("") + buf += ["!{0} {1}".format(k, v.get_reference()) + for k, v in self.metadata.items()] + return ', '.join(buf) + else: + return '' diff --git a/venv/lib/python3.10/site-packages/llvmlite/ir/builder.py b/venv/lib/python3.10/site-packages/llvmlite/ir/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..5a1ecf74deb39d6ee92a4cba899702241c6b44cc --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/ir/builder.py @@ -0,0 +1,1120 @@ +import contextlib +import functools + +from llvmlite.ir import instructions, types, values + +_CMP_MAP = { + '>': 'gt', + '<': 'lt', + '==': 'eq', + '!=': 'ne', + '>=': 'ge', + '<=': 'le', +} + + +def _unop(opname, cls=instructions.Instruction): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, arg, name='', flags=()): + instr = cls(self.block, arg.type, opname, [arg], name, flags) + self._insert(instr) + return instr + + return wrapped + + return wrap + + +def _binop(opname, cls=instructions.Instruction): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, lhs, rhs, name='', flags=()): + if lhs.type != rhs.type: + raise ValueError("Operands must be the same type, got (%s, %s)" + % (lhs.type, rhs.type)) + instr = cls(self.block, lhs.type, opname, (lhs, rhs), name, flags) + self._insert(instr) + return instr + + return wrapped + + return wrap + + +def _binop_with_overflow(opname, cls=instructions.Instruction): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, lhs, rhs, name=''): + if lhs.type != rhs.type: + raise ValueError("Operands must be the same type, got (%s, %s)" + % (lhs.type, rhs.type)) + ty = lhs.type + if not isinstance(ty, types.IntType): + raise TypeError("expected an integer type, got %s" % (ty,)) + bool_ty = types.IntType(1) + + mod = self.module + fnty = types.FunctionType(types.LiteralStructType([ty, bool_ty]), + [ty, ty]) + fn = mod.declare_intrinsic("llvm.%s.with.overflow" % (opname,), + [ty], fnty) + ret = self.call(fn, [lhs, rhs], name=name) + return ret + + return wrapped + + return wrap + + +def _uniop(opname, cls=instructions.Instruction): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, operand, name=''): + instr = cls(self.block, operand.type, opname, [operand], name) + self._insert(instr) + return instr + + return wrapped + + return wrap + + +def _uniop_intrinsic_int(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, operand, name=''): + if not isinstance(operand.type, types.IntType): + raise TypeError( + "expected an integer type, got %s" % + operand.type) + fn = self.module.declare_intrinsic(opname, [operand.type]) + return self.call(fn, [operand], name) + + return wrapped + + return wrap + + +def _uniop_intrinsic_float(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, operand, name=''): + if not isinstance( + operand.type, (types.FloatType, types.DoubleType)): + raise TypeError("expected a float type, got %s" % operand.type) + fn = self.module.declare_intrinsic(opname, [operand.type]) + return self.call(fn, [operand], name) + + return wrapped + + return wrap + + +def _uniop_intrinsic_with_flag(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, operand, flag, name=''): + if not isinstance(operand.type, types.IntType): + raise TypeError( + "expected an integer type, got %s" % + operand.type) + if not (isinstance(flag.type, types.IntType) and + flag.type.width == 1): + raise TypeError("expected an i1 type, got %s" % flag.type) + fn = self.module.declare_intrinsic( + opname, [operand.type, flag.type]) + return self.call(fn, [operand, flag], name) + + return wrapped + + return wrap + + +def _triop_intrinsic(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, a, b, c, name=''): + if a.type != b.type or b.type != c.type: + raise TypeError( + "expected types to be the same, got %s, %s, %s" % ( + a.type, + b.type, + c.type)) + elif not isinstance( + a.type, + (types.HalfType, types.FloatType, types.DoubleType)): + raise TypeError( + "expected an floating point type, got %s" % + a.type) + fn = self.module.declare_intrinsic(opname, [a.type, b.type, c.type]) + return self.call(fn, [a, b, c], name) + + return wrapped + + return wrap + + +def _castop(opname, cls=instructions.CastInstr): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, val, typ, name=''): + if val.type == typ: + return val + instr = cls(self.block, opname, val, typ, name) + self._insert(instr) + return instr + + return wrapped + + return wrap + + +def _label_suffix(label, suffix): + """Returns (label + suffix) or a truncated version if it's too long. + Parameters + ---------- + label : str + Label name + suffix : str + Label suffix + """ + if len(label) > 50: + nhead = 25 + return ''.join([label[:nhead], '..', suffix]) + else: + return label + suffix + + +class IRBuilder(object): + def __init__(self, block=None): + self._block = block + self._anchor = len(block.instructions) if block else 0 + self.debug_metadata = None + + @property + def block(self): + """ + The current basic block. + """ + return self._block + + basic_block = block + + @property + def function(self): + """ + The current function. + """ + return self.block.parent + + @property + def module(self): + """ + The current module. + """ + return self.block.parent.module + + def position_before(self, instr): + """ + Position immediately before the given instruction. The current block + is also changed to the instruction's basic block. + """ + self._block = instr.parent + self._anchor = self._block.instructions.index(instr) + + def position_after(self, instr): + """ + Position immediately after the given instruction. The current block + is also changed to the instruction's basic block. + """ + self._block = instr.parent + self._anchor = self._block.instructions.index(instr) + 1 + + def position_at_start(self, block): + """ + Position at the start of the basic *block*. + """ + self._block = block + self._anchor = 0 + + def position_at_end(self, block): + """ + Position at the end of the basic *block*. + """ + self._block = block + self._anchor = len(block.instructions) + + def append_basic_block(self, name=''): + """ + Append a basic block, with the given optional *name*, to the current + function. The current block is not changed. The new block is returned. + """ + return self.function.append_basic_block(name) + + def remove(self, instr): + """Remove the given instruction.""" + idx = self._block.instructions.index(instr) + del self._block.instructions[idx] + if self._block.terminator == instr: + self._block.terminator = None + if self._anchor > idx: + self._anchor -= 1 + + @contextlib.contextmanager + def goto_block(self, block): + """ + A context manager which temporarily positions the builder at the end + of basic block *bb* (but before any terminator). + """ + old_block = self.basic_block + term = block.terminator + if term is not None: + self.position_before(term) + else: + self.position_at_end(block) + try: + yield + finally: + self.position_at_end(old_block) + + @contextlib.contextmanager + def goto_entry_block(self): + """ + A context manager which temporarily positions the builder at the + end of the function's entry block. + """ + with self.goto_block(self.function.entry_basic_block): + yield + + @contextlib.contextmanager + def _branch_helper(self, bbenter, bbexit): + self.position_at_end(bbenter) + yield bbexit + if self.basic_block.terminator is None: + self.branch(bbexit) + + @contextlib.contextmanager + def if_then(self, pred, likely=None): + """ + A context manager which sets up a conditional basic block based + on the given predicate (a i1 value). If the conditional block + is not explicitly terminated, a branch will be added to the next + block. + If *likely* is given, its boolean value indicates whether the + predicate is likely to be true or not, and metadata is issued + for LLVM's optimizers to account for that. + """ + bb = self.basic_block + bbif = self.append_basic_block(name=_label_suffix(bb.name, '.if')) + bbend = self.append_basic_block(name=_label_suffix(bb.name, '.endif')) + br = self.cbranch(pred, bbif, bbend) + if likely is not None: + br.set_weights([99, 1] if likely else [1, 99]) + + with self._branch_helper(bbif, bbend): + yield bbend + + self.position_at_end(bbend) + + @contextlib.contextmanager + def if_else(self, pred, likely=None): + """ + A context manager which sets up two conditional basic blocks based + on the given predicate (a i1 value). + A tuple of context managers is yield'ed. Each context manager + acts as a if_then() block. + *likely* has the same meaning as in if_then(). + + Typical use:: + with builder.if_else(pred) as (then, otherwise): + with then: + # emit instructions for when the predicate is true + with otherwise: + # emit instructions for when the predicate is false + """ + bb = self.basic_block + bbif = self.append_basic_block(name=_label_suffix(bb.name, '.if')) + bbelse = self.append_basic_block(name=_label_suffix(bb.name, '.else')) + bbend = self.append_basic_block(name=_label_suffix(bb.name, '.endif')) + br = self.cbranch(pred, bbif, bbelse) + if likely is not None: + br.set_weights([99, 1] if likely else [1, 99]) + + then = self._branch_helper(bbif, bbend) + otherwise = self._branch_helper(bbelse, bbend) + + yield then, otherwise + + self.position_at_end(bbend) + + def _insert(self, instr): + if self.debug_metadata is not None and 'dbg' not in instr.metadata: + instr.metadata['dbg'] = self.debug_metadata + self._block.instructions.insert(self._anchor, instr) + self._anchor += 1 + + def _set_terminator(self, term): + assert not self.block.is_terminated + self._insert(term) + self.block.terminator = term + return term + + # + # Arithmetic APIs + # + + @_binop('shl') + def shl(self, lhs, rhs, name=''): + """ + Left integer shift: + name = lhs << rhs + """ + + @_binop('lshr') + def lshr(self, lhs, rhs, name=''): + """ + Logical (unsigned) right integer shift: + name = lhs >> rhs + """ + + @_binop('ashr') + def ashr(self, lhs, rhs, name=''): + """ + Arithmetic (signed) right integer shift: + name = lhs >> rhs + """ + + @_binop('add') + def add(self, lhs, rhs, name=''): + """ + Integer addition: + name = lhs + rhs + """ + + @_binop('fadd') + def fadd(self, lhs, rhs, name=''): + """ + Floating-point addition: + name = lhs + rhs + """ + + @_binop('sub') + def sub(self, lhs, rhs, name=''): + """ + Integer subtraction: + name = lhs - rhs + """ + + @_binop('fsub') + def fsub(self, lhs, rhs, name=''): + """ + Floating-point subtraction: + name = lhs - rhs + """ + + @_binop('mul') + def mul(self, lhs, rhs, name=''): + """ + Integer multiplication: + name = lhs * rhs + """ + + @_binop('fmul') + def fmul(self, lhs, rhs, name=''): + """ + Floating-point multiplication: + name = lhs * rhs + """ + + @_binop('udiv') + def udiv(self, lhs, rhs, name=''): + """ + Unsigned integer division: + name = lhs / rhs + """ + + @_binop('sdiv') + def sdiv(self, lhs, rhs, name=''): + """ + Signed integer division: + name = lhs / rhs + """ + + @_binop('fdiv') + def fdiv(self, lhs, rhs, name=''): + """ + Floating-point division: + name = lhs / rhs + """ + + @_binop('urem') + def urem(self, lhs, rhs, name=''): + """ + Unsigned integer remainder: + name = lhs % rhs + """ + + @_binop('srem') + def srem(self, lhs, rhs, name=''): + """ + Signed integer remainder: + name = lhs % rhs + """ + + @_binop('frem') + def frem(self, lhs, rhs, name=''): + """ + Floating-point remainder: + name = lhs % rhs + """ + + @_binop('or') + def or_(self, lhs, rhs, name=''): + """ + Bitwise integer OR: + name = lhs | rhs + """ + + @_binop('and') + def and_(self, lhs, rhs, name=''): + """ + Bitwise integer AND: + name = lhs & rhs + """ + + @_binop('xor') + def xor(self, lhs, rhs, name=''): + """ + Bitwise integer XOR: + name = lhs ^ rhs + """ + + @_binop_with_overflow('sadd') + def sadd_with_overflow(self, lhs, rhs, name=''): + """ + Signed integer addition with overflow: + name = {result, overflow bit} = lhs + rhs + """ + + @_binop_with_overflow('smul') + def smul_with_overflow(self, lhs, rhs, name=''): + """ + Signed integer multiplication with overflow: + name = {result, overflow bit} = lhs * rhs + """ + + @_binop_with_overflow('ssub') + def ssub_with_overflow(self, lhs, rhs, name=''): + """ + Signed integer subtraction with overflow: + name = {result, overflow bit} = lhs - rhs + """ + + @_binop_with_overflow('uadd') + def uadd_with_overflow(self, lhs, rhs, name=''): + """ + Unsigned integer addition with overflow: + name = {result, overflow bit} = lhs + rhs + """ + + @_binop_with_overflow('umul') + def umul_with_overflow(self, lhs, rhs, name=''): + """ + Unsigned integer multiplication with overflow: + name = {result, overflow bit} = lhs * rhs + """ + + @_binop_with_overflow('usub') + def usub_with_overflow(self, lhs, rhs, name=''): + """ + Unsigned integer subtraction with overflow: + name = {result, overflow bit} = lhs - rhs + """ + + # + # Unary APIs + # + + def not_(self, value, name=''): + """ + Bitwise integer complement: + name = ~value + """ + if isinstance(value.type, types.VectorType): + rhs = values.Constant(value.type, (-1,) * value.type.count) + else: + rhs = values.Constant(value.type, -1) + return self.xor(value, rhs, name=name) + + def neg(self, value, name=''): + """ + Integer negative: + name = -value + """ + return self.sub(values.Constant(value.type, 0), value, name=name) + + @_unop('fneg') + def fneg(self, arg, name='', flags=()): + """ + Floating-point negative: + name = -arg + """ + + # + # Comparison APIs + # + + def _icmp(self, prefix, cmpop, lhs, rhs, name): + try: + op = _CMP_MAP[cmpop] + except KeyError: + raise ValueError("invalid comparison %r for icmp" % (cmpop,)) + if cmpop not in ('==', '!='): + op = prefix + op + instr = instructions.ICMPInstr(self.block, op, lhs, rhs, name=name) + self._insert(instr) + return instr + + def icmp_signed(self, cmpop, lhs, rhs, name=''): + """ + Signed integer comparison: + name = lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=' + """ + return self._icmp('s', cmpop, lhs, rhs, name) + + def icmp_unsigned(self, cmpop, lhs, rhs, name=''): + """ + Unsigned integer (or pointer) comparison: + name = lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=' + """ + return self._icmp('u', cmpop, lhs, rhs, name) + + def fcmp_ordered(self, cmpop, lhs, rhs, name='', flags=()): + """ + Floating-point ordered comparison: + name = lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' + """ + if cmpop in _CMP_MAP: + op = 'o' + _CMP_MAP[cmpop] + else: + op = cmpop + instr = instructions.FCMPInstr( + self.block, op, lhs, rhs, name=name, flags=flags) + self._insert(instr) + return instr + + def fcmp_unordered(self, cmpop, lhs, rhs, name='', flags=()): + """ + Floating-point unordered comparison: + name = lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' + """ + if cmpop in _CMP_MAP: + op = 'u' + _CMP_MAP[cmpop] + else: + op = cmpop + instr = instructions.FCMPInstr( + self.block, op, lhs, rhs, name=name, flags=flags) + self._insert(instr) + return instr + + def select(self, cond, lhs, rhs, name='', flags=()): + """ + Ternary select operator: + name = cond ? lhs : rhs + """ + instr = instructions.SelectInstr(self.block, cond, lhs, rhs, name=name, + flags=flags) + self._insert(instr) + return instr + + # + # Cast APIs + # + + @_castop('trunc') + def trunc(self, value, typ, name=''): + """ + Truncating integer downcast to a smaller type: + name = (typ) value + """ + + @_castop('zext') + def zext(self, value, typ, name=''): + """ + Zero-extending integer upcast to a larger type: + name = (typ) value + """ + + @_castop('sext') + def sext(self, value, typ, name=''): + """ + Sign-extending integer upcast to a larger type: + name = (typ) value + """ + + @_castop('fptrunc') + def fptrunc(self, value, typ, name=''): + """ + Floating-point downcast to a less precise type: + name = (typ) value + """ + + @_castop('fpext') + def fpext(self, value, typ, name=''): + """ + Floating-point upcast to a more precise type: + name = (typ) value + """ + + @_castop('bitcast') + def bitcast(self, value, typ, name=''): + """ + Pointer cast to a different pointer type: + name = (typ) value + """ + + @_castop('addrspacecast') + def addrspacecast(self, value, typ, name=''): + """ + Pointer cast to a different address space: + name = (typ) value + """ + + @_castop('fptoui') + def fptoui(self, value, typ, name=''): + """ + Convert floating-point to unsigned integer: + name = (typ) value + """ + + @_castop('uitofp') + def uitofp(self, value, typ, name=''): + """ + Convert unsigned integer to floating-point: + name = (typ) value + """ + + @_castop('fptosi') + def fptosi(self, value, typ, name=''): + """ + Convert floating-point to signed integer: + name = (typ) value + """ + + @_castop('sitofp') + def sitofp(self, value, typ, name=''): + """ + Convert signed integer to floating-point: + name = (typ) value + """ + + @_castop('ptrtoint') + def ptrtoint(self, value, typ, name=''): + """ + Cast pointer to integer: + name = (typ) value + """ + + @_castop('inttoptr') + def inttoptr(self, value, typ, name=''): + """ + Cast integer to pointer: + name = (typ) value + """ + + # + # Memory APIs + # + + def alloca(self, typ, size=None, name=''): + """ + Stack-allocate a slot for *size* elements of the given type. + (default one element) + """ + if size is None: + pass + elif isinstance(size, (values.Value, values.Constant)): + assert isinstance(size.type, types.IntType) + else: + # If it is not a Value instance, + # assume to be a Python integer. + size = values.Constant(types.IntType(32), size) + + al = instructions.AllocaInstr(self.block, typ, size, name) + self._insert(al) + return al + + def load(self, ptr, name='', align=None, typ=None): + """ + Load value from pointer, with optional guaranteed alignment: + name = *ptr + """ + if not isinstance(ptr.type, types.PointerType): + msg = "cannot load from value of type %s (%r): not a pointer" + raise TypeError(msg % (ptr.type, str(ptr))) + ld = instructions.LoadInstr(self.block, ptr, name, typ=typ) + ld.align = align + self._insert(ld) + return ld + + def store(self, value, ptr, align=None): + """ + Store value to pointer, with optional guaranteed alignment: + *ptr = name + """ + if not isinstance(ptr.type, types.PointerType): + msg = "cannot store to value of type %s (%r): not a pointer" + raise TypeError(msg % (ptr.type, str(ptr))) + if not ptr.type.is_opaque and ptr.type.pointee != value.type: + raise TypeError("cannot store %s to %s: mismatching types" + % (value.type, ptr.type)) + st = instructions.StoreInstr(self.block, value, ptr) + st.align = align + self._insert(st) + return st + + def load_atomic(self, ptr, ordering, align, name='', typ=None): + """ + Load value from pointer, with optional guaranteed alignment: + name = *ptr + """ + if not isinstance(ptr.type, types.PointerType): + msg = "cannot load from value of type %s (%r): not a pointer" + raise TypeError(msg % (ptr.type, str(ptr))) + ld = instructions.LoadAtomicInstr( + self.block, ptr, ordering, align, name, typ=typ) + self._insert(ld) + return ld + + def store_atomic(self, value, ptr, ordering, align): + """ + Store value to pointer, with optional guaranteed alignment: + *ptr = name + """ + if not isinstance(ptr.type, types.PointerType): + msg = "cannot store to value of type %s (%r): not a pointer" + raise TypeError(msg % (ptr.type, str(ptr))) + if ptr.type.pointee != value.type: + raise TypeError("cannot store %s to %s: mismatching types" + % (value.type, ptr.type)) + st = instructions.StoreAtomicInstr( + self.block, value, ptr, ordering, align) + self._insert(st) + return st + + # + # Terminators APIs + # + + def switch(self, value, default): + """ + Create a switch-case with a single *default* target. + """ + swt = instructions.SwitchInstr(self.block, 'switch', value, default) + self._set_terminator(swt) + return swt + + def branch(self, target): + """ + Unconditional branch to *target*. + """ + br = instructions.Branch(self.block, "br", [target]) + self._set_terminator(br) + return br + + def cbranch(self, cond, truebr, falsebr): + """ + Conditional branch to *truebr* if *cond* is true, else to *falsebr*. + """ + br = instructions.ConditionalBranch(self.block, "br", + [cond, truebr, falsebr]) + self._set_terminator(br) + return br + + def branch_indirect(self, addr): + """ + Indirect branch to target *addr*. + """ + br = instructions.IndirectBranch(self.block, "indirectbr", addr) + self._set_terminator(br) + return br + + def ret_void(self): + """ + Return from function without a value. + """ + return self._set_terminator( + instructions.Ret(self.block, "ret void")) + + def ret(self, value): + """ + Return from function with the given *value*. + """ + return self._set_terminator( + instructions.Ret(self.block, "ret", value)) + + def resume(self, landingpad): + """ + Resume an in-flight exception. + """ + br = instructions.Branch(self.block, "resume", [landingpad]) + self._set_terminator(br) + return br + + # Call APIs + + def call(self, fn, args, name='', cconv=None, tail=False, fastmath=(), + attrs=(), arg_attrs=None): + """ + Call function *fn* with *args*: + name = fn(args...) + """ + inst = instructions.CallInstr(self.block, fn, args, name=name, + cconv=cconv, tail=tail, fastmath=fastmath, + attrs=attrs, arg_attrs=arg_attrs) + self._insert(inst) + return inst + + def asm(self, ftype, asm, constraint, args, side_effect, name=''): + """ + Inline assembler. + """ + asm = instructions.InlineAsm(ftype, asm, constraint, side_effect) + return self.call(asm, args, name) + + def load_reg(self, reg_type, reg_name, name=''): + """ + Load a register value into an LLVM value. + Example: v = load_reg(IntType(32), "eax") + """ + ftype = types.FunctionType(reg_type, []) + return self.asm(ftype, "", "={%s}" % reg_name, [], False, name) + + def store_reg(self, value, reg_type, reg_name, name=''): + """ + Store an LLVM value inside a register + Example: + store_reg(Constant(IntType(32), 0xAAAAAAAA), IntType(32), "eax") + """ + ftype = types.FunctionType(types.VoidType(), [reg_type]) + return self.asm(ftype, "", "{%s}" % reg_name, [value], True, name) + + def invoke(self, fn, args, normal_to, unwind_to, + name='', cconv=None, fastmath=(), attrs=(), arg_attrs=None): + inst = instructions.InvokeInstr(self.block, fn, args, normal_to, + unwind_to, name=name, cconv=cconv, + fastmath=fastmath, attrs=attrs, + arg_attrs=arg_attrs) + self._set_terminator(inst) + return inst + + # GEP APIs + + def gep(self, ptr, indices, inbounds=False, name='', source_etype=None): + """ + Compute effective address (getelementptr): + name = getelementptr ptr, + """ + instr = instructions.GEPInstr(self.block, ptr, indices, + inbounds=inbounds, name=name, + source_etype=source_etype) + self._insert(instr) + return instr + + # Vector Operations APIs + + def extract_element(self, vector, idx, name=''): + """ + Returns the value at position idx. + """ + instr = instructions.ExtractElement(self.block, vector, idx, name=name) + self._insert(instr) + return instr + + def insert_element(self, vector, value, idx, name=''): + """ + Returns vector with vector[idx] replaced by value. + The result is undefined if the idx is larger or equal the vector length. + """ + instr = instructions.InsertElement(self.block, vector, value, idx, + name=name) + self._insert(instr) + return instr + + def shuffle_vector(self, vector1, vector2, mask, name=''): + """ + Constructs a permutation of elements from *vector1* and *vector2*. + Returns a new vector in the same length of *mask*. + + * *vector1* and *vector2* must have the same element type. + * *mask* must be a constant vector of integer types. + """ + instr = instructions.ShuffleVector(self.block, vector1, vector2, mask, + name=name) + self._insert(instr) + return instr + + # Aggregate APIs + + def extract_value(self, agg, idx, name=''): + """ + Extract member number *idx* from aggregate. + """ + if not isinstance(idx, (tuple, list)): + idx = [idx] + instr = instructions.ExtractValue(self.block, agg, idx, name=name) + self._insert(instr) + return instr + + def insert_value(self, agg, value, idx, name=''): + """ + Insert *value* into member number *idx* from aggregate. + """ + if not isinstance(idx, (tuple, list)): + idx = [idx] + instr = instructions.InsertValue(self.block, agg, value, idx, name=name) + self._insert(instr) + return instr + + # PHI APIs + + def phi(self, typ, name='', flags=()): + inst = instructions.PhiInstr(self.block, typ, name=name, flags=flags) + self._insert(inst) + return inst + + # Special API + + def unreachable(self): + inst = instructions.Unreachable(self.block) + self._set_terminator(inst) + return inst + + def atomic_rmw(self, op, ptr, val, ordering, name=''): + inst = instructions.AtomicRMW( + self.block, op, ptr, val, ordering, name=name) + self._insert(inst) + return inst + + def cmpxchg(self, ptr, cmp, val, ordering, failordering=None, name=''): + """ + Atomic compared-and-set: + atomic { + old = *ptr + success = (old == cmp) + if (success) + *ptr = val + } + name = { old, success } + + If failordering is `None`, the value of `ordering` is used. + """ + failordering = ordering if failordering is None else failordering + inst = instructions.CmpXchg(self.block, ptr, cmp, val, ordering, + failordering, name=name) + self._insert(inst) + return inst + + def landingpad(self, typ, name='', cleanup=False): + inst = instructions.LandingPadInstr(self.block, typ, name, cleanup) + self._insert(inst) + return inst + + def assume(self, cond): + """ + Optimizer hint: assume *cond* is always true. + """ + fn = self.module.declare_intrinsic("llvm.assume") + return self.call(fn, [cond]) + + def fence(self, ordering, targetscope=None, name=''): + """ + Add a memory barrier, preventing certain reorderings of load and/or + store accesses with + respect to other processors and devices. + """ + inst = instructions.Fence(self.block, ordering, targetscope, name=name) + self._insert(inst) + return inst + + def comment(self, text): + """ + Puts a single-line comment into the generated IR. This will be ignored + by LLVM, but can be useful for debugging the output of a compiler. Adds + a comment to the source file. + + * *text* is a string that does not contain new line characters. + """ + inst = instructions.Comment(self.block, text) + self._insert(inst) + return inst + + @_uniop_intrinsic_int("llvm.bswap") + def bswap(self, cond): + """ + Used to byte swap integer values with an even number of bytes (positive + multiple of 16 bits) + """ + + @_uniop_intrinsic_int("llvm.bitreverse") + def bitreverse(self, cond): + """ + Reverse the bitpattern of an integer value; for example 0b10110110 + becomes 0b01101101. + """ + + @_uniop_intrinsic_int("llvm.ctpop") + def ctpop(self, cond): + """ + Counts the number of bits set in a value. + """ + + @_uniop_intrinsic_with_flag("llvm.ctlz") + def ctlz(self, cond, flag): + """ + Counts leading zero bits in *value*. Boolean *flag* indicates whether + the result is defined for ``0``. + """ + + @_uniop_intrinsic_with_flag("llvm.cttz") + def cttz(self, cond, flag): + """ + Counts trailing zero bits in *value*. Boolean *flag* indicates whether + the result is defined for ``0``. + """ + + @_triop_intrinsic("llvm.fma") + def fma(self, a, b, c): + """ + Perform the fused multiply-add operation. + """ + + def convert_from_fp16(self, a, to=None, name=''): + """ + Convert from an i16 to the given FP type + """ + if not to: + raise TypeError("expected a float return type") + if not isinstance(to, (types.FloatType, types.DoubleType)): + raise TypeError("expected a float type, got %s" % to) + if not (isinstance(a.type, types.IntType) and a.type.width == 16): + raise TypeError("expected an i16 type, got %s" % a.type) + + opname = 'llvm.convert.from.fp16' + fn = self.module.declare_intrinsic(opname, [to]) + return self.call(fn, [a], name) + + @_uniop_intrinsic_float("llvm.convert.to.fp16") + def convert_to_fp16(self, a): + """ + Convert the given FP number to an i16 + """ diff --git a/venv/lib/python3.10/site-packages/llvmlite/ir/context.py b/venv/lib/python3.10/site-packages/llvmlite/ir/context.py new file mode 100644 index 0000000000000000000000000000000000000000..7152e1390fd2fc0819893ae43eefce62f4366472 --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/ir/context.py @@ -0,0 +1,20 @@ +from llvmlite.ir import _utils +from llvmlite.ir import types + + +class Context(object): + def __init__(self): + self.scope = _utils.NameScope() + self.identified_types = {} + + def get_identified_type(self, name, packed=False): + if name not in self.identified_types: + self.scope.register(name) + ty = types.IdentifiedStructType(self, name, packed) + self.identified_types[name] = ty + else: + ty = self.identified_types[name] + return ty + + +global_context = Context() diff --git a/venv/lib/python3.10/site-packages/llvmlite/ir/instructions.py b/venv/lib/python3.10/site-packages/llvmlite/ir/instructions.py new file mode 100644 index 0000000000000000000000000000000000000000..58039ab50ed99c86cbbbe075f866dc947f0a6195 --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/ir/instructions.py @@ -0,0 +1,920 @@ +""" +Implementation of LLVM IR instructions. +""" + +from llvmlite.ir import types +from llvmlite.ir.values import (Block, Function, Value, NamedValue, Constant, + MetaDataArgument, MetaDataString, AttributeSet, + Undefined, ArgumentAttributes) +from llvmlite.ir._utils import _HasMetadata + + +class Instruction(NamedValue, _HasMetadata): + def __init__(self, parent, typ, opname, operands, name='', flags=()): + super(Instruction, self).__init__(parent, typ, name=name) + assert isinstance(parent, Block) + assert isinstance(flags, (tuple, list)) + self.opname = opname + self.operands = operands + self.flags = list(flags) + self.metadata = {} + + @property + def function(self): + return self.parent.function + + @property + def module(self): + return self.parent.function.module + + def descr(self, buf): + opname = self.opname + if self.flags: + opname = ' '.join([opname] + self.flags) + operands = ', '.join([op.get_reference() for op in self.operands]) + typ = self.type + metadata = self._stringify_metadata(leading_comma=True) + buf.append("{0} {1} {2}{3}\n" + .format(opname, typ, operands, metadata)) + + def replace_usage(self, old, new): + if old in self.operands: + ops = [] + for op in self.operands: + ops.append(new if op is old else op) + self.operands = tuple(ops) + self._clear_string_cache() + + def __repr__(self): + return "" % ( + self.__class__.__name__, self.name, self.type, + self.opname, self.operands) + + +class CallInstrAttributes(AttributeSet): + _known = frozenset(['convergent', 'noreturn', 'nounwind', 'readonly', + 'readnone', 'noinline', 'alwaysinline']) + + +TailMarkerOptions = frozenset(['tail', 'musttail', 'notail']) + + +class FastMathFlags(AttributeSet): + _known = frozenset(['fast', 'nnan', 'ninf', 'nsz', 'arcp', 'contract', + 'afn', 'reassoc']) + + +class CallInstr(Instruction): + def __init__(self, parent, func, args, name='', cconv=None, tail=None, + fastmath=(), attrs=(), arg_attrs=None): + self.cconv = (func.calling_convention + if cconv is None and isinstance(func, Function) + else cconv) + + # For backwards compatibility with previous API of accepting a "truthy" + # value for a hint to the optimizer to potentially tail optimize. + if isinstance(tail, str) and tail in TailMarkerOptions: + pass + elif tail: + tail = "tail" + else: + tail = "" + + self.tail = tail + self.fastmath = FastMathFlags(fastmath) + self.attributes = CallInstrAttributes(attrs) + self.arg_attributes = {} + if arg_attrs: + for idx, attrs in arg_attrs.items(): + if not (0 <= idx < len(args)): + raise ValueError("Invalid argument index {}" + .format(idx)) + self.arg_attributes[idx] = ArgumentAttributes(attrs) + + # Fix and validate arguments + args = list(args) + for i in range(len(func.function_type.args)): + arg = args[i] + expected_type = func.function_type.args[i] + if (isinstance(expected_type, types.MetaDataType) and + arg.type != expected_type): + arg = MetaDataArgument(arg) + if arg.type != expected_type: + msg = ("Type of #{0} arg mismatch: {1} != {2}" + .format(1 + i, expected_type, arg.type)) + raise TypeError(msg) + args[i] = arg + + super(CallInstr, self).__init__(parent, func.function_type.return_type, + "call", [func] + list(args), name=name) + + @property + def callee(self): + return self.operands[0] + + @callee.setter + def callee(self, newcallee): + self.operands[0] = newcallee + + @property + def args(self): + return self.operands[1:] + + def replace_callee(self, newfunc): + if newfunc.function_type != self.callee.function_type: + raise TypeError("New function has incompatible type") + self.callee = newfunc + + @property + def called_function(self): + """The callee function""" + return self.callee + + def _descr(self, buf, add_metadata): + def descr_arg(i, a): + if i in self.arg_attributes: + attrs = ' '.join(self.arg_attributes[i]._to_list(a.type)) + ' ' + else: + attrs = '' + return '{0} {1}{2}'.format(a.type, attrs, a.get_reference()) + args = ', '.join([descr_arg(i, a) for i, a in enumerate(self.args)]) + + fnty = self.callee.function_type + # Only print function type if variable-argument + if fnty.var_arg: + ty = fnty + # Otherwise, just print the return type. + else: + # Fastmath flag work only in this case + ty = fnty.return_type + callee_ref = "{0} {1}".format(ty, self.callee.get_reference()) + if self.cconv: + callee_ref = "{0} {1}".format(self.cconv, callee_ref) + + tail_marker = "" + if self.tail: + tail_marker = "{0} ".format(self.tail) + + fn_attrs = ' ' + ' '.join(self.attributes._to_list(fnty.return_type))\ + if self.attributes else '' + + fm_attrs = ' ' + ' '.join(self.fastmath._to_list(fnty.return_type))\ + if self.fastmath else '' + + buf.append("{tail}{op}{fastmath} {callee}({args}){attr}{meta}\n".format( + tail=tail_marker, + op=self.opname, + callee=callee_ref, + fastmath=fm_attrs, + args=args, + attr=fn_attrs, + meta=(self._stringify_metadata(leading_comma=True) + if add_metadata else ""), + )) + + def descr(self, buf): + self._descr(buf, add_metadata=True) + + +class InvokeInstr(CallInstr): + def __init__(self, parent, func, args, normal_to, unwind_to, name='', + cconv=None, fastmath=(), attrs=(), arg_attrs=None): + assert isinstance(normal_to, Block) + assert isinstance(unwind_to, Block) + super(InvokeInstr, self).__init__(parent, func, args, name, cconv, + tail=False, fastmath=fastmath, + attrs=attrs, arg_attrs=arg_attrs) + self.opname = "invoke" + self.normal_to = normal_to + self.unwind_to = unwind_to + + def descr(self, buf): + super(InvokeInstr, self)._descr(buf, add_metadata=False) + buf.append(" to label {0} unwind label {1}{metadata}\n".format( + self.normal_to.get_reference(), + self.unwind_to.get_reference(), + metadata=self._stringify_metadata(leading_comma=True), + )) + + +class Terminator(Instruction): + def __init__(self, parent, opname, operands): + super(Terminator, self).__init__(parent, types.VoidType(), opname, + operands) + + def descr(self, buf): + opname = self.opname + operands = ', '.join(["{0} {1}".format(op.type, op.get_reference()) + for op in self.operands]) + metadata = self._stringify_metadata(leading_comma=True) + buf.append("{0} {1}{2}".format(opname, operands, metadata)) + + +class PredictableInstr(Instruction): + + def set_weights(self, weights): + operands = [MetaDataString(self.module, "branch_weights")] + for w in weights: + if w < 0: + raise ValueError("branch weight must be a positive integer") + operands.append(Constant(types.IntType(32), w)) + md = self.module.add_metadata(operands) + self.set_metadata("prof", md) + + +class Ret(Terminator): + def __init__(self, parent, opname, return_value=None): + operands = [return_value] if return_value is not None else [] + super(Ret, self).__init__(parent, opname, operands) + + @property + def return_value(self): + if self.operands: + return self.operands[0] + else: + return None + + def descr(self, buf): + return_value = self.return_value + metadata = self._stringify_metadata(leading_comma=True) + if return_value is not None: + buf.append("{0} {1} {2}{3}\n" + .format(self.opname, return_value.type, + return_value.get_reference(), + metadata)) + else: + buf.append("{0}{1}\n".format(self.opname, metadata)) + + +class Branch(Terminator): + pass + + +class ConditionalBranch(PredictableInstr, Terminator): + pass + + +class IndirectBranch(PredictableInstr, Terminator): + def __init__(self, parent, opname, addr): + super(IndirectBranch, self).__init__(parent, opname, [addr]) + self.destinations = [] + + @property + def address(self): + return self.operands[0] + + def add_destination(self, block): + assert isinstance(block, Block) + self.destinations.append(block) + + def descr(self, buf): + destinations = ["label {0}".format(blk.get_reference()) + for blk in self.destinations] + buf.append("indirectbr {0} {1}, [{2}] {3}\n".format( + self.address.type, + self.address.get_reference(), + ', '.join(destinations), + self._stringify_metadata(leading_comma=True), + )) + + +class SwitchInstr(PredictableInstr, Terminator): + + def __init__(self, parent, opname, val, default): + super(SwitchInstr, self).__init__(parent, opname, [val]) + self.default = default + self.cases = [] + + @property + def value(self): + return self.operands[0] + + def add_case(self, val, block): + assert isinstance(block, Block) + if not isinstance(val, Value): + val = Constant(self.value.type, val) + self.cases.append((val, block)) + + def descr(self, buf): + cases = ["{0} {1}, label {2}".format(val.type, val.get_reference(), + blk.get_reference()) + for val, blk in self.cases] + buf.append("switch {0} {1}, label {2} [{3}] {4}\n".format( + self.value.type, + self.value.get_reference(), + self.default.get_reference(), + ' '.join(cases), + self._stringify_metadata(leading_comma=True), + )) + + +class Resume(Terminator): + pass + + +class SelectInstr(Instruction): + def __init__(self, parent, cond, lhs, rhs, name='', flags=()): + assert lhs.type == rhs.type + super(SelectInstr, self).__init__(parent, lhs.type, "select", + [cond, lhs, rhs], name=name, + flags=flags) + + @property + def cond(self): + return self.operands[0] + + @property + def lhs(self): + return self.operands[1] + + @property + def rhs(self): + return self.operands[2] + + def descr(self, buf): + buf.append("select {0} {1} {2}, {3} {4}, {5} {6} {7}\n".format( + ' '.join(self.flags), + self.cond.type, self.cond.get_reference(), + self.lhs.type, self.lhs.get_reference(), + self.rhs.type, self.rhs.get_reference(), + self._stringify_metadata(leading_comma=True), + )) + + +class CompareInstr(Instruction): + # Define the following in subclasses + OPNAME = 'invalid-compare' + VALID_OP = {} + + def __init__(self, parent, op, lhs, rhs, name='', flags=[]): + if op not in self.VALID_OP: + raise ValueError("invalid comparison %r for %s" % (op, self.OPNAME)) + for flag in flags: + if flag not in self.VALID_FLAG: + raise ValueError("invalid flag %r for %s" % (flag, self.OPNAME)) + opname = self.OPNAME + if isinstance(lhs.type, types.VectorType): + typ = types.VectorType(types.IntType(1), lhs.type.count) + else: + typ = types.IntType(1) + super(CompareInstr, self).__init__(parent, typ, + opname, [lhs, rhs], flags=flags, + name=name) + self.op = op + + def descr(self, buf): + buf.append("{opname}{flags} {op} {ty} {lhs}, {rhs} {meta}\n".format( + opname=self.opname, + flags=''.join(' ' + it for it in self.flags), + op=self.op, + ty=self.operands[0].type, + lhs=self.operands[0].get_reference(), + rhs=self.operands[1].get_reference(), + meta=self._stringify_metadata(leading_comma=True), + )) + + +class ICMPInstr(CompareInstr): + OPNAME = 'icmp' + VALID_OP = { + 'eq': 'equal', + 'ne': 'not equal', + 'ugt': 'unsigned greater than', + 'uge': 'unsigned greater or equal', + 'ult': 'unsigned less than', + 'ule': 'unsigned less or equal', + 'sgt': 'signed greater than', + 'sge': 'signed greater or equal', + 'slt': 'signed less than', + 'sle': 'signed less or equal', + } + VALID_FLAG = set() + + +class FCMPInstr(CompareInstr): + OPNAME = 'fcmp' + VALID_OP = { + 'false': 'no comparison, always returns false', + 'oeq': 'ordered and equal', + 'ogt': 'ordered and greater than', + 'oge': 'ordered and greater than or equal', + 'olt': 'ordered and less than', + 'ole': 'ordered and less than or equal', + 'one': 'ordered and not equal', + 'ord': 'ordered (no nans)', + 'ueq': 'unordered or equal', + 'ugt': 'unordered or greater than', + 'uge': 'unordered or greater than or equal', + 'ult': 'unordered or less than', + 'ule': 'unordered or less than or equal', + 'une': 'unordered or not equal', + 'uno': 'unordered (either nans)', + 'true': 'no comparison, always returns true', + } + VALID_FLAG = {'nnan', 'ninf', 'nsz', 'arcp', 'contract', 'afn', 'reassoc', + 'fast'} + + +class CastInstr(Instruction): + def __init__(self, parent, op, val, typ, name=''): + super(CastInstr, self).__init__(parent, typ, op, [val], name=name) + + def descr(self, buf): + buf.append("{0} {1} {2} to {3} {4}\n".format( + self.opname, + self.operands[0].type, + self.operands[0].get_reference(), + self.type, + self._stringify_metadata(leading_comma=True), + )) + + +class LoadInstr(Instruction): + + def __init__(self, parent, ptr, name='', typ=None): + if typ is None: + if isinstance(ptr, AllocaInstr): + typ = ptr.allocated_type + # For compatibility with typed pointers. Eventually this should + # probably be removed (when typed pointers are fully removed). + elif not ptr.type.is_opaque: + typ = ptr.type.pointee + else: + raise ValueError("Load lacks type.") + super(LoadInstr, self).__init__(parent, typ, "load", [ptr], name=name) + self.align = None + + def descr(self, buf): + [val] = self.operands + if self.align is not None: + align = ', align %d' % (self.align) + else: + align = '' + buf.append("load {0}, {1} {2}{3}{4}\n".format( + self.type, + val.type, + val.get_reference(), + align, + self._stringify_metadata(leading_comma=True), + )) + + +class StoreInstr(Instruction): + def __init__(self, parent, val, ptr): + super(StoreInstr, self).__init__(parent, types.VoidType(), "store", + [val, ptr]) + + def descr(self, buf): + val, ptr = self.operands + if self.align is not None: + align = ', align %d' % (self.align) + else: + align = '' + buf.append("store {0} {1}, {2} {3}{4}{5}\n".format( + val.type, + val.get_reference(), + ptr.type, + ptr.get_reference(), + align, + self._stringify_metadata(leading_comma=True), + )) + + +class LoadAtomicInstr(Instruction): + def __init__(self, parent, ptr, ordering, align, name='', typ=None): + if typ is None: + if isinstance(ptr, AllocaInstr): + typ = ptr.allocated_type + # For compatibility with typed pointers. Eventually this should + # probably be removed (when typed pointers are fully removed). + elif not ptr.type.is_opaque: + typ = ptr.type.pointee + else: + raise ValueError("Load atomic lacks type.") + super(LoadAtomicInstr, self).__init__(parent, typ, "load atomic", + [ptr], name=name) + self.ordering = ordering + self.align = align + + def descr(self, buf): + [val] = self.operands + buf.append("load atomic {0}, {1} {2} {3}, align {4}{5}\n".format( + self.type, + val.type, + val.get_reference(), + self.ordering, + self.align, + self._stringify_metadata(leading_comma=True), + )) + + +class StoreAtomicInstr(Instruction): + def __init__(self, parent, val, ptr, ordering, align): + super(StoreAtomicInstr, self).__init__(parent, types.VoidType(), + "store atomic", [val, ptr]) + self.ordering = ordering + self.align = align + + def descr(self, buf): + val, ptr = self.operands + buf.append("store atomic {0} {1}, {2} {3} {4}, align {5}{6}\n".format( + val.type, + val.get_reference(), + ptr.type, + ptr.get_reference(), + self.ordering, + self.align, + self._stringify_metadata(leading_comma=True), + )) + + +class AllocaInstr(Instruction): + def __init__(self, parent, typ, count, name): + operands = [count] if count else () + super(AllocaInstr, self).__init__(parent, typ.as_pointer(), "alloca", + operands, name) + self.allocated_type = typ + self.align = None + + def descr(self, buf): + buf.append("{0} {1}".format(self.opname, self.allocated_type)) + if self.operands: + op, = self.operands + buf.append(", {0} {1}".format(op.type, op.get_reference())) + if self.align is not None: + buf.append(", align {0}".format(self.align)) + if self.metadata: + buf.append(self._stringify_metadata(leading_comma=True)) + + +class GEPInstr(Instruction): + def __init__(self, parent, ptr, indices, inbounds, name, + source_etype=None): + if source_etype is not None: + typ = ptr.type + self.source_etype = source_etype + # For compatibility with typed pointers. Eventually this should + # probably be removed (when typed pointers are fully removed). + elif not ptr.type.is_opaque: + typ = ptr.type + lasttyp = None + lastaddrspace = 0 + for i in indices: + lasttyp, typ = typ, typ.gep(i) + # inherit the addrspace from the last seen pointer + if isinstance(lasttyp, types.PointerType): + lastaddrspace = lasttyp.addrspace + + if (not isinstance(typ, types.PointerType) and + isinstance(lasttyp, types.PointerType)): + typ = lasttyp + else: + typ = typ.as_pointer(lastaddrspace) + self.source_etype = ptr.type.pointee + else: + raise ValueError("GEP lacks type.") + super(GEPInstr, self).__init__(parent, typ, "getelementptr", + [ptr] + list(indices), name=name) + self.pointer = ptr + self.indices = indices + self.inbounds = inbounds + + def descr(self, buf): + indices = ['{0} {1}'.format(i.type, i.get_reference()) + for i in self.indices] + op = "getelementptr inbounds" if self.inbounds else "getelementptr" + buf.append("{0} {1}, {2} {3}, {4} {5}\n".format( + op, + self.source_etype, + self.pointer.type, + self.pointer.get_reference(), + ', '.join(indices), + self._stringify_metadata(leading_comma=True), + )) + + +class PhiInstr(Instruction): + def __init__(self, parent, typ, name, flags=()): + super(PhiInstr, self).__init__(parent, typ, "phi", (), name=name, + flags=flags) + self.incomings = [] + + def descr(self, buf): + incs = ', '.join('[{0}, {1}]'.format(v.get_reference(), + b.get_reference()) + for v, b in self.incomings) + buf.append("phi {0} {1} {2} {3}\n".format( + ' '.join(self.flags), + self.type, + incs, + self._stringify_metadata(leading_comma=True), + )) + + def add_incoming(self, value, block): + assert isinstance(block, Block) + self.incomings.append((value, block)) + + def replace_usage(self, old, new): + self.incomings = [((new if val is old else val), blk) + for (val, blk) in self.incomings] + + +class ExtractElement(Instruction): + def __init__(self, parent, vector, index, name=''): + if not isinstance(vector.type, types.VectorType): + raise TypeError("vector needs to be of VectorType.") + if not isinstance(index.type, types.IntType): + raise TypeError("index needs to be of IntType.") + typ = vector.type.element + super(ExtractElement, self).__init__(parent, typ, "extractelement", + [vector, index], name=name) + + def descr(self, buf): + operands = ", ".join("{0} {1}".format( + op.type, op.get_reference()) for op in self.operands) + buf.append("{opname} {operands}\n".format( + opname=self.opname, operands=operands)) + + +class InsertElement(Instruction): + def __init__(self, parent, vector, value, index, name=''): + if not isinstance(vector.type, types.VectorType): + raise TypeError("vector needs to be of VectorType.") + if not value.type == vector.type.element: + raise TypeError( + "value needs to be of type {} not {}.".format( + vector.type.element, value.type)) + if not isinstance(index.type, types.IntType): + raise TypeError("index needs to be of IntType.") + typ = vector.type + super(InsertElement, self).__init__(parent, typ, "insertelement", + [vector, value, index], name=name) + + def descr(self, buf): + operands = ", ".join("{0} {1}".format( + op.type, op.get_reference()) for op in self.operands) + buf.append("{opname} {operands}\n".format( + opname=self.opname, operands=operands)) + + +class ShuffleVector(Instruction): + def __init__(self, parent, vector1, vector2, mask, name=''): + if not isinstance(vector1.type, types.VectorType): + raise TypeError("vector1 needs to be of VectorType.") + if vector2 != Undefined: + if vector2.type != vector1.type: + raise TypeError("vector2 needs to be " + + "Undefined or of the same type as vector1.") + if (not isinstance(mask, Constant) or + not isinstance(mask.type, types.VectorType) or + not (isinstance(mask.type.element, types.IntType) and + mask.type.element.width == 32)): + raise TypeError("mask needs to be a constant i32 vector.") + typ = types.VectorType(vector1.type.element, mask.type.count) + index_range = range(vector1.type.count + if vector2 == Undefined + else 2 * vector1.type.count) + if not all(ii.constant in index_range for ii in mask.constant): + raise IndexError( + "mask values need to be in {0}".format(index_range), + ) + super(ShuffleVector, self).__init__(parent, typ, "shufflevector", + [vector1, vector2, mask], name=name) + + def descr(self, buf): + buf.append("shufflevector {0} {1}\n".format( + ", ".join("{0} {1}".format(op.type, op.get_reference()) + for op in self.operands), + self._stringify_metadata(leading_comma=True), + )) + + +class ExtractValue(Instruction): + def __init__(self, parent, agg, indices, name=''): + typ = agg.type + try: + for i in indices: + typ = typ.elements[i] + except (AttributeError, IndexError): + raise TypeError("Can't index at %r in %s" + % (list(indices), agg.type)) + + super(ExtractValue, self).__init__(parent, typ, "extractvalue", + [agg], name=name) + + self.aggregate = agg + self.indices = indices + + def descr(self, buf): + indices = [str(i) for i in self.indices] + + buf.append("extractvalue {0} {1}, {2} {3}\n".format( + self.aggregate.type, + self.aggregate.get_reference(), + ', '.join(indices), + self._stringify_metadata(leading_comma=True), + )) + + +class InsertValue(Instruction): + def __init__(self, parent, agg, elem, indices, name=''): + typ = agg.type + try: + for i in indices: + typ = typ.elements[i] + except (AttributeError, IndexError): + raise TypeError("Can't index at %r in %s" + % (list(indices), agg.type)) + if elem.type != typ: + raise TypeError("Can only insert %s at %r in %s: got %s" + % (typ, list(indices), agg.type, elem.type)) + super(InsertValue, self).__init__(parent, agg.type, "insertvalue", + [agg, elem], name=name) + + self.aggregate = agg + self.value = elem + self.indices = indices + + def descr(self, buf): + indices = [str(i) for i in self.indices] + + buf.append("insertvalue {0} {1}, {2} {3}, {4} {5}\n".format( + self.aggregate.type, self.aggregate.get_reference(), + self.value.type, self.value.get_reference(), + ', '.join(indices), + self._stringify_metadata(leading_comma=True), + )) + + +class Unreachable(Instruction): + def __init__(self, parent): + super(Unreachable, self).__init__(parent, types.VoidType(), + "unreachable", (), name='') + + def descr(self, buf): + buf += (self.opname, "\n") + + +class InlineAsm(object): + def __init__(self, ftype, asm, constraint, side_effect=False): + self.type = ftype.return_type + self.function_type = ftype + self.asm = asm + self.constraint = constraint + self.side_effect = side_effect + + def descr(self, buf): + sideeffect = 'sideeffect' if self.side_effect else '' + fmt = 'asm {sideeffect} "{asm}", "{constraint}"\n' + buf.append(fmt.format(sideeffect=sideeffect, asm=self.asm, + constraint=self.constraint)) + + def get_reference(self): + buf = [] + self.descr(buf) + return "".join(buf) + + def __str__(self): + return "{0} {1}".format(self.type, self.get_reference()) + + +class AtomicRMW(Instruction): + def __init__(self, parent, op, ptr, val, ordering, name): + super(AtomicRMW, self).__init__(parent, val.type, "atomicrmw", + (ptr, val), name=name) + self.operation = op + self.ordering = ordering + + def descr(self, buf): + ptr, val = self.operands + fmt = ("atomicrmw {op} {ptrty} {ptr}, {valty} {val} {ordering} " + "{metadata}\n") + buf.append(fmt.format(op=self.operation, + ptrty=ptr.type, + ptr=ptr.get_reference(), + valty=val.type, + val=val.get_reference(), + ordering=self.ordering, + metadata=self._stringify_metadata( + leading_comma=True), + )) + + +class CmpXchg(Instruction): + """This instruction has changed since llvm3.5. It is not compatible with + older llvm versions. + """ + + def __init__(self, parent, ptr, cmp, val, ordering, failordering, name): + outtype = types.LiteralStructType([val.type, types.IntType(1)]) + super(CmpXchg, self).__init__(parent, outtype, "cmpxchg", + (ptr, cmp, val), name=name) + self.ordering = ordering + self.failordering = failordering + + def descr(self, buf): + ptr, cmpval, val = self.operands + fmt = "cmpxchg {ptrty} {ptr}, {ty} {cmp}, {ty} {val} {ordering} " \ + "{failordering} {metadata}\n" + buf.append(fmt.format(ptrty=ptr.type, + ptr=ptr.get_reference(), + ty=cmpval.type, + cmp=cmpval.get_reference(), + val=val.get_reference(), + ordering=self.ordering, + failordering=self.failordering, + metadata=self._stringify_metadata( + leading_comma=True), + )) + + +class _LandingPadClause(object): + def __init__(self, value): + self.value = value + + def __str__(self): + return "{kind} {type} {value}".format( + kind=self.kind, + type=self.value.type, + value=self.value.get_reference()) + + +class CatchClause(_LandingPadClause): + kind = 'catch' + + +class FilterClause(_LandingPadClause): + kind = 'filter' + + def __init__(self, value): + assert isinstance(value, Constant) + assert isinstance(value.type, types.ArrayType) + super(FilterClause, self).__init__(value) + + +class LandingPadInstr(Instruction): + def __init__(self, parent, typ, name='', cleanup=False): + super(LandingPadInstr, self).__init__(parent, typ, "landingpad", [], + name=name) + self.cleanup = cleanup + self.clauses = [] + + def add_clause(self, clause): + assert isinstance(clause, _LandingPadClause) + self.clauses.append(clause) + + def descr(self, buf): + fmt = "landingpad {type}{cleanup}{clauses}\n" + buf.append(fmt.format(type=self.type, + cleanup=' cleanup' if self.cleanup else '', + clauses=''.join(["\n {0}".format(clause) + for clause in self.clauses]), + )) + + +class Fence(Instruction): + """ + The `fence` instruction. + + As of LLVM 5.0.1: + + fence [syncscope("")] ; yields void + """ + + VALID_FENCE_ORDERINGS = {"acquire", "release", "acq_rel", "seq_cst"} + + def __init__(self, parent, ordering, targetscope=None, name=''): + super(Fence, self).__init__(parent, types.VoidType(), "fence", (), + name=name) + if ordering not in self.VALID_FENCE_ORDERINGS: + msg = "Invalid fence ordering \"{0}\"! Should be one of {1}." + raise ValueError(msg .format(ordering, + ", ".join(self.VALID_FENCE_ORDERINGS))) + self.ordering = ordering + self.targetscope = targetscope + + def descr(self, buf): + if self.targetscope is None: + syncscope = "" + else: + syncscope = 'syncscope("{0}") '.format(self.targetscope) + + fmt = "fence {syncscope}{ordering}\n" + buf.append(fmt.format(syncscope=syncscope, + ordering=self.ordering, + )) + + +class Comment(Instruction): + """ + A line comment. + """ + + def __init__(self, parent, text): + super(Comment, self).__init__(parent, types.VoidType(), ";", (), + name='') + assert "\n" not in text, "Comment cannot contain new line" + self.text = text + + def descr(self, buf): + buf.append(f"; {self.text}") diff --git a/venv/lib/python3.10/site-packages/llvmlite/ir/module.py b/venv/lib/python3.10/site-packages/llvmlite/ir/module.py new file mode 100644 index 0000000000000000000000000000000000000000..464f91ec34344e02bd9fb7e5f6dec46803407f00 --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/ir/module.py @@ -0,0 +1,246 @@ +import collections + +from llvmlite.ir import context, values, types, _utils + + +class Module(object): + def __init__(self, name='', context=context.global_context): + self.context = context + self.name = name # name is for debugging/informational + self.data_layout = "" + self.scope = _utils.NameScope() + self.triple = 'unknown-unknown-unknown' + self.globals = collections.OrderedDict() + # Innamed metadata nodes. + self.metadata = [] + # Named metadata nodes + self.namedmetadata = {} + # Cache for metadata node deduplication + self._metadatacache = {} + + def _fix_metadata_operands(self, operands): + fixed_ops = [] + for op in operands: + if op is None: + # A literal None creates a null metadata value + op = types.MetaDataType()(None) + elif isinstance(op, str): + # A literal string creates a metadata string value + op = values.MetaDataString(self, op) + elif isinstance(op, (list, tuple)): + # A sequence creates a metadata node reference + op = self.add_metadata(op) + fixed_ops.append(op) + return fixed_ops + + def _fix_di_operands(self, operands): + fixed_ops = [] + for name, op in operands: + if isinstance(op, (list, tuple)): + # A sequence creates a metadata node reference + op = self.add_metadata(op) + fixed_ops.append((name, op)) + return fixed_ops + + def add_metadata(self, operands): + """ + Add an unnamed metadata to the module with the given *operands* + (a sequence of values) or return a previous equivalent metadata. + A MDValue instance is returned, it can then be associated to + e.g. an instruction. + """ + if not isinstance(operands, (list, tuple)): + raise TypeError("expected a list or tuple of metadata values, " + "got %r" % (operands,)) + operands = self._fix_metadata_operands(operands) + key = tuple(operands) + if key not in self._metadatacache: + n = len(self.metadata) + md = values.MDValue(self, operands, name=str(n)) + self._metadatacache[key] = md + else: + md = self._metadatacache[key] + return md + + def add_debug_info(self, kind, operands, is_distinct=False): + """ + Add debug information metadata to the module with the given + *operands* (a dict of values with string keys) or return + a previous equivalent metadata. *kind* is a string of the + debug information kind (e.g. "DICompileUnit"). + + A DIValue instance is returned, it can then be associated to e.g. + an instruction. + """ + operands = tuple(sorted(self._fix_di_operands(operands.items()))) + key = (kind, operands, is_distinct) + if key not in self._metadatacache: + n = len(self.metadata) + di = values.DIValue(self, is_distinct, kind, operands, name=str(n)) + self._metadatacache[key] = di + else: + di = self._metadatacache[key] + return di + + def add_named_metadata(self, name, element=None): + """ + Add a named metadata node to the module, if it doesn't exist, + or return the existing node. + If *element* is given, it will append a new element to + the named metadata node. If *element* is a sequence of values + (rather than a metadata value), a new unnamed node will first be + created. + + Example:: + module.add_named_metadata("llvm.ident", ["llvmlite/1.0"]) + """ + if name in self.namedmetadata: + nmd = self.namedmetadata[name] + else: + nmd = self.namedmetadata[name] = values.NamedMetaData(self) + if element is not None: + if not isinstance(element, values.Value): + element = self.add_metadata(element) + if not isinstance(element.type, types.MetaDataType): + raise TypeError("wrong type for metadata element: got %r" + % (element,)) + nmd.add(element) + return nmd + + def get_named_metadata(self, name): + """ + Return the metadata node with the given *name*. KeyError is raised + if no such node exists (contrast with add_named_metadata()). + """ + return self.namedmetadata[name] + + @property + def functions(self): + """ + A list of functions declared or defined in this module. + """ + return [v for v in self.globals.values() + if isinstance(v, values.Function)] + + @property + def global_values(self): + """ + An iterable of global values in this module. + """ + return self.globals.values() + + def get_global(self, name): + """ + Get a global value by name. + """ + return self.globals[name] + + def add_global(self, globalvalue): + """ + Add a new global value. + """ + assert globalvalue.name not in self.globals + self.globals[globalvalue.name] = globalvalue + + def get_unique_name(self, name=''): + """ + Get a unique global name with the following *name* hint. + """ + return self.scope.deduplicate(name) + + def declare_intrinsic(self, intrinsic, tys=(), fnty=None): + def _error(): + raise NotImplementedError("unknown intrinsic %r with %d types" + % (intrinsic, len(tys))) + + if intrinsic in {'llvm.cttz', 'llvm.ctlz', 'llvm.fma'}: + suffixes = [tys[0].intrinsic_name] + else: + suffixes = [t.intrinsic_name for t in tys] + name = '.'.join([intrinsic] + suffixes) + if name in self.globals: + return self.globals[name] + + if fnty is not None: + # General case: function type is given + pass + # Compute function type if omitted for common cases + elif len(tys) == 0 and intrinsic == 'llvm.assume': + fnty = types.FunctionType(types.VoidType(), [types.IntType(1)]) + elif len(tys) == 1: + if intrinsic == 'llvm.powi': + fnty = types.FunctionType(tys[0], [tys[0], types.IntType(32)]) + elif intrinsic == 'llvm.pow': + fnty = types.FunctionType(tys[0], tys * 2) + elif intrinsic == 'llvm.convert.from.fp16': + fnty = types.FunctionType(tys[0], [types.IntType(16)]) + elif intrinsic == 'llvm.convert.to.fp16': + fnty = types.FunctionType(types.IntType(16), tys) + else: + fnty = types.FunctionType(tys[0], tys) + elif len(tys) == 2: + if intrinsic == 'llvm.memset': + tys = [tys[0], types.IntType(8), tys[1], + types.IntType(1)] + fnty = types.FunctionType(types.VoidType(), tys) + elif intrinsic in {'llvm.cttz', 'llvm.ctlz'}: + tys = [tys[0], types.IntType(1)] + fnty = types.FunctionType(tys[0], tys) + else: + _error() + elif len(tys) == 3: + if intrinsic in ('llvm.memcpy', 'llvm.memmove'): + tys = tys + [types.IntType(1)] + fnty = types.FunctionType(types.VoidType(), tys) + elif intrinsic == 'llvm.fma': + tys = [tys[0]] * 3 + fnty = types.FunctionType(tys[0], tys) + else: + _error() + else: + _error() + return values.Function(self, fnty, name=name) + + def get_identified_types(self): + return self.context.identified_types + + def _get_body_lines(self): + # Type declarations + lines = [it.get_declaration() + for it in self.get_identified_types().values()] + # Global values (including function definitions) + lines += [str(v) for v in self.globals.values()] + return lines + + def _get_metadata_lines(self): + mdbuf = [] + for k, v in self.namedmetadata.items(): + mdbuf.append("!{name} = !{{ {operands} }}".format( + name=k, operands=', '.join(i.get_reference() + for i in v.operands))) + for md in self.metadata: + mdbuf.append(str(md)) + return mdbuf + + def _stringify_body(self): + # For testing + return "\n".join(self._get_body_lines()) + + def _stringify_metadata(self): + # For testing + return "\n".join(self._get_metadata_lines()) + + def __repr__(self): + lines = [] + # Header + lines += [ + '; ModuleID = "%s"' % (self.name,), + 'target triple = "%s"' % (self.triple,), + 'target datalayout = "%s"' % (self.data_layout,), + ''] + # Body + lines += self._get_body_lines() + # Metadata + lines += self._get_metadata_lines() + + return "\n".join(lines) diff --git a/venv/lib/python3.10/site-packages/llvmlite/ir/transforms.py b/venv/lib/python3.10/site-packages/llvmlite/ir/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..a69113d36e93b6b9e42a2a15119697375cff62e5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/ir/transforms.py @@ -0,0 +1,64 @@ +from llvmlite.ir import CallInstr + + +class Visitor(object): + def visit(self, module): + self._module = module + for func in module.functions: + self.visit_Function(func) + + def visit_Function(self, func): + self._function = func + for bb in func.blocks: + self.visit_BasicBlock(bb) + + def visit_BasicBlock(self, bb): + self._basic_block = bb + for instr in bb.instructions: + self.visit_Instruction(instr) + + def visit_Instruction(self, instr): + raise NotImplementedError + + @property + def module(self): + return self._module + + @property + def function(self): + return self._function + + @property + def basic_block(self): + return self._basic_block + + +class CallVisitor(Visitor): + def visit_Instruction(self, instr): + if isinstance(instr, CallInstr): + self.visit_Call(instr) + + def visit_Call(self, instr): + raise NotImplementedError + + +class ReplaceCalls(CallVisitor): + def __init__(self, orig, repl): + super(ReplaceCalls, self).__init__() + self.orig = orig + self.repl = repl + self.calls = [] + + def visit_Call(self, instr): + if instr.callee == self.orig: + instr.replace_callee(self.repl) + self.calls.append(instr) + + +def replace_all_calls(mod, orig, repl): + """Replace all calls to `orig` to `repl` in module `mod`. + Returns the references to the returned calls + """ + rc = ReplaceCalls(orig, repl) + rc.visit(mod) + return rc.calls diff --git a/venv/lib/python3.10/site-packages/llvmlite/ir/types.py b/venv/lib/python3.10/site-packages/llvmlite/ir/types.py new file mode 100644 index 0000000000000000000000000000000000000000..eac3ada7a9dfea2f79a90a6a7ed43418edd8e95e --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/ir/types.py @@ -0,0 +1,734 @@ +""" +Classes that are LLVM types +""" + +import struct + +from llvmlite.ir._utils import _StrCaching + +# FIXME: Remove me once typed pointers are no longer supported. +from llvmlite import opaque_pointers_enabled + + +def _wrapname(x): + return '"{0}"'.format(x.replace('\\', '\\5c').replace('"', '\\22')) + + +class Type(_StrCaching): + """ + The base class for all LLVM types. + """ + is_pointer = False + null = 'zeroinitializer' + + def __repr__(self): + return "<%s %s>" % (type(self), str(self)) + + def _to_string(self): + raise NotImplementedError + + def as_pointer(self, addrspace=0): + return PointerType(self, addrspace) + + def __ne__(self, other): + return not (self == other) + + def _get_ll_global_value_type(self, target_data, context=None): + """ + Convert this type object to an LLVM type. + """ + from llvmlite.ir import Module, GlobalVariable + from llvmlite.binding import parse_assembly + + if context is None: + m = Module() + else: + m = Module(context=context) + foo = GlobalVariable(m, self, name="foo") + with parse_assembly(str(m)) as llmod: + return llmod.get_global_variable(foo.name).global_value_type + + def get_abi_size(self, target_data, context=None): + """ + Get the ABI size of this type according to data layout *target_data*. + """ + llty = self._get_ll_global_value_type(target_data, context) + return target_data.get_abi_size(llty) + + def get_element_offset(self, target_data, ndx, context=None): + llty = self._get_ll_global_value_type(target_data, context) + return target_data.get_element_offset(llty, ndx) + + def get_abi_alignment(self, target_data, context=None): + """ + Get the minimum ABI alignment of this type according to data layout + *target_data*. + """ + llty = self._get_ll_global_value_type(target_data, context) + return target_data.get_abi_alignment(llty) + + def format_constant(self, value): + """ + Format constant *value* of this type. This method may be overriden + by subclasses. + """ + return str(value) + + def wrap_constant_value(self, value): + """ + Wrap constant *value* if necessary. This method may be overriden + by subclasses (especially aggregate types). + """ + return value + + def __call__(self, value): + """ + Create a LLVM constant of this type with the given Python value. + """ + from llvmlite.ir import Constant + return Constant(self, value) + + +class MetaDataType(Type): + + def _to_string(self): + return "metadata" + + def as_pointer(self): + raise TypeError + + def __eq__(self, other): + return isinstance(other, MetaDataType) + + def __hash__(self): + return hash(MetaDataType) + + +class LabelType(Type): + """ + The label type is the type of e.g. basic blocks. + """ + + def _to_string(self): + return "label" + + +class PointerType(Type): + """ + The type of all pointer values. + By default (without specialisation) represents an opaque pointer. + """ + is_opaque = True + is_pointer = True + null = 'null' + + # Factory to create typed or opaque pointers based on `pointee'. + def __new__(cls, pointee=None, addrspace=0): + if cls is PointerType and pointee is not None: + return super().__new__(_TypedPointerType) + return super(PointerType, cls).__new__(cls) + + def __init__(self, addrspace=0): + self.addrspace = addrspace + + def _to_string(self): + if self.addrspace != 0: + return "ptr addrspace({0})".format(self.addrspace) + else: + return "ptr" + + def __hash__(self): + return hash(PointerType) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + if not opaque_pointers_enabled: + return _TypedPointerType.from_llvm(typeref, ir_ctx) + return cls() + + +class _TypedPointerType(PointerType): + """ + The type of typed pointer values. To be removed eventually. + """ + + def __init__(self, pointee, addrspace=0): + super(_TypedPointerType, self).__init__(addrspace) + assert pointee is not None + assert not isinstance(pointee, VoidType) + self.pointee = pointee + self.is_opaque = False + + def _to_string(self): + if not opaque_pointers_enabled: + return "{0}*".format(self.pointee) if self.addrspace == 0 else \ + "{0} addrspace({1})*".format(self.pointee, self.addrspace) + return super(_TypedPointerType, self)._to_string() + + # This implements ``isOpaqueOrPointeeTypeEquals''. + def __eq__(self, other): + if isinstance(other, _TypedPointerType): + return (self.pointee, self.addrspace) == (other.pointee, + other.addrspace) + return isinstance(other, PointerType) + + def __hash__(self): + return hash(_TypedPointerType) + + def gep(self, i): + """ + Resolve the type of the i-th element (for getelementptr lookups). + """ + if not isinstance(i.type, IntType): + raise TypeError(i.type) + return self.pointee + + @property + def intrinsic_name(self): + return 'p%d%s' % (self.addrspace, self.pointee.intrinsic_name) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + assert not opaque_pointers_enabled + # opaque pointer will change this + [pointee] = typeref.elements + # addrspace is not handled + return cls(pointee.as_ir(ir_ctx=ir_ctx)) + + +class VoidType(Type): + """ + The type for empty values (e.g. a function returning no value). + """ + + def _to_string(self): + return 'void' + + def __eq__(self, other): + return isinstance(other, VoidType) + + def __hash__(self): + return hash(VoidType) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + return cls() + + +class FunctionType(Type): + """ + The type for functions. + """ + + def __init__(self, return_type, args, var_arg=False): + self.return_type = return_type + self.args = tuple(args) + self.var_arg = var_arg + + def _to_string(self): + if self.args: + strargs = ', '.join([str(a) for a in self.args]) + if self.var_arg: + return '{0} ({1}, ...)'.format(self.return_type, strargs) + else: + return '{0} ({1})'.format(self.return_type, strargs) + elif self.var_arg: + return '{0} (...)'.format(self.return_type) + else: + return '{0} ()'.format(self.return_type) + + def __eq__(self, other): + if isinstance(other, FunctionType): + return (self.return_type == other.return_type and + self.args == other.args and self.var_arg == other.var_arg) + else: + return False + + def __hash__(self): + return hash(FunctionType) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + params = tuple(x.as_ir(ir_ctx=ir_ctx) + for x in typeref.get_function_parameters()) + ret = typeref.get_function_return().as_ir(ir_ctx=ir_ctx) + is_vararg = typeref.is_function_vararg + return cls(ret, params, is_vararg) + + +class IntType(Type): + """ + The type for integers. + """ + null = '0' + _instance_cache = {} + width: int + + def __new__(cls, bits): + # Cache all common integer types + if 0 <= bits <= 128: + try: + return cls._instance_cache[bits] + except KeyError: + inst = cls._instance_cache[bits] = cls.__new(bits) + return inst + return cls.__new(bits) + + @classmethod + def __new(cls, bits): + assert isinstance(bits, int) and bits >= 0 + self = super(IntType, cls).__new__(cls) + self.width = bits + return self + + def __getnewargs__(self): + return self.width, + + def __copy__(self): + return self + + def _to_string(self): + return 'i%u' % (self.width,) + + def __eq__(self, other): + if isinstance(other, IntType): + return self.width == other.width + else: + return False + + def __hash__(self): + return hash(IntType) + + def format_constant(self, val): + if isinstance(val, bool): + return str(val).lower() + else: + return str(val) + + def wrap_constant_value(self, val): + if val is None: + return 0 + return val + + @property + def intrinsic_name(self): + return str(self) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + return IntType(typeref.type_width) + + +def _as_float(value): + """ + Truncate to single-precision float. + """ + return struct.unpack('f', struct.pack('f', value))[0] + + +def _as_half(value): + """ + Truncate to half-precision float. + """ + try: + return struct.unpack('e', struct.pack('e', value))[0] + except struct.error: + # 'e' only added in Python 3.6+ + return _as_float(value) + + +def _format_float_as_hex(value, packfmt, unpackfmt, numdigits): + raw = struct.pack(packfmt, float(value)) + intrep = struct.unpack(unpackfmt, raw)[0] + out = '{{0:#{0}x}}'.format(numdigits).format(intrep) + return out + + +def _format_double(value): + """ + Format *value* as a hexadecimal string of its IEEE double precision + representation. + """ + return _format_float_as_hex(value, 'd', 'Q', 16) + + +class _BaseFloatType(Type): + + def __new__(cls): + return cls._instance_cache + + def __eq__(self, other): + return isinstance(other, type(self)) + + def __hash__(self): + return hash(type(self)) + + @classmethod + def _create_instance(cls): + cls._instance_cache = super(_BaseFloatType, cls).__new__(cls) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + return cls() + + +class HalfType(_BaseFloatType): + """ + The type for single-precision floats. + """ + null = '0.0' + intrinsic_name = 'f16' + + def __str__(self): + return 'half' + + def format_constant(self, value): + return _format_double(_as_half(value)) + + +class FloatType(_BaseFloatType): + """ + The type for single-precision floats. + """ + null = '0.0' + intrinsic_name = 'f32' + + def __str__(self): + return 'float' + + def format_constant(self, value): + return _format_double(_as_float(value)) + + +class DoubleType(_BaseFloatType): + """ + The type for double-precision floats. + """ + null = '0.0' + intrinsic_name = 'f64' + + def __str__(self): + return 'double' + + def format_constant(self, value): + return _format_double(value) + + +for _cls in (HalfType, FloatType, DoubleType): + _cls._create_instance() + + +class _Repeat(object): + def __init__(self, value, size): + self.value = value + self.size = size + + def __len__(self): + return self.size + + def __getitem__(self, item): + if 0 <= item < self.size: + return self.value + else: + raise IndexError(item) + + +class VectorType(Type): + """ + The type for vectors of primitive data items (e.g. ""). + """ + + def __init__(self, element, count): + self.element = element + self.count = count + + @property + def elements(self): + return _Repeat(self.element, self.count) + + def __len__(self): + return self.count + + def _to_string(self): + return "<%d x %s>" % (self.count, self.element) + + def __eq__(self, other): + if isinstance(other, VectorType): + return self.element == other.element and self.count == other.count + + def __hash__(self): + # TODO: why does this not take self.element/self.count into account? + return hash(VectorType) + + def __copy__(self): + return self + + def format_constant(self, value): + itemstring = ", " .join(["{0} {1}".format(x.type, x.get_reference()) + for x in value]) + return "<{0}>".format(itemstring) + + def wrap_constant_value(self, values): + from . import Value, Constant + if not isinstance(values, (list, tuple)): + if isinstance(values, Constant): + if values.type != self.element: + raise TypeError("expected {} for {}".format( + self.element, values.type)) + return (values, ) * self.count + return (Constant(self.element, values), ) * self.count + if len(values) != len(self): + raise ValueError("wrong constant size for %s: got %d elements" + % (self, len(values))) + return [Constant(ty, val) if not isinstance(val, Value) else val + for ty, val in zip(self.elements, values)] + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + [elemtyperef] = typeref.elements + elemty = elemtyperef.as_ir(ir_ctx=ir_ctx) + count = typeref.element_count + return cls(elemty, count) + + +class Aggregate(Type): + """ + Base class for aggregate types. + See http://llvm.org/docs/LangRef.html#t-aggregate + """ + + def wrap_constant_value(self, values): + from . import Value, Constant + + if not isinstance(values, (list, tuple)): + return values + if len(values) != len(self): + raise ValueError("wrong constant size for %s: got %d elements" + % (self, len(values))) + return [Constant(ty, val) if not isinstance(val, Value) else val + for ty, val in zip(self.elements, values)] + + +class ArrayType(Aggregate): + """ + The type for fixed-size homogenous arrays (e.g. "[f32 x 3]"). + """ + + def __init__(self, element, count): + self.element = element + self.count = count + + @property + def elements(self): + return _Repeat(self.element, self.count) + + def __len__(self): + return self.count + + def _to_string(self): + return "[%d x %s]" % (self.count, self.element) + + def __eq__(self, other): + if isinstance(other, ArrayType): + return self.element == other.element and self.count == other.count + + def __hash__(self): + return hash(ArrayType) + + def gep(self, i): + """ + Resolve the type of the i-th element (for getelementptr lookups). + """ + if not isinstance(i.type, IntType): + raise TypeError(i.type) + return self.element + + def format_constant(self, value): + itemstring = ", " .join(["{0} {1}".format(x.type, x.get_reference()) + for x in value]) + return "[{0}]".format(itemstring) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + [elemtyperef] = typeref.elements + elemty = elemtyperef.as_ir(ir_ctx=ir_ctx) + count = typeref.element_count + return cls(elemty, count) + + +class BaseStructType(Aggregate): + """ + The base type for heterogenous struct types. + """ + _packed = False + + @property + def packed(self): + """ + A boolean attribute that indicates whether the structure uses + packed layout. + """ + return self._packed + + @packed.setter + def packed(self, val): + self._packed = bool(val) + + def __len__(self): + assert self.elements is not None + return len(self.elements) + + def __iter__(self): + assert self.elements is not None + return iter(self.elements) + + @property + def is_opaque(self): + return self.elements is None + + def structure_repr(self): + """ + Return the LLVM IR for the structure representation + """ + ret = '{%s}' % ', '.join([str(x) for x in self.elements]) + return self._wrap_packed(ret) + + def format_constant(self, value): + itemstring = ", " .join(["{0} {1}".format(x.type, x.get_reference()) + for x in value]) + ret = "{{{0}}}".format(itemstring) + return self._wrap_packed(ret) + + def gep(self, i): + """ + Resolve the type of the i-th element (for getelementptr lookups). + + *i* needs to be a LLVM constant, so that the type can be determined + at compile-time. + """ + if not isinstance(i.type, IntType): + raise TypeError(i.type) + return self.elements[i.constant] + + def _wrap_packed(self, textrepr): + """ + Internal helper to wrap textual repr of struct type into packed struct + """ + if self.packed: + return '<{}>'.format(textrepr) + else: + return textrepr + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + if typeref.is_literal_struct: + elems = [el.as_ir(ir_ctx=ir_ctx) for el in typeref.elements] + return cls(elems, typeref.is_packed_struct) + else: + return ir_ctx.get_identified_type(typeref.name) + + +class LiteralStructType(BaseStructType): + """ + The type of "literal" structs, i.e. structs with a literally-defined + type (by contrast with IdentifiedStructType). + """ + + null = 'zeroinitializer' + + def __init__(self, elems, packed=False): + """ + *elems* is a sequence of types to be used as members. + *packed* controls the use of packed layout. + """ + self.elements = tuple(elems) + self.packed = packed + + def _to_string(self): + return self.structure_repr() + + def __eq__(self, other): + if isinstance(other, LiteralStructType): + return (self.elements == other.elements + and self.packed == other.packed) + + def __hash__(self): + return hash(LiteralStructType) + + +class IdentifiedStructType(BaseStructType): + """ + A type which is a named alias for another struct type, akin to a typedef. + While literal struct types can be structurally equal (see + LiteralStructType), identified struct types are compared by name. + + Do not use this directly. + """ + null = 'zeroinitializer' + + def __init__(self, context, name, packed=False): + """ + *context* is a llvmlite.ir.Context. + *name* is the identifier for the new struct type. + *packed* controls the use of packed layout. + """ + assert name + self.context = context + self.name = name + self.elements = None + self.packed = packed + + def _to_string(self): + return "%{name}".format(name=_wrapname(self.name)) + + def get_declaration(self): + """ + Returns the string for the declaration of the type + """ + if self.is_opaque: + out = "{strrep} = type opaque".format(strrep=str(self)) + else: + out = "{strrep} = type {struct}".format( + strrep=str(self), struct=self.structure_repr()) + return out + + def __eq__(self, other): + if isinstance(other, IdentifiedStructType): + return (self.name == other.name + and self.packed == other.packed) + + def __hash__(self): + return hash(IdentifiedStructType) + + def set_body(self, *elems): + if not self.is_opaque: + raise RuntimeError("{name} is already defined".format( + name=self.name)) + self.elements = tuple(elems) diff --git a/venv/lib/python3.10/site-packages/llvmlite/ir/values.py b/venv/lib/python3.10/site-packages/llvmlite/ir/values.py new file mode 100644 index 0000000000000000000000000000000000000000..7807eef6bc20708b6e770b670ac247bc6c8f7fa5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/ir/values.py @@ -0,0 +1,1217 @@ +""" +Classes that are LLVM values: Value, Constant... +Instructions are in the instructions module. +""" + +import functools +import string +import re +from types import MappingProxyType + +from llvmlite.ir import values, types, _utils +from llvmlite.ir._utils import (_StrCaching, _StringReferenceCaching, + _HasMetadata) + +_VALID_CHARS = (frozenset(map(ord, string.ascii_letters)) | + frozenset(map(ord, string.digits)) | + frozenset(map(ord, ' !#$%&\'()*+,-./:;<=>?@[]^_`{|}~'))) + +_SIMPLE_IDENTIFIER_RE = re.compile(r"[-a-zA-Z$._][-a-zA-Z$._0-9]*$") + +_CMP_MAP = { + '>': 'gt', + '<': 'lt', + '==': 'eq', + '!=': 'ne', + '>=': 'ge', + '<=': 'le', +} + + +def _escape_string(text, _map={}): + """ + Escape the given bytestring for safe use as a LLVM array constant. + Any unicode string input is first encoded with utf8 into bytes. + """ + if isinstance(text, str): + text = text.encode() + assert isinstance(text, (bytes, bytearray)) + + if not _map: + for ch in range(256): + if ch in _VALID_CHARS: + _map[ch] = chr(ch) + else: + _map[ch] = '\\%02x' % ch + + buf = [_map[ch] for ch in text] + return ''.join(buf) + + +def _binop(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(lhs, rhs): + if lhs.type != rhs.type: + raise ValueError("Operands must be the same type, got (%s, %s)" + % (lhs.type, rhs.type)) + + fmt = "{0} ({1} {2}, {3} {4})".format(opname, + lhs.type, lhs.get_reference(), + rhs.type, rhs.get_reference()) + return FormattedConstant(lhs.type, fmt) + + return wrapped + return wrap + + +def _castop(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, typ): + fn(self, typ) + if typ == self.type: + return self + + op = "{0} ({1} {2} to {3})".format(opname, self.type, + self.get_reference(), typ) + return FormattedConstant(typ, op) + + return wrapped + return wrap + + +class _ConstOpMixin(object): + """ + A mixin defining constant operations, for use in constant-like classes. + """ + + # + # Arithmetic APIs + # + + @_binop('shl') + def shl(self, other): + """ + Left integer shift: + lhs << rhs + """ + + @_binop('lshr') + def lshr(self, other): + """ + Logical (unsigned) right integer shift: + lhs >> rhs + """ + + @_binop('ashr') + def ashr(self, other): + """ + Arithmetic (signed) right integer shift: + lhs >> rhs + """ + + @_binop('add') + def add(self, other): + """ + Integer addition: + lhs + rhs + """ + + @_binop('fadd') + def fadd(self, other): + """ + Floating-point addition: + lhs + rhs + """ + + @_binop('sub') + def sub(self, other): + """ + Integer subtraction: + lhs - rhs + """ + + @_binop('fsub') + def fsub(self, other): + """ + Floating-point subtraction: + lhs - rhs + """ + + @_binop('mul') + def mul(self, other): + """ + Integer multiplication: + lhs * rhs + """ + + @_binop('fmul') + def fmul(self, other): + """ + Floating-point multiplication: + lhs * rhs + """ + + @_binop('udiv') + def udiv(self, other): + """ + Unsigned integer division: + lhs / rhs + """ + + @_binop('sdiv') + def sdiv(self, other): + """ + Signed integer division: + lhs / rhs + """ + + @_binop('fdiv') + def fdiv(self, other): + """ + Floating-point division: + lhs / rhs + """ + + @_binop('urem') + def urem(self, other): + """ + Unsigned integer remainder: + lhs % rhs + """ + + @_binop('srem') + def srem(self, other): + """ + Signed integer remainder: + lhs % rhs + """ + + @_binop('frem') + def frem(self, other): + """ + Floating-point remainder: + lhs % rhs + """ + + @_binop('or') + def or_(self, other): + """ + Bitwise integer OR: + lhs | rhs + """ + + @_binop('and') + def and_(self, other): + """ + Bitwise integer AND: + lhs & rhs + """ + + @_binop('xor') + def xor(self, other): + """ + Bitwise integer XOR: + lhs ^ rhs + """ + + def _cmp(self, prefix, sign, cmpop, other): + ins = prefix + 'cmp' + try: + op = _CMP_MAP[cmpop] + except KeyError: + raise ValueError("invalid comparison %r for %s" % (cmpop, ins)) + + if not (prefix == 'i' and cmpop in ('==', '!=')): + op = sign + op + + if self.type != other.type: + raise ValueError("Operands must be the same type, got (%s, %s)" + % (self.type, other.type)) + + fmt = "{0} {1} ({2} {3}, {4} {5})".format( + ins, op, + self.type, self.get_reference(), + other.type, other.get_reference()) + + return FormattedConstant(types.IntType(1), fmt) + + def icmp_signed(self, cmpop, other): + """ + Signed integer comparison: + lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=' + """ + return self._cmp('i', 's', cmpop, other) + + def icmp_unsigned(self, cmpop, other): + """ + Unsigned integer (or pointer) comparison: + lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=' + """ + return self._cmp('i', 'u', cmpop, other) + + def fcmp_ordered(self, cmpop, other): + """ + Floating-point ordered comparison: + lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' + """ + return self._cmp('f', 'o', cmpop, other) + + def fcmp_unordered(self, cmpop, other): + """ + Floating-point unordered comparison: + lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' + """ + return self._cmp('f', 'u', cmpop, other) + + # + # Unary APIs + # + + def not_(self): + """ + Bitwise integer complement: + ~value + """ + if isinstance(self.type, types.VectorType): + rhs = values.Constant(self.type, (-1,) * self.type.count) + else: + rhs = values.Constant(self.type, -1) + + return self.xor(rhs) + + def neg(self): + """ + Integer negative: + -value + """ + zero = values.Constant(self.type, 0) + return zero.sub(self) + + def fneg(self): + """ + Floating-point negative: + -value + """ + fmt = "fneg ({0} {1})".format(self.type, self.get_reference()) + return FormattedConstant(self.type, fmt) + + # + # Cast APIs + # + + @_castop('trunc') + def trunc(self, typ): + """ + Truncating integer downcast to a smaller type. + """ + + @_castop('zext') + def zext(self, typ): + """ + Zero-extending integer upcast to a larger type + """ + + @_castop('sext') + def sext(self, typ): + """ + Sign-extending integer upcast to a larger type. + """ + + @_castop('fptrunc') + def fptrunc(self, typ): + """ + Floating-point downcast to a less precise type. + """ + + @_castop('fpext') + def fpext(self, typ): + """ + Floating-point upcast to a more precise type. + """ + + @_castop('bitcast') + def bitcast(self, typ): + """ + Pointer cast to a different pointer type. + """ + + @_castop('fptoui') + def fptoui(self, typ): + """ + Convert floating-point to unsigned integer. + """ + + @_castop('uitofp') + def uitofp(self, typ): + """ + Convert unsigned integer to floating-point. + """ + + @_castop('fptosi') + def fptosi(self, typ): + """ + Convert floating-point to signed integer. + """ + + @_castop('sitofp') + def sitofp(self, typ): + """ + Convert signed integer to floating-point. + """ + + @_castop('ptrtoint') + def ptrtoint(self, typ): + """ + Cast pointer to integer. + """ + if not isinstance(self.type, types.PointerType): + msg = "can only call ptrtoint() on pointer type, not '%s'" + raise TypeError(msg % (self.type,)) + if not isinstance(typ, types.IntType): + raise TypeError("can only ptrtoint() to integer type, not '%s'" + % (typ,)) + + @_castop('inttoptr') + def inttoptr(self, typ): + """ + Cast integer to pointer. + """ + if not isinstance(self.type, types.IntType): + msg = "can only call inttoptr() on integer constants, not '%s'" + raise TypeError(msg % (self.type,)) + if not isinstance(typ, types.PointerType): + raise TypeError("can only inttoptr() to pointer type, not '%s'" + % (typ,)) + + def gep(self, indices): + """ + Call getelementptr on this pointer constant. + """ + if not isinstance(self.type, types.PointerType): + raise TypeError("can only call gep() on pointer constants, not '%s'" + % (self.type,)) + + outtype = self.type + for i in indices: + outtype = outtype.gep(i) + + strindices = ["{0} {1}".format(idx.type, idx.get_reference()) + for idx in indices] + + op = "getelementptr ({0}, {1} {2}, {3})".format( + self.type.pointee, self.type, + self.get_reference(), ', '.join(strindices)) + return FormattedConstant(outtype.as_pointer(self.addrspace), op) + + +class Value(object): + """ + The base class for all values. + """ + + def __repr__(self): + return "" % (self.__class__.__name__, self.type,) + + +class _Undefined(object): + """ + 'undef': a value for undefined values. + """ + def __new__(cls): + try: + return Undefined + except NameError: + return object.__new__(_Undefined) + + +Undefined = _Undefined() + + +class Constant(_StrCaching, _StringReferenceCaching, _ConstOpMixin, Value): + """ + A constant LLVM value. + """ + + def __init__(self, typ, constant): + assert isinstance(typ, types.Type) + assert not isinstance(typ, types.VoidType) + self.type = typ + constant = typ.wrap_constant_value(constant) + self.constant = constant + + def _to_string(self): + return '{0} {1}'.format(self.type, self.get_reference()) + + def _get_reference(self): + if self.constant is None: + val = self.type.null + + elif self.constant is Undefined: + val = "undef" + + elif isinstance(self.constant, bytearray): + val = 'c"{0}"'.format(_escape_string(self.constant)) + + else: + val = self.type.format_constant(self.constant) + + return val + + @classmethod + def literal_array(cls, elems): + """ + Construct a literal array constant made of the given members. + """ + tys = [el.type for el in elems] + if len(tys) == 0: + raise ValueError("need at least one element") + ty = tys[0] + for other in tys: + if ty != other: + raise TypeError("all elements must have the same type") + return cls(types.ArrayType(ty, len(elems)), elems) + + @classmethod + def literal_struct(cls, elems, packed=False): + """ + Construct a literal structure constant made of the given members. + """ + tys = [el.type for el in elems] + return cls(types.LiteralStructType(tys, packed), elems) + + @property + def addrspace(self): + if not isinstance(self.type, types.PointerType): + raise TypeError("Only pointer constant have address spaces") + return self.type.addrspace + + def __eq__(self, other): + if isinstance(other, Constant): + return str(self) == str(other) + else: + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash(str(self)) + + def __repr__(self): + return "" % (self.type, self.constant) + + +class FormattedConstant(Constant): + """ + A constant with an already formatted IR representation. + """ + + def __init__(self, typ, constant): + assert isinstance(constant, str) + Constant.__init__(self, typ, constant) + + def _to_string(self): + return self.constant + + def _get_reference(self): + return self.constant + + +class NamedValue(_StrCaching, _StringReferenceCaching, Value): + """ + The base class for named values. + """ + name_prefix = '%' + deduplicate_name = True + + def __init__(self, parent, type, name): + assert parent is not None + assert isinstance(type, types.Type) + self.parent = parent + self.type = type + self._set_name(name) + + def _to_string(self): + buf = [] + if not isinstance(self.type, types.VoidType): + buf.append("{0} = ".format(self.get_reference())) + self.descr(buf) + return "".join(buf).rstrip() + + def descr(self, buf): + raise NotImplementedError + + def _get_name(self): + return self._name + + def _set_name(self, name): + name = self.parent.scope.register(name, + deduplicate=self.deduplicate_name) + self._name = name + + name = property(_get_name, _set_name) + + def _get_reference(self): + name = self.name + # Quote and escape value name + if '\\' in name or '"' in name: + name = name.replace('\\', '\\5c').replace('"', '\\22') + return '{0}"{1}"'.format(self.name_prefix, name) + + def __repr__(self): + return "" % ( + self.__class__.__name__, self.name, self.type) + + @property + def function_type(self): + ty = self.type + if isinstance(ty, types.PointerType): + ty = self.type.pointee + if isinstance(ty, types.FunctionType): + return ty + else: + raise TypeError("Not a function: {0}".format(self.type)) + + +class MetaDataString(NamedValue): + """ + A metadata string, i.e. a constant string used as a value in a metadata + node. + """ + + def __init__(self, parent, string): + super(MetaDataString, self).__init__(parent, + types.MetaDataType(), + name="") + self.string = string + + def descr(self, buf): + buf += (self.get_reference(), "\n") + + def _get_reference(self): + return '!"{0}"'.format(_escape_string(self.string)) + + _to_string = _get_reference + + def __eq__(self, other): + if isinstance(other, MetaDataString): + return self.string == other.string + else: + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash(self.string) + + +class MetaDataArgument(_StrCaching, _StringReferenceCaching, Value): + """ + An argument value to a function taking metadata arguments. + This can wrap any other kind of LLVM value. + + Do not instantiate directly, Builder.call() will create these + automatically. + """ + + def __init__(self, value): + assert isinstance(value, Value) + assert not isinstance(value.type, types.MetaDataType) + self.type = types.MetaDataType() + self.wrapped_value = value + + def _get_reference(self): + # e.g. "i32* %2" + return "{0} {1}".format(self.wrapped_value.type, + self.wrapped_value.get_reference()) + + _to_string = _get_reference + + +class NamedMetaData(object): + """ + A named metadata node. + + Do not instantiate directly, use Module.add_named_metadata() instead. + """ + + def __init__(self, parent): + self.parent = parent + self.operands = [] + + def add(self, md): + self.operands.append(md) + + +class MDValue(NamedValue): + """ + A metadata node's value, consisting of a sequence of elements ("operands"). + + Do not instantiate directly, use Module.add_metadata() instead. + """ + name_prefix = '!' + + def __init__(self, parent, values, name): + super(MDValue, self).__init__(parent, + types.MetaDataType(), + name=name) + self.operands = tuple(values) + parent.metadata.append(self) + + def descr(self, buf): + operands = [] + for op in self.operands: + if isinstance(op.type, types.MetaDataType): + if isinstance(op, Constant) and op.constant is None: + operands.append("null") + else: + operands.append(op.get_reference()) + else: + operands.append("{0} {1}".format(op.type, op.get_reference())) + operands = ', '.join(operands) + buf += ("!{{ {0} }}".format(operands), "\n") + + def _get_reference(self): + return self.name_prefix + str(self.name) + + def __eq__(self, other): + if isinstance(other, MDValue): + return self.operands == other.operands + else: + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash(self.operands) + + +class DIToken: + """ + A debug information enumeration value that should appear bare in + the emitted metadata. + + Use this to wrap known constants, e.g. the DW_* enumerations. + """ + + def __init__(self, value): + self.value = value + + +class DIValue(NamedValue): + """ + A debug information descriptor, containing key-value pairs. + + Do not instantiate directly, use Module.add_debug_info() instead. + """ + name_prefix = '!' + + def __init__(self, parent, is_distinct, kind, operands, name): + super(DIValue, self).__init__(parent, + types.MetaDataType(), + name=name) + self.is_distinct = is_distinct + self.kind = kind + self.operands = tuple(operands) + parent.metadata.append(self) + + def descr(self, buf): + if self.is_distinct: + buf += ("distinct ",) + operands = [] + for key, value in self.operands: + if value is None: + strvalue = "null" + elif value is True: + strvalue = "true" + elif value is False: + strvalue = "false" + elif isinstance(value, DIToken): + strvalue = value.value + elif isinstance(value, str): + strvalue = '"{}"'.format(_escape_string(value)) + elif isinstance(value, int): + strvalue = str(value) + elif isinstance(value, NamedValue): + strvalue = value.get_reference() + else: + raise TypeError("invalid operand type for debug info: %r" + % (value,)) + operands.append("{0}: {1}".format(key, strvalue)) + operands = ', '.join(operands) + buf += ("!", self.kind, "(", operands, ")\n") + + def _get_reference(self): + return self.name_prefix + str(self.name) + + def __eq__(self, other): + if isinstance(other, DIValue): + return self.is_distinct == other.is_distinct and \ + self.kind == other.kind and \ + self.operands == other.operands + else: + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash((self.is_distinct, self.kind, self.operands)) + + +class GlobalValue(NamedValue, _ConstOpMixin, _HasMetadata): + """ + A global value. + """ + name_prefix = '@' + deduplicate_name = False + + def __init__(self, *args, **kwargs): + super(GlobalValue, self).__init__(*args, **kwargs) + self.linkage = '' + self.storage_class = '' + self.section = '' + self.metadata = {} + + +class GlobalVariable(GlobalValue): + """ + A global variable. + """ + + def __init__(self, module, typ, name, addrspace=0): + assert isinstance(typ, types.Type) + super(GlobalVariable, self).__init__(module, typ.as_pointer(addrspace), + name=name) + self.value_type = typ + self.initializer = None + self.unnamed_addr = False + self.global_constant = False + self.addrspace = addrspace + self.align = None + self.parent.add_global(self) + + def descr(self, buf): + if self.global_constant: + kind = 'constant' + else: + kind = 'global' + + if not self.linkage: + # Default to external linkage + linkage = 'external' if self.initializer is None else '' + else: + linkage = self.linkage + + if linkage: + buf.append(linkage + " ") + if self.storage_class: + buf.append(self.storage_class + " ") + if self.unnamed_addr: + buf.append("unnamed_addr ") + if self.addrspace != 0: + buf.append('addrspace({0:d}) '.format(self.addrspace)) + + buf.append("{kind} {type}" .format(kind=kind, type=self.value_type)) + + if self.initializer is not None: + if self.initializer.type != self.value_type: + raise TypeError("got initializer of type %s " + "for global value type %s" + % (self.initializer.type, self.value_type)) + buf.append(" " + self.initializer.get_reference()) + elif linkage not in ('external', 'extern_weak'): + # emit 'undef' for non-external linkage GV + buf.append(" " + self.value_type(Undefined).get_reference()) + + if self.section: + buf.append(", section \"%s\"" % (self.section,)) + + if self.align is not None: + buf.append(", align %d" % (self.align,)) + + if self.metadata: + buf.append(self._stringify_metadata(leading_comma=True)) + + buf.append("\n") + + +class AttributeSet(set): + """A set of string attribute. + Only accept items listed in *_known*. + + Properties: + * Iterate in sorted order + """ + _known = () + + def __init__(self, args=()): + super().__init__() + if isinstance(args, str): + args = [args] + for name in args: + self.add(name) + + def _expand(self, name, typ): + return name + + def add(self, name): + if name not in self._known: + raise ValueError('unknown attr {!r} for {}'.format(name, self)) + return super(AttributeSet, self).add(name) + + def _to_list(self, typ): + return [self._expand(i, typ) for i in sorted(self)] + + +class FunctionAttributes(AttributeSet): + _known = frozenset([ + 'argmemonly', 'alwaysinline', 'builtin', 'cold', 'convergent', + 'inaccessiblememonly', 'inaccessiblemem_or_argmemonly', 'inlinehint', + 'jumptable', 'minsize', 'naked', 'nobuiltin', 'noduplicate', + 'noimplicitfloat', 'noinline', 'nonlazybind', 'norecurse', + 'noredzone', 'noreturn', 'nounwind', 'optnone', 'optsize', + 'readnone', 'readonly', 'returns_twice', 'sanitize_address', + 'sanitize_memory', 'sanitize_thread', 'ssp', + 'sspreg', 'sspstrong', 'uwtable']) + + def __init__(self, args=()): + self._alignstack = 0 + self._personality = None + super(FunctionAttributes, self).__init__(args) + + def add(self, name): + if ((name == 'alwaysinline' and 'noinline' in self) or + (name == 'noinline' and 'alwaysinline' in self)): + raise ValueError("Can't have alwaysinline and noinline") + + super().add(name) + + @property + def alignstack(self): + return self._alignstack + + @alignstack.setter + def alignstack(self, val): + assert val >= 0 + self._alignstack = val + + @property + def personality(self): + return self._personality + + @personality.setter + def personality(self, val): + assert val is None or isinstance(val, GlobalValue) + self._personality = val + + def _to_list(self, ret_type): + attrs = super()._to_list(ret_type) + if self.alignstack: + attrs.append('alignstack({0:d})'.format(self.alignstack)) + if self.personality: + attrs.append('personality {persty} {persfn}'.format( + persty=self.personality.type, + persfn=self.personality.get_reference())) + return attrs + + +class Function(GlobalValue): + """Represent a LLVM Function but does uses a Module as parent. + Global Values are stored as a set of dependencies (attribute `depends`). + """ + + def __init__(self, module, ftype, name): + assert isinstance(ftype, types.Type) + super(Function, self).__init__(module, ftype.as_pointer(), name=name) + self.ftype = ftype + self.scope = _utils.NameScope() + self.blocks = [] + self.attributes = FunctionAttributes() + self.args = tuple([Argument(self, t) + for t in ftype.args]) + self.return_value = ReturnValue(self, ftype.return_type) + self.parent.add_global(self) + self.calling_convention = '' + + @property + def module(self): + return self.parent + + @property + def entry_basic_block(self): + return self.blocks[0] + + @property + def basic_blocks(self): + return self.blocks + + def append_basic_block(self, name=''): + blk = Block(parent=self, name=name) + self.blocks.append(blk) + return blk + + def insert_basic_block(self, before, name=''): + """Insert block before + """ + blk = Block(parent=self, name=name) + self.blocks.insert(before, blk) + return blk + + def descr_prototype(self, buf): + """ + Describe the prototype ("head") of the function. + """ + state = "define" if self.blocks else "declare" + ret = self.return_value + args = ", ".join(str(a) for a in self.args) + name = self.get_reference() + attrs = ' ' + ' '.join(self.attributes._to_list( + self.ftype.return_type)) if self.attributes else '' + if any(self.args): + vararg = ', ...' if self.ftype.var_arg else '' + else: + vararg = '...' if self.ftype.var_arg else '' + linkage = self.linkage + cconv = self.calling_convention + prefix = " ".join(str(x) for x in [state, linkage, cconv, ret] if x) + metadata = self._stringify_metadata() + metadata = ' {}'.format(metadata) if metadata else '' + section = ' section "{}"'.format(self.section) if self.section else '' + pt_str = "{prefix} {name}({args}{vararg}){attrs}{section}{metadata}\n" + prototype = pt_str.format(prefix=prefix, name=name, args=args, + vararg=vararg, attrs=attrs, section=section, + metadata=metadata) + buf.append(prototype) + + def descr_body(self, buf): + """ + Describe of the body of the function. + """ + for blk in self.blocks: + blk.descr(buf) + + def descr(self, buf): + self.descr_prototype(buf) + if self.blocks: + buf.append("{\n") + self.descr_body(buf) + buf.append("}\n") + + def __str__(self): + buf = [] + self.descr(buf) + return "".join(buf) + + @property + def is_declaration(self): + return len(self.blocks) == 0 + + +class ArgumentAttributes(AttributeSet): + # List from + # https://releases.llvm.org/14.0.0/docs/LangRef.html#parameter-attributes + _known = MappingProxyType({ + # True (emit type), + # False (emit name only) + 'byref': True, + 'byval': True, + 'elementtype': True, + 'immarg': False, + 'inalloca': True, + 'inreg': False, + 'nest': False, + 'noalias': False, + 'nocapture': False, + 'nofree': False, + 'nonnull': False, + 'noundef': False, + 'preallocated': True, + 'returned': False, + 'signext': False, + 'sret': True, + 'swiftasync': False, + 'swifterror': False, + 'swiftself': False, + 'zeroext': False, + }) + + def __init__(self, args=()): + self._align = 0 + self._dereferenceable = 0 + self._dereferenceable_or_null = 0 + super(ArgumentAttributes, self).__init__(args) + + def _expand(self, name, typ): + requires_type = self._known.get(name) + if requires_type: + return f"{name}({typ.pointee})" + else: + return name + + @property + def align(self): + return self._align + + @align.setter + def align(self, val): + assert isinstance(val, int) and val >= 0 + self._align = val + + @property + def dereferenceable(self): + return self._dereferenceable + + @dereferenceable.setter + def dereferenceable(self, val): + assert isinstance(val, int) and val >= 0 + self._dereferenceable = val + + @property + def dereferenceable_or_null(self): + return self._dereferenceable_or_null + + @dereferenceable_or_null.setter + def dereferenceable_or_null(self, val): + assert isinstance(val, int) and val >= 0 + self._dereferenceable_or_null = val + + def _to_list(self, typ): + attrs = super()._to_list(typ) + if self.align: + attrs.append('align {0:d}'.format(self.align)) + if self.dereferenceable: + attrs.append('dereferenceable({0:d})'.format(self.dereferenceable)) + if self.dereferenceable_or_null: + dref = 'dereferenceable_or_null({0:d})' + attrs.append(dref.format(self.dereferenceable_or_null)) + return attrs + + +class _BaseArgument(NamedValue): + def __init__(self, parent, typ, name=''): + assert isinstance(typ, types.Type) + super(_BaseArgument, self).__init__(parent, typ, name=name) + self.parent = parent + self.attributes = ArgumentAttributes() + + def __repr__(self): + return "" % (self.__class__.__name__, self.name, + self.type) + + def add_attribute(self, attr): + self.attributes.add(attr) + + +class Argument(_BaseArgument): + """ + The specification of a function argument. + """ + + def __str__(self): + attrs = self.attributes._to_list(self.type) + if attrs: + return "{0} {1} {2}".format(self.type, ' '.join(attrs), + self.get_reference()) + else: + return "{0} {1}".format(self.type, self.get_reference()) + + +class ReturnValue(_BaseArgument): + """ + The specification of a function's return value. + """ + + def __str__(self): + attrs = self.attributes._to_list(self.type) + if attrs: + return "{0} {1}".format(' '.join(attrs), self.type) + else: + return str(self.type) + + +class Block(NamedValue): + """ + A LLVM IR basic block. A basic block is a sequence of + instructions whose execution always goes from start to end. That + is, a control flow instruction (branch) can only appear as the + last instruction, and incoming branches can only jump to the first + instruction. + """ + + def __init__(self, parent, name=''): + super(Block, self).__init__(parent, types.LabelType(), name=name) + self.scope = parent.scope + self.instructions = [] + self.terminator = None + + @property + def is_terminated(self): + return self.terminator is not None + + @property + def function(self): + return self.parent + + @property + def module(self): + return self.parent.module + + def descr(self, buf): + buf.append("{0}:\n".format(self._format_name())) + buf += [" {0}\n".format(instr) for instr in self.instructions] + + def replace(self, old, new): + """Replace an instruction""" + if old.type != new.type: + raise TypeError("new instruction has a different type") + pos = self.instructions.index(old) + self.instructions.remove(old) + self.instructions.insert(pos, new) + + for bb in self.parent.basic_blocks: + for instr in bb.instructions: + instr.replace_usage(old, new) + + def _format_name(self): + # Per the LLVM Language Ref on identifiers, names matching the following + # regex do not need to be quoted: [%@][-a-zA-Z$._][-a-zA-Z$._0-9]* + # Otherwise, the identifier must be quoted and escaped. + name = self.name + if not _SIMPLE_IDENTIFIER_RE.match(name): + name = name.replace('\\', '\\5c').replace('"', '\\22') + name = '"{0}"'.format(name) + return name + + +class BlockAddress(Value): + """ + The address of a basic block. + """ + + def __init__(self, function, basic_block): + assert isinstance(function, Function) + assert isinstance(basic_block, Block) + self.type = types.IntType(8).as_pointer() + self.function = function + self.basic_block = basic_block + + def __str__(self): + return '{0} {1}'.format(self.type, self.get_reference()) + + def get_reference(self): + return "blockaddress({0}, {1})".format( + self.function.get_reference(), + self.basic_block.get_reference()) diff --git a/venv/lib/python3.10/site-packages/llvmlite/utils.py b/venv/lib/python3.10/site-packages/llvmlite/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e07ecd370f45b3af0fe67f9a0ac6ea1cee16db3f --- /dev/null +++ b/venv/lib/python3.10/site-packages/llvmlite/utils.py @@ -0,0 +1,29 @@ +import os +import sys + + +# This module must be importable without loading the binding, to avoid +# bootstrapping issues in setup.py. + +def get_library_name(): + """ + Return the name of the llvmlite shared library file. + """ + if os.name == 'posix': + if sys.platform == 'darwin': + return 'libllvmlite.dylib' + else: + return 'libllvmlite.so' + else: + assert os.name == 'nt' + return 'llvmlite.dll' + + +def get_library_files(): + """ + Return the names of shared library files needed for this platform. + """ + files = [get_library_name()] + if os.name == 'nt': + files.extend(['msvcr120.dll', 'msvcp120.dll']) + return files diff --git a/venv/lib/python3.10/site-packages/mpmath/__init__.py b/venv/lib/python3.10/site-packages/mpmath/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..46a7c6f7c0875548f264612b604a9e1574b00a84 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/__init__.py @@ -0,0 +1,468 @@ +__version__ = '1.3.0' + +from .usertools import monitor, timing + +from .ctx_fp import FPContext +from .ctx_mp import MPContext +from .ctx_iv import MPIntervalContext + +fp = FPContext() +mp = MPContext() +iv = MPIntervalContext() + +fp._mp = mp +mp._mp = mp +iv._mp = mp +mp._fp = fp +fp._fp = fp +mp._iv = iv +fp._iv = iv +iv._iv = iv + +# XXX: extremely bad pickle hack +from . import ctx_mp as _ctx_mp +_ctx_mp._mpf_module.mpf = mp.mpf +_ctx_mp._mpf_module.mpc = mp.mpc + +make_mpf = mp.make_mpf +make_mpc = mp.make_mpc + +extraprec = mp.extraprec +extradps = mp.extradps +workprec = mp.workprec +workdps = mp.workdps +autoprec = mp.autoprec +maxcalls = mp.maxcalls +memoize = mp.memoize + +mag = mp.mag + +bernfrac = mp.bernfrac + +qfrom = mp.qfrom +mfrom = mp.mfrom +kfrom = mp.kfrom +taufrom = mp.taufrom +qbarfrom = mp.qbarfrom +ellipfun = mp.ellipfun +jtheta = mp.jtheta +kleinj = mp.kleinj +eta = mp.eta + +qp = mp.qp +qhyper = mp.qhyper +qgamma = mp.qgamma +qfac = mp.qfac + +nint_distance = mp.nint_distance + +plot = mp.plot +cplot = mp.cplot +splot = mp.splot + +odefun = mp.odefun + +jacobian = mp.jacobian +findroot = mp.findroot +multiplicity = mp.multiplicity + +isinf = mp.isinf +isnan = mp.isnan +isnormal = mp.isnormal +isint = mp.isint +isfinite = mp.isfinite +almosteq = mp.almosteq +nan = mp.nan +rand = mp.rand + +absmin = mp.absmin +absmax = mp.absmax + +fraction = mp.fraction + +linspace = mp.linspace +arange = mp.arange + +mpmathify = convert = mp.convert +mpc = mp.mpc + +mpi = iv._mpi + +nstr = mp.nstr +nprint = mp.nprint +chop = mp.chop + +fneg = mp.fneg +fadd = mp.fadd +fsub = mp.fsub +fmul = mp.fmul +fdiv = mp.fdiv +fprod = mp.fprod + +quad = mp.quad +quadgl = mp.quadgl +quadts = mp.quadts +quadosc = mp.quadosc +quadsubdiv = mp.quadsubdiv + +invertlaplace = mp.invertlaplace +invlaptalbot = mp.invlaptalbot +invlapstehfest = mp.invlapstehfest +invlapdehoog = mp.invlapdehoog + +pslq = mp.pslq +identify = mp.identify +findpoly = mp.findpoly + +richardson = mp.richardson +shanks = mp.shanks +levin = mp.levin +cohen_alt = mp.cohen_alt +nsum = mp.nsum +nprod = mp.nprod +difference = mp.difference +diff = mp.diff +diffs = mp.diffs +diffs_prod = mp.diffs_prod +diffs_exp = mp.diffs_exp +diffun = mp.diffun +differint = mp.differint +taylor = mp.taylor +pade = mp.pade +polyval = mp.polyval +polyroots = mp.polyroots +fourier = mp.fourier +fourierval = mp.fourierval +sumem = mp.sumem +sumap = mp.sumap +chebyfit = mp.chebyfit +limit = mp.limit + +matrix = mp.matrix +eye = mp.eye +diag = mp.diag +zeros = mp.zeros +ones = mp.ones +hilbert = mp.hilbert +randmatrix = mp.randmatrix +swap_row = mp.swap_row +extend = mp.extend +norm = mp.norm +mnorm = mp.mnorm + +lu_solve = mp.lu_solve +lu = mp.lu +qr = mp.qr +unitvector = mp.unitvector +inverse = mp.inverse +residual = mp.residual +qr_solve = mp.qr_solve +cholesky = mp.cholesky +cholesky_solve = mp.cholesky_solve +det = mp.det +cond = mp.cond +hessenberg = mp.hessenberg +schur = mp.schur +eig = mp.eig +eig_sort = mp.eig_sort +eigsy = mp.eigsy +eighe = mp.eighe +eigh = mp.eigh +svd_r = mp.svd_r +svd_c = mp.svd_c +svd = mp.svd +gauss_quadrature = mp.gauss_quadrature + +expm = mp.expm +sqrtm = mp.sqrtm +powm = mp.powm +logm = mp.logm +sinm = mp.sinm +cosm = mp.cosm + +mpf = mp.mpf +j = mp.j +exp = mp.exp +expj = mp.expj +expjpi = mp.expjpi +ln = mp.ln +im = mp.im +re = mp.re +inf = mp.inf +ninf = mp.ninf +sign = mp.sign + +eps = mp.eps +pi = mp.pi +ln2 = mp.ln2 +ln10 = mp.ln10 +phi = mp.phi +e = mp.e +euler = mp.euler +catalan = mp.catalan +khinchin = mp.khinchin +glaisher = mp.glaisher +apery = mp.apery +degree = mp.degree +twinprime = mp.twinprime +mertens = mp.mertens + +ldexp = mp.ldexp +frexp = mp.frexp + +fsum = mp.fsum +fdot = mp.fdot + +sqrt = mp.sqrt +cbrt = mp.cbrt +exp = mp.exp +ln = mp.ln +log = mp.log +log10 = mp.log10 +power = mp.power +cos = mp.cos +sin = mp.sin +tan = mp.tan +cosh = mp.cosh +sinh = mp.sinh +tanh = mp.tanh +acos = mp.acos +asin = mp.asin +atan = mp.atan +asinh = mp.asinh +acosh = mp.acosh +atanh = mp.atanh +sec = mp.sec +csc = mp.csc +cot = mp.cot +sech = mp.sech +csch = mp.csch +coth = mp.coth +asec = mp.asec +acsc = mp.acsc +acot = mp.acot +asech = mp.asech +acsch = mp.acsch +acoth = mp.acoth +cospi = mp.cospi +sinpi = mp.sinpi +sinc = mp.sinc +sincpi = mp.sincpi +cos_sin = mp.cos_sin +cospi_sinpi = mp.cospi_sinpi +fabs = mp.fabs +re = mp.re +im = mp.im +conj = mp.conj +floor = mp.floor +ceil = mp.ceil +nint = mp.nint +frac = mp.frac +root = mp.root +nthroot = mp.nthroot +hypot = mp.hypot +fmod = mp.fmod +ldexp = mp.ldexp +frexp = mp.frexp +sign = mp.sign +arg = mp.arg +phase = mp.phase +polar = mp.polar +rect = mp.rect +degrees = mp.degrees +radians = mp.radians +atan2 = mp.atan2 +fib = mp.fib +fibonacci = mp.fibonacci +lambertw = mp.lambertw +zeta = mp.zeta +altzeta = mp.altzeta +gamma = mp.gamma +rgamma = mp.rgamma +factorial = mp.factorial +fac = mp.fac +fac2 = mp.fac2 +beta = mp.beta +betainc = mp.betainc +psi = mp.psi +#psi0 = mp.psi0 +#psi1 = mp.psi1 +#psi2 = mp.psi2 +#psi3 = mp.psi3 +polygamma = mp.polygamma +digamma = mp.digamma +#trigamma = mp.trigamma +#tetragamma = mp.tetragamma +#pentagamma = mp.pentagamma +harmonic = mp.harmonic +bernoulli = mp.bernoulli +bernfrac = mp.bernfrac +stieltjes = mp.stieltjes +hurwitz = mp.hurwitz +dirichlet = mp.dirichlet +bernpoly = mp.bernpoly +eulerpoly = mp.eulerpoly +eulernum = mp.eulernum +polylog = mp.polylog +clsin = mp.clsin +clcos = mp.clcos +gammainc = mp.gammainc +gammaprod = mp.gammaprod +binomial = mp.binomial +rf = mp.rf +ff = mp.ff +hyper = mp.hyper +hyp0f1 = mp.hyp0f1 +hyp1f1 = mp.hyp1f1 +hyp1f2 = mp.hyp1f2 +hyp2f1 = mp.hyp2f1 +hyp2f2 = mp.hyp2f2 +hyp2f0 = mp.hyp2f0 +hyp2f3 = mp.hyp2f3 +hyp3f2 = mp.hyp3f2 +hyperu = mp.hyperu +hypercomb = mp.hypercomb +meijerg = mp.meijerg +appellf1 = mp.appellf1 +appellf2 = mp.appellf2 +appellf3 = mp.appellf3 +appellf4 = mp.appellf4 +hyper2d = mp.hyper2d +bihyper = mp.bihyper +erf = mp.erf +erfc = mp.erfc +erfi = mp.erfi +erfinv = mp.erfinv +npdf = mp.npdf +ncdf = mp.ncdf +expint = mp.expint +e1 = mp.e1 +ei = mp.ei +li = mp.li +ci = mp.ci +si = mp.si +chi = mp.chi +shi = mp.shi +fresnels = mp.fresnels +fresnelc = mp.fresnelc +airyai = mp.airyai +airybi = mp.airybi +airyaizero = mp.airyaizero +airybizero = mp.airybizero +scorergi = mp.scorergi +scorerhi = mp.scorerhi +ellipk = mp.ellipk +ellipe = mp.ellipe +ellipf = mp.ellipf +ellippi = mp.ellippi +elliprc = mp.elliprc +elliprj = mp.elliprj +elliprf = mp.elliprf +elliprd = mp.elliprd +elliprg = mp.elliprg +agm = mp.agm +jacobi = mp.jacobi +chebyt = mp.chebyt +chebyu = mp.chebyu +legendre = mp.legendre +legenp = mp.legenp +legenq = mp.legenq +hermite = mp.hermite +pcfd = mp.pcfd +pcfu = mp.pcfu +pcfv = mp.pcfv +pcfw = mp.pcfw +gegenbauer = mp.gegenbauer +laguerre = mp.laguerre +spherharm = mp.spherharm +besselj = mp.besselj +j0 = mp.j0 +j1 = mp.j1 +besseli = mp.besseli +bessely = mp.bessely +besselk = mp.besselk +besseljzero = mp.besseljzero +besselyzero = mp.besselyzero +hankel1 = mp.hankel1 +hankel2 = mp.hankel2 +struveh = mp.struveh +struvel = mp.struvel +angerj = mp.angerj +webere = mp.webere +lommels1 = mp.lommels1 +lommels2 = mp.lommels2 +whitm = mp.whitm +whitw = mp.whitw +ber = mp.ber +bei = mp.bei +ker = mp.ker +kei = mp.kei +coulombc = mp.coulombc +coulombf = mp.coulombf +coulombg = mp.coulombg +barnesg = mp.barnesg +superfac = mp.superfac +hyperfac = mp.hyperfac +loggamma = mp.loggamma +siegeltheta = mp.siegeltheta +siegelz = mp.siegelz +grampoint = mp.grampoint +zetazero = mp.zetazero +riemannr = mp.riemannr +primepi = mp.primepi +primepi2 = mp.primepi2 +primezeta = mp.primezeta +bell = mp.bell +polyexp = mp.polyexp +expm1 = mp.expm1 +log1p = mp.log1p +powm1 = mp.powm1 +unitroots = mp.unitroots +cyclotomic = mp.cyclotomic +mangoldt = mp.mangoldt +secondzeta = mp.secondzeta +nzeros = mp.nzeros +backlunds = mp.backlunds +lerchphi = mp.lerchphi +stirling1 = mp.stirling1 +stirling2 = mp.stirling2 +squarew = mp.squarew +trianglew = mp.trianglew +sawtoothw = mp.sawtoothw +unit_triangle = mp.unit_triangle +sigmoid = mp.sigmoid + +# be careful when changing this name, don't use test*! +def runtests(): + """ + Run all mpmath tests and print output. + """ + import os.path + from inspect import getsourcefile + from .tests import runtests as tests + testdir = os.path.dirname(os.path.abspath(getsourcefile(tests))) + importdir = os.path.abspath(testdir + '/../..') + tests.testit(importdir, testdir) + +def doctests(filter=[]): + import sys + from timeit import default_timer as clock + for i, arg in enumerate(sys.argv): + if '__init__.py' in arg: + filter = [sn for sn in sys.argv[i+1:] if not sn.startswith("-")] + break + import doctest + globs = globals().copy() + for obj in globs: #sorted(globs.keys()): + if filter: + if not sum([pat in obj for pat in filter]): + continue + sys.stdout.write(str(obj) + " ") + sys.stdout.flush() + t1 = clock() + doctest.run_docstring_examples(globs[obj], {}, verbose=("-v" in sys.argv)) + t2 = clock() + print(round(t2-t1, 3)) + +if __name__ == '__main__': + doctests() diff --git a/venv/lib/python3.10/site-packages/mpmath/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c87795d2a9f099913497a8a42a15a928f8cf923 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_base.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6587125686a5ab93d4239361188f25f32207be79 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_base.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_fp.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_fp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b326cfef3567f7960315859a652fbc7779feb36 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_fp.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_iv.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_iv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d9c7c4868cc012e80906c8f7fc2e512065dcefb Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_iv.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_mp.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_mp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a359db2d63bd2f1b350837d19bd6ae385ced897d Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_mp.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_mp_python.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_mp_python.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bbe3ccfaf292f7264b768158fef10fb34b1e3c1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_mp_python.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/__pycache__/identification.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/__pycache__/identification.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1dce38eb01d915594fe011095939c25b8f8685a5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/__pycache__/identification.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/__pycache__/math2.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/__pycache__/math2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a83b860f6793791b3c5cbe9f237234d6588ce336 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/__pycache__/math2.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/__pycache__/rational.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/__pycache__/rational.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2efb13de40d8ee9c7f7cd7e41154af7b4555d9f Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/__pycache__/rational.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/__pycache__/usertools.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/__pycache__/usertools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed37c4a644932c80c5f728a459cb16bfe781a587 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/__pycache__/usertools.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/__pycache__/visualization.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/__pycache__/visualization.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7916b82b2d348b4a4736f843a77082717b7200e7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/__pycache__/visualization.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/__init__.py b/venv/lib/python3.10/site-packages/mpmath/calculus/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..040a3806b968f75b8d1a88ae37a4979fe83d466a --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/calculus/__init__.py @@ -0,0 +1,6 @@ +from . import calculus +# XXX: hack to set methods +from . import approximation +from . import differentiation +from . import extrapolation +from . import polynomials diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a9ec2cbf50f4cf4a2c61d98e58ccd9b6693d673 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/approximation.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/approximation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f84fd9ff1453f5fdc8c285bd7ad71c536f0fcd9c Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/approximation.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/calculus.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/calculus.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b96cb1ad4fbf96ac0083b693d436fe88890373ea Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/calculus.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/differentiation.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/differentiation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf0903110e650882df544dc8498e0d3eaf280ed7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/differentiation.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/extrapolation.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/extrapolation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9e648c3512410456aa18742ff8a8aebc12a6979 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/extrapolation.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/inverselaplace.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/inverselaplace.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a75040cf17f06a703d2e620509efa1dc97fb25ef Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/inverselaplace.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/odes.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/odes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0993f50d0b5267c5a7ff34bd3725872a192bd592 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/odes.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/optimization.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/optimization.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cd733f5ae97f805ce875f3063d83b0ee82eb435 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/optimization.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/polynomials.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/polynomials.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2491f02e692286b5194826186393e961537646f Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/polynomials.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/quadrature.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/quadrature.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13dd1cfdcd77039164c15788f8af490170b72d23 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/calculus/__pycache__/quadrature.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/approximation.py b/venv/lib/python3.10/site-packages/mpmath/calculus/approximation.py new file mode 100644 index 0000000000000000000000000000000000000000..7ca5cc598fb53491cb6ae4a41a40477c58544d53 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/calculus/approximation.py @@ -0,0 +1,246 @@ +from ..libmp.backend import xrange +from .calculus import defun + +#----------------------------------------------------------------------------# +# Approximation methods # +#----------------------------------------------------------------------------# + +# The Chebyshev approximation formula is given at: +# http://mathworld.wolfram.com/ChebyshevApproximationFormula.html + +# The only major changes in the following code is that we return the +# expanded polynomial coefficients instead of Chebyshev coefficients, +# and that we automatically transform [a,b] -> [-1,1] and back +# for convenience. + +# Coefficient in Chebyshev approximation +def chebcoeff(ctx,f,a,b,j,N): + s = ctx.mpf(0) + h = ctx.mpf(0.5) + for k in range(1, N+1): + t = ctx.cospi((k-h)/N) + s += f(t*(b-a)*h + (b+a)*h) * ctx.cospi(j*(k-h)/N) + return 2*s/N + +# Generate Chebyshev polynomials T_n(ax+b) in expanded form +def chebT(ctx, a=1, b=0): + Tb = [1] + yield Tb + Ta = [b, a] + while 1: + yield Ta + # Recurrence: T[n+1](ax+b) = 2*(ax+b)*T[n](ax+b) - T[n-1](ax+b) + Tmp = [0] + [2*a*t for t in Ta] + for i, c in enumerate(Ta): Tmp[i] += 2*b*c + for i, c in enumerate(Tb): Tmp[i] -= c + Ta, Tb = Tmp, Ta + +@defun +def chebyfit(ctx, f, interval, N, error=False): + r""" + Computes a polynomial of degree `N-1` that approximates the + given function `f` on the interval `[a, b]`. With ``error=True``, + :func:`~mpmath.chebyfit` also returns an accurate estimate of the + maximum absolute error; that is, the maximum value of + `|f(x) - P(x)|` for `x \in [a, b]`. + + :func:`~mpmath.chebyfit` uses the Chebyshev approximation formula, + which gives a nearly optimal solution: that is, the maximum + error of the approximating polynomial is very close to + the smallest possible for any polynomial of the same degree. + + Chebyshev approximation is very useful if one needs repeated + evaluation of an expensive function, such as function defined + implicitly by an integral or a differential equation. (For + example, it could be used to turn a slow mpmath function + into a fast machine-precision version of the same.) + + **Examples** + + Here we use :func:`~mpmath.chebyfit` to generate a low-degree approximation + of `f(x) = \cos(x)`, valid on the interval `[1, 2]`:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> poly, err = chebyfit(cos, [1, 2], 5, error=True) + >>> nprint(poly) + [0.00291682, 0.146166, -0.732491, 0.174141, 0.949553] + >>> nprint(err, 12) + 1.61351758081e-5 + + The polynomial can be evaluated using ``polyval``:: + + >>> nprint(polyval(poly, 1.6), 12) + -0.0291858904138 + >>> nprint(cos(1.6), 12) + -0.0291995223013 + + Sampling the true error at 1000 points shows that the error + estimate generated by ``chebyfit`` is remarkably good:: + + >>> error = lambda x: abs(cos(x) - polyval(poly, x)) + >>> nprint(max([error(1+n/1000.) for n in range(1000)]), 12) + 1.61349954245e-5 + + **Choice of degree** + + The degree `N` can be set arbitrarily high, to obtain an + arbitrarily good approximation. As a rule of thumb, an + `N`-term Chebyshev approximation is good to `N/(b-a)` decimal + places on a unit interval (although this depends on how + well-behaved `f` is). The cost grows accordingly: ``chebyfit`` + evaluates the function `(N^2)/2` times to compute the + coefficients and an additional `N` times to estimate the error. + + **Possible issues** + + One should be careful to use a sufficiently high working + precision both when calling ``chebyfit`` and when evaluating + the resulting polynomial, as the polynomial is sometimes + ill-conditioned. It is for example difficult to reach + 15-digit accuracy when evaluating the polynomial using + machine precision floats, no matter the theoretical + accuracy of the polynomial. (The option to return the + coefficients in Chebyshev form should be made available + in the future.) + + It is important to note the Chebyshev approximation works + poorly if `f` is not smooth. A function containing singularities, + rapid oscillation, etc can be approximated more effectively by + multiplying it by a weight function that cancels out the + nonsmooth features, or by dividing the interval into several + segments. + """ + a, b = ctx._as_points(interval) + orig = ctx.prec + try: + ctx.prec = orig + int(N**0.5) + 20 + c = [chebcoeff(ctx,f,a,b,k,N) for k in range(N)] + d = [ctx.zero] * N + d[0] = -c[0]/2 + h = ctx.mpf(0.5) + T = chebT(ctx, ctx.mpf(2)/(b-a), ctx.mpf(-1)*(b+a)/(b-a)) + for (k, Tk) in zip(range(N), T): + for i in range(len(Tk)): + d[i] += c[k]*Tk[i] + d = d[::-1] + # Estimate maximum error + err = ctx.zero + for k in range(N): + x = ctx.cos(ctx.pi*k/N) * (b-a)*h + (b+a)*h + err = max(err, abs(f(x) - ctx.polyval(d, x))) + finally: + ctx.prec = orig + if error: + return d, +err + else: + return d + +@defun +def fourier(ctx, f, interval, N): + r""" + Computes the Fourier series of degree `N` of the given function + on the interval `[a, b]`. More precisely, :func:`~mpmath.fourier` returns + two lists `(c, s)` of coefficients (the cosine series and sine + series, respectively), such that + + .. math :: + + f(x) \sim \sum_{k=0}^N + c_k \cos(k m x) + s_k \sin(k m x) + + where `m = 2 \pi / (b-a)`. + + Note that many texts define the first coefficient as `2 c_0` instead + of `c_0`. The easiest way to evaluate the computed series correctly + is to pass it to :func:`~mpmath.fourierval`. + + **Examples** + + The function `f(x) = x` has a simple Fourier series on the standard + interval `[-\pi, \pi]`. The cosine coefficients are all zero (because + the function has odd symmetry), and the sine coefficients are + rational numbers:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> c, s = fourier(lambda x: x, [-pi, pi], 5) + >>> nprint(c) + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + >>> nprint(s) + [0.0, 2.0, -1.0, 0.666667, -0.5, 0.4] + + This computes a Fourier series of a nonsymmetric function on + a nonstandard interval:: + + >>> I = [-1, 1.5] + >>> f = lambda x: x**2 - 4*x + 1 + >>> cs = fourier(f, I, 4) + >>> nprint(cs[0]) + [0.583333, 1.12479, -1.27552, 0.904708, -0.441296] + >>> nprint(cs[1]) + [0.0, -2.6255, 0.580905, 0.219974, -0.540057] + + It is instructive to plot a function along with its truncated + Fourier series:: + + >>> plot([f, lambda x: fourierval(cs, I, x)], I) #doctest: +SKIP + + Fourier series generally converge slowly (and may not converge + pointwise). For example, if `f(x) = \cosh(x)`, a 10-term Fourier + series gives an `L^2` error corresponding to 2-digit accuracy:: + + >>> I = [-1, 1] + >>> cs = fourier(cosh, I, 9) + >>> g = lambda x: (cosh(x) - fourierval(cs, I, x))**2 + >>> nprint(sqrt(quad(g, I))) + 0.00467963 + + :func:`~mpmath.fourier` uses numerical quadrature. For nonsmooth functions, + the accuracy (and speed) can be improved by including all singular + points in the interval specification:: + + >>> nprint(fourier(abs, [-1, 1], 0), 10) + ([0.5000441648], [0.0]) + >>> nprint(fourier(abs, [-1, 0, 1], 0), 10) + ([0.5], [0.0]) + + """ + interval = ctx._as_points(interval) + a = interval[0] + b = interval[-1] + L = b-a + cos_series = [] + sin_series = [] + cutoff = ctx.eps*10 + for n in xrange(N+1): + m = 2*n*ctx.pi/L + an = 2*ctx.quadgl(lambda t: f(t)*ctx.cos(m*t), interval)/L + bn = 2*ctx.quadgl(lambda t: f(t)*ctx.sin(m*t), interval)/L + if n == 0: + an /= 2 + if abs(an) < cutoff: an = ctx.zero + if abs(bn) < cutoff: bn = ctx.zero + cos_series.append(an) + sin_series.append(bn) + return cos_series, sin_series + +@defun +def fourierval(ctx, series, interval, x): + """ + Evaluates a Fourier series (in the format computed by + by :func:`~mpmath.fourier` for the given interval) at the point `x`. + + The series should be a pair `(c, s)` where `c` is the + cosine series and `s` is the sine series. The two lists + need not have the same length. + """ + cs, ss = series + ab = ctx._as_points(interval) + a = interval[0] + b = interval[-1] + m = 2*ctx.pi/(ab[-1]-ab[0]) + s = ctx.zero + s += ctx.fsum(cs[n]*ctx.cos(m*n*x) for n in xrange(len(cs)) if cs[n]) + s += ctx.fsum(ss[n]*ctx.sin(m*n*x) for n in xrange(len(ss)) if ss[n]) + return s diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/calculus.py b/venv/lib/python3.10/site-packages/mpmath/calculus/calculus.py new file mode 100644 index 0000000000000000000000000000000000000000..24256f121d6c07e5ce954f2a5f5024f156f64016 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/calculus/calculus.py @@ -0,0 +1,6 @@ +class CalculusMethods(object): + pass + +def defun(f): + setattr(CalculusMethods, f.__name__, f) + return f diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/differentiation.py b/venv/lib/python3.10/site-packages/mpmath/calculus/differentiation.py new file mode 100644 index 0000000000000000000000000000000000000000..f8186bebd4476476eded9e4b2f8dc3eb23ef5ff9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/calculus/differentiation.py @@ -0,0 +1,647 @@ +from ..libmp.backend import xrange +from .calculus import defun + +try: + iteritems = dict.iteritems +except AttributeError: + iteritems = dict.items + +#----------------------------------------------------------------------------# +# Differentiation # +#----------------------------------------------------------------------------# + +@defun +def difference(ctx, s, n): + r""" + Given a sequence `(s_k)` containing at least `n+1` items, returns the + `n`-th forward difference, + + .. math :: + + \Delta^n = \sum_{k=0}^{\infty} (-1)^{k+n} {n \choose k} s_k. + """ + n = int(n) + d = ctx.zero + b = (-1) ** (n & 1) + for k in xrange(n+1): + d += b * s[k] + b = (b * (k-n)) // (k+1) + return d + +def hsteps(ctx, f, x, n, prec, **options): + singular = options.get('singular') + addprec = options.get('addprec', 10) + direction = options.get('direction', 0) + workprec = (prec+2*addprec) * (n+1) + orig = ctx.prec + try: + ctx.prec = workprec + h = options.get('h') + if h is None: + if options.get('relative'): + hextramag = int(ctx.mag(x)) + else: + hextramag = 0 + h = ctx.ldexp(1, -prec-addprec-hextramag) + else: + h = ctx.convert(h) + # Directed: steps x, x+h, ... x+n*h + direction = options.get('direction', 0) + if direction: + h *= ctx.sign(direction) + steps = xrange(n+1) + norm = h + # Central: steps x-n*h, x-(n-2)*h ..., x, ..., x+(n-2)*h, x+n*h + else: + steps = xrange(-n, n+1, 2) + norm = (2*h) + # Perturb + if singular: + x += 0.5*h + values = [f(x+k*h) for k in steps] + return values, norm, workprec + finally: + ctx.prec = orig + + +@defun +def diff(ctx, f, x, n=1, **options): + r""" + Numerically computes the derivative of `f`, `f'(x)`, or generally for + an integer `n \ge 0`, the `n`-th derivative `f^{(n)}(x)`. + A few basic examples are:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> diff(lambda x: x**2 + x, 1.0) + 3.0 + >>> diff(lambda x: x**2 + x, 1.0, 2) + 2.0 + >>> diff(lambda x: x**2 + x, 1.0, 3) + 0.0 + >>> nprint([diff(exp, 3, n) for n in range(5)]) # exp'(x) = exp(x) + [20.0855, 20.0855, 20.0855, 20.0855, 20.0855] + + Even more generally, given a tuple of arguments `(x_1, \ldots, x_k)` + and order `(n_1, \ldots, n_k)`, the partial derivative + `f^{(n_1,\ldots,n_k)}(x_1,\ldots,x_k)` is evaluated. For example:: + + >>> diff(lambda x,y: 3*x*y + 2*y - x, (0.25, 0.5), (0,1)) + 2.75 + >>> diff(lambda x,y: 3*x*y + 2*y - x, (0.25, 0.5), (1,1)) + 3.0 + + **Options** + + The following optional keyword arguments are recognized: + + ``method`` + Supported methods are ``'step'`` or ``'quad'``: derivatives may be + computed using either a finite difference with a small step + size `h` (default), or numerical quadrature. + ``direction`` + Direction of finite difference: can be -1 for a left + difference, 0 for a central difference (default), or +1 + for a right difference; more generally can be any complex number. + ``addprec`` + Extra precision for `h` used to account for the function's + sensitivity to perturbations (default = 10). + ``relative`` + Choose `h` relative to the magnitude of `x`, rather than an + absolute value; useful for large or tiny `x` (default = False). + ``h`` + As an alternative to ``addprec`` and ``relative``, manually + select the step size `h`. + ``singular`` + If True, evaluation exactly at the point `x` is avoided; this is + useful for differentiating functions with removable singularities. + Default = False. + ``radius`` + Radius of integration contour (with ``method = 'quad'``). + Default = 0.25. A larger radius typically is faster and more + accurate, but it must be chosen so that `f` has no + singularities within the radius from the evaluation point. + + A finite difference requires `n+1` function evaluations and must be + performed at `(n+1)` times the target precision. Accordingly, `f` must + support fast evaluation at high precision. + + With integration, a larger number of function evaluations is + required, but not much extra precision is required. For high order + derivatives, this method may thus be faster if f is very expensive to + evaluate at high precision. + + **Further examples** + + The direction option is useful for computing left- or right-sided + derivatives of nonsmooth functions:: + + >>> diff(abs, 0, direction=0) + 0.0 + >>> diff(abs, 0, direction=1) + 1.0 + >>> diff(abs, 0, direction=-1) + -1.0 + + More generally, if the direction is nonzero, a right difference + is computed where the step size is multiplied by sign(direction). + For example, with direction=+j, the derivative from the positive + imaginary direction will be computed:: + + >>> diff(abs, 0, direction=j) + (0.0 - 1.0j) + + With integration, the result may have a small imaginary part + even even if the result is purely real:: + + >>> diff(sqrt, 1, method='quad') # doctest:+ELLIPSIS + (0.5 - 4.59...e-26j) + >>> chop(_) + 0.5 + + Adding precision to obtain an accurate value:: + + >>> diff(cos, 1e-30) + 0.0 + >>> diff(cos, 1e-30, h=0.0001) + -9.99999998328279e-31 + >>> diff(cos, 1e-30, addprec=100) + -1.0e-30 + + """ + partial = False + try: + orders = list(n) + x = list(x) + partial = True + except TypeError: + pass + if partial: + x = [ctx.convert(_) for _ in x] + return _partial_diff(ctx, f, x, orders, options) + method = options.get('method', 'step') + if n == 0 and method != 'quad' and not options.get('singular'): + return f(ctx.convert(x)) + prec = ctx.prec + try: + if method == 'step': + values, norm, workprec = hsteps(ctx, f, x, n, prec, **options) + ctx.prec = workprec + v = ctx.difference(values, n) / norm**n + elif method == 'quad': + ctx.prec += 10 + radius = ctx.convert(options.get('radius', 0.25)) + def g(t): + rei = radius*ctx.expj(t) + z = x + rei + return f(z) / rei**n + d = ctx.quadts(g, [0, 2*ctx.pi]) + v = d * ctx.factorial(n) / (2*ctx.pi) + else: + raise ValueError("unknown method: %r" % method) + finally: + ctx.prec = prec + return +v + +def _partial_diff(ctx, f, xs, orders, options): + if not orders: + return f() + if not sum(orders): + return f(*xs) + i = 0 + for i in range(len(orders)): + if orders[i]: + break + order = orders[i] + def fdiff_inner(*f_args): + def inner(t): + return f(*(f_args[:i] + (t,) + f_args[i+1:])) + return ctx.diff(inner, f_args[i], order, **options) + orders[i] = 0 + return _partial_diff(ctx, fdiff_inner, xs, orders, options) + +@defun +def diffs(ctx, f, x, n=None, **options): + r""" + Returns a generator that yields the sequence of derivatives + + .. math :: + + f(x), f'(x), f''(x), \ldots, f^{(k)}(x), \ldots + + With ``method='step'``, :func:`~mpmath.diffs` uses only `O(k)` + function evaluations to generate the first `k` derivatives, + rather than the roughly `O(k^2)` evaluations + required if one calls :func:`~mpmath.diff` `k` separate times. + + With `n < \infty`, the generator stops as soon as the + `n`-th derivative has been generated. If the exact number of + needed derivatives is known in advance, this is further + slightly more efficient. + + Options are the same as for :func:`~mpmath.diff`. + + **Examples** + + >>> from mpmath import * + >>> mp.dps = 15 + >>> nprint(list(diffs(cos, 1, 5))) + [0.540302, -0.841471, -0.540302, 0.841471, 0.540302, -0.841471] + >>> for i, d in zip(range(6), diffs(cos, 1)): + ... print("%s %s" % (i, d)) + ... + 0 0.54030230586814 + 1 -0.841470984807897 + 2 -0.54030230586814 + 3 0.841470984807897 + 4 0.54030230586814 + 5 -0.841470984807897 + + """ + if n is None: + n = ctx.inf + else: + n = int(n) + if options.get('method', 'step') != 'step': + k = 0 + while k < n + 1: + yield ctx.diff(f, x, k, **options) + k += 1 + return + singular = options.get('singular') + if singular: + yield ctx.diff(f, x, 0, singular=True) + else: + yield f(ctx.convert(x)) + if n < 1: + return + if n == ctx.inf: + A, B = 1, 2 + else: + A, B = 1, n+1 + while 1: + callprec = ctx.prec + y, norm, workprec = hsteps(ctx, f, x, B, callprec, **options) + for k in xrange(A, B): + try: + ctx.prec = workprec + d = ctx.difference(y, k) / norm**k + finally: + ctx.prec = callprec + yield +d + if k >= n: + return + A, B = B, int(A*1.4+1) + B = min(B, n) + +def iterable_to_function(gen): + gen = iter(gen) + data = [] + def f(k): + for i in xrange(len(data), k+1): + data.append(next(gen)) + return data[k] + return f + +@defun +def diffs_prod(ctx, factors): + r""" + Given a list of `N` iterables or generators yielding + `f_k(x), f'_k(x), f''_k(x), \ldots` for `k = 1, \ldots, N`, + generate `g(x), g'(x), g''(x), \ldots` where + `g(x) = f_1(x) f_2(x) \cdots f_N(x)`. + + At high precision and for large orders, this is typically more efficient + than numerical differentiation if the derivatives of each `f_k(x)` + admit direct computation. + + Note: This function does not increase the working precision internally, + so guard digits may have to be added externally for full accuracy. + + **Examples** + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> f = lambda x: exp(x)*cos(x)*sin(x) + >>> u = diffs(f, 1) + >>> v = mp.diffs_prod([diffs(exp,1), diffs(cos,1), diffs(sin,1)]) + >>> next(u); next(v) + 1.23586333600241 + 1.23586333600241 + >>> next(u); next(v) + 0.104658952245596 + 0.104658952245596 + >>> next(u); next(v) + -5.96999877552086 + -5.96999877552086 + >>> next(u); next(v) + -12.4632923122697 + -12.4632923122697 + + """ + N = len(factors) + if N == 1: + for c in factors[0]: + yield c + else: + u = iterable_to_function(ctx.diffs_prod(factors[:N//2])) + v = iterable_to_function(ctx.diffs_prod(factors[N//2:])) + n = 0 + while 1: + #yield sum(binomial(n,k)*u(n-k)*v(k) for k in xrange(n+1)) + s = u(n) * v(0) + a = 1 + for k in xrange(1,n+1): + a = a * (n-k+1) // k + s += a * u(n-k) * v(k) + yield s + n += 1 + +def dpoly(n, _cache={}): + """ + nth differentiation polynomial for exp (Faa di Bruno's formula). + + TODO: most exponents are zero, so maybe a sparse representation + would be better. + """ + if n in _cache: + return _cache[n] + if not _cache: + _cache[0] = {(0,):1} + R = dpoly(n-1) + R = dict((c+(0,),v) for (c,v) in iteritems(R)) + Ra = {} + for powers, count in iteritems(R): + powers1 = (powers[0]+1,) + powers[1:] + if powers1 in Ra: + Ra[powers1] += count + else: + Ra[powers1] = count + for powers, count in iteritems(R): + if not sum(powers): + continue + for k,p in enumerate(powers): + if p: + powers2 = powers[:k] + (p-1,powers[k+1]+1) + powers[k+2:] + if powers2 in Ra: + Ra[powers2] += p*count + else: + Ra[powers2] = p*count + _cache[n] = Ra + return _cache[n] + +@defun +def diffs_exp(ctx, fdiffs): + r""" + Given an iterable or generator yielding `f(x), f'(x), f''(x), \ldots` + generate `g(x), g'(x), g''(x), \ldots` where `g(x) = \exp(f(x))`. + + At high precision and for large orders, this is typically more efficient + than numerical differentiation if the derivatives of `f(x)` + admit direct computation. + + Note: This function does not increase the working precision internally, + so guard digits may have to be added externally for full accuracy. + + **Examples** + + The derivatives of the gamma function can be computed using + logarithmic differentiation:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> + >>> def diffs_loggamma(x): + ... yield loggamma(x) + ... i = 0 + ... while 1: + ... yield psi(i,x) + ... i += 1 + ... + >>> u = diffs_exp(diffs_loggamma(3)) + >>> v = diffs(gamma, 3) + >>> next(u); next(v) + 2.0 + 2.0 + >>> next(u); next(v) + 1.84556867019693 + 1.84556867019693 + >>> next(u); next(v) + 2.49292999190269 + 2.49292999190269 + >>> next(u); next(v) + 3.44996501352367 + 3.44996501352367 + + """ + fn = iterable_to_function(fdiffs) + f0 = ctx.exp(fn(0)) + yield f0 + i = 1 + while 1: + s = ctx.mpf(0) + for powers, c in iteritems(dpoly(i)): + s += c*ctx.fprod(fn(k+1)**p for (k,p) in enumerate(powers) if p) + yield s * f0 + i += 1 + +@defun +def differint(ctx, f, x, n=1, x0=0): + r""" + Calculates the Riemann-Liouville differintegral, or fractional + derivative, defined by + + .. math :: + + \,_{x_0}{\mathbb{D}}^n_xf(x) = \frac{1}{\Gamma(m-n)} \frac{d^m}{dx^m} + \int_{x_0}^{x}(x-t)^{m-n-1}f(t)dt + + where `f` is a given (presumably well-behaved) function, + `x` is the evaluation point, `n` is the order, and `x_0` is + the reference point of integration (`m` is an arbitrary + parameter selected automatically). + + With `n = 1`, this is just the standard derivative `f'(x)`; with `n = 2`, + the second derivative `f''(x)`, etc. With `n = -1`, it gives + `\int_{x_0}^x f(t) dt`, with `n = -2` + it gives `\int_{x_0}^x \left( \int_{x_0}^t f(u) du \right) dt`, etc. + + As `n` is permitted to be any number, this operator generalizes + iterated differentiation and iterated integration to a single + operator with a continuous order parameter. + + **Examples** + + There is an exact formula for the fractional derivative of a + monomial `x^p`, which may be used as a reference. For example, + the following gives a half-derivative (order 0.5):: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> x = mpf(3); p = 2; n = 0.5 + >>> differint(lambda t: t**p, x, n) + 7.81764019044672 + >>> gamma(p+1)/gamma(p-n+1) * x**(p-n) + 7.81764019044672 + + Another useful test function is the exponential function, whose + integration / differentiation formula easy generalizes + to arbitrary order. Here we first compute a third derivative, + and then a triply nested integral. (The reference point `x_0` + is set to `-\infty` to avoid nonzero endpoint terms.):: + + >>> differint(lambda x: exp(pi*x), -1.5, 3) + 0.278538406900792 + >>> exp(pi*-1.5) * pi**3 + 0.278538406900792 + >>> differint(lambda x: exp(pi*x), 3.5, -3, -inf) + 1922.50563031149 + >>> exp(pi*3.5) / pi**3 + 1922.50563031149 + + However, for noninteger `n`, the differentiation formula for the + exponential function must be modified to give the same result as the + Riemann-Liouville differintegral:: + + >>> x = mpf(3.5) + >>> c = pi + >>> n = 1+2*j + >>> differint(lambda x: exp(c*x), x, n) + (-123295.005390743 + 140955.117867654j) + >>> x**(-n) * exp(c)**x * (x*c)**n * gammainc(-n, 0, x*c) / gamma(-n) + (-123295.005390743 + 140955.117867654j) + + + """ + m = max(int(ctx.ceil(ctx.re(n)))+1, 1) + r = m-n-1 + g = lambda x: ctx.quad(lambda t: (x-t)**r * f(t), [x0, x]) + return ctx.diff(g, x, m) / ctx.gamma(m-n) + +@defun +def diffun(ctx, f, n=1, **options): + r""" + Given a function `f`, returns a function `g(x)` that evaluates the nth + derivative `f^{(n)}(x)`:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> cos2 = diffun(sin) + >>> sin2 = diffun(sin, 4) + >>> cos(1.3), cos2(1.3) + (0.267498828624587, 0.267498828624587) + >>> sin(1.3), sin2(1.3) + (0.963558185417193, 0.963558185417193) + + The function `f` must support arbitrary precision evaluation. + See :func:`~mpmath.diff` for additional details and supported + keyword options. + """ + if n == 0: + return f + def g(x): + return ctx.diff(f, x, n, **options) + return g + +@defun +def taylor(ctx, f, x, n, **options): + r""" + Produces a degree-`n` Taylor polynomial around the point `x` of the + given function `f`. The coefficients are returned as a list. + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> nprint(chop(taylor(sin, 0, 5))) + [0.0, 1.0, 0.0, -0.166667, 0.0, 0.00833333] + + The coefficients are computed using high-order numerical + differentiation. The function must be possible to evaluate + to arbitrary precision. See :func:`~mpmath.diff` for additional details + and supported keyword options. + + Note that to evaluate the Taylor polynomial as an approximation + of `f`, e.g. with :func:`~mpmath.polyval`, the coefficients must be reversed, + and the point of the Taylor expansion must be subtracted from + the argument: + + >>> p = taylor(exp, 2.0, 10) + >>> polyval(p[::-1], 2.5 - 2.0) + 12.1824939606092 + >>> exp(2.5) + 12.1824939607035 + + """ + gen = enumerate(ctx.diffs(f, x, n, **options)) + if options.get("chop", True): + return [ctx.chop(d)/ctx.factorial(i) for i, d in gen] + else: + return [d/ctx.factorial(i) for i, d in gen] + +@defun +def pade(ctx, a, L, M): + r""" + Computes a Pade approximation of degree `(L, M)` to a function. + Given at least `L+M+1` Taylor coefficients `a` approximating + a function `A(x)`, :func:`~mpmath.pade` returns coefficients of + polynomials `P, Q` satisfying + + .. math :: + + P = \sum_{k=0}^L p_k x^k + + Q = \sum_{k=0}^M q_k x^k + + Q_0 = 1 + + A(x) Q(x) = P(x) + O(x^{L+M+1}) + + `P(x)/Q(x)` can provide a good approximation to an analytic function + beyond the radius of convergence of its Taylor series (example + from G.A. Baker 'Essentials of Pade Approximants' Academic Press, + Ch.1A):: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> one = mpf(1) + >>> def f(x): + ... return sqrt((one + 2*x)/(one + x)) + ... + >>> a = taylor(f, 0, 6) + >>> p, q = pade(a, 3, 3) + >>> x = 10 + >>> polyval(p[::-1], x)/polyval(q[::-1], x) + 1.38169105566806 + >>> f(x) + 1.38169855941551 + + """ + # To determine L+1 coefficients of P and M coefficients of Q + # L+M+1 coefficients of A must be provided + if len(a) < L+M+1: + raise ValueError("L+M+1 Coefficients should be provided") + + if M == 0: + if L == 0: + return [ctx.one], [ctx.one] + else: + return a[:L+1], [ctx.one] + + # Solve first + # a[L]*q[1] + ... + a[L-M+1]*q[M] = -a[L+1] + # ... + # a[L+M-1]*q[1] + ... + a[L]*q[M] = -a[L+M] + A = ctx.matrix(M) + for j in range(M): + for i in range(min(M, L+j+1)): + A[j, i] = a[L+j-i] + v = -ctx.matrix(a[(L+1):(L+M+1)]) + x = ctx.lu_solve(A, v) + q = [ctx.one] + list(x) + # compute p + p = [0]*(L+1) + for i in range(L+1): + s = a[i] + for j in range(1, min(M,i) + 1): + s += q[j]*a[i-j] + p[i] = s + return p, q diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/extrapolation.py b/venv/lib/python3.10/site-packages/mpmath/calculus/extrapolation.py new file mode 100644 index 0000000000000000000000000000000000000000..7df0fea3c62c9b71ee24d3f39fd9b7fd3318ed23 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/calculus/extrapolation.py @@ -0,0 +1,2115 @@ +try: + from itertools import izip +except ImportError: + izip = zip + +from ..libmp.backend import xrange +from .calculus import defun + +try: + next = next +except NameError: + next = lambda _: _.next() + +@defun +def richardson(ctx, seq): + r""" + Given a list ``seq`` of the first `N` elements of a slowly convergent + infinite sequence, :func:`~mpmath.richardson` computes the `N`-term + Richardson extrapolate for the limit. + + :func:`~mpmath.richardson` returns `(v, c)` where `v` is the estimated + limit and `c` is the magnitude of the largest weight used during the + computation. The weight provides an estimate of the precision + lost to cancellation. Due to cancellation effects, the sequence must + be typically be computed at a much higher precision than the target + accuracy of the extrapolation. + + **Applicability and issues** + + The `N`-step Richardson extrapolation algorithm used by + :func:`~mpmath.richardson` is described in [1]. + + Richardson extrapolation only works for a specific type of sequence, + namely one converging like partial sums of + `P(1)/Q(1) + P(2)/Q(2) + \ldots` where `P` and `Q` are polynomials. + When the sequence does not convergence at such a rate + :func:`~mpmath.richardson` generally produces garbage. + + Richardson extrapolation has the advantage of being fast: the `N`-term + extrapolate requires only `O(N)` arithmetic operations, and usually + produces an estimate that is accurate to `O(N)` digits. Contrast with + the Shanks transformation (see :func:`~mpmath.shanks`), which requires + `O(N^2)` operations. + + :func:`~mpmath.richardson` is unable to produce an estimate for the + approximation error. One way to estimate the error is to perform + two extrapolations with slightly different `N` and comparing the + results. + + Richardson extrapolation does not work for oscillating sequences. + As a simple workaround, :func:`~mpmath.richardson` detects if the last + three elements do not differ monotonically, and in that case + applies extrapolation only to the even-index elements. + + **Example** + + Applying Richardson extrapolation to the Leibniz series for `\pi`:: + + >>> from mpmath import * + >>> mp.dps = 30; mp.pretty = True + >>> S = [4*sum(mpf(-1)**n/(2*n+1) for n in range(m)) + ... for m in range(1,30)] + >>> v, c = richardson(S[:10]) + >>> v + 3.2126984126984126984126984127 + >>> nprint([v-pi, c]) + [0.0711058, 2.0] + + >>> v, c = richardson(S[:30]) + >>> v + 3.14159265468624052829954206226 + >>> nprint([v-pi, c]) + [1.09645e-9, 20833.3] + + **References** + + 1. [BenderOrszag]_ pp. 375-376 + + """ + if len(seq) < 3: + raise ValueError("seq should be of minimum length 3") + if ctx.sign(seq[-1]-seq[-2]) != ctx.sign(seq[-2]-seq[-3]): + seq = seq[::2] + N = len(seq)//2-1 + s = ctx.zero + # The general weight is c[k] = (N+k)**N * (-1)**(k+N) / k! / (N-k)! + # To avoid repeated factorials, we simplify the quotient + # of successive weights to obtain a recurrence relation + c = (-1)**N * N**N / ctx.mpf(ctx._ifac(N)) + maxc = 1 + for k in xrange(N+1): + s += c * seq[N+k] + maxc = max(abs(c), maxc) + c *= (k-N)*ctx.mpf(k+N+1)**N + c /= ((1+k)*ctx.mpf(k+N)**N) + return s, maxc + +@defun +def shanks(ctx, seq, table=None, randomized=False): + r""" + Given a list ``seq`` of the first `N` elements of a slowly + convergent infinite sequence `(A_k)`, :func:`~mpmath.shanks` computes the iterated + Shanks transformation `S(A), S(S(A)), \ldots, S^{N/2}(A)`. The Shanks + transformation often provides strong convergence acceleration, + especially if the sequence is oscillating. + + The iterated Shanks transformation is computed using the Wynn + epsilon algorithm (see [1]). :func:`~mpmath.shanks` returns the full + epsilon table generated by Wynn's algorithm, which can be read + off as follows: + + * The table is a list of lists forming a lower triangular matrix, + where higher row and column indices correspond to more accurate + values. + * The columns with even index hold dummy entries (required for the + computation) and the columns with odd index hold the actual + extrapolates. + * The last element in the last row is typically the most + accurate estimate of the limit. + * The difference to the third last element in the last row + provides an estimate of the approximation error. + * The magnitude of the second last element provides an estimate + of the numerical accuracy lost to cancellation. + + For convenience, so the extrapolation is stopped at an odd index + so that ``shanks(seq)[-1][-1]`` always gives an estimate of the + limit. + + Optionally, an existing table can be passed to :func:`~mpmath.shanks`. + This can be used to efficiently extend a previous computation after + new elements have been appended to the sequence. The table will + then be updated in-place. + + **The Shanks transformation** + + The Shanks transformation is defined as follows (see [2]): given + the input sequence `(A_0, A_1, \ldots)`, the transformed sequence is + given by + + .. math :: + + S(A_k) = \frac{A_{k+1}A_{k-1}-A_k^2}{A_{k+1}+A_{k-1}-2 A_k} + + The Shanks transformation gives the exact limit `A_{\infty}` in a + single step if `A_k = A + a q^k`. Note in particular that it + extrapolates the exact sum of a geometric series in a single step. + + Applying the Shanks transformation once often improves convergence + substantially for an arbitrary sequence, but the optimal effect is + obtained by applying it iteratively: + `S(S(A_k)), S(S(S(A_k))), \ldots`. + + Wynn's epsilon algorithm provides an efficient way to generate + the table of iterated Shanks transformations. It reduces the + computation of each element to essentially a single division, at + the cost of requiring dummy elements in the table. See [1] for + details. + + **Precision issues** + + Due to cancellation effects, the sequence must be typically be + computed at a much higher precision than the target accuracy + of the extrapolation. + + If the Shanks transformation converges to the exact limit (such + as if the sequence is a geometric series), then a division by + zero occurs. By default, :func:`~mpmath.shanks` handles this case by + terminating the iteration and returning the table it has + generated so far. With *randomized=True*, it will instead + replace the zero by a pseudorandom number close to zero. + (TODO: find a better solution to this problem.) + + **Examples** + + We illustrate by applying Shanks transformation to the Leibniz + series for `\pi`:: + + >>> from mpmath import * + >>> mp.dps = 50 + >>> S = [4*sum(mpf(-1)**n/(2*n+1) for n in range(m)) + ... for m in range(1,30)] + >>> + >>> T = shanks(S[:7]) + >>> for row in T: + ... nprint(row) + ... + [-0.75] + [1.25, 3.16667] + [-1.75, 3.13333, -28.75] + [2.25, 3.14524, 82.25, 3.14234] + [-2.75, 3.13968, -177.75, 3.14139, -969.937] + [3.25, 3.14271, 327.25, 3.14166, 3515.06, 3.14161] + + The extrapolated accuracy is about 4 digits, and about 4 digits + may have been lost due to cancellation:: + + >>> L = T[-1] + >>> nprint([abs(L[-1] - pi), abs(L[-1] - L[-3]), abs(L[-2])]) + [2.22532e-5, 4.78309e-5, 3515.06] + + Now we extend the computation:: + + >>> T = shanks(S[:25], T) + >>> L = T[-1] + >>> nprint([abs(L[-1] - pi), abs(L[-1] - L[-3]), abs(L[-2])]) + [3.75527e-19, 1.48478e-19, 2.96014e+17] + + The value for pi is now accurate to 18 digits. About 18 digits may + also have been lost to cancellation. + + Here is an example with a geometric series, where the convergence + is immediate (the sum is exactly 1):: + + >>> mp.dps = 15 + >>> for row in shanks([0.5, 0.75, 0.875, 0.9375, 0.96875]): + ... nprint(row) + [4.0] + [8.0, 1.0] + + **References** + + 1. [GravesMorris]_ + + 2. [BenderOrszag]_ pp. 368-375 + + """ + if len(seq) < 2: + raise ValueError("seq should be of minimum length 2") + if table: + START = len(table) + else: + START = 0 + table = [] + STOP = len(seq) - 1 + if STOP & 1: + STOP -= 1 + one = ctx.one + eps = +ctx.eps + if randomized: + from random import Random + rnd = Random() + rnd.seed(START) + for i in xrange(START, STOP): + row = [] + for j in xrange(i+1): + if j == 0: + a, b = 0, seq[i+1]-seq[i] + else: + if j == 1: + a = seq[i] + else: + a = table[i-1][j-2] + b = row[j-1] - table[i-1][j-1] + if not b: + if randomized: + b = (1 + rnd.getrandbits(10))*eps + elif i & 1: + return table[:-1] + else: + return table + row.append(a + one/b) + table.append(row) + return table + + +class levin_class: + # levin: Copyright 2013 Timo Hartmann (thartmann15 at gmail.com) + r""" + This interface implements Levin's (nonlinear) sequence transformation for + convergence acceleration and summation of divergent series. It performs + better than the Shanks/Wynn-epsilon algorithm for logarithmic convergent + or alternating divergent series. + + Let *A* be the series we want to sum: + + .. math :: + + A = \sum_{k=0}^{\infty} a_k + + Attention: all `a_k` must be non-zero! + + Let `s_n` be the partial sums of this series: + + .. math :: + + s_n = \sum_{k=0}^n a_k. + + **Methods** + + Calling ``levin`` returns an object with the following methods. + + ``update(...)`` works with the list of individual terms `a_k` of *A*, and + ``update_step(...)`` works with the list of partial sums `s_k` of *A*: + + .. code :: + + v, e = ...update([a_0, a_1,..., a_k]) + v, e = ...update_psum([s_0, s_1,..., s_k]) + + ``step(...)`` works with the individual terms `a_k` and ``step_psum(...)`` + works with the partial sums `s_k`: + + .. code :: + + v, e = ...step(a_k) + v, e = ...step_psum(s_k) + + *v* is the current estimate for *A*, and *e* is an error estimate which is + simply the difference between the current estimate and the last estimate. + One should not mix ``update``, ``update_psum``, ``step`` and ``step_psum``. + + **A word of caution** + + One can only hope for good results (i.e. convergence acceleration or + resummation) if the `s_n` have some well defind asymptotic behavior for + large `n` and are not erratic or random. Furthermore one usually needs very + high working precision because of the numerical cancellation. If the working + precision is insufficient, levin may produce silently numerical garbage. + Furthermore even if the Levin-transformation converges, in the general case + there is no proof that the result is mathematically sound. Only for very + special classes of problems one can prove that the Levin-transformation + converges to the expected result (for example Stieltjes-type integrals). + Furthermore the Levin-transform is quite expensive (i.e. slow) in comparison + to Shanks/Wynn-epsilon, Richardson & co. + In summary one can say that the Levin-transformation is powerful but + unreliable and that it may need a copious amount of working precision. + + The Levin transform has several variants differing in the choice of weights. + Some variants are better suited for the possible flavours of convergence + behaviour of *A* than other variants: + + .. code :: + + convergence behaviour levin-u levin-t levin-v shanks/wynn-epsilon + + logarithmic + - + - + linear + + + + + alternating divergent + + + + + + "+" means the variant is suitable,"-" means the variant is not suitable; + for comparison the Shanks/Wynn-epsilon transform is listed, too. + + The variant is controlled though the variant keyword (i.e. ``variant="u"``, + ``variant="t"`` or ``variant="v"``). Overall "u" is probably the best choice. + + Finally it is possible to use the Sidi-S transform instead of the Levin transform + by using the keyword ``method='sidi'``. The Sidi-S transform works better than the + Levin transformation for some divergent series (see the examples). + + Parameters: + + .. code :: + + method "levin" or "sidi" chooses either the Levin or the Sidi-S transformation + variant "u","t" or "v" chooses the weight variant. + + The Levin transform is also accessible through the nsum interface. + ``method="l"`` or ``method="levin"`` select the normal Levin transform while + ``method="sidi"`` + selects the Sidi-S transform. The variant is in both cases selected through the + levin_variant keyword. The stepsize in :func:`~mpmath.nsum` must not be chosen too large, otherwise + it will miss the point where the Levin transform converges resulting in numerical + overflow/garbage. For highly divergent series a copious amount of working precision + must be chosen. + + **Examples** + + First we sum the zeta function:: + + >>> from mpmath import mp + >>> mp.prec = 53 + >>> eps = mp.mpf(mp.eps) + >>> with mp.extraprec(2 * mp.prec): # levin needs a high working precision + ... L = mp.levin(method = "levin", variant = "u") + ... S, s, n = [], 0, 1 + ... while 1: + ... s += mp.one / (n * n) + ... n += 1 + ... S.append(s) + ... v, e = L.update_psum(S) + ... if e < eps: + ... break + ... if n > 1000: raise RuntimeError("iteration limit exceeded") + >>> print(mp.chop(v - mp.pi ** 2 / 6)) + 0.0 + >>> w = mp.nsum(lambda n: 1 / (n*n), [1, mp.inf], method = "levin", levin_variant = "u") + >>> print(mp.chop(v - w)) + 0.0 + + Now we sum the zeta function outside its range of convergence + (attention: This does not work at the negative integers!):: + + >>> eps = mp.mpf(mp.eps) + >>> with mp.extraprec(2 * mp.prec): # levin needs a high working precision + ... L = mp.levin(method = "levin", variant = "v") + ... A, n = [], 1 + ... while 1: + ... s = mp.mpf(n) ** (2 + 3j) + ... n += 1 + ... A.append(s) + ... v, e = L.update(A) + ... if e < eps: + ... break + ... if n > 1000: raise RuntimeError("iteration limit exceeded") + >>> print(mp.chop(v - mp.zeta(-2-3j))) + 0.0 + >>> w = mp.nsum(lambda n: n ** (2 + 3j), [1, mp.inf], method = "levin", levin_variant = "v") + >>> print(mp.chop(v - w)) + 0.0 + + Now we sum the divergent asymptotic expansion of an integral related to the + exponential integral (see also [2] p.373). The Sidi-S transform works best here:: + + >>> z = mp.mpf(10) + >>> exact = mp.quad(lambda x: mp.exp(-x)/(1+x/z),[0,mp.inf]) + >>> # exact = z * mp.exp(z) * mp.expint(1,z) # this is the symbolic expression for the integral + >>> eps = mp.mpf(mp.eps) + >>> with mp.extraprec(2 * mp.prec): # high working precisions are mandatory for divergent resummation + ... L = mp.levin(method = "sidi", variant = "t") + ... n = 0 + ... while 1: + ... s = (-1)**n * mp.fac(n) * z ** (-n) + ... v, e = L.step(s) + ... n += 1 + ... if e < eps: + ... break + ... if n > 1000: raise RuntimeError("iteration limit exceeded") + >>> print(mp.chop(v - exact)) + 0.0 + >>> w = mp.nsum(lambda n: (-1) ** n * mp.fac(n) * z ** (-n), [0, mp.inf], method = "sidi", levin_variant = "t") + >>> print(mp.chop(v - w)) + 0.0 + + Another highly divergent integral is also summable:: + + >>> z = mp.mpf(2) + >>> eps = mp.mpf(mp.eps) + >>> exact = mp.quad(lambda x: mp.exp( -x * x / 2 - z * x ** 4), [0,mp.inf]) * 2 / mp.sqrt(2 * mp.pi) + >>> # exact = mp.exp(mp.one / (32 * z)) * mp.besselk(mp.one / 4, mp.one / (32 * z)) / (4 * mp.sqrt(z * mp.pi)) # this is the symbolic expression for the integral + >>> with mp.extraprec(7 * mp.prec): # we need copious amount of precision to sum this highly divergent series + ... L = mp.levin(method = "levin", variant = "t") + ... n, s = 0, 0 + ... while 1: + ... s += (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n)) + ... n += 1 + ... v, e = L.step_psum(s) + ... if e < eps: + ... break + ... if n > 1000: raise RuntimeError("iteration limit exceeded") + >>> print(mp.chop(v - exact)) + 0.0 + >>> w = mp.nsum(lambda n: (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n)), + ... [0, mp.inf], method = "levin", levin_variant = "t", workprec = 8*mp.prec, steps = [2] + [1 for x in xrange(1000)]) + >>> print(mp.chop(v - w)) + 0.0 + + These examples run with 15-20 decimal digits precision. For higher precision the + working precision must be raised. + + **Examples for nsum** + + Here we calculate Euler's constant as the constant term in the Laurent + expansion of `\zeta(s)` at `s=1`. This sum converges extremly slowly because of + the logarithmic convergence behaviour of the Dirichlet series for zeta:: + + >>> mp.dps = 30 + >>> z = mp.mpf(10) ** (-10) + >>> a = mp.nsum(lambda n: n**(-(1+z)), [1, mp.inf], method = "l") - 1 / z + >>> print(mp.chop(a - mp.euler, tol = 1e-10)) + 0.0 + + The Sidi-S transform performs excellently for the alternating series of `\log(2)`:: + + >>> a = mp.nsum(lambda n: (-1)**(n-1) / n, [1, mp.inf], method = "sidi") + >>> print(mp.chop(a - mp.log(2))) + 0.0 + + Hypergeometric series can also be summed outside their range of convergence. + The stepsize in :func:`~mpmath.nsum` must not be chosen too large, otherwise it will miss the + point where the Levin transform converges resulting in numerical overflow/garbage:: + + >>> z = 2 + 1j + >>> exact = mp.hyp2f1(2 / mp.mpf(3), 4 / mp.mpf(3), 1 / mp.mpf(3), z) + >>> f = lambda n: mp.rf(2 / mp.mpf(3), n) * mp.rf(4 / mp.mpf(3), n) * z**n / (mp.rf(1 / mp.mpf(3), n) * mp.fac(n)) + >>> v = mp.nsum(f, [0, mp.inf], method = "levin", steps = [10 for x in xrange(1000)]) + >>> print(mp.chop(exact-v)) + 0.0 + + References: + + [1] E.J. Weniger - "Nonlinear Sequence Transformations for the Acceleration of + Convergence and the Summation of Divergent Series" arXiv:math/0306302 + + [2] A. Sidi - "Pratical Extrapolation Methods" + + [3] H.H.H. Homeier - "Scalar Levin-Type Sequence Transformations" arXiv:math/0005209 + + """ + + def __init__(self, method = "levin", variant = "u"): + self.variant = variant + self.n = 0 + self.a0 = 0 + self.theta = 1 + self.A = [] + self.B = [] + self.last = 0 + self.last_s = False + + if method == "levin": + self.factor = self.factor_levin + elif method == "sidi": + self.factor = self.factor_sidi + else: + raise ValueError("levin: unknown method \"%s\"" % method) + + def factor_levin(self, i): + # original levin + # [1] p.50,e.7.5-7 (with n-j replaced by i) + return (self.theta + i) * (self.theta + self.n - 1) ** (self.n - i - 2) / self.ctx.mpf(self.theta + self.n) ** (self.n - i - 1) + + def factor_sidi(self, i): + # sidi analogon to levin (factorial series) + # [1] p.59,e.8.3-16 (with n-j replaced by i) + return (self.theta + self.n - 1) * (self.theta + self.n - 2) / self.ctx.mpf((self.theta + 2 * self.n - i - 2) * (self.theta + 2 * self.n - i - 3)) + + def run(self, s, a0, a1 = 0): + if self.variant=="t": + # levin t + w=a0 + elif self.variant=="u": + # levin u + w=a0*(self.theta+self.n) + elif self.variant=="v": + # levin v + w=a0*a1/(a0-a1) + else: + assert False, "unknown variant" + + if w==0: + raise ValueError("levin: zero weight") + + self.A.append(s/w) + self.B.append(1/w) + + for i in range(self.n-1,-1,-1): + if i==self.n-1: + f=1 + else: + f=self.factor(i) + + self.A[i]=self.A[i+1]-f*self.A[i] + self.B[i]=self.B[i+1]-f*self.B[i] + + self.n+=1 + + ########################################################################### + + def update_psum(self,S): + """ + This routine applies the convergence acceleration to the list of partial sums. + + A = sum(a_k, k = 0..infinity) + s_n = sum(a_k, k = 0..n) + + v, e = ...update_psum([s_0, s_1,..., s_k]) + + output: + v current estimate of the series A + e an error estimate which is simply the difference between the current + estimate and the last estimate. + """ + + if self.variant!="v": + if self.n==0: + self.run(S[0],S[0]) + while self.n>> from mpmath import mp + >>> AC = mp.cohen_alt() + >>> S, s, n = [], 0, 1 + >>> while 1: + ... s += -((-1) ** n) * mp.one / (n * n) + ... n += 1 + ... S.append(s) + ... v, e = AC.update_psum(S) + ... if e < mp.eps: + ... break + ... if n > 1000: raise RuntimeError("iteration limit exceeded") + >>> print(mp.chop(v - mp.pi ** 2 / 12)) + 0.0 + + Here we compute the product `\prod_{n=1}^{\infty} \Gamma(1+1/(2n-1)) / \Gamma(1+1/(2n))`:: + + >>> A = [] + >>> AC = mp.cohen_alt() + >>> n = 1 + >>> while 1: + ... A.append( mp.loggamma(1 + mp.one / (2 * n - 1))) + ... A.append(-mp.loggamma(1 + mp.one / (2 * n))) + ... n += 1 + ... v, e = AC.update(A) + ... if e < mp.eps: + ... break + ... if n > 1000: raise RuntimeError("iteration limit exceeded") + >>> v = mp.exp(v) + >>> print(mp.chop(v - 1.06215090557106, tol = 1e-12)) + 0.0 + + ``cohen_alt`` is also accessible through the :func:`~mpmath.nsum` interface:: + + >>> v = mp.nsum(lambda n: (-1)**(n-1) / n, [1, mp.inf], method = "a") + >>> print(mp.chop(v - mp.log(2))) + 0.0 + >>> v = mp.nsum(lambda n: (-1)**n / (2 * n + 1), [0, mp.inf], method = "a") + >>> print(mp.chop(v - mp.pi / 4)) + 0.0 + >>> v = mp.nsum(lambda n: (-1)**n * mp.log(n) * n, [1, mp.inf], method = "a") + >>> print(mp.chop(v - mp.diff(lambda s: mp.altzeta(s), -1))) + 0.0 + + """ + + def __init__(self): + self.last=0 + + def update(self, A): + """ + This routine applies the convergence acceleration to the list of individual terms. + + A = sum(a_k, k = 0..infinity) + + v, e = ...update([a_0, a_1,..., a_k]) + + output: + v current estimate of the series A + e an error estimate which is simply the difference between the current + estimate and the last estimate. + """ + + n = len(A) + d = (3 + self.ctx.sqrt(8)) ** n + d = (d + 1 / d) / 2 + b = -self.ctx.one + c = -d + s = 0 + + for k in xrange(n): + c = b - c + if k % 2 == 0: + s = s + c * A[k] + else: + s = s - c * A[k] + b = 2 * (k + n) * (k - n) * b / ((2 * k + 1) * (k + self.ctx.one)) + + value = s / d + + err = abs(value - self.last) + self.last = value + + return value, err + + def update_psum(self, S): + """ + This routine applies the convergence acceleration to the list of partial sums. + + A = sum(a_k, k = 0..infinity) + s_n = sum(a_k ,k = 0..n) + + v, e = ...update_psum([s_0, s_1,..., s_k]) + + output: + v current estimate of the series A + e an error estimate which is simply the difference between the current + estimate and the last estimate. + """ + + n = len(S) + d = (3 + self.ctx.sqrt(8)) ** n + d = (d + 1 / d) / 2 + b = self.ctx.one + s = 0 + + for k in xrange(n): + b = 2 * (n + k) * (n - k) * b / ((2 * k + 1) * (k + self.ctx.one)) + s += b * S[k] + + value = s / d + + err = abs(value - self.last) + self.last = value + + return value, err + +def cohen_alt(ctx): + L = cohen_alt_class() + L.ctx = ctx + return L + +cohen_alt.__doc__ = cohen_alt_class.__doc__ +defun(cohen_alt) + + +@defun +def sumap(ctx, f, interval, integral=None, error=False): + r""" + Evaluates an infinite series of an analytic summand *f* using the + Abel-Plana formula + + .. math :: + + \sum_{k=0}^{\infty} f(k) = \int_0^{\infty} f(t) dt + \frac{1}{2} f(0) + + i \int_0^{\infty} \frac{f(it)-f(-it)}{e^{2\pi t}-1} dt. + + Unlike the Euler-Maclaurin formula (see :func:`~mpmath.sumem`), + the Abel-Plana formula does not require derivatives. However, + it only works when `|f(it)-f(-it)|` does not + increase too rapidly with `t`. + + **Examples** + + The Abel-Plana formula is particularly useful when the summand + decreases like a power of `k`; for example when the sum is a pure + zeta function:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> sumap(lambda k: 1/k**2.5, [1,inf]) + 1.34148725725091717975677 + >>> zeta(2.5) + 1.34148725725091717975677 + >>> sumap(lambda k: 1/(k+1j)**(2.5+2.5j), [1,inf]) + (-3.385361068546473342286084 - 0.7432082105196321803869551j) + >>> zeta(2.5+2.5j, 1+1j) + (-3.385361068546473342286084 - 0.7432082105196321803869551j) + + If the series is alternating, numerical quadrature along the real + line is likely to give poor results, so it is better to evaluate + the first term symbolically whenever possible: + + >>> n=3; z=-0.75 + >>> I = expint(n,-log(z)) + >>> chop(sumap(lambda k: z**k / k**n, [1,inf], integral=I)) + -0.6917036036904594510141448 + >>> polylog(n,z) + -0.6917036036904594510141448 + + """ + prec = ctx.prec + try: + ctx.prec += 10 + a, b = interval + if b != ctx.inf: + raise ValueError("b should be equal to ctx.inf") + g = lambda x: f(x+a) + if integral is None: + i1, err1 = ctx.quad(g, [0,ctx.inf], error=True) + else: + i1, err1 = integral, 0 + j = ctx.j + p = ctx.pi * 2 + if ctx._is_real_type(i1): + h = lambda t: -2 * ctx.im(g(j*t)) / ctx.expm1(p*t) + else: + h = lambda t: j*(g(j*t)-g(-j*t)) / ctx.expm1(p*t) + i2, err2 = ctx.quad(h, [0,ctx.inf], error=True) + err = err1+err2 + v = i1+i2+0.5*g(ctx.mpf(0)) + finally: + ctx.prec = prec + if error: + return +v, err + return +v + + +@defun +def sumem(ctx, f, interval, tol=None, reject=10, integral=None, + adiffs=None, bdiffs=None, verbose=False, error=False, + _fast_abort=False): + r""" + Uses the Euler-Maclaurin formula to compute an approximation accurate + to within ``tol`` (which defaults to the present epsilon) of the sum + + .. math :: + + S = \sum_{k=a}^b f(k) + + where `(a,b)` are given by ``interval`` and `a` or `b` may be + infinite. The approximation is + + .. math :: + + S \sim \int_a^b f(x) \,dx + \frac{f(a)+f(b)}{2} + + \sum_{k=1}^{\infty} \frac{B_{2k}}{(2k)!} + \left(f^{(2k-1)}(b)-f^{(2k-1)}(a)\right). + + The last sum in the Euler-Maclaurin formula is not generally + convergent (a notable exception is if `f` is a polynomial, in + which case Euler-Maclaurin actually gives an exact result). + + The summation is stopped as soon as the quotient between two + consecutive terms falls below *reject*. That is, by default + (*reject* = 10), the summation is continued as long as each + term adds at least one decimal. + + Although not convergent, convergence to a given tolerance can + often be "forced" if `b = \infty` by summing up to `a+N` and then + applying the Euler-Maclaurin formula to the sum over the range + `(a+N+1, \ldots, \infty)`. This procedure is implemented by + :func:`~mpmath.nsum`. + + By default numerical quadrature and differentiation is used. + If the symbolic values of the integral and endpoint derivatives + are known, it is more efficient to pass the value of the + integral explicitly as ``integral`` and the derivatives + explicitly as ``adiffs`` and ``bdiffs``. The derivatives + should be given as iterables that yield + `f(a), f'(a), f''(a), \ldots` (and the equivalent for `b`). + + **Examples** + + Summation of an infinite series, with automatic and symbolic + integral and derivative values (the second should be much faster):: + + >>> from mpmath import * + >>> mp.dps = 50; mp.pretty = True + >>> sumem(lambda n: 1/n**2, [32, inf]) + 0.03174336652030209012658168043874142714132886413417 + >>> I = mpf(1)/32 + >>> D = adiffs=((-1)**n*fac(n+1)*32**(-2-n) for n in range(999)) + >>> sumem(lambda n: 1/n**2, [32, inf], integral=I, adiffs=D) + 0.03174336652030209012658168043874142714132886413417 + + An exact evaluation of a finite polynomial sum:: + + >>> sumem(lambda n: n**5-12*n**2+3*n, [-100000, 200000]) + 10500155000624963999742499550000.0 + >>> print(sum(n**5-12*n**2+3*n for n in range(-100000, 200001))) + 10500155000624963999742499550000 + + """ + tol = tol or +ctx.eps + interval = ctx._as_points(interval) + a = ctx.convert(interval[0]) + b = ctx.convert(interval[-1]) + err = ctx.zero + prev = 0 + M = 10000 + if a == ctx.ninf: adiffs = (0 for n in xrange(M)) + else: adiffs = adiffs or ctx.diffs(f, a) + if b == ctx.inf: bdiffs = (0 for n in xrange(M)) + else: bdiffs = bdiffs or ctx.diffs(f, b) + orig = ctx.prec + #verbose = 1 + try: + ctx.prec += 10 + s = ctx.zero + for k, (da, db) in enumerate(izip(adiffs, bdiffs)): + if k & 1: + term = (db-da) * ctx.bernoulli(k+1) / ctx.factorial(k+1) + mag = abs(term) + if verbose: + print("term", k, "magnitude =", ctx.nstr(mag)) + if k > 4 and mag < tol: + s += term + break + elif k > 4 and abs(prev) / mag < reject: + err += mag + if _fast_abort: + return [s, (s, err)][error] + if verbose: + print("Failed to converge") + break + else: + s += term + prev = term + # Endpoint correction + if a != ctx.ninf: s += f(a)/2 + if b != ctx.inf: s += f(b)/2 + # Tail integral + if verbose: + print("Integrating f(x) from x = %s to %s" % (ctx.nstr(a), ctx.nstr(b))) + if integral: + s += integral + else: + integral, ierr = ctx.quad(f, interval, error=True) + if verbose: + print("Integration error:", ierr) + s += integral + err += ierr + finally: + ctx.prec = orig + if error: + return s, err + else: + return s + +@defun +def adaptive_extrapolation(ctx, update, emfun, kwargs): + option = kwargs.get + if ctx._fixed_precision: + tol = option('tol', ctx.eps*2**10) + else: + tol = option('tol', ctx.eps/2**10) + verbose = option('verbose', False) + maxterms = option('maxterms', ctx.dps*10) + method = set(option('method', 'r+s').split('+')) + skip = option('skip', 0) + steps = iter(option('steps', xrange(10, 10**9, 10))) + strict = option('strict') + #steps = (10 for i in xrange(1000)) + summer=[] + if 'd' in method or 'direct' in method: + TRY_RICHARDSON = TRY_SHANKS = TRY_EULER_MACLAURIN = False + else: + TRY_RICHARDSON = ('r' in method) or ('richardson' in method) + TRY_SHANKS = ('s' in method) or ('shanks' in method) + TRY_EULER_MACLAURIN = ('e' in method) or \ + ('euler-maclaurin' in method) + + def init_levin(m): + variant = kwargs.get("levin_variant", "u") + if isinstance(variant, str): + if variant == "all": + variant = ["u", "v", "t"] + else: + variant = [variant] + for s in variant: + L = levin_class(method = m, variant = s) + L.ctx = ctx + L.name = m + "(" + s + ")" + summer.append(L) + + if ('l' in method) or ('levin' in method): + init_levin("levin") + + if ('sidi' in method): + init_levin("sidi") + + if ('a' in method) or ('alternating' in method): + L = cohen_alt_class() + L.ctx = ctx + L.name = "alternating" + summer.append(L) + + last_richardson_value = 0 + shanks_table = [] + index = 0 + step = 10 + partial = [] + best = ctx.zero + orig = ctx.prec + try: + if 'workprec' in kwargs: + ctx.prec = kwargs['workprec'] + elif TRY_RICHARDSON or TRY_SHANKS or len(summer)!=0: + ctx.prec = (ctx.prec+10) * 4 + else: + ctx.prec += 30 + while 1: + if index >= maxterms: + break + + # Get new batch of terms + try: + step = next(steps) + except StopIteration: + pass + if verbose: + print("-"*70) + print("Adding terms #%i-#%i" % (index, index+step)) + update(partial, xrange(index, index+step)) + index += step + + # Check direct error + best = partial[-1] + error = abs(best - partial[-2]) + if verbose: + print("Direct error: %s" % ctx.nstr(error)) + if error <= tol: + return best + + # Check each extrapolation method + if TRY_RICHARDSON: + value, maxc = ctx.richardson(partial) + # Convergence + richardson_error = abs(value - last_richardson_value) + if verbose: + print("Richardson error: %s" % ctx.nstr(richardson_error)) + # Convergence + if richardson_error <= tol: + return value + last_richardson_value = value + # Unreliable due to cancellation + if ctx.eps*maxc > tol: + if verbose: + print("Ran out of precision for Richardson") + TRY_RICHARDSON = False + if richardson_error < error: + error = richardson_error + best = value + if TRY_SHANKS: + shanks_table = ctx.shanks(partial, shanks_table, randomized=True) + row = shanks_table[-1] + if len(row) == 2: + est1 = row[-1] + shanks_error = 0 + else: + est1, maxc, est2 = row[-1], abs(row[-2]), row[-3] + shanks_error = abs(est1-est2) + if verbose: + print("Shanks error: %s" % ctx.nstr(shanks_error)) + if shanks_error <= tol: + return est1 + if ctx.eps*maxc > tol: + if verbose: + print("Ran out of precision for Shanks") + TRY_SHANKS = False + if shanks_error < error: + error = shanks_error + best = est1 + for L in summer: + est, lerror = L.update_psum(partial) + if verbose: + print("%s error: %s" % (L.name, ctx.nstr(lerror))) + if lerror <= tol: + return est + if lerror < error: + error = lerror + best = est + if TRY_EULER_MACLAURIN: + if ctx.almosteq(ctx.mpc(ctx.sign(partial[-1]) / ctx.sign(partial[-2])), -1): + if verbose: + print ("NOT using Euler-Maclaurin: the series appears" + " to be alternating, so numerical\n quadrature" + " will most likely fail") + TRY_EULER_MACLAURIN = False + else: + value, em_error = emfun(index, tol) + value += partial[-1] + if verbose: + print("Euler-Maclaurin error: %s" % ctx.nstr(em_error)) + if em_error <= tol: + return value + if em_error < error: + best = value + finally: + ctx.prec = orig + if strict: + raise ctx.NoConvergence + if verbose: + print("Warning: failed to converge to target accuracy") + return best + +@defun +def nsum(ctx, f, *intervals, **options): + r""" + Computes the sum + + .. math :: S = \sum_{k=a}^b f(k) + + where `(a, b)` = *interval*, and where `a = -\infty` and/or + `b = \infty` are allowed, or more generally + + .. math :: S = \sum_{k_1=a_1}^{b_1} \cdots + \sum_{k_n=a_n}^{b_n} f(k_1,\ldots,k_n) + + if multiple intervals are given. + + Two examples of infinite series that can be summed by :func:`~mpmath.nsum`, + where the first converges rapidly and the second converges slowly, + are:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> nsum(lambda n: 1/fac(n), [0, inf]) + 2.71828182845905 + >>> nsum(lambda n: 1/n**2, [1, inf]) + 1.64493406684823 + + When appropriate, :func:`~mpmath.nsum` applies convergence acceleration to + accurately estimate the sums of slowly convergent series. If the series is + finite, :func:`~mpmath.nsum` currently does not attempt to perform any + extrapolation, and simply calls :func:`~mpmath.fsum`. + + Multidimensional infinite series are reduced to a single-dimensional + series over expanding hypercubes; if both infinite and finite dimensions + are present, the finite ranges are moved innermost. For more advanced + control over the summation order, use nested calls to :func:`~mpmath.nsum`, + or manually rewrite the sum as a single-dimensional series. + + **Options** + + *tol* + Desired maximum final error. Defaults roughly to the + epsilon of the working precision. + + *method* + Which summation algorithm to use (described below). + Default: ``'richardson+shanks'``. + + *maxterms* + Cancel after at most this many terms. Default: 10*dps. + + *steps* + An iterable giving the number of terms to add between + each extrapolation attempt. The default sequence is + [10, 20, 30, 40, ...]. For example, if you know that + approximately 100 terms will be required, efficiency might be + improved by setting this to [100, 10]. Then the first + extrapolation will be performed after 100 terms, the second + after 110, etc. + + *verbose* + Print details about progress. + + *ignore* + If enabled, any term that raises ``ArithmeticError`` + or ``ValueError`` (e.g. through division by zero) is replaced + by a zero. This is convenient for lattice sums with + a singular term near the origin. + + **Methods** + + Unfortunately, an algorithm that can efficiently sum any infinite + series does not exist. :func:`~mpmath.nsum` implements several different + algorithms that each work well in different cases. The *method* + keyword argument selects a method. + + The default method is ``'r+s'``, i.e. both Richardson extrapolation + and Shanks transformation is attempted. A slower method that + handles more cases is ``'r+s+e'``. For very high precision + summation, or if the summation needs to be fast (for example if + multiple sums need to be evaluated), it is a good idea to + investigate which one method works best and only use that. + + ``'richardson'`` / ``'r'``: + Uses Richardson extrapolation. Provides useful extrapolation + when `f(k) \sim P(k)/Q(k)` or when `f(k) \sim (-1)^k P(k)/Q(k)` + for polynomials `P` and `Q`. See :func:`~mpmath.richardson` for + additional information. + + ``'shanks'`` / ``'s'``: + Uses Shanks transformation. Typically provides useful + extrapolation when `f(k) \sim c^k` or when successive terms + alternate signs. Is able to sum some divergent series. + See :func:`~mpmath.shanks` for additional information. + + ``'levin'`` / ``'l'``: + Uses the Levin transformation. It performs better than the Shanks + transformation for logarithmic convergent or alternating divergent + series. The ``'levin_variant'``-keyword selects the variant. Valid + choices are "u", "t", "v" and "all" whereby "all" uses all three + u,t and v simultanously (This is good for performance comparison in + conjunction with "verbose=True"). Instead of the Levin transform one can + also use the Sidi-S transform by selecting the method ``'sidi'``. + See :func:`~mpmath.levin` for additional details. + + ``'alternating'`` / ``'a'``: + This is the convergence acceleration of alternating series developped + by Cohen, Villegras and Zagier. + See :func:`~mpmath.cohen_alt` for additional details. + + ``'euler-maclaurin'`` / ``'e'``: + Uses the Euler-Maclaurin summation formula to approximate + the remainder sum by an integral. This requires high-order + numerical derivatives and numerical integration. The advantage + of this algorithm is that it works regardless of the + decay rate of `f`, as long as `f` is sufficiently smooth. + See :func:`~mpmath.sumem` for additional information. + + ``'direct'`` / ``'d'``: + Does not perform any extrapolation. This can be used + (and should only be used for) rapidly convergent series. + The summation automatically stops when the terms + decrease below the target tolerance. + + **Basic examples** + + A finite sum:: + + >>> nsum(lambda k: 1/k, [1, 6]) + 2.45 + + Summation of a series going to negative infinity and a doubly + infinite series:: + + >>> nsum(lambda k: 1/k**2, [-inf, -1]) + 1.64493406684823 + >>> nsum(lambda k: 1/(1+k**2), [-inf, inf]) + 3.15334809493716 + + :func:`~mpmath.nsum` handles sums of complex numbers:: + + >>> nsum(lambda k: (0.5+0.25j)**k, [0, inf]) + (1.6 + 0.8j) + + The following sum converges very rapidly, so it is most + efficient to sum it by disabling convergence acceleration:: + + >>> mp.dps = 1000 + >>> a = nsum(lambda k: -(-1)**k * k**2 / fac(2*k), [1, inf], + ... method='direct') + >>> b = (cos(1)+sin(1))/4 + >>> abs(a-b) < mpf('1e-998') + True + + **Examples with Richardson extrapolation** + + Richardson extrapolation works well for sums over rational + functions, as well as their alternating counterparts:: + + >>> mp.dps = 50 + >>> nsum(lambda k: 1 / k**3, [1, inf], + ... method='richardson') + 1.2020569031595942853997381615114499907649862923405 + >>> zeta(3) + 1.2020569031595942853997381615114499907649862923405 + + >>> nsum(lambda n: (n + 3)/(n**3 + n**2), [1, inf], + ... method='richardson') + 2.9348022005446793094172454999380755676568497036204 + >>> pi**2/2-2 + 2.9348022005446793094172454999380755676568497036204 + + >>> nsum(lambda k: (-1)**k / k**3, [1, inf], + ... method='richardson') + -0.90154267736969571404980362113358749307373971925537 + >>> -3*zeta(3)/4 + -0.90154267736969571404980362113358749307373971925538 + + **Examples with Shanks transformation** + + The Shanks transformation works well for geometric series + and typically provides excellent acceleration for Taylor + series near the border of their disk of convergence. + Here we apply it to a series for `\log(2)`, which can be + seen as the Taylor series for `\log(1+x)` with `x = 1`:: + + >>> nsum(lambda k: -(-1)**k/k, [1, inf], + ... method='shanks') + 0.69314718055994530941723212145817656807550013436025 + >>> log(2) + 0.69314718055994530941723212145817656807550013436025 + + Here we apply it to a slowly convergent geometric series:: + + >>> nsum(lambda k: mpf('0.995')**k, [0, inf], + ... method='shanks') + 200.0 + + Finally, Shanks' method works very well for alternating series + where `f(k) = (-1)^k g(k)`, and often does so regardless of + the exact decay rate of `g(k)`:: + + >>> mp.dps = 15 + >>> nsum(lambda k: (-1)**(k+1) / k**1.5, [1, inf], + ... method='shanks') + 0.765147024625408 + >>> (2-sqrt(2))*zeta(1.5)/2 + 0.765147024625408 + + The following slowly convergent alternating series has no known + closed-form value. Evaluating the sum a second time at higher + precision indicates that the value is probably correct:: + + >>> nsum(lambda k: (-1)**k / log(k), [2, inf], + ... method='shanks') + 0.924299897222939 + >>> mp.dps = 30 + >>> nsum(lambda k: (-1)**k / log(k), [2, inf], + ... method='shanks') + 0.92429989722293885595957018136 + + **Examples with Levin transformation** + + The following example calculates Euler's constant as the constant term in + the Laurent expansion of zeta(s) at s=1. This sum converges extremly slow + because of the logarithmic convergence behaviour of the Dirichlet series + for zeta. + + >>> mp.dps = 30 + >>> z = mp.mpf(10) ** (-10) + >>> a = mp.nsum(lambda n: n**(-(1+z)), [1, mp.inf], method = "levin") - 1 / z + >>> print(mp.chop(a - mp.euler, tol = 1e-10)) + 0.0 + + Now we sum the zeta function outside its range of convergence + (attention: This does not work at the negative integers!): + + >>> mp.dps = 15 + >>> w = mp.nsum(lambda n: n ** (2 + 3j), [1, mp.inf], method = "levin", levin_variant = "v") + >>> print(mp.chop(w - mp.zeta(-2-3j))) + 0.0 + + The next example resummates an asymptotic series expansion of an integral + related to the exponential integral. + + >>> mp.dps = 15 + >>> z = mp.mpf(10) + >>> # exact = mp.quad(lambda x: mp.exp(-x)/(1+x/z),[0,mp.inf]) + >>> exact = z * mp.exp(z) * mp.expint(1,z) # this is the symbolic expression for the integral + >>> w = mp.nsum(lambda n: (-1) ** n * mp.fac(n) * z ** (-n), [0, mp.inf], method = "sidi", levin_variant = "t") + >>> print(mp.chop(w - exact)) + 0.0 + + Following highly divergent asymptotic expansion needs some care. Firstly we + need copious amount of working precision. Secondly the stepsize must not be + chosen to large, otherwise nsum may miss the point where the Levin transform + converges and reach the point where only numerical garbage is produced due to + numerical cancellation. + + >>> mp.dps = 15 + >>> z = mp.mpf(2) + >>> # exact = mp.quad(lambda x: mp.exp( -x * x / 2 - z * x ** 4), [0,mp.inf]) * 2 / mp.sqrt(2 * mp.pi) + >>> exact = mp.exp(mp.one / (32 * z)) * mp.besselk(mp.one / 4, mp.one / (32 * z)) / (4 * mp.sqrt(z * mp.pi)) # this is the symbolic expression for the integral + >>> w = mp.nsum(lambda n: (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n)), + ... [0, mp.inf], method = "levin", levin_variant = "t", workprec = 8*mp.prec, steps = [2] + [1 for x in xrange(1000)]) + >>> print(mp.chop(w - exact)) + 0.0 + + The hypergeoemtric function can also be summed outside its range of convergence: + + >>> mp.dps = 15 + >>> z = 2 + 1j + >>> exact = mp.hyp2f1(2 / mp.mpf(3), 4 / mp.mpf(3), 1 / mp.mpf(3), z) + >>> f = lambda n: mp.rf(2 / mp.mpf(3), n) * mp.rf(4 / mp.mpf(3), n) * z**n / (mp.rf(1 / mp.mpf(3), n) * mp.fac(n)) + >>> v = mp.nsum(f, [0, mp.inf], method = "levin", steps = [10 for x in xrange(1000)]) + >>> print(mp.chop(exact-v)) + 0.0 + + **Examples with Cohen's alternating series resummation** + + The next example sums the alternating zeta function: + + >>> v = mp.nsum(lambda n: (-1)**(n-1) / n, [1, mp.inf], method = "a") + >>> print(mp.chop(v - mp.log(2))) + 0.0 + + The derivate of the alternating zeta function outside its range of + convergence: + + >>> v = mp.nsum(lambda n: (-1)**n * mp.log(n) * n, [1, mp.inf], method = "a") + >>> print(mp.chop(v - mp.diff(lambda s: mp.altzeta(s), -1))) + 0.0 + + **Examples with Euler-Maclaurin summation** + + The sum in the following example has the wrong rate of convergence + for either Richardson or Shanks to be effective. + + >>> f = lambda k: log(k)/k**2.5 + >>> mp.dps = 15 + >>> nsum(f, [1, inf], method='euler-maclaurin') + 0.38734195032621 + >>> -diff(zeta, 2.5) + 0.38734195032621 + + Increasing ``steps`` improves speed at higher precision:: + + >>> mp.dps = 50 + >>> nsum(f, [1, inf], method='euler-maclaurin', steps=[250]) + 0.38734195032620997271199237593105101319948228874688 + >>> -diff(zeta, 2.5) + 0.38734195032620997271199237593105101319948228874688 + + **Divergent series** + + The Shanks transformation is able to sum some *divergent* + series. In particular, it is often able to sum Taylor series + beyond their radius of convergence (this is due to a relation + between the Shanks transformation and Pade approximations; + see :func:`~mpmath.pade` for an alternative way to evaluate divergent + Taylor series). Furthermore the Levin-transform examples above + contain some divergent series resummation. + + Here we apply it to `\log(1+x)` far outside the region of + convergence:: + + >>> mp.dps = 50 + >>> nsum(lambda k: -(-9)**k/k, [1, inf], + ... method='shanks') + 2.3025850929940456840179914546843642076011014886288 + >>> log(10) + 2.3025850929940456840179914546843642076011014886288 + + A particular type of divergent series that can be summed + using the Shanks transformation is geometric series. + The result is the same as using the closed-form formula + for an infinite geometric series:: + + >>> mp.dps = 15 + >>> for n in range(-8, 8): + ... if n == 1: + ... continue + ... print("%s %s %s" % (mpf(n), mpf(1)/(1-n), + ... nsum(lambda k: n**k, [0, inf], method='shanks'))) + ... + -8.0 0.111111111111111 0.111111111111111 + -7.0 0.125 0.125 + -6.0 0.142857142857143 0.142857142857143 + -5.0 0.166666666666667 0.166666666666667 + -4.0 0.2 0.2 + -3.0 0.25 0.25 + -2.0 0.333333333333333 0.333333333333333 + -1.0 0.5 0.5 + 0.0 1.0 1.0 + 2.0 -1.0 -1.0 + 3.0 -0.5 -0.5 + 4.0 -0.333333333333333 -0.333333333333333 + 5.0 -0.25 -0.25 + 6.0 -0.2 -0.2 + 7.0 -0.166666666666667 -0.166666666666667 + + **Multidimensional sums** + + Any combination of finite and infinite ranges is allowed for the + summation indices:: + + >>> mp.dps = 15 + >>> nsum(lambda x,y: x+y, [2,3], [4,5]) + 28.0 + >>> nsum(lambda x,y: x/2**y, [1,3], [1,inf]) + 6.0 + >>> nsum(lambda x,y: y/2**x, [1,inf], [1,3]) + 6.0 + >>> nsum(lambda x,y,z: z/(2**x*2**y), [1,inf], [1,inf], [3,4]) + 7.0 + >>> nsum(lambda x,y,z: y/(2**x*2**z), [1,inf], [3,4], [1,inf]) + 7.0 + >>> nsum(lambda x,y,z: x/(2**z*2**y), [3,4], [1,inf], [1,inf]) + 7.0 + + Some nice examples of double series with analytic solutions or + reductions to single-dimensional series (see [1]):: + + >>> nsum(lambda m, n: 1/2**(m*n), [1,inf], [1,inf]) + 1.60669515241529 + >>> nsum(lambda n: 1/(2**n-1), [1,inf]) + 1.60669515241529 + + >>> nsum(lambda i,j: (-1)**(i+j)/(i**2+j**2), [1,inf], [1,inf]) + 0.278070510848213 + >>> pi*(pi-3*ln2)/12 + 0.278070510848213 + + >>> nsum(lambda i,j: (-1)**(i+j)/(i+j)**2, [1,inf], [1,inf]) + 0.129319852864168 + >>> altzeta(2) - altzeta(1) + 0.129319852864168 + + >>> nsum(lambda i,j: (-1)**(i+j)/(i+j)**3, [1,inf], [1,inf]) + 0.0790756439455825 + >>> altzeta(3) - altzeta(2) + 0.0790756439455825 + + >>> nsum(lambda m,n: m**2*n/(3**m*(n*3**m+m*3**n)), + ... [1,inf], [1,inf]) + 0.28125 + >>> mpf(9)/32 + 0.28125 + + >>> nsum(lambda i,j: fac(i-1)*fac(j-1)/fac(i+j), + ... [1,inf], [1,inf], workprec=400) + 1.64493406684823 + >>> zeta(2) + 1.64493406684823 + + A hard example of a multidimensional sum is the Madelung constant + in three dimensions (see [2]). The defining sum converges very + slowly and only conditionally, so :func:`~mpmath.nsum` is lucky to + obtain an accurate value through convergence acceleration. The + second evaluation below uses a much more efficient, rapidly + convergent 2D sum:: + + >>> nsum(lambda x,y,z: (-1)**(x+y+z)/(x*x+y*y+z*z)**0.5, + ... [-inf,inf], [-inf,inf], [-inf,inf], ignore=True) + -1.74756459463318 + >>> nsum(lambda x,y: -12*pi*sech(0.5*pi * \ + ... sqrt((2*x+1)**2+(2*y+1)**2))**2, [0,inf], [0,inf]) + -1.74756459463318 + + Another example of a lattice sum in 2D:: + + >>> nsum(lambda x,y: (-1)**(x+y) / (x**2+y**2), [-inf,inf], + ... [-inf,inf], ignore=True) + -2.1775860903036 + >>> -pi*ln2 + -2.1775860903036 + + An example of an Eisenstein series:: + + >>> nsum(lambda m,n: (m+n*1j)**(-4), [-inf,inf], [-inf,inf], + ... ignore=True) + (3.1512120021539 + 0.0j) + + **References** + + 1. [Weisstein]_ http://mathworld.wolfram.com/DoubleSeries.html, + 2. [Weisstein]_ http://mathworld.wolfram.com/MadelungConstants.html + + """ + infinite, g = standardize(ctx, f, intervals, options) + if not infinite: + return +g() + + def update(partial_sums, indices): + if partial_sums: + psum = partial_sums[-1] + else: + psum = ctx.zero + for k in indices: + psum = psum + g(ctx.mpf(k)) + partial_sums.append(psum) + + prec = ctx.prec + + def emfun(point, tol): + workprec = ctx.prec + ctx.prec = prec + 10 + v = ctx.sumem(g, [point, ctx.inf], tol, error=1) + ctx.prec = workprec + return v + + return +ctx.adaptive_extrapolation(update, emfun, options) + + +def wrapsafe(f): + def g(*args): + try: + return f(*args) + except (ArithmeticError, ValueError): + return 0 + return g + +def standardize(ctx, f, intervals, options): + if options.get("ignore"): + f = wrapsafe(f) + finite = [] + infinite = [] + for k, points in enumerate(intervals): + a, b = ctx._as_points(points) + if b < a: + return False, (lambda: ctx.zero) + if a == ctx.ninf or b == ctx.inf: + infinite.append((k, (a,b))) + else: + finite.append((k, (int(a), int(b)))) + if finite: + f = fold_finite(ctx, f, finite) + if not infinite: + return False, lambda: f(*([0]*len(intervals))) + if infinite: + f = standardize_infinite(ctx, f, infinite) + f = fold_infinite(ctx, f, infinite) + args = [0] * len(intervals) + d = infinite[0][0] + def g(k): + args[d] = k + return f(*args) + return True, g + +# backwards compatible itertools.product +def cartesian_product(args): + pools = map(tuple, args) + result = [[]] + for pool in pools: + result = [x+[y] for x in result for y in pool] + for prod in result: + yield tuple(prod) + +def fold_finite(ctx, f, intervals): + if not intervals: + return f + indices = [v[0] for v in intervals] + points = [v[1] for v in intervals] + ranges = [xrange(a, b+1) for (a,b) in points] + def g(*args): + args = list(args) + s = ctx.zero + for xs in cartesian_product(ranges): + for dim, x in zip(indices, xs): + args[dim] = ctx.mpf(x) + s += f(*args) + return s + #print "Folded finite", indices + return g + +# Standardize each interval to [0,inf] +def standardize_infinite(ctx, f, intervals): + if not intervals: + return f + dim, [a,b] = intervals[-1] + if a == ctx.ninf: + if b == ctx.inf: + def g(*args): + args = list(args) + k = args[dim] + if k: + s = f(*args) + args[dim] = -k + s += f(*args) + return s + else: + return f(*args) + else: + def g(*args): + args = list(args) + args[dim] = b - args[dim] + return f(*args) + else: + def g(*args): + args = list(args) + args[dim] += a + return f(*args) + #print "Standardized infinity along dimension", dim, a, b + return standardize_infinite(ctx, g, intervals[:-1]) + +def fold_infinite(ctx, f, intervals): + if len(intervals) < 2: + return f + dim1 = intervals[-2][0] + dim2 = intervals[-1][0] + # Assume intervals are [0,inf] x [0,inf] x ... + def g(*args): + args = list(args) + #args.insert(dim2, None) + n = int(args[dim1]) + s = ctx.zero + #y = ctx.mpf(n) + args[dim2] = ctx.mpf(n) #y + for x in xrange(n+1): + args[dim1] = ctx.mpf(x) + s += f(*args) + args[dim1] = ctx.mpf(n) #ctx.mpf(n) + for y in xrange(n): + args[dim2] = ctx.mpf(y) + s += f(*args) + return s + #print "Folded infinite from", len(intervals), "to", (len(intervals)-1) + return fold_infinite(ctx, g, intervals[:-1]) + +@defun +def nprod(ctx, f, interval, nsum=False, **kwargs): + r""" + Computes the product + + .. math :: + + P = \prod_{k=a}^b f(k) + + where `(a, b)` = *interval*, and where `a = -\infty` and/or + `b = \infty` are allowed. + + By default, :func:`~mpmath.nprod` uses the same extrapolation methods as + :func:`~mpmath.nsum`, except applied to the partial products rather than + partial sums, and the same keyword options as for :func:`~mpmath.nsum` are + supported. If ``nsum=True``, the product is instead computed via + :func:`~mpmath.nsum` as + + .. math :: + + P = \exp\left( \sum_{k=a}^b \log(f(k)) \right). + + This is slower, but can sometimes yield better results. It is + also required (and used automatically) when Euler-Maclaurin + summation is requested. + + **Examples** + + A simple finite product:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> nprod(lambda k: k, [1, 4]) + 24.0 + + A large number of infinite products have known exact values, + and can therefore be used as a reference. Most of the following + examples are taken from MathWorld [1]. + + A few infinite products with simple values are:: + + >>> 2*nprod(lambda k: (4*k**2)/(4*k**2-1), [1, inf]) + 3.141592653589793238462643 + >>> nprod(lambda k: (1+1/k)**2/(1+2/k), [1, inf]) + 2.0 + >>> nprod(lambda k: (k**3-1)/(k**3+1), [2, inf]) + 0.6666666666666666666666667 + >>> nprod(lambda k: (1-1/k**2), [2, inf]) + 0.5 + + Next, several more infinite products with more complicated + values:: + + >>> nprod(lambda k: exp(1/k**2), [1, inf]); exp(pi**2/6) + 5.180668317897115748416626 + 5.180668317897115748416626 + + >>> nprod(lambda k: (k**2-1)/(k**2+1), [2, inf]); pi*csch(pi) + 0.2720290549821331629502366 + 0.2720290549821331629502366 + + >>> nprod(lambda k: (k**4-1)/(k**4+1), [2, inf]) + 0.8480540493529003921296502 + >>> pi*sinh(pi)/(cosh(sqrt(2)*pi)-cos(sqrt(2)*pi)) + 0.8480540493529003921296502 + + >>> nprod(lambda k: (1+1/k+1/k**2)**2/(1+2/k+3/k**2), [1, inf]) + 1.848936182858244485224927 + >>> 3*sqrt(2)*cosh(pi*sqrt(3)/2)**2*csch(pi*sqrt(2))/pi + 1.848936182858244485224927 + + >>> nprod(lambda k: (1-1/k**4), [2, inf]); sinh(pi)/(4*pi) + 0.9190194775937444301739244 + 0.9190194775937444301739244 + + >>> nprod(lambda k: (1-1/k**6), [2, inf]) + 0.9826842777421925183244759 + >>> (1+cosh(pi*sqrt(3)))/(12*pi**2) + 0.9826842777421925183244759 + + >>> nprod(lambda k: (1+1/k**2), [2, inf]); sinh(pi)/(2*pi) + 1.838038955187488860347849 + 1.838038955187488860347849 + + >>> nprod(lambda n: (1+1/n)**n * exp(1/(2*n)-1), [1, inf]) + 1.447255926890365298959138 + >>> exp(1+euler/2)/sqrt(2*pi) + 1.447255926890365298959138 + + The following two products are equivalent and can be evaluated in + terms of a Jacobi theta function. Pi can be replaced by any value + (as long as convergence is preserved):: + + >>> nprod(lambda k: (1-pi**-k)/(1+pi**-k), [1, inf]) + 0.3838451207481672404778686 + >>> nprod(lambda k: tanh(k*log(pi)/2), [1, inf]) + 0.3838451207481672404778686 + >>> jtheta(4,0,1/pi) + 0.3838451207481672404778686 + + This product does not have a known closed form value:: + + >>> nprod(lambda k: (1-1/2**k), [1, inf]) + 0.2887880950866024212788997 + + A product taken from `-\infty`:: + + >>> nprod(lambda k: 1-k**(-3), [-inf,-2]) + 0.8093965973662901095786805 + >>> cosh(pi*sqrt(3)/2)/(3*pi) + 0.8093965973662901095786805 + + A doubly infinite product:: + + >>> nprod(lambda k: exp(1/(1+k**2)), [-inf, inf]) + 23.41432688231864337420035 + >>> exp(pi/tanh(pi)) + 23.41432688231864337420035 + + A product requiring the use of Euler-Maclaurin summation to compute + an accurate value:: + + >>> nprod(lambda k: (1-1/k**2.5), [2, inf], method='e') + 0.696155111336231052898125 + + **References** + + 1. [Weisstein]_ http://mathworld.wolfram.com/InfiniteProduct.html + + """ + if nsum or ('e' in kwargs.get('method', '')): + orig = ctx.prec + try: + # TODO: we are evaluating log(1+eps) -> eps, which is + # inaccurate. This currently works because nsum greatly + # increases the working precision. But we should be + # more intelligent and handle the precision here. + ctx.prec += 10 + v = ctx.nsum(lambda n: ctx.ln(f(n)), interval, **kwargs) + finally: + ctx.prec = orig + return +ctx.exp(v) + + a, b = ctx._as_points(interval) + if a == ctx.ninf: + if b == ctx.inf: + return f(0) * ctx.nprod(lambda k: f(-k) * f(k), [1, ctx.inf], **kwargs) + return ctx.nprod(f, [-b, ctx.inf], **kwargs) + elif b != ctx.inf: + return ctx.fprod(f(ctx.mpf(k)) for k in xrange(int(a), int(b)+1)) + + a = int(a) + + def update(partial_products, indices): + if partial_products: + pprod = partial_products[-1] + else: + pprod = ctx.one + for k in indices: + pprod = pprod * f(a + ctx.mpf(k)) + partial_products.append(pprod) + + return +ctx.adaptive_extrapolation(update, None, kwargs) + + +@defun +def limit(ctx, f, x, direction=1, exp=False, **kwargs): + r""" + Computes an estimate of the limit + + .. math :: + + \lim_{t \to x} f(t) + + where `x` may be finite or infinite. + + For finite `x`, :func:`~mpmath.limit` evaluates `f(x + d/n)` for + consecutive integer values of `n`, where the approach direction + `d` may be specified using the *direction* keyword argument. + For infinite `x`, :func:`~mpmath.limit` evaluates values of + `f(\mathrm{sign}(x) \cdot n)`. + + If the approach to the limit is not sufficiently fast to give + an accurate estimate directly, :func:`~mpmath.limit` attempts to find + the limit using Richardson extrapolation or the Shanks + transformation. You can select between these methods using + the *method* keyword (see documentation of :func:`~mpmath.nsum` for + more information). + + **Options** + + The following options are available with essentially the + same meaning as for :func:`~mpmath.nsum`: *tol*, *method*, *maxterms*, + *steps*, *verbose*. + + If the option *exp=True* is set, `f` will be + sampled at exponentially spaced points `n = 2^1, 2^2, 2^3, \ldots` + instead of the linearly spaced points `n = 1, 2, 3, \ldots`. + This can sometimes improve the rate of convergence so that + :func:`~mpmath.limit` may return a more accurate answer (and faster). + However, do note that this can only be used if `f` + supports fast and accurate evaluation for arguments that + are extremely close to the limit point (or if infinite, + very large arguments). + + **Examples** + + A basic evaluation of a removable singularity:: + + >>> from mpmath import * + >>> mp.dps = 30; mp.pretty = True + >>> limit(lambda x: (x-sin(x))/x**3, 0) + 0.166666666666666666666666666667 + + Computing the exponential function using its limit definition:: + + >>> limit(lambda n: (1+3/n)**n, inf) + 20.0855369231876677409285296546 + >>> exp(3) + 20.0855369231876677409285296546 + + A limit for `\pi`:: + + >>> f = lambda n: 2**(4*n+1)*fac(n)**4/(2*n+1)/fac(2*n)**2 + >>> limit(f, inf) + 3.14159265358979323846264338328 + + Calculating the coefficient in Stirling's formula:: + + >>> limit(lambda n: fac(n) / (sqrt(n)*(n/e)**n), inf) + 2.50662827463100050241576528481 + >>> sqrt(2*pi) + 2.50662827463100050241576528481 + + Evaluating Euler's constant `\gamma` using the limit representation + + .. math :: + + \gamma = \lim_{n \rightarrow \infty } \left[ \left( + \sum_{k=1}^n \frac{1}{k} \right) - \log(n) \right] + + (which converges notoriously slowly):: + + >>> f = lambda n: sum([mpf(1)/k for k in range(1,int(n)+1)]) - log(n) + >>> limit(f, inf) + 0.577215664901532860606512090082 + >>> +euler + 0.577215664901532860606512090082 + + With default settings, the following limit converges too slowly + to be evaluated accurately. Changing to exponential sampling + however gives a perfect result:: + + >>> f = lambda x: sqrt(x**3+x**2)/(sqrt(x**3)+x) + >>> limit(f, inf) + 0.992831158558330281129249686491 + >>> limit(f, inf, exp=True) + 1.0 + + """ + + if ctx.isinf(x): + direction = ctx.sign(x) + g = lambda k: f(ctx.mpf(k+1)*direction) + else: + direction *= ctx.one + g = lambda k: f(x + direction/(k+1)) + if exp: + h = g + g = lambda k: h(2**k) + + def update(values, indices): + for k in indices: + values.append(g(k+1)) + + # XXX: steps used by nsum don't work well + if not 'steps' in kwargs: + kwargs['steps'] = [10] + + return +ctx.adaptive_extrapolation(update, None, kwargs) diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/inverselaplace.py b/venv/lib/python3.10/site-packages/mpmath/calculus/inverselaplace.py new file mode 100644 index 0000000000000000000000000000000000000000..d2206b05c1601ee781b09dcbedf3c0fcd89cfa59 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/calculus/inverselaplace.py @@ -0,0 +1,973 @@ +# contributed to mpmath by Kristopher L. Kuhlman, February 2017 +# contributed to mpmath by Guillermo Navas-Palencia, February 2022 + +class InverseLaplaceTransform(object): + r""" + Inverse Laplace transform methods are implemented using this + class, in order to simplify the code and provide a common + infrastructure. + + Implement a custom inverse Laplace transform algorithm by + subclassing :class:`InverseLaplaceTransform` and implementing the + appropriate methods. The subclass can then be used by + :func:`~mpmath.invertlaplace` by passing it as the *method* + argument. + """ + + def __init__(self, ctx): + self.ctx = ctx + + def calc_laplace_parameter(self, t, **kwargs): + r""" + Determine the vector of Laplace parameter values needed for an + algorithm, this will depend on the choice of algorithm (de + Hoog is default), the algorithm-specific parameters passed (or + default ones), and desired time. + """ + raise NotImplementedError + + def calc_time_domain_solution(self, fp): + r""" + Compute the time domain solution, after computing the + Laplace-space function evaluations at the abscissa required + for the algorithm. Abscissa computed for one algorithm are + typically not useful for another algorithm. + """ + raise NotImplementedError + + +class FixedTalbot(InverseLaplaceTransform): + + def calc_laplace_parameter(self, t, **kwargs): + r"""The "fixed" Talbot method deforms the Bromwich contour towards + `-\infty` in the shape of a parabola. Traditionally the Talbot + algorithm has adjustable parameters, but the "fixed" version + does not. The `r` parameter could be passed in as a parameter, + if you want to override the default given by (Abate & Valko, + 2004). + + The Laplace parameter is sampled along a parabola opening + along the negative imaginary axis, with the base of the + parabola along the real axis at + `p=\frac{r}{t_\mathrm{max}}`. As the number of terms used in + the approximation (degree) grows, the abscissa required for + function evaluation tend towards `-\infty`, requiring high + precision to prevent overflow. If any poles, branch cuts or + other singularities exist such that the deformed Bromwich + contour lies to the left of the singularity, the method will + fail. + + **Optional arguments** + + :class:`~mpmath.calculus.inverselaplace.FixedTalbot.calc_laplace_parameter` + recognizes the following keywords + + *tmax* + maximum time associated with vector of times + (typically just the time requested) + *degree* + integer order of approximation (M = number of terms) + *r* + abscissa for `p_0` (otherwise computed using rule + of thumb `2M/5`) + + The working precision will be increased according to a rule of + thumb. If 'degree' is not specified, the working precision and + degree are chosen to hopefully achieve the dps of the calling + context. If 'degree' is specified, the working precision is + chosen to achieve maximum resulting precision for the + specified degree. + + .. math :: + + p_0=\frac{r}{t} + + .. math :: + + p_i=\frac{i r \pi}{Mt_\mathrm{max}}\left[\cot\left( + \frac{i\pi}{M}\right) + j \right] \qquad 1\le i 0: + self.degree += 1 + + M = self.degree + + # this is adjusting the dps of the calling context + # hopefully the caller doesn't monkey around with it + # between calling this routine and calc_time_domain_solution() + self.dps_orig = self.ctx.dps + self.ctx.dps = self.dps_goal + + self.V = self._coeff() + self.p = self.ctx.matrix(self.ctx.arange(1, M+1))*self.ctx.ln2/self.t + + # NB: p is real (mpf) + + def _coeff(self): + r"""Salzer summation weights (aka, "Stehfest coefficients") + only depend on the approximation order (M) and the precision""" + + M = self.degree + M2 = int(M/2) # checked earlier that M is even + + V = self.ctx.matrix(M, 1) + + # Salzer summation weights + # get very large in magnitude and oscillate in sign, + # if the precision is not high enough, there will be + # catastrophic cancellation + for k in range(1, M+1): + z = self.ctx.matrix(min(k, M2)+1, 1) + for j in range(int((k+1)/2), min(k, M2)+1): + z[j] = (self.ctx.power(j, M2)*self.ctx.fac(2*j)/ + (self.ctx.fac(M2-j)*self.ctx.fac(j)* + self.ctx.fac(j-1)*self.ctx.fac(k-j)* + self.ctx.fac(2*j-k))) + V[k-1] = self.ctx.power(-1, k+M2)*self.ctx.fsum(z) + + return V + + def calc_time_domain_solution(self, fp, t, manual_prec=False): + r"""Compute time-domain Stehfest algorithm solution. + + .. math :: + + f(t,M) = \frac{\log 2}{t} \sum_{k=1}^{M} V_k \bar{f}\left( + p_k \right) + + where + + .. math :: + + V_k = (-1)^{k + N/2} \sum^{\min(k,N/2)}_{i=\lfloor(k+1)/2 \rfloor} + \frac{i^{\frac{N}{2}}(2i)!}{\left(\frac{N}{2}-i \right)! \, i! \, + \left(i-1 \right)! \, \left(k-i\right)! \, \left(2i-k \right)!} + + As the degree increases, the abscissa (`p_k`) only increase + linearly towards `\infty`, but the Stehfest coefficients + (`V_k`) alternate in sign and increase rapidly in sign, + requiring high precision to prevent overflow or loss of + significance when evaluating the sum. + + **References** + + 1. Widder, D. (1941). *The Laplace Transform*. Princeton. + 2. Stehfest, H. (1970). Algorithm 368: numerical inversion of + Laplace transforms. *Communications of the ACM* 13(1):47-49, + http://dx.doi.org/10.1145/361953.361969 + + """ + + # required + self.t = self.ctx.convert(t) + + # assume fp was computed from p matrix returned from + # calc_laplace_parameter(), so is already + # a list or matrix of mpmath 'mpf' types + + result = self.ctx.fdot(self.V, fp)*self.ctx.ln2/self.t + + # setting dps back to value when calc_laplace_parameter was called + if not manual_prec: + self.ctx.dps = self.dps_orig + + # ignore any small imaginary part + return result.real + + +# **************************************** + +class deHoog(InverseLaplaceTransform): + + def calc_laplace_parameter(self, t, **kwargs): + r"""the de Hoog, Knight & Stokes algorithm is an + accelerated form of the Fourier series numerical + inverse Laplace transform algorithms. + + .. math :: + + p_k = \gamma + \frac{jk}{T} \qquad 0 \le k < 2M+1 + + where + + .. math :: + + \gamma = \alpha - \frac{\log \mathrm{tol}}{2T}, + + `j=\sqrt{-1}`, `T = 2t_\mathrm{max}` is a scaled time, + `\alpha=10^{-\mathrm{dps\_goal}}` is the real part of the + rightmost pole or singularity, which is chosen based on the + desired accuracy (assuming the rightmost singularity is 0), + and `\mathrm{tol}=10\alpha` is the desired tolerance, which is + chosen in relation to `\alpha`.` + + When increasing the degree, the abscissa increase towards + `j\infty`, but more slowly than the fixed Talbot + algorithm. The de Hoog et al. algorithm typically does better + with oscillatory functions of time, and less well-behaved + functions. The method tends to be slower than the Talbot and + Stehfest algorithsm, especially so at very high precision + (e.g., `>500` digits precision). + + """ + + # required + # ------------------------------ + self.t = self.ctx.convert(t) + + # optional + # ------------------------------ + self.tmax = kwargs.get('tmax', self.t) + + # empirical relationships used here based on a linear fit of + # requested and delivered dps for exponentially decaying time + # functions for requested dps up to 512. + + if 'degree' in kwargs: + self.degree = kwargs['degree'] + self.dps_goal = int(1.38*self.degree) + else: + self.dps_goal = int(self.ctx.dps*1.36) + self.degree = max(10, self.dps_goal) + + # 2*M+1 terms in approximation + M = self.degree + + # adjust alpha component of abscissa of convergence for higher + # precision + tmp = self.ctx.power(10.0, -self.dps_goal) + self.alpha = self.ctx.convert(kwargs.get('alpha', tmp)) + + # desired tolerance (here simply related to alpha) + self.tol = self.ctx.convert(kwargs.get('tol', self.alpha*10.0)) + self.np = 2*self.degree+1 # number of terms in approximation + + # this is adjusting the dps of the calling context + # hopefully the caller doesn't monkey around with it + # between calling this routine and calc_time_domain_solution() + self.dps_orig = self.ctx.dps + self.ctx.dps = self.dps_goal + + # scaling factor (likely tun-able, but 2 is typical) + self.scale = kwargs.get('scale', 2) + self.T = self.ctx.convert(kwargs.get('T', self.scale*self.tmax)) + + self.p = self.ctx.matrix(2*M+1, 1) + self.gamma = self.alpha - self.ctx.log(self.tol)/(self.scale*self.T) + self.p = (self.gamma + self.ctx.pi* + self.ctx.matrix(self.ctx.arange(self.np))/self.T*1j) + + # NB: p is complex (mpc) + + def calc_time_domain_solution(self, fp, t, manual_prec=False): + r"""Calculate time-domain solution for + de Hoog, Knight & Stokes algorithm. + + The un-accelerated Fourier series approach is: + + .. math :: + + f(t,2M+1) = \frac{e^{\gamma t}}{T} \sum_{k=0}^{2M}{}^{'} + \Re\left[\bar{f}\left( p_k \right) + e^{i\pi t/T} \right], + + where the prime on the summation indicates the first term is halved. + + This simplistic approach requires so many function evaluations + that it is not practical. Non-linear acceleration is + accomplished via Pade-approximation and an analytic expression + for the remainder of the continued fraction. See the original + paper (reference 2 below) a detailed description of the + numerical approach. + + **References** + + 1. Davies, B. (2005). *Integral Transforms and their + Applications*, Third Edition. Springer. + 2. de Hoog, F., J. Knight, A. Stokes (1982). An improved + method for numerical inversion of Laplace transforms. *SIAM + Journal of Scientific and Statistical Computing* 3:357-366, + http://dx.doi.org/10.1137/0903022 + + """ + + M = self.degree + np = self.np + T = self.T + + self.t = self.ctx.convert(t) + + # would it be useful to try re-using + # space between e&q and A&B? + e = self.ctx.zeros(np, M+1) + q = self.ctx.matrix(2*M, M) + d = self.ctx.matrix(np, 1) + A = self.ctx.zeros(np+1, 1) + B = self.ctx.ones(np+1, 1) + + # initialize Q-D table + e[:, 0] = 0.0 + 0j + q[0, 0] = fp[1]/(fp[0]/2) + for i in range(1, 2*M): + q[i, 0] = fp[i+1]/fp[i] + + # rhombus rule for filling triangular Q-D table (e & q) + for r in range(1, M+1): + # start with e, column 1, 0:2*M-2 + mr = 2*(M-r) + 1 + e[0:mr, r] = q[1:mr+1, r-1] - q[0:mr, r-1] + e[1:mr+1, r-1] + if not r == M: + rq = r+1 + mr = 2*(M-rq)+1 + 2 + for i in range(mr): + q[i, rq-1] = q[i+1, rq-2]*e[i+1, rq-1]/e[i, rq-1] + + # build up continued fraction coefficients (d) + d[0] = fp[0]/2 + for r in range(1, M+1): + d[2*r-1] = -q[0, r-1] # even terms + d[2*r] = -e[0, r] # odd terms + + # seed A and B for recurrence + A[0] = 0.0 + 0.0j + A[1] = d[0] + B[0:2] = 1.0 + 0.0j + + # base of the power series + z = self.ctx.expjpi(self.t/T) # i*pi is already in fcn + + # coefficients of Pade approximation (A & B) + # using recurrence for all but last term + for i in range(1, 2*M): + A[i+1] = A[i] + d[i]*A[i-1]*z + B[i+1] = B[i] + d[i]*B[i-1]*z + + # "improved remainder" to continued fraction + brem = (1 + (d[2*M-1] - d[2*M])*z)/2 + # powm1(x,y) computes x^y - 1 more accurately near zero + rem = brem*self.ctx.powm1(1 + d[2*M]*z/brem, + self.ctx.fraction(1, 2)) + + # last term of recurrence using new remainder + A[np] = A[2*M] + rem*A[2*M-1] + B[np] = B[2*M] + rem*B[2*M-1] + + # diagonal Pade approximation + # F=A/B represents accelerated trapezoid rule + result = self.ctx.exp(self.gamma*self.t)/T*(A[np]/B[np]).real + + # setting dps back to value when calc_laplace_parameter was called + if not manual_prec: + self.ctx.dps = self.dps_orig + + return result + + +# **************************************** + +class Cohen(InverseLaplaceTransform): + + def calc_laplace_parameter(self, t, **kwargs): + r"""The Cohen algorithm accelerates the convergence of the nearly + alternating series resulting from the application of the trapezoidal + rule to the Bromwich contour inversion integral. + + .. math :: + + p_k = \frac{\gamma}{2 t} + \frac{\pi i k}{t} \qquad 0 \le k < M + + where + + .. math :: + + \gamma = \frac{2}{3} (d + \log(10) + \log(2 t)), + + `d = \mathrm{dps\_goal}`, which is chosen based on the desired + accuracy using the method developed in [1] to improve numerical + stability. The Cohen algorithm shows robustness similar to the de Hoog + et al. algorithm, but it is faster than the fixed Talbot algorithm. + + **Optional arguments** + + *degree* + integer order of the approximation (M = number of terms) + *alpha* + abscissa for `p_0` (controls the discretization error) + + The working precision will be increased according to a rule of + thumb. If 'degree' is not specified, the working precision and + degree are chosen to hopefully achieve the dps of the calling + context. If 'degree' is specified, the working precision is + chosen to achieve maximum resulting precision for the + specified degree. + + **References** + + 1. P. Glasserman, J. Ruiz-Mata (2006). Computing the credit loss + distribution in the Gaussian copula model: a comparison of methods. + *Journal of Credit Risk* 2(4):33-66, 10.21314/JCR.2006.057 + + """ + self.t = self.ctx.convert(t) + + if 'degree' in kwargs: + self.degree = kwargs['degree'] + self.dps_goal = int(1.5 * self.degree) + else: + self.dps_goal = int(self.ctx.dps * 1.74) + self.degree = max(22, int(1.31 * self.dps_goal)) + + M = self.degree + 1 + + # this is adjusting the dps of the calling context hopefully + # the caller doesn't monkey around with it between calling + # this routine and calc_time_domain_solution() + self.dps_orig = self.ctx.dps + self.ctx.dps = self.dps_goal + + ttwo = 2 * self.t + tmp = self.ctx.dps * self.ctx.log(10) + self.ctx.log(ttwo) + tmp = self.ctx.fraction(2, 3) * tmp + self.alpha = self.ctx.convert(kwargs.get('alpha', tmp)) + + # all but time-dependent part of p + a_t = self.alpha / ttwo + p_t = self.ctx.pi * 1j / self.t + + self.p = self.ctx.matrix(M, 1) + self.p[0] = a_t + + for i in range(1, M): + self.p[i] = a_t + i * p_t + + def calc_time_domain_solution(self, fp, t, manual_prec=False): + r"""Calculate time-domain solution for Cohen algorithm. + + The accelerated nearly alternating series is: + + .. math :: + + f(t, M) = \frac{e^{\gamma / 2}}{t} \left[\frac{1}{2} + \Re\left(\bar{f}\left(\frac{\gamma}{2t}\right) \right) - + \sum_{k=0}^{M-1}\frac{c_{M,k}}{d_M}\Re\left(\bar{f} + \left(\frac{\gamma + 2(k+1) \pi i}{2t}\right)\right)\right], + + where coefficients `\frac{c_{M, k}}{d_M}` are described in [1]. + + 1. H. Cohen, F. Rodriguez Villegas, D. Zagier (2000). Convergence + acceleration of alternating series. *Experiment. Math* 9(1):3-12 + + """ + self.t = self.ctx.convert(t) + + n = self.degree + M = n + 1 + + A = self.ctx.matrix(M, 1) + for i in range(M): + A[i] = fp[i].real + + d = (3 + self.ctx.sqrt(8)) ** n + d = (d + 1 / d) / 2 + b = -self.ctx.one + c = -d + s = 0 + + for k in range(n): + c = b - c + s = s + c * A[k + 1] + b = 2 * (k + n) * (k - n) * b / ((2 * k + 1) * (k + self.ctx.one)) + + result = self.ctx.exp(self.alpha / 2) / self.t * (A[0] / 2 - s / d) + + # setting dps back to value when calc_laplace_parameter was + # called, unless flag is set. + if not manual_prec: + self.ctx.dps = self.dps_orig + + return result + + +# **************************************** + +class LaplaceTransformInversionMethods(object): + def __init__(ctx, *args, **kwargs): + ctx._fixed_talbot = FixedTalbot(ctx) + ctx._stehfest = Stehfest(ctx) + ctx._de_hoog = deHoog(ctx) + ctx._cohen = Cohen(ctx) + + def invertlaplace(ctx, f, t, **kwargs): + r"""Computes the numerical inverse Laplace transform for a + Laplace-space function at a given time. The function being + evaluated is assumed to be a real-valued function of time. + + The user must supply a Laplace-space function `\bar{f}(p)`, + and a desired time at which to estimate the time-domain + solution `f(t)`. + + A few basic examples of Laplace-space functions with known + inverses (see references [1,2]) : + + .. math :: + + \mathcal{L}\left\lbrace f(t) \right\rbrace=\bar{f}(p) + + .. math :: + + \mathcal{L}^{-1}\left\lbrace \bar{f}(p) \right\rbrace = f(t) + + .. math :: + + \bar{f}(p) = \frac{1}{(p+1)^2} + + .. math :: + + f(t) = t e^{-t} + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> tt = [0.001, 0.01, 0.1, 1, 10] + >>> fp = lambda p: 1/(p+1)**2 + >>> ft = lambda t: t*exp(-t) + >>> ft(tt[0]),ft(tt[0])-invertlaplace(fp,tt[0],method='talbot') + (0.000999000499833375, 8.57923043561212e-20) + >>> ft(tt[1]),ft(tt[1])-invertlaplace(fp,tt[1],method='talbot') + (0.00990049833749168, 3.27007646698047e-19) + >>> ft(tt[2]),ft(tt[2])-invertlaplace(fp,tt[2],method='talbot') + (0.090483741803596, -1.75215800052168e-18) + >>> ft(tt[3]),ft(tt[3])-invertlaplace(fp,tt[3],method='talbot') + (0.367879441171442, 1.2428864009344e-17) + >>> ft(tt[4]),ft(tt[4])-invertlaplace(fp,tt[4],method='talbot') + (0.000453999297624849, 4.04513489306658e-20) + + The methods also work for higher precision: + + >>> mp.dps = 100; mp.pretty = True + >>> nstr(ft(tt[0]),15),nstr(ft(tt[0])-invertlaplace(fp,tt[0],method='talbot'),15) + ('0.000999000499833375', '-4.96868310693356e-105') + >>> nstr(ft(tt[1]),15),nstr(ft(tt[1])-invertlaplace(fp,tt[1],method='talbot'),15) + ('0.00990049833749168', '1.23032291513122e-104') + + .. math :: + + \bar{f}(p) = \frac{1}{p^2+1} + + .. math :: + + f(t) = \mathrm{J}_0(t) + + >>> mp.dps = 15; mp.pretty = True + >>> fp = lambda p: 1/sqrt(p*p + 1) + >>> ft = lambda t: besselj(0,t) + >>> ft(tt[0]),ft(tt[0])-invertlaplace(fp,tt[0],method='dehoog') + (0.999999750000016, -6.09717765032273e-18) + >>> ft(tt[1]),ft(tt[1])-invertlaplace(fp,tt[1],method='dehoog') + (0.99997500015625, -5.61756281076169e-17) + + .. math :: + + \bar{f}(p) = \frac{\log p}{p} + + .. math :: + + f(t) = -\gamma -\log t + + >>> mp.dps = 15; mp.pretty = True + >>> fp = lambda p: log(p)/p + >>> ft = lambda t: -euler-log(t) + >>> ft(tt[0]),ft(tt[0])-invertlaplace(fp,tt[0],method='stehfest') + (6.3305396140806, -1.92126634837863e-16) + >>> ft(tt[1]),ft(tt[1])-invertlaplace(fp,tt[1],method='stehfest') + (4.02795452108656, -4.81486093200704e-16) + + **Options** + + :func:`~mpmath.invertlaplace` recognizes the following optional + keywords valid for all methods: + + *method* + Chooses numerical inverse Laplace transform algorithm + (described below). + *degree* + Number of terms used in the approximation + + **Algorithms** + + Mpmath implements four numerical inverse Laplace transform + algorithms, attributed to: Talbot, Stehfest, and de Hoog, + Knight and Stokes. These can be selected by using + *method='talbot'*, *method='stehfest'*, *method='dehoog'* or + *method='cohen'* or by passing the classes *method=FixedTalbot*, + *method=Stehfest*, *method=deHoog*, or *method=Cohen*. The functions + :func:`~mpmath.invlaptalbot`, :func:`~mpmath.invlapstehfest`, + :func:`~mpmath.invlapdehoog`, and :func:`~mpmath.invlapcohen` + are also available as shortcuts. + + All four algorithms implement a heuristic balance between the + requested precision and the precision used internally for the + calculations. This has been tuned for a typical exponentially + decaying function and precision up to few hundred decimal + digits. + + The Laplace transform converts the variable time (i.e., along + a line) into a parameter given by the right half of the + complex `p`-plane. Singularities, poles, and branch cuts in + the complex `p`-plane contain all the information regarding + the time behavior of the corresponding function. Any numerical + method must therefore sample `p`-plane "close enough" to the + singularities to accurately characterize them, while not + getting too close to have catastrophic cancellation, overflow, + or underflow issues. Most significantly, if one or more of the + singularities in the `p`-plane is not on the left side of the + Bromwich contour, its effects will be left out of the computed + solution, and the answer will be completely wrong. + + *Talbot* + + The fixed Talbot method is high accuracy and fast, but the + method can catastrophically fail for certain classes of time-domain + behavior, including a Heaviside step function for positive + time (e.g., `H(t-2)`), or some oscillatory behaviors. The + Talbot method usually has adjustable parameters, but the + "fixed" variety implemented here does not. This method + deforms the Bromwich integral contour in the shape of a + parabola towards `-\infty`, which leads to problems + when the solution has a decaying exponential in it (e.g., a + Heaviside step function is equivalent to multiplying by a + decaying exponential in Laplace space). + + *Stehfest* + + The Stehfest algorithm only uses abscissa along the real axis + of the complex `p`-plane to estimate the time-domain + function. Oscillatory time-domain functions have poles away + from the real axis, so this method does not work well with + oscillatory functions, especially high-frequency ones. This + method also depends on summation of terms in a series that + grows very large, and will have catastrophic cancellation + during summation if the working precision is too low. + + *de Hoog et al.* + + The de Hoog, Knight, and Stokes method is essentially a + Fourier-series quadrature-type approximation to the Bromwich + contour integral, with non-linear series acceleration and an + analytical expression for the remainder term. This method is + typically one of the most robust. This method also involves the + greatest amount of overhead, so it is typically the slowest of the + four methods at high precision. + + *Cohen* + + The Cohen method is a trapezoidal rule approximation to the Bromwich + contour integral, with linear acceleration for alternating + series. This method is as robust as the de Hoog et al method and the + fastest of the four methods at high precision, and is therefore the + default method. + + **Singularities** + + All numerical inverse Laplace transform methods have problems + at large time when the Laplace-space function has poles, + singularities, or branch cuts to the right of the origin in + the complex plane. For simple poles in `\bar{f}(p)` at the + `p`-plane origin, the time function is constant in time (e.g., + `\mathcal{L}\left\lbrace 1 \right\rbrace=1/p` has a pole at + `p=0`). A pole in `\bar{f}(p)` to the left of the origin is a + decreasing function of time (e.g., `\mathcal{L}\left\lbrace + e^{-t/2} \right\rbrace=1/(p+1/2)` has a pole at `p=-1/2`), and + a pole to the right of the origin leads to an increasing + function in time (e.g., `\mathcal{L}\left\lbrace t e^{t/4} + \right\rbrace = 1/(p-1/4)^2` has a pole at `p=1/4`). When + singularities occur off the real `p` axis, the time-domain + function is oscillatory. For example `\mathcal{L}\left\lbrace + \mathrm{J}_0(t) \right\rbrace=1/\sqrt{p^2+1}` has a branch cut + starting at `p=j=\sqrt{-1}` and is a decaying oscillatory + function, This range of behaviors is illustrated in Duffy [3] + Figure 4.10.4, p. 228. + + In general as `p \rightarrow \infty` `t \rightarrow 0` and + vice-versa. All numerical inverse Laplace transform methods + require their abscissa to shift closer to the origin for + larger times. If the abscissa shift left of the rightmost + singularity in the Laplace domain, the answer will be + completely wrong (the effect of singularities to the right of + the Bromwich contour are not included in the results). + + For example, the following exponentially growing function has + a pole at `p=3`: + + .. math :: + + \bar{f}(p)=\frac{1}{p^2-9} + + .. math :: + + f(t)=\frac{1}{3}\sinh 3t + + >>> mp.dps = 15; mp.pretty = True + >>> fp = lambda p: 1/(p*p-9) + >>> ft = lambda t: sinh(3*t)/3 + >>> tt = [0.01,0.1,1.0,10.0] + >>> ft(tt[0]),invertlaplace(fp,tt[0],method='talbot') + (0.0100015000675014, 0.0100015000675014) + >>> ft(tt[1]),invertlaplace(fp,tt[1],method='talbot') + (0.101506764482381, 0.101506764482381) + >>> ft(tt[2]),invertlaplace(fp,tt[2],method='talbot') + (3.33929164246997, 3.33929164246997) + >>> ft(tt[3]),invertlaplace(fp,tt[3],method='talbot') + (1781079096920.74, -1.61331069624091e-14) + + **References** + + 1. [DLMF]_ section 1.14 (http://dlmf.nist.gov/1.14T4) + 2. Cohen, A.M. (2007). Numerical Methods for Laplace Transform + Inversion, Springer. + 3. Duffy, D.G. (1998). Advanced Engineering Mathematics, CRC Press. + + **Numerical Inverse Laplace Transform Reviews** + + 1. Bellman, R., R.E. Kalaba, J.A. Lockett (1966). *Numerical + inversion of the Laplace transform: Applications to Biology, + Economics, Engineering, and Physics*. Elsevier. + 2. Davies, B., B. Martin (1979). Numerical inversion of the + Laplace transform: a survey and comparison of methods. *Journal + of Computational Physics* 33:1-32, + http://dx.doi.org/10.1016/0021-9991(79)90025-1 + 3. Duffy, D.G. (1993). On the numerical inversion of Laplace + transforms: Comparison of three new methods on characteristic + problems from applications. *ACM Transactions on Mathematical + Software* 19(3):333-359, http://dx.doi.org/10.1145/155743.155788 + 4. Kuhlman, K.L., (2013). Review of Inverse Laplace Transform + Algorithms for Laplace-Space Numerical Approaches, *Numerical + Algorithms*, 63(2):339-355. + http://dx.doi.org/10.1007/s11075-012-9625-3 + + """ + + rule = kwargs.get('method', 'cohen') + if type(rule) is str: + lrule = rule.lower() + if lrule == 'talbot': + rule = ctx._fixed_talbot + elif lrule == 'stehfest': + rule = ctx._stehfest + elif lrule == 'dehoog': + rule = ctx._de_hoog + elif rule == 'cohen': + rule = ctx._cohen + else: + raise ValueError("unknown invlap algorithm: %s" % rule) + else: + rule = rule(ctx) + + # determine the vector of Laplace-space parameter + # needed for the requested method and desired time + rule.calc_laplace_parameter(t, **kwargs) + + # compute the Laplace-space function evalutations + # at the required abscissa. + fp = [f(p) for p in rule.p] + + # compute the time-domain solution from the + # Laplace-space function evaluations + return rule.calc_time_domain_solution(fp, t) + + # shortcuts for the above function for specific methods + def invlaptalbot(ctx, *args, **kwargs): + kwargs['method'] = 'talbot' + return ctx.invertlaplace(*args, **kwargs) + + def invlapstehfest(ctx, *args, **kwargs): + kwargs['method'] = 'stehfest' + return ctx.invertlaplace(*args, **kwargs) + + def invlapdehoog(ctx, *args, **kwargs): + kwargs['method'] = 'dehoog' + return ctx.invertlaplace(*args, **kwargs) + + def invlapcohen(ctx, *args, **kwargs): + kwargs['method'] = 'cohen' + return ctx.invertlaplace(*args, **kwargs) + + +# **************************************** + +if __name__ == '__main__': + import doctest + doctest.testmod() diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/odes.py b/venv/lib/python3.10/site-packages/mpmath/calculus/odes.py new file mode 100644 index 0000000000000000000000000000000000000000..ac6bd3cb056c8841e6cf77ba4d08a0b1abb2f2c9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/calculus/odes.py @@ -0,0 +1,288 @@ +from bisect import bisect +from ..libmp.backend import xrange + +class ODEMethods(object): + pass + +def ode_taylor(ctx, derivs, x0, y0, tol_prec, n): + h = tol = ctx.ldexp(1, -tol_prec) + dim = len(y0) + xs = [x0] + ys = [y0] + x = x0 + y = y0 + orig = ctx.prec + try: + ctx.prec = orig*(1+n) + # Use n steps with Euler's method to get + # evaluation points for derivatives + for i in range(n): + fxy = derivs(x, y) + y = [y[i]+h*fxy[i] for i in xrange(len(y))] + x += h + xs.append(x) + ys.append(y) + # Compute derivatives + ser = [[] for d in range(dim)] + for j in range(n+1): + s = [0]*dim + b = (-1) ** (j & 1) + k = 1 + for i in range(j+1): + for d in range(dim): + s[d] += b * ys[i][d] + b = (b * (j-k+1)) // (-k) + k += 1 + scale = h**(-j) / ctx.fac(j) + for d in range(dim): + s[d] = s[d] * scale + ser[d].append(s[d]) + finally: + ctx.prec = orig + # Estimate radius for which we can get full accuracy. + # XXX: do this right for zeros + radius = ctx.one + for ts in ser: + if ts[-1]: + radius = min(radius, ctx.nthroot(tol/abs(ts[-1]), n)) + radius /= 2 # XXX + return ser, x0+radius + +def odefun(ctx, F, x0, y0, tol=None, degree=None, method='taylor', verbose=False): + r""" + Returns a function `y(x) = [y_0(x), y_1(x), \ldots, y_n(x)]` + that is a numerical solution of the `n+1`-dimensional first-order + ordinary differential equation (ODE) system + + .. math :: + + y_0'(x) = F_0(x, [y_0(x), y_1(x), \ldots, y_n(x)]) + + y_1'(x) = F_1(x, [y_0(x), y_1(x), \ldots, y_n(x)]) + + \vdots + + y_n'(x) = F_n(x, [y_0(x), y_1(x), \ldots, y_n(x)]) + + The derivatives are specified by the vector-valued function + *F* that evaluates + `[y_0', \ldots, y_n'] = F(x, [y_0, \ldots, y_n])`. + The initial point `x_0` is specified by the scalar argument *x0*, + and the initial value `y(x_0) = [y_0(x_0), \ldots, y_n(x_0)]` is + specified by the vector argument *y0*. + + For convenience, if the system is one-dimensional, you may optionally + provide just a scalar value for *y0*. In this case, *F* should accept + a scalar *y* argument and return a scalar. The solution function + *y* will return scalar values instead of length-1 vectors. + + Evaluation of the solution function `y(x)` is permitted + for any `x \ge x_0`. + + A high-order ODE can be solved by transforming it into first-order + vector form. This transformation is described in standard texts + on ODEs. Examples will also be given below. + + **Options, speed and accuracy** + + By default, :func:`~mpmath.odefun` uses a high-order Taylor series + method. For reasonably well-behaved problems, the solution will + be fully accurate to within the working precision. Note that + *F* must be possible to evaluate to very high precision + for the generation of Taylor series to work. + + To get a faster but less accurate solution, you can set a large + value for *tol* (which defaults roughly to *eps*). If you just + want to plot the solution or perform a basic simulation, + *tol = 0.01* is likely sufficient. + + The *degree* argument controls the degree of the solver (with + *method='taylor'*, this is the degree of the Taylor series + expansion). A higher degree means that a longer step can be taken + before a new local solution must be generated from *F*, + meaning that fewer steps are required to get from `x_0` to a given + `x_1`. On the other hand, a higher degree also means that each + local solution becomes more expensive (i.e., more evaluations of + *F* are required per step, and at higher precision). + + The optimal setting therefore involves a tradeoff. Generally, + decreasing the *degree* for Taylor series is likely to give faster + solution at low precision, while increasing is likely to be better + at higher precision. + + The function + object returned by :func:`~mpmath.odefun` caches the solutions at all step + points and uses polynomial interpolation between step points. + Therefore, once `y(x_1)` has been evaluated for some `x_1`, + `y(x)` can be evaluated very quickly for any `x_0 \le x \le x_1`. + and continuing the evaluation up to `x_2 > x_1` is also fast. + + **Examples of first-order ODEs** + + We will solve the standard test problem `y'(x) = y(x), y(0) = 1` + which has explicit solution `y(x) = \exp(x)`:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> f = odefun(lambda x, y: y, 0, 1) + >>> for x in [0, 1, 2.5]: + ... print((f(x), exp(x))) + ... + (1.0, 1.0) + (2.71828182845905, 2.71828182845905) + (12.1824939607035, 12.1824939607035) + + The solution with high precision:: + + >>> mp.dps = 50 + >>> f = odefun(lambda x, y: y, 0, 1) + >>> f(1) + 2.7182818284590452353602874713526624977572470937 + >>> exp(1) + 2.7182818284590452353602874713526624977572470937 + + Using the more general vectorized form, the test problem + can be input as (note that *f* returns a 1-element vector):: + + >>> mp.dps = 15 + >>> f = odefun(lambda x, y: [y[0]], 0, [1]) + >>> f(1) + [2.71828182845905] + + :func:`~mpmath.odefun` can solve nonlinear ODEs, which are generally + impossible (and at best difficult) to solve analytically. As + an example of a nonlinear ODE, we will solve `y'(x) = x \sin(y(x))` + for `y(0) = \pi/2`. An exact solution happens to be known + for this problem, and is given by + `y(x) = 2 \tan^{-1}\left(\exp\left(x^2/2\right)\right)`:: + + >>> f = odefun(lambda x, y: x*sin(y), 0, pi/2) + >>> for x in [2, 5, 10]: + ... print((f(x), 2*atan(exp(mpf(x)**2/2)))) + ... + (2.87255666284091, 2.87255666284091) + (3.14158520028345, 3.14158520028345) + (3.14159265358979, 3.14159265358979) + + If `F` is independent of `y`, an ODE can be solved using direct + integration. We can therefore obtain a reference solution with + :func:`~mpmath.quad`:: + + >>> f = lambda x: (1+x**2)/(1+x**3) + >>> g = odefun(lambda x, y: f(x), pi, 0) + >>> g(2*pi) + 0.72128263801696 + >>> quad(f, [pi, 2*pi]) + 0.72128263801696 + + **Examples of second-order ODEs** + + We will solve the harmonic oscillator equation `y''(x) + y(x) = 0`. + To do this, we introduce the helper functions `y_0 = y, y_1 = y_0'` + whereby the original equation can be written as `y_1' + y_0' = 0`. Put + together, we get the first-order, two-dimensional vector ODE + + .. math :: + + \begin{cases} + y_0' = y_1 \\ + y_1' = -y_0 + \end{cases} + + To get a well-defined IVP, we need two initial values. With + `y(0) = y_0(0) = 1` and `-y'(0) = y_1(0) = 0`, the problem will of + course be solved by `y(x) = y_0(x) = \cos(x)` and + `-y'(x) = y_1(x) = \sin(x)`. We check this:: + + >>> f = odefun(lambda x, y: [-y[1], y[0]], 0, [1, 0]) + >>> for x in [0, 1, 2.5, 10]: + ... nprint(f(x), 15) + ... nprint([cos(x), sin(x)], 15) + ... print("---") + ... + [1.0, 0.0] + [1.0, 0.0] + --- + [0.54030230586814, 0.841470984807897] + [0.54030230586814, 0.841470984807897] + --- + [-0.801143615546934, 0.598472144103957] + [-0.801143615546934, 0.598472144103957] + --- + [-0.839071529076452, -0.54402111088937] + [-0.839071529076452, -0.54402111088937] + --- + + Note that we get both the sine and the cosine solutions + simultaneously. + + **TODO** + + * Better automatic choice of degree and step size + * Make determination of Taylor series convergence radius + more robust + * Allow solution for `x < x_0` + * Allow solution for complex `x` + * Test for difficult (ill-conditioned) problems + * Implement Runge-Kutta and other algorithms + + """ + if tol: + tol_prec = int(-ctx.log(tol, 2))+10 + else: + tol_prec = ctx.prec+10 + degree = degree or (3 + int(3*ctx.dps/2.)) + workprec = ctx.prec + 40 + try: + len(y0) + return_vector = True + except TypeError: + F_ = F + F = lambda x, y: [F_(x, y[0])] + y0 = [y0] + return_vector = False + ser, xb = ode_taylor(ctx, F, x0, y0, tol_prec, degree) + series_boundaries = [x0, xb] + series_data = [(ser, x0, xb)] + # We will be working with vectors of Taylor series + def mpolyval(ser, a): + return [ctx.polyval(s[::-1], a) for s in ser] + # Find nearest expansion point; compute if necessary + def get_series(x): + if x < x0: + raise ValueError + n = bisect(series_boundaries, x) + if n < len(series_boundaries): + return series_data[n-1] + while 1: + ser, xa, xb = series_data[-1] + if verbose: + print("Computing Taylor series for [%f, %f]" % (xa, xb)) + y = mpolyval(ser, xb-xa) + xa = xb + ser, xb = ode_taylor(ctx, F, xb, y, tol_prec, degree) + series_boundaries.append(xb) + series_data.append((ser, xa, xb)) + if x <= xb: + return series_data[-1] + # Evaluation function + def interpolant(x): + x = ctx.convert(x) + orig = ctx.prec + try: + ctx.prec = workprec + ser, xa, xb = get_series(x) + y = mpolyval(ser, x-xa) + finally: + ctx.prec = orig + if return_vector: + return [+yk for yk in y] + else: + return +y[0] + return interpolant + +ODEMethods.odefun = odefun + +if __name__ == "__main__": + import doctest + doctest.testmod() diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/optimization.py b/venv/lib/python3.10/site-packages/mpmath/calculus/optimization.py new file mode 100644 index 0000000000000000000000000000000000000000..69724f78336ee24856366db48917a47108b1b416 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/calculus/optimization.py @@ -0,0 +1,1102 @@ +from __future__ import print_function + +from copy import copy + +from ..libmp.backend import xrange + +class OptimizationMethods(object): + def __init__(ctx): + pass + +############## +# 1D-SOLVERS # +############## + +class Newton: + """ + 1d-solver generating pairs of approximative root and error. + + Needs starting points x0 close to the root. + + Pro: + + * converges fast + * sometimes more robust than secant with bad second starting point + + Contra: + + * converges slowly for multiple roots + * needs first derivative + * 2 function evaluations per iteration + """ + maxsteps = 20 + + def __init__(self, ctx, f, x0, **kwargs): + self.ctx = ctx + if len(x0) == 1: + self.x0 = x0[0] + else: + raise ValueError('expected 1 starting point, got %i' % len(x0)) + self.f = f + if not 'df' in kwargs: + def df(x): + return self.ctx.diff(f, x) + else: + df = kwargs['df'] + self.df = df + + def __iter__(self): + f = self.f + df = self.df + x0 = self.x0 + while True: + x1 = x0 - f(x0) / df(x0) + error = abs(x1 - x0) + x0 = x1 + yield (x1, error) + +class Secant: + """ + 1d-solver generating pairs of approximative root and error. + + Needs starting points x0 and x1 close to the root. + x1 defaults to x0 + 0.25. + + Pro: + + * converges fast + + Contra: + + * converges slowly for multiple roots + """ + maxsteps = 30 + + def __init__(self, ctx, f, x0, **kwargs): + self.ctx = ctx + if len(x0) == 1: + self.x0 = x0[0] + self.x1 = self.x0 + 0.25 + elif len(x0) == 2: + self.x0 = x0[0] + self.x1 = x0[1] + else: + raise ValueError('expected 1 or 2 starting points, got %i' % len(x0)) + self.f = f + + def __iter__(self): + f = self.f + x0 = self.x0 + x1 = self.x1 + f0 = f(x0) + while True: + f1 = f(x1) + l = x1 - x0 + if not l: + break + s = (f1 - f0) / l + if not s: + break + x0, x1 = x1, x1 - f1/s + f0 = f1 + yield x1, abs(l) + +class MNewton: + """ + 1d-solver generating pairs of approximative root and error. + + Needs starting point x0 close to the root. + Uses modified Newton's method that converges fast regardless of the + multiplicity of the root. + + Pro: + + * converges fast for multiple roots + + Contra: + + * needs first and second derivative of f + * 3 function evaluations per iteration + """ + maxsteps = 20 + + def __init__(self, ctx, f, x0, **kwargs): + self.ctx = ctx + if not len(x0) == 1: + raise ValueError('expected 1 starting point, got %i' % len(x0)) + self.x0 = x0[0] + self.f = f + if not 'df' in kwargs: + def df(x): + return self.ctx.diff(f, x) + else: + df = kwargs['df'] + self.df = df + if not 'd2f' in kwargs: + def d2f(x): + return self.ctx.diff(df, x) + else: + d2f = kwargs['df'] + self.d2f = d2f + + def __iter__(self): + x = self.x0 + f = self.f + df = self.df + d2f = self.d2f + while True: + prevx = x + fx = f(x) + if fx == 0: + break + dfx = df(x) + d2fx = d2f(x) + # x = x - F(x)/F'(x) with F(x) = f(x)/f'(x) + x -= fx / (dfx - fx * d2fx / dfx) + error = abs(x - prevx) + yield x, error + +class Halley: + """ + 1d-solver generating pairs of approximative root and error. + + Needs a starting point x0 close to the root. + Uses Halley's method with cubic convergence rate. + + Pro: + + * converges even faster the Newton's method + * useful when computing with *many* digits + + Contra: + + * needs first and second derivative of f + * 3 function evaluations per iteration + * converges slowly for multiple roots + """ + + maxsteps = 20 + + def __init__(self, ctx, f, x0, **kwargs): + self.ctx = ctx + if not len(x0) == 1: + raise ValueError('expected 1 starting point, got %i' % len(x0)) + self.x0 = x0[0] + self.f = f + if not 'df' in kwargs: + def df(x): + return self.ctx.diff(f, x) + else: + df = kwargs['df'] + self.df = df + if not 'd2f' in kwargs: + def d2f(x): + return self.ctx.diff(df, x) + else: + d2f = kwargs['df'] + self.d2f = d2f + + def __iter__(self): + x = self.x0 + f = self.f + df = self.df + d2f = self.d2f + while True: + prevx = x + fx = f(x) + dfx = df(x) + d2fx = d2f(x) + x -= 2*fx*dfx / (2*dfx**2 - fx*d2fx) + error = abs(x - prevx) + yield x, error + +class Muller: + """ + 1d-solver generating pairs of approximative root and error. + + Needs starting points x0, x1 and x2 close to the root. + x1 defaults to x0 + 0.25; x2 to x1 + 0.25. + Uses Muller's method that converges towards complex roots. + + Pro: + + * converges fast (somewhat faster than secant) + * can find complex roots + + Contra: + + * converges slowly for multiple roots + * may have complex values for real starting points and real roots + + http://en.wikipedia.org/wiki/Muller's_method + """ + maxsteps = 30 + + def __init__(self, ctx, f, x0, **kwargs): + self.ctx = ctx + if len(x0) == 1: + self.x0 = x0[0] + self.x1 = self.x0 + 0.25 + self.x2 = self.x1 + 0.25 + elif len(x0) == 2: + self.x0 = x0[0] + self.x1 = x0[1] + self.x2 = self.x1 + 0.25 + elif len(x0) == 3: + self.x0 = x0[0] + self.x1 = x0[1] + self.x2 = x0[2] + else: + raise ValueError('expected 1, 2 or 3 starting points, got %i' + % len(x0)) + self.f = f + self.verbose = kwargs['verbose'] + + def __iter__(self): + f = self.f + x0 = self.x0 + x1 = self.x1 + x2 = self.x2 + fx0 = f(x0) + fx1 = f(x1) + fx2 = f(x2) + while True: + # TODO: maybe refactoring with function for divided differences + # calculate divided differences + fx2x1 = (fx1 - fx2) / (x1 - x2) + fx2x0 = (fx0 - fx2) / (x0 - x2) + fx1x0 = (fx0 - fx1) / (x0 - x1) + w = fx2x1 + fx2x0 - fx1x0 + fx2x1x0 = (fx1x0 - fx2x1) / (x0 - x2) + if w == 0 and fx2x1x0 == 0: + if self.verbose: + print('canceled with') + print('x0 =', x0, ', x1 =', x1, 'and x2 =', x2) + break + x0 = x1 + fx0 = fx1 + x1 = x2 + fx1 = fx2 + # denominator should be as large as possible => choose sign + r = self.ctx.sqrt(w**2 - 4*fx2*fx2x1x0) + if abs(w - r) > abs(w + r): + r = -r + x2 -= 2*fx2 / (w + r) + fx2 = f(x2) + error = abs(x2 - x1) + yield x2, error + +# TODO: consider raising a ValueError when there's no sign change in a and b +class Bisection: + """ + 1d-solver generating pairs of approximative root and error. + + Uses bisection method to find a root of f in [a, b]. + Might fail for multiple roots (needs sign change). + + Pro: + + * robust and reliable + + Contra: + + * converges slowly + * needs sign change + """ + maxsteps = 100 + + def __init__(self, ctx, f, x0, **kwargs): + self.ctx = ctx + if len(x0) != 2: + raise ValueError('expected interval of 2 points, got %i' % len(x0)) + self.f = f + self.a = x0[0] + self.b = x0[1] + + def __iter__(self): + f = self.f + a = self.a + b = self.b + l = b - a + fb = f(b) + while True: + m = self.ctx.ldexp(a + b, -1) + fm = f(m) + sign = fm * fb + if sign < 0: + a = m + elif sign > 0: + b = m + fb = fm + else: + yield m, self.ctx.zero + l /= 2 + yield (a + b)/2, abs(l) + +def _getm(method): + """ + Return a function to calculate m for Illinois-like methods. + """ + if method == 'illinois': + def getm(fz, fb): + return 0.5 + elif method == 'pegasus': + def getm(fz, fb): + return fb/(fb + fz) + elif method == 'anderson': + def getm(fz, fb): + m = 1 - fz/fb + if m > 0: + return m + else: + return 0.5 + else: + raise ValueError("method '%s' not recognized" % method) + return getm + +class Illinois: + """ + 1d-solver generating pairs of approximative root and error. + + Uses Illinois method or similar to find a root of f in [a, b]. + Might fail for multiple roots (needs sign change). + Combines bisect with secant (improved regula falsi). + + The only difference between the methods is the scaling factor m, which is + used to ensure convergence (you can choose one using the 'method' keyword): + + Illinois method ('illinois'): + m = 0.5 + + Pegasus method ('pegasus'): + m = fb/(fb + fz) + + Anderson-Bjoerk method ('anderson'): + m = 1 - fz/fb if positive else 0.5 + + Pro: + + * converges very fast + + Contra: + + * has problems with multiple roots + * needs sign change + """ + maxsteps = 30 + + def __init__(self, ctx, f, x0, **kwargs): + self.ctx = ctx + if len(x0) != 2: + raise ValueError('expected interval of 2 points, got %i' % len(x0)) + self.a = x0[0] + self.b = x0[1] + self.f = f + self.tol = kwargs['tol'] + self.verbose = kwargs['verbose'] + self.method = kwargs.get('method', 'illinois') + self.getm = _getm(self.method) + if self.verbose: + print('using %s method' % self.method) + + def __iter__(self): + method = self.method + f = self.f + a = self.a + b = self.b + fa = f(a) + fb = f(b) + m = None + while True: + l = b - a + if l == 0: + break + s = (fb - fa) / l + z = a - fa/s + fz = f(z) + if abs(fz) < self.tol: + # TODO: better condition (when f is very flat) + if self.verbose: + print('canceled with z =', z) + yield z, l + break + if fz * fb < 0: # root in [z, b] + a = b + fa = fb + b = z + fb = fz + else: # root in [a, z] + m = self.getm(fz, fb) + b = z + fb = fz + fa = m*fa # scale down to ensure convergence + if self.verbose and m and not method == 'illinois': + print('m:', m) + yield (a + b)/2, abs(l) + +def Pegasus(*args, **kwargs): + """ + 1d-solver generating pairs of approximative root and error. + + Uses Pegasus method to find a root of f in [a, b]. + Wrapper for illinois to use method='pegasus'. + """ + kwargs['method'] = 'pegasus' + return Illinois(*args, **kwargs) + +def Anderson(*args, **kwargs): + """ + 1d-solver generating pairs of approximative root and error. + + Uses Anderson-Bjoerk method to find a root of f in [a, b]. + Wrapper for illinois to use method='pegasus'. + """ + kwargs['method'] = 'anderson' + return Illinois(*args, **kwargs) + +# TODO: check whether it's possible to combine it with Illinois stuff +class Ridder: + """ + 1d-solver generating pairs of approximative root and error. + + Ridders' method to find a root of f in [a, b]. + Is told to perform as well as Brent's method while being simpler. + + Pro: + + * very fast + * simpler than Brent's method + + Contra: + + * two function evaluations per step + * has problems with multiple roots + * needs sign change + + http://en.wikipedia.org/wiki/Ridders'_method + """ + maxsteps = 30 + + def __init__(self, ctx, f, x0, **kwargs): + self.ctx = ctx + self.f = f + if len(x0) != 2: + raise ValueError('expected interval of 2 points, got %i' % len(x0)) + self.x1 = x0[0] + self.x2 = x0[1] + self.verbose = kwargs['verbose'] + self.tol = kwargs['tol'] + + def __iter__(self): + ctx = self.ctx + f = self.f + x1 = self.x1 + fx1 = f(x1) + x2 = self.x2 + fx2 = f(x2) + while True: + x3 = 0.5*(x1 + x2) + fx3 = f(x3) + x4 = x3 + (x3 - x1) * ctx.sign(fx1 - fx2) * fx3 / ctx.sqrt(fx3**2 - fx1*fx2) + fx4 = f(x4) + if abs(fx4) < self.tol: + # TODO: better condition (when f is very flat) + if self.verbose: + print('canceled with f(x4) =', fx4) + yield x4, abs(x1 - x2) + break + if fx4 * fx2 < 0: # root in [x4, x2] + x1 = x4 + fx1 = fx4 + else: # root in [x1, x4] + x2 = x4 + fx2 = fx4 + error = abs(x1 - x2) + yield (x1 + x2)/2, error + +class ANewton: + """ + EXPERIMENTAL 1d-solver generating pairs of approximative root and error. + + Uses Newton's method modified to use Steffensens method when convergence is + slow. (I.e. for multiple roots.) + """ + maxsteps = 20 + + def __init__(self, ctx, f, x0, **kwargs): + self.ctx = ctx + if not len(x0) == 1: + raise ValueError('expected 1 starting point, got %i' % len(x0)) + self.x0 = x0[0] + self.f = f + if not 'df' in kwargs: + def df(x): + return self.ctx.diff(f, x) + else: + df = kwargs['df'] + self.df = df + def phi(x): + return x - f(x) / df(x) + self.phi = phi + self.verbose = kwargs['verbose'] + + def __iter__(self): + x0 = self.x0 + f = self.f + df = self.df + phi = self.phi + error = 0 + counter = 0 + while True: + prevx = x0 + try: + x0 = phi(x0) + except ZeroDivisionError: + if self.verbose: + print('ZeroDivisionError: canceled with x =', x0) + break + preverror = error + error = abs(prevx - x0) + # TODO: decide not to use convergence acceleration + if error and abs(error - preverror) / error < 1: + if self.verbose: + print('converging slowly') + counter += 1 + if counter >= 3: + # accelerate convergence + phi = steffensen(phi) + counter = 0 + if self.verbose: + print('accelerating convergence') + yield x0, error + +# TODO: add Brent + +############################ +# MULTIDIMENSIONAL SOLVERS # +############################ + +def jacobian(ctx, f, x): + """ + Calculate the Jacobian matrix of a function at the point x0. + + This is the first derivative of a vectorial function: + + f : R^m -> R^n with m >= n + """ + x = ctx.matrix(x) + h = ctx.sqrt(ctx.eps) + fx = ctx.matrix(f(*x)) + m = len(fx) + n = len(x) + J = ctx.matrix(m, n) + for j in xrange(n): + xj = x.copy() + xj[j] += h + Jj = (ctx.matrix(f(*xj)) - fx) / h + for i in xrange(m): + J[i,j] = Jj[i] + return J + +# TODO: test with user-specified jacobian matrix +class MDNewton: + """ + Find the root of a vector function numerically using Newton's method. + + f is a vector function representing a nonlinear equation system. + + x0 is the starting point close to the root. + + J is a function returning the Jacobian matrix for a point. + + Supports overdetermined systems. + + Use the 'norm' keyword to specify which norm to use. Defaults to max-norm. + The function to calculate the Jacobian matrix can be given using the + keyword 'J'. Otherwise it will be calculated numerically. + + Please note that this method converges only locally. Especially for high- + dimensional systems it is not trivial to find a good starting point being + close enough to the root. + + It is recommended to use a faster, low-precision solver from SciPy [1] or + OpenOpt [2] to get an initial guess. Afterwards you can use this method for + root-polishing to any precision. + + [1] http://scipy.org + + [2] http://openopt.org/Welcome + """ + maxsteps = 10 + + def __init__(self, ctx, f, x0, **kwargs): + self.ctx = ctx + self.f = f + if isinstance(x0, (tuple, list)): + x0 = ctx.matrix(x0) + assert x0.cols == 1, 'need a vector' + self.x0 = x0 + if 'J' in kwargs: + self.J = kwargs['J'] + else: + def J(*x): + return ctx.jacobian(f, x) + self.J = J + self.norm = kwargs['norm'] + self.verbose = kwargs['verbose'] + + def __iter__(self): + f = self.f + x0 = self.x0 + norm = self.norm + J = self.J + fx = self.ctx.matrix(f(*x0)) + fxnorm = norm(fx) + cancel = False + while not cancel: + # get direction of descent + fxn = -fx + Jx = J(*x0) + s = self.ctx.lu_solve(Jx, fxn) + if self.verbose: + print('Jx:') + print(Jx) + print('s:', s) + # damping step size TODO: better strategy (hard task) + l = self.ctx.one + x1 = x0 + s + while True: + if x1 == x0: + if self.verbose: + print("canceled, won't get more excact") + cancel = True + break + fx = self.ctx.matrix(f(*x1)) + newnorm = norm(fx) + if newnorm < fxnorm: + # new x accepted + fxnorm = newnorm + x0 = x1 + break + l /= 2 + x1 = x0 + l*s + yield (x0, fxnorm) + +############# +# UTILITIES # +############# + +str2solver = {'newton':Newton, 'secant':Secant, 'mnewton':MNewton, + 'halley':Halley, 'muller':Muller, 'bisect':Bisection, + 'illinois':Illinois, 'pegasus':Pegasus, 'anderson':Anderson, + 'ridder':Ridder, 'anewton':ANewton, 'mdnewton':MDNewton} + +def findroot(ctx, f, x0, solver='secant', tol=None, verbose=False, verify=True, **kwargs): + r""" + Find an approximate solution to `f(x) = 0`, using *x0* as starting point or + interval for *x*. + + Multidimensional overdetermined systems are supported. + You can specify them using a function or a list of functions. + + Mathematically speaking, this function returns `x` such that + `|f(x)|^2 \leq \mathrm{tol}` is true within the current working precision. + If the computed value does not meet this criterion, an exception is raised. + This exception can be disabled with *verify=False*. + + For interval arithmetic (``iv.findroot()``), please note that + the returned interval ``x`` is not guaranteed to contain `f(x)=0`! + It is only some `x` for which `|f(x)|^2 \leq \mathrm{tol}` certainly holds + regardless of numerical error. This may be improved in the future. + + **Arguments** + + *f* + one dimensional function + *x0* + starting point, several starting points or interval (depends on solver) + *tol* + the returned solution has an error smaller than this + *verbose* + print additional information for each iteration if true + *verify* + verify the solution and raise a ValueError if `|f(x)|^2 > \mathrm{tol}` + *solver* + a generator for *f* and *x0* returning approximative solution and error + *maxsteps* + after how many steps the solver will cancel + *df* + first derivative of *f* (used by some solvers) + *d2f* + second derivative of *f* (used by some solvers) + *multidimensional* + force multidimensional solving + *J* + Jacobian matrix of *f* (used by multidimensional solvers) + *norm* + used vector norm (used by multidimensional solvers) + + solver has to be callable with ``(f, x0, **kwargs)`` and return an generator + yielding pairs of approximative solution and estimated error (which is + expected to be positive). + You can use the following string aliases: + 'secant', 'mnewton', 'halley', 'muller', 'illinois', 'pegasus', 'anderson', + 'ridder', 'anewton', 'bisect' + + See mpmath.calculus.optimization for their documentation. + + **Examples** + + The function :func:`~mpmath.findroot` locates a root of a given function using the + secant method by default. A simple example use of the secant method is to + compute `\pi` as the root of `\sin x` closest to `x_0 = 3`:: + + >>> from mpmath import * + >>> mp.dps = 30; mp.pretty = True + >>> findroot(sin, 3) + 3.14159265358979323846264338328 + + The secant method can be used to find complex roots of analytic functions, + although it must in that case generally be given a nonreal starting value + (or else it will never leave the real line):: + + >>> mp.dps = 15 + >>> findroot(lambda x: x**3 + 2*x + 1, j) + (0.226698825758202 + 1.46771150871022j) + + A nice application is to compute nontrivial roots of the Riemann zeta + function with many digits (good initial values are needed for convergence):: + + >>> mp.dps = 30 + >>> findroot(zeta, 0.5+14j) + (0.5 + 14.1347251417346937904572519836j) + + The secant method can also be used as an optimization algorithm, by passing + it a derivative of a function. The following example locates the positive + minimum of the gamma function:: + + >>> mp.dps = 20 + >>> findroot(lambda x: diff(gamma, x), 1) + 1.4616321449683623413 + + Finally, a useful application is to compute inverse functions, such as the + Lambert W function which is the inverse of `w e^w`, given the first + term of the solution's asymptotic expansion as the initial value. In basic + cases, this gives identical results to mpmath's built-in ``lambertw`` + function:: + + >>> def lambert(x): + ... return findroot(lambda w: w*exp(w) - x, log(1+x)) + ... + >>> mp.dps = 15 + >>> lambert(1); lambertw(1) + 0.567143290409784 + 0.567143290409784 + >>> lambert(1000); lambert(1000) + 5.2496028524016 + 5.2496028524016 + + Multidimensional functions are also supported:: + + >>> f = [lambda x1, x2: x1**2 + x2, + ... lambda x1, x2: 5*x1**2 - 3*x1 + 2*x2 - 3] + >>> findroot(f, (0, 0)) + [-0.618033988749895] + [-0.381966011250105] + >>> findroot(f, (10, 10)) + [ 1.61803398874989] + [-2.61803398874989] + + You can verify this by solving the system manually. + + Please note that the following (more general) syntax also works:: + + >>> def f(x1, x2): + ... return x1**2 + x2, 5*x1**2 - 3*x1 + 2*x2 - 3 + ... + >>> findroot(f, (0, 0)) + [-0.618033988749895] + [-0.381966011250105] + + + **Multiple roots** + + For multiple roots all methods of the Newtonian family (including secant) + converge slowly. Consider this example:: + + >>> f = lambda x: (x - 1)**99 + >>> findroot(f, 0.9, verify=False) + 0.918073542444929 + + Even for a very close starting point the secant method converges very + slowly. Use ``verbose=True`` to illustrate this. + + It is possible to modify Newton's method to make it converge regardless of + the root's multiplicity:: + + >>> findroot(f, -10, solver='mnewton') + 1.0 + + This variant uses the first and second derivative of the function, which is + not very efficient. + + Alternatively you can use an experimental Newtonian solver that keeps track + of the speed of convergence and accelerates it using Steffensen's method if + necessary:: + + >>> findroot(f, -10, solver='anewton', verbose=True) + x: -9.88888888888888888889 + error: 0.111111111111111111111 + converging slowly + x: -9.77890011223344556678 + error: 0.10998877665544332211 + converging slowly + x: -9.67002233332199662166 + error: 0.108877778911448945119 + converging slowly + accelerating convergence + x: -9.5622443299551077669 + error: 0.107778003366888854764 + converging slowly + x: 0.99999999999999999214 + error: 10.562244329955107759 + x: 1.0 + error: 7.8598304758094664213e-18 + ZeroDivisionError: canceled with x = 1.0 + 1.0 + + **Complex roots** + + For complex roots it's recommended to use Muller's method as it converges + even for real starting points very fast:: + + >>> findroot(lambda x: x**4 + x + 1, (0, 1, 2), solver='muller') + (0.727136084491197 + 0.934099289460529j) + + + **Intersection methods** + + When you need to find a root in a known interval, it's highly recommended to + use an intersection-based solver like ``'anderson'`` or ``'ridder'``. + Usually they converge faster and more reliable. They have however problems + with multiple roots and usually need a sign change to find a root:: + + >>> findroot(lambda x: x**3, (-1, 1), solver='anderson') + 0.0 + + Be careful with symmetric functions:: + + >>> findroot(lambda x: x**2, (-1, 1), solver='anderson') #doctest:+ELLIPSIS + Traceback (most recent call last): + ... + ZeroDivisionError + + It fails even for better starting points, because there is no sign change:: + + >>> findroot(lambda x: x**2, (-1, .5), solver='anderson') + Traceback (most recent call last): + ... + ValueError: Could not find root within given tolerance. (1.0 > 2.16840434497100886801e-19) + Try another starting point or tweak arguments. + + """ + prec = ctx.prec + try: + ctx.prec += 20 + + # initialize arguments + if tol is None: + tol = ctx.eps * 2**10 + + kwargs['verbose'] = kwargs.get('verbose', verbose) + + if 'd1f' in kwargs: + kwargs['df'] = kwargs['d1f'] + + kwargs['tol'] = tol + if isinstance(x0, (list, tuple)): + x0 = [ctx.convert(x) for x in x0] + else: + x0 = [ctx.convert(x0)] + + if isinstance(solver, str): + try: + solver = str2solver[solver] + except KeyError: + raise ValueError('could not recognize solver') + + # accept list of functions + if isinstance(f, (list, tuple)): + f2 = copy(f) + def tmp(*args): + return [fn(*args) for fn in f2] + f = tmp + + # detect multidimensional functions + try: + fx = f(*x0) + multidimensional = isinstance(fx, (list, tuple, ctx.matrix)) + except TypeError: + fx = f(x0[0]) + multidimensional = False + if 'multidimensional' in kwargs: + multidimensional = kwargs['multidimensional'] + if multidimensional: + # only one multidimensional solver available at the moment + solver = MDNewton + if not 'norm' in kwargs: + norm = lambda x: ctx.norm(x, 'inf') + kwargs['norm'] = norm + else: + norm = kwargs['norm'] + else: + norm = abs + + # happily return starting point if it's a root + if norm(fx) == 0: + if multidimensional: + return ctx.matrix(x0) + else: + return x0[0] + + # use solver + iterations = solver(ctx, f, x0, **kwargs) + if 'maxsteps' in kwargs: + maxsteps = kwargs['maxsteps'] + else: + maxsteps = iterations.maxsteps + i = 0 + for x, error in iterations: + if verbose: + print('x: ', x) + print('error:', error) + i += 1 + if error < tol * max(1, norm(x)) or i >= maxsteps: + break + else: + if not i: + raise ValueError('Could not find root using the given solver.\n' + 'Try another starting point or tweak arguments.') + if not isinstance(x, (list, tuple, ctx.matrix)): + xl = [x] + else: + xl = x + if verify and norm(f(*xl))**2 > tol: # TODO: better condition? + raise ValueError('Could not find root within given tolerance. ' + '(%s > %s)\n' + 'Try another starting point or tweak arguments.' + % (norm(f(*xl))**2, tol)) + return x + finally: + ctx.prec = prec + + +def multiplicity(ctx, f, root, tol=None, maxsteps=10, **kwargs): + """ + Return the multiplicity of a given root of f. + + Internally, numerical derivatives are used. This might be inefficient for + higher order derviatives. Due to this, ``multiplicity`` cancels after + evaluating 10 derivatives by default. You can be specify the n-th derivative + using the dnf keyword. + + >>> from mpmath import * + >>> multiplicity(lambda x: sin(x) - 1, pi/2) + 2 + + """ + if tol is None: + tol = ctx.eps ** 0.8 + kwargs['d0f'] = f + for i in xrange(maxsteps): + dfstr = 'd' + str(i) + 'f' + if dfstr in kwargs: + df = kwargs[dfstr] + else: + df = lambda x: ctx.diff(f, x, i) + if not abs(df(root)) < tol: + break + return i + +def steffensen(f): + """ + linear convergent function -> quadratic convergent function + + Steffensen's method for quadratic convergence of a linear converging + sequence. + Don not use it for higher rates of convergence. + It may even work for divergent sequences. + + Definition: + F(x) = (x*f(f(x)) - f(x)**2) / (f(f(x)) - 2*f(x) + x) + + Example + ....... + + You can use Steffensen's method to accelerate a fixpoint iteration of linear + (or less) convergence. + + x* is a fixpoint of the iteration x_{k+1} = phi(x_k) if x* = phi(x*). For + phi(x) = x**2 there are two fixpoints: 0 and 1. + + Let's try Steffensen's method: + + >>> f = lambda x: x**2 + >>> from mpmath.calculus.optimization import steffensen + >>> F = steffensen(f) + >>> for x in [0.5, 0.9, 2.0]: + ... fx = Fx = x + ... for i in xrange(9): + ... try: + ... fx = f(fx) + ... except OverflowError: + ... pass + ... try: + ... Fx = F(Fx) + ... except ZeroDivisionError: + ... pass + ... print('%20g %20g' % (fx, Fx)) + 0.25 -0.5 + 0.0625 0.1 + 0.00390625 -0.0011236 + 1.52588e-05 1.41691e-09 + 2.32831e-10 -2.84465e-27 + 5.42101e-20 2.30189e-80 + 2.93874e-39 -1.2197e-239 + 8.63617e-78 0 + 7.45834e-155 0 + 0.81 1.02676 + 0.6561 1.00134 + 0.430467 1 + 0.185302 1 + 0.0343368 1 + 0.00117902 1 + 1.39008e-06 1 + 1.93233e-12 1 + 3.73392e-24 1 + 4 1.6 + 16 1.2962 + 256 1.10194 + 65536 1.01659 + 4.29497e+09 1.00053 + 1.84467e+19 1 + 3.40282e+38 1 + 1.15792e+77 1 + 1.34078e+154 1 + + Unmodified, the iteration converges only towards 0. Modified it converges + not only much faster, it converges even to the repelling fixpoint 1. + """ + def F(x): + fx = f(x) + ffx = f(fx) + return (x*ffx - fx**2) / (ffx - 2*fx + x) + return F + +OptimizationMethods.jacobian = jacobian +OptimizationMethods.findroot = findroot +OptimizationMethods.multiplicity = multiplicity + +if __name__ == '__main__': + import doctest + doctest.testmod() diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/polynomials.py b/venv/lib/python3.10/site-packages/mpmath/calculus/polynomials.py new file mode 100644 index 0000000000000000000000000000000000000000..ba75c1e88cbc5d40aa590a786c0af5229f193103 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/calculus/polynomials.py @@ -0,0 +1,213 @@ +from ..libmp.backend import xrange +from .calculus import defun + +#----------------------------------------------------------------------------# +# Polynomials # +#----------------------------------------------------------------------------# + +# XXX: extra precision +@defun +def polyval(ctx, coeffs, x, derivative=False): + r""" + Given coefficients `[c_n, \ldots, c_2, c_1, c_0]` and a number `x`, + :func:`~mpmath.polyval` evaluates the polynomial + + .. math :: + + P(x) = c_n x^n + \ldots + c_2 x^2 + c_1 x + c_0. + + If *derivative=True* is set, :func:`~mpmath.polyval` simultaneously + evaluates `P(x)` with the derivative, `P'(x)`, and returns the + tuple `(P(x), P'(x))`. + + >>> from mpmath import * + >>> mp.pretty = True + >>> polyval([3, 0, 2], 0.5) + 2.75 + >>> polyval([3, 0, 2], 0.5, derivative=True) + (2.75, 3.0) + + The coefficients and the evaluation point may be any combination + of real or complex numbers. + """ + if not coeffs: + return ctx.zero + p = ctx.convert(coeffs[0]) + q = ctx.zero + for c in coeffs[1:]: + if derivative: + q = p + x*q + p = c + x*p + if derivative: + return p, q + else: + return p + +@defun +def polyroots(ctx, coeffs, maxsteps=50, cleanup=True, extraprec=10, + error=False, roots_init=None): + """ + Computes all roots (real or complex) of a given polynomial. + + The roots are returned as a sorted list, where real roots appear first + followed by complex conjugate roots as adjacent elements. The polynomial + should be given as a list of coefficients, in the format used by + :func:`~mpmath.polyval`. The leading coefficient must be nonzero. + + With *error=True*, :func:`~mpmath.polyroots` returns a tuple *(roots, err)* + where *err* is an estimate of the maximum error among the computed roots. + + **Examples** + + Finding the three real roots of `x^3 - x^2 - 14x + 24`:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> nprint(polyroots([1,-1,-14,24]), 4) + [-4.0, 2.0, 3.0] + + Finding the two complex conjugate roots of `4x^2 + 3x + 2`, with an + error estimate:: + + >>> roots, err = polyroots([4,3,2], error=True) + >>> for r in roots: + ... print(r) + ... + (-0.375 + 0.59947894041409j) + (-0.375 - 0.59947894041409j) + >>> + >>> err + 2.22044604925031e-16 + >>> + >>> polyval([4,3,2], roots[0]) + (2.22044604925031e-16 + 0.0j) + >>> polyval([4,3,2], roots[1]) + (2.22044604925031e-16 + 0.0j) + + The following example computes all the 5th roots of unity; that is, + the roots of `x^5 - 1`:: + + >>> mp.dps = 20 + >>> for r in polyroots([1, 0, 0, 0, 0, -1]): + ... print(r) + ... + 1.0 + (-0.8090169943749474241 + 0.58778525229247312917j) + (-0.8090169943749474241 - 0.58778525229247312917j) + (0.3090169943749474241 + 0.95105651629515357212j) + (0.3090169943749474241 - 0.95105651629515357212j) + + **Precision and conditioning** + + The roots are computed to the current working precision accuracy. If this + accuracy cannot be achieved in ``maxsteps`` steps, then a + ``NoConvergence`` exception is raised. The algorithm internally is using + the current working precision extended by ``extraprec``. If + ``NoConvergence`` was raised, that is caused either by not having enough + extra precision to achieve convergence (in which case increasing + ``extraprec`` should fix the problem) or too low ``maxsteps`` (in which + case increasing ``maxsteps`` should fix the problem), or a combination of + both. + + The user should always do a convergence study with regards to + ``extraprec`` to ensure accurate results. It is possible to get + convergence to a wrong answer with too low ``extraprec``. + + Provided there are no repeated roots, :func:`~mpmath.polyroots` can + typically compute all roots of an arbitrary polynomial to high precision:: + + >>> mp.dps = 60 + >>> for r in polyroots([1, 0, -10, 0, 1]): + ... print(r) + ... + -3.14626436994197234232913506571557044551247712918732870123249 + -0.317837245195782244725757617296174288373133378433432554879127 + 0.317837245195782244725757617296174288373133378433432554879127 + 3.14626436994197234232913506571557044551247712918732870123249 + >>> + >>> sqrt(3) + sqrt(2) + 3.14626436994197234232913506571557044551247712918732870123249 + >>> sqrt(3) - sqrt(2) + 0.317837245195782244725757617296174288373133378433432554879127 + + **Algorithm** + + :func:`~mpmath.polyroots` implements the Durand-Kerner method [1], which + uses complex arithmetic to locate all roots simultaneously. + The Durand-Kerner method can be viewed as approximately performing + simultaneous Newton iteration for all the roots. In particular, + the convergence to simple roots is quadratic, just like Newton's + method. + + Although all roots are internally calculated using complex arithmetic, any + root found to have an imaginary part smaller than the estimated numerical + error is truncated to a real number (small real parts are also chopped). + Real roots are placed first in the returned list, sorted by value. The + remaining complex roots are sorted by their real parts so that conjugate + roots end up next to each other. + + **References** + + 1. http://en.wikipedia.org/wiki/Durand-Kerner_method + + """ + if len(coeffs) <= 1: + if not coeffs or not coeffs[0]: + raise ValueError("Input to polyroots must not be the zero polynomial") + # Constant polynomial with no roots + return [] + + orig = ctx.prec + tol = +ctx.eps + with ctx.extraprec(extraprec): + deg = len(coeffs) - 1 + # Must be monic + lead = ctx.convert(coeffs[0]) + if lead == 1: + coeffs = [ctx.convert(c) for c in coeffs] + else: + coeffs = [c/lead for c in coeffs] + f = lambda x: ctx.polyval(coeffs, x) + if roots_init is None: + roots = [ctx.mpc((0.4+0.9j)**n) for n in xrange(deg)] + else: + roots = [None]*deg; + deg_init = min(deg, len(roots_init)) + roots[:deg_init] = list(roots_init[:deg_init]) + roots[deg_init:] = [ctx.mpc((0.4+0.9j)**n) for n + in xrange(deg_init,deg)] + err = [ctx.one for n in xrange(deg)] + # Durand-Kerner iteration until convergence + for step in xrange(maxsteps): + if abs(max(err)) < tol: + break + for i in xrange(deg): + p = roots[i] + x = f(p) + for j in range(deg): + if i != j: + try: + x /= (p-roots[j]) + except ZeroDivisionError: + continue + roots[i] = p - x + err[i] = abs(x) + if abs(max(err)) >= tol: + raise ctx.NoConvergence("Didn't converge in maxsteps=%d steps." \ + % maxsteps) + # Remove small real or imaginary parts + if cleanup: + for i in xrange(deg): + if abs(roots[i]) < tol: + roots[i] = ctx.zero + elif abs(ctx._im(roots[i])) < tol: + roots[i] = roots[i].real + elif abs(ctx._re(roots[i])) < tol: + roots[i] = roots[i].imag * 1j + roots.sort(key=lambda x: (abs(ctx._im(x)), ctx._re(x))) + if error: + err = max(err) + err = max(err, ctx.ldexp(1, -orig+1)) + return [+r for r in roots], +err + else: + return [+r for r in roots] diff --git a/venv/lib/python3.10/site-packages/mpmath/calculus/quadrature.py b/venv/lib/python3.10/site-packages/mpmath/calculus/quadrature.py new file mode 100644 index 0000000000000000000000000000000000000000..0545b3ad3e6f70a44f4ec31a0c3bcfb4ffde422b --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/calculus/quadrature.py @@ -0,0 +1,1115 @@ +import math + +from ..libmp.backend import xrange + +class QuadratureRule(object): + """ + Quadrature rules are implemented using this class, in order to + simplify the code and provide a common infrastructure + for tasks such as error estimation and node caching. + + You can implement a custom quadrature rule by subclassing + :class:`QuadratureRule` and implementing the appropriate + methods. The subclass can then be used by :func:`~mpmath.quad` by + passing it as the *method* argument. + + :class:`QuadratureRule` instances are supposed to be singletons. + :class:`QuadratureRule` therefore implements instance caching + in :func:`~mpmath.__new__`. + """ + + def __init__(self, ctx): + self.ctx = ctx + self.standard_cache = {} + self.transformed_cache = {} + self.interval_count = {} + + def clear(self): + """ + Delete cached node data. + """ + self.standard_cache = {} + self.transformed_cache = {} + self.interval_count = {} + + def calc_nodes(self, degree, prec, verbose=False): + r""" + Compute nodes for the standard interval `[-1, 1]`. Subclasses + should probably implement only this method, and use + :func:`~mpmath.get_nodes` method to retrieve the nodes. + """ + raise NotImplementedError + + def get_nodes(self, a, b, degree, prec, verbose=False): + """ + Return nodes for given interval, degree and precision. The + nodes are retrieved from a cache if already computed; + otherwise they are computed by calling :func:`~mpmath.calc_nodes` + and are then cached. + + Subclasses should probably not implement this method, + but just implement :func:`~mpmath.calc_nodes` for the actual + node computation. + """ + key = (a, b, degree, prec) + if key in self.transformed_cache: + return self.transformed_cache[key] + orig = self.ctx.prec + try: + self.ctx.prec = prec+20 + # Get nodes on standard interval + if (degree, prec) in self.standard_cache: + nodes = self.standard_cache[degree, prec] + else: + nodes = self.calc_nodes(degree, prec, verbose) + self.standard_cache[degree, prec] = nodes + # Transform to general interval + nodes = self.transform_nodes(nodes, a, b, verbose) + if key in self.interval_count: + self.transformed_cache[key] = nodes + else: + self.interval_count[key] = True + finally: + self.ctx.prec = orig + return nodes + + def transform_nodes(self, nodes, a, b, verbose=False): + r""" + Rescale standardized nodes (for `[-1, 1]`) to a general + interval `[a, b]`. For a finite interval, a simple linear + change of variables is used. Otherwise, the following + transformations are used: + + .. math :: + + \lbrack a, \infty \rbrack : t = \frac{1}{x} + (a-1) + + \lbrack -\infty, b \rbrack : t = (b+1) - \frac{1}{x} + + \lbrack -\infty, \infty \rbrack : t = \frac{x}{\sqrt{1-x^2}} + + """ + ctx = self.ctx + a = ctx.convert(a) + b = ctx.convert(b) + one = ctx.one + if (a, b) == (-one, one): + return nodes + half = ctx.mpf(0.5) + new_nodes = [] + if ctx.isinf(a) or ctx.isinf(b): + if (a, b) == (ctx.ninf, ctx.inf): + p05 = -half + for x, w in nodes: + x2 = x*x + px1 = one-x2 + spx1 = px1**p05 + x = x*spx1 + w *= spx1/px1 + new_nodes.append((x, w)) + elif a == ctx.ninf: + b1 = b+1 + for x, w in nodes: + u = 2/(x+one) + x = b1-u + w *= half*u**2 + new_nodes.append((x, w)) + elif b == ctx.inf: + a1 = a-1 + for x, w in nodes: + u = 2/(x+one) + x = a1+u + w *= half*u**2 + new_nodes.append((x, w)) + elif a == ctx.inf or b == ctx.ninf: + return [(x,-w) for (x,w) in self.transform_nodes(nodes, b, a, verbose)] + else: + raise NotImplementedError + else: + # Simple linear change of variables + C = (b-a)/2 + D = (b+a)/2 + for x, w in nodes: + new_nodes.append((D+C*x, C*w)) + return new_nodes + + def guess_degree(self, prec): + """ + Given a desired precision `p` in bits, estimate the degree `m` + of the quadrature required to accomplish full accuracy for + typical integrals. By default, :func:`~mpmath.quad` will perform up + to `m` iterations. The value of `m` should be a slight + overestimate, so that "slightly bad" integrals can be dealt + with automatically using a few extra iterations. On the + other hand, it should not be too big, so :func:`~mpmath.quad` can + quit within a reasonable amount of time when it is given + an "unsolvable" integral. + + The default formula used by :func:`~mpmath.guess_degree` is tuned + for both :class:`TanhSinh` and :class:`GaussLegendre`. + The output is roughly as follows: + + +---------+---------+ + | `p` | `m` | + +=========+=========+ + | 50 | 6 | + +---------+---------+ + | 100 | 7 | + +---------+---------+ + | 500 | 10 | + +---------+---------+ + | 3000 | 12 | + +---------+---------+ + + This formula is based purely on a limited amount of + experimentation and will sometimes be wrong. + """ + # Expected degree + # XXX: use mag + g = int(4 + max(0, self.ctx.log(prec/30.0, 2))) + # Reasonable "worst case" + g += 2 + return g + + def estimate_error(self, results, prec, epsilon): + r""" + Given results from integrations `[I_1, I_2, \ldots, I_k]` done + with a quadrature of rule of degree `1, 2, \ldots, k`, estimate + the error of `I_k`. + + For `k = 2`, we estimate `|I_{\infty}-I_2|` as `|I_2-I_1|`. + + For `k > 2`, we extrapolate `|I_{\infty}-I_k| \approx |I_{k+1}-I_k|` + from `|I_k-I_{k-1}|` and `|I_k-I_{k-2}|` under the assumption + that each degree increment roughly doubles the accuracy of + the quadrature rule (this is true for both :class:`TanhSinh` + and :class:`GaussLegendre`). The extrapolation formula is given + by Borwein, Bailey & Girgensohn. Although not very conservative, + this method seems to be very robust in practice. + """ + if len(results) == 2: + return abs(results[0]-results[1]) + try: + if results[-1] == results[-2] == results[-3]: + return self.ctx.zero + D1 = self.ctx.log(abs(results[-1]-results[-2]), 10) + D2 = self.ctx.log(abs(results[-1]-results[-3]), 10) + except ValueError: + return epsilon + D3 = -prec + D4 = min(0, max(D1**2/D2, 2*D1, D3)) + return self.ctx.mpf(10) ** int(D4) + + def summation(self, f, points, prec, epsilon, max_degree, verbose=False): + """ + Main integration function. Computes the 1D integral over + the interval specified by *points*. For each subinterval, + performs quadrature of degree from 1 up to *max_degree* + until :func:`~mpmath.estimate_error` signals convergence. + + :func:`~mpmath.summation` transforms each subintegration to + the standard interval and then calls :func:`~mpmath.sum_next`. + """ + ctx = self.ctx + I = total_err = ctx.zero + for i in xrange(len(points)-1): + a, b = points[i], points[i+1] + if a == b: + continue + # XXX: we could use a single variable transformation, + # but this is not good in practice. We get better accuracy + # by having 0 as an endpoint. + if (a, b) == (ctx.ninf, ctx.inf): + _f = f + f = lambda x: _f(-x) + _f(x) + a, b = (ctx.zero, ctx.inf) + results = [] + err = ctx.zero + for degree in xrange(1, max_degree+1): + nodes = self.get_nodes(a, b, degree, prec, verbose) + if verbose: + print("Integrating from %s to %s (degree %s of %s)" % \ + (ctx.nstr(a), ctx.nstr(b), degree, max_degree)) + result = self.sum_next(f, nodes, degree, prec, results, verbose) + results.append(result) + if degree > 1: + err = self.estimate_error(results, prec, epsilon) + if verbose: + print("Estimated error:", ctx.nstr(err), " epsilon:", ctx.nstr(epsilon), " result: ", ctx.nstr(result)) + if err <= epsilon: + break + I += results[-1] + total_err += err + if total_err > epsilon: + if verbose: + print("Failed to reach full accuracy. Estimated error:", ctx.nstr(total_err)) + return I, total_err + + def sum_next(self, f, nodes, degree, prec, previous, verbose=False): + r""" + Evaluates the step sum `\sum w_k f(x_k)` where the *nodes* list + contains the `(w_k, x_k)` pairs. + + :func:`~mpmath.summation` will supply the list *results* of + values computed by :func:`~mpmath.sum_next` at previous degrees, in + case the quadrature rule is able to reuse them. + """ + return self.ctx.fdot((w, f(x)) for (x,w) in nodes) + + +class TanhSinh(QuadratureRule): + r""" + This class implements "tanh-sinh" or "doubly exponential" + quadrature. This quadrature rule is based on the Euler-Maclaurin + integral formula. By performing a change of variables involving + nested exponentials / hyperbolic functions (hence the name), the + derivatives at the endpoints vanish rapidly. Since the error term + in the Euler-Maclaurin formula depends on the derivatives at the + endpoints, a simple step sum becomes extremely accurate. In + practice, this means that doubling the number of evaluation + points roughly doubles the number of accurate digits. + + Comparison to Gauss-Legendre: + * Initial computation of nodes is usually faster + * Handles endpoint singularities better + * Handles infinite integration intervals better + * Is slower for smooth integrands once nodes have been computed + + The implementation of the tanh-sinh algorithm is based on the + description given in Borwein, Bailey & Girgensohn, "Experimentation + in Mathematics - Computational Paths to Discovery", A K Peters, + 2003, pages 312-313. In the present implementation, a few + improvements have been made: + + * A more efficient scheme is used to compute nodes (exploiting + recurrence for the exponential function) + * The nodes are computed successively instead of all at once + + **References** + + * [Bailey]_ + * http://users.cs.dal.ca/~jborwein/tanh-sinh.pdf + + """ + + def sum_next(self, f, nodes, degree, prec, previous, verbose=False): + """ + Step sum for tanh-sinh quadrature of degree `m`. We exploit the + fact that half of the abscissas at degree `m` are precisely the + abscissas from degree `m-1`. Thus reusing the result from + the previous level allows a 2x speedup. + """ + h = self.ctx.mpf(2)**(-degree) + # Abscissas overlap, so reusing saves half of the time + if previous: + S = previous[-1]/(h*2) + else: + S = self.ctx.zero + S += self.ctx.fdot((w,f(x)) for (x,w) in nodes) + return h*S + + def calc_nodes(self, degree, prec, verbose=False): + r""" + The abscissas and weights for tanh-sinh quadrature of degree + `m` are given by + + .. math:: + + x_k = \tanh(\pi/2 \sinh(t_k)) + + w_k = \pi/2 \cosh(t_k) / \cosh(\pi/2 \sinh(t_k))^2 + + where `t_k = t_0 + hk` for a step length `h \sim 2^{-m}`. The + list of nodes is actually infinite, but the weights die off so + rapidly that only a few are needed. + """ + ctx = self.ctx + nodes = [] + + extra = 20 + ctx.prec += extra + tol = ctx.ldexp(1, -prec-10) + pi4 = ctx.pi/4 + + # For simplicity, we work in steps h = 1/2^n, with the first point + # offset so that we can reuse the sum from the previous degree + + # We define degree 1 to include the "degree 0" steps, including + # the point x = 0. (It doesn't work well otherwise; not sure why.) + t0 = ctx.ldexp(1, -degree) + if degree == 1: + #nodes.append((mpf(0), pi4)) + #nodes.append((-mpf(0), pi4)) + nodes.append((ctx.zero, ctx.pi/2)) + h = t0 + else: + h = t0*2 + + # Since h is fixed, we can compute the next exponential + # by simply multiplying by exp(h) + expt0 = ctx.exp(t0) + a = pi4 * expt0 + b = pi4 / expt0 + udelta = ctx.exp(h) + urdelta = 1/udelta + + for k in xrange(0, 20*2**degree+1): + # Reference implementation: + # t = t0 + k*h + # x = tanh(pi/2 * sinh(t)) + # w = pi/2 * cosh(t) / cosh(pi/2 * sinh(t))**2 + + # Fast implementation. Note that c = exp(pi/2 * sinh(t)) + c = ctx.exp(a-b) + d = 1/c + co = (c+d)/2 + si = (c-d)/2 + x = si / co + w = (a+b) / co**2 + diff = abs(x-1) + if diff <= tol: + break + + nodes.append((x, w)) + nodes.append((-x, w)) + + a *= udelta + b *= urdelta + + if verbose and k % 300 == 150: + # Note: the number displayed is rather arbitrary. Should + # figure out how to print something that looks more like a + # percentage + print("Calculating nodes:", ctx.nstr(-ctx.log(diff, 10) / prec)) + + ctx.prec -= extra + return nodes + + +class GaussLegendre(QuadratureRule): + r""" + This class implements Gauss-Legendre quadrature, which is + exceptionally efficient for polynomials and polynomial-like (i.e. + very smooth) integrands. + + The abscissas and weights are given by roots and values of + Legendre polynomials, which are the orthogonal polynomials + on `[-1, 1]` with respect to the unit weight + (see :func:`~mpmath.legendre`). + + In this implementation, we take the "degree" `m` of the quadrature + to denote a Gauss-Legendre rule of degree `3 \cdot 2^m` (following + Borwein, Bailey & Girgensohn). This way we get quadratic, rather + than linear, convergence as the degree is incremented. + + Comparison to tanh-sinh quadrature: + * Is faster for smooth integrands once nodes have been computed + * Initial computation of nodes is usually slower + * Handles endpoint singularities worse + * Handles infinite integration intervals worse + + """ + + def calc_nodes(self, degree, prec, verbose=False): + r""" + Calculates the abscissas and weights for Gauss-Legendre + quadrature of degree of given degree (actually `3 \cdot 2^m`). + """ + ctx = self.ctx + # It is important that the epsilon is set lower than the + # "real" epsilon + epsilon = ctx.ldexp(1, -prec-8) + # Fairly high precision might be required for accurate + # evaluation of the roots + orig = ctx.prec + ctx.prec = int(prec*1.5) + if degree == 1: + x = ctx.sqrt(ctx.mpf(3)/5) + w = ctx.mpf(5)/9 + nodes = [(-x,w),(ctx.zero,ctx.mpf(8)/9),(x,w)] + ctx.prec = orig + return nodes + nodes = [] + n = 3*2**(degree-1) + upto = n//2 + 1 + for j in xrange(1, upto): + # Asymptotic formula for the roots + r = ctx.mpf(math.cos(math.pi*(j-0.25)/(n+0.5))) + # Newton iteration + while 1: + t1, t2 = 1, 0 + # Evaluates the Legendre polynomial using its defining + # recurrence relation + for j1 in xrange(1,n+1): + t3, t2, t1 = t2, t1, ((2*j1-1)*r*t1 - (j1-1)*t2)/j1 + t4 = n*(r*t1-t2)/(r**2-1) + a = t1/t4 + r = r - a + if abs(a) < epsilon: + break + x = r + w = 2/((1-r**2)*t4**2) + if verbose and j % 30 == 15: + print("Computing nodes (%i of %i)" % (j, upto)) + nodes.append((x, w)) + nodes.append((-x, w)) + ctx.prec = orig + return nodes + +class QuadratureMethods(object): + + def __init__(ctx, *args, **kwargs): + ctx._gauss_legendre = GaussLegendre(ctx) + ctx._tanh_sinh = TanhSinh(ctx) + + def quad(ctx, f, *points, **kwargs): + r""" + Computes a single, double or triple integral over a given + 1D interval, 2D rectangle, or 3D cuboid. A basic example:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> quad(sin, [0, pi]) + 2.0 + + A basic 2D integral:: + + >>> f = lambda x, y: cos(x+y/2) + >>> quad(f, [-pi/2, pi/2], [0, pi]) + 4.0 + + **Interval format** + + The integration range for each dimension may be specified + using a list or tuple. Arguments are interpreted as follows: + + ``quad(f, [x1, x2])`` -- calculates + `\int_{x_1}^{x_2} f(x) \, dx` + + ``quad(f, [x1, x2], [y1, y2])`` -- calculates + `\int_{x_1}^{x_2} \int_{y_1}^{y_2} f(x,y) \, dy \, dx` + + ``quad(f, [x1, x2], [y1, y2], [z1, z2])`` -- calculates + `\int_{x_1}^{x_2} \int_{y_1}^{y_2} \int_{z_1}^{z_2} f(x,y,z) + \, dz \, dy \, dx` + + Endpoints may be finite or infinite. An interval descriptor + may also contain more than two points. In this + case, the integration is split into subintervals, between + each pair of consecutive points. This is useful for + dealing with mid-interval discontinuities, or integrating + over large intervals where the function is irregular or + oscillates. + + **Options** + + :func:`~mpmath.quad` recognizes the following keyword arguments: + + *method* + Chooses integration algorithm (described below). + *error* + If set to true, :func:`~mpmath.quad` returns `(v, e)` where `v` is the + integral and `e` is the estimated error. + *maxdegree* + Maximum degree of the quadrature rule to try before + quitting. + *verbose* + Print details about progress. + + **Algorithms** + + Mpmath presently implements two integration algorithms: tanh-sinh + quadrature and Gauss-Legendre quadrature. These can be selected + using *method='tanh-sinh'* or *method='gauss-legendre'* or by + passing the classes *method=TanhSinh*, *method=GaussLegendre*. + The functions :func:`~mpmath.quadts` and :func:`~mpmath.quadgl` are also available + as shortcuts. + + Both algorithms have the property that doubling the number of + evaluation points roughly doubles the accuracy, so both are ideal + for high precision quadrature (hundreds or thousands of digits). + + At high precision, computing the nodes and weights for the + integration can be expensive (more expensive than computing the + function values). To make repeated integrations fast, nodes + are automatically cached. + + The advantages of the tanh-sinh algorithm are that it tends to + handle endpoint singularities well, and that the nodes are cheap + to compute on the first run. For these reasons, it is used by + :func:`~mpmath.quad` as the default algorithm. + + Gauss-Legendre quadrature often requires fewer function + evaluations, and is therefore often faster for repeated use, but + the algorithm does not handle endpoint singularities as well and + the nodes are more expensive to compute. Gauss-Legendre quadrature + can be a better choice if the integrand is smooth and repeated + integrations are required (e.g. for multiple integrals). + + See the documentation for :class:`TanhSinh` and + :class:`GaussLegendre` for additional details. + + **Examples of 1D integrals** + + Intervals may be infinite or half-infinite. The following two + examples evaluate the limits of the inverse tangent function + (`\int 1/(1+x^2) = \tan^{-1} x`), and the Gaussian integral + `\int_{\infty}^{\infty} \exp(-x^2)\,dx = \sqrt{\pi}`:: + + >>> mp.dps = 15 + >>> quad(lambda x: 2/(x**2+1), [0, inf]) + 3.14159265358979 + >>> quad(lambda x: exp(-x**2), [-inf, inf])**2 + 3.14159265358979 + + Integrals can typically be resolved to high precision. + The following computes 50 digits of `\pi` by integrating the + area of the half-circle defined by `x^2 + y^2 \le 1`, + `-1 \le x \le 1`, `y \ge 0`:: + + >>> mp.dps = 50 + >>> 2*quad(lambda x: sqrt(1-x**2), [-1, 1]) + 3.1415926535897932384626433832795028841971693993751 + + One can just as well compute 1000 digits (output truncated):: + + >>> mp.dps = 1000 + >>> 2*quad(lambda x: sqrt(1-x**2), [-1, 1]) #doctest:+ELLIPSIS + 3.141592653589793238462643383279502884...216420199 + + Complex integrals are supported. The following computes + a residue at `z = 0` by integrating counterclockwise along the + diamond-shaped path from `1` to `+i` to `-1` to `-i` to `1`:: + + >>> mp.dps = 15 + >>> chop(quad(lambda z: 1/z, [1,j,-1,-j,1])) + (0.0 + 6.28318530717959j) + + **Examples of 2D and 3D integrals** + + Here are several nice examples of analytically solvable + 2D integrals (taken from MathWorld [1]) that can be evaluated + to high precision fairly rapidly by :func:`~mpmath.quad`:: + + >>> mp.dps = 30 + >>> f = lambda x, y: (x-1)/((1-x*y)*log(x*y)) + >>> quad(f, [0, 1], [0, 1]) + 0.577215664901532860606512090082 + >>> +euler + 0.577215664901532860606512090082 + + >>> f = lambda x, y: 1/sqrt(1+x**2+y**2) + >>> quad(f, [-1, 1], [-1, 1]) + 3.17343648530607134219175646705 + >>> 4*log(2+sqrt(3))-2*pi/3 + 3.17343648530607134219175646705 + + >>> f = lambda x, y: 1/(1-x**2 * y**2) + >>> quad(f, [0, 1], [0, 1]) + 1.23370055013616982735431137498 + >>> pi**2 / 8 + 1.23370055013616982735431137498 + + >>> quad(lambda x, y: 1/(1-x*y), [0, 1], [0, 1]) + 1.64493406684822643647241516665 + >>> pi**2 / 6 + 1.64493406684822643647241516665 + + Multiple integrals may be done over infinite ranges:: + + >>> mp.dps = 15 + >>> print(quad(lambda x,y: exp(-x-y), [0, inf], [1, inf])) + 0.367879441171442 + >>> print(1/e) + 0.367879441171442 + + For nonrectangular areas, one can call :func:`~mpmath.quad` recursively. + For example, we can replicate the earlier example of calculating + `\pi` by integrating over the unit-circle, and actually use double + quadrature to actually measure the area circle:: + + >>> f = lambda x: quad(lambda y: 1, [-sqrt(1-x**2), sqrt(1-x**2)]) + >>> quad(f, [-1, 1]) + 3.14159265358979 + + Here is a simple triple integral:: + + >>> mp.dps = 15 + >>> f = lambda x,y,z: x*y/(1+z) + >>> quad(f, [0,1], [0,1], [1,2], method='gauss-legendre') + 0.101366277027041 + >>> (log(3)-log(2))/4 + 0.101366277027041 + + **Singularities** + + Both tanh-sinh and Gauss-Legendre quadrature are designed to + integrate smooth (infinitely differentiable) functions. Neither + algorithm copes well with mid-interval singularities (such as + mid-interval discontinuities in `f(x)` or `f'(x)`). + The best solution is to split the integral into parts:: + + >>> mp.dps = 15 + >>> quad(lambda x: abs(sin(x)), [0, 2*pi]) # Bad + 3.99900894176779 + >>> quad(lambda x: abs(sin(x)), [0, pi, 2*pi]) # Good + 4.0 + + The tanh-sinh rule often works well for integrands having a + singularity at one or both endpoints:: + + >>> mp.dps = 15 + >>> quad(log, [0, 1], method='tanh-sinh') # Good + -1.0 + >>> quad(log, [0, 1], method='gauss-legendre') # Bad + -0.999932197413801 + + However, the result may still be inaccurate for some functions:: + + >>> quad(lambda x: 1/sqrt(x), [0, 1], method='tanh-sinh') + 1.99999999946942 + + This problem is not due to the quadrature rule per se, but to + numerical amplification of errors in the nodes. The problem can be + circumvented by temporarily increasing the precision:: + + >>> mp.dps = 30 + >>> a = quad(lambda x: 1/sqrt(x), [0, 1], method='tanh-sinh') + >>> mp.dps = 15 + >>> +a + 2.0 + + **Highly variable functions** + + For functions that are smooth (in the sense of being infinitely + differentiable) but contain sharp mid-interval peaks or many + "bumps", :func:`~mpmath.quad` may fail to provide full accuracy. For + example, with default settings, :func:`~mpmath.quad` is able to integrate + `\sin(x)` accurately over an interval of length 100 but not over + length 1000:: + + >>> quad(sin, [0, 100]); 1-cos(100) # Good + 0.137681127712316 + 0.137681127712316 + >>> quad(sin, [0, 1000]); 1-cos(1000) # Bad + -37.8587612408485 + 0.437620923709297 + + One solution is to break the integration into 10 intervals of + length 100:: + + >>> quad(sin, linspace(0, 1000, 10)) # Good + 0.437620923709297 + + Another is to increase the degree of the quadrature:: + + >>> quad(sin, [0, 1000], maxdegree=10) # Also good + 0.437620923709297 + + Whether splitting the interval or increasing the degree is + more efficient differs from case to case. Another example is the + function `1/(1+x^2)`, which has a sharp peak centered around + `x = 0`:: + + >>> f = lambda x: 1/(1+x**2) + >>> quad(f, [-100, 100]) # Bad + 3.64804647105268 + >>> quad(f, [-100, 100], maxdegree=10) # Good + 3.12159332021646 + >>> quad(f, [-100, 0, 100]) # Also good + 3.12159332021646 + + **References** + + 1. http://mathworld.wolfram.com/DoubleIntegral.html + + """ + rule = kwargs.get('method', 'tanh-sinh') + if type(rule) is str: + if rule == 'tanh-sinh': + rule = ctx._tanh_sinh + elif rule == 'gauss-legendre': + rule = ctx._gauss_legendre + else: + raise ValueError("unknown quadrature rule: %s" % rule) + else: + rule = rule(ctx) + verbose = kwargs.get('verbose') + dim = len(points) + orig = prec = ctx.prec + epsilon = ctx.eps/8 + m = kwargs.get('maxdegree') or rule.guess_degree(prec) + points = [ctx._as_points(p) for p in points] + try: + ctx.prec += 20 + if dim == 1: + v, err = rule.summation(f, points[0], prec, epsilon, m, verbose) + elif dim == 2: + v, err = rule.summation(lambda x: \ + rule.summation(lambda y: f(x,y), \ + points[1], prec, epsilon, m)[0], + points[0], prec, epsilon, m, verbose) + elif dim == 3: + v, err = rule.summation(lambda x: \ + rule.summation(lambda y: \ + rule.summation(lambda z: f(x,y,z), \ + points[2], prec, epsilon, m)[0], + points[1], prec, epsilon, m)[0], + points[0], prec, epsilon, m, verbose) + else: + raise NotImplementedError("quadrature must have dim 1, 2 or 3") + finally: + ctx.prec = orig + if kwargs.get("error"): + return +v, err + return +v + + def quadts(ctx, *args, **kwargs): + """ + Performs tanh-sinh quadrature. The call + + quadts(func, *points, ...) + + is simply a shortcut for: + + quad(func, *points, ..., method=TanhSinh) + + For example, a single integral and a double integral: + + quadts(lambda x: exp(cos(x)), [0, 1]) + quadts(lambda x, y: exp(cos(x+y)), [0, 1], [0, 1]) + + See the documentation for quad for information about how points + arguments and keyword arguments are parsed. + + See documentation for TanhSinh for algorithmic information about + tanh-sinh quadrature. + """ + kwargs['method'] = 'tanh-sinh' + return ctx.quad(*args, **kwargs) + + def quadgl(ctx, *args, **kwargs): + """ + Performs Gauss-Legendre quadrature. The call + + quadgl(func, *points, ...) + + is simply a shortcut for: + + quad(func, *points, ..., method=GaussLegendre) + + For example, a single integral and a double integral: + + quadgl(lambda x: exp(cos(x)), [0, 1]) + quadgl(lambda x, y: exp(cos(x+y)), [0, 1], [0, 1]) + + See the documentation for quad for information about how points + arguments and keyword arguments are parsed. + + See documentation for TanhSinh for algorithmic information about + tanh-sinh quadrature. + """ + kwargs['method'] = 'gauss-legendre' + return ctx.quad(*args, **kwargs) + + def quadosc(ctx, f, interval, omega=None, period=None, zeros=None): + r""" + Calculates + + .. math :: + + I = \int_a^b f(x) dx + + where at least one of `a` and `b` is infinite and where + `f(x) = g(x) \cos(\omega x + \phi)` for some slowly + decreasing function `g(x)`. With proper input, :func:`~mpmath.quadosc` + can also handle oscillatory integrals where the oscillation + rate is different from a pure sine or cosine wave. + + In the standard case when `|a| < \infty, b = \infty`, + :func:`~mpmath.quadosc` works by evaluating the infinite series + + .. math :: + + I = \int_a^{x_1} f(x) dx + + \sum_{k=1}^{\infty} \int_{x_k}^{x_{k+1}} f(x) dx + + where `x_k` are consecutive zeros (alternatively + some other periodic reference point) of `f(x)`. + Accordingly, :func:`~mpmath.quadosc` requires information about the + zeros of `f(x)`. For a periodic function, you can specify + the zeros by either providing the angular frequency `\omega` + (*omega*) or the *period* `2 \pi/\omega`. In general, you can + specify the `n`-th zero by providing the *zeros* arguments. + Below is an example of each:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> f = lambda x: sin(3*x)/(x**2+1) + >>> quadosc(f, [0,inf], omega=3) + 0.37833007080198 + >>> quadosc(f, [0,inf], period=2*pi/3) + 0.37833007080198 + >>> quadosc(f, [0,inf], zeros=lambda n: pi*n/3) + 0.37833007080198 + >>> (ei(3)*exp(-3)-exp(3)*ei(-3))/2 # Computed by Mathematica + 0.37833007080198 + + Note that *zeros* was specified to multiply `n` by the + *half-period*, not the full period. In theory, it does not matter + whether each partial integral is done over a half period or a full + period. However, if done over half-periods, the infinite series + passed to :func:`~mpmath.nsum` becomes an *alternating series* and this + typically makes the extrapolation much more efficient. + + Here is an example of an integration over the entire real line, + and a half-infinite integration starting at `-\infty`:: + + >>> quadosc(lambda x: cos(x)/(1+x**2), [-inf, inf], omega=1) + 1.15572734979092 + >>> pi/e + 1.15572734979092 + >>> quadosc(lambda x: cos(x)/x**2, [-inf, -1], period=2*pi) + -0.0844109505595739 + >>> cos(1)+si(1)-pi/2 + -0.0844109505595738 + + Of course, the integrand may contain a complex exponential just as + well as a real sine or cosine:: + + >>> quadosc(lambda x: exp(3*j*x)/(1+x**2), [-inf,inf], omega=3) + (0.156410688228254 + 0.0j) + >>> pi/e**3 + 0.156410688228254 + >>> quadosc(lambda x: exp(3*j*x)/(2+x+x**2), [-inf,inf], omega=3) + (0.00317486988463794 - 0.0447701735209082j) + >>> 2*pi/sqrt(7)/exp(3*(j+sqrt(7))/2) + (0.00317486988463794 - 0.0447701735209082j) + + **Non-periodic functions** + + If `f(x) = g(x) h(x)` for some function `h(x)` that is not + strictly periodic, *omega* or *period* might not work, and it might + be necessary to use *zeros*. + + A notable exception can be made for Bessel functions which, though not + periodic, are "asymptotically periodic" in a sufficiently strong sense + that the sum extrapolation will work out:: + + >>> quadosc(j0, [0, inf], period=2*pi) + 1.0 + >>> quadosc(j1, [0, inf], period=2*pi) + 1.0 + + More properly, one should provide the exact Bessel function zeros:: + + >>> j0zero = lambda n: findroot(j0, pi*(n-0.25)) + >>> quadosc(j0, [0, inf], zeros=j0zero) + 1.0 + + For an example where *zeros* becomes necessary, consider the + complete Fresnel integrals + + .. math :: + + \int_0^{\infty} \cos x^2\,dx = \int_0^{\infty} \sin x^2\,dx + = \sqrt{\frac{\pi}{8}}. + + Although the integrands do not decrease in magnitude as + `x \to \infty`, the integrals are convergent since the oscillation + rate increases (causing consecutive periods to asymptotically + cancel out). These integrals are virtually impossible to calculate + to any kind of accuracy using standard quadrature rules. However, + if one provides the correct asymptotic distribution of zeros + (`x_n \sim \sqrt{n}`), :func:`~mpmath.quadosc` works:: + + >>> mp.dps = 30 + >>> f = lambda x: cos(x**2) + >>> quadosc(f, [0,inf], zeros=lambda n:sqrt(pi*n)) + 0.626657068657750125603941321203 + >>> f = lambda x: sin(x**2) + >>> quadosc(f, [0,inf], zeros=lambda n:sqrt(pi*n)) + 0.626657068657750125603941321203 + >>> sqrt(pi/8) + 0.626657068657750125603941321203 + + (Interestingly, these integrals can still be evaluated if one + places some other constant than `\pi` in the square root sign.) + + In general, if `f(x) \sim g(x) \cos(h(x))`, the zeros follow + the inverse-function distribution `h^{-1}(x)`:: + + >>> mp.dps = 15 + >>> f = lambda x: sin(exp(x)) + >>> quadosc(f, [1,inf], zeros=lambda n: log(n)) + -0.25024394235267 + >>> pi/2-si(e) + -0.250243942352671 + + **Non-alternating functions** + + If the integrand oscillates around a positive value, without + alternating signs, the extrapolation might fail. A simple trick + that sometimes works is to multiply or divide the frequency by 2:: + + >>> f = lambda x: 1/x**2+sin(x)/x**4 + >>> quadosc(f, [1,inf], omega=1) # Bad + 1.28642190869861 + >>> quadosc(f, [1,inf], omega=0.5) # Perfect + 1.28652953559617 + >>> 1+(cos(1)+ci(1)+sin(1))/6 + 1.28652953559617 + + **Fast decay** + + :func:`~mpmath.quadosc` is primarily useful for slowly decaying + integrands. If the integrand decreases exponentially or faster, + :func:`~mpmath.quad` will likely handle it without trouble (and generally be + much faster than :func:`~mpmath.quadosc`):: + + >>> quadosc(lambda x: cos(x)/exp(x), [0, inf], omega=1) + 0.5 + >>> quad(lambda x: cos(x)/exp(x), [0, inf]) + 0.5 + + """ + a, b = ctx._as_points(interval) + a = ctx.convert(a) + b = ctx.convert(b) + if [omega, period, zeros].count(None) != 2: + raise ValueError( \ + "must specify exactly one of omega, period, zeros") + if a == ctx.ninf and b == ctx.inf: + s1 = ctx.quadosc(f, [a, 0], omega=omega, zeros=zeros, period=period) + s2 = ctx.quadosc(f, [0, b], omega=omega, zeros=zeros, period=period) + return s1 + s2 + if a == ctx.ninf: + if zeros: + return ctx.quadosc(lambda x:f(-x), [-b,-a], lambda n: zeros(-n)) + else: + return ctx.quadosc(lambda x:f(-x), [-b,-a], omega=omega, period=period) + if b != ctx.inf: + raise ValueError("quadosc requires an infinite integration interval") + if not zeros: + if omega: + period = 2*ctx.pi/omega + zeros = lambda n: n*period/2 + #for n in range(1,10): + # p = zeros(n) + # if p > a: + # break + #if n >= 9: + # raise ValueError("zeros do not appear to be correctly indexed") + n = 1 + s = ctx.quadgl(f, [a, zeros(n)]) + def term(k): + return ctx.quadgl(f, [zeros(k), zeros(k+1)]) + s += ctx.nsum(term, [n, ctx.inf]) + return s + + def quadsubdiv(ctx, f, interval, tol=None, maxintervals=None, **kwargs): + """ + Computes the integral of *f* over the interval or path specified + by *interval*, using :func:`~mpmath.quad` together with adaptive + subdivision of the interval. + + This function gives an accurate answer for some integrals where + :func:`~mpmath.quad` fails:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> quad(lambda x: abs(sin(x)), [0, 2*pi]) + 3.99900894176779 + >>> quadsubdiv(lambda x: abs(sin(x)), [0, 2*pi]) + 4.0 + >>> quadsubdiv(sin, [0, 1000]) + 0.437620923709297 + >>> quadsubdiv(lambda x: 1/(1+x**2), [-100, 100]) + 3.12159332021646 + >>> quadsubdiv(lambda x: ceil(x), [0, 100]) + 5050.0 + >>> quadsubdiv(lambda x: sin(x+exp(x)), [0,8]) + 0.347400172657248 + + The argument *maxintervals* can be set to limit the permissible + subdivision:: + + >>> quadsubdiv(lambda x: sin(x**2), [0,100], maxintervals=5, error=True) + (-5.40487904307774, 5.011) + >>> quadsubdiv(lambda x: sin(x**2), [0,100], maxintervals=100, error=True) + (0.631417921866934, 1.10101120134116e-17) + + Subdivision does not guarantee a correct answer since, the error + estimate on subintervals may be inaccurate:: + + >>> quadsubdiv(lambda x: sech(10*x-2)**2 + sech(100*x-40)**4 + sech(1000*x-600)**6, [0,1], error=True) + (0.210802735500549, 1.0001111101e-17) + >>> mp.dps = 20 + >>> quadsubdiv(lambda x: sech(10*x-2)**2 + sech(100*x-40)**4 + sech(1000*x-600)**6, [0,1], error=True) + (0.21080273550054927738, 2.200000001e-24) + + The second answer is correct. We can get an accurate result at lower + precision by forcing a finer initial subdivision:: + + >>> mp.dps = 15 + >>> quadsubdiv(lambda x: sech(10*x-2)**2 + sech(100*x-40)**4 + sech(1000*x-600)**6, linspace(0,1,5)) + 0.210802735500549 + + The following integral is too oscillatory for convergence, but we can get a + reasonable estimate:: + + >>> v, err = fp.quadsubdiv(lambda x: fp.sin(1/x), [0,1], error=True) + >>> round(v, 6), round(err, 6) + (0.504067, 1e-06) + >>> sin(1) - ci(1) + 0.504067061906928 + + """ + queue = [] + for i in range(len(interval)-1): + queue.append((interval[i], interval[i+1])) + total = ctx.zero + total_error = ctx.zero + if maxintervals is None: + maxintervals = 10 * ctx.prec + count = 0 + quad_args = kwargs.copy() + quad_args["verbose"] = False + quad_args["error"] = True + if tol is None: + tol = +ctx.eps + orig = ctx.prec + try: + ctx.prec += 5 + while queue: + a, b = queue.pop() + s, err = ctx.quad(f, [a, b], **quad_args) + if kwargs.get("verbose"): + print("subinterval", count, a, b, err) + if err < tol or count > maxintervals: + total += s + total_error += err + else: + count += 1 + if count == maxintervals and kwargs.get("verbose"): + print("warning: number of intervals exceeded maxintervals") + if a == -ctx.inf and b == ctx.inf: + m = 0 + elif a == -ctx.inf: + m = min(b-1, 2*b) + elif b == ctx.inf: + m = max(a+1, 2*a) + else: + m = a + (b - a) / 2 + queue.append((a, m)) + queue.append((m, b)) + finally: + ctx.prec = orig + if kwargs.get("error"): + return +total, +total_error + else: + return +total + +if __name__ == '__main__': + import doctest + doctest.testmod() diff --git a/venv/lib/python3.10/site-packages/mpmath/ctx_base.py b/venv/lib/python3.10/site-packages/mpmath/ctx_base.py new file mode 100644 index 0000000000000000000000000000000000000000..1946f8daf4dbe165b3943be09af361812828aab1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/ctx_base.py @@ -0,0 +1,494 @@ +from operator import gt, lt + +from .libmp.backend import xrange + +from .functions.functions import SpecialFunctions +from .functions.rszeta import RSCache +from .calculus.quadrature import QuadratureMethods +from .calculus.inverselaplace import LaplaceTransformInversionMethods +from .calculus.calculus import CalculusMethods +from .calculus.optimization import OptimizationMethods +from .calculus.odes import ODEMethods +from .matrices.matrices import MatrixMethods +from .matrices.calculus import MatrixCalculusMethods +from .matrices.linalg import LinearAlgebraMethods +from .matrices.eigen import Eigen +from .identification import IdentificationMethods +from .visualization import VisualizationMethods + +from . import libmp + +class Context(object): + pass + +class StandardBaseContext(Context, + SpecialFunctions, + RSCache, + QuadratureMethods, + LaplaceTransformInversionMethods, + CalculusMethods, + MatrixMethods, + MatrixCalculusMethods, + LinearAlgebraMethods, + Eigen, + IdentificationMethods, + OptimizationMethods, + ODEMethods, + VisualizationMethods): + + NoConvergence = libmp.NoConvergence + ComplexResult = libmp.ComplexResult + + def __init__(ctx): + ctx._aliases = {} + # Call those that need preinitialization (e.g. for wrappers) + SpecialFunctions.__init__(ctx) + RSCache.__init__(ctx) + QuadratureMethods.__init__(ctx) + LaplaceTransformInversionMethods.__init__(ctx) + CalculusMethods.__init__(ctx) + MatrixMethods.__init__(ctx) + + def _init_aliases(ctx): + for alias, value in ctx._aliases.items(): + try: + setattr(ctx, alias, getattr(ctx, value)) + except AttributeError: + pass + + _fixed_precision = False + + # XXX + verbose = False + + def warn(ctx, msg): + print("Warning:", msg) + + def bad_domain(ctx, msg): + raise ValueError(msg) + + def _re(ctx, x): + if hasattr(x, "real"): + return x.real + return x + + def _im(ctx, x): + if hasattr(x, "imag"): + return x.imag + return ctx.zero + + def _as_points(ctx, x): + return x + + def fneg(ctx, x, **kwargs): + return -ctx.convert(x) + + def fadd(ctx, x, y, **kwargs): + return ctx.convert(x)+ctx.convert(y) + + def fsub(ctx, x, y, **kwargs): + return ctx.convert(x)-ctx.convert(y) + + def fmul(ctx, x, y, **kwargs): + return ctx.convert(x)*ctx.convert(y) + + def fdiv(ctx, x, y, **kwargs): + return ctx.convert(x)/ctx.convert(y) + + def fsum(ctx, args, absolute=False, squared=False): + if absolute: + if squared: + return sum((abs(x)**2 for x in args), ctx.zero) + return sum((abs(x) for x in args), ctx.zero) + if squared: + return sum((x**2 for x in args), ctx.zero) + return sum(args, ctx.zero) + + def fdot(ctx, xs, ys=None, conjugate=False): + if ys is not None: + xs = zip(xs, ys) + if conjugate: + cf = ctx.conj + return sum((x*cf(y) for (x,y) in xs), ctx.zero) + else: + return sum((x*y for (x,y) in xs), ctx.zero) + + def fprod(ctx, args): + prod = ctx.one + for arg in args: + prod *= arg + return prod + + def nprint(ctx, x, n=6, **kwargs): + """ + Equivalent to ``print(nstr(x, n))``. + """ + print(ctx.nstr(x, n, **kwargs)) + + def chop(ctx, x, tol=None): + """ + Chops off small real or imaginary parts, or converts + numbers close to zero to exact zeros. The input can be a + single number or an iterable:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> chop(5+1e-10j, tol=1e-9) + mpf('5.0') + >>> nprint(chop([1.0, 1e-20, 3+1e-18j, -4, 2])) + [1.0, 0.0, 3.0, -4.0, 2.0] + + The tolerance defaults to ``100*eps``. + """ + if tol is None: + tol = 100*ctx.eps + try: + x = ctx.convert(x) + absx = abs(x) + if abs(x) < tol: + return ctx.zero + if ctx._is_complex_type(x): + #part_tol = min(tol, absx*tol) + part_tol = max(tol, absx*tol) + if abs(x.imag) < part_tol: + return x.real + if abs(x.real) < part_tol: + return ctx.mpc(0, x.imag) + except TypeError: + if isinstance(x, ctx.matrix): + return x.apply(lambda a: ctx.chop(a, tol)) + if hasattr(x, "__iter__"): + return [ctx.chop(a, tol) for a in x] + return x + + def almosteq(ctx, s, t, rel_eps=None, abs_eps=None): + r""" + Determine whether the difference between `s` and `t` is smaller + than a given epsilon, either relatively or absolutely. + + Both a maximum relative difference and a maximum difference + ('epsilons') may be specified. The absolute difference is + defined as `|s-t|` and the relative difference is defined + as `|s-t|/\max(|s|, |t|)`. + + If only one epsilon is given, both are set to the same value. + If none is given, both epsilons are set to `2^{-p+m}` where + `p` is the current working precision and `m` is a small + integer. The default setting typically allows :func:`~mpmath.almosteq` + to be used to check for mathematical equality + in the presence of small rounding errors. + + **Examples** + + >>> from mpmath import * + >>> mp.dps = 15 + >>> almosteq(3.141592653589793, 3.141592653589790) + True + >>> almosteq(3.141592653589793, 3.141592653589700) + False + >>> almosteq(3.141592653589793, 3.141592653589700, 1e-10) + True + >>> almosteq(1e-20, 2e-20) + True + >>> almosteq(1e-20, 2e-20, rel_eps=0, abs_eps=0) + False + + """ + t = ctx.convert(t) + if abs_eps is None and rel_eps is None: + rel_eps = abs_eps = ctx.ldexp(1, -ctx.prec+4) + if abs_eps is None: + abs_eps = rel_eps + elif rel_eps is None: + rel_eps = 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 + + def arange(ctx, *args): + r""" + This is a generalized version of Python's :func:`~mpmath.range` function + that accepts fractional endpoints and step sizes and + returns a list of ``mpf`` instances. Like :func:`~mpmath.range`, + :func:`~mpmath.arange` can be called with 1, 2 or 3 arguments: + + ``arange(b)`` + `[0, 1, 2, \ldots, x]` + ``arange(a, b)`` + `[a, a+1, a+2, \ldots, x]` + ``arange(a, b, h)`` + `[a, a+h, a+h, \ldots, x]` + + where `b-1 \le x < b` (in the third case, `b-h \le x < b`). + + Like Python's :func:`~mpmath.range`, the endpoint is not included. To + produce ranges where the endpoint is included, :func:`~mpmath.linspace` + is more convenient. + + **Examples** + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> arange(4) + [mpf('0.0'), mpf('1.0'), mpf('2.0'), mpf('3.0')] + >>> arange(1, 2, 0.25) + [mpf('1.0'), mpf('1.25'), mpf('1.5'), mpf('1.75')] + >>> arange(1, -1, -0.75) + [mpf('1.0'), mpf('0.25'), mpf('-0.5')] + + """ + if not len(args) <= 3: + raise TypeError('arange expected at most 3 arguments, got %i' + % len(args)) + if not len(args) >= 1: + raise TypeError('arange expected at least 1 argument, got %i' + % len(args)) + # set default + a = 0 + dt = 1 + # interpret arguments + if len(args) == 1: + b = args[0] + elif len(args) >= 2: + a = args[0] + b = args[1] + if len(args) == 3: + dt = args[2] + a, b, dt = ctx.mpf(a), ctx.mpf(b), ctx.mpf(dt) + assert a + dt != a, 'dt is too small and would cause an infinite loop' + # adapt code for sign of dt + if a > b: + if dt > 0: + return [] + op = gt + else: + if dt < 0: + return [] + op = lt + # create list + result = [] + i = 0 + t = a + while 1: + t = a + dt*i + i += 1 + if op(t, b): + result.append(t) + else: + break + return result + + def linspace(ctx, *args, **kwargs): + """ + ``linspace(a, b, n)`` returns a list of `n` evenly spaced + samples from `a` to `b`. The syntax ``linspace(mpi(a,b), n)`` + is also valid. + + This function is often more convenient than :func:`~mpmath.arange` + for partitioning an interval into subintervals, since + the endpoint is included:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> linspace(1, 4, 4) + [mpf('1.0'), mpf('2.0'), mpf('3.0'), mpf('4.0')] + + You may also provide the keyword argument ``endpoint=False``:: + + >>> linspace(1, 4, 4, endpoint=False) + [mpf('1.0'), mpf('1.75'), mpf('2.5'), mpf('3.25')] + + """ + if len(args) == 3: + a = ctx.mpf(args[0]) + b = ctx.mpf(args[1]) + n = int(args[2]) + elif len(args) == 2: + assert hasattr(args[0], '_mpi_') + a = args[0].a + b = args[0].b + n = int(args[1]) + else: + raise TypeError('linspace expected 2 or 3 arguments, got %i' \ + % len(args)) + if n < 1: + raise ValueError('n must be greater than 0') + if not 'endpoint' in kwargs or kwargs['endpoint']: + if n == 1: + return [ctx.mpf(a)] + step = (b - a) / ctx.mpf(n - 1) + y = [i*step + a for i in xrange(n)] + y[-1] = b + else: + step = (b - a) / ctx.mpf(n) + y = [i*step + a for i in xrange(n)] + return y + + def cos_sin(ctx, z, **kwargs): + return ctx.cos(z, **kwargs), ctx.sin(z, **kwargs) + + def cospi_sinpi(ctx, z, **kwargs): + return ctx.cospi(z, **kwargs), ctx.sinpi(z, **kwargs) + + def _default_hyper_maxprec(ctx, p): + return int(1000 * p**0.25 + 4*p) + + _gcd = staticmethod(libmp.gcd) + list_primes = staticmethod(libmp.list_primes) + isprime = staticmethod(libmp.isprime) + bernfrac = staticmethod(libmp.bernfrac) + moebius = staticmethod(libmp.moebius) + _ifac = staticmethod(libmp.ifac) + _eulernum = staticmethod(libmp.eulernum) + _stirling1 = staticmethod(libmp.stirling1) + _stirling2 = staticmethod(libmp.stirling2) + + def sum_accurately(ctx, terms, check_step=1): + prec = ctx.prec + try: + extraprec = 10 + while 1: + ctx.prec = prec + extraprec + 5 + max_mag = ctx.ninf + s = ctx.zero + k = 0 + for term in terms(): + s += term + if (not k % check_step) and term: + term_mag = ctx.mag(term) + max_mag = max(max_mag, term_mag) + sum_mag = ctx.mag(s) + if sum_mag - term_mag > ctx.prec: + break + k += 1 + cancellation = max_mag - sum_mag + if cancellation != cancellation: + break + if cancellation < extraprec or ctx._fixed_precision: + break + extraprec += min(ctx.prec, cancellation) + return s + finally: + ctx.prec = prec + + def mul_accurately(ctx, factors, check_step=1): + prec = ctx.prec + try: + extraprec = 10 + while 1: + ctx.prec = prec + extraprec + 5 + max_mag = ctx.ninf + one = ctx.one + s = one + k = 0 + for factor in factors(): + s *= factor + term = factor - one + if (not k % check_step): + term_mag = ctx.mag(term) + max_mag = max(max_mag, term_mag) + sum_mag = ctx.mag(s-one) + #if sum_mag - term_mag > ctx.prec: + # break + if -term_mag > ctx.prec: + break + k += 1 + cancellation = max_mag - sum_mag + if cancellation != cancellation: + break + if cancellation < extraprec or ctx._fixed_precision: + break + extraprec += min(ctx.prec, cancellation) + return s + finally: + ctx.prec = prec + + def power(ctx, x, y): + r"""Converts `x` and `y` to mpmath numbers and evaluates + `x^y = \exp(y \log(x))`:: + + >>> from mpmath import * + >>> mp.dps = 30; mp.pretty = True + >>> power(2, 0.5) + 1.41421356237309504880168872421 + + This shows the leading few digits of a large Mersenne prime + (performing the exact calculation ``2**43112609-1`` and + displaying the result in Python would be very slow):: + + >>> power(2, 43112609)-1 + 3.16470269330255923143453723949e+12978188 + """ + return ctx.convert(x) ** ctx.convert(y) + + def _zeta_int(ctx, n): + return ctx.zeta(n) + + def maxcalls(ctx, f, N): + """ + Return a wrapped copy of *f* that raises ``NoConvergence`` when *f* + has been called more than *N* times:: + + >>> from mpmath import * + >>> mp.dps = 15 + >>> f = maxcalls(sin, 10) + >>> print(sum(f(n) for n in range(10))) + 1.95520948210738 + >>> f(10) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + NoConvergence: maxcalls: function evaluated 10 times + + """ + counter = [0] + def f_maxcalls_wrapped(*args, **kwargs): + counter[0] += 1 + if counter[0] > N: + raise ctx.NoConvergence("maxcalls: function evaluated %i times" % N) + return f(*args, **kwargs) + return f_maxcalls_wrapped + + def memoize(ctx, f): + """ + Return a wrapped copy of *f* that caches computed values, i.e. + a memoized copy of *f*. Values are only reused if the cached precision + is equal to or higher than the working precision:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> f = memoize(maxcalls(sin, 1)) + >>> f(2) + 0.909297426825682 + >>> f(2) + 0.909297426825682 + >>> mp.dps = 25 + >>> f(2) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + NoConvergence: maxcalls: function evaluated 1 times + + """ + f_cache = {} + def f_cached(*args, **kwargs): + if kwargs: + key = args, tuple(kwargs.items()) + else: + key = args + prec = ctx.prec + if key in f_cache: + cprec, cvalue = f_cache[key] + if cprec >= prec: + return +cvalue + value = f(*args, **kwargs) + f_cache[key] = (prec, value) + return value + f_cached.__name__ = f.__name__ + f_cached.__doc__ = f.__doc__ + return f_cached diff --git a/venv/lib/python3.10/site-packages/mpmath/ctx_fp.py b/venv/lib/python3.10/site-packages/mpmath/ctx_fp.py new file mode 100644 index 0000000000000000000000000000000000000000..aa72ea5b03fde4da66b0d8fbf8ffa4012e3f6178 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/ctx_fp.py @@ -0,0 +1,253 @@ +from .ctx_base import StandardBaseContext + +import math +import cmath +from . import math2 + +from . import function_docs + +from .libmp import mpf_bernoulli, to_float, int_types +from . import libmp + +class FPContext(StandardBaseContext): + """ + Context for fast low-precision arithmetic (53-bit precision, giving at most + about 15-digit accuracy), using Python's builtin float and complex. + """ + + def __init__(ctx): + StandardBaseContext.__init__(ctx) + + # Override SpecialFunctions implementation + ctx.loggamma = math2.loggamma + ctx._bernoulli_cache = {} + ctx.pretty = False + + ctx._init_aliases() + + _mpq = lambda cls, x: float(x[0])/x[1] + + NoConvergence = libmp.NoConvergence + + def _get_prec(ctx): return 53 + def _set_prec(ctx, p): return + def _get_dps(ctx): return 15 + def _set_dps(ctx, p): return + + _fixed_precision = True + + prec = property(_get_prec, _set_prec) + dps = property(_get_dps, _set_dps) + + zero = 0.0 + one = 1.0 + eps = math2.EPS + inf = math2.INF + ninf = math2.NINF + nan = math2.NAN + j = 1j + + # Called by SpecialFunctions.__init__() + @classmethod + def _wrap_specfun(cls, name, f, wrap): + if wrap: + def f_wrapped(ctx, *args, **kwargs): + convert = ctx.convert + args = [convert(a) for a in args] + return f(ctx, *args, **kwargs) + else: + f_wrapped = f + f_wrapped.__doc__ = function_docs.__dict__.get(name, f.__doc__) + setattr(cls, name, f_wrapped) + + def bernoulli(ctx, n): + cache = ctx._bernoulli_cache + if n in cache: + return cache[n] + cache[n] = to_float(mpf_bernoulli(n, 53, 'n'), strict=True) + return cache[n] + + pi = math2.pi + e = math2.e + euler = math2.euler + sqrt2 = 1.4142135623730950488 + sqrt5 = 2.2360679774997896964 + phi = 1.6180339887498948482 + ln2 = 0.69314718055994530942 + ln10 = 2.302585092994045684 + euler = 0.57721566490153286061 + catalan = 0.91596559417721901505 + khinchin = 2.6854520010653064453 + apery = 1.2020569031595942854 + glaisher = 1.2824271291006226369 + + absmin = absmax = abs + + def is_special(ctx, x): + return x - x != 0.0 + + def isnan(ctx, x): + return x != x + + def isinf(ctx, x): + return abs(x) == math2.INF + + def isnormal(ctx, x): + if x: + return x - x == 0.0 + return False + + def isnpint(ctx, x): + if type(x) is complex: + if x.imag: + return False + x = x.real + return x <= 0.0 and round(x) == x + + mpf = float + mpc = complex + + def convert(ctx, x): + try: + return float(x) + except: + return complex(x) + + power = staticmethod(math2.pow) + sqrt = staticmethod(math2.sqrt) + exp = staticmethod(math2.exp) + ln = log = staticmethod(math2.log) + cos = staticmethod(math2.cos) + sin = staticmethod(math2.sin) + tan = staticmethod(math2.tan) + cos_sin = staticmethod(math2.cos_sin) + acos = staticmethod(math2.acos) + asin = staticmethod(math2.asin) + atan = staticmethod(math2.atan) + cosh = staticmethod(math2.cosh) + sinh = staticmethod(math2.sinh) + tanh = staticmethod(math2.tanh) + gamma = staticmethod(math2.gamma) + rgamma = staticmethod(math2.rgamma) + fac = factorial = staticmethod(math2.factorial) + floor = staticmethod(math2.floor) + ceil = staticmethod(math2.ceil) + cospi = staticmethod(math2.cospi) + sinpi = staticmethod(math2.sinpi) + cbrt = staticmethod(math2.cbrt) + _nthroot = staticmethod(math2.nthroot) + _ei = staticmethod(math2.ei) + _e1 = staticmethod(math2.e1) + _zeta = _zeta_int = staticmethod(math2.zeta) + + # XXX: math2 + def arg(ctx, z): + z = complex(z) + return math.atan2(z.imag, z.real) + + def expj(ctx, x): + return ctx.exp(ctx.j*x) + + def expjpi(ctx, x): + return ctx.exp(ctx.j*ctx.pi*x) + + ldexp = math.ldexp + frexp = math.frexp + + def mag(ctx, z): + if z: + return ctx.frexp(abs(z))[1] + return ctx.ninf + + def isint(ctx, z): + if hasattr(z, "imag"): # float/int don't have .real/.imag in py2.5 + if z.imag: + return False + z = z.real + try: + return z == int(z) + except: + return False + + def nint_distance(ctx, z): + if hasattr(z, "imag"): # float/int don't have .real/.imag in py2.5 + n = round(z.real) + else: + n = round(z) + if n == z: + return n, ctx.ninf + return n, ctx.mag(abs(z-n)) + + def _convert_param(ctx, z): + if type(z) is tuple: + p, q = z + return ctx.mpf(p) / q, 'R' + if hasattr(z, "imag"): # float/int don't have .real/.imag in py2.5 + intz = int(z.real) + else: + intz = int(z) + if z == intz: + return intz, 'Z' + return z, 'R' + + def _is_real_type(ctx, z): + return isinstance(z, float) or isinstance(z, int_types) + + def _is_complex_type(ctx, z): + return isinstance(z, complex) + + def hypsum(ctx, p, q, types, coeffs, z, maxterms=6000, **kwargs): + coeffs = list(coeffs) + num = range(p) + den = range(p,p+q) + tol = ctx.eps + s = t = 1.0 + k = 0 + while 1: + for i in num: t *= (coeffs[i]+k) + for i in den: t /= (coeffs[i]+k) + k += 1; t /= k; t *= z; s += t + if abs(t) < tol: + return s + if k > maxterms: + raise ctx.NoConvergence + + def atan2(ctx, x, y): + return math.atan2(x, y) + + def psi(ctx, m, z): + m = int(m) + if m == 0: + return ctx.digamma(z) + return (-1)**(m+1) * ctx.fac(m) * ctx.zeta(m+1, z) + + digamma = staticmethod(math2.digamma) + + def harmonic(ctx, x): + x = ctx.convert(x) + if x == 0 or x == 1: + return x + return ctx.digamma(x+1) + ctx.euler + + nstr = str + + def to_fixed(ctx, x, prec): + return int(math.ldexp(x, prec)) + + def rand(ctx): + import random + return random.random() + + _erf = staticmethod(math2.erf) + _erfc = staticmethod(math2.erfc) + + def sum_accurately(ctx, terms, check_step=1): + s = ctx.zero + k = 0 + for term in terms(): + s += term + if (not k % check_step) and term: + if abs(term) <= 1e-18*abs(s): + break + k += 1 + return s diff --git a/venv/lib/python3.10/site-packages/mpmath/ctx_iv.py b/venv/lib/python3.10/site-packages/mpmath/ctx_iv.py new file mode 100644 index 0000000000000000000000000000000000000000..c038e00a5677e318d222b63c22d225e3045e1c2b --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/ctx_iv.py @@ -0,0 +1,551 @@ +import operator + +from . import libmp + +from .libmp.backend import basestring + +from .libmp import ( + int_types, MPZ_ONE, + prec_to_dps, dps_to_prec, repr_dps, + round_floor, round_ceiling, + fzero, finf, fninf, fnan, + mpf_le, mpf_neg, + from_int, from_float, from_str, from_rational, + mpi_mid, mpi_delta, mpi_str, + mpi_abs, mpi_pos, mpi_neg, mpi_add, mpi_sub, + mpi_mul, mpi_div, mpi_pow_int, mpi_pow, + mpi_from_str, + mpci_pos, mpci_neg, mpci_add, mpci_sub, mpci_mul, mpci_div, mpci_pow, + mpci_abs, mpci_pow, mpci_exp, mpci_log, + ComplexResult, + mpf_hash, mpc_hash) +from .matrices.matrices import _matrix + +mpi_zero = (fzero, fzero) + +from .ctx_base import StandardBaseContext + +new = object.__new__ + +def convert_mpf_(x, prec, rounding): + if hasattr(x, "_mpf_"): return x._mpf_ + if isinstance(x, int_types): return from_int(x, prec, rounding) + if isinstance(x, float): return from_float(x, prec, rounding) + if isinstance(x, basestring): return from_str(x, prec, rounding) + raise NotImplementedError + + +class ivmpf(object): + """ + Interval arithmetic class. Precision is controlled by iv.prec. + """ + + def __new__(cls, x=0): + return cls.ctx.convert(x) + + def cast(self, cls, f_convert): + a, b = self._mpi_ + if a == b: + return cls(f_convert(a)) + raise ValueError + + def __int__(self): + return self.cast(int, libmp.to_int) + + def __float__(self): + return self.cast(float, libmp.to_float) + + def __complex__(self): + return self.cast(complex, libmp.to_float) + + def __hash__(self): + a, b = self._mpi_ + if a == b: + return mpf_hash(a) + else: + return hash(self._mpi_) + + @property + def real(self): return self + + @property + def imag(self): return self.ctx.zero + + def conjugate(self): return self + + @property + def a(self): + a, b = self._mpi_ + return self.ctx.make_mpf((a, a)) + + @property + def b(self): + a, b = self._mpi_ + return self.ctx.make_mpf((b, b)) + + @property + def mid(self): + ctx = self.ctx + v = mpi_mid(self._mpi_, ctx.prec) + return ctx.make_mpf((v, v)) + + @property + def delta(self): + ctx = self.ctx + v = mpi_delta(self._mpi_, ctx.prec) + return ctx.make_mpf((v,v)) + + @property + def _mpci_(self): + return self._mpi_, mpi_zero + + def _compare(*args): + raise TypeError("no ordering relation is defined for intervals") + + __gt__ = _compare + __le__ = _compare + __gt__ = _compare + __ge__ = _compare + + def __contains__(self, t): + t = self.ctx.mpf(t) + return (self.a <= t.a) and (t.b <= self.b) + + def __str__(self): + return mpi_str(self._mpi_, self.ctx.prec) + + def __repr__(self): + if self.ctx.pretty: + return str(self) + a, b = self._mpi_ + n = repr_dps(self.ctx.prec) + a = libmp.to_str(a, n) + b = libmp.to_str(b, n) + return "mpi(%r, %r)" % (a, b) + + def _compare(s, t, cmpfun): + if not hasattr(t, "_mpi_"): + try: + t = s.ctx.convert(t) + except: + return NotImplemented + return cmpfun(s._mpi_, t._mpi_) + + def __eq__(s, t): return s._compare(t, libmp.mpi_eq) + def __ne__(s, t): return s._compare(t, libmp.mpi_ne) + def __lt__(s, t): return s._compare(t, libmp.mpi_lt) + def __le__(s, t): return s._compare(t, libmp.mpi_le) + def __gt__(s, t): return s._compare(t, libmp.mpi_gt) + def __ge__(s, t): return s._compare(t, libmp.mpi_ge) + + def __abs__(self): + return self.ctx.make_mpf(mpi_abs(self._mpi_, self.ctx.prec)) + def __pos__(self): + return self.ctx.make_mpf(mpi_pos(self._mpi_, self.ctx.prec)) + def __neg__(self): + return self.ctx.make_mpf(mpi_neg(self._mpi_, self.ctx.prec)) + + def ae(s, t, rel_eps=None, abs_eps=None): + return s.ctx.almosteq(s, t, rel_eps, abs_eps) + +class ivmpc(object): + + def __new__(cls, re=0, im=0): + re = cls.ctx.convert(re) + im = cls.ctx.convert(im) + y = new(cls) + y._mpci_ = re._mpi_, im._mpi_ + return y + + def __hash__(self): + (a, b), (c,d) = self._mpci_ + if a == b and c == d: + return mpc_hash((a, c)) + else: + return hash(self._mpci_) + + def __repr__(s): + if s.ctx.pretty: + return str(s) + return "iv.mpc(%s, %s)" % (repr(s.real), repr(s.imag)) + + def __str__(s): + return "(%s + %s*j)" % (str(s.real), str(s.imag)) + + @property + def a(self): + (a, b), (c,d) = self._mpci_ + return self.ctx.make_mpf((a, a)) + + @property + def b(self): + (a, b), (c,d) = self._mpci_ + return self.ctx.make_mpf((b, b)) + + @property + def c(self): + (a, b), (c,d) = self._mpci_ + return self.ctx.make_mpf((c, c)) + + @property + def d(self): + (a, b), (c,d) = self._mpci_ + return self.ctx.make_mpf((d, d)) + + @property + def real(s): + return s.ctx.make_mpf(s._mpci_[0]) + + @property + def imag(s): + return s.ctx.make_mpf(s._mpci_[1]) + + def conjugate(s): + a, b = s._mpci_ + return s.ctx.make_mpc((a, mpf_neg(b))) + + def overlap(s, t): + t = s.ctx.convert(t) + real_overlap = (s.a <= t.a <= s.b) or (s.a <= t.b <= s.b) or (t.a <= s.a <= t.b) or (t.a <= s.b <= t.b) + imag_overlap = (s.c <= t.c <= s.d) or (s.c <= t.d <= s.d) or (t.c <= s.c <= t.d) or (t.c <= s.d <= t.d) + return real_overlap and imag_overlap + + def __contains__(s, t): + t = s.ctx.convert(t) + return t.real in s.real and t.imag in s.imag + + def _compare(s, t, ne=False): + if not isinstance(t, s.ctx._types): + try: + t = s.ctx.convert(t) + except: + return NotImplemented + if hasattr(t, '_mpi_'): + tval = t._mpi_, mpi_zero + elif hasattr(t, '_mpci_'): + tval = t._mpci_ + if ne: + return s._mpci_ != tval + return s._mpci_ == tval + + def __eq__(s, t): return s._compare(t) + def __ne__(s, t): return s._compare(t, True) + + def __lt__(s, t): raise TypeError("complex intervals cannot be ordered") + __le__ = __gt__ = __ge__ = __lt__ + + def __neg__(s): return s.ctx.make_mpc(mpci_neg(s._mpci_, s.ctx.prec)) + def __pos__(s): return s.ctx.make_mpc(mpci_pos(s._mpci_, s.ctx.prec)) + def __abs__(s): return s.ctx.make_mpf(mpci_abs(s._mpci_, s.ctx.prec)) + + def ae(s, t, rel_eps=None, abs_eps=None): + return s.ctx.almosteq(s, t, rel_eps, abs_eps) + +def _binary_op(f_real, f_complex): + def g_complex(ctx, sval, tval): + return ctx.make_mpc(f_complex(sval, tval, ctx.prec)) + def g_real(ctx, sval, tval): + try: + return ctx.make_mpf(f_real(sval, tval, ctx.prec)) + except ComplexResult: + sval = (sval, mpi_zero) + tval = (tval, mpi_zero) + return g_complex(ctx, sval, tval) + def lop_real(s, t): + if isinstance(t, _matrix): return NotImplemented + ctx = s.ctx + if not isinstance(t, ctx._types): t = ctx.convert(t) + if hasattr(t, "_mpi_"): return g_real(ctx, s._mpi_, t._mpi_) + if hasattr(t, "_mpci_"): return g_complex(ctx, (s._mpi_, mpi_zero), t._mpci_) + return NotImplemented + def rop_real(s, t): + ctx = s.ctx + if not isinstance(t, ctx._types): t = ctx.convert(t) + if hasattr(t, "_mpi_"): return g_real(ctx, t._mpi_, s._mpi_) + if hasattr(t, "_mpci_"): return g_complex(ctx, t._mpci_, (s._mpi_, mpi_zero)) + return NotImplemented + def lop_complex(s, t): + if isinstance(t, _matrix): return NotImplemented + ctx = s.ctx + if not isinstance(t, s.ctx._types): + try: + t = s.ctx.convert(t) + except (ValueError, TypeError): + return NotImplemented + return g_complex(ctx, s._mpci_, t._mpci_) + def rop_complex(s, t): + ctx = s.ctx + if not isinstance(t, s.ctx._types): + t = s.ctx.convert(t) + return g_complex(ctx, t._mpci_, s._mpci_) + return lop_real, rop_real, lop_complex, rop_complex + +ivmpf.__add__, ivmpf.__radd__, ivmpc.__add__, ivmpc.__radd__ = _binary_op(mpi_add, mpci_add) +ivmpf.__sub__, ivmpf.__rsub__, ivmpc.__sub__, ivmpc.__rsub__ = _binary_op(mpi_sub, mpci_sub) +ivmpf.__mul__, ivmpf.__rmul__, ivmpc.__mul__, ivmpc.__rmul__ = _binary_op(mpi_mul, mpci_mul) +ivmpf.__div__, ivmpf.__rdiv__, ivmpc.__div__, ivmpc.__rdiv__ = _binary_op(mpi_div, mpci_div) +ivmpf.__pow__, ivmpf.__rpow__, ivmpc.__pow__, ivmpc.__rpow__ = _binary_op(mpi_pow, mpci_pow) + +ivmpf.__truediv__ = ivmpf.__div__; ivmpf.__rtruediv__ = ivmpf.__rdiv__ +ivmpc.__truediv__ = ivmpc.__div__; ivmpc.__rtruediv__ = ivmpc.__rdiv__ + +class ivmpf_constant(ivmpf): + def __new__(cls, f): + self = new(cls) + self._f = f + return self + def _get_mpi_(self): + prec = self.ctx._prec[0] + a = self._f(prec, round_floor) + b = self._f(prec, round_ceiling) + return a, b + _mpi_ = property(_get_mpi_) + +class MPIntervalContext(StandardBaseContext): + + def __init__(ctx): + ctx.mpf = type('ivmpf', (ivmpf,), {}) + ctx.mpc = type('ivmpc', (ivmpc,), {}) + ctx._types = (ctx.mpf, ctx.mpc) + ctx._constant = type('ivmpf_constant', (ivmpf_constant,), {}) + ctx._prec = [53] + ctx._set_prec(53) + ctx._constant._ctxdata = ctx.mpf._ctxdata = ctx.mpc._ctxdata = [ctx.mpf, new, ctx._prec] + ctx._constant.ctx = ctx.mpf.ctx = ctx.mpc.ctx = ctx + ctx.pretty = False + StandardBaseContext.__init__(ctx) + ctx._init_builtins() + + def _mpi(ctx, a, b=None): + if b is None: + return ctx.mpf(a) + return ctx.mpf((a,b)) + + def _init_builtins(ctx): + ctx.one = ctx.mpf(1) + ctx.zero = ctx.mpf(0) + ctx.inf = ctx.mpf('inf') + ctx.ninf = -ctx.inf + ctx.nan = ctx.mpf('nan') + ctx.j = ctx.mpc(0,1) + ctx.exp = ctx._wrap_mpi_function(libmp.mpi_exp, libmp.mpci_exp) + ctx.sqrt = ctx._wrap_mpi_function(libmp.mpi_sqrt) + ctx.ln = ctx._wrap_mpi_function(libmp.mpi_log, libmp.mpci_log) + ctx.cos = ctx._wrap_mpi_function(libmp.mpi_cos, libmp.mpci_cos) + ctx.sin = ctx._wrap_mpi_function(libmp.mpi_sin, libmp.mpci_sin) + ctx.tan = ctx._wrap_mpi_function(libmp.mpi_tan) + ctx.gamma = ctx._wrap_mpi_function(libmp.mpi_gamma, libmp.mpci_gamma) + ctx.loggamma = ctx._wrap_mpi_function(libmp.mpi_loggamma, libmp.mpci_loggamma) + ctx.rgamma = ctx._wrap_mpi_function(libmp.mpi_rgamma, libmp.mpci_rgamma) + ctx.factorial = ctx._wrap_mpi_function(libmp.mpi_factorial, libmp.mpci_factorial) + ctx.fac = ctx.factorial + + ctx.eps = ctx._constant(lambda prec, rnd: (0, MPZ_ONE, 1-prec, 1)) + ctx.pi = ctx._constant(libmp.mpf_pi) + ctx.e = ctx._constant(libmp.mpf_e) + ctx.ln2 = ctx._constant(libmp.mpf_ln2) + ctx.ln10 = ctx._constant(libmp.mpf_ln10) + ctx.phi = ctx._constant(libmp.mpf_phi) + ctx.euler = ctx._constant(libmp.mpf_euler) + ctx.catalan = ctx._constant(libmp.mpf_catalan) + ctx.glaisher = ctx._constant(libmp.mpf_glaisher) + ctx.khinchin = ctx._constant(libmp.mpf_khinchin) + ctx.twinprime = ctx._constant(libmp.mpf_twinprime) + + def _wrap_mpi_function(ctx, f_real, f_complex=None): + def g(x, **kwargs): + if kwargs: + prec = kwargs.get('prec', ctx._prec[0]) + else: + prec = ctx._prec[0] + x = ctx.convert(x) + if hasattr(x, "_mpi_"): + return ctx.make_mpf(f_real(x._mpi_, prec)) + if hasattr(x, "_mpci_"): + return ctx.make_mpc(f_complex(x._mpci_, prec)) + raise ValueError + return g + + @classmethod + def _wrap_specfun(cls, name, f, wrap): + if wrap: + def f_wrapped(ctx, *args, **kwargs): + convert = ctx.convert + args = [convert(a) for a in args] + prec = ctx.prec + try: + ctx.prec += 10 + retval = f(ctx, *args, **kwargs) + finally: + ctx.prec = prec + return +retval + else: + f_wrapped = f + setattr(cls, name, f_wrapped) + + def _set_prec(ctx, n): + ctx._prec[0] = max(1, int(n)) + ctx._dps = prec_to_dps(n) + + def _set_dps(ctx, n): + ctx._prec[0] = dps_to_prec(n) + ctx._dps = max(1, int(n)) + + prec = property(lambda ctx: ctx._prec[0], _set_prec) + dps = property(lambda ctx: ctx._dps, _set_dps) + + def make_mpf(ctx, v): + a = new(ctx.mpf) + a._mpi_ = v + return a + + def make_mpc(ctx, v): + a = new(ctx.mpc) + a._mpci_ = v + return a + + def _mpq(ctx, pq): + p, q = pq + a = libmp.from_rational(p, q, ctx.prec, round_floor) + b = libmp.from_rational(p, q, ctx.prec, round_ceiling) + return ctx.make_mpf((a, b)) + + def convert(ctx, x): + if isinstance(x, (ctx.mpf, ctx.mpc)): + return x + if isinstance(x, ctx._constant): + return +x + if isinstance(x, complex) or hasattr(x, "_mpc_"): + re = ctx.convert(x.real) + im = ctx.convert(x.imag) + return ctx.mpc(re,im) + if isinstance(x, basestring): + v = mpi_from_str(x, ctx.prec) + return ctx.make_mpf(v) + if hasattr(x, "_mpi_"): + a, b = x._mpi_ + else: + try: + a, b = x + except (TypeError, ValueError): + a = b = x + if hasattr(a, "_mpi_"): + a = a._mpi_[0] + else: + a = convert_mpf_(a, ctx.prec, round_floor) + if hasattr(b, "_mpi_"): + b = b._mpi_[1] + else: + b = convert_mpf_(b, ctx.prec, round_ceiling) + if a == fnan or b == fnan: + a = fninf + b = finf + assert mpf_le(a, b), "endpoints must be properly ordered" + return ctx.make_mpf((a, b)) + + def nstr(ctx, x, n=5, **kwargs): + x = ctx.convert(x) + if hasattr(x, "_mpi_"): + return libmp.mpi_to_str(x._mpi_, n, **kwargs) + if hasattr(x, "_mpci_"): + re = libmp.mpi_to_str(x._mpci_[0], n, **kwargs) + im = libmp.mpi_to_str(x._mpci_[1], n, **kwargs) + return "(%s + %s*j)" % (re, im) + + def mag(ctx, x): + x = ctx.convert(x) + if isinstance(x, ctx.mpc): + return max(ctx.mag(x.real), ctx.mag(x.imag)) + 1 + a, b = libmp.mpi_abs(x._mpi_) + sign, man, exp, bc = b + if man: + return exp+bc + if b == fzero: + return ctx.ninf + if b == fnan: + return ctx.nan + return ctx.inf + + def isnan(ctx, x): + return False + + def isinf(ctx, x): + return x == ctx.inf + + def isint(ctx, x): + x = ctx.convert(x) + a, b = x._mpi_ + if a == b: + sign, man, exp, bc = a + if man: + return exp >= 0 + return a == fzero + return None + + def ldexp(ctx, x, n): + a, b = ctx.convert(x)._mpi_ + a = libmp.mpf_shift(a, n) + b = libmp.mpf_shift(b, n) + return ctx.make_mpf((a,b)) + + def absmin(ctx, x): + return abs(ctx.convert(x)).a + + def absmax(ctx, x): + return abs(ctx.convert(x)).b + + def atan2(ctx, y, x): + y = ctx.convert(y)._mpi_ + x = ctx.convert(x)._mpi_ + return ctx.make_mpf(libmp.mpi_atan2(y,x,ctx.prec)) + + def _convert_param(ctx, x): + if isinstance(x, libmp.int_types): + return x, 'Z' + if isinstance(x, tuple): + p, q = x + return (ctx.mpf(p) / ctx.mpf(q), 'R') + x = ctx.convert(x) + if isinstance(x, ctx.mpf): + return x, 'R' + if isinstance(x, ctx.mpc): + return x, 'C' + raise ValueError + + def _is_real_type(ctx, z): + return isinstance(z, ctx.mpf) or isinstance(z, int_types) + + def _is_complex_type(ctx, z): + return isinstance(z, ctx.mpc) + + def hypsum(ctx, p, q, types, coeffs, z, maxterms=6000, **kwargs): + coeffs = list(coeffs) + num = range(p) + den = range(p,p+q) + #tol = ctx.eps + s = t = ctx.one + k = 0 + while 1: + for i in num: t *= (coeffs[i]+k) + for i in den: t /= (coeffs[i]+k) + k += 1; t /= k; t *= z; s += t + if t == 0: + return s + #if abs(t) < tol: + # return s + if k > maxterms: + raise ctx.NoConvergence + + +# Register with "numbers" ABC +# We do not subclass, hence we do not use the @abstractmethod checks. While +# this is less invasive it may turn out that we do not actually support +# parts of the expected interfaces. See +# http://docs.python.org/2/library/numbers.html for list of abstract +# methods. +try: + import numbers + numbers.Complex.register(ivmpc) + numbers.Real.register(ivmpf) +except ImportError: + pass diff --git a/venv/lib/python3.10/site-packages/mpmath/ctx_mp.py b/venv/lib/python3.10/site-packages/mpmath/ctx_mp.py new file mode 100644 index 0000000000000000000000000000000000000000..93594dd44474a415c74e4b0beb83bd7012666c9d --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/ctx_mp.py @@ -0,0 +1,1339 @@ +""" +This module defines the mpf, mpc classes, and standard functions for +operating with them. +""" +__docformat__ = 'plaintext' + +import functools + +import re + +from .ctx_base import StandardBaseContext + +from .libmp.backend import basestring, BACKEND + +from . import libmp + +from .libmp import (MPZ, MPZ_ZERO, MPZ_ONE, int_types, repr_dps, + round_floor, round_ceiling, dps_to_prec, round_nearest, prec_to_dps, + ComplexResult, to_pickable, from_pickable, normalize, + from_int, from_float, from_str, to_int, to_float, to_str, + from_rational, from_man_exp, + fone, fzero, finf, fninf, fnan, + mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, mpf_mul_int, + mpf_div, mpf_rdiv_int, mpf_pow_int, mpf_mod, + mpf_eq, mpf_cmp, mpf_lt, mpf_gt, mpf_le, mpf_ge, + mpf_hash, mpf_rand, + mpf_sum, + bitcount, to_fixed, + mpc_to_str, + mpc_to_complex, mpc_hash, mpc_pos, mpc_is_nonzero, mpc_neg, mpc_conjugate, + mpc_abs, mpc_add, mpc_add_mpf, mpc_sub, mpc_sub_mpf, mpc_mul, mpc_mul_mpf, + mpc_mul_int, mpc_div, mpc_div_mpf, mpc_pow, mpc_pow_mpf, mpc_pow_int, + mpc_mpf_div, + mpf_pow, + mpf_pi, mpf_degree, mpf_e, mpf_phi, mpf_ln2, mpf_ln10, + mpf_euler, mpf_catalan, mpf_apery, mpf_khinchin, + mpf_glaisher, mpf_twinprime, mpf_mertens, + int_types) + +from . import function_docs +from . import rational + +new = object.__new__ + +get_complex = re.compile(r'^\(?(?P[\+\-]?\d*(\.\d*)?(e[\+\-]?\d+)?)??' + r'(?P[\+\-]?\d*(\.\d*)?(e[\+\-]?\d+)?j)?\)?$') + +if BACKEND == 'sage': + from sage.libs.mpmath.ext_main import Context as BaseMPContext + # pickle hack + import sage.libs.mpmath.ext_main as _mpf_module +else: + from .ctx_mp_python import PythonMPContext as BaseMPContext + from . import ctx_mp_python as _mpf_module + +from .ctx_mp_python import _mpf, _mpc, mpnumeric + +class MPContext(BaseMPContext, StandardBaseContext): + """ + Context for multiprecision arithmetic with a global precision. + """ + + def __init__(ctx): + BaseMPContext.__init__(ctx) + ctx.trap_complex = False + ctx.pretty = False + ctx.types = [ctx.mpf, ctx.mpc, ctx.constant] + ctx._mpq = rational.mpq + ctx.default() + StandardBaseContext.__init__(ctx) + + ctx.mpq = rational.mpq + ctx.init_builtins() + + ctx.hyp_summators = {} + + ctx._init_aliases() + + # XXX: automate + try: + ctx.bernoulli.im_func.func_doc = function_docs.bernoulli + ctx.primepi.im_func.func_doc = function_docs.primepi + ctx.psi.im_func.func_doc = function_docs.psi + ctx.atan2.im_func.func_doc = function_docs.atan2 + except AttributeError: + # python 3 + ctx.bernoulli.__func__.func_doc = function_docs.bernoulli + ctx.primepi.__func__.func_doc = function_docs.primepi + ctx.psi.__func__.func_doc = function_docs.psi + ctx.atan2.__func__.func_doc = function_docs.atan2 + + ctx.digamma.func_doc = function_docs.digamma + ctx.cospi.func_doc = function_docs.cospi + ctx.sinpi.func_doc = function_docs.sinpi + + def init_builtins(ctx): + + mpf = ctx.mpf + mpc = ctx.mpc + + # Exact constants + ctx.one = ctx.make_mpf(fone) + ctx.zero = ctx.make_mpf(fzero) + 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) + + eps = ctx.constant(lambda prec, rnd: (0, MPZ_ONE, 1-prec, 1), + "epsilon of working precision", "eps") + ctx.eps = eps + + # Approximate constants + ctx.pi = ctx.constant(mpf_pi, "pi", "pi") + ctx.ln2 = ctx.constant(mpf_ln2, "ln(2)", "ln2") + ctx.ln10 = ctx.constant(mpf_ln10, "ln(10)", "ln10") + ctx.phi = ctx.constant(mpf_phi, "Golden ratio phi", "phi") + ctx.e = ctx.constant(mpf_e, "e = exp(1)", "e") + ctx.euler = ctx.constant(mpf_euler, "Euler's constant", "euler") + ctx.catalan = ctx.constant(mpf_catalan, "Catalan's constant", "catalan") + ctx.khinchin = ctx.constant(mpf_khinchin, "Khinchin's constant", "khinchin") + ctx.glaisher = ctx.constant(mpf_glaisher, "Glaisher's constant", "glaisher") + ctx.apery = ctx.constant(mpf_apery, "Apery's constant", "apery") + ctx.degree = ctx.constant(mpf_degree, "1 deg = pi / 180", "degree") + ctx.twinprime = ctx.constant(mpf_twinprime, "Twin prime constant", "twinprime") + ctx.mertens = ctx.constant(mpf_mertens, "Mertens' constant", "mertens") + + # Standard functions + ctx.sqrt = ctx._wrap_libmp_function(libmp.mpf_sqrt, libmp.mpc_sqrt) + ctx.cbrt = ctx._wrap_libmp_function(libmp.mpf_cbrt, libmp.mpc_cbrt) + ctx.ln = ctx._wrap_libmp_function(libmp.mpf_log, libmp.mpc_log) + ctx.atan = ctx._wrap_libmp_function(libmp.mpf_atan, libmp.mpc_atan) + ctx.exp = ctx._wrap_libmp_function(libmp.mpf_exp, libmp.mpc_exp) + ctx.expj = ctx._wrap_libmp_function(libmp.mpf_expj, libmp.mpc_expj) + ctx.expjpi = ctx._wrap_libmp_function(libmp.mpf_expjpi, libmp.mpc_expjpi) + ctx.sin = ctx._wrap_libmp_function(libmp.mpf_sin, libmp.mpc_sin) + ctx.cos = ctx._wrap_libmp_function(libmp.mpf_cos, libmp.mpc_cos) + ctx.tan = ctx._wrap_libmp_function(libmp.mpf_tan, libmp.mpc_tan) + ctx.sinh = ctx._wrap_libmp_function(libmp.mpf_sinh, libmp.mpc_sinh) + ctx.cosh = ctx._wrap_libmp_function(libmp.mpf_cosh, libmp.mpc_cosh) + ctx.tanh = ctx._wrap_libmp_function(libmp.mpf_tanh, libmp.mpc_tanh) + ctx.asin = ctx._wrap_libmp_function(libmp.mpf_asin, libmp.mpc_asin) + ctx.acos = ctx._wrap_libmp_function(libmp.mpf_acos, libmp.mpc_acos) + ctx.atan = ctx._wrap_libmp_function(libmp.mpf_atan, libmp.mpc_atan) + ctx.asinh = ctx._wrap_libmp_function(libmp.mpf_asinh, libmp.mpc_asinh) + ctx.acosh = ctx._wrap_libmp_function(libmp.mpf_acosh, libmp.mpc_acosh) + ctx.atanh = ctx._wrap_libmp_function(libmp.mpf_atanh, libmp.mpc_atanh) + ctx.sinpi = ctx._wrap_libmp_function(libmp.mpf_sin_pi, libmp.mpc_sin_pi) + ctx.cospi = ctx._wrap_libmp_function(libmp.mpf_cos_pi, libmp.mpc_cos_pi) + ctx.floor = ctx._wrap_libmp_function(libmp.mpf_floor, libmp.mpc_floor) + ctx.ceil = ctx._wrap_libmp_function(libmp.mpf_ceil, libmp.mpc_ceil) + ctx.nint = ctx._wrap_libmp_function(libmp.mpf_nint, libmp.mpc_nint) + ctx.frac = ctx._wrap_libmp_function(libmp.mpf_frac, libmp.mpc_frac) + ctx.fib = ctx.fibonacci = ctx._wrap_libmp_function(libmp.mpf_fibonacci, libmp.mpc_fibonacci) + + ctx.gamma = ctx._wrap_libmp_function(libmp.mpf_gamma, libmp.mpc_gamma) + ctx.rgamma = ctx._wrap_libmp_function(libmp.mpf_rgamma, libmp.mpc_rgamma) + ctx.loggamma = ctx._wrap_libmp_function(libmp.mpf_loggamma, libmp.mpc_loggamma) + ctx.fac = ctx.factorial = ctx._wrap_libmp_function(libmp.mpf_factorial, libmp.mpc_factorial) + + ctx.digamma = ctx._wrap_libmp_function(libmp.mpf_psi0, libmp.mpc_psi0) + ctx.harmonic = ctx._wrap_libmp_function(libmp.mpf_harmonic, libmp.mpc_harmonic) + ctx.ei = ctx._wrap_libmp_function(libmp.mpf_ei, libmp.mpc_ei) + ctx.e1 = ctx._wrap_libmp_function(libmp.mpf_e1, libmp.mpc_e1) + ctx._ci = ctx._wrap_libmp_function(libmp.mpf_ci, libmp.mpc_ci) + ctx._si = ctx._wrap_libmp_function(libmp.mpf_si, libmp.mpc_si) + ctx.ellipk = ctx._wrap_libmp_function(libmp.mpf_ellipk, libmp.mpc_ellipk) + ctx._ellipe = ctx._wrap_libmp_function(libmp.mpf_ellipe, libmp.mpc_ellipe) + ctx.agm1 = ctx._wrap_libmp_function(libmp.mpf_agm1, libmp.mpc_agm1) + ctx._erf = ctx._wrap_libmp_function(libmp.mpf_erf, None) + ctx._erfc = ctx._wrap_libmp_function(libmp.mpf_erfc, None) + ctx._zeta = ctx._wrap_libmp_function(libmp.mpf_zeta, libmp.mpc_zeta) + ctx._altzeta = ctx._wrap_libmp_function(libmp.mpf_altzeta, libmp.mpc_altzeta) + + # Faster versions + ctx.sqrt = getattr(ctx, "_sage_sqrt", ctx.sqrt) + ctx.exp = getattr(ctx, "_sage_exp", ctx.exp) + ctx.ln = getattr(ctx, "_sage_ln", ctx.ln) + ctx.cos = getattr(ctx, "_sage_cos", ctx.cos) + ctx.sin = getattr(ctx, "_sage_sin", ctx.sin) + + def to_fixed(ctx, x, prec): + return x.to_fixed(prec) + + def hypot(ctx, x, y): + r""" + Computes the Euclidean norm of the vector `(x, y)`, equal + to `\sqrt{x^2 + y^2}`. Both `x` and `y` must be real.""" + x = ctx.convert(x) + y = ctx.convert(y) + return ctx.make_mpf(libmp.mpf_hypot(x._mpf_, y._mpf_, *ctx._prec_rounding)) + + def _gamma_upper_int(ctx, n, z): + n = int(ctx._re(n)) + if n == 0: + return ctx.e1(z) + if not hasattr(z, '_mpf_'): + raise NotImplementedError + prec, rounding = ctx._prec_rounding + real, imag = libmp.mpf_expint(n, z._mpf_, prec, rounding, gamma=True) + if imag is None: + return ctx.make_mpf(real) + else: + return ctx.make_mpc((real, imag)) + + def _expint_int(ctx, n, z): + n = int(n) + if n == 1: + return ctx.e1(z) + if not hasattr(z, '_mpf_'): + raise NotImplementedError + prec, rounding = ctx._prec_rounding + real, imag = libmp.mpf_expint(n, z._mpf_, prec, rounding) + if imag is None: + return ctx.make_mpf(real) + else: + return ctx.make_mpc((real, imag)) + + def _nthroot(ctx, x, n): + if hasattr(x, '_mpf_'): + try: + return ctx.make_mpf(libmp.mpf_nthroot(x._mpf_, n, *ctx._prec_rounding)) + except ComplexResult: + if ctx.trap_complex: + raise + x = (x._mpf_, libmp.fzero) + else: + x = x._mpc_ + return ctx.make_mpc(libmp.mpc_nthroot(x, n, *ctx._prec_rounding)) + + def _besselj(ctx, n, z): + prec, rounding = ctx._prec_rounding + if hasattr(z, '_mpf_'): + return ctx.make_mpf(libmp.mpf_besseljn(n, z._mpf_, prec, rounding)) + elif hasattr(z, '_mpc_'): + return ctx.make_mpc(libmp.mpc_besseljn(n, z._mpc_, prec, rounding)) + + def _agm(ctx, a, b=1): + prec, rounding = ctx._prec_rounding + if hasattr(a, '_mpf_') and hasattr(b, '_mpf_'): + try: + v = libmp.mpf_agm(a._mpf_, b._mpf_, prec, rounding) + return ctx.make_mpf(v) + except ComplexResult: + pass + if hasattr(a, '_mpf_'): a = (a._mpf_, libmp.fzero) + else: a = a._mpc_ + if hasattr(b, '_mpf_'): b = (b._mpf_, libmp.fzero) + else: b = b._mpc_ + return ctx.make_mpc(libmp.mpc_agm(a, b, prec, rounding)) + + def bernoulli(ctx, n): + return ctx.make_mpf(libmp.mpf_bernoulli(int(n), *ctx._prec_rounding)) + + def _zeta_int(ctx, n): + return ctx.make_mpf(libmp.mpf_zeta_int(int(n), *ctx._prec_rounding)) + + def atan2(ctx, y, x): + x = ctx.convert(x) + y = ctx.convert(y) + return ctx.make_mpf(libmp.mpf_atan2(y._mpf_, x._mpf_, *ctx._prec_rounding)) + + def psi(ctx, m, z): + z = ctx.convert(z) + m = int(m) + if ctx._is_real_type(z): + return ctx.make_mpf(libmp.mpf_psi(m, z._mpf_, *ctx._prec_rounding)) + else: + return ctx.make_mpc(libmp.mpc_psi(m, z._mpc_, *ctx._prec_rounding)) + + def cos_sin(ctx, x, **kwargs): + if type(x) not in ctx.types: + x = ctx.convert(x) + prec, rounding = ctx._parse_prec(kwargs) + if hasattr(x, '_mpf_'): + c, s = libmp.mpf_cos_sin(x._mpf_, prec, rounding) + return ctx.make_mpf(c), ctx.make_mpf(s) + elif hasattr(x, '_mpc_'): + c, s = libmp.mpc_cos_sin(x._mpc_, prec, rounding) + return ctx.make_mpc(c), ctx.make_mpc(s) + else: + return ctx.cos(x, **kwargs), ctx.sin(x, **kwargs) + + def cospi_sinpi(ctx, x, **kwargs): + if type(x) not in ctx.types: + x = ctx.convert(x) + prec, rounding = ctx._parse_prec(kwargs) + if hasattr(x, '_mpf_'): + c, s = libmp.mpf_cos_sin_pi(x._mpf_, prec, rounding) + return ctx.make_mpf(c), ctx.make_mpf(s) + elif hasattr(x, '_mpc_'): + c, s = libmp.mpc_cos_sin_pi(x._mpc_, prec, rounding) + return ctx.make_mpc(c), ctx.make_mpc(s) + else: + return ctx.cos(x, **kwargs), ctx.sin(x, **kwargs) + + def clone(ctx): + """ + Create a copy of the context, with the same working precision. + """ + a = ctx.__class__() + a.prec = ctx.prec + return a + + # Several helper methods + # TODO: add more of these, make consistent, write docstrings, ... + + def _is_real_type(ctx, x): + if hasattr(x, '_mpc_') or type(x) is complex: + return False + return True + + def _is_complex_type(ctx, x): + if hasattr(x, '_mpc_') or type(x) is complex: + return True + return False + + def isnan(ctx, x): + """ + Return *True* if *x* is a NaN (not-a-number), or for a complex + number, whether either the real or complex part is NaN; + otherwise return *False*:: + + >>> from mpmath import * + >>> isnan(3.14) + False + >>> isnan(nan) + True + >>> isnan(mpc(3.14,2.72)) + False + >>> isnan(mpc(3.14,nan)) + True + + """ + if hasattr(x, "_mpf_"): + return x._mpf_ == fnan + if hasattr(x, "_mpc_"): + return fnan in x._mpc_ + if isinstance(x, int_types) or isinstance(x, rational.mpq): + return False + x = ctx.convert(x) + if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'): + return ctx.isnan(x) + raise TypeError("isnan() needs a number as input") + + def isfinite(ctx, x): + """ + Return *True* if *x* is a finite number, i.e. neither + an infinity or a NaN. + + >>> from mpmath import * + >>> isfinite(inf) + False + >>> isfinite(-inf) + False + >>> isfinite(3) + True + >>> isfinite(nan) + False + >>> isfinite(3+4j) + True + >>> isfinite(mpc(3,inf)) + False + >>> isfinite(mpc(nan,3)) + False + + """ + if ctx.isinf(x) or ctx.isnan(x): + return False + return True + + def isnpint(ctx, x): + """ + Determine if *x* is a nonpositive integer. + """ + if not x: + return True + if hasattr(x, '_mpf_'): + sign, man, exp, bc = x._mpf_ + return sign and exp >= 0 + if hasattr(x, '_mpc_'): + return not x.imag and ctx.isnpint(x.real) + if type(x) in int_types: + return x <= 0 + if isinstance(x, ctx.mpq): + p, q = x._mpq_ + if not p: + return True + return q == 1 and p <= 0 + return ctx.isnpint(ctx.convert(x)) + + def __str__(ctx): + lines = ["Mpmath settings:", + (" mp.prec = %s" % ctx.prec).ljust(30) + "[default: 53]", + (" mp.dps = %s" % ctx.dps).ljust(30) + "[default: 15]", + (" mp.trap_complex = %s" % ctx.trap_complex).ljust(30) + "[default: False]", + ] + return "\n".join(lines) + + @property + def _repr_digits(ctx): + return repr_dps(ctx._prec) + + @property + def _str_digits(ctx): + return ctx._dps + + def extraprec(ctx, n, normalize_output=False): + """ + The block + + with extraprec(n): + + + increases the precision n bits, executes , and then + restores the precision. + + extraprec(n)(f) returns a decorated version of the function f + that increases the working precision by n bits before execution, + and restores the parent precision afterwards. With + normalize_output=True, it rounds the return value to the parent + precision. + """ + return PrecisionManager(ctx, lambda p: p + n, None, normalize_output) + + def extradps(ctx, n, normalize_output=False): + """ + This function is analogous to extraprec (see documentation) + but changes the decimal precision instead of the number of bits. + """ + return PrecisionManager(ctx, None, lambda d: d + n, normalize_output) + + def workprec(ctx, n, normalize_output=False): + """ + The block + + with workprec(n): + + + sets the precision to n bits, executes , and then restores + the precision. + + workprec(n)(f) returns a decorated version of the function f + that sets the precision to n bits before execution, + and restores the precision afterwards. With normalize_output=True, + it rounds the return value to the parent precision. + """ + return PrecisionManager(ctx, lambda p: n, None, normalize_output) + + def workdps(ctx, n, normalize_output=False): + """ + This function is analogous to workprec (see documentation) + but changes the decimal precision instead of the number of bits. + """ + return PrecisionManager(ctx, None, lambda d: n, normalize_output) + + def autoprec(ctx, f, maxprec=None, catch=(), verbose=False): + r""" + Return a wrapped copy of *f* that repeatedly evaluates *f* + with increasing precision until the result converges to the + full precision used at the point of the call. + + This heuristically protects against rounding errors, at the cost of + roughly a 2x slowdown compared to manually setting the optimal + precision. This method can, however, easily be fooled if the results + from *f* depend "discontinuously" on the precision, for instance + if catastrophic cancellation can occur. Therefore, :func:`~mpmath.autoprec` + should be used judiciously. + + **Examples** + + Many functions are sensitive to perturbations of the input arguments. + If the arguments are decimal numbers, they may have to be converted + to binary at a much higher precision. If the amount of required + extra precision is unknown, :func:`~mpmath.autoprec` is convenient:: + + >>> from mpmath import * + >>> mp.dps = 15 + >>> mp.pretty = True + >>> besselj(5, 125 * 10**28) # Exact input + -8.03284785591801e-17 + >>> besselj(5, '1.25e30') # Bad + 7.12954868316652e-16 + >>> autoprec(besselj)(5, '1.25e30') # Good + -8.03284785591801e-17 + + The following fails to converge because `\sin(\pi) = 0` whereas all + finite-precision approximations of `\pi` give nonzero values:: + + >>> autoprec(sin)(pi) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + NoConvergence: autoprec: prec increased to 2910 without convergence + + As the following example shows, :func:`~mpmath.autoprec` can protect against + cancellation, but is fooled by too severe cancellation:: + + >>> x = 1e-10 + >>> exp(x)-1; expm1(x); autoprec(lambda t: exp(t)-1)(x) + 1.00000008274037e-10 + 1.00000000005e-10 + 1.00000000005e-10 + >>> x = 1e-50 + >>> exp(x)-1; expm1(x); autoprec(lambda t: exp(t)-1)(x) + 0.0 + 1.0e-50 + 0.0 + + With *catch*, an exception or list of exceptions to intercept + may be specified. The raised exception is interpreted + as signaling insufficient precision. This permits, for example, + evaluating a function where a too low precision results in a + division by zero:: + + >>> f = lambda x: 1/(exp(x)-1) + >>> f(1e-30) + Traceback (most recent call last): + ... + ZeroDivisionError + >>> autoprec(f, catch=ZeroDivisionError)(1e-30) + 1.0e+30 + + + """ + def f_autoprec_wrapped(*args, **kwargs): + prec = ctx.prec + if maxprec is None: + maxprec2 = ctx._default_hyper_maxprec(prec) + else: + maxprec2 = maxprec + try: + ctx.prec = prec + 10 + try: + v1 = f(*args, **kwargs) + except catch: + v1 = ctx.nan + prec2 = prec + 20 + while 1: + ctx.prec = prec2 + try: + v2 = f(*args, **kwargs) + except catch: + v2 = ctx.nan + if v1 == v2: + break + err = ctx.mag(v2-v1) - ctx.mag(v2) + if err < (-prec): + break + if verbose: + print("autoprec: target=%s, prec=%s, accuracy=%s" \ + % (prec, prec2, -err)) + v1 = v2 + if prec2 >= maxprec2: + raise ctx.NoConvergence(\ + "autoprec: prec increased to %i without convergence"\ + % prec2) + prec2 += int(prec2*2) + prec2 = min(prec2, maxprec2) + finally: + ctx.prec = prec + return +v2 + return f_autoprec_wrapped + + def nstr(ctx, x, n=6, **kwargs): + """ + Convert an ``mpf`` or ``mpc`` to a decimal string literal with *n* + significant digits. The small default value for *n* is chosen to + make this function useful for printing collections of numbers + (lists, matrices, etc). + + If *x* is a list or tuple, :func:`~mpmath.nstr` is applied recursively + to each element. For unrecognized classes, :func:`~mpmath.nstr` + simply returns ``str(x)``. + + The companion function :func:`~mpmath.nprint` prints the result + instead of returning it. + + The keyword arguments *strip_zeros*, *min_fixed*, *max_fixed* + and *show_zero_exponent* are forwarded to :func:`~mpmath.libmp.to_str`. + + The number will be printed in fixed-point format if the position + of the leading digit is strictly between min_fixed + (default = min(-dps/3,-5)) and max_fixed (default = dps). + + To force fixed-point format always, set min_fixed = -inf, + max_fixed = +inf. To force floating-point format, set + min_fixed >= max_fixed. + + >>> from mpmath import * + >>> nstr([+pi, ldexp(1,-500)]) + '[3.14159, 3.05494e-151]' + >>> nprint([+pi, ldexp(1,-500)]) + [3.14159, 3.05494e-151] + >>> nstr(mpf("5e-10"), 5) + '5.0e-10' + >>> nstr(mpf("5e-10"), 5, strip_zeros=False) + '5.0000e-10' + >>> nstr(mpf("5e-10"), 5, strip_zeros=False, min_fixed=-11) + '0.00000000050000' + >>> nstr(mpf(0), 5, show_zero_exponent=True) + '0.0e+0' + + """ + if isinstance(x, list): + return "[%s]" % (", ".join(ctx.nstr(c, n, **kwargs) for c in x)) + if isinstance(x, tuple): + return "(%s)" % (", ".join(ctx.nstr(c, n, **kwargs) for c in x)) + if hasattr(x, '_mpf_'): + return to_str(x._mpf_, n, **kwargs) + if hasattr(x, '_mpc_'): + return "(" + mpc_to_str(x._mpc_, n, **kwargs) + ")" + if isinstance(x, basestring): + return repr(x) + if isinstance(x, ctx.matrix): + return x.__nstr__(n, **kwargs) + return str(x) + + def _convert_fallback(ctx, x, strings): + if strings and isinstance(x, basestring): + if 'j' in x.lower(): + x = x.lower().replace(' ', '') + match = get_complex.match(x) + re = match.group('re') + if not re: + re = 0 + im = match.group('im').rstrip('j') + return ctx.mpc(ctx.convert(re), ctx.convert(im)) + if hasattr(x, "_mpi_"): + a, b = x._mpi_ + if a == b: + return ctx.make_mpf(a) + else: + raise ValueError("can only create mpf from zero-width interval") + raise TypeError("cannot create mpf from " + repr(x)) + + def mpmathify(ctx, *args, **kwargs): + return ctx.convert(*args, **kwargs) + + def _parse_prec(ctx, kwargs): + if kwargs: + if kwargs.get('exact'): + return 0, 'f' + prec, rounding = ctx._prec_rounding + if 'rounding' in kwargs: + rounding = kwargs['rounding'] + if 'prec' in kwargs: + prec = kwargs['prec'] + if prec == ctx.inf: + return 0, 'f' + else: + prec = int(prec) + elif 'dps' in kwargs: + dps = kwargs['dps'] + if dps == ctx.inf: + return 0, 'f' + prec = dps_to_prec(dps) + return prec, rounding + return ctx._prec_rounding + + _exact_overflow_msg = "the exact result does not fit in memory" + + _hypsum_msg = """hypsum() failed to converge to the requested %i bits of accuracy +using a working precision of %i bits. Try with a higher maxprec, +maxterms, or set zeroprec.""" + + def hypsum(ctx, p, q, flags, coeffs, z, accurate_small=True, **kwargs): + if hasattr(z, "_mpf_"): + key = p, q, flags, 'R' + v = z._mpf_ + elif hasattr(z, "_mpc_"): + key = p, q, flags, 'C' + v = z._mpc_ + if key not in ctx.hyp_summators: + ctx.hyp_summators[key] = libmp.make_hyp_summator(key)[1] + summator = ctx.hyp_summators[key] + prec = ctx.prec + maxprec = kwargs.get('maxprec', ctx._default_hyper_maxprec(prec)) + extraprec = 50 + epsshift = 25 + # Jumps in magnitude occur when parameters are close to negative + # integers. We must ensure that these terms are included in + # the sum and added accurately + magnitude_check = {} + max_total_jump = 0 + for i, c in enumerate(coeffs): + if flags[i] == 'Z': + if i >= p and c <= 0: + ok = False + for ii, cc in enumerate(coeffs[:p]): + # Note: c <= cc or c < cc, depending on convention + if flags[ii] == 'Z' and cc <= 0 and c <= cc: + ok = True + if not ok: + raise ZeroDivisionError("pole in hypergeometric series") + continue + n, d = ctx.nint_distance(c) + n = -int(n) + d = -d + if i >= p and n >= 0 and d > 4: + if n in magnitude_check: + magnitude_check[n] += d + else: + magnitude_check[n] = d + extraprec = max(extraprec, d - prec + 60) + max_total_jump += abs(d) + while 1: + if extraprec > maxprec: + raise ValueError(ctx._hypsum_msg % (prec, prec+extraprec)) + wp = prec + extraprec + if magnitude_check: + mag_dict = dict((n,None) for n in magnitude_check) + else: + mag_dict = {} + zv, have_complex, magnitude = summator(coeffs, v, prec, wp, \ + epsshift, mag_dict, **kwargs) + cancel = -magnitude + jumps_resolved = True + if extraprec < max_total_jump: + for n in mag_dict.values(): + if (n is None) or (n < prec): + jumps_resolved = False + break + accurate = (cancel < extraprec-25-5 or not accurate_small) + if jumps_resolved: + if accurate: + break + # zero? + zeroprec = kwargs.get('zeroprec') + if zeroprec is not None: + if cancel > zeroprec: + if have_complex: + return ctx.mpc(0) + else: + return ctx.zero + + # Some near-singularities were not included, so increase + # precision and repeat until they are + extraprec *= 2 + # Possible workaround for bad roundoff in fixed-point arithmetic + epsshift += 5 + extraprec += 5 + + if type(zv) is tuple: + if have_complex: + return ctx.make_mpc(zv) + else: + return ctx.make_mpf(zv) + else: + return zv + + def ldexp(ctx, x, n): + r""" + Computes `x 2^n` efficiently. No rounding is performed. + The argument `x` must be a real floating-point number (or + possible to convert into one) and `n` must be a Python ``int``. + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> ldexp(1, 10) + mpf('1024.0') + >>> ldexp(1, -3) + mpf('0.125') + + """ + x = ctx.convert(x) + return ctx.make_mpf(libmp.mpf_shift(x._mpf_, n)) + + def frexp(ctx, x): + r""" + Given a real number `x`, returns `(y, n)` with `y \in [0.5, 1)`, + `n` a Python integer, and such that `x = y 2^n`. No rounding is + performed. + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> frexp(7.5) + (mpf('0.9375'), 3) + + """ + x = ctx.convert(x) + y, n = libmp.mpf_frexp(x._mpf_) + return ctx.make_mpf(y), n + + def fneg(ctx, x, **kwargs): + """ + Negates the number *x*, giving a floating-point result, optionally + using a custom precision and rounding mode. + + See the documentation of :func:`~mpmath.fadd` for a detailed description + of how to specify precision and rounding. + + **Examples** + + An mpmath number is returned:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> fneg(2.5) + mpf('-2.5') + >>> fneg(-5+2j) + mpc(real='5.0', imag='-2.0') + + Precise control over rounding is possible:: + + >>> x = fadd(2, 1e-100, exact=True) + >>> fneg(x) + mpf('-2.0') + >>> fneg(x, rounding='f') + mpf('-2.0000000000000004') + + Negating with and without roundoff:: + + >>> n = 200000000000000000000001 + >>> print(int(-mpf(n))) + -200000000000000016777216 + >>> print(int(fneg(n))) + -200000000000000016777216 + >>> print(int(fneg(n, prec=log(n,2)+1))) + -200000000000000000000001 + >>> print(int(fneg(n, dps=log(n,10)+1))) + -200000000000000000000001 + >>> print(int(fneg(n, prec=inf))) + -200000000000000000000001 + >>> print(int(fneg(n, dps=inf))) + -200000000000000000000001 + >>> print(int(fneg(n, exact=True))) + -200000000000000000000001 + + """ + prec, rounding = ctx._parse_prec(kwargs) + x = ctx.convert(x) + if hasattr(x, '_mpf_'): + return ctx.make_mpf(mpf_neg(x._mpf_, prec, rounding)) + if hasattr(x, '_mpc_'): + return ctx.make_mpc(mpc_neg(x._mpc_, prec, rounding)) + raise ValueError("Arguments need to be mpf or mpc compatible numbers") + + def fadd(ctx, x, y, **kwargs): + """ + Adds the numbers *x* and *y*, giving a floating-point result, + optionally using a custom precision and rounding mode. + + The default precision is the working precision of the context. + You can specify a custom precision in bits by passing the *prec* keyword + argument, or by providing an equivalent decimal precision with the *dps* + keyword argument. If the precision is set to ``+inf``, or if the flag + *exact=True* is passed, an exact addition with no rounding is performed. + + When the precision is finite, the optional *rounding* keyword argument + specifies the direction of rounding. Valid options are ``'n'`` for + nearest (default), ``'f'`` for floor, ``'c'`` for ceiling, ``'d'`` + for down, ``'u'`` for up. + + **Examples** + + Using :func:`~mpmath.fadd` with precision and rounding control:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> fadd(2, 1e-20) + mpf('2.0') + >>> fadd(2, 1e-20, rounding='u') + mpf('2.0000000000000004') + >>> nprint(fadd(2, 1e-20, prec=100), 25) + 2.00000000000000000001 + >>> nprint(fadd(2, 1e-20, dps=15), 25) + 2.0 + >>> nprint(fadd(2, 1e-20, dps=25), 25) + 2.00000000000000000001 + >>> nprint(fadd(2, 1e-20, exact=True), 25) + 2.00000000000000000001 + + Exact addition avoids cancellation errors, enforcing familiar laws + of numbers such as `x+y-x = y`, which don't hold in floating-point + arithmetic with finite precision:: + + >>> x, y = mpf(2), mpf('1e-1000') + >>> print(x + y - x) + 0.0 + >>> print(fadd(x, y, prec=inf) - x) + 1.0e-1000 + >>> print(fadd(x, y, exact=True) - x) + 1.0e-1000 + + Exact addition can be inefficient and may be impossible to perform + with large magnitude differences:: + + >>> fadd(1, '1e-100000000000000000000', prec=inf) + Traceback (most recent call last): + ... + OverflowError: the exact result does not fit in memory + + """ + prec, rounding = ctx._parse_prec(kwargs) + x = ctx.convert(x) + y = ctx.convert(y) + try: + if hasattr(x, '_mpf_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpf(mpf_add(x._mpf_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_add_mpf(y._mpc_, x._mpf_, prec, rounding)) + if hasattr(x, '_mpc_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpc(mpc_add_mpf(x._mpc_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_add(x._mpc_, y._mpc_, prec, rounding)) + except (ValueError, OverflowError): + raise OverflowError(ctx._exact_overflow_msg) + raise ValueError("Arguments need to be mpf or mpc compatible numbers") + + def fsub(ctx, x, y, **kwargs): + """ + Subtracts the numbers *x* and *y*, giving a floating-point result, + optionally using a custom precision and rounding mode. + + See the documentation of :func:`~mpmath.fadd` for a detailed description + of how to specify precision and rounding. + + **Examples** + + Using :func:`~mpmath.fsub` with precision and rounding control:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> fsub(2, 1e-20) + mpf('2.0') + >>> fsub(2, 1e-20, rounding='d') + mpf('1.9999999999999998') + >>> nprint(fsub(2, 1e-20, prec=100), 25) + 1.99999999999999999999 + >>> nprint(fsub(2, 1e-20, dps=15), 25) + 2.0 + >>> nprint(fsub(2, 1e-20, dps=25), 25) + 1.99999999999999999999 + >>> nprint(fsub(2, 1e-20, exact=True), 25) + 1.99999999999999999999 + + Exact subtraction avoids cancellation errors, enforcing familiar laws + of numbers such as `x-y+y = x`, which don't hold in floating-point + arithmetic with finite precision:: + + >>> x, y = mpf(2), mpf('1e1000') + >>> print(x - y + y) + 0.0 + >>> print(fsub(x, y, prec=inf) + y) + 2.0 + >>> print(fsub(x, y, exact=True) + y) + 2.0 + + Exact addition can be inefficient and may be impossible to perform + with large magnitude differences:: + + >>> fsub(1, '1e-100000000000000000000', prec=inf) + Traceback (most recent call last): + ... + OverflowError: the exact result does not fit in memory + + """ + prec, rounding = ctx._parse_prec(kwargs) + x = ctx.convert(x) + y = ctx.convert(y) + try: + if hasattr(x, '_mpf_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpf(mpf_sub(x._mpf_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_sub((x._mpf_, fzero), y._mpc_, prec, rounding)) + if hasattr(x, '_mpc_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpc(mpc_sub_mpf(x._mpc_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_sub(x._mpc_, y._mpc_, prec, rounding)) + except (ValueError, OverflowError): + raise OverflowError(ctx._exact_overflow_msg) + raise ValueError("Arguments need to be mpf or mpc compatible numbers") + + def fmul(ctx, x, y, **kwargs): + """ + Multiplies the numbers *x* and *y*, giving a floating-point result, + optionally using a custom precision and rounding mode. + + See the documentation of :func:`~mpmath.fadd` for a detailed description + of how to specify precision and rounding. + + **Examples** + + The result is an mpmath number:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> fmul(2, 5.0) + mpf('10.0') + >>> fmul(0.5j, 0.5) + mpc(real='0.0', imag='0.25') + + Avoiding roundoff:: + + >>> x, y = 10**10+1, 10**15+1 + >>> print(x*y) + 10000000001000010000000001 + >>> print(mpf(x) * mpf(y)) + 1.0000000001e+25 + >>> print(int(mpf(x) * mpf(y))) + 10000000001000011026399232 + >>> print(int(fmul(x, y))) + 10000000001000011026399232 + >>> print(int(fmul(x, y, dps=25))) + 10000000001000010000000001 + >>> print(int(fmul(x, y, exact=True))) + 10000000001000010000000001 + + Exact multiplication with complex numbers can be inefficient and may + be impossible to perform with large magnitude differences between + real and imaginary parts:: + + >>> x = 1+2j + >>> y = mpc(2, '1e-100000000000000000000') + >>> fmul(x, y) + mpc(real='2.0', imag='4.0') + >>> fmul(x, y, rounding='u') + mpc(real='2.0', imag='4.0000000000000009') + >>> fmul(x, y, exact=True) + Traceback (most recent call last): + ... + OverflowError: the exact result does not fit in memory + + """ + prec, rounding = ctx._parse_prec(kwargs) + x = ctx.convert(x) + y = ctx.convert(y) + try: + if hasattr(x, '_mpf_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpf(mpf_mul(x._mpf_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_mul_mpf(y._mpc_, x._mpf_, prec, rounding)) + if hasattr(x, '_mpc_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpc(mpc_mul_mpf(x._mpc_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_mul(x._mpc_, y._mpc_, prec, rounding)) + except (ValueError, OverflowError): + raise OverflowError(ctx._exact_overflow_msg) + raise ValueError("Arguments need to be mpf or mpc compatible numbers") + + def fdiv(ctx, x, y, **kwargs): + """ + Divides the numbers *x* and *y*, giving a floating-point result, + optionally using a custom precision and rounding mode. + + See the documentation of :func:`~mpmath.fadd` for a detailed description + of how to specify precision and rounding. + + **Examples** + + The result is an mpmath number:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> fdiv(3, 2) + mpf('1.5') + >>> fdiv(2, 3) + mpf('0.66666666666666663') + >>> fdiv(2+4j, 0.5) + mpc(real='4.0', imag='8.0') + + The rounding direction and precision can be controlled:: + + >>> fdiv(2, 3, dps=3) # Should be accurate to at least 3 digits + mpf('0.6666259765625') + >>> fdiv(2, 3, rounding='d') + mpf('0.66666666666666663') + >>> fdiv(2, 3, prec=60) + mpf('0.66666666666666667') + >>> fdiv(2, 3, rounding='u') + mpf('0.66666666666666674') + + Checking the error of a division by performing it at higher precision:: + + >>> fdiv(2, 3) - fdiv(2, 3, prec=100) + mpf('-3.7007434154172148e-17') + + Unlike :func:`~mpmath.fadd`, :func:`~mpmath.fmul`, etc., exact division is not + allowed since the quotient of two floating-point numbers generally + does not have an exact floating-point representation. (In the + future this might be changed to allow the case where the division + is actually exact.) + + >>> fdiv(2, 3, exact=True) + Traceback (most recent call last): + ... + ValueError: division is not an exact operation + + """ + prec, rounding = ctx._parse_prec(kwargs) + if not prec: + raise ValueError("division is not an exact operation") + x = ctx.convert(x) + y = ctx.convert(y) + if hasattr(x, '_mpf_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpf(mpf_div(x._mpf_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_div((x._mpf_, fzero), y._mpc_, prec, rounding)) + if hasattr(x, '_mpc_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpc(mpc_div_mpf(x._mpc_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_div(x._mpc_, y._mpc_, prec, rounding)) + raise ValueError("Arguments need to be mpf or mpc compatible numbers") + + def nint_distance(ctx, x): + r""" + Return `(n,d)` where `n` is the nearest integer to `x` and `d` is + an estimate of `\log_2(|x-n|)`. If `d < 0`, `-d` gives the precision + (measured in bits) lost to cancellation when computing `x-n`. + + >>> from mpmath import * + >>> n, d = nint_distance(5) + >>> print(n); print(d) + 5 + -inf + >>> n, d = nint_distance(mpf(5)) + >>> print(n); print(d) + 5 + -inf + >>> n, d = nint_distance(mpf(5.00000001)) + >>> print(n); print(d) + 5 + -26 + >>> n, d = nint_distance(mpf(4.99999999)) + >>> print(n); print(d) + 5 + -26 + >>> n, d = nint_distance(mpc(5,10)) + >>> print(n); print(d) + 5 + 4 + >>> n, d = nint_distance(mpc(5,0.000001)) + >>> print(n); print(d) + 5 + -19 + + """ + typx = type(x) + if typx in int_types: + return int(x), ctx.ninf + elif typx is rational.mpq: + p, q = x._mpq_ + n, r = divmod(p, q) + if 2*r >= q: + n += 1 + elif not r: + return n, ctx.ninf + # log(p/q-n) = log((p-nq)/q) = log(p-nq) - log(q) + d = bitcount(abs(p-n*q)) - bitcount(q) + return n, d + if hasattr(x, "_mpf_"): + re = x._mpf_ + im_dist = ctx.ninf + elif hasattr(x, "_mpc_"): + re, im = x._mpc_ + isign, iman, iexp, ibc = im + if iman: + im_dist = iexp + ibc + elif im == fzero: + im_dist = ctx.ninf + else: + raise ValueError("requires a finite number") + else: + x = ctx.convert(x) + if hasattr(x, "_mpf_") or hasattr(x, "_mpc_"): + return ctx.nint_distance(x) + else: + raise TypeError("requires an mpf/mpc") + sign, man, exp, bc = re + mag = exp+bc + # |x| < 0.5 + if mag < 0: + n = 0 + re_dist = mag + elif man: + # exact integer + if exp >= 0: + n = man << exp + re_dist = ctx.ninf + # exact half-integer + elif exp == -1: + n = (man>>1)+1 + re_dist = 0 + else: + d = (-exp-1) + t = man >> d + if t & 1: + t += 1 + man = (t<>1 # int(t)>>1 + re_dist = exp+bitcount(man) + if sign: + n = -n + elif re == fzero: + re_dist = ctx.ninf + n = 0 + else: + raise ValueError("requires a finite number") + return n, max(re_dist, im_dist) + + def fprod(ctx, factors): + r""" + Calculates a product containing a finite number of factors (for + infinite products, see :func:`~mpmath.nprod`). The factors will be + converted to mpmath numbers. + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> fprod([1, 2, 0.5, 7]) + mpf('7.0') + + """ + orig = ctx.prec + try: + v = ctx.one + for p in factors: + v *= p + finally: + ctx.prec = orig + return +v + + def rand(ctx): + """ + Returns an ``mpf`` with value chosen randomly from `[0, 1)`. + The number of randomly generated bits in the mantissa is equal + to the working precision. + """ + return ctx.make_mpf(mpf_rand(ctx._prec)) + + def fraction(ctx, p, q): + """ + Given Python integers `(p, q)`, returns a lazy ``mpf`` representing + the fraction `p/q`. The value is updated with the precision. + + >>> from mpmath import * + >>> mp.dps = 15 + >>> a = fraction(1,100) + >>> b = mpf(1)/100 + >>> print(a); print(b) + 0.01 + 0.01 + >>> mp.dps = 30 + >>> print(a); print(b) # a will be accurate + 0.01 + 0.0100000000000000002081668171172 + >>> mp.dps = 15 + """ + return ctx.constant(lambda prec, rnd: from_rational(p, q, prec, rnd), + '%s/%s' % (p, q)) + + def absmin(ctx, x): + return abs(ctx.convert(x)) + + def absmax(ctx, x): + return abs(ctx.convert(x)) + + def _as_points(ctx, x): + # XXX: remove this? + if hasattr(x, '_mpi_'): + a, b = x._mpi_ + return [ctx.make_mpf(a), ctx.make_mpf(b)] + return x + + ''' + def _zetasum(ctx, s, a, b): + """ + Computes sum of k^(-s) for k = a, a+1, ..., b with a, b both small + integers. + """ + a = int(a) + b = int(b) + s = ctx.convert(s) + prec, rounding = ctx._prec_rounding + if hasattr(s, '_mpf_'): + v = ctx.make_mpf(libmp.mpf_zetasum(s._mpf_, a, b, prec)) + elif hasattr(s, '_mpc_'): + v = ctx.make_mpc(libmp.mpc_zetasum(s._mpc_, a, b, prec)) + return v + ''' + + def _zetasum_fast(ctx, s, a, n, derivatives=[0], reflect=False): + if not (ctx.isint(a) and hasattr(s, "_mpc_")): + raise NotImplementedError + a = int(a) + prec = ctx._prec + xs, ys = libmp.mpc_zetasum(s._mpc_, a, n, derivatives, reflect, prec) + xs = [ctx.make_mpc(x) for x in xs] + ys = [ctx.make_mpc(y) for y in ys] + return xs, ys + +class PrecisionManager: + def __init__(self, ctx, precfun, dpsfun, normalize_output=False): + self.ctx = ctx + self.precfun = precfun + self.dpsfun = dpsfun + self.normalize_output = normalize_output + def __call__(self, f): + @functools.wraps(f) + def g(*args, **kwargs): + orig = self.ctx.prec + try: + if self.precfun: + self.ctx.prec = self.precfun(self.ctx.prec) + else: + self.ctx.dps = self.dpsfun(self.ctx.dps) + if self.normalize_output: + v = f(*args, **kwargs) + if type(v) is tuple: + return tuple([+a for a in v]) + return +v + else: + return f(*args, **kwargs) + finally: + self.ctx.prec = orig + return g + def __enter__(self): + self.origp = self.ctx.prec + if self.precfun: + self.ctx.prec = self.precfun(self.ctx.prec) + else: + self.ctx.dps = self.dpsfun(self.ctx.dps) + def __exit__(self, exc_type, exc_val, exc_tb): + self.ctx.prec = self.origp + return False + + +if __name__ == '__main__': + import doctest + doctest.testmod() diff --git a/venv/lib/python3.10/site-packages/mpmath/ctx_mp_python.py b/venv/lib/python3.10/site-packages/mpmath/ctx_mp_python.py new file mode 100644 index 0000000000000000000000000000000000000000..cfbd72fb8300bf840069c38529b7b41418d26eeb --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/ctx_mp_python.py @@ -0,0 +1,1149 @@ +#from ctx_base import StandardBaseContext + +from .libmp.backend import basestring, exec_ + +from .libmp import (MPZ, MPZ_ZERO, MPZ_ONE, int_types, repr_dps, + round_floor, round_ceiling, dps_to_prec, round_nearest, prec_to_dps, + ComplexResult, to_pickable, from_pickable, normalize, + from_int, from_float, from_npfloat, from_Decimal, from_str, to_int, to_float, to_str, + from_rational, from_man_exp, + fone, fzero, finf, fninf, fnan, + mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, mpf_mul_int, + mpf_div, mpf_rdiv_int, mpf_pow_int, mpf_mod, + mpf_eq, mpf_cmp, mpf_lt, mpf_gt, mpf_le, mpf_ge, + mpf_hash, mpf_rand, + mpf_sum, + bitcount, to_fixed, + mpc_to_str, + mpc_to_complex, mpc_hash, mpc_pos, mpc_is_nonzero, mpc_neg, mpc_conjugate, + mpc_abs, mpc_add, mpc_add_mpf, mpc_sub, mpc_sub_mpf, mpc_mul, mpc_mul_mpf, + mpc_mul_int, mpc_div, mpc_div_mpf, mpc_pow, mpc_pow_mpf, mpc_pow_int, + mpc_mpf_div, + mpf_pow, + mpf_pi, mpf_degree, mpf_e, mpf_phi, mpf_ln2, mpf_ln10, + mpf_euler, mpf_catalan, mpf_apery, mpf_khinchin, + mpf_glaisher, mpf_twinprime, mpf_mertens, + int_types) + +from . import rational +from . import function_docs + +new = object.__new__ + +class mpnumeric(object): + """Base class for mpf and mpc.""" + __slots__ = [] + def __new__(cls, val): + raise NotImplementedError + +class _mpf(mpnumeric): + """ + An mpf instance holds a real-valued floating-point number. mpf:s + work analogously to Python floats, but support arbitrary-precision + arithmetic. + """ + __slots__ = ['_mpf_'] + + def __new__(cls, val=fzero, **kwargs): + """A new mpf can be created from a Python float, an int, a + or a decimal string representing a number in floating-point + format.""" + prec, rounding = cls.context._prec_rounding + if kwargs: + prec = kwargs.get('prec', prec) + if 'dps' in kwargs: + prec = dps_to_prec(kwargs['dps']) + rounding = kwargs.get('rounding', rounding) + if type(val) is cls: + sign, man, exp, bc = val._mpf_ + if (not man) and exp: + return val + v = new(cls) + v._mpf_ = normalize(sign, man, exp, bc, prec, rounding) + return v + elif type(val) is tuple: + if len(val) == 2: + v = new(cls) + v._mpf_ = from_man_exp(val[0], val[1], prec, rounding) + return v + if len(val) == 4: + if val not in (finf, fninf, fnan): + sign, man, exp, bc = val + val = normalize(sign, MPZ(man), exp, bc, prec, rounding) + v = new(cls) + v._mpf_ = val + return v + raise ValueError + else: + v = new(cls) + v._mpf_ = mpf_pos(cls.mpf_convert_arg(val, prec, rounding), prec, rounding) + return v + + @classmethod + def mpf_convert_arg(cls, x, prec, rounding): + if isinstance(x, int_types): return from_int(x) + if isinstance(x, float): return from_float(x) + if isinstance(x, basestring): return from_str(x, prec, rounding) + if isinstance(x, cls.context.constant): return x.func(prec, rounding) + if hasattr(x, '_mpf_'): return x._mpf_ + if hasattr(x, '_mpmath_'): + t = cls.context.convert(x._mpmath_(prec, rounding)) + if hasattr(t, '_mpf_'): + return t._mpf_ + if hasattr(x, '_mpi_'): + a, b = x._mpi_ + if a == b: + return a + raise ValueError("can only create mpf from zero-width interval") + raise TypeError("cannot create mpf from " + repr(x)) + + @classmethod + def mpf_convert_rhs(cls, x): + if isinstance(x, int_types): return from_int(x) + if isinstance(x, float): return from_float(x) + if isinstance(x, complex_types): return cls.context.mpc(x) + if isinstance(x, rational.mpq): + p, q = x._mpq_ + return from_rational(p, q, cls.context.prec) + if hasattr(x, '_mpf_'): return x._mpf_ + if hasattr(x, '_mpmath_'): + t = cls.context.convert(x._mpmath_(*cls.context._prec_rounding)) + if hasattr(t, '_mpf_'): + return t._mpf_ + return t + return NotImplemented + + @classmethod + def mpf_convert_lhs(cls, x): + x = cls.mpf_convert_rhs(x) + if type(x) is tuple: + return cls.context.make_mpf(x) + return x + + man_exp = property(lambda self: self._mpf_[1:3]) + man = property(lambda self: self._mpf_[1]) + exp = property(lambda self: self._mpf_[2]) + bc = property(lambda self: self._mpf_[3]) + + real = property(lambda self: self) + imag = property(lambda self: self.context.zero) + + conjugate = lambda self: self + + def __getstate__(self): return to_pickable(self._mpf_) + def __setstate__(self, val): self._mpf_ = from_pickable(val) + + def __repr__(s): + if s.context.pretty: + return str(s) + return "mpf('%s')" % to_str(s._mpf_, s.context._repr_digits) + + def __str__(s): return to_str(s._mpf_, s.context._str_digits) + def __hash__(s): return mpf_hash(s._mpf_) + def __int__(s): return int(to_int(s._mpf_)) + def __long__(s): return long(to_int(s._mpf_)) + def __float__(s): return to_float(s._mpf_, rnd=s.context._prec_rounding[1]) + def __complex__(s): return complex(float(s)) + def __nonzero__(s): return s._mpf_ != fzero + + __bool__ = __nonzero__ + + def __abs__(s): + cls, new, (prec, rounding) = s._ctxdata + v = new(cls) + v._mpf_ = mpf_abs(s._mpf_, prec, rounding) + return v + + def __pos__(s): + cls, new, (prec, rounding) = s._ctxdata + v = new(cls) + v._mpf_ = mpf_pos(s._mpf_, prec, rounding) + return v + + def __neg__(s): + cls, new, (prec, rounding) = s._ctxdata + v = new(cls) + v._mpf_ = mpf_neg(s._mpf_, prec, rounding) + return v + + def _cmp(s, t, func): + if hasattr(t, '_mpf_'): + t = t._mpf_ + else: + t = s.mpf_convert_rhs(t) + if t is NotImplemented: + return t + return func(s._mpf_, t) + + def __cmp__(s, t): return s._cmp(t, mpf_cmp) + def __lt__(s, t): return s._cmp(t, mpf_lt) + def __gt__(s, t): return s._cmp(t, mpf_gt) + def __le__(s, t): return s._cmp(t, mpf_le) + def __ge__(s, t): return s._cmp(t, mpf_ge) + + def __ne__(s, t): + v = s.__eq__(t) + if v is NotImplemented: + return v + return not v + + def __rsub__(s, t): + cls, new, (prec, rounding) = s._ctxdata + if type(t) in int_types: + v = new(cls) + v._mpf_ = mpf_sub(from_int(t), s._mpf_, prec, rounding) + return v + t = s.mpf_convert_lhs(t) + if t is NotImplemented: + return t + return t - s + + def __rdiv__(s, t): + cls, new, (prec, rounding) = s._ctxdata + if isinstance(t, int_types): + v = new(cls) + v._mpf_ = mpf_rdiv_int(t, s._mpf_, prec, rounding) + return v + t = s.mpf_convert_lhs(t) + if t is NotImplemented: + return t + return t / s + + def __rpow__(s, t): + t = s.mpf_convert_lhs(t) + if t is NotImplemented: + return t + return t ** s + + def __rmod__(s, t): + t = s.mpf_convert_lhs(t) + if t is NotImplemented: + return t + return t % s + + def sqrt(s): + return s.context.sqrt(s) + + def ae(s, t, rel_eps=None, abs_eps=None): + return s.context.almosteq(s, t, rel_eps, abs_eps) + + def to_fixed(self, prec): + return to_fixed(self._mpf_, prec) + + def __round__(self, *args): + return round(float(self), *args) + +mpf_binary_op = """ +def %NAME%(self, other): + mpf, new, (prec, rounding) = self._ctxdata + sval = self._mpf_ + if hasattr(other, '_mpf_'): + tval = other._mpf_ + %WITH_MPF% + ttype = type(other) + if ttype in int_types: + %WITH_INT% + elif ttype is float: + tval = from_float(other) + %WITH_MPF% + elif hasattr(other, '_mpc_'): + tval = other._mpc_ + mpc = type(other) + %WITH_MPC% + elif ttype is complex: + tval = from_float(other.real), from_float(other.imag) + mpc = self.context.mpc + %WITH_MPC% + if isinstance(other, mpnumeric): + return NotImplemented + try: + other = mpf.context.convert(other, strings=False) + except TypeError: + return NotImplemented + return self.%NAME%(other) +""" + +return_mpf = "; obj = new(mpf); obj._mpf_ = val; return obj" +return_mpc = "; obj = new(mpc); obj._mpc_ = val; return obj" + +mpf_pow_same = """ + try: + val = mpf_pow(sval, tval, prec, rounding) %s + except ComplexResult: + if mpf.context.trap_complex: + raise + mpc = mpf.context.mpc + val = mpc_pow((sval, fzero), (tval, fzero), prec, rounding) %s +""" % (return_mpf, return_mpc) + +def binary_op(name, with_mpf='', with_int='', with_mpc=''): + code = mpf_binary_op + code = code.replace("%WITH_INT%", with_int) + code = code.replace("%WITH_MPC%", with_mpc) + code = code.replace("%WITH_MPF%", with_mpf) + code = code.replace("%NAME%", name) + np = {} + exec_(code, globals(), np) + return np[name] + +_mpf.__eq__ = binary_op('__eq__', + 'return mpf_eq(sval, tval)', + 'return mpf_eq(sval, from_int(other))', + 'return (tval[1] == fzero) and mpf_eq(tval[0], sval)') + +_mpf.__add__ = binary_op('__add__', + 'val = mpf_add(sval, tval, prec, rounding)' + return_mpf, + 'val = mpf_add(sval, from_int(other), prec, rounding)' + return_mpf, + 'val = mpc_add_mpf(tval, sval, prec, rounding)' + return_mpc) + +_mpf.__sub__ = binary_op('__sub__', + 'val = mpf_sub(sval, tval, prec, rounding)' + return_mpf, + 'val = mpf_sub(sval, from_int(other), prec, rounding)' + return_mpf, + 'val = mpc_sub((sval, fzero), tval, prec, rounding)' + return_mpc) + +_mpf.__mul__ = binary_op('__mul__', + 'val = mpf_mul(sval, tval, prec, rounding)' + return_mpf, + 'val = mpf_mul_int(sval, other, prec, rounding)' + return_mpf, + 'val = mpc_mul_mpf(tval, sval, prec, rounding)' + return_mpc) + +_mpf.__div__ = binary_op('__div__', + 'val = mpf_div(sval, tval, prec, rounding)' + return_mpf, + 'val = mpf_div(sval, from_int(other), prec, rounding)' + return_mpf, + 'val = mpc_mpf_div(sval, tval, prec, rounding)' + return_mpc) + +_mpf.__mod__ = binary_op('__mod__', + 'val = mpf_mod(sval, tval, prec, rounding)' + return_mpf, + 'val = mpf_mod(sval, from_int(other), prec, rounding)' + return_mpf, + 'raise NotImplementedError("complex modulo")') + +_mpf.__pow__ = binary_op('__pow__', + mpf_pow_same, + 'val = mpf_pow_int(sval, other, prec, rounding)' + return_mpf, + 'val = mpc_pow((sval, fzero), tval, prec, rounding)' + return_mpc) + +_mpf.__radd__ = _mpf.__add__ +_mpf.__rmul__ = _mpf.__mul__ +_mpf.__truediv__ = _mpf.__div__ +_mpf.__rtruediv__ = _mpf.__rdiv__ + + +class _constant(_mpf): + """Represents a mathematical constant with dynamic precision. + When printed or used in an arithmetic operation, a constant + is converted to a regular mpf at the working precision. A + regular mpf can also be obtained using the operation +x.""" + + def __new__(cls, func, name, docname=''): + a = object.__new__(cls) + a.name = name + a.func = func + a.__doc__ = getattr(function_docs, docname, '') + return a + + def __call__(self, prec=None, dps=None, rounding=None): + prec2, rounding2 = self.context._prec_rounding + if not prec: prec = prec2 + if not rounding: rounding = rounding2 + if dps: prec = dps_to_prec(dps) + return self.context.make_mpf(self.func(prec, rounding)) + + @property + def _mpf_(self): + prec, rounding = self.context._prec_rounding + return self.func(prec, rounding) + + def __repr__(self): + return "<%s: %s~>" % (self.name, self.context.nstr(self(dps=15))) + + +class _mpc(mpnumeric): + """ + An mpc represents a complex number using a pair of mpf:s (one + for the real part and another for the imaginary part.) The mpc + class behaves fairly similarly to Python's complex type. + """ + + __slots__ = ['_mpc_'] + + def __new__(cls, real=0, imag=0): + s = object.__new__(cls) + if isinstance(real, complex_types): + real, imag = real.real, real.imag + elif hasattr(real, '_mpc_'): + s._mpc_ = real._mpc_ + return s + real = cls.context.mpf(real) + imag = cls.context.mpf(imag) + s._mpc_ = (real._mpf_, imag._mpf_) + return s + + real = property(lambda self: self.context.make_mpf(self._mpc_[0])) + imag = property(lambda self: self.context.make_mpf(self._mpc_[1])) + + def __getstate__(self): + return to_pickable(self._mpc_[0]), to_pickable(self._mpc_[1]) + + def __setstate__(self, val): + self._mpc_ = from_pickable(val[0]), from_pickable(val[1]) + + def __repr__(s): + if s.context.pretty: + return str(s) + r = repr(s.real)[4:-1] + i = repr(s.imag)[4:-1] + return "%s(real=%s, imag=%s)" % (type(s).__name__, r, i) + + def __str__(s): + return "(%s)" % mpc_to_str(s._mpc_, s.context._str_digits) + + def __complex__(s): + return mpc_to_complex(s._mpc_, rnd=s.context._prec_rounding[1]) + + def __pos__(s): + cls, new, (prec, rounding) = s._ctxdata + v = new(cls) + v._mpc_ = mpc_pos(s._mpc_, prec, rounding) + return v + + def __abs__(s): + prec, rounding = s.context._prec_rounding + v = new(s.context.mpf) + v._mpf_ = mpc_abs(s._mpc_, prec, rounding) + return v + + def __neg__(s): + cls, new, (prec, rounding) = s._ctxdata + v = new(cls) + v._mpc_ = mpc_neg(s._mpc_, prec, rounding) + return v + + def conjugate(s): + cls, new, (prec, rounding) = s._ctxdata + v = new(cls) + v._mpc_ = mpc_conjugate(s._mpc_, prec, rounding) + return v + + def __nonzero__(s): + return mpc_is_nonzero(s._mpc_) + + __bool__ = __nonzero__ + + def __hash__(s): + return mpc_hash(s._mpc_) + + @classmethod + def mpc_convert_lhs(cls, x): + try: + y = cls.context.convert(x) + return y + except TypeError: + return NotImplemented + + def __eq__(s, t): + if not hasattr(t, '_mpc_'): + if isinstance(t, str): + return False + t = s.mpc_convert_lhs(t) + if t is NotImplemented: + return t + return s.real == t.real and s.imag == t.imag + + def __ne__(s, t): + b = s.__eq__(t) + if b is NotImplemented: + return b + return not b + + def _compare(*args): + raise TypeError("no ordering relation is defined for complex numbers") + + __gt__ = _compare + __le__ = _compare + __gt__ = _compare + __ge__ = _compare + + def __add__(s, t): + cls, new, (prec, rounding) = s._ctxdata + if not hasattr(t, '_mpc_'): + t = s.mpc_convert_lhs(t) + if t is NotImplemented: + return t + if hasattr(t, '_mpf_'): + v = new(cls) + v._mpc_ = mpc_add_mpf(s._mpc_, t._mpf_, prec, rounding) + return v + v = new(cls) + v._mpc_ = mpc_add(s._mpc_, t._mpc_, prec, rounding) + return v + + def __sub__(s, t): + cls, new, (prec, rounding) = s._ctxdata + if not hasattr(t, '_mpc_'): + t = s.mpc_convert_lhs(t) + if t is NotImplemented: + return t + if hasattr(t, '_mpf_'): + v = new(cls) + v._mpc_ = mpc_sub_mpf(s._mpc_, t._mpf_, prec, rounding) + return v + v = new(cls) + v._mpc_ = mpc_sub(s._mpc_, t._mpc_, prec, rounding) + return v + + def __mul__(s, t): + cls, new, (prec, rounding) = s._ctxdata + if not hasattr(t, '_mpc_'): + if isinstance(t, int_types): + v = new(cls) + v._mpc_ = mpc_mul_int(s._mpc_, t, prec, rounding) + return v + t = s.mpc_convert_lhs(t) + if t is NotImplemented: + return t + if hasattr(t, '_mpf_'): + v = new(cls) + v._mpc_ = mpc_mul_mpf(s._mpc_, t._mpf_, prec, rounding) + return v + t = s.mpc_convert_lhs(t) + v = new(cls) + v._mpc_ = mpc_mul(s._mpc_, t._mpc_, prec, rounding) + return v + + def __div__(s, t): + cls, new, (prec, rounding) = s._ctxdata + if not hasattr(t, '_mpc_'): + t = s.mpc_convert_lhs(t) + if t is NotImplemented: + return t + if hasattr(t, '_mpf_'): + v = new(cls) + v._mpc_ = mpc_div_mpf(s._mpc_, t._mpf_, prec, rounding) + return v + v = new(cls) + v._mpc_ = mpc_div(s._mpc_, t._mpc_, prec, rounding) + return v + + def __pow__(s, t): + cls, new, (prec, rounding) = s._ctxdata + if isinstance(t, int_types): + v = new(cls) + v._mpc_ = mpc_pow_int(s._mpc_, t, prec, rounding) + return v + t = s.mpc_convert_lhs(t) + if t is NotImplemented: + return t + v = new(cls) + if hasattr(t, '_mpf_'): + v._mpc_ = mpc_pow_mpf(s._mpc_, t._mpf_, prec, rounding) + else: + v._mpc_ = mpc_pow(s._mpc_, t._mpc_, prec, rounding) + return v + + __radd__ = __add__ + + def __rsub__(s, t): + t = s.mpc_convert_lhs(t) + if t is NotImplemented: + return t + return t - s + + def __rmul__(s, t): + cls, new, (prec, rounding) = s._ctxdata + if isinstance(t, int_types): + v = new(cls) + v._mpc_ = mpc_mul_int(s._mpc_, t, prec, rounding) + return v + t = s.mpc_convert_lhs(t) + if t is NotImplemented: + return t + return t * s + + def __rdiv__(s, t): + t = s.mpc_convert_lhs(t) + if t is NotImplemented: + return t + return t / s + + def __rpow__(s, t): + t = s.mpc_convert_lhs(t) + if t is NotImplemented: + return t + return t ** s + + __truediv__ = __div__ + __rtruediv__ = __rdiv__ + + def ae(s, t, rel_eps=None, abs_eps=None): + return s.context.almosteq(s, t, rel_eps, abs_eps) + + +complex_types = (complex, _mpc) + + +class PythonMPContext(object): + + def __init__(ctx): + ctx._prec_rounding = [53, round_nearest] + ctx.mpf = type('mpf', (_mpf,), {}) + ctx.mpc = type('mpc', (_mpc,), {}) + ctx.mpf._ctxdata = [ctx.mpf, new, ctx._prec_rounding] + ctx.mpc._ctxdata = [ctx.mpc, new, ctx._prec_rounding] + ctx.mpf.context = ctx + ctx.mpc.context = ctx + ctx.constant = type('constant', (_constant,), {}) + ctx.constant._ctxdata = [ctx.mpf, new, ctx._prec_rounding] + ctx.constant.context = ctx + + def make_mpf(ctx, v): + a = new(ctx.mpf) + a._mpf_ = v + return a + + def make_mpc(ctx, v): + a = new(ctx.mpc) + a._mpc_ = v + return a + + def default(ctx): + ctx._prec = ctx._prec_rounding[0] = 53 + ctx._dps = 15 + ctx.trap_complex = False + + def _set_prec(ctx, n): + ctx._prec = ctx._prec_rounding[0] = max(1, int(n)) + ctx._dps = prec_to_dps(n) + + def _set_dps(ctx, n): + ctx._prec = ctx._prec_rounding[0] = dps_to_prec(n) + ctx._dps = max(1, int(n)) + + prec = property(lambda ctx: ctx._prec, _set_prec) + dps = property(lambda ctx: ctx._dps, _set_dps) + + def convert(ctx, x, strings=True): + """ + Converts *x* to an ``mpf`` or ``mpc``. If *x* is of type ``mpf``, + ``mpc``, ``int``, ``float``, ``complex``, the conversion + will be performed losslessly. + + If *x* is a string, the result will be rounded to the present + working precision. Strings representing fractions or complex + numbers are permitted. + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> mpmathify(3.5) + mpf('3.5') + >>> mpmathify('2.1') + mpf('2.1000000000000001') + >>> mpmathify('3/4') + mpf('0.75') + >>> mpmathify('2+3j') + mpc(real='2.0', imag='3.0') + + """ + if type(x) in ctx.types: return x + if isinstance(x, int_types): return ctx.make_mpf(from_int(x)) + if isinstance(x, float): return ctx.make_mpf(from_float(x)) + if isinstance(x, complex): + return ctx.make_mpc((from_float(x.real), from_float(x.imag))) + if type(x).__module__ == 'numpy': return ctx.npconvert(x) + if isinstance(x, numbers.Rational): # e.g. Fraction + try: x = rational.mpq(int(x.numerator), int(x.denominator)) + except: pass + prec, rounding = ctx._prec_rounding + if isinstance(x, rational.mpq): + p, q = x._mpq_ + return ctx.make_mpf(from_rational(p, q, prec)) + if strings and isinstance(x, basestring): + try: + _mpf_ = from_str(x, prec, rounding) + return ctx.make_mpf(_mpf_) + except ValueError: + pass + if hasattr(x, '_mpf_'): return ctx.make_mpf(x._mpf_) + if hasattr(x, '_mpc_'): return ctx.make_mpc(x._mpc_) + if hasattr(x, '_mpmath_'): + return ctx.convert(x._mpmath_(prec, rounding)) + if type(x).__module__ == 'decimal': + try: return ctx.make_mpf(from_Decimal(x, prec, rounding)) + except: pass + return ctx._convert_fallback(x, strings) + + def npconvert(ctx, x): + """ + Converts *x* to an ``mpf`` or ``mpc``. *x* should be a numpy + scalar. + """ + import numpy as np + if isinstance(x, np.integer): return ctx.make_mpf(from_int(int(x))) + if isinstance(x, np.floating): return ctx.make_mpf(from_npfloat(x)) + if isinstance(x, np.complexfloating): + return ctx.make_mpc((from_npfloat(x.real), from_npfloat(x.imag))) + raise TypeError("cannot create mpf from " + repr(x)) + + def isnan(ctx, x): + """ + Return *True* if *x* is a NaN (not-a-number), or for a complex + number, whether either the real or complex part is NaN; + otherwise return *False*:: + + >>> from mpmath import * + >>> isnan(3.14) + False + >>> isnan(nan) + True + >>> isnan(mpc(3.14,2.72)) + False + >>> isnan(mpc(3.14,nan)) + True + + """ + if hasattr(x, "_mpf_"): + return x._mpf_ == fnan + if hasattr(x, "_mpc_"): + return fnan in x._mpc_ + if isinstance(x, int_types) or isinstance(x, rational.mpq): + return False + x = ctx.convert(x) + if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'): + return ctx.isnan(x) + raise TypeError("isnan() needs a number as input") + + def isinf(ctx, x): + """ + Return *True* if the absolute value of *x* is infinite; + otherwise return *False*:: + + >>> from mpmath import * + >>> isinf(inf) + True + >>> isinf(-inf) + True + >>> isinf(3) + False + >>> isinf(3+4j) + False + >>> isinf(mpc(3,inf)) + True + >>> isinf(mpc(inf,3)) + True + + """ + if hasattr(x, "_mpf_"): + return x._mpf_ in (finf, fninf) + if hasattr(x, "_mpc_"): + re, im = x._mpc_ + return re in (finf, fninf) or im in (finf, fninf) + if isinstance(x, int_types) or isinstance(x, rational.mpq): + return False + x = ctx.convert(x) + if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'): + return ctx.isinf(x) + raise TypeError("isinf() needs a number as input") + + def isnormal(ctx, x): + """ + Determine whether *x* is "normal" in the sense of floating-point + representation; that is, return *False* if *x* is zero, an + infinity or NaN; otherwise return *True*. By extension, a + complex number *x* is considered "normal" if its magnitude is + normal:: + + >>> from mpmath import * + >>> isnormal(3) + True + >>> isnormal(0) + False + >>> isnormal(inf); isnormal(-inf); isnormal(nan) + False + False + False + >>> isnormal(0+0j) + False + >>> isnormal(0+3j) + True + >>> isnormal(mpc(2,nan)) + False + """ + if hasattr(x, "_mpf_"): + return bool(x._mpf_[1]) + if hasattr(x, "_mpc_"): + re, im = x._mpc_ + re_normal = bool(re[1]) + im_normal = bool(im[1]) + if re == fzero: return im_normal + if im == fzero: return re_normal + return re_normal and im_normal + if isinstance(x, int_types) or isinstance(x, rational.mpq): + return bool(x) + x = ctx.convert(x) + if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'): + return ctx.isnormal(x) + raise TypeError("isnormal() needs a number as input") + + def isint(ctx, x, gaussian=False): + """ + Return *True* if *x* is integer-valued; otherwise return + *False*:: + + >>> from mpmath import * + >>> isint(3) + True + >>> isint(mpf(3)) + True + >>> isint(3.2) + False + >>> isint(inf) + False + + Optionally, Gaussian integers can be checked for:: + + >>> isint(3+0j) + True + >>> isint(3+2j) + False + >>> isint(3+2j, gaussian=True) + True + + """ + if isinstance(x, int_types): + return True + if hasattr(x, "_mpf_"): + sign, man, exp, bc = xval = x._mpf_ + return bool((man and exp >= 0) or xval == fzero) + if hasattr(x, "_mpc_"): + re, im = x._mpc_ + rsign, rman, rexp, rbc = re + isign, iman, iexp, ibc = im + re_isint = (rman and rexp >= 0) or re == fzero + if gaussian: + im_isint = (iman and iexp >= 0) or im == fzero + return re_isint and im_isint + return re_isint and im == fzero + if isinstance(x, rational.mpq): + p, q = x._mpq_ + return p % q == 0 + x = ctx.convert(x) + if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'): + return ctx.isint(x, gaussian) + raise TypeError("isint() needs a number as input") + + def fsum(ctx, terms, absolute=False, squared=False): + """ + Calculates a sum containing a finite number of terms (for infinite + series, see :func:`~mpmath.nsum`). The terms will be converted to + mpmath numbers. For len(terms) > 2, this function is generally + faster and produces more accurate results than the builtin + Python function :func:`sum`. + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> fsum([1, 2, 0.5, 7]) + mpf('10.5') + + With squared=True each term is squared, and with absolute=True + the absolute value of each term is used. + """ + prec, rnd = ctx._prec_rounding + real = [] + imag = [] + for term in terms: + reval = imval = 0 + if hasattr(term, "_mpf_"): + reval = term._mpf_ + elif hasattr(term, "_mpc_"): + reval, imval = term._mpc_ + else: + term = ctx.convert(term) + if hasattr(term, "_mpf_"): + reval = term._mpf_ + elif hasattr(term, "_mpc_"): + reval, imval = term._mpc_ + else: + raise NotImplementedError + if imval: + if squared: + if absolute: + real.append(mpf_mul(reval,reval)) + real.append(mpf_mul(imval,imval)) + else: + reval, imval = mpc_pow_int((reval,imval),2,prec+10) + real.append(reval) + imag.append(imval) + elif absolute: + real.append(mpc_abs((reval,imval), prec)) + else: + real.append(reval) + imag.append(imval) + else: + if squared: + reval = mpf_mul(reval, reval) + elif absolute: + reval = mpf_abs(reval) + real.append(reval) + s = mpf_sum(real, prec, rnd, absolute) + if imag: + s = ctx.make_mpc((s, mpf_sum(imag, prec, rnd))) + else: + s = ctx.make_mpf(s) + return s + + def fdot(ctx, A, B=None, conjugate=False): + r""" + Computes the dot product of the iterables `A` and `B`, + + .. math :: + + \sum_{k=0} A_k B_k. + + Alternatively, :func:`~mpmath.fdot` accepts a single iterable of pairs. + In other words, ``fdot(A,B)`` and ``fdot(zip(A,B))`` are equivalent. + The elements are automatically converted to mpmath numbers. + + With ``conjugate=True``, the elements in the second vector + will be conjugated: + + .. math :: + + \sum_{k=0} A_k \overline{B_k} + + **Examples** + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> A = [2, 1.5, 3] + >>> B = [1, -1, 2] + >>> fdot(A, B) + mpf('6.5') + >>> list(zip(A, B)) + [(2, 1), (1.5, -1), (3, 2)] + >>> fdot(_) + mpf('6.5') + >>> A = [2, 1.5, 3j] + >>> B = [1+j, 3, -1-j] + >>> fdot(A, B) + mpc(real='9.5', imag='-1.0') + >>> fdot(A, B, conjugate=True) + mpc(real='3.5', imag='-5.0') + + """ + if B is not None: + A = zip(A, B) + prec, rnd = ctx._prec_rounding + real = [] + imag = [] + hasattr_ = hasattr + types = (ctx.mpf, ctx.mpc) + for a, b in A: + if type(a) not in types: a = ctx.convert(a) + if type(b) not in types: b = ctx.convert(b) + a_real = hasattr_(a, "_mpf_") + b_real = hasattr_(b, "_mpf_") + if a_real and b_real: + real.append(mpf_mul(a._mpf_, b._mpf_)) + continue + a_complex = hasattr_(a, "_mpc_") + b_complex = hasattr_(b, "_mpc_") + if a_real and b_complex: + aval = a._mpf_ + bre, bim = b._mpc_ + if conjugate: + bim = mpf_neg(bim) + real.append(mpf_mul(aval, bre)) + imag.append(mpf_mul(aval, bim)) + elif b_real and a_complex: + are, aim = a._mpc_ + bval = b._mpf_ + real.append(mpf_mul(are, bval)) + imag.append(mpf_mul(aim, bval)) + elif a_complex and b_complex: + #re, im = mpc_mul(a._mpc_, b._mpc_, prec+20) + are, aim = a._mpc_ + bre, bim = b._mpc_ + if conjugate: + bim = mpf_neg(bim) + real.append(mpf_mul(are, bre)) + real.append(mpf_neg(mpf_mul(aim, bim))) + imag.append(mpf_mul(are, bim)) + imag.append(mpf_mul(aim, bre)) + else: + raise NotImplementedError + s = mpf_sum(real, prec, rnd) + if imag: + s = ctx.make_mpc((s, mpf_sum(imag, prec, rnd))) + else: + s = ctx.make_mpf(s) + return s + + def _wrap_libmp_function(ctx, mpf_f, mpc_f=None, mpi_f=None, doc=""): + """ + Given a low-level mpf_ function, and optionally similar functions + for mpc_ and mpi_, defines the function as a context method. + + It is assumed that the return type is the same as that of + the input; the exception is that propagation from mpf to mpc is possible + by raising ComplexResult. + + """ + def f(x, **kwargs): + if type(x) not in ctx.types: + x = ctx.convert(x) + prec, rounding = ctx._prec_rounding + if kwargs: + prec = kwargs.get('prec', prec) + if 'dps' in kwargs: + prec = dps_to_prec(kwargs['dps']) + rounding = kwargs.get('rounding', rounding) + if hasattr(x, '_mpf_'): + try: + return ctx.make_mpf(mpf_f(x._mpf_, prec, rounding)) + except ComplexResult: + # Handle propagation to complex + if ctx.trap_complex: + raise + return ctx.make_mpc(mpc_f((x._mpf_, fzero), prec, rounding)) + elif hasattr(x, '_mpc_'): + return ctx.make_mpc(mpc_f(x._mpc_, prec, rounding)) + raise NotImplementedError("%s of a %s" % (name, type(x))) + name = mpf_f.__name__[4:] + f.__doc__ = function_docs.__dict__.get(name, "Computes the %s of x" % doc) + return f + + # Called by SpecialFunctions.__init__() + @classmethod + def _wrap_specfun(cls, name, f, wrap): + if wrap: + def f_wrapped(ctx, *args, **kwargs): + convert = ctx.convert + args = [convert(a) for a in args] + prec = ctx.prec + try: + ctx.prec += 10 + retval = f(ctx, *args, **kwargs) + finally: + ctx.prec = prec + return +retval + else: + f_wrapped = f + f_wrapped.__doc__ = function_docs.__dict__.get(name, f.__doc__) + setattr(cls, name, f_wrapped) + + def _convert_param(ctx, x): + if hasattr(x, "_mpc_"): + v, im = x._mpc_ + if im != fzero: + return x, 'C' + elif hasattr(x, "_mpf_"): + v = x._mpf_ + else: + if type(x) in int_types: + return int(x), 'Z' + p = None + if isinstance(x, tuple): + p, q = x + elif hasattr(x, '_mpq_'): + p, q = x._mpq_ + elif isinstance(x, basestring) and '/' in x: + p, q = x.split('/') + p = int(p) + q = int(q) + if p is not None: + if not p % q: + return p // q, 'Z' + return ctx.mpq(p,q), 'Q' + x = ctx.convert(x) + if hasattr(x, "_mpc_"): + v, im = x._mpc_ + if im != fzero: + return x, 'C' + elif hasattr(x, "_mpf_"): + v = x._mpf_ + else: + return x, 'U' + sign, man, exp, bc = v + if man: + if exp >= -4: + if sign: + man = -man + if exp >= 0: + return int(man) << exp, 'Z' + if exp >= -4: + p, q = int(man), (1<<(-exp)) + return ctx.mpq(p,q), 'Q' + x = ctx.make_mpf(v) + return x, 'R' + elif not exp: + return 0, 'Z' + else: + return x, 'U' + + def _mpf_mag(ctx, x): + sign, man, exp, bc = x + if man: + return exp+bc + if x == fzero: + return ctx.ninf + if x == finf or x == fninf: + return ctx.inf + return ctx.nan + + def mag(ctx, x): + """ + Quick logarithmic magnitude estimate of a number. Returns an + integer or infinity `m` such that `|x| <= 2^m`. It is not + guaranteed that `m` is an optimal bound, but it will never + be too large by more than 2 (and probably not more than 1). + + **Examples** + + >>> from mpmath import * + >>> mp.pretty = True + >>> mag(10), mag(10.0), mag(mpf(10)), int(ceil(log(10,2))) + (4, 4, 4, 4) + >>> mag(10j), mag(10+10j) + (4, 5) + >>> mag(0.01), int(ceil(log(0.01,2))) + (-6, -6) + >>> mag(0), mag(inf), mag(-inf), mag(nan) + (-inf, +inf, +inf, nan) + + """ + if hasattr(x, "_mpf_"): + return ctx._mpf_mag(x._mpf_) + elif hasattr(x, "_mpc_"): + r, i = x._mpc_ + if r == fzero: + return ctx._mpf_mag(i) + if i == fzero: + return ctx._mpf_mag(r) + return 1+max(ctx._mpf_mag(r), ctx._mpf_mag(i)) + elif isinstance(x, int_types): + if x: + return bitcount(abs(x)) + return ctx.ninf + elif isinstance(x, rational.mpq): + p, q = x._mpq_ + if p: + return 1 + bitcount(abs(p)) - bitcount(q) + return ctx.ninf + else: + x = ctx.convert(x) + if hasattr(x, "_mpf_") or hasattr(x, "_mpc_"): + return ctx.mag(x) + else: + raise TypeError("requires an mpf/mpc") + + +# Register with "numbers" ABC +# We do not subclass, hence we do not use the @abstractmethod checks. While +# this is less invasive it may turn out that we do not actually support +# parts of the expected interfaces. See +# http://docs.python.org/2/library/numbers.html for list of abstract +# methods. +try: + import numbers + numbers.Complex.register(_mpc) + numbers.Real.register(_mpf) +except ImportError: + pass diff --git a/venv/lib/python3.10/site-packages/mpmath/function_docs.py b/venv/lib/python3.10/site-packages/mpmath/function_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..73c071dc30a25c0ea1366e06a407a20206bd18a2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/function_docs.py @@ -0,0 +1,10201 @@ +""" +Extended docstrings for functions.py +""" + + +pi = r""" +`\pi`, roughly equal to 3.141592654, represents the area of the unit +circle, the half-period of trigonometric functions, and many other +things in mathematics. + +Mpmath can evaluate `\pi` to arbitrary precision:: + + >>> from mpmath import * + >>> mp.dps = 50; mp.pretty = True + >>> +pi + 3.1415926535897932384626433832795028841971693993751 + +This shows digits 99991-100000 of `\pi` (the last digit is actually +a 4 when the decimal expansion is truncated, but here the nearest +rounding is used):: + + >>> mp.dps = 100000 + >>> str(pi)[-10:] + '5549362465' + +**Possible issues** + +:data:`pi` always rounds to the nearest floating-point +number when used. This means that exact mathematical identities +involving `\pi` will generally not be preserved in floating-point +arithmetic. In particular, multiples of :data:`pi` (except for +the trivial case ``0*pi``) are *not* the exact roots of +:func:`~mpmath.sin`, but differ roughly by the current epsilon:: + + >>> mp.dps = 15 + >>> sin(pi) + 1.22464679914735e-16 + +One solution is to use the :func:`~mpmath.sinpi` function instead:: + + >>> sinpi(1) + 0.0 + +See the documentation of trigonometric functions for additional +details. + +**References** + +* [BorweinBorwein]_ + +""" + +degree = r""" +Represents one degree of angle, `1^{\circ} = \pi/180`, or +about 0.01745329. This constant may be evaluated to arbitrary +precision:: + + >>> from mpmath import * + >>> mp.dps = 50; mp.pretty = True + >>> +degree + 0.017453292519943295769236907684886127134428718885417 + +The :data:`degree` object is convenient for conversion +to radians:: + + >>> sin(30 * degree) + 0.5 + >>> asin(0.5) / degree + 30.0 +""" + +e = r""" +The transcendental number `e` = 2.718281828... is the base of the +natural logarithm (:func:`~mpmath.ln`) and of the exponential function +(:func:`~mpmath.exp`). + +Mpmath can be evaluate `e` to arbitrary precision:: + + >>> from mpmath import * + >>> mp.dps = 50; mp.pretty = True + >>> +e + 2.7182818284590452353602874713526624977572470937 + +This shows digits 99991-100000 of `e` (the last digit is actually +a 5 when the decimal expansion is truncated, but here the nearest +rounding is used):: + + >>> mp.dps = 100000 + >>> str(e)[-10:] + '2100427166' + +**Possible issues** + +:data:`e` always rounds to the nearest floating-point number +when used, and mathematical identities involving `e` may not +hold in floating-point arithmetic. For example, ``ln(e)`` +might not evaluate exactly to 1. + +In particular, don't use ``e**x`` to compute the exponential +function. Use ``exp(x)`` instead; this is both faster and more +accurate. +""" + +phi = r""" +Represents the golden ratio `\phi = (1+\sqrt 5)/2`, +approximately equal to 1.6180339887. To high precision, +its value is:: + + >>> from mpmath import * + >>> mp.dps = 50; mp.pretty = True + >>> +phi + 1.6180339887498948482045868343656381177203091798058 + +Formulas for the golden ratio include the following:: + + >>> (1+sqrt(5))/2 + 1.6180339887498948482045868343656381177203091798058 + >>> findroot(lambda x: x**2-x-1, 1) + 1.6180339887498948482045868343656381177203091798058 + >>> limit(lambda n: fib(n+1)/fib(n), inf) + 1.6180339887498948482045868343656381177203091798058 +""" + +euler = r""" +Euler's constant or the Euler-Mascheroni constant `\gamma` += 0.57721566... is a number of central importance to +number theory and special functions. It is defined as the limit + +.. math :: + + \gamma = \lim_{n\to\infty} H_n - \log n + +where `H_n = 1 + \frac{1}{2} + \ldots + \frac{1}{n}` is a harmonic +number (see :func:`~mpmath.harmonic`). + +Evaluation of `\gamma` is supported at arbitrary precision:: + + >>> from mpmath import * + >>> mp.dps = 50; mp.pretty = True + >>> +euler + 0.57721566490153286060651209008240243104215933593992 + +We can also compute `\gamma` directly from the definition, +although this is less efficient:: + + >>> limit(lambda n: harmonic(n)-log(n), inf) + 0.57721566490153286060651209008240243104215933593992 + +This shows digits 9991-10000 of `\gamma` (the last digit is actually +a 5 when the decimal expansion is truncated, but here the nearest +rounding is used):: + + >>> mp.dps = 10000 + >>> str(euler)[-10:] + '4679858166' + +Integrals, series, and representations for `\gamma` in terms of +special functions include the following (there are many others):: + + >>> mp.dps = 25 + >>> -quad(lambda x: exp(-x)*log(x), [0,inf]) + 0.5772156649015328606065121 + >>> quad(lambda x,y: (x-1)/(1-x*y)/log(x*y), [0,1], [0,1]) + 0.5772156649015328606065121 + >>> nsum(lambda k: 1/k-log(1+1/k), [1,inf]) + 0.5772156649015328606065121 + >>> nsum(lambda k: (-1)**k*zeta(k)/k, [2,inf]) + 0.5772156649015328606065121 + >>> -diff(gamma, 1) + 0.5772156649015328606065121 + >>> limit(lambda x: 1/x-gamma(x), 0) + 0.5772156649015328606065121 + >>> limit(lambda x: zeta(x)-1/(x-1), 1) + 0.5772156649015328606065121 + >>> (log(2*pi*nprod(lambda n: + ... exp(-2+2/n)*(1+2/n)**n, [1,inf]))-3)/2 + 0.5772156649015328606065121 + +For generalizations of the identities `\gamma = -\Gamma'(1)` +and `\gamma = \lim_{x\to1} \zeta(x)-1/(x-1)`, see +:func:`~mpmath.psi` and :func:`~mpmath.stieltjes` respectively. + +**References** + +* [BorweinBailey]_ + +""" + +catalan = r""" +Catalan's constant `K` = 0.91596559... is given by the infinite +series + +.. math :: + + K = \sum_{k=0}^{\infty} \frac{(-1)^k}{(2k+1)^2}. + +Mpmath can evaluate it to arbitrary precision:: + + >>> from mpmath import * + >>> mp.dps = 50; mp.pretty = True + >>> +catalan + 0.91596559417721901505460351493238411077414937428167 + +One can also compute `K` directly from the definition, although +this is significantly less efficient:: + + >>> nsum(lambda k: (-1)**k/(2*k+1)**2, [0, inf]) + 0.91596559417721901505460351493238411077414937428167 + +This shows digits 9991-10000 of `K` (the last digit is actually +a 3 when the decimal expansion is truncated, but here the nearest +rounding is used):: + + >>> mp.dps = 10000 + >>> str(catalan)[-10:] + '9537871504' + +Catalan's constant has numerous integral representations:: + + >>> mp.dps = 50 + >>> quad(lambda x: -log(x)/(1+x**2), [0, 1]) + 0.91596559417721901505460351493238411077414937428167 + >>> quad(lambda x: atan(x)/x, [0, 1]) + 0.91596559417721901505460351493238411077414937428167 + >>> quad(lambda x: ellipk(x**2)/2, [0, 1]) + 0.91596559417721901505460351493238411077414937428167 + >>> quad(lambda x,y: 1/(1+(x*y)**2), [0, 1], [0, 1]) + 0.91596559417721901505460351493238411077414937428167 + +As well as series representations:: + + >>> pi*log(sqrt(3)+2)/8 + 3*nsum(lambda n: + ... (fac(n)/(2*n+1))**2/fac(2*n), [0, inf])/8 + 0.91596559417721901505460351493238411077414937428167 + >>> 1-nsum(lambda n: n*zeta(2*n+1)/16**n, [1,inf]) + 0.91596559417721901505460351493238411077414937428167 +""" + +khinchin = r""" +Khinchin's constant `K` = 2.68542... is a number that +appears in the theory of continued fractions. Mpmath can evaluate +it to arbitrary precision:: + + >>> from mpmath import * + >>> mp.dps = 50; mp.pretty = True + >>> +khinchin + 2.6854520010653064453097148354817956938203822939945 + +An integral representation is:: + + >>> I = quad(lambda x: log((1-x**2)/sincpi(x))/x/(1+x), [0, 1]) + >>> 2*exp(1/log(2)*I) + 2.6854520010653064453097148354817956938203822939945 + +The computation of ``khinchin`` is based on an efficient +implementation of the following series:: + + >>> f = lambda n: (zeta(2*n)-1)/n*sum((-1)**(k+1)/mpf(k) + ... for k in range(1,2*int(n))) + >>> exp(nsum(f, [1,inf])/log(2)) + 2.6854520010653064453097148354817956938203822939945 +""" + +glaisher = r""" +Glaisher's constant `A`, also known as the Glaisher-Kinkelin +constant, is a number approximately equal to 1.282427129 that +sometimes appears in formulas related to gamma and zeta functions. +It is also related to the Barnes G-function (see :func:`~mpmath.barnesg`). + +The constant is defined as `A = \exp(1/12-\zeta'(-1))` where +`\zeta'(s)` denotes the derivative of the Riemann zeta function +(see :func:`~mpmath.zeta`). + +Mpmath can evaluate Glaisher's constant to arbitrary precision: + + >>> from mpmath import * + >>> mp.dps = 50; mp.pretty = True + >>> +glaisher + 1.282427129100622636875342568869791727767688927325 + +We can verify that the value computed by :data:`glaisher` is +correct using mpmath's facilities for numerical +differentiation and arbitrary evaluation of the zeta function: + + >>> exp(mpf(1)/12 - diff(zeta, -1)) + 1.282427129100622636875342568869791727767688927325 + +Here is an example of an integral that can be evaluated in +terms of Glaisher's constant: + + >>> mp.dps = 15 + >>> quad(lambda x: log(gamma(x)), [1, 1.5]) + -0.0428537406502909 + >>> -0.5 - 7*log(2)/24 + log(pi)/4 + 3*log(glaisher)/2 + -0.042853740650291 + +Mpmath computes Glaisher's constant by applying Euler-Maclaurin +summation to a slowly convergent series. The implementation is +reasonably efficient up to about 10,000 digits. See the source +code for additional details. + +References: +http://mathworld.wolfram.com/Glaisher-KinkelinConstant.html +""" + +apery = r""" +Represents Apery's constant, which is the irrational number +approximately equal to 1.2020569 given by + +.. math :: + + \zeta(3) = \sum_{k=1}^\infty\frac{1}{k^3}. + +The calculation is based on an efficient hypergeometric +series. To 50 decimal places, the value is given by:: + + >>> from mpmath import * + >>> mp.dps = 50; mp.pretty = True + >>> +apery + 1.2020569031595942853997381615114499907649862923405 + +Other ways to evaluate Apery's constant using mpmath +include:: + + >>> zeta(3) + 1.2020569031595942853997381615114499907649862923405 + >>> -psi(2,1)/2 + 1.2020569031595942853997381615114499907649862923405 + >>> 8*nsum(lambda k: 1/(2*k+1)**3, [0,inf])/7 + 1.2020569031595942853997381615114499907649862923405 + >>> f = lambda k: 2/k**3/(exp(2*pi*k)-1) + >>> 7*pi**3/180 - nsum(f, [1,inf]) + 1.2020569031595942853997381615114499907649862923405 + +This shows digits 9991-10000 of Apery's constant:: + + >>> mp.dps = 10000 + >>> str(apery)[-10:] + '3189504235' +""" + +mertens = r""" +Represents the Mertens or Meissel-Mertens constant, which is the +prime number analog of Euler's constant: + +.. math :: + + B_1 = \lim_{N\to\infty} + \left(\sum_{p_k \le N} \frac{1}{p_k} - \log \log N \right) + +Here `p_k` denotes the `k`-th prime number. Other names for this +constant include the Hadamard-de la Vallee-Poussin constant or +the prime reciprocal constant. + +The following gives the Mertens constant to 50 digits:: + + >>> from mpmath import * + >>> mp.dps = 50; mp.pretty = True + >>> +mertens + 0.2614972128476427837554268386086958590515666482612 + +References: +http://mathworld.wolfram.com/MertensConstant.html +""" + +twinprime = r""" +Represents the twin prime constant, which is the factor `C_2` +featuring in the Hardy-Littlewood conjecture for the growth of the +twin prime counting function, + +.. math :: + + \pi_2(n) \sim 2 C_2 \frac{n}{\log^2 n}. + +It is given by the product over primes + +.. math :: + + C_2 = \prod_{p\ge3} \frac{p(p-2)}{(p-1)^2} \approx 0.66016 + +Computing `C_2` to 50 digits:: + + >>> from mpmath import * + >>> mp.dps = 50; mp.pretty = True + >>> +twinprime + 0.66016181584686957392781211001455577843262336028473 + +References: +http://mathworld.wolfram.com/TwinPrimesConstant.html +""" + +ln = r""" +Computes the natural logarithm of `x`, `\ln x`. +See :func:`~mpmath.log` for additional documentation.""" + +sqrt = r""" +``sqrt(x)`` gives the principal square root of `x`, `\sqrt x`. +For positive real numbers, the principal root is simply the +positive square root. For arbitrary complex numbers, the principal +square root is defined to satisfy `\sqrt x = \exp(\log(x)/2)`. +The function thus has a branch cut along the negative half real axis. + +For all mpmath numbers ``x``, calling ``sqrt(x)`` is equivalent to +performing ``x**0.5``. + +**Examples** + +Basic examples and limits:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> sqrt(10) + 3.16227766016838 + >>> sqrt(100) + 10.0 + >>> sqrt(-4) + (0.0 + 2.0j) + >>> sqrt(1+1j) + (1.09868411346781 + 0.455089860562227j) + >>> sqrt(inf) + +inf + +Square root evaluation is fast at huge precision:: + + >>> mp.dps = 50000 + >>> a = sqrt(3) + >>> str(a)[-10:] + '9329332815' + +:func:`mpmath.iv.sqrt` supports interval arguments:: + + >>> iv.dps = 15; iv.pretty = True + >>> iv.sqrt([16,100]) + [4.0, 10.0] + >>> iv.sqrt(2) + [1.4142135623730949234, 1.4142135623730951455] + >>> iv.sqrt(2) ** 2 + [1.9999999999999995559, 2.0000000000000004441] + +""" + +cbrt = r""" +``cbrt(x)`` computes the cube root of `x`, `x^{1/3}`. This +function is faster and more accurate than raising to a floating-point +fraction:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> 125**(mpf(1)/3) + mpf('4.9999999999999991') + >>> cbrt(125) + mpf('5.0') + +Every nonzero complex number has three cube roots. This function +returns the cube root defined by `\exp(\log(x)/3)` where the +principal branch of the natural logarithm is used. Note that this +does not give a real cube root for negative real numbers:: + + >>> mp.pretty = True + >>> cbrt(-1) + (0.5 + 0.866025403784439j) +""" + +exp = r""" +Computes the exponential function, + +.. math :: + + \exp(x) = e^x = \sum_{k=0}^{\infty} \frac{x^k}{k!}. + +For complex numbers, the exponential function also satisfies + +.. math :: + + \exp(x+yi) = e^x (\cos y + i \sin y). + +**Basic examples** + +Some values of the exponential function:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> exp(0) + 1.0 + >>> exp(1) + 2.718281828459045235360287 + >>> exp(-1) + 0.3678794411714423215955238 + >>> exp(inf) + +inf + >>> exp(-inf) + 0.0 + +Arguments can be arbitrarily large:: + + >>> exp(10000) + 8.806818225662921587261496e+4342 + >>> exp(-10000) + 1.135483865314736098540939e-4343 + +Evaluation is supported for interval arguments via +:func:`mpmath.iv.exp`:: + + >>> iv.dps = 25; iv.pretty = True + >>> iv.exp([-inf,0]) + [0.0, 1.0] + >>> iv.exp([0,1]) + [1.0, 2.71828182845904523536028749558] + +The exponential function can be evaluated efficiently to arbitrary +precision:: + + >>> mp.dps = 10000 + >>> exp(pi) #doctest: +ELLIPSIS + 23.140692632779269005729...8984304016040616 + +**Functional properties** + +Numerical verification of Euler's identity for the complex +exponential function:: + + >>> mp.dps = 15 + >>> exp(j*pi)+1 + (0.0 + 1.22464679914735e-16j) + >>> chop(exp(j*pi)+1) + 0.0 + +This recovers the coefficients (reciprocal factorials) in the +Maclaurin series expansion of exp:: + + >>> nprint(taylor(exp, 0, 5)) + [1.0, 1.0, 0.5, 0.166667, 0.0416667, 0.00833333] + +The exponential function is its own derivative and antiderivative:: + + >>> exp(pi) + 23.1406926327793 + >>> diff(exp, pi) + 23.1406926327793 + >>> quad(exp, [-inf, pi]) + 23.1406926327793 + +The exponential function can be evaluated using various methods, +including direct summation of the series, limits, and solving +the defining differential equation:: + + >>> nsum(lambda k: pi**k/fac(k), [0,inf]) + 23.1406926327793 + >>> limit(lambda k: (1+pi/k)**k, inf) + 23.1406926327793 + >>> odefun(lambda t, x: x, 0, 1)(pi) + 23.1406926327793 +""" + +cosh = r""" +Computes the hyperbolic cosine of `x`, +`\cosh(x) = (e^x + e^{-x})/2`. Values and limits include:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> cosh(0) + 1.0 + >>> cosh(1) + 1.543080634815243778477906 + >>> cosh(-inf), cosh(+inf) + (+inf, +inf) + +The hyperbolic cosine is an even, convex function with +a global minimum at `x = 0`, having a Maclaurin series +that starts:: + + >>> nprint(chop(taylor(cosh, 0, 5))) + [1.0, 0.0, 0.5, 0.0, 0.0416667, 0.0] + +Generalized to complex numbers, the hyperbolic cosine is +equivalent to a cosine with the argument rotated +in the imaginary direction, or `\cosh x = \cos ix`:: + + >>> cosh(2+3j) + (-3.724545504915322565473971 + 0.5118225699873846088344638j) + >>> cos(3-2j) + (-3.724545504915322565473971 + 0.5118225699873846088344638j) +""" + +sinh = r""" +Computes the hyperbolic sine of `x`, +`\sinh(x) = (e^x - e^{-x})/2`. Values and limits include:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> sinh(0) + 0.0 + >>> sinh(1) + 1.175201193643801456882382 + >>> sinh(-inf), sinh(+inf) + (-inf, +inf) + +The hyperbolic sine is an odd function, with a Maclaurin +series that starts:: + + >>> nprint(chop(taylor(sinh, 0, 5))) + [0.0, 1.0, 0.0, 0.166667, 0.0, 0.00833333] + +Generalized to complex numbers, the hyperbolic sine is +essentially a sine with a rotation `i` applied to +the argument; more precisely, `\sinh x = -i \sin ix`:: + + >>> sinh(2+3j) + (-3.590564589985779952012565 + 0.5309210862485198052670401j) + >>> j*sin(3-2j) + (-3.590564589985779952012565 + 0.5309210862485198052670401j) +""" + +tanh = r""" +Computes the hyperbolic tangent of `x`, +`\tanh(x) = \sinh(x)/\cosh(x)`. Values and limits include:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> tanh(0) + 0.0 + >>> tanh(1) + 0.7615941559557648881194583 + >>> tanh(-inf), tanh(inf) + (-1.0, 1.0) + +The hyperbolic tangent is an odd, sigmoidal function, similar +to the inverse tangent and error function. Its Maclaurin +series is:: + + >>> nprint(chop(taylor(tanh, 0, 5))) + [0.0, 1.0, 0.0, -0.333333, 0.0, 0.133333] + +Generalized to complex numbers, the hyperbolic tangent is +essentially a tangent with a rotation `i` applied to +the argument; more precisely, `\tanh x = -i \tan ix`:: + + >>> tanh(2+3j) + (0.9653858790221331242784803 - 0.009884375038322493720314034j) + >>> j*tan(3-2j) + (0.9653858790221331242784803 - 0.009884375038322493720314034j) +""" + +cos = r""" +Computes the cosine of `x`, `\cos(x)`. + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> cos(pi/3) + 0.5 + >>> cos(100000001) + -0.9802850113244713353133243 + >>> cos(2+3j) + (-4.189625690968807230132555 - 9.109227893755336597979197j) + >>> cos(inf) + nan + >>> nprint(chop(taylor(cos, 0, 6))) + [1.0, 0.0, -0.5, 0.0, 0.0416667, 0.0, -0.00138889] + +Intervals are supported via :func:`mpmath.iv.cos`:: + + >>> iv.dps = 25; iv.pretty = True + >>> iv.cos([0,1]) + [0.540302305868139717400936602301, 1.0] + >>> iv.cos([0,2]) + [-0.41614683654714238699756823214, 1.0] +""" + +sin = r""" +Computes the sine of `x`, `\sin(x)`. + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> sin(pi/3) + 0.8660254037844386467637232 + >>> sin(100000001) + 0.1975887055794968911438743 + >>> sin(2+3j) + (9.1544991469114295734673 - 4.168906959966564350754813j) + >>> sin(inf) + nan + >>> nprint(chop(taylor(sin, 0, 6))) + [0.0, 1.0, 0.0, -0.166667, 0.0, 0.00833333, 0.0] + +Intervals are supported via :func:`mpmath.iv.sin`:: + + >>> iv.dps = 25; iv.pretty = True + >>> iv.sin([0,1]) + [0.0, 0.841470984807896506652502331201] + >>> iv.sin([0,2]) + [0.0, 1.0] +""" + +tan = r""" +Computes the tangent of `x`, `\tan(x) = \frac{\sin(x)}{\cos(x)}`. +The tangent function is singular at `x = (n+1/2)\pi`, but +``tan(x)`` always returns a finite result since `(n+1/2)\pi` +cannot be represented exactly using floating-point arithmetic. + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> tan(pi/3) + 1.732050807568877293527446 + >>> tan(100000001) + -0.2015625081449864533091058 + >>> tan(2+3j) + (-0.003764025641504248292751221 + 1.003238627353609801446359j) + >>> tan(inf) + nan + >>> nprint(chop(taylor(tan, 0, 6))) + [0.0, 1.0, 0.0, 0.333333, 0.0, 0.133333, 0.0] + +Intervals are supported via :func:`mpmath.iv.tan`:: + + >>> iv.dps = 25; iv.pretty = True + >>> iv.tan([0,1]) + [0.0, 1.55740772465490223050697482944] + >>> iv.tan([0,2]) # Interval includes a singularity + [-inf, +inf] +""" + +sec = r""" +Computes the secant of `x`, `\mathrm{sec}(x) = \frac{1}{\cos(x)}`. +The secant function is singular at `x = (n+1/2)\pi`, but +``sec(x)`` always returns a finite result since `(n+1/2)\pi` +cannot be represented exactly using floating-point arithmetic. + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> sec(pi/3) + 2.0 + >>> sec(10000001) + -1.184723164360392819100265 + >>> sec(2+3j) + (-0.04167496441114427004834991 + 0.0906111371962375965296612j) + >>> sec(inf) + nan + >>> nprint(chop(taylor(sec, 0, 6))) + [1.0, 0.0, 0.5, 0.0, 0.208333, 0.0, 0.0847222] + +Intervals are supported via :func:`mpmath.iv.sec`:: + + >>> iv.dps = 25; iv.pretty = True + >>> iv.sec([0,1]) + [1.0, 1.85081571768092561791175326276] + >>> iv.sec([0,2]) # Interval includes a singularity + [-inf, +inf] +""" + +csc = r""" +Computes the cosecant of `x`, `\mathrm{csc}(x) = \frac{1}{\sin(x)}`. +This cosecant function is singular at `x = n \pi`, but with the +exception of the point `x = 0`, ``csc(x)`` returns a finite result +since `n \pi` cannot be represented exactly using floating-point +arithmetic. + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> csc(pi/3) + 1.154700538379251529018298 + >>> csc(10000001) + -1.864910497503629858938891 + >>> csc(2+3j) + (0.09047320975320743980579048 + 0.04120098628857412646300981j) + >>> csc(inf) + nan + +Intervals are supported via :func:`mpmath.iv.csc`:: + + >>> iv.dps = 25; iv.pretty = True + >>> iv.csc([0,1]) # Interval includes a singularity + [1.18839510577812121626159943988, +inf] + >>> iv.csc([0,2]) + [1.0, +inf] +""" + +cot = r""" +Computes the cotangent of `x`, +`\mathrm{cot}(x) = \frac{1}{\tan(x)} = \frac{\cos(x)}{\sin(x)}`. +This cotangent function is singular at `x = n \pi`, but with the +exception of the point `x = 0`, ``cot(x)`` returns a finite result +since `n \pi` cannot be represented exactly using floating-point +arithmetic. + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> cot(pi/3) + 0.5773502691896257645091488 + >>> cot(10000001) + 1.574131876209625656003562 + >>> cot(2+3j) + (-0.003739710376336956660117409 - 0.9967577965693583104609688j) + >>> cot(inf) + nan + +Intervals are supported via :func:`mpmath.iv.cot`:: + + >>> iv.dps = 25; iv.pretty = True + >>> iv.cot([0,1]) # Interval includes a singularity + [0.642092615934330703006419974862, +inf] + >>> iv.cot([1,2]) + [-inf, +inf] +""" + +acos = r""" +Computes the inverse cosine or arccosine of `x`, `\cos^{-1}(x)`. +Since `-1 \le \cos(x) \le 1` for real `x`, the inverse +cosine is real-valued only for `-1 \le x \le 1`. On this interval, +:func:`~mpmath.acos` is defined to be a monotonically decreasing +function assuming values between `+\pi` and `0`. + +Basic values are:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> acos(-1) + 3.141592653589793238462643 + >>> acos(0) + 1.570796326794896619231322 + >>> acos(1) + 0.0 + >>> nprint(chop(taylor(acos, 0, 6))) + [1.5708, -1.0, 0.0, -0.166667, 0.0, -0.075, 0.0] + +:func:`~mpmath.acos` is defined so as to be a proper inverse function of +`\cos(\theta)` for `0 \le \theta < \pi`. +We have `\cos(\cos^{-1}(x)) = x` for all `x`, but +`\cos^{-1}(\cos(x)) = x` only for `0 \le \Re[x] < \pi`:: + + >>> for x in [1, 10, -1, 2+3j, 10+3j]: + ... print("%s %s" % (cos(acos(x)), acos(cos(x)))) + ... + 1.0 1.0 + (10.0 + 0.0j) 2.566370614359172953850574 + -1.0 1.0 + (2.0 + 3.0j) (2.0 + 3.0j) + (10.0 + 3.0j) (2.566370614359172953850574 - 3.0j) + +The inverse cosine has two branch points: `x = \pm 1`. :func:`~mpmath.acos` +places the branch cuts along the line segments `(-\infty, -1)` and +`(+1, +\infty)`. In general, + +.. math :: + + \cos^{-1}(x) = \frac{\pi}{2} + i \log\left(ix + \sqrt{1-x^2} \right) + +where the principal-branch log and square root are implied. +""" + +asin = r""" +Computes the inverse sine or arcsine of `x`, `\sin^{-1}(x)`. +Since `-1 \le \sin(x) \le 1` for real `x`, the inverse +sine is real-valued only for `-1 \le x \le 1`. +On this interval, it is defined to be a monotonically increasing +function assuming values between `-\pi/2` and `\pi/2`. + +Basic values are:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> asin(-1) + -1.570796326794896619231322 + >>> asin(0) + 0.0 + >>> asin(1) + 1.570796326794896619231322 + >>> nprint(chop(taylor(asin, 0, 6))) + [0.0, 1.0, 0.0, 0.166667, 0.0, 0.075, 0.0] + +:func:`~mpmath.asin` is defined so as to be a proper inverse function of +`\sin(\theta)` for `-\pi/2 < \theta < \pi/2`. +We have `\sin(\sin^{-1}(x)) = x` for all `x`, but +`\sin^{-1}(\sin(x)) = x` only for `-\pi/2 < \Re[x] < \pi/2`:: + + >>> for x in [1, 10, -1, 1+3j, -2+3j]: + ... print("%s %s" % (chop(sin(asin(x))), asin(sin(x)))) + ... + 1.0 1.0 + 10.0 -0.5752220392306202846120698 + -1.0 -1.0 + (1.0 + 3.0j) (1.0 + 3.0j) + (-2.0 + 3.0j) (-1.141592653589793238462643 - 3.0j) + +The inverse sine has two branch points: `x = \pm 1`. :func:`~mpmath.asin` +places the branch cuts along the line segments `(-\infty, -1)` and +`(+1, +\infty)`. In general, + +.. math :: + + \sin^{-1}(x) = -i \log\left(ix + \sqrt{1-x^2} \right) + +where the principal-branch log and square root are implied. +""" + +atan = r""" +Computes the inverse tangent or arctangent of `x`, `\tan^{-1}(x)`. +This is a real-valued function for all real `x`, with range +`(-\pi/2, \pi/2)`. + +Basic values are:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> atan(-inf) + -1.570796326794896619231322 + >>> atan(-1) + -0.7853981633974483096156609 + >>> atan(0) + 0.0 + >>> atan(1) + 0.7853981633974483096156609 + >>> atan(inf) + 1.570796326794896619231322 + >>> nprint(chop(taylor(atan, 0, 6))) + [0.0, 1.0, 0.0, -0.333333, 0.0, 0.2, 0.0] + +The inverse tangent is often used to compute angles. However, +the atan2 function is often better for this as it preserves sign +(see :func:`~mpmath.atan2`). + +:func:`~mpmath.atan` is defined so as to be a proper inverse function of +`\tan(\theta)` for `-\pi/2 < \theta < \pi/2`. +We have `\tan(\tan^{-1}(x)) = x` for all `x`, but +`\tan^{-1}(\tan(x)) = x` only for `-\pi/2 < \Re[x] < \pi/2`:: + + >>> mp.dps = 25 + >>> for x in [1, 10, -1, 1+3j, -2+3j]: + ... print("%s %s" % (tan(atan(x)), atan(tan(x)))) + ... + 1.0 1.0 + 10.0 0.5752220392306202846120698 + -1.0 -1.0 + (1.0 + 3.0j) (1.000000000000000000000001 + 3.0j) + (-2.0 + 3.0j) (1.141592653589793238462644 + 3.0j) + +The inverse tangent has two branch points: `x = \pm i`. :func:`~mpmath.atan` +places the branch cuts along the line segments `(-i \infty, -i)` and +`(+i, +i \infty)`. In general, + +.. math :: + + \tan^{-1}(x) = \frac{i}{2}\left(\log(1-ix)-\log(1+ix)\right) + +where the principal-branch log is implied. +""" + +acot = r"""Computes the inverse cotangent of `x`, +`\mathrm{cot}^{-1}(x) = \tan^{-1}(1/x)`.""" + +asec = r"""Computes the inverse secant of `x`, +`\mathrm{sec}^{-1}(x) = \cos^{-1}(1/x)`.""" + +acsc = r"""Computes the inverse cosecant of `x`, +`\mathrm{csc}^{-1}(x) = \sin^{-1}(1/x)`.""" + +coth = r"""Computes the hyperbolic cotangent of `x`, +`\mathrm{coth}(x) = \frac{\cosh(x)}{\sinh(x)}`. +""" + +sech = r"""Computes the hyperbolic secant of `x`, +`\mathrm{sech}(x) = \frac{1}{\cosh(x)}`. +""" + +csch = r"""Computes the hyperbolic cosecant of `x`, +`\mathrm{csch}(x) = \frac{1}{\sinh(x)}`. +""" + +acosh = r"""Computes the inverse hyperbolic cosine of `x`, +`\mathrm{cosh}^{-1}(x) = \log(x+\sqrt{x+1}\sqrt{x-1})`. +""" + +asinh = r"""Computes the inverse hyperbolic sine of `x`, +`\mathrm{sinh}^{-1}(x) = \log(x+\sqrt{1+x^2})`. +""" + +atanh = r"""Computes the inverse hyperbolic tangent of `x`, +`\mathrm{tanh}^{-1}(x) = \frac{1}{2}\left(\log(1+x)-\log(1-x)\right)`. +""" + +acoth = r"""Computes the inverse hyperbolic cotangent of `x`, +`\mathrm{coth}^{-1}(x) = \tanh^{-1}(1/x)`.""" + +asech = r"""Computes the inverse hyperbolic secant of `x`, +`\mathrm{sech}^{-1}(x) = \cosh^{-1}(1/x)`.""" + +acsch = r"""Computes the inverse hyperbolic cosecant of `x`, +`\mathrm{csch}^{-1}(x) = \sinh^{-1}(1/x)`.""" + + + +sinpi = r""" +Computes `\sin(\pi x)`, more accurately than the expression +``sin(pi*x)``:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> sinpi(10**10), sin(pi*(10**10)) + (0.0, -2.23936276195592e-6) + >>> sinpi(10**10+0.5), sin(pi*(10**10+0.5)) + (1.0, 0.999999999998721) +""" + +cospi = r""" +Computes `\cos(\pi x)`, more accurately than the expression +``cos(pi*x)``:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> cospi(10**10), cos(pi*(10**10)) + (1.0, 0.999999999997493) + >>> cospi(10**10+0.5), cos(pi*(10**10+0.5)) + (0.0, 1.59960492420134e-6) +""" + +sinc = r""" +``sinc(x)`` computes the unnormalized sinc function, defined as + +.. math :: + + \mathrm{sinc}(x) = \begin{cases} + \sin(x)/x, & \mbox{if } x \ne 0 \\ + 1, & \mbox{if } x = 0. + \end{cases} + +See :func:`~mpmath.sincpi` for the normalized sinc function. + +Simple values and limits include:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> sinc(0) + 1.0 + >>> sinc(1) + 0.841470984807897 + >>> sinc(inf) + 0.0 + +The integral of the sinc function is the sine integral Si:: + + >>> quad(sinc, [0, 1]) + 0.946083070367183 + >>> si(1) + 0.946083070367183 +""" + +sincpi = r""" +``sincpi(x)`` computes the normalized sinc function, defined as + +.. math :: + + \mathrm{sinc}_{\pi}(x) = \begin{cases} + \sin(\pi x)/(\pi x), & \mbox{if } x \ne 0 \\ + 1, & \mbox{if } x = 0. + \end{cases} + +Equivalently, we have +`\mathrm{sinc}_{\pi}(x) = \mathrm{sinc}(\pi x)`. + +The normalization entails that the function integrates +to unity over the entire real line:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> quadosc(sincpi, [-inf, inf], period=2.0) + 1.0 + +Like, :func:`~mpmath.sinpi`, :func:`~mpmath.sincpi` is evaluated accurately +at its roots:: + + >>> sincpi(10) + 0.0 +""" + +expj = r""" +Convenience function for computing `e^{ix}`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> expj(0) + (1.0 + 0.0j) + >>> expj(-1) + (0.5403023058681397174009366 - 0.8414709848078965066525023j) + >>> expj(j) + (0.3678794411714423215955238 + 0.0j) + >>> expj(1+j) + (0.1987661103464129406288032 + 0.3095598756531121984439128j) +""" + +expjpi = r""" +Convenience function for computing `e^{i \pi x}`. +Evaluation is accurate near zeros (see also :func:`~mpmath.cospi`, +:func:`~mpmath.sinpi`):: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> expjpi(0) + (1.0 + 0.0j) + >>> expjpi(1) + (-1.0 + 0.0j) + >>> expjpi(0.5) + (0.0 + 1.0j) + >>> expjpi(-1) + (-1.0 + 0.0j) + >>> expjpi(j) + (0.04321391826377224977441774 + 0.0j) + >>> expjpi(1+j) + (-0.04321391826377224977441774 + 0.0j) +""" + +floor = r""" +Computes the floor of `x`, `\lfloor x \rfloor`, defined as +the largest integer less than or equal to `x`:: + + >>> from mpmath import * + >>> mp.pretty = False + >>> floor(3.5) + mpf('3.0') + +.. note :: + + :func:`~mpmath.floor`, :func:`~mpmath.ceil` and :func:`~mpmath.nint` return a + floating-point number, not a Python ``int``. If `\lfloor x \rfloor` is + too large to be represented exactly at the present working precision, + the result will be rounded, not necessarily in the direction + implied by the mathematical definition of the function. + +To avoid rounding, use *prec=0*:: + + >>> mp.dps = 15 + >>> print(int(floor(10**30+1))) + 1000000000000000019884624838656 + >>> print(int(floor(10**30+1, prec=0))) + 1000000000000000000000000000001 + +The floor function is defined for complex numbers and +acts on the real and imaginary parts separately:: + + >>> floor(3.25+4.75j) + mpc(real='3.0', imag='4.0') +""" + +ceil = r""" +Computes the ceiling of `x`, `\lceil x \rceil`, defined as +the smallest integer greater than or equal to `x`:: + + >>> from mpmath import * + >>> mp.pretty = False + >>> ceil(3.5) + mpf('4.0') + +The ceiling function is defined for complex numbers and +acts on the real and imaginary parts separately:: + + >>> ceil(3.25+4.75j) + mpc(real='4.0', imag='5.0') + +See notes about rounding for :func:`~mpmath.floor`. +""" + +nint = r""" +Evaluates the nearest integer function, `\mathrm{nint}(x)`. +This gives the nearest integer to `x`; on a tie, it +gives the nearest even integer:: + + >>> from mpmath import * + >>> mp.pretty = False + >>> nint(3.2) + mpf('3.0') + >>> nint(3.8) + mpf('4.0') + >>> nint(3.5) + mpf('4.0') + >>> nint(4.5) + mpf('4.0') + +The nearest integer function is defined for complex numbers and +acts on the real and imaginary parts separately:: + + >>> nint(3.25+4.75j) + mpc(real='3.0', imag='5.0') + +See notes about rounding for :func:`~mpmath.floor`. +""" + +frac = r""" +Gives the fractional part of `x`, defined as +`\mathrm{frac}(x) = x - \lfloor x \rfloor` (see :func:`~mpmath.floor`). +In effect, this computes `x` modulo 1, or `x+n` where +`n \in \mathbb{Z}` is such that `x+n \in [0,1)`:: + + >>> from mpmath import * + >>> mp.pretty = False + >>> frac(1.25) + mpf('0.25') + >>> frac(3) + mpf('0.0') + >>> frac(-1.25) + mpf('0.75') + +For a complex number, the fractional part function applies to +the real and imaginary parts separately:: + + >>> frac(2.25+3.75j) + mpc(real='0.25', imag='0.75') + +Plotted, the fractional part function gives a sawtooth +wave. The Fourier series coefficients have a simple +form:: + + >>> mp.dps = 15 + >>> nprint(fourier(lambda x: frac(x)-0.5, [0,1], 4)) + ([0.0, 0.0, 0.0, 0.0, 0.0], [0.0, -0.31831, -0.159155, -0.106103, -0.0795775]) + >>> nprint([-1/(pi*k) for k in range(1,5)]) + [-0.31831, -0.159155, -0.106103, -0.0795775] + +.. note:: + + The fractional part is sometimes defined as a symmetric + function, i.e. returning `-\mathrm{frac}(-x)` if `x < 0`. + This convention is used, for instance, by Mathematica's + ``FractionalPart``. + +""" + +sign = r""" +Returns the sign of `x`, defined as `\mathrm{sign}(x) = x / |x|` +(with the special case `\mathrm{sign}(0) = 0`):: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> sign(10) + mpf('1.0') + >>> sign(-10) + mpf('-1.0') + >>> sign(0) + mpf('0.0') + +Note that the sign function is also defined for complex numbers, +for which it gives the projection onto the unit circle:: + + >>> mp.dps = 15; mp.pretty = True + >>> sign(1+j) + (0.707106781186547 + 0.707106781186547j) + +""" + +arg = r""" +Computes the complex argument (phase) of `x`, defined as the +signed angle between the positive real axis and `x` in the +complex plane:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> arg(3) + 0.0 + >>> arg(3+3j) + 0.785398163397448 + >>> arg(3j) + 1.5707963267949 + >>> arg(-3) + 3.14159265358979 + >>> arg(-3j) + -1.5707963267949 + +The angle is defined to satisfy `-\pi < \arg(x) \le \pi` and +with the sign convention that a nonnegative imaginary part +results in a nonnegative argument. + +The value returned by :func:`~mpmath.arg` is an ``mpf`` instance. +""" + +fabs = r""" +Returns the absolute value of `x`, `|x|`. Unlike :func:`abs`, +:func:`~mpmath.fabs` converts non-mpmath numbers (such as ``int``) +into mpmath numbers:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> fabs(3) + mpf('3.0') + >>> fabs(-3) + mpf('3.0') + >>> fabs(3+4j) + mpf('5.0') +""" + +re = r""" +Returns the real part of `x`, `\Re(x)`. :func:`~mpmath.re` +converts a non-mpmath number to an mpmath number:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> re(3) + mpf('3.0') + >>> re(-1+4j) + mpf('-1.0') +""" + +im = r""" +Returns the imaginary part of `x`, `\Im(x)`. :func:`~mpmath.im` +converts a non-mpmath number to an mpmath number:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> im(3) + mpf('0.0') + >>> im(-1+4j) + mpf('4.0') +""" + +conj = r""" +Returns the complex conjugate of `x`, `\overline{x}`. Unlike +``x.conjugate()``, :func:`~mpmath.im` converts `x` to a mpmath number:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> conj(3) + mpf('3.0') + >>> conj(-1+4j) + mpc(real='-1.0', imag='-4.0') +""" + +polar = r""" +Returns the polar representation of the complex number `z` +as a pair `(r, \phi)` such that `z = r e^{i \phi}`:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> polar(-2) + (2.0, 3.14159265358979) + >>> polar(3-4j) + (5.0, -0.927295218001612) +""" + +rect = r""" +Returns the complex number represented by polar +coordinates `(r, \phi)`:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> chop(rect(2, pi)) + -2.0 + >>> rect(sqrt(2), -pi/4) + (1.0 - 1.0j) +""" + +expm1 = r""" +Computes `e^x - 1`, accurately for small `x`. + +Unlike the expression ``exp(x) - 1``, ``expm1(x)`` does not suffer from +potentially catastrophic cancellation:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> exp(1e-10)-1; print(expm1(1e-10)) + 1.00000008274037e-10 + 1.00000000005e-10 + >>> exp(1e-20)-1; print(expm1(1e-20)) + 0.0 + 1.0e-20 + >>> 1/(exp(1e-20)-1) + Traceback (most recent call last): + ... + ZeroDivisionError + >>> 1/expm1(1e-20) + 1.0e+20 + +Evaluation works for extremely tiny values:: + + >>> expm1(0) + 0.0 + >>> expm1('1e-10000000') + 1.0e-10000000 + +""" + +log1p = r""" +Computes `\log(1+x)`, accurately for small `x`. + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> log(1+1e-10); print(mp.log1p(1e-10)) + 1.00000008269037e-10 + 9.9999999995e-11 + >>> mp.log1p(1e-100j) + (5.0e-201 + 1.0e-100j) + >>> mp.log1p(0) + 0.0 + +""" + + +powm1 = r""" +Computes `x^y - 1`, accurately when `x^y` is very close to 1. + +This avoids potentially catastrophic cancellation:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> power(0.99999995, 1e-10) - 1 + 0.0 + >>> powm1(0.99999995, 1e-10) + -5.00000012791934e-18 + +Powers exactly equal to 1, and only those powers, yield 0 exactly:: + + >>> powm1(-j, 4) + (0.0 + 0.0j) + >>> powm1(3, 0) + 0.0 + >>> powm1(fadd(-1, 1e-100, exact=True), 4) + -4.0e-100 + +Evaluation works for extremely tiny `y`:: + + >>> powm1(2, '1e-100000') + 6.93147180559945e-100001 + >>> powm1(j, '1e-1000') + (-1.23370055013617e-2000 + 1.5707963267949e-1000j) + +""" + +root = r""" +``root(z, n, k=0)`` computes an `n`-th root of `z`, i.e. returns a number +`r` that (up to possible approximation error) satisfies `r^n = z`. +(``nthroot`` is available as an alias for ``root``.) + +Every complex number `z \ne 0` has `n` distinct `n`-th roots, which are +equidistant points on a circle with radius `|z|^{1/n}`, centered around the +origin. A specific root may be selected using the optional index +`k`. The roots are indexed counterclockwise, starting with `k = 0` for the root +closest to the positive real half-axis. + +The `k = 0` root is the so-called principal `n`-th root, often denoted by +`\sqrt[n]{z}` or `z^{1/n}`, and also given by `\exp(\log(z) / n)`. If `z` is +a positive real number, the principal root is just the unique positive +`n`-th root of `z`. Under some circumstances, non-principal real roots exist: +for positive real `z`, `n` even, there is a negative root given by `k = n/2`; +for negative real `z`, `n` odd, there is a negative root given by `k = (n-1)/2`. + +To obtain all roots with a simple expression, use +``[root(z,n,k) for k in range(n)]``. + +An important special case, ``root(1, n, k)`` returns the `k`-th `n`-th root of +unity, `\zeta_k = e^{2 \pi i k / n}`. Alternatively, :func:`~mpmath.unitroots` +provides a slightly more convenient way to obtain the roots of unity, +including the option to compute only the primitive roots of unity. + +Both `k` and `n` should be integers; `k` outside of ``range(n)`` will be +reduced modulo `n`. If `n` is negative, `x^{-1/n} = 1/x^{1/n}` (or +the equivalent reciprocal for a non-principal root with `k \ne 0`) is computed. + +:func:`~mpmath.root` is implemented to use Newton's method for small +`n`. At high precision, this makes `x^{1/n}` not much more +expensive than the regular exponentiation, `x^n`. For very large +`n`, :func:`~mpmath.nthroot` falls back to use the exponential function. + +**Examples** + +:func:`~mpmath.nthroot`/:func:`~mpmath.root` is faster and more accurate than raising to a +floating-point fraction:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> 16807 ** (mpf(1)/5) + mpf('7.0000000000000009') + >>> root(16807, 5) + mpf('7.0') + >>> nthroot(16807, 5) # Alias + mpf('7.0') + +A high-precision root:: + + >>> mp.dps = 50; mp.pretty = True + >>> nthroot(10, 5) + 1.584893192461113485202101373391507013269442133825 + >>> nthroot(10, 5) ** 5 + 10.0 + +Computing principal and non-principal square and cube roots:: + + >>> mp.dps = 15 + >>> root(10, 2) + 3.16227766016838 + >>> root(10, 2, 1) + -3.16227766016838 + >>> root(-10, 3) + (1.07721734501594 + 1.86579517236206j) + >>> root(-10, 3, 1) + -2.15443469003188 + >>> root(-10, 3, 2) + (1.07721734501594 - 1.86579517236206j) + +All the 7th roots of a complex number:: + + >>> for r in [root(3+4j, 7, k) for k in range(7)]: + ... print("%s %s" % (r, r**7)) + ... + (1.24747270589553 + 0.166227124177353j) (3.0 + 4.0j) + (0.647824911301003 + 1.07895435170559j) (3.0 + 4.0j) + (-0.439648254723098 + 1.17920694574172j) (3.0 + 4.0j) + (-1.19605731775069 + 0.391492658196305j) (3.0 + 4.0j) + (-1.05181082538903 - 0.691023585965793j) (3.0 + 4.0j) + (-0.115529328478668 - 1.25318497558335j) (3.0 + 4.0j) + (0.907748109144957 - 0.871672518271819j) (3.0 + 4.0j) + +Cube roots of unity:: + + >>> for k in range(3): print(root(1, 3, k)) + ... + 1.0 + (-0.5 + 0.866025403784439j) + (-0.5 - 0.866025403784439j) + +Some exact high order roots:: + + >>> root(75**210, 105) + 5625.0 + >>> root(1, 128, 96) + (0.0 - 1.0j) + >>> root(4**128, 128, 96) + (0.0 - 4.0j) + +""" + +unitroots = r""" +``unitroots(n)`` returns `\zeta_0, \zeta_1, \ldots, \zeta_{n-1}`, +all the distinct `n`-th roots of unity, as a list. If the option +*primitive=True* is passed, only the primitive roots are returned. + +Every `n`-th root of unity satisfies `(\zeta_k)^n = 1`. There are `n` distinct +roots for each `n` (`\zeta_k` and `\zeta_j` are the same when +`k = j \pmod n`), which form a regular polygon with vertices on the unit +circle. They are ordered counterclockwise with increasing `k`, starting +with `\zeta_0 = 1`. + +**Examples** + +The roots of unity up to `n = 4`:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> nprint(unitroots(1)) + [1.0] + >>> nprint(unitroots(2)) + [1.0, -1.0] + >>> nprint(unitroots(3)) + [1.0, (-0.5 + 0.866025j), (-0.5 - 0.866025j)] + >>> nprint(unitroots(4)) + [1.0, (0.0 + 1.0j), -1.0, (0.0 - 1.0j)] + +Roots of unity form a geometric series that sums to 0:: + + >>> mp.dps = 50 + >>> chop(fsum(unitroots(25))) + 0.0 + +Primitive roots up to `n = 4`:: + + >>> mp.dps = 15 + >>> nprint(unitroots(1, primitive=True)) + [1.0] + >>> nprint(unitroots(2, primitive=True)) + [-1.0] + >>> nprint(unitroots(3, primitive=True)) + [(-0.5 + 0.866025j), (-0.5 - 0.866025j)] + >>> nprint(unitroots(4, primitive=True)) + [(0.0 + 1.0j), (0.0 - 1.0j)] + +There are only four primitive 12th roots:: + + >>> nprint(unitroots(12, primitive=True)) + [(0.866025 + 0.5j), (-0.866025 + 0.5j), (-0.866025 - 0.5j), (0.866025 - 0.5j)] + +The `n`-th roots of unity form a group, the cyclic group of order `n`. +Any primitive root `r` is a generator for this group, meaning that +`r^0, r^1, \ldots, r^{n-1}` gives the whole set of unit roots (in +some permuted order):: + + >>> for r in unitroots(6): print(r) + ... + 1.0 + (0.5 + 0.866025403784439j) + (-0.5 + 0.866025403784439j) + -1.0 + (-0.5 - 0.866025403784439j) + (0.5 - 0.866025403784439j) + >>> r = unitroots(6, primitive=True)[1] + >>> for k in range(6): print(chop(r**k)) + ... + 1.0 + (0.5 - 0.866025403784439j) + (-0.5 - 0.866025403784439j) + -1.0 + (-0.5 + 0.866025403784438j) + (0.5 + 0.866025403784438j) + +The number of primitive roots equals the Euler totient function `\phi(n)`:: + + >>> [len(unitroots(n, primitive=True)) for n in range(1,20)] + [1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16, 6, 18] + +""" + + +log = r""" +Computes the base-`b` logarithm of `x`, `\log_b(x)`. If `b` is +unspecified, :func:`~mpmath.log` computes the natural (base `e`) logarithm +and is equivalent to :func:`~mpmath.ln`. In general, the base `b` logarithm +is defined in terms of the natural logarithm as +`\log_b(x) = \ln(x)/\ln(b)`. + +By convention, we take `\log(0) = -\infty`. + +The natural logarithm is real if `x > 0` and complex if `x < 0` or if +`x` is complex. The principal branch of the complex logarithm is +used, meaning that `\Im(\ln(x)) = -\pi < \arg(x) \le \pi`. + +**Examples** + +Some basic values and limits:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> log(1) + 0.0 + >>> log(2) + 0.693147180559945 + >>> log(1000,10) + 3.0 + >>> log(4, 16) + 0.5 + >>> log(j) + (0.0 + 1.5707963267949j) + >>> log(-1) + (0.0 + 3.14159265358979j) + >>> log(0) + -inf + >>> log(inf) + +inf + +The natural logarithm is the antiderivative of `1/x`:: + + >>> quad(lambda x: 1/x, [1, 5]) + 1.6094379124341 + >>> log(5) + 1.6094379124341 + >>> diff(log, 10) + 0.1 + +The Taylor series expansion of the natural logarithm around +`x = 1` has coefficients `(-1)^{n+1}/n`:: + + >>> nprint(taylor(log, 1, 7)) + [0.0, 1.0, -0.5, 0.333333, -0.25, 0.2, -0.166667, 0.142857] + +:func:`~mpmath.log` supports arbitrary precision evaluation:: + + >>> mp.dps = 50 + >>> log(pi) + 1.1447298858494001741434273513530587116472948129153 + >>> log(pi, pi**3) + 0.33333333333333333333333333333333333333333333333333 + >>> mp.dps = 25 + >>> log(3+4j) + (1.609437912434100374600759 + 0.9272952180016122324285125j) +""" + +log10 = r""" +Computes the base-10 logarithm of `x`, `\log_{10}(x)`. ``log10(x)`` +is equivalent to ``log(x, 10)``. +""" + +fmod = r""" +Converts `x` and `y` to mpmath numbers and returns `x \mod y`. +For mpmath numbers, this is equivalent to ``x % y``. + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> fmod(100, pi) + 2.61062773871641 + +You can use :func:`~mpmath.fmod` to compute fractional parts of numbers:: + + >>> fmod(10.25, 1) + 0.25 + +""" + +radians = r""" +Converts the degree angle `x` to radians:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> radians(60) + 1.0471975511966 +""" + +degrees = r""" +Converts the radian angle `x` to a degree angle:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> degrees(pi/3) + 60.0 +""" + +atan2 = r""" +Computes the two-argument arctangent, `\mathrm{atan2}(y, x)`, +giving the signed angle between the positive `x`-axis and the +point `(x, y)` in the 2D plane. This function is defined for +real `x` and `y` only. + +The two-argument arctangent essentially computes +`\mathrm{atan}(y/x)`, but accounts for the signs of both +`x` and `y` to give the angle for the correct quadrant. The +following examples illustrate the difference:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> atan2(1,1), atan(1/1.) + (0.785398163397448, 0.785398163397448) + >>> atan2(1,-1), atan(1/-1.) + (2.35619449019234, -0.785398163397448) + >>> atan2(-1,1), atan(-1/1.) + (-0.785398163397448, -0.785398163397448) + >>> atan2(-1,-1), atan(-1/-1.) + (-2.35619449019234, 0.785398163397448) + +The angle convention is the same as that used for the complex +argument; see :func:`~mpmath.arg`. +""" + +fibonacci = r""" +``fibonacci(n)`` computes the `n`-th Fibonacci number, `F(n)`. The +Fibonacci numbers are defined by the recurrence `F(n) = F(n-1) + F(n-2)` +with the initial values `F(0) = 0`, `F(1) = 1`. :func:`~mpmath.fibonacci` +extends this definition to arbitrary real and complex arguments +using the formula + +.. math :: + + F(z) = \frac{\phi^z - \cos(\pi z) \phi^{-z}}{\sqrt 5} + +where `\phi` is the golden ratio. :func:`~mpmath.fibonacci` also uses this +continuous formula to compute `F(n)` for extremely large `n`, where +calculating the exact integer would be wasteful. + +For convenience, :func:`~mpmath.fib` is available as an alias for +:func:`~mpmath.fibonacci`. + +**Basic examples** + +Some small Fibonacci numbers are:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> for i in range(10): + ... print(fibonacci(i)) + ... + 0.0 + 1.0 + 1.0 + 2.0 + 3.0 + 5.0 + 8.0 + 13.0 + 21.0 + 34.0 + >>> fibonacci(50) + 12586269025.0 + +The recurrence for `F(n)` extends backwards to negative `n`:: + + >>> for i in range(10): + ... print(fibonacci(-i)) + ... + 0.0 + 1.0 + -1.0 + 2.0 + -3.0 + 5.0 + -8.0 + 13.0 + -21.0 + 34.0 + +Large Fibonacci numbers will be computed approximately unless +the precision is set high enough:: + + >>> fib(200) + 2.8057117299251e+41 + >>> mp.dps = 45 + >>> fib(200) + 280571172992510140037611932413038677189525.0 + +:func:`~mpmath.fibonacci` can compute approximate Fibonacci numbers +of stupendous size:: + + >>> mp.dps = 15 + >>> fibonacci(10**25) + 3.49052338550226e+2089876402499787337692720 + +**Real and complex arguments** + +The extended Fibonacci function is an analytic function. The +property `F(z) = F(z-1) + F(z-2)` holds for arbitrary `z`:: + + >>> mp.dps = 15 + >>> fib(pi) + 2.1170270579161 + >>> fib(pi-1) + fib(pi-2) + 2.1170270579161 + >>> fib(3+4j) + (-5248.51130728372 - 14195.962288353j) + >>> fib(2+4j) + fib(1+4j) + (-5248.51130728372 - 14195.962288353j) + +The Fibonacci function has infinitely many roots on the +negative half-real axis. The first root is at 0, the second is +close to -0.18, and then there are infinitely many roots that +asymptotically approach `-n+1/2`:: + + >>> findroot(fib, -0.2) + -0.183802359692956 + >>> findroot(fib, -2) + -1.57077646820395 + >>> findroot(fib, -17) + -16.4999999596115 + >>> findroot(fib, -24) + -23.5000000000479 + +**Mathematical relationships** + +For large `n`, `F(n+1)/F(n)` approaches the golden ratio:: + + >>> mp.dps = 50 + >>> fibonacci(101)/fibonacci(100) + 1.6180339887498948482045868343656381177203127439638 + >>> +phi + 1.6180339887498948482045868343656381177203091798058 + +The sum of reciprocal Fibonacci numbers converges to an irrational +number for which no closed form expression is known:: + + >>> mp.dps = 15 + >>> nsum(lambda n: 1/fib(n), [1, inf]) + 3.35988566624318 + +Amazingly, however, the sum of odd-index reciprocal Fibonacci +numbers can be expressed in terms of a Jacobi theta function:: + + >>> nsum(lambda n: 1/fib(2*n+1), [0, inf]) + 1.82451515740692 + >>> sqrt(5)*jtheta(2,0,(3-sqrt(5))/2)**2/4 + 1.82451515740692 + +Some related sums can be done in closed form:: + + >>> nsum(lambda k: 1/(1+fib(2*k+1)), [0, inf]) + 1.11803398874989 + >>> phi - 0.5 + 1.11803398874989 + >>> f = lambda k:(-1)**(k+1) / sum(fib(n)**2 for n in range(1,int(k+1))) + >>> nsum(f, [1, inf]) + 0.618033988749895 + >>> phi-1 + 0.618033988749895 + +**References** + +1. http://mathworld.wolfram.com/FibonacciNumber.html +""" + +altzeta = r""" +Gives the Dirichlet eta function, `\eta(s)`, also known as the +alternating zeta function. This function is defined in analogy +with the Riemann zeta function as providing the sum of the +alternating series + +.. math :: + + \eta(s) = \sum_{k=0}^{\infty} \frac{(-1)^k}{k^s} + = 1-\frac{1}{2^s}+\frac{1}{3^s}-\frac{1}{4^s}+\ldots + +The eta function, unlike the Riemann zeta function, is an entire +function, having a finite value for all complex `s`. The special case +`\eta(1) = \log(2)` gives the value of the alternating harmonic series. + +The alternating zeta function may expressed using the Riemann zeta function +as `\eta(s) = (1 - 2^{1-s}) \zeta(s)`. It can also be expressed +in terms of the Hurwitz zeta function, for example using +:func:`~mpmath.dirichlet` (see documentation for that function). + +**Examples** + +Some special values are:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> altzeta(1) + 0.693147180559945 + >>> altzeta(0) + 0.5 + >>> altzeta(-1) + 0.25 + >>> altzeta(-2) + 0.0 + +An example of a sum that can be computed more accurately and +efficiently via :func:`~mpmath.altzeta` than via numerical summation:: + + >>> sum(-(-1)**n / mpf(n)**2.5 for n in range(1, 100)) + 0.867204951503984 + >>> altzeta(2.5) + 0.867199889012184 + +At positive even integers, the Dirichlet eta function +evaluates to a rational multiple of a power of `\pi`:: + + >>> altzeta(2) + 0.822467033424113 + >>> pi**2/12 + 0.822467033424113 + +Like the Riemann zeta function, `\eta(s)`, approaches 1 +as `s` approaches positive infinity, although it does +so from below rather than from above:: + + >>> altzeta(30) + 0.999999999068682 + >>> altzeta(inf) + 1.0 + >>> mp.pretty = False + >>> altzeta(1000, rounding='d') + mpf('0.99999999999999989') + >>> altzeta(1000, rounding='u') + mpf('1.0') + +**References** + +1. http://mathworld.wolfram.com/DirichletEtaFunction.html + +2. http://en.wikipedia.org/wiki/Dirichlet_eta_function +""" + +factorial = r""" +Computes the factorial, `x!`. For integers `n \ge 0`, we have +`n! = 1 \cdot 2 \cdots (n-1) \cdot n` and more generally the factorial +is defined for real or complex `x` by `x! = \Gamma(x+1)`. + +**Examples** + +Basic values and limits:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> for k in range(6): + ... print("%s %s" % (k, fac(k))) + ... + 0 1.0 + 1 1.0 + 2 2.0 + 3 6.0 + 4 24.0 + 5 120.0 + >>> fac(inf) + +inf + >>> fac(0.5), sqrt(pi)/2 + (0.886226925452758, 0.886226925452758) + +For large positive `x`, `x!` can be approximated by +Stirling's formula:: + + >>> x = 10**10 + >>> fac(x) + 2.32579620567308e+95657055186 + >>> sqrt(2*pi*x)*(x/e)**x + 2.32579597597705e+95657055186 + +:func:`~mpmath.fac` supports evaluation for astronomically large values:: + + >>> fac(10**30) + 6.22311232304258e+29565705518096748172348871081098 + +Reciprocal factorials appear in the Taylor series of the +exponential function (among many other contexts):: + + >>> nsum(lambda k: 1/fac(k), [0, inf]), exp(1) + (2.71828182845905, 2.71828182845905) + >>> nsum(lambda k: pi**k/fac(k), [0, inf]), exp(pi) + (23.1406926327793, 23.1406926327793) + +""" + +gamma = r""" +Computes the gamma function, `\Gamma(x)`. The gamma function is a +shifted version of the ordinary factorial, satisfying +`\Gamma(n) = (n-1)!` for integers `n > 0`. More generally, it +is defined by + +.. math :: + + \Gamma(x) = \int_0^{\infty} t^{x-1} e^{-t}\, dt + +for any real or complex `x` with `\Re(x) > 0` and for `\Re(x) < 0` +by analytic continuation. + +**Examples** + +Basic values and limits:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> for k in range(1, 6): + ... print("%s %s" % (k, gamma(k))) + ... + 1 1.0 + 2 1.0 + 3 2.0 + 4 6.0 + 5 24.0 + >>> gamma(inf) + +inf + >>> gamma(0) + Traceback (most recent call last): + ... + ValueError: gamma function pole + +The gamma function of a half-integer is a rational multiple of +`\sqrt{\pi}`:: + + >>> gamma(0.5), sqrt(pi) + (1.77245385090552, 1.77245385090552) + >>> gamma(1.5), sqrt(pi)/2 + (0.886226925452758, 0.886226925452758) + +We can check the integral definition:: + + >>> gamma(3.5) + 3.32335097044784 + >>> quad(lambda t: t**2.5*exp(-t), [0,inf]) + 3.32335097044784 + +:func:`~mpmath.gamma` supports arbitrary-precision evaluation and +complex arguments:: + + >>> mp.dps = 50 + >>> gamma(sqrt(3)) + 0.91510229697308632046045539308226554038315280564184 + >>> mp.dps = 25 + >>> gamma(2j) + (0.009902440080927490985955066 - 0.07595200133501806872408048j) + +Arguments can also be large. Note that the gamma function grows +very quickly:: + + >>> mp.dps = 15 + >>> gamma(10**20) + 1.9328495143101e+1956570551809674817225 + +**References** + +* [Spouge]_ + +""" + +psi = r""" +Gives the polygamma function of order `m` of `z`, `\psi^{(m)}(z)`. +Special cases are known as the *digamma function* (`\psi^{(0)}(z)`), +the *trigamma function* (`\psi^{(1)}(z)`), etc. The polygamma +functions are defined as the logarithmic derivatives of the gamma +function: + +.. math :: + + \psi^{(m)}(z) = \left(\frac{d}{dz}\right)^{m+1} \log \Gamma(z) + +In particular, `\psi^{(0)}(z) = \Gamma'(z)/\Gamma(z)`. In the +present implementation of :func:`~mpmath.psi`, the order `m` must be a +nonnegative integer, while the argument `z` may be an arbitrary +complex number (with exception for the polygamma function's poles +at `z = 0, -1, -2, \ldots`). + +**Examples** + +For various rational arguments, the polygamma function reduces to +a combination of standard mathematical constants:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> psi(0, 1), -euler + (-0.5772156649015328606065121, -0.5772156649015328606065121) + >>> psi(1, '1/4'), pi**2+8*catalan + (17.19732915450711073927132, 17.19732915450711073927132) + >>> psi(2, '1/2'), -14*apery + (-16.82879664423431999559633, -16.82879664423431999559633) + +The polygamma functions are derivatives of each other:: + + >>> diff(lambda x: psi(3, x), pi), psi(4, pi) + (-0.1105749312578862734526952, -0.1105749312578862734526952) + >>> quad(lambda x: psi(4, x), [2, 3]), psi(3,3)-psi(3,2) + (-0.375, -0.375) + +The digamma function diverges logarithmically as `z \to \infty`, +while higher orders tend to zero:: + + >>> psi(0,inf), psi(1,inf), psi(2,inf) + (+inf, 0.0, 0.0) + +Evaluation for a complex argument:: + + >>> psi(2, -1-2j) + (0.03902435405364952654838445 + 0.1574325240413029954685366j) + +Evaluation is supported for large orders `m` and/or large +arguments `z`:: + + >>> psi(3, 10**100) + 2.0e-300 + >>> psi(250, 10**30+10**20*j) + (-1.293142504363642687204865e-7010 + 3.232856260909107391513108e-7018j) + +**Application to infinite series** + +Any infinite series where the summand is a rational function of +the index `k` can be evaluated in closed form in terms of polygamma +functions of the roots and poles of the summand:: + + >>> a = sqrt(2) + >>> b = sqrt(3) + >>> nsum(lambda k: 1/((k+a)**2*(k+b)), [0, inf]) + 0.4049668927517857061917531 + >>> (psi(0,a)-psi(0,b)-a*psi(1,a)+b*psi(1,a))/(a-b)**2 + 0.4049668927517857061917531 + +This follows from the series representation (`m > 0`) + +.. math :: + + \psi^{(m)}(z) = (-1)^{m+1} m! \sum_{k=0}^{\infty} + \frac{1}{(z+k)^{m+1}}. + +Since the roots of a polynomial may be complex, it is sometimes +necessary to use the complex polygamma function to evaluate +an entirely real-valued sum:: + + >>> nsum(lambda k: 1/(k**2-2*k+3), [0, inf]) + 1.694361433907061256154665 + >>> nprint(polyroots([1,-2,3])) + [(1.0 - 1.41421j), (1.0 + 1.41421j)] + >>> r1 = 1-sqrt(2)*j + >>> r2 = r1.conjugate() + >>> (psi(0,-r2)-psi(0,-r1))/(r1-r2) + (1.694361433907061256154665 + 0.0j) + +""" + +digamma = r""" +Shortcut for ``psi(0,z)``. +""" + +harmonic = r""" +If `n` is an integer, ``harmonic(n)`` gives a floating-point +approximation of the `n`-th harmonic number `H(n)`, defined as + +.. math :: + + H(n) = 1 + \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n} + +The first few harmonic numbers are:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> for n in range(8): + ... print("%s %s" % (n, harmonic(n))) + ... + 0 0.0 + 1 1.0 + 2 1.5 + 3 1.83333333333333 + 4 2.08333333333333 + 5 2.28333333333333 + 6 2.45 + 7 2.59285714285714 + +The infinite harmonic series `1 + 1/2 + 1/3 + \ldots` diverges:: + + >>> harmonic(inf) + +inf + +:func:`~mpmath.harmonic` is evaluated using the digamma function rather +than by summing the harmonic series term by term. It can therefore +be computed quickly for arbitrarily large `n`, and even for +nonintegral arguments:: + + >>> harmonic(10**100) + 230.835724964306 + >>> harmonic(0.5) + 0.613705638880109 + >>> harmonic(3+4j) + (2.24757548223494 + 0.850502209186044j) + +:func:`~mpmath.harmonic` supports arbitrary precision evaluation:: + + >>> mp.dps = 50 + >>> harmonic(11) + 3.0198773448773448773448773448773448773448773448773 + >>> harmonic(pi) + 1.8727388590273302654363491032336134987519132374152 + +The harmonic series diverges, but at a glacial pace. It is possible +to calculate the exact number of terms required before the sum +exceeds a given amount, say 100:: + + >>> mp.dps = 50 + >>> v = 10**findroot(lambda x: harmonic(10**x) - 100, 10) + >>> v + 15092688622113788323693563264538101449859496.864101 + >>> v = int(ceil(v)) + >>> print(v) + 15092688622113788323693563264538101449859497 + >>> harmonic(v-1) + 99.999999999999999999999999999999999999999999942747 + >>> harmonic(v) + 100.000000000000000000000000000000000000000000009 + +""" + +bernoulli = r""" +Computes the nth Bernoulli number, `B_n`, for any integer `n \ge 0`. + +The Bernoulli numbers are rational numbers, but this function +returns a floating-point approximation. To obtain an exact +fraction, use :func:`~mpmath.bernfrac` instead. + +**Examples** + +Numerical values of the first few Bernoulli numbers:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> for n in range(15): + ... print("%s %s" % (n, bernoulli(n))) + ... + 0 1.0 + 1 -0.5 + 2 0.166666666666667 + 3 0.0 + 4 -0.0333333333333333 + 5 0.0 + 6 0.0238095238095238 + 7 0.0 + 8 -0.0333333333333333 + 9 0.0 + 10 0.0757575757575758 + 11 0.0 + 12 -0.253113553113553 + 13 0.0 + 14 1.16666666666667 + +Bernoulli numbers can be approximated with arbitrary precision:: + + >>> mp.dps = 50 + >>> bernoulli(100) + -2.8382249570693706959264156336481764738284680928013e+78 + +Arbitrarily large `n` are supported:: + + >>> mp.dps = 15 + >>> bernoulli(10**20 + 2) + 3.09136296657021e+1876752564973863312327 + +The Bernoulli numbers are related to the Riemann zeta function +at integer arguments:: + + >>> -bernoulli(8) * (2*pi)**8 / (2*fac(8)) + 1.00407735619794 + >>> zeta(8) + 1.00407735619794 + +**Algorithm** + +For small `n` (`n < 3000`) :func:`~mpmath.bernoulli` uses a recurrence +formula due to Ramanujan. All results in this range are cached, +so sequential computation of small Bernoulli numbers is +guaranteed to be fast. + +For larger `n`, `B_n` is evaluated in terms of the Riemann zeta +function. +""" + +stieltjes = r""" +For a nonnegative integer `n`, ``stieltjes(n)`` computes the +`n`-th Stieltjes constant `\gamma_n`, defined as the +`n`-th coefficient in the Laurent series expansion of the +Riemann zeta function around the pole at `s = 1`. That is, +we have: + +.. math :: + + \zeta(s) = \frac{1}{s-1} \sum_{n=0}^{\infty} + \frac{(-1)^n}{n!} \gamma_n (s-1)^n + +More generally, ``stieltjes(n, a)`` gives the corresponding +coefficient `\gamma_n(a)` for the Hurwitz zeta function +`\zeta(s,a)` (with `\gamma_n = \gamma_n(1)`). + +**Examples** + +The zeroth Stieltjes constant is just Euler's constant `\gamma`:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> stieltjes(0) + 0.577215664901533 + +Some more values are:: + + >>> stieltjes(1) + -0.0728158454836767 + >>> stieltjes(10) + 0.000205332814909065 + >>> stieltjes(30) + 0.00355772885557316 + >>> stieltjes(1000) + -1.57095384420474e+486 + >>> stieltjes(2000) + 2.680424678918e+1109 + >>> stieltjes(1, 2.5) + -0.23747539175716 + +An alternative way to compute `\gamma_1`:: + + >>> diff(extradps(15)(lambda x: 1/(x-1) - zeta(x)), 1) + -0.0728158454836767 + +:func:`~mpmath.stieltjes` supports arbitrary precision evaluation:: + + >>> mp.dps = 50 + >>> stieltjes(2) + -0.0096903631928723184845303860352125293590658061013408 + +**Algorithm** + +:func:`~mpmath.stieltjes` numerically evaluates the integral in +the following representation due to Ainsworth, Howell and +Coffey [1], [2]: + +.. math :: + + \gamma_n(a) = \frac{\log^n a}{2a} - \frac{\log^{n+1}(a)}{n+1} + + \frac{2}{a} \Re \int_0^{\infty} + \frac{(x/a-i)\log^n(a-ix)}{(1+x^2/a^2)(e^{2\pi x}-1)} dx. + +For some reference values with `a = 1`, see e.g. [4]. + +**References** + +1. O. R. Ainsworth & L. W. Howell, "An integral representation of + the generalized Euler-Mascheroni constants", NASA Technical + Paper 2456 (1985), + http://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19850014994_1985014994.pdf + +2. M. W. Coffey, "The Stieltjes constants, their relation to the + `\eta_j` coefficients, and representation of the Hurwitz + zeta function", arXiv:0706.0343v1 http://arxiv.org/abs/0706.0343 + +3. http://mathworld.wolfram.com/StieltjesConstants.html + +4. http://pi.lacim.uqam.ca/piDATA/stieltjesgamma.txt + +""" + +gammaprod = r""" +Given iterables `a` and `b`, ``gammaprod(a, b)`` computes the +product / quotient of gamma functions: + +.. math :: + + \frac{\Gamma(a_0) \Gamma(a_1) \cdots \Gamma(a_p)} + {\Gamma(b_0) \Gamma(b_1) \cdots \Gamma(b_q)} + +Unlike direct calls to :func:`~mpmath.gamma`, :func:`~mpmath.gammaprod` considers +the entire product as a limit and evaluates this limit properly if +any of the numerator or denominator arguments are nonpositive +integers such that poles of the gamma function are encountered. +That is, :func:`~mpmath.gammaprod` evaluates + +.. math :: + + \lim_{\epsilon \to 0} + \frac{\Gamma(a_0+\epsilon) \Gamma(a_1+\epsilon) \cdots + \Gamma(a_p+\epsilon)} + {\Gamma(b_0+\epsilon) \Gamma(b_1+\epsilon) \cdots + \Gamma(b_q+\epsilon)} + +In particular: + +* If there are equally many poles in the numerator and the + denominator, the limit is a rational number times the remaining, + regular part of the product. + +* If there are more poles in the numerator, :func:`~mpmath.gammaprod` + returns ``+inf``. + +* If there are more poles in the denominator, :func:`~mpmath.gammaprod` + returns 0. + +**Examples** + +The reciprocal gamma function `1/\Gamma(x)` evaluated at `x = 0`:: + + >>> from mpmath import * + >>> mp.dps = 15 + >>> gammaprod([], [0]) + 0.0 + +A limit:: + + >>> gammaprod([-4], [-3]) + -0.25 + >>> limit(lambda x: gamma(x-1)/gamma(x), -3, direction=1) + -0.25 + >>> limit(lambda x: gamma(x-1)/gamma(x), -3, direction=-1) + -0.25 + +""" + +beta = r""" +Computes the beta function, +`B(x,y) = \Gamma(x) \Gamma(y) / \Gamma(x+y)`. +The beta function is also commonly defined by the integral +representation + +.. math :: + + B(x,y) = \int_0^1 t^{x-1} (1-t)^{y-1} \, dt + +**Examples** + +For integer and half-integer arguments where all three gamma +functions are finite, the beta function becomes either rational +number or a rational multiple of `\pi`:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> beta(5, 2) + 0.0333333333333333 + >>> beta(1.5, 2) + 0.266666666666667 + >>> 16*beta(2.5, 1.5) + 3.14159265358979 + +Where appropriate, :func:`~mpmath.beta` evaluates limits. A pole +of the beta function is taken to result in ``+inf``:: + + >>> beta(-0.5, 0.5) + 0.0 + >>> beta(-3, 3) + -0.333333333333333 + >>> beta(-2, 3) + +inf + >>> beta(inf, 1) + 0.0 + >>> beta(inf, 0) + nan + +:func:`~mpmath.beta` supports complex numbers and arbitrary precision +evaluation:: + + >>> beta(1, 2+j) + (0.4 - 0.2j) + >>> mp.dps = 25 + >>> beta(j,0.5) + (1.079424249270925780135675 - 1.410032405664160838288752j) + >>> mp.dps = 50 + >>> beta(pi, e) + 0.037890298781212201348153837138927165984170287886464 + +Various integrals can be computed by means of the +beta function:: + + >>> mp.dps = 15 + >>> quad(lambda t: t**2.5*(1-t)**2, [0, 1]) + 0.0230880230880231 + >>> beta(3.5, 3) + 0.0230880230880231 + >>> quad(lambda t: sin(t)**4 * sqrt(cos(t)), [0, pi/2]) + 0.319504062596158 + >>> beta(2.5, 0.75)/2 + 0.319504062596158 + +""" + +betainc = r""" +``betainc(a, b, x1=0, x2=1, regularized=False)`` gives the generalized +incomplete beta function, + +.. math :: + + I_{x_1}^{x_2}(a,b) = \int_{x_1}^{x_2} t^{a-1} (1-t)^{b-1} dt. + +When `x_1 = 0, x_2 = 1`, this reduces to the ordinary (complete) +beta function `B(a,b)`; see :func:`~mpmath.beta`. + +With the keyword argument ``regularized=True``, :func:`~mpmath.betainc` +computes the regularized incomplete beta function +`I_{x_1}^{x_2}(a,b) / B(a,b)`. This is the cumulative distribution of the +beta distribution with parameters `a`, `b`. + +.. note : + + Implementations of the incomplete beta function in some other + software uses a different argument order. For example, Mathematica uses the + reversed argument order ``Beta[x1,x2,a,b]``. For the equivalent of SciPy's + three-argument incomplete beta integral (implicitly with `x1 = 0`), use + ``betainc(a,b,0,x2,regularized=True)``. + +**Examples** + +Verifying that :func:`~mpmath.betainc` computes the integral in the +definition:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> x,y,a,b = 3, 4, 0, 6 + >>> betainc(x, y, a, b) + -4010.4 + >>> quad(lambda t: t**(x-1) * (1-t)**(y-1), [a, b]) + -4010.4 + +The arguments may be arbitrary complex numbers:: + + >>> betainc(0.75, 1-4j, 0, 2+3j) + (0.2241657956955709603655887 + 0.3619619242700451992411724j) + +With regularization:: + + >>> betainc(1, 2, 0, 0.25, regularized=True) + 0.4375 + >>> betainc(pi, e, 0, 1, regularized=True) # Complete + 1.0 + +The beta integral satisfies some simple argument transformation +symmetries:: + + >>> mp.dps = 15 + >>> betainc(2,3,4,5), -betainc(2,3,5,4), betainc(3,2,1-5,1-4) + (56.0833333333333, 56.0833333333333, 56.0833333333333) + +The beta integral can often be evaluated analytically. For integer and +rational arguments, the incomplete beta function typically reduces to a +simple algebraic-logarithmic expression:: + + >>> mp.dps = 25 + >>> identify(chop(betainc(0, 0, 3, 4))) + '-(log((9/8)))' + >>> identify(betainc(2, 3, 4, 5)) + '(673/12)' + >>> identify(betainc(1.5, 1, 1, 2)) + '((-12+sqrt(1152))/18)' + +""" + +binomial = r""" +Computes the binomial coefficient + +.. math :: + + {n \choose k} = \frac{n!}{k!(n-k)!}. + +The binomial coefficient gives the number of ways that `k` items +can be chosen from a set of `n` items. More generally, the binomial +coefficient is a well-defined function of arbitrary real or +complex `n` and `k`, via the gamma function. + +**Examples** + +Generate Pascal's triangle:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> for n in range(5): + ... nprint([binomial(n,k) for k in range(n+1)]) + ... + [1.0] + [1.0, 1.0] + [1.0, 2.0, 1.0] + [1.0, 3.0, 3.0, 1.0] + [1.0, 4.0, 6.0, 4.0, 1.0] + +There is 1 way to select 0 items from the empty set, and 0 ways to +select 1 item from the empty set:: + + >>> binomial(0, 0) + 1.0 + >>> binomial(0, 1) + 0.0 + +:func:`~mpmath.binomial` supports large arguments:: + + >>> binomial(10**20, 10**20-5) + 8.33333333333333e+97 + >>> binomial(10**20, 10**10) + 2.60784095465201e+104342944813 + +Nonintegral binomial coefficients find use in series +expansions:: + + >>> nprint(taylor(lambda x: (1+x)**0.25, 0, 4)) + [1.0, 0.25, -0.09375, 0.0546875, -0.0375977] + >>> nprint([binomial(0.25, k) for k in range(5)]) + [1.0, 0.25, -0.09375, 0.0546875, -0.0375977] + +An integral representation:: + + >>> n, k = 5, 3 + >>> f = lambda t: exp(-j*k*t)*(1+exp(j*t))**n + >>> chop(quad(f, [-pi,pi])/(2*pi)) + 10.0 + >>> binomial(n,k) + 10.0 + +""" + +rf = r""" +Computes the rising factorial or Pochhammer symbol, + +.. math :: + + x^{(n)} = x (x+1) \cdots (x+n-1) = \frac{\Gamma(x+n)}{\Gamma(x)} + +where the rightmost expression is valid for nonintegral `n`. + +**Examples** + +For integral `n`, the rising factorial is a polynomial:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> for n in range(5): + ... nprint(taylor(lambda x: rf(x,n), 0, n)) + ... + [1.0] + [0.0, 1.0] + [0.0, 1.0, 1.0] + [0.0, 2.0, 3.0, 1.0] + [0.0, 6.0, 11.0, 6.0, 1.0] + +Evaluation is supported for arbitrary arguments:: + + >>> rf(2+3j, 5.5) + (-7202.03920483347 - 3777.58810701527j) +""" + +ff = r""" +Computes the falling factorial, + +.. math :: + + (x)_n = x (x-1) \cdots (x-n+1) = \frac{\Gamma(x+1)}{\Gamma(x-n+1)} + +where the rightmost expression is valid for nonintegral `n`. + +**Examples** + +For integral `n`, the falling factorial is a polynomial:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> for n in range(5): + ... nprint(taylor(lambda x: ff(x,n), 0, n)) + ... + [1.0] + [0.0, 1.0] + [0.0, -1.0, 1.0] + [0.0, 2.0, -3.0, 1.0] + [0.0, -6.0, 11.0, -6.0, 1.0] + +Evaluation is supported for arbitrary arguments:: + + >>> ff(2+3j, 5.5) + (-720.41085888203 + 316.101124983878j) +""" + +fac2 = r""" +Computes the double factorial `x!!`, defined for integers +`x > 0` by + +.. math :: + + x!! = \begin{cases} + 1 \cdot 3 \cdots (x-2) \cdot x & x \;\mathrm{odd} \\ + 2 \cdot 4 \cdots (x-2) \cdot x & x \;\mathrm{even} + \end{cases} + +and more generally by [1] + +.. math :: + + x!! = 2^{x/2} \left(\frac{\pi}{2}\right)^{(\cos(\pi x)-1)/4} + \Gamma\left(\frac{x}{2}+1\right). + +**Examples** + +The integer sequence of double factorials begins:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> nprint([fac2(n) for n in range(10)]) + [1.0, 1.0, 2.0, 3.0, 8.0, 15.0, 48.0, 105.0, 384.0, 945.0] + +For large `x`, double factorials follow a Stirling-like asymptotic +approximation:: + + >>> x = mpf(10000) + >>> fac2(x) + 5.97272691416282e+17830 + >>> sqrt(pi)*x**((x+1)/2)*exp(-x/2) + 5.97262736954392e+17830 + +The recurrence formula `x!! = x (x-2)!!` can be reversed to +define the double factorial of negative odd integers (but +not negative even integers):: + + >>> fac2(-1), fac2(-3), fac2(-5), fac2(-7) + (1.0, -1.0, 0.333333333333333, -0.0666666666666667) + >>> fac2(-2) + Traceback (most recent call last): + ... + ValueError: gamma function pole + +With the exception of the poles at negative even integers, +:func:`~mpmath.fac2` supports evaluation for arbitrary complex arguments. +The recurrence formula is valid generally:: + + >>> fac2(pi+2j) + (-1.3697207890154e-12 + 3.93665300979176e-12j) + >>> (pi+2j)*fac2(pi-2+2j) + (-1.3697207890154e-12 + 3.93665300979176e-12j) + +Double factorials should not be confused with nested factorials, +which are immensely larger:: + + >>> fac(fac(20)) + 5.13805976125208e+43675043585825292774 + >>> fac2(20) + 3715891200.0 + +Double factorials appear, among other things, in series expansions +of Gaussian functions and the error function. Infinite series +include:: + + >>> nsum(lambda k: 1/fac2(k), [0, inf]) + 3.05940740534258 + >>> sqrt(e)*(1+sqrt(pi/2)*erf(sqrt(2)/2)) + 3.05940740534258 + >>> nsum(lambda k: 2**k/fac2(2*k-1), [1, inf]) + 4.06015693855741 + >>> e * erf(1) * sqrt(pi) + 4.06015693855741 + +A beautiful Ramanujan sum:: + + >>> nsum(lambda k: (-1)**k*(fac2(2*k-1)/fac2(2*k))**3, [0,inf]) + 0.90917279454693 + >>> (gamma('9/8')/gamma('5/4')/gamma('7/8'))**2 + 0.90917279454693 + +**References** + +1. http://functions.wolfram.com/GammaBetaErf/Factorial2/27/01/0002/ + +2. http://mathworld.wolfram.com/DoubleFactorial.html + +""" + +hyper = r""" +Evaluates the generalized hypergeometric function + +.. math :: + + \,_pF_q(a_1,\ldots,a_p; b_1,\ldots,b_q; z) = + \sum_{n=0}^\infty \frac{(a_1)_n (a_2)_n \ldots (a_p)_n} + {(b_1)_n(b_2)_n\ldots(b_q)_n} \frac{z^n}{n!} + +where `(x)_n` denotes the rising factorial (see :func:`~mpmath.rf`). + +The parameters lists ``a_s`` and ``b_s`` may contain integers, +real numbers, complex numbers, as well as exact fractions given in +the form of tuples `(p, q)`. :func:`~mpmath.hyper` is optimized to handle +integers and fractions more efficiently than arbitrary +floating-point parameters (since rational parameters are by +far the most common). + +**Examples** + +Verifying that :func:`~mpmath.hyper` gives the sum in the definition, by +comparison with :func:`~mpmath.nsum`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> a,b,c,d = 2,3,4,5 + >>> x = 0.25 + >>> hyper([a,b],[c,d],x) + 1.078903941164934876086237 + >>> fn = lambda n: rf(a,n)*rf(b,n)/rf(c,n)/rf(d,n)*x**n/fac(n) + >>> nsum(fn, [0, inf]) + 1.078903941164934876086237 + +The parameters can be any combination of integers, fractions, +floats and complex numbers:: + + >>> a, b, c, d, e = 1, (-1,2), pi, 3+4j, (2,3) + >>> x = 0.2j + >>> hyper([a,b],[c,d,e],x) + (0.9923571616434024810831887 - 0.005753848733883879742993122j) + >>> b, e = -0.5, mpf(2)/3 + >>> fn = lambda n: rf(a,n)*rf(b,n)/rf(c,n)/rf(d,n)/rf(e,n)*x**n/fac(n) + >>> nsum(fn, [0, inf]) + (0.9923571616434024810831887 - 0.005753848733883879742993122j) + +The `\,_0F_0` and `\,_1F_0` series are just elementary functions:: + + >>> a, z = sqrt(2), +pi + >>> hyper([],[],z) + 23.14069263277926900572909 + >>> exp(z) + 23.14069263277926900572909 + >>> hyper([a],[],z) + (-0.09069132879922920160334114 + 0.3283224323946162083579656j) + >>> (1-z)**(-a) + (-0.09069132879922920160334114 + 0.3283224323946162083579656j) + +If any `a_k` coefficient is a nonpositive integer, the series terminates +into a finite polynomial:: + + >>> hyper([1,1,1,-3],[2,5],1) + 0.7904761904761904761904762 + >>> identify(_) + '(83/105)' + +If any `b_k` is a nonpositive integer, the function is undefined (unless the +series terminates before the division by zero occurs):: + + >>> hyper([1,1,1,-3],[-2,5],1) + Traceback (most recent call last): + ... + ZeroDivisionError: pole in hypergeometric series + >>> hyper([1,1,1,-1],[-2,5],1) + 1.1 + +Except for polynomial cases, the radius of convergence `R` of the hypergeometric +series is either `R = \infty` (if `p \le q`), `R = 1` (if `p = q+1`), or +`R = 0` (if `p > q+1`). + +The analytic continuations of the functions with `p = q+1`, i.e. `\,_2F_1`, +`\,_3F_2`, `\,_4F_3`, etc, are all implemented and therefore these functions +can be evaluated for `|z| \ge 1`. The shortcuts :func:`~mpmath.hyp2f1`, :func:`~mpmath.hyp3f2` +are available to handle the most common cases (see their documentation), +but functions of higher degree are also supported via :func:`~mpmath.hyper`:: + + >>> hyper([1,2,3,4], [5,6,7], 1) # 4F3 at finite-valued branch point + 1.141783505526870731311423 + >>> hyper([4,5,6,7], [1,2,3], 1) # 4F3 at pole + +inf + >>> hyper([1,2,3,4,5], [6,7,8,9], 10) # 5F4 + (1.543998916527972259717257 - 0.5876309929580408028816365j) + >>> hyper([1,2,3,4,5,6], [7,8,9,10,11], 1j) # 6F5 + (0.9996565821853579063502466 + 0.0129721075905630604445669j) + +Near `z = 1` with noninteger parameters:: + + >>> hyper(['1/3',1,'3/2',2], ['1/5','11/6','41/8'], 1) + 2.219433352235586121250027 + >>> hyper(['1/3',1,'3/2',2], ['1/5','11/6','5/4'], 1) + +inf + >>> eps1 = extradps(6)(lambda: 1 - mpf('1e-6'))() + >>> hyper(['1/3',1,'3/2',2], ['1/5','11/6','5/4'], eps1) + 2923978034.412973409330956 + +Please note that, as currently implemented, evaluation of `\,_pF_{p-1}` +with `p \ge 3` may be slow or inaccurate when `|z-1|` is small, +for some parameter values. + +Evaluation may be aborted if convergence appears to be too slow. +The optional ``maxterms`` (limiting the number of series terms) and ``maxprec`` +(limiting the internal precision) keyword arguments can be used +to control evaluation:: + + >>> hyper([1,2,3], [4,5,6], 10000) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + NoConvergence: Hypergeometric series converges too slowly. Try increasing maxterms. + >>> hyper([1,2,3], [4,5,6], 10000, maxterms=10**6) + 7.622806053177969474396918e+4310 + +Additional options include ``force_series`` (which forces direct use of +a hypergeometric series even if another evaluation method might work better) +and ``asymp_tol`` which controls the target tolerance for using +asymptotic series. + +When `p > q+1`, ``hyper`` computes the (iterated) Borel sum of the divergent +series. For `\,_2F_0` the Borel sum has an analytic solution and can be +computed efficiently (see :func:`~mpmath.hyp2f0`). For higher degrees, the functions +is evaluated first by attempting to sum it directly as an asymptotic +series (this only works for tiny `|z|`), and then by evaluating the Borel +regularized sum using numerical integration. Except for +special parameter combinations, this can be extremely slow. + + >>> hyper([1,1], [], 0.5) # regularization of 2F0 + (1.340965419580146562086448 + 0.8503366631752726568782447j) + >>> hyper([1,1,1,1], [1], 0.5) # regularization of 4F1 + (1.108287213689475145830699 + 0.5327107430640678181200491j) + +With the following magnitude of argument, the asymptotic series for `\,_3F_1` +gives only a few digits. Using Borel summation, ``hyper`` can produce +a value with full accuracy:: + + >>> mp.dps = 15 + >>> hyper([2,0.5,4], [5.25], '0.08', force_series=True) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + NoConvergence: Hypergeometric series converges too slowly. Try increasing maxterms. + >>> hyper([2,0.5,4], [5.25], '0.08', asymp_tol=1e-4) + 1.0725535790737 + >>> hyper([2,0.5,4], [5.25], '0.08') + (1.07269542893559 + 5.54668863216891e-5j) + >>> hyper([2,0.5,4], [5.25], '-0.08', asymp_tol=1e-4) + 0.946344925484879 + >>> hyper([2,0.5,4], [5.25], '-0.08') + 0.946312503737771 + >>> mp.dps = 25 + >>> hyper([2,0.5,4], [5.25], '-0.08') + 0.9463125037377662296700858 + +Note that with the positive `z` value, there is a complex part in the +correct result, which falls below the tolerance of the asymptotic series. + +By default, a parameter that appears in both ``a_s`` and ``b_s`` will be removed +unless it is a nonpositive integer. This generally speeds up evaluation +by producing a hypergeometric function of lower order. +This optimization can be disabled by passing ``eliminate=False``. + + >>> hyper([1,2,3], [4,5,3], 10000) + 1.268943190440206905892212e+4321 + >>> hyper([1,2,3], [4,5,3], 10000, eliminate=False) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + NoConvergence: Hypergeometric series converges too slowly. Try increasing maxterms. + >>> hyper([1,2,3], [4,5,3], 10000, eliminate=False, maxterms=10**6) + 1.268943190440206905892212e+4321 + +If a nonpositive integer `-n` appears in both ``a_s`` and ``b_s``, this parameter +cannot be unambiguously removed since it creates a term 0 / 0. +In this case the hypergeometric series is understood to terminate before +the division by zero occurs. This convention is consistent with Mathematica. +An alternative convention of eliminating the parameters can be toggled +with ``eliminate_all=True``: + + >>> hyper([2,-1], [-1], 3) + 7.0 + >>> hyper([2,-1], [-1], 3, eliminate_all=True) + 0.25 + >>> hyper([2], [], 3) + 0.25 + +""" + +hypercomb = r""" +Computes a weighted combination of hypergeometric functions + +.. math :: + + \sum_{r=1}^N \left[ \prod_{k=1}^{l_r} {w_{r,k}}^{c_{r,k}} + \frac{\prod_{k=1}^{m_r} \Gamma(\alpha_{r,k})}{\prod_{k=1}^{n_r} + \Gamma(\beta_{r,k})} + \,_{p_r}F_{q_r}(a_{r,1},\ldots,a_{r,p}; b_{r,1}, + \ldots, b_{r,q}; z_r)\right]. + +Typically the parameters are linear combinations of a small set of base +parameters; :func:`~mpmath.hypercomb` permits computing a correct value in +the case that some of the `\alpha`, `\beta`, `b` turn out to be +nonpositive integers, or if division by zero occurs for some `w^c`, +assuming that there are opposing singularities that cancel out. +The limit is computed by evaluating the function with the base +parameters perturbed, at a higher working precision. + +The first argument should be a function that takes the perturbable +base parameters ``params`` as input and returns `N` tuples +``(w, c, alpha, beta, a, b, z)``, where the coefficients ``w``, ``c``, +gamma factors ``alpha``, ``beta``, and hypergeometric coefficients +``a``, ``b`` each should be lists of numbers, and ``z`` should be a single +number. + +**Examples** + +The following evaluates + +.. math :: + + (a-1) \frac{\Gamma(a-3)}{\Gamma(a-4)} \,_1F_1(a,a-1,z) = e^z(a-4)(a+z-1) + +with `a=1, z=3`. There is a zero factor, two gamma function poles, and +the 1F1 function is singular; all singularities cancel out to give a finite +value:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> hypercomb(lambda a: [([a-1],[1],[a-3],[a-4],[a],[a-1],3)], [1]) + -180.769832308689 + >>> -9*exp(3) + -180.769832308689 + +""" + +hyp0f1 = r""" +Gives the hypergeometric function `\,_0F_1`, sometimes known as the +confluent limit function, defined as + +.. math :: + + \,_0F_1(a,z) = \sum_{k=0}^{\infty} \frac{1}{(a)_k} \frac{z^k}{k!}. + +This function satisfies the differential equation `z f''(z) + a f'(z) = f(z)`, +and is related to the Bessel function of the first kind (see :func:`~mpmath.besselj`). + +``hyp0f1(a,z)`` is equivalent to ``hyper([],[a],z)``; see documentation for +:func:`~mpmath.hyper` for more information. + +**Examples** + +Evaluation for arbitrary arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> hyp0f1(2, 0.25) + 1.130318207984970054415392 + >>> hyp0f1((1,2), 1234567) + 6.27287187546220705604627e+964 + >>> hyp0f1(3+4j, 1000000j) + (3.905169561300910030267132e+606 + 3.807708544441684513934213e+606j) + +Evaluation is supported for arbitrarily large values of `z`, +using asymptotic expansions:: + + >>> hyp0f1(1, 10**50) + 2.131705322874965310390701e+8685889638065036553022565 + >>> hyp0f1(1, -10**50) + 1.115945364792025420300208e-13 + +Verifying the differential equation:: + + >>> a = 2.5 + >>> f = lambda z: hyp0f1(a,z) + >>> for z in [0, 10, 3+4j]: + ... chop(z*diff(f,z,2) + a*diff(f,z) - f(z)) + ... + 0.0 + 0.0 + 0.0 + +""" + +hyp1f1 = r""" +Gives the confluent hypergeometric function of the first kind, + +.. math :: + + \,_1F_1(a,b,z) = \sum_{k=0}^{\infty} \frac{(a)_k}{(b)_k} \frac{z^k}{k!}, + +also known as Kummer's function and sometimes denoted by `M(a,b,z)`. This +function gives one solution to the confluent (Kummer's) differential equation + +.. math :: + + z f''(z) + (b-z) f'(z) - af(z) = 0. + +A second solution is given by the `U` function; see :func:`~mpmath.hyperu`. +Solutions are also given in an alternate form by the Whittaker +functions (:func:`~mpmath.whitm`, :func:`~mpmath.whitw`). + +``hyp1f1(a,b,z)`` is equivalent +to ``hyper([a],[b],z)``; see documentation for :func:`~mpmath.hyper` for more +information. + +**Examples** + +Evaluation for real and complex values of the argument `z`, with +fixed parameters `a = 2, b = -1/3`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> hyp1f1(2, (-1,3), 3.25) + -2815.956856924817275640248 + >>> hyp1f1(2, (-1,3), -3.25) + -1.145036502407444445553107 + >>> hyp1f1(2, (-1,3), 1000) + -8.021799872770764149793693e+441 + >>> hyp1f1(2, (-1,3), -1000) + 0.000003131987633006813594535331 + >>> hyp1f1(2, (-1,3), 100+100j) + (-3.189190365227034385898282e+48 - 1.106169926814270418999315e+49j) + +Parameters may be complex:: + + >>> hyp1f1(2+3j, -1+j, 10j) + (261.8977905181045142673351 + 160.8930312845682213562172j) + +Arbitrarily large values of `z` are supported:: + + >>> hyp1f1(3, 4, 10**20) + 3.890569218254486878220752e+43429448190325182745 + >>> hyp1f1(3, 4, -10**20) + 6.0e-60 + >>> hyp1f1(3, 4, 10**20*j) + (-1.935753855797342532571597e-20 - 2.291911213325184901239155e-20j) + +Verifying the differential equation:: + + >>> a, b = 1.5, 2 + >>> f = lambda z: hyp1f1(a,b,z) + >>> for z in [0, -10, 3, 3+4j]: + ... chop(z*diff(f,z,2) + (b-z)*diff(f,z) - a*f(z)) + ... + 0.0 + 0.0 + 0.0 + 0.0 + +An integral representation:: + + >>> a, b = 1.5, 3 + >>> z = 1.5 + >>> hyp1f1(a,b,z) + 2.269381460919952778587441 + >>> g = lambda t: exp(z*t)*t**(a-1)*(1-t)**(b-a-1) + >>> gammaprod([b],[a,b-a])*quad(g, [0,1]) + 2.269381460919952778587441 + + +""" + +hyp1f2 = r""" +Gives the hypergeometric function `\,_1F_2(a_1,a_2;b_1,b_2; z)`. +The call ``hyp1f2(a1,b1,b2,z)`` is equivalent to +``hyper([a1],[b1,b2],z)``. + +Evaluation works for complex and arbitrarily large arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> a, b, c = 1.5, (-1,3), 2.25 + >>> hyp1f2(a, b, c, 10**20) + -1.159388148811981535941434e+8685889639 + >>> hyp1f2(a, b, c, -10**20) + -12.60262607892655945795907 + >>> hyp1f2(a, b, c, 10**20*j) + (4.237220401382240876065501e+6141851464 - 2.950930337531768015892987e+6141851464j) + >>> hyp1f2(2+3j, -2j, 0.5j, 10-20j) + (135881.9905586966432662004 - 86681.95885418079535738828j) + +""" + +hyp2f2 = r""" +Gives the hypergeometric function `\,_2F_2(a_1,a_2;b_1,b_2; z)`. +The call ``hyp2f2(a1,a2,b1,b2,z)`` is equivalent to +``hyper([a1,a2],[b1,b2],z)``. + +Evaluation works for complex and arbitrarily large arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> a, b, c, d = 1.5, (-1,3), 2.25, 4 + >>> hyp2f2(a, b, c, d, 10**20) + -5.275758229007902299823821e+43429448190325182663 + >>> hyp2f2(a, b, c, d, -10**20) + 2561445.079983207701073448 + >>> hyp2f2(a, b, c, d, 10**20*j) + (2218276.509664121194836667 - 1280722.539991603850462856j) + >>> hyp2f2(2+3j, -2j, 0.5j, 4j, 10-20j) + (80500.68321405666957342788 - 20346.82752982813540993502j) + +""" + +hyp2f3 = r""" +Gives the hypergeometric function `\,_2F_3(a_1,a_2;b_1,b_2,b_3; z)`. +The call ``hyp2f3(a1,a2,b1,b2,b3,z)`` is equivalent to +``hyper([a1,a2],[b1,b2,b3],z)``. + +Evaluation works for arbitrarily large arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> a1,a2,b1,b2,b3 = 1.5, (-1,3), 2.25, 4, (1,5) + >>> hyp2f3(a1,a2,b1,b2,b3,10**20) + -4.169178177065714963568963e+8685889590 + >>> hyp2f3(a1,a2,b1,b2,b3,-10**20) + 7064472.587757755088178629 + >>> hyp2f3(a1,a2,b1,b2,b3,10**20*j) + (-5.163368465314934589818543e+6141851415 + 1.783578125755972803440364e+6141851416j) + >>> hyp2f3(2+3j, -2j, 0.5j, 4j, -1-j, 10-20j) + (-2280.938956687033150740228 + 13620.97336609573659199632j) + >>> hyp2f3(2+3j, -2j, 0.5j, 4j, -1-j, 10000000-20000000j) + (4.849835186175096516193e+3504 - 3.365981529122220091353633e+3504j) + +""" + +hyp2f1 = r""" +Gives the Gauss hypergeometric function `\,_2F_1` (often simply referred to as +*the* hypergeometric function), defined for `|z| < 1` as + +.. math :: + + \,_2F_1(a,b,c,z) = \sum_{k=0}^{\infty} + \frac{(a)_k (b)_k}{(c)_k} \frac{z^k}{k!}. + +and for `|z| \ge 1` by analytic continuation, with a branch cut on `(1, \infty)` +when necessary. + +Special cases of this function include many of the orthogonal polynomials as +well as the incomplete beta function and other functions. Properties of the +Gauss hypergeometric function are documented comprehensively in many references, +for example Abramowitz & Stegun, section 15. + +The implementation supports the analytic continuation as well as evaluation +close to the unit circle where `|z| \approx 1`. The syntax ``hyp2f1(a,b,c,z)`` +is equivalent to ``hyper([a,b],[c],z)``. + +**Examples** + +Evaluation with `z` inside, outside and on the unit circle, for +fixed parameters:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> hyp2f1(2, (1,2), 4, 0.75) + 1.303703703703703703703704 + >>> hyp2f1(2, (1,2), 4, -1.75) + 0.7431290566046919177853916 + >>> hyp2f1(2, (1,2), 4, 1.75) + (1.418075801749271137026239 - 1.114976146679907015775102j) + >>> hyp2f1(2, (1,2), 4, 1) + 1.6 + >>> hyp2f1(2, (1,2), 4, -1) + 0.8235498012182875315037882 + >>> hyp2f1(2, (1,2), 4, j) + (0.9144026291433065674259078 + 0.2050415770437884900574923j) + >>> hyp2f1(2, (1,2), 4, 2+j) + (0.9274013540258103029011549 + 0.7455257875808100868984496j) + >>> hyp2f1(2, (1,2), 4, 0.25j) + (0.9931169055799728251931672 + 0.06154836525312066938147793j) + +Evaluation with complex parameter values:: + + >>> hyp2f1(1+j, 0.75, 10j, 1+5j) + (0.8834833319713479923389638 + 0.7053886880648105068343509j) + +Evaluation with `z = 1`:: + + >>> hyp2f1(-2.5, 3.5, 1.5, 1) + 0.0 + >>> hyp2f1(-2.5, 3, 4, 1) + 0.06926406926406926406926407 + >>> hyp2f1(2, 3, 4, 1) + +inf + +Evaluation for huge arguments:: + + >>> hyp2f1((-1,3), 1.75, 4, '1e100') + (7.883714220959876246415651e+32 + 1.365499358305579597618785e+33j) + >>> hyp2f1((-1,3), 1.75, 4, '1e1000000') + (7.883714220959876246415651e+333332 + 1.365499358305579597618785e+333333j) + >>> hyp2f1((-1,3), 1.75, 4, '1e1000000j') + (1.365499358305579597618785e+333333 - 7.883714220959876246415651e+333332j) + +An integral representation:: + + >>> a,b,c,z = -0.5, 1, 2.5, 0.25 + >>> g = lambda t: t**(b-1) * (1-t)**(c-b-1) * (1-t*z)**(-a) + >>> gammaprod([c],[b,c-b]) * quad(g, [0,1]) + 0.9480458814362824478852618 + >>> hyp2f1(a,b,c,z) + 0.9480458814362824478852618 + +Verifying the hypergeometric differential equation:: + + >>> f = lambda z: hyp2f1(a,b,c,z) + >>> chop(z*(1-z)*diff(f,z,2) + (c-(a+b+1)*z)*diff(f,z) - a*b*f(z)) + 0.0 + +""" + +hyp3f2 = r""" +Gives the generalized hypergeometric function `\,_3F_2`, defined for `|z| < 1` +as + +.. math :: + + \,_3F_2(a_1,a_2,a_3,b_1,b_2,z) = \sum_{k=0}^{\infty} + \frac{(a_1)_k (a_2)_k (a_3)_k}{(b_1)_k (b_2)_k} \frac{z^k}{k!}. + +and for `|z| \ge 1` by analytic continuation. The analytic structure of this +function is similar to that of `\,_2F_1`, generally with a singularity at +`z = 1` and a branch cut on `(1, \infty)`. + +Evaluation is supported inside, on, and outside +the circle of convergence `|z| = 1`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> hyp3f2(1,2,3,4,5,0.25) + 1.083533123380934241548707 + >>> hyp3f2(1,2+2j,3,4,5,-10+10j) + (0.1574651066006004632914361 - 0.03194209021885226400892963j) + >>> hyp3f2(1,2,3,4,5,-10) + 0.3071141169208772603266489 + >>> hyp3f2(1,2,3,4,5,10) + (-0.4857045320523947050581423 - 0.5988311440454888436888028j) + >>> hyp3f2(0.25,1,1,2,1.5,1) + 1.157370995096772047567631 + >>> (8-pi-2*ln2)/3 + 1.157370995096772047567631 + >>> hyp3f2(1+j,0.5j,2,1,-2j,-1) + (1.74518490615029486475959 + 0.1454701525056682297614029j) + >>> hyp3f2(1+j,0.5j,2,1,-2j,sqrt(j)) + (0.9829816481834277511138055 - 0.4059040020276937085081127j) + >>> hyp3f2(-3,2,1,-5,4,1) + 1.41 + >>> hyp3f2(-3,2,1,-5,4,2) + 2.12 + +Evaluation very close to the unit circle:: + + >>> hyp3f2(1,2,3,4,5,'1.0001') + (1.564877796743282766872279 - 3.76821518787438186031973e-11j) + >>> hyp3f2(1,2,3,4,5,'1+0.0001j') + (1.564747153061671573212831 + 0.0001305757570366084557648482j) + >>> hyp3f2(1,2,3,4,5,'0.9999') + 1.564616644881686134983664 + >>> hyp3f2(1,2,3,4,5,'-0.9999') + 0.7823896253461678060196207 + +.. note :: + + Evaluation for `|z-1|` small can currently be inaccurate or slow + for some parameter combinations. + +For various parameter combinations, `\,_3F_2` admits representation in terms +of hypergeometric functions of lower degree, or in terms of +simpler functions:: + + >>> for a, b, z in [(1,2,-1), (2,0.5,1)]: + ... hyp2f1(a,b,a+b+0.5,z)**2 + ... hyp3f2(2*a,a+b,2*b,a+b+0.5,2*a+2*b,z) + ... + 0.4246104461966439006086308 + 0.4246104461966439006086308 + 7.111111111111111111111111 + 7.111111111111111111111111 + + >>> z = 2+3j + >>> hyp3f2(0.5,1,1.5,2,2,z) + (0.7621440939243342419729144 + 0.4249117735058037649915723j) + >>> 4*(pi-2*ellipe(z))/(pi*z) + (0.7621440939243342419729144 + 0.4249117735058037649915723j) + +""" + +hyperu = r""" +Gives the Tricomi confluent hypergeometric function `U`, also known as +the Kummer or confluent hypergeometric function of the second kind. This +function gives a second linearly independent solution to the confluent +hypergeometric differential equation (the first is provided by `\,_1F_1` -- +see :func:`~mpmath.hyp1f1`). + +**Examples** + +Evaluation for arbitrary complex arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> hyperu(2,3,4) + 0.0625 + >>> hyperu(0.25, 5, 1000) + 0.1779949416140579573763523 + >>> hyperu(0.25, 5, -1000) + (0.1256256609322773150118907 - 0.1256256609322773150118907j) + +The `U` function may be singular at `z = 0`:: + + >>> hyperu(1.5, 2, 0) + +inf + >>> hyperu(1.5, -2, 0) + 0.1719434921288400112603671 + +Verifying the differential equation:: + + >>> a, b = 1.5, 2 + >>> f = lambda z: hyperu(a,b,z) + >>> for z in [-10, 3, 3+4j]: + ... chop(z*diff(f,z,2) + (b-z)*diff(f,z) - a*f(z)) + ... + 0.0 + 0.0 + 0.0 + +An integral representation:: + + >>> a,b,z = 2, 3.5, 4.25 + >>> hyperu(a,b,z) + 0.06674960718150520648014567 + >>> quad(lambda t: exp(-z*t)*t**(a-1)*(1+t)**(b-a-1),[0,inf]) / gamma(a) + 0.06674960718150520648014567 + + +[1] http://people.math.sfu.ca/~cbm/aands/page_504.htm +""" + +hyp2f0 = r""" +Gives the hypergeometric function `\,_2F_0`, defined formally by the +series + +.. math :: + + \,_2F_0(a,b;;z) = \sum_{n=0}^{\infty} (a)_n (b)_n \frac{z^n}{n!}. + +This series usually does not converge. For small enough `z`, it can be viewed +as an asymptotic series that may be summed directly with an appropriate +truncation. When this is not the case, :func:`~mpmath.hyp2f0` gives a regularized sum, +or equivalently, it uses a representation in terms of the +hypergeometric U function [1]. The series also converges when either `a` or `b` +is a nonpositive integer, as it then terminates into a polynomial +after `-a` or `-b` terms. + +**Examples** + +Evaluation is supported for arbitrary complex arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> hyp2f0((2,3), 1.25, -100) + 0.07095851870980052763312791 + >>> hyp2f0((2,3), 1.25, 100) + (-0.03254379032170590665041131 + 0.07269254613282301012735797j) + >>> hyp2f0(-0.75, 1-j, 4j) + (-0.3579987031082732264862155 - 3.052951783922142735255881j) + +Even with real arguments, the regularized value of 2F0 is often complex-valued, +but the imaginary part decreases exponentially as `z \to 0`. In the following +example, the first call uses complex evaluation while the second has a small +enough `z` to evaluate using the direct series and thus the returned value +is strictly real (this should be taken to indicate that the imaginary +part is less than ``eps``):: + + >>> mp.dps = 15 + >>> hyp2f0(1.5, 0.5, 0.05) + (1.04166637647907 + 8.34584913683906e-8j) + >>> hyp2f0(1.5, 0.5, 0.0005) + 1.00037535207621 + +The imaginary part can be retrieved by increasing the working precision:: + + >>> mp.dps = 80 + >>> nprint(hyp2f0(1.5, 0.5, 0.009).imag) + 1.23828e-46 + +In the polynomial case (the series terminating), 2F0 can evaluate exactly:: + + >>> mp.dps = 15 + >>> hyp2f0(-6,-6,2) + 291793.0 + >>> identify(hyp2f0(-2,1,0.25)) + '(5/8)' + +The coefficients of the polynomials can be recovered using Taylor expansion:: + + >>> nprint(taylor(lambda x: hyp2f0(-3,0.5,x), 0, 10)) + [1.0, -1.5, 2.25, -1.875, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + >>> nprint(taylor(lambda x: hyp2f0(-4,0.5,x), 0, 10)) + [1.0, -2.0, 4.5, -7.5, 6.5625, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + + +[1] http://people.math.sfu.ca/~cbm/aands/page_504.htm +""" + + +gammainc = r""" +``gammainc(z, a=0, b=inf)`` computes the (generalized) incomplete +gamma function with integration limits `[a, b]`: + +.. math :: + + \Gamma(z,a,b) = \int_a^b t^{z-1} e^{-t} \, dt + +The generalized incomplete gamma function reduces to the +following special cases when one or both endpoints are fixed: + +* `\Gamma(z,0,\infty)` is the standard ("complete") + gamma function, `\Gamma(z)` (available directly + as the mpmath function :func:`~mpmath.gamma`) +* `\Gamma(z,a,\infty)` is the "upper" incomplete gamma + function, `\Gamma(z,a)` +* `\Gamma(z,0,b)` is the "lower" incomplete gamma + function, `\gamma(z,b)`. + +Of course, we have +`\Gamma(z,0,x) + \Gamma(z,x,\infty) = \Gamma(z)` +for all `z` and `x`. + +Note however that some authors reverse the order of the +arguments when defining the lower and upper incomplete +gamma function, so one should be careful to get the correct +definition. + +If also given the keyword argument ``regularized=True``, +:func:`~mpmath.gammainc` computes the "regularized" incomplete gamma +function + +.. math :: + + P(z,a,b) = \frac{\Gamma(z,a,b)}{\Gamma(z)}. + +**Examples** + +We can compare with numerical quadrature to verify that +:func:`~mpmath.gammainc` computes the integral in the definition:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> gammainc(2+3j, 4, 10) + (0.00977212668627705160602312 - 0.0770637306312989892451977j) + >>> quad(lambda t: t**(2+3j-1) * exp(-t), [4, 10]) + (0.00977212668627705160602312 - 0.0770637306312989892451977j) + +Argument symmetries follow directly from the integral definition:: + + >>> gammainc(3, 4, 5) + gammainc(3, 5, 4) + 0.0 + >>> gammainc(3,0,2) + gammainc(3,2,4); gammainc(3,0,4) + 1.523793388892911312363331 + 1.523793388892911312363331 + >>> findroot(lambda z: gammainc(2,z,3), 1) + 3.0 + +Evaluation for arbitrarily large arguments:: + + >>> gammainc(10, 100) + 4.083660630910611272288592e-26 + >>> gammainc(10, 10000000000000000) + 5.290402449901174752972486e-4342944819032375 + >>> gammainc(3+4j, 1000000+1000000j) + (-1.257913707524362408877881e-434284 + 2.556691003883483531962095e-434284j) + +Evaluation of a generalized incomplete gamma function automatically chooses +the representation that gives a more accurate result, depending on which +parameter is larger:: + + >>> gammainc(10000000, 3) - gammainc(10000000, 2) # Bad + 0.0 + >>> gammainc(10000000, 2, 3) # Good + 1.755146243738946045873491e+4771204 + >>> gammainc(2, 0, 100000001) - gammainc(2, 0, 100000000) # Bad + 0.0 + >>> gammainc(2, 100000000, 100000001) # Good + 4.078258353474186729184421e-43429441 + +The incomplete gamma functions satisfy simple recurrence +relations:: + + >>> mp.dps = 25 + >>> z, a = mpf(3.5), mpf(2) + >>> gammainc(z+1, a); z*gammainc(z,a) + a**z*exp(-a) + 10.60130296933533459267329 + 10.60130296933533459267329 + >>> gammainc(z+1,0,a); z*gammainc(z,0,a) - a**z*exp(-a) + 1.030425427232114336470932 + 1.030425427232114336470932 + +Evaluation at integers and poles:: + + >>> gammainc(-3, -4, -5) + (-0.2214577048967798566234192 + 0.0j) + >>> gammainc(-3, 0, 5) + +inf + +If `z` is an integer, the recurrence reduces the incomplete gamma +function to `P(a) \exp(-a) + Q(b) \exp(-b)` where `P` and +`Q` are polynomials:: + + >>> gammainc(1, 2); exp(-2) + 0.1353352832366126918939995 + 0.1353352832366126918939995 + >>> mp.dps = 50 + >>> identify(gammainc(6, 1, 2), ['exp(-1)', 'exp(-2)']) + '(326*exp(-1) + (-872)*exp(-2))' + +The incomplete gamma functions reduce to functions such as +the exponential integral Ei and the error function for special +arguments:: + + >>> mp.dps = 25 + >>> gammainc(0, 4); -ei(-4) + 0.00377935240984890647887486 + 0.00377935240984890647887486 + >>> gammainc(0.5, 0, 2); sqrt(pi)*erf(sqrt(2)) + 1.691806732945198336509541 + 1.691806732945198336509541 + +""" + +erf = r""" +Computes the error function, `\mathrm{erf}(x)`. The error +function is the normalized antiderivative of the Gaussian function +`\exp(-t^2)`. More precisely, + +.. math:: + + \mathrm{erf}(x) = \frac{2}{\sqrt \pi} \int_0^x \exp(-t^2) \,dt + +**Basic examples** + +Simple values and limits include:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> erf(0) + 0.0 + >>> erf(1) + 0.842700792949715 + >>> erf(-1) + -0.842700792949715 + >>> erf(inf) + 1.0 + >>> erf(-inf) + -1.0 + +For large real `x`, `\mathrm{erf}(x)` approaches 1 very +rapidly:: + + >>> erf(3) + 0.999977909503001 + >>> erf(5) + 0.999999999998463 + +The error function is an odd function:: + + >>> nprint(chop(taylor(erf, 0, 5))) + [0.0, 1.12838, 0.0, -0.376126, 0.0, 0.112838] + +:func:`~mpmath.erf` implements arbitrary-precision evaluation and +supports complex numbers:: + + >>> mp.dps = 50 + >>> erf(0.5) + 0.52049987781304653768274665389196452873645157575796 + >>> mp.dps = 25 + >>> erf(1+j) + (1.316151281697947644880271 + 0.1904534692378346862841089j) + +Evaluation is supported for large arguments:: + + >>> mp.dps = 25 + >>> erf('1e1000') + 1.0 + >>> erf('-1e1000') + -1.0 + >>> erf('1e-1000') + 1.128379167095512573896159e-1000 + >>> erf('1e7j') + (0.0 + 8.593897639029319267398803e+43429448190317j) + >>> erf('1e7+1e7j') + (0.9999999858172446172631323 + 3.728805278735270407053139e-8j) + +**Related functions** + +See also :func:`~mpmath.erfc`, which is more accurate for large `x`, +and :func:`~mpmath.erfi` which gives the antiderivative of +`\exp(t^2)`. + +The Fresnel integrals :func:`~mpmath.fresnels` and :func:`~mpmath.fresnelc` +are also related to the error function. +""" + +erfc = r""" +Computes the complementary error function, +`\mathrm{erfc}(x) = 1-\mathrm{erf}(x)`. +This function avoids cancellation that occurs when naively +computing the complementary error function as ``1-erf(x)``:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> 1 - erf(10) + 0.0 + >>> erfc(10) + 2.08848758376254e-45 + +:func:`~mpmath.erfc` works accurately even for ludicrously large +arguments:: + + >>> erfc(10**10) + 4.3504398860243e-43429448190325182776 + +Complex arguments are supported:: + + >>> erfc(500+50j) + (1.19739830969552e-107492 + 1.46072418957528e-107491j) + +""" + + +erfi = r""" +Computes the imaginary error function, `\mathrm{erfi}(x)`. +The imaginary error function is defined in analogy with the +error function, but with a positive sign in the integrand: + +.. math :: + + \mathrm{erfi}(x) = \frac{2}{\sqrt \pi} \int_0^x \exp(t^2) \,dt + +Whereas the error function rapidly converges to 1 as `x` grows, +the imaginary error function rapidly diverges to infinity. +The functions are related as +`\mathrm{erfi}(x) = -i\,\mathrm{erf}(ix)` for all complex +numbers `x`. + +**Examples** + +Basic values and limits:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> erfi(0) + 0.0 + >>> erfi(1) + 1.65042575879754 + >>> erfi(-1) + -1.65042575879754 + >>> erfi(inf) + +inf + >>> erfi(-inf) + -inf + +Note the symmetry between erf and erfi:: + + >>> erfi(3j) + (0.0 + 0.999977909503001j) + >>> erf(3) + 0.999977909503001 + >>> erf(1+2j) + (-0.536643565778565 - 5.04914370344703j) + >>> erfi(2+1j) + (-5.04914370344703 - 0.536643565778565j) + +Large arguments are supported:: + + >>> erfi(1000) + 1.71130938718796e+434291 + >>> erfi(10**10) + 7.3167287567024e+43429448190325182754 + >>> erfi(-10**10) + -7.3167287567024e+43429448190325182754 + >>> erfi(1000-500j) + (2.49895233563961e+325717 + 2.6846779342253e+325717j) + >>> erfi(100000j) + (0.0 + 1.0j) + >>> erfi(-100000j) + (0.0 - 1.0j) + + +""" + +erfinv = r""" +Computes the inverse error function, satisfying + +.. math :: + + \mathrm{erf}(\mathrm{erfinv}(x)) = + \mathrm{erfinv}(\mathrm{erf}(x)) = x. + +This function is defined only for `-1 \le x \le 1`. + +**Examples** + +Special values include:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> erfinv(0) + 0.0 + >>> erfinv(1) + +inf + >>> erfinv(-1) + -inf + +The domain is limited to the standard interval:: + + >>> erfinv(2) + Traceback (most recent call last): + ... + ValueError: erfinv(x) is defined only for -1 <= x <= 1 + +It is simple to check that :func:`~mpmath.erfinv` computes inverse values of +:func:`~mpmath.erf` as promised:: + + >>> erf(erfinv(0.75)) + 0.75 + >>> erf(erfinv(-0.995)) + -0.995 + +:func:`~mpmath.erfinv` supports arbitrary-precision evaluation:: + + >>> mp.dps = 50 + >>> x = erf(2) + >>> x + 0.99532226501895273416206925636725292861089179704006 + >>> erfinv(x) + 2.0 + +A definite integral involving the inverse error function:: + + >>> mp.dps = 15 + >>> quad(erfinv, [0, 1]) + 0.564189583547756 + >>> 1/sqrt(pi) + 0.564189583547756 + +The inverse error function can be used to generate random numbers +with a Gaussian distribution (although this is a relatively +inefficient algorithm):: + + >>> nprint([erfinv(2*rand()-1) for n in range(6)]) # doctest: +SKIP + [-0.586747, 1.10233, -0.376796, 0.926037, -0.708142, -0.732012] + +""" + +npdf = r""" +``npdf(x, mu=0, sigma=1)`` evaluates the probability density +function of a normal distribution with mean value `\mu` +and variance `\sigma^2`. + +Elementary properties of the probability distribution can +be verified using numerical integration:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> quad(npdf, [-inf, inf]) + 1.0 + >>> quad(lambda x: npdf(x, 3), [3, inf]) + 0.5 + >>> quad(lambda x: npdf(x, 3, 2), [3, inf]) + 0.5 + +See also :func:`~mpmath.ncdf`, which gives the cumulative +distribution. +""" + +ncdf = r""" +``ncdf(x, mu=0, sigma=1)`` evaluates the cumulative distribution +function of a normal distribution with mean value `\mu` +and variance `\sigma^2`. + +See also :func:`~mpmath.npdf`, which gives the probability density. + +Elementary properties include:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> ncdf(pi, mu=pi) + 0.5 + >>> ncdf(-inf) + 0.0 + >>> ncdf(+inf) + 1.0 + +The cumulative distribution is the integral of the density +function having identical mu and sigma:: + + >>> mp.dps = 15 + >>> diff(ncdf, 2) + 0.053990966513188 + >>> npdf(2) + 0.053990966513188 + >>> diff(lambda x: ncdf(x, 1, 0.5), 0) + 0.107981933026376 + >>> npdf(0, 1, 0.5) + 0.107981933026376 +""" + +expint = r""" +:func:`~mpmath.expint(n,z)` gives the generalized exponential integral +or En-function, + +.. math :: + + \mathrm{E}_n(z) = \int_1^{\infty} \frac{e^{-zt}}{t^n} dt, + +where `n` and `z` may both be complex numbers. The case with `n = 1` is +also given by :func:`~mpmath.e1`. + +**Examples** + +Evaluation at real and complex arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> expint(1, 6.25) + 0.0002704758872637179088496194 + >>> expint(-3, 2+3j) + (0.00299658467335472929656159 + 0.06100816202125885450319632j) + >>> expint(2+3j, 4-5j) + (0.001803529474663565056945248 - 0.002235061547756185403349091j) + +At negative integer values of `n`, `E_n(z)` reduces to a +rational-exponential function:: + + >>> f = lambda n, z: fac(n)*sum(z**k/fac(k-1) for k in range(1,n+2))/\ + ... exp(z)/z**(n+2) + >>> n = 3 + >>> z = 1/pi + >>> expint(-n,z) + 584.2604820613019908668219 + >>> f(n,z) + 584.2604820613019908668219 + >>> n = 5 + >>> expint(-n,z) + 115366.5762594725451811138 + >>> f(n,z) + 115366.5762594725451811138 +""" + +e1 = r""" +Computes the exponential integral `\mathrm{E}_1(z)`, given by + +.. math :: + + \mathrm{E}_1(z) = \int_z^{\infty} \frac{e^{-t}}{t} dt. + +This is equivalent to :func:`~mpmath.expint` with `n = 1`. + +**Examples** + +Two ways to evaluate this function:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> e1(6.25) + 0.0002704758872637179088496194 + >>> expint(1,6.25) + 0.0002704758872637179088496194 + +The E1-function is essentially the same as the Ei-function (:func:`~mpmath.ei`) +with negated argument, except for an imaginary branch cut term:: + + >>> e1(2.5) + 0.02491491787026973549562801 + >>> -ei(-2.5) + 0.02491491787026973549562801 + >>> e1(-2.5) + (-7.073765894578600711923552 - 3.141592653589793238462643j) + >>> -ei(2.5) + -7.073765894578600711923552 + +""" + +ei = r""" +Computes the exponential integral or Ei-function, `\mathrm{Ei}(x)`. +The exponential integral is defined as + +.. math :: + + \mathrm{Ei}(x) = \int_{-\infty\,}^x \frac{e^t}{t} \, dt. + +When the integration range includes `t = 0`, the exponential +integral is interpreted as providing the Cauchy principal value. + +For real `x`, the Ei-function behaves roughly like +`\mathrm{Ei}(x) \approx \exp(x) + \log(|x|)`. + +The Ei-function is related to the more general family of exponential +integral functions denoted by `E_n`, which are available as :func:`~mpmath.expint`. + +**Basic examples** + +Some basic values and limits are:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> ei(0) + -inf + >>> ei(1) + 1.89511781635594 + >>> ei(inf) + +inf + >>> ei(-inf) + 0.0 + +For `x < 0`, the defining integral can be evaluated +numerically as a reference:: + + >>> ei(-4) + -0.00377935240984891 + >>> quad(lambda t: exp(t)/t, [-inf, -4]) + -0.00377935240984891 + +:func:`~mpmath.ei` supports complex arguments and arbitrary +precision evaluation:: + + >>> mp.dps = 50 + >>> ei(pi) + 10.928374389331410348638445906907535171566338835056 + >>> mp.dps = 25 + >>> ei(3+4j) + (-4.154091651642689822535359 + 4.294418620024357476985535j) + +**Related functions** + +The exponential integral is closely related to the logarithmic +integral. See :func:`~mpmath.li` for additional information. + +The exponential integral is related to the hyperbolic +and trigonometric integrals (see :func:`~mpmath.chi`, :func:`~mpmath.shi`, +:func:`~mpmath.ci`, :func:`~mpmath.si`) similarly to how the ordinary +exponential function is related to the hyperbolic and +trigonometric functions:: + + >>> mp.dps = 15 + >>> ei(3) + 9.93383257062542 + >>> chi(3) + shi(3) + 9.93383257062542 + >>> chop(ci(3j) - j*si(3j) - pi*j/2) + 9.93383257062542 + +Beware that logarithmic corrections, as in the last example +above, are required to obtain the correct branch in general. +For details, see [1]. + +The exponential integral is also a special case of the +hypergeometric function `\,_2F_2`:: + + >>> z = 0.6 + >>> z*hyper([1,1],[2,2],z) + (ln(z)-ln(1/z))/2 + euler + 0.769881289937359 + >>> ei(z) + 0.769881289937359 + +**References** + +1. Relations between Ei and other functions: + http://functions.wolfram.com/GammaBetaErf/ExpIntegralEi/27/01/ + +2. Abramowitz & Stegun, section 5: + http://people.math.sfu.ca/~cbm/aands/page_228.htm + +3. Asymptotic expansion for Ei: + http://mathworld.wolfram.com/En-Function.html +""" + +li = r""" +Computes the logarithmic integral or li-function +`\mathrm{li}(x)`, defined by + +.. math :: + + \mathrm{li}(x) = \int_0^x \frac{1}{\log t} \, dt + +The logarithmic integral has a singularity at `x = 1`. + +Alternatively, ``li(x, offset=True)`` computes the offset +logarithmic integral (used in number theory) + +.. math :: + + \mathrm{Li}(x) = \int_2^x \frac{1}{\log t} \, dt. + +These two functions are related via the simple identity +`\mathrm{Li}(x) = \mathrm{li}(x) - \mathrm{li}(2)`. + +The logarithmic integral should also not be confused with +the polylogarithm (also denoted by Li), which is implemented +as :func:`~mpmath.polylog`. + +**Examples** + +Some basic values and limits:: + + >>> from mpmath import * + >>> mp.dps = 30; mp.pretty = True + >>> li(0) + 0.0 + >>> li(1) + -inf + >>> li(1) + -inf + >>> li(2) + 1.04516378011749278484458888919 + >>> findroot(li, 2) + 1.45136923488338105028396848589 + >>> li(inf) + +inf + >>> li(2, offset=True) + 0.0 + >>> li(1, offset=True) + -inf + >>> li(0, offset=True) + -1.04516378011749278484458888919 + >>> li(10, offset=True) + 5.12043572466980515267839286347 + +The logarithmic integral can be evaluated for arbitrary +complex arguments:: + + >>> mp.dps = 20 + >>> li(3+4j) + (3.1343755504645775265 + 2.6769247817778742392j) + +The logarithmic integral is related to the exponential integral:: + + >>> ei(log(3)) + 2.1635885946671919729 + >>> li(3) + 2.1635885946671919729 + +The logarithmic integral grows like `O(x/\log(x))`:: + + >>> mp.dps = 15 + >>> x = 10**100 + >>> x/log(x) + 4.34294481903252e+97 + >>> li(x) + 4.3619719871407e+97 + +The prime number theorem states that the number of primes less +than `x` is asymptotic to `\mathrm{Li}(x)` (equivalently +`\mathrm{li}(x)`). For example, it is known that there are +exactly 1,925,320,391,606,803,968,923 prime numbers less than +`10^{23}` [1]. The logarithmic integral provides a very +accurate estimate:: + + >>> li(10**23, offset=True) + 1.92532039161405e+21 + +A definite integral is:: + + >>> quad(li, [0, 1]) + -0.693147180559945 + >>> -ln(2) + -0.693147180559945 + +**References** + +1. http://mathworld.wolfram.com/PrimeCountingFunction.html + +2. http://mathworld.wolfram.com/LogarithmicIntegral.html + +""" + +ci = r""" +Computes the cosine integral, + +.. math :: + + \mathrm{Ci}(x) = -\int_x^{\infty} \frac{\cos t}{t}\,dt + = \gamma + \log x + \int_0^x \frac{\cos t - 1}{t}\,dt + +**Examples** + +Some values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> ci(0) + -inf + >>> ci(1) + 0.3374039229009681346626462 + >>> ci(pi) + 0.07366791204642548599010096 + >>> ci(inf) + 0.0 + >>> ci(-inf) + (0.0 + 3.141592653589793238462643j) + >>> ci(2+3j) + (1.408292501520849518759125 - 2.983617742029605093121118j) + +The cosine integral behaves roughly like the sinc function +(see :func:`~mpmath.sinc`) for large real `x`:: + + >>> ci(10**10) + -4.875060251748226537857298e-11 + >>> sinc(10**10) + -4.875060250875106915277943e-11 + >>> chop(limit(ci, inf)) + 0.0 + +It has infinitely many roots on the positive real axis:: + + >>> findroot(ci, 1) + 0.6165054856207162337971104 + >>> findroot(ci, 2) + 3.384180422551186426397851 + +Evaluation is supported for `z` anywhere in the complex plane:: + + >>> ci(10**6*(1+j)) + (4.449410587611035724984376e+434287 + 9.75744874290013526417059e+434287j) + +We can evaluate the defining integral as a reference:: + + >>> mp.dps = 15 + >>> -quadosc(lambda t: cos(t)/t, [5, inf], omega=1) + -0.190029749656644 + >>> ci(5) + -0.190029749656644 + +Some infinite series can be evaluated using the +cosine integral:: + + >>> nsum(lambda k: (-1)**k/(fac(2*k)*(2*k)), [1,inf]) + -0.239811742000565 + >>> ci(1) - euler + -0.239811742000565 + +""" + +si = r""" +Computes the sine integral, + +.. math :: + + \mathrm{Si}(x) = \int_0^x \frac{\sin t}{t}\,dt. + +The sine integral is thus the antiderivative of the sinc +function (see :func:`~mpmath.sinc`). + +**Examples** + +Some values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> si(0) + 0.0 + >>> si(1) + 0.9460830703671830149413533 + >>> si(-1) + -0.9460830703671830149413533 + >>> si(pi) + 1.851937051982466170361053 + >>> si(inf) + 1.570796326794896619231322 + >>> si(-inf) + -1.570796326794896619231322 + >>> si(2+3j) + (4.547513889562289219853204 + 1.399196580646054789459839j) + +The sine integral approaches `\pi/2` for large real `x`:: + + >>> si(10**10) + 1.570796326707584656968511 + >>> pi/2 + 1.570796326794896619231322 + +Evaluation is supported for `z` anywhere in the complex plane:: + + >>> si(10**6*(1+j)) + (-9.75744874290013526417059e+434287 + 4.449410587611035724984376e+434287j) + +We can evaluate the defining integral as a reference:: + + >>> mp.dps = 15 + >>> quad(sinc, [0, 5]) + 1.54993124494467 + >>> si(5) + 1.54993124494467 + +Some infinite series can be evaluated using the +sine integral:: + + >>> nsum(lambda k: (-1)**k/(fac(2*k+1)*(2*k+1)), [0,inf]) + 0.946083070367183 + >>> si(1) + 0.946083070367183 + +""" + +chi = r""" +Computes the hyperbolic cosine integral, defined +in analogy with the cosine integral (see :func:`~mpmath.ci`) as + +.. math :: + + \mathrm{Chi}(x) = -\int_x^{\infty} \frac{\cosh t}{t}\,dt + = \gamma + \log x + \int_0^x \frac{\cosh t - 1}{t}\,dt + +Some values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> chi(0) + -inf + >>> chi(1) + 0.8378669409802082408946786 + >>> chi(inf) + +inf + >>> findroot(chi, 0.5) + 0.5238225713898644064509583 + >>> chi(2+3j) + (-0.1683628683277204662429321 + 2.625115880451325002151688j) + +Evaluation is supported for `z` anywhere in the complex plane:: + + >>> chi(10**6*(1+j)) + (4.449410587611035724984376e+434287 - 9.75744874290013526417059e+434287j) + +""" + +shi = r""" +Computes the hyperbolic sine integral, defined +in analogy with the sine integral (see :func:`~mpmath.si`) as + +.. math :: + + \mathrm{Shi}(x) = \int_0^x \frac{\sinh t}{t}\,dt. + +Some values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> shi(0) + 0.0 + >>> shi(1) + 1.057250875375728514571842 + >>> shi(-1) + -1.057250875375728514571842 + >>> shi(inf) + +inf + >>> shi(2+3j) + (-0.1931890762719198291678095 + 2.645432555362369624818525j) + +Evaluation is supported for `z` anywhere in the complex plane:: + + >>> shi(10**6*(1+j)) + (4.449410587611035724984376e+434287 - 9.75744874290013526417059e+434287j) + +""" + +fresnels = r""" +Computes the Fresnel sine integral + +.. math :: + + S(x) = \int_0^x \sin\left(\frac{\pi t^2}{2}\right) \,dt + +Note that some sources define this function +without the normalization factor `\pi/2`. + +**Examples** + +Some basic values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> fresnels(0) + 0.0 + >>> fresnels(inf) + 0.5 + >>> fresnels(-inf) + -0.5 + >>> fresnels(1) + 0.4382591473903547660767567 + >>> fresnels(1+2j) + (36.72546488399143842838788 + 15.58775110440458732748279j) + +Comparing with the definition:: + + >>> fresnels(3) + 0.4963129989673750360976123 + >>> quad(lambda t: sin(pi*t**2/2), [0,3]) + 0.4963129989673750360976123 +""" + +fresnelc = r""" +Computes the Fresnel cosine integral + +.. math :: + + C(x) = \int_0^x \cos\left(\frac{\pi t^2}{2}\right) \,dt + +Note that some sources define this function +without the normalization factor `\pi/2`. + +**Examples** + +Some basic values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> fresnelc(0) + 0.0 + >>> fresnelc(inf) + 0.5 + >>> fresnelc(-inf) + -0.5 + >>> fresnelc(1) + 0.7798934003768228294742064 + >>> fresnelc(1+2j) + (16.08787137412548041729489 - 36.22568799288165021578758j) + +Comparing with the definition:: + + >>> fresnelc(3) + 0.6057207892976856295561611 + >>> quad(lambda t: cos(pi*t**2/2), [0,3]) + 0.6057207892976856295561611 +""" + +airyai = r""" +Computes the Airy function `\operatorname{Ai}(z)`, which is +the solution of the Airy differential equation `f''(z) - z f(z) = 0` +with initial conditions + +.. math :: + + \operatorname{Ai}(0) = + \frac{1}{3^{2/3}\Gamma\left(\frac{2}{3}\right)} + + \operatorname{Ai}'(0) = + -\frac{1}{3^{1/3}\Gamma\left(\frac{1}{3}\right)}. + +Other common ways of defining the Ai-function include +integrals such as + +.. math :: + + \operatorname{Ai}(x) = \frac{1}{\pi} + \int_0^{\infty} \cos\left(\frac{1}{3}t^3+xt\right) dt + \qquad x \in \mathbb{R} + + \operatorname{Ai}(z) = \frac{\sqrt{3}}{2\pi} + \int_0^{\infty} + \exp\left(-\frac{t^3}{3}-\frac{z^3}{3t^3}\right) dt. + +The Ai-function is an entire function with a turning point, +behaving roughly like a slowly decaying sine wave for `z < 0` and +like a rapidly decreasing exponential for `z > 0`. +A second solution of the Airy differential equation +is given by `\operatorname{Bi}(z)` (see :func:`~mpmath.airybi`). + +Optionally, with *derivative=alpha*, :func:`airyai` can compute the +`\alpha`-th order fractional derivative with respect to `z`. +For `\alpha = n = 1,2,3,\ldots` this gives the derivative +`\operatorname{Ai}^{(n)}(z)`, and for `\alpha = -n = -1,-2,-3,\ldots` +this gives the `n`-fold iterated integral + +.. math :: + + f_0(z) = \operatorname{Ai}(z) + + f_n(z) = \int_0^z f_{n-1}(t) dt. + +The Ai-function has infinitely many zeros, all located along the +negative half of the real axis. They can be computed with +:func:`~mpmath.airyaizero`. + +**Plots** + +.. literalinclude :: /plots/ai.py +.. image :: /plots/ai.png +.. literalinclude :: /plots/ai_c.py +.. image :: /plots/ai_c.png + +**Basic examples** + +Limits and values include:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> airyai(0); 1/(power(3,'2/3')*gamma('2/3')) + 0.3550280538878172392600632 + 0.3550280538878172392600632 + >>> airyai(1) + 0.1352924163128814155241474 + >>> airyai(-1) + 0.5355608832923521187995166 + >>> airyai(inf); airyai(-inf) + 0.0 + 0.0 + +Evaluation is supported for large magnitudes of the argument:: + + >>> airyai(-100) + 0.1767533932395528780908311 + >>> airyai(100) + 2.634482152088184489550553e-291 + >>> airyai(50+50j) + (-5.31790195707456404099817e-68 - 1.163588003770709748720107e-67j) + >>> airyai(-50+50j) + (1.041242537363167632587245e+158 + 3.347525544923600321838281e+157j) + +Huge arguments are also fine:: + + >>> airyai(10**10) + 1.162235978298741779953693e-289529654602171 + >>> airyai(-10**10) + 0.0001736206448152818510510181 + >>> w = airyai(10**10*(1+j)) + >>> w.real + 5.711508683721355528322567e-186339621747698 + >>> w.imag + 1.867245506962312577848166e-186339621747697 + +The first root of the Ai-function is:: + + >>> findroot(airyai, -2) + -2.338107410459767038489197 + >>> airyaizero(1) + -2.338107410459767038489197 + +**Properties and relations** + +Verifying the Airy differential equation:: + + >>> for z in [-3.4, 0, 2.5, 1+2j]: + ... chop(airyai(z,2) - z*airyai(z)) + ... + 0.0 + 0.0 + 0.0 + 0.0 + +The first few terms of the Taylor series expansion around `z = 0` +(every third term is zero):: + + >>> nprint(taylor(airyai, 0, 5)) + [0.355028, -0.258819, 0.0, 0.0591713, -0.0215683, 0.0] + +The Airy functions satisfy the Wronskian relation +`\operatorname{Ai}(z) \operatorname{Bi}'(z) - +\operatorname{Ai}'(z) \operatorname{Bi}(z) = 1/\pi`:: + + >>> z = -0.5 + >>> airyai(z)*airybi(z,1) - airyai(z,1)*airybi(z) + 0.3183098861837906715377675 + >>> 1/pi + 0.3183098861837906715377675 + +The Airy functions can be expressed in terms of Bessel +functions of order `\pm 1/3`. For `\Re[z] \le 0`, we have:: + + >>> z = -3 + >>> airyai(z) + -0.3788142936776580743472439 + >>> y = 2*power(-z,'3/2')/3 + >>> (sqrt(-z) * (besselj('1/3',y) + besselj('-1/3',y)))/3 + -0.3788142936776580743472439 + +**Derivatives and integrals** + +Derivatives of the Ai-function (directly and using :func:`~mpmath.diff`):: + + >>> airyai(-3,1); diff(airyai,-3) + 0.3145837692165988136507873 + 0.3145837692165988136507873 + >>> airyai(-3,2); diff(airyai,-3,2) + 1.136442881032974223041732 + 1.136442881032974223041732 + >>> airyai(1000,1); diff(airyai,1000) + -2.943133917910336090459748e-9156 + -2.943133917910336090459748e-9156 + +Several derivatives at `z = 0`:: + + >>> airyai(0,0); airyai(0,1); airyai(0,2) + 0.3550280538878172392600632 + -0.2588194037928067984051836 + 0.0 + >>> airyai(0,3); airyai(0,4); airyai(0,5) + 0.3550280538878172392600632 + -0.5176388075856135968103671 + 0.0 + >>> airyai(0,15); airyai(0,16); airyai(0,17) + 1292.30211615165475090663 + -3188.655054727379756351861 + 0.0 + +The integral of the Ai-function:: + + >>> airyai(3,-1); quad(airyai, [0,3]) + 0.3299203760070217725002701 + 0.3299203760070217725002701 + >>> airyai(-10,-1); quad(airyai, [0,-10]) + -0.765698403134212917425148 + -0.765698403134212917425148 + +Integrals of high or fractional order:: + + >>> airyai(-2,0.5); differint(airyai,-2,0.5,0) + (0.0 + 0.2453596101351438273844725j) + (0.0 + 0.2453596101351438273844725j) + >>> airyai(-2,-4); differint(airyai,-2,-4,0) + 0.2939176441636809580339365 + 0.2939176441636809580339365 + >>> airyai(0,-1); airyai(0,-2); airyai(0,-3) + 0.0 + 0.0 + 0.0 + +Integrals of the Ai-function can be evaluated at limit points:: + + >>> airyai(-1000000,-1); airyai(-inf,-1) + -0.6666843728311539978751512 + -0.6666666666666666666666667 + >>> airyai(10,-1); airyai(+inf,-1) + 0.3333333332991690159427932 + 0.3333333333333333333333333 + >>> airyai(+inf,-2); airyai(+inf,-3) + +inf + +inf + >>> airyai(-1000000,-2); airyai(-inf,-2) + 666666.4078472650651209742 + +inf + >>> airyai(-1000000,-3); airyai(-inf,-3) + -333333074513.7520264995733 + -inf + +**References** + +1. [DLMF]_ Chapter 9: Airy and Related Functions +2. [WolframFunctions]_ section: Bessel-Type Functions + +""" + +airybi = r""" +Computes the Airy function `\operatorname{Bi}(z)`, which is +the solution of the Airy differential equation `f''(z) - z f(z) = 0` +with initial conditions + +.. math :: + + \operatorname{Bi}(0) = + \frac{1}{3^{1/6}\Gamma\left(\frac{2}{3}\right)} + + \operatorname{Bi}'(0) = + \frac{3^{1/6}}{\Gamma\left(\frac{1}{3}\right)}. + +Like the Ai-function (see :func:`~mpmath.airyai`), the Bi-function +is oscillatory for `z < 0`, but it grows rather than decreases +for `z > 0`. + +Optionally, as for :func:`~mpmath.airyai`, derivatives, integrals +and fractional derivatives can be computed with the *derivative* +parameter. + +The Bi-function has infinitely many zeros along the negative +half-axis, as well as complex zeros, which can all be computed +with :func:`~mpmath.airybizero`. + +**Plots** + +.. literalinclude :: /plots/bi.py +.. image :: /plots/bi.png +.. literalinclude :: /plots/bi_c.py +.. image :: /plots/bi_c.png + +**Basic examples** + +Limits and values include:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> airybi(0); 1/(power(3,'1/6')*gamma('2/3')) + 0.6149266274460007351509224 + 0.6149266274460007351509224 + >>> airybi(1) + 1.207423594952871259436379 + >>> airybi(-1) + 0.10399738949694461188869 + >>> airybi(inf); airybi(-inf) + +inf + 0.0 + +Evaluation is supported for large magnitudes of the argument:: + + >>> airybi(-100) + 0.02427388768016013160566747 + >>> airybi(100) + 6.041223996670201399005265e+288 + >>> airybi(50+50j) + (-5.322076267321435669290334e+63 + 1.478450291165243789749427e+65j) + >>> airybi(-50+50j) + (-3.347525544923600321838281e+157 + 1.041242537363167632587245e+158j) + +Huge arguments:: + + >>> airybi(10**10) + 1.369385787943539818688433e+289529654602165 + >>> airybi(-10**10) + 0.001775656141692932747610973 + >>> w = airybi(10**10*(1+j)) + >>> w.real + -6.559955931096196875845858e+186339621747689 + >>> w.imag + -6.822462726981357180929024e+186339621747690 + +The first real root of the Bi-function is:: + + >>> findroot(airybi, -1); airybizero(1) + -1.17371322270912792491998 + -1.17371322270912792491998 + +**Properties and relations** + +Verifying the Airy differential equation:: + + >>> for z in [-3.4, 0, 2.5, 1+2j]: + ... chop(airybi(z,2) - z*airybi(z)) + ... + 0.0 + 0.0 + 0.0 + 0.0 + +The first few terms of the Taylor series expansion around `z = 0` +(every third term is zero):: + + >>> nprint(taylor(airybi, 0, 5)) + [0.614927, 0.448288, 0.0, 0.102488, 0.0373574, 0.0] + +The Airy functions can be expressed in terms of Bessel +functions of order `\pm 1/3`. For `\Re[z] \le 0`, we have:: + + >>> z = -3 + >>> airybi(z) + -0.1982896263749265432206449 + >>> p = 2*power(-z,'3/2')/3 + >>> sqrt(-mpf(z)/3)*(besselj('-1/3',p) - besselj('1/3',p)) + -0.1982896263749265432206449 + +**Derivatives and integrals** + +Derivatives of the Bi-function (directly and using :func:`~mpmath.diff`):: + + >>> airybi(-3,1); diff(airybi,-3) + -0.675611222685258537668032 + -0.675611222685258537668032 + >>> airybi(-3,2); diff(airybi,-3,2) + 0.5948688791247796296619346 + 0.5948688791247796296619346 + >>> airybi(1000,1); diff(airybi,1000) + 1.710055114624614989262335e+9156 + 1.710055114624614989262335e+9156 + +Several derivatives at `z = 0`:: + + >>> airybi(0,0); airybi(0,1); airybi(0,2) + 0.6149266274460007351509224 + 0.4482883573538263579148237 + 0.0 + >>> airybi(0,3); airybi(0,4); airybi(0,5) + 0.6149266274460007351509224 + 0.8965767147076527158296474 + 0.0 + >>> airybi(0,15); airybi(0,16); airybi(0,17) + 2238.332923903442675949357 + 5522.912562599140729510628 + 0.0 + +The integral of the Bi-function:: + + >>> airybi(3,-1); quad(airybi, [0,3]) + 10.06200303130620056316655 + 10.06200303130620056316655 + >>> airybi(-10,-1); quad(airybi, [0,-10]) + -0.01504042480614002045135483 + -0.01504042480614002045135483 + +Integrals of high or fractional order:: + + >>> airybi(-2,0.5); differint(airybi, -2, 0.5, 0) + (0.0 + 0.5019859055341699223453257j) + (0.0 + 0.5019859055341699223453257j) + >>> airybi(-2,-4); differint(airybi,-2,-4,0) + 0.2809314599922447252139092 + 0.2809314599922447252139092 + >>> airybi(0,-1); airybi(0,-2); airybi(0,-3) + 0.0 + 0.0 + 0.0 + +Integrals of the Bi-function can be evaluated at limit points:: + + >>> airybi(-1000000,-1); airybi(-inf,-1) + 0.000002191261128063434047966873 + 0.0 + >>> airybi(10,-1); airybi(+inf,-1) + 147809803.1074067161675853 + +inf + >>> airybi(+inf,-2); airybi(+inf,-3) + +inf + +inf + >>> airybi(-1000000,-2); airybi(-inf,-2) + 0.4482883750599908479851085 + 0.4482883573538263579148237 + >>> gamma('2/3')*power(3,'2/3')/(2*pi) + 0.4482883573538263579148237 + >>> airybi(-100000,-3); airybi(-inf,-3) + -44828.52827206932872493133 + -inf + >>> airybi(-100000,-4); airybi(-inf,-4) + 2241411040.437759489540248 + +inf + +""" + +airyaizero = r""" +Gives the `k`-th zero of the Airy Ai-function, +i.e. the `k`-th number `a_k` ordered by magnitude for which +`\operatorname{Ai}(a_k) = 0`. + +Optionally, with *derivative=1*, the corresponding +zero `a'_k` of the derivative function, i.e. +`\operatorname{Ai}'(a'_k) = 0`, is computed. + +**Examples** + +Some values of `a_k`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> airyaizero(1) + -2.338107410459767038489197 + >>> airyaizero(2) + -4.087949444130970616636989 + >>> airyaizero(3) + -5.520559828095551059129856 + >>> airyaizero(1000) + -281.0315196125215528353364 + +Some values of `a'_k`:: + + >>> airyaizero(1,1) + -1.018792971647471089017325 + >>> airyaizero(2,1) + -3.248197582179836537875424 + >>> airyaizero(3,1) + -4.820099211178735639400616 + >>> airyaizero(1000,1) + -280.9378080358935070607097 + +Verification:: + + >>> chop(airyai(airyaizero(1))) + 0.0 + >>> chop(airyai(airyaizero(1,1),1)) + 0.0 + +""" + +airybizero = r""" +With *complex=False*, gives the `k`-th real zero of the Airy Bi-function, +i.e. the `k`-th number `b_k` ordered by magnitude for which +`\operatorname{Bi}(b_k) = 0`. + +With *complex=True*, gives the `k`-th complex zero in the upper +half plane `\beta_k`. Also the conjugate `\overline{\beta_k}` +is a zero. + +Optionally, with *derivative=1*, the corresponding +zero `b'_k` or `\beta'_k` of the derivative function, i.e. +`\operatorname{Bi}'(b'_k) = 0` or `\operatorname{Bi}'(\beta'_k) = 0`, +is computed. + +**Examples** + +Some values of `b_k`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> airybizero(1) + -1.17371322270912792491998 + >>> airybizero(2) + -3.271093302836352715680228 + >>> airybizero(3) + -4.830737841662015932667709 + >>> airybizero(1000) + -280.9378112034152401578834 + +Some values of `b_k`:: + + >>> airybizero(1,1) + -2.294439682614123246622459 + >>> airybizero(2,1) + -4.073155089071828215552369 + >>> airybizero(3,1) + -5.512395729663599496259593 + >>> airybizero(1000,1) + -281.0315164471118527161362 + +Some values of `\beta_k`:: + + >>> airybizero(1,complex=True) + (0.9775448867316206859469927 + 2.141290706038744575749139j) + >>> airybizero(2,complex=True) + (1.896775013895336346627217 + 3.627291764358919410440499j) + >>> airybizero(3,complex=True) + (2.633157739354946595708019 + 4.855468179979844983174628j) + >>> airybizero(1000,complex=True) + (140.4978560578493018899793 + 243.3907724215792121244867j) + +Some values of `\beta'_k`:: + + >>> airybizero(1,1,complex=True) + (0.2149470745374305676088329 + 1.100600143302797880647194j) + >>> airybizero(2,1,complex=True) + (1.458168309223507392028211 + 2.912249367458445419235083j) + >>> airybizero(3,1,complex=True) + (2.273760763013482299792362 + 4.254528549217097862167015j) + >>> airybizero(1000,1,complex=True) + (140.4509972835270559730423 + 243.3096175398562811896208j) + +Verification:: + + >>> chop(airybi(airybizero(1))) + 0.0 + >>> chop(airybi(airybizero(1,1),1)) + 0.0 + >>> u = airybizero(1,complex=True) + >>> chop(airybi(u)) + 0.0 + >>> chop(airybi(conj(u))) + 0.0 + +The complex zeros (in the upper and lower half-planes respectively) +asymptotically approach the rays `z = R \exp(\pm i \pi /3)`:: + + >>> arg(airybizero(1,complex=True)) + 1.142532510286334022305364 + >>> arg(airybizero(1000,complex=True)) + 1.047271114786212061583917 + >>> arg(airybizero(1000000,complex=True)) + 1.047197624741816183341355 + >>> pi/3 + 1.047197551196597746154214 + +""" + + +ellipk = r""" +Evaluates the complete elliptic integral of the first kind, +`K(m)`, defined by + +.. math :: + + K(m) = \int_0^{\pi/2} \frac{dt}{\sqrt{1-m \sin^2 t}} \, = \, + \frac{\pi}{2} \,_2F_1\left(\frac{1}{2}, \frac{1}{2}, 1, m\right). + +Note that the argument is the parameter `m = k^2`, +not the modulus `k` which is sometimes used. + +**Plots** + +.. literalinclude :: /plots/ellipk.py +.. image :: /plots/ellipk.png + +**Examples** + +Values and limits include:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> ellipk(0) + 1.570796326794896619231322 + >>> ellipk(inf) + (0.0 + 0.0j) + >>> ellipk(-inf) + 0.0 + >>> ellipk(1) + +inf + >>> ellipk(-1) + 1.31102877714605990523242 + >>> ellipk(2) + (1.31102877714605990523242 - 1.31102877714605990523242j) + +Verifying the defining integral and hypergeometric +representation:: + + >>> ellipk(0.5) + 1.85407467730137191843385 + >>> quad(lambda t: (1-0.5*sin(t)**2)**-0.5, [0, pi/2]) + 1.85407467730137191843385 + >>> pi/2*hyp2f1(0.5,0.5,1,0.5) + 1.85407467730137191843385 + +Evaluation is supported for arbitrary complex `m`:: + + >>> ellipk(3+4j) + (0.9111955638049650086562171 + 0.6313342832413452438845091j) + +A definite integral:: + + >>> quad(ellipk, [0, 1]) + 2.0 +""" + +agm = r""" +``agm(a, b)`` computes the arithmetic-geometric mean of `a` and +`b`, defined as the limit of the following iteration: + +.. math :: + + a_0 = a + + b_0 = b + + a_{n+1} = \frac{a_n+b_n}{2} + + b_{n+1} = \sqrt{a_n b_n} + +This function can be called with a single argument, computing +`\mathrm{agm}(a,1) = \mathrm{agm}(1,a)`. + +**Examples** + +It is a well-known theorem that the geometric mean of +two distinct positive numbers is less than the arithmetic +mean. It follows that the arithmetic-geometric mean lies +between the two means:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> a = mpf(3) + >>> b = mpf(4) + >>> sqrt(a*b) + 3.46410161513775 + >>> agm(a,b) + 3.48202767635957 + >>> (a+b)/2 + 3.5 + +The arithmetic-geometric mean is scale-invariant:: + + >>> agm(10*e, 10*pi) + 29.261085515723 + >>> 10*agm(e, pi) + 29.261085515723 + +As an order-of-magnitude estimate, `\mathrm{agm}(1,x) \approx x` +for large `x`:: + + >>> agm(10**10) + 643448704.760133 + >>> agm(10**50) + 1.34814309345871e+48 + +For tiny `x`, `\mathrm{agm}(1,x) \approx -\pi/(2 \log(x/4))`:: + + >>> agm('0.01') + 0.262166887202249 + >>> -pi/2/log('0.0025') + 0.262172347753122 + +The arithmetic-geometric mean can also be computed for complex +numbers:: + + >>> agm(3, 2+j) + (2.51055133276184 + 0.547394054060638j) + +The AGM iteration converges very quickly (each step doubles +the number of correct digits), so :func:`~mpmath.agm` supports efficient +high-precision evaluation:: + + >>> mp.dps = 10000 + >>> a = agm(1,2) + >>> str(a)[-10:] + '1679581912' + +**Mathematical relations** + +The arithmetic-geometric mean may be used to evaluate the +following two parametric definite integrals: + +.. math :: + + I_1 = \int_0^{\infty} + \frac{1}{\sqrt{(x^2+a^2)(x^2+b^2)}} \,dx + + I_2 = \int_0^{\pi/2} + \frac{1}{\sqrt{a^2 \cos^2(x) + b^2 \sin^2(x)}} \,dx + +We have:: + + >>> mp.dps = 15 + >>> a = 3 + >>> b = 4 + >>> f1 = lambda x: ((x**2+a**2)*(x**2+b**2))**-0.5 + >>> f2 = lambda x: ((a*cos(x))**2 + (b*sin(x))**2)**-0.5 + >>> quad(f1, [0, inf]) + 0.451115405388492 + >>> quad(f2, [0, pi/2]) + 0.451115405388492 + >>> pi/(2*agm(a,b)) + 0.451115405388492 + +A formula for `\Gamma(1/4)`:: + + >>> gamma(0.25) + 3.62560990822191 + >>> sqrt(2*sqrt(2*pi**3)/agm(1,sqrt(2))) + 3.62560990822191 + +**Possible issues** + +The branch cut chosen for complex `a` and `b` is somewhat +arbitrary. + +""" + +gegenbauer = r""" +Evaluates the Gegenbauer polynomial, or ultraspherical polynomial, + +.. math :: + + C_n^{(a)}(z) = {n+2a-1 \choose n} \,_2F_1\left(-n, n+2a; + a+\frac{1}{2}; \frac{1}{2}(1-z)\right). + +When `n` is a nonnegative integer, this formula gives a polynomial +in `z` of degree `n`, but all parameters are permitted to be +complex numbers. With `a = 1/2`, the Gegenbauer polynomial +reduces to a Legendre polynomial. + +**Examples** + +Evaluation for arbitrary arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> gegenbauer(3, 0.5, -10) + -2485.0 + >>> gegenbauer(1000, 10, 100) + 3.012757178975667428359374e+2322 + >>> gegenbauer(2+3j, -0.75, -1000j) + (-5038991.358609026523401901 + 9414549.285447104177860806j) + +Evaluation at negative integer orders:: + + >>> gegenbauer(-4, 2, 1.75) + -1.0 + >>> gegenbauer(-4, 3, 1.75) + 0.0 + >>> gegenbauer(-4, 2j, 1.75) + 0.0 + >>> gegenbauer(-7, 0.5, 3) + 8989.0 + +The Gegenbauer polynomials solve the differential equation:: + + >>> n, a = 4.5, 1+2j + >>> f = lambda z: gegenbauer(n, a, z) + >>> for z in [0, 0.75, -0.5j]: + ... chop((1-z**2)*diff(f,z,2) - (2*a+1)*z*diff(f,z) + n*(n+2*a)*f(z)) + ... + 0.0 + 0.0 + 0.0 + +The Gegenbauer polynomials have generating function +`(1-2zt+t^2)^{-a}`:: + + >>> a, z = 2.5, 1 + >>> taylor(lambda t: (1-2*z*t+t**2)**(-a), 0, 3) + [1.0, 5.0, 15.0, 35.0] + >>> [gegenbauer(n,a,z) for n in range(4)] + [1.0, 5.0, 15.0, 35.0] + +The Gegenbauer polynomials are orthogonal on `[-1, 1]` with respect +to the weight `(1-z^2)^{a-\frac{1}{2}}`:: + + >>> a, n, m = 2.5, 4, 5 + >>> Cn = lambda z: gegenbauer(n, a, z, zeroprec=1000) + >>> Cm = lambda z: gegenbauer(m, a, z, zeroprec=1000) + >>> chop(quad(lambda z: Cn(z)*Cm(z)*(1-z**2)*(a-0.5), [-1, 1])) + 0.0 +""" + +laguerre = r""" +Gives the generalized (associated) Laguerre polynomial, defined by + +.. math :: + + L_n^a(z) = \frac{\Gamma(n+b+1)}{\Gamma(b+1) \Gamma(n+1)} + \,_1F_1(-n, a+1, z). + +With `a = 0` and `n` a nonnegative integer, this reduces to an ordinary +Laguerre polynomial, the sequence of which begins +`L_0(z) = 1, L_1(z) = 1-z, L_2(z) = z^2-2z+1, \ldots`. + +The Laguerre polynomials are orthogonal with respect to the weight +`z^a e^{-z}` on `[0, \infty)`. + +**Plots** + +.. literalinclude :: /plots/laguerre.py +.. image :: /plots/laguerre.png + +**Examples** + +Evaluation for arbitrary arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> laguerre(5, 0, 0.25) + 0.03726399739583333333333333 + >>> laguerre(1+j, 0.5, 2+3j) + (4.474921610704496808379097 - 11.02058050372068958069241j) + >>> laguerre(2, 0, 10000) + 49980001.0 + >>> laguerre(2.5, 0, 10000) + -9.327764910194842158583189e+4328 + +The first few Laguerre polynomials, normalized to have integer +coefficients:: + + >>> for n in range(7): + ... chop(taylor(lambda z: fac(n)*laguerre(n, 0, z), 0, n)) + ... + [1.0] + [1.0, -1.0] + [2.0, -4.0, 1.0] + [6.0, -18.0, 9.0, -1.0] + [24.0, -96.0, 72.0, -16.0, 1.0] + [120.0, -600.0, 600.0, -200.0, 25.0, -1.0] + [720.0, -4320.0, 5400.0, -2400.0, 450.0, -36.0, 1.0] + +Verifying orthogonality:: + + >>> Lm = lambda t: laguerre(m,a,t) + >>> Ln = lambda t: laguerre(n,a,t) + >>> a, n, m = 2.5, 2, 3 + >>> chop(quad(lambda t: exp(-t)*t**a*Lm(t)*Ln(t), [0,inf])) + 0.0 + + +""" + +hermite = r""" +Evaluates the Hermite polynomial `H_n(z)`, which may be defined using +the recurrence + +.. math :: + + H_0(z) = 1 + + H_1(z) = 2z + + H_{n+1} = 2z H_n(z) - 2n H_{n-1}(z). + +The Hermite polynomials are orthogonal on `(-\infty, \infty)` with +respect to the weight `e^{-z^2}`. More generally, allowing arbitrary complex +values of `n`, the Hermite function `H_n(z)` is defined as + +.. math :: + + H_n(z) = (2z)^n \,_2F_0\left(-\frac{n}{2}, \frac{1-n}{2}, + -\frac{1}{z^2}\right) + +for `\Re{z} > 0`, or generally + +.. math :: + + H_n(z) = 2^n \sqrt{\pi} \left( + \frac{1}{\Gamma\left(\frac{1-n}{2}\right)} + \,_1F_1\left(-\frac{n}{2}, \frac{1}{2}, z^2\right) - + \frac{2z}{\Gamma\left(-\frac{n}{2}\right)} + \,_1F_1\left(\frac{1-n}{2}, \frac{3}{2}, z^2\right) + \right). + +**Plots** + +.. literalinclude :: /plots/hermite.py +.. image :: /plots/hermite.png + +**Examples** + +Evaluation for arbitrary arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> hermite(0, 10) + 1.0 + >>> hermite(1, 10); hermite(2, 10) + 20.0 + 398.0 + >>> hermite(10000, 2) + 4.950440066552087387515653e+19334 + >>> hermite(3, -10**8) + -7999999999999998800000000.0 + >>> hermite(-3, -10**8) + 1.675159751729877682920301e+4342944819032534 + >>> hermite(2+3j, -1+2j) + (-0.07652130602993513389421901 - 0.1084662449961914580276007j) + +Coefficients of the first few Hermite polynomials are:: + + >>> for n in range(7): + ... chop(taylor(lambda z: hermite(n, z), 0, n)) + ... + [1.0] + [0.0, 2.0] + [-2.0, 0.0, 4.0] + [0.0, -12.0, 0.0, 8.0] + [12.0, 0.0, -48.0, 0.0, 16.0] + [0.0, 120.0, 0.0, -160.0, 0.0, 32.0] + [-120.0, 0.0, 720.0, 0.0, -480.0, 0.0, 64.0] + +Values at `z = 0`:: + + >>> for n in range(-5, 9): + ... hermite(n, 0) + ... + 0.02769459142039868792653387 + 0.08333333333333333333333333 + 0.2215567313631895034122709 + 0.5 + 0.8862269254527580136490837 + 1.0 + 0.0 + -2.0 + 0.0 + 12.0 + 0.0 + -120.0 + 0.0 + 1680.0 + +Hermite functions satisfy the differential equation:: + + >>> n = 4 + >>> f = lambda z: hermite(n, z) + >>> z = 1.5 + >>> chop(diff(f,z,2) - 2*z*diff(f,z) + 2*n*f(z)) + 0.0 + +Verifying orthogonality:: + + >>> chop(quad(lambda t: hermite(2,t)*hermite(4,t)*exp(-t**2), [-inf,inf])) + 0.0 + +""" + +jacobi = r""" +``jacobi(n, a, b, x)`` evaluates the Jacobi polynomial +`P_n^{(a,b)}(x)`. The Jacobi polynomials are a special +case of the hypergeometric function `\,_2F_1` given by: + +.. math :: + + P_n^{(a,b)}(x) = {n+a \choose n} + \,_2F_1\left(-n,1+a+b+n,a+1,\frac{1-x}{2}\right). + +Note that this definition generalizes to nonintegral values +of `n`. When `n` is an integer, the hypergeometric series +terminates after a finite number of terms, giving +a polynomial in `x`. + +**Evaluation of Jacobi polynomials** + +A special evaluation is `P_n^{(a,b)}(1) = {n+a \choose n}`:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> jacobi(4, 0.5, 0.25, 1) + 2.4609375 + >>> binomial(4+0.5, 4) + 2.4609375 + +A Jacobi polynomial of degree `n` is equal to its +Taylor polynomial of degree `n`. The explicit +coefficients of Jacobi polynomials can therefore +be recovered easily using :func:`~mpmath.taylor`:: + + >>> for n in range(5): + ... nprint(taylor(lambda x: jacobi(n,1,2,x), 0, n)) + ... + [1.0] + [-0.5, 2.5] + [-0.75, -1.5, 5.25] + [0.5, -3.5, -3.5, 10.5] + [0.625, 2.5, -11.25, -7.5, 20.625] + +For nonintegral `n`, the Jacobi "polynomial" is no longer +a polynomial:: + + >>> nprint(taylor(lambda x: jacobi(0.5,1,2,x), 0, 4)) + [0.309983, 1.84119, -1.26933, 1.26699, -1.34808] + +**Orthogonality** + +The Jacobi polynomials are orthogonal on the interval +`[-1, 1]` with respect to the weight function +`w(x) = (1-x)^a (1+x)^b`. That is, +`w(x) P_n^{(a,b)}(x) P_m^{(a,b)}(x)` integrates to +zero if `m \ne n` and to a nonzero number if `m = n`. + +The orthogonality is easy to verify using numerical +quadrature:: + + >>> P = jacobi + >>> f = lambda x: (1-x)**a * (1+x)**b * P(m,a,b,x) * P(n,a,b,x) + >>> a = 2 + >>> b = 3 + >>> m, n = 3, 4 + >>> chop(quad(f, [-1, 1]), 1) + 0.0 + >>> m, n = 4, 4 + >>> quad(f, [-1, 1]) + 1.9047619047619 + +**Differential equation** + +The Jacobi polynomials are solutions of the differential +equation + +.. math :: + + (1-x^2) y'' + (b-a-(a+b+2)x) y' + n (n+a+b+1) y = 0. + +We can verify that :func:`~mpmath.jacobi` approximately satisfies +this equation:: + + >>> from mpmath import * + >>> mp.dps = 15 + >>> a = 2.5 + >>> b = 4 + >>> n = 3 + >>> y = lambda x: jacobi(n,a,b,x) + >>> x = pi + >>> A0 = n*(n+a+b+1)*y(x) + >>> A1 = (b-a-(a+b+2)*x)*diff(y,x) + >>> A2 = (1-x**2)*diff(y,x,2) + >>> nprint(A2 + A1 + A0, 1) + 4.0e-12 + +The difference of order `10^{-12}` is as close to zero as +it could be at 15-digit working precision, since the terms +are large:: + + >>> A0, A1, A2 + (26560.2328981879, -21503.7641037294, -5056.46879445852) + +""" + +legendre = r""" +``legendre(n, x)`` evaluates the Legendre polynomial `P_n(x)`. +The Legendre polynomials are given by the formula + +.. math :: + + P_n(x) = \frac{1}{2^n n!} \frac{d^n}{dx^n} (x^2 -1)^n. + +Alternatively, they can be computed recursively using + +.. math :: + + P_0(x) = 1 + + P_1(x) = x + + (n+1) P_{n+1}(x) = (2n+1) x P_n(x) - n P_{n-1}(x). + +A third definition is in terms of the hypergeometric function +`\,_2F_1`, whereby they can be generalized to arbitrary `n`: + +.. math :: + + P_n(x) = \,_2F_1\left(-n, n+1, 1, \frac{1-x}{2}\right) + +**Plots** + +.. literalinclude :: /plots/legendre.py +.. image :: /plots/legendre.png + +**Basic evaluation** + +The Legendre polynomials assume fixed values at the points +`x = -1` and `x = 1`:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> nprint([legendre(n, 1) for n in range(6)]) + [1.0, 1.0, 1.0, 1.0, 1.0, 1.0] + >>> nprint([legendre(n, -1) for n in range(6)]) + [1.0, -1.0, 1.0, -1.0, 1.0, -1.0] + +The coefficients of Legendre polynomials can be recovered +using degree-`n` Taylor expansion:: + + >>> for n in range(5): + ... nprint(chop(taylor(lambda x: legendre(n, x), 0, n))) + ... + [1.0] + [0.0, 1.0] + [-0.5, 0.0, 1.5] + [0.0, -1.5, 0.0, 2.5] + [0.375, 0.0, -3.75, 0.0, 4.375] + +The roots of Legendre polynomials are located symmetrically +on the interval `[-1, 1]`:: + + >>> for n in range(5): + ... nprint(polyroots(taylor(lambda x: legendre(n, x), 0, n)[::-1])) + ... + [] + [0.0] + [-0.57735, 0.57735] + [-0.774597, 0.0, 0.774597] + [-0.861136, -0.339981, 0.339981, 0.861136] + +An example of an evaluation for arbitrary `n`:: + + >>> legendre(0.75, 2+4j) + (1.94952805264875 + 2.1071073099422j) + +**Orthogonality** + +The Legendre polynomials are orthogonal on `[-1, 1]` with respect +to the trivial weight `w(x) = 1`. That is, `P_m(x) P_n(x)` +integrates to zero if `m \ne n` and to `2/(2n+1)` if `m = n`:: + + >>> m, n = 3, 4 + >>> quad(lambda x: legendre(m,x)*legendre(n,x), [-1, 1]) + 0.0 + >>> m, n = 4, 4 + >>> quad(lambda x: legendre(m,x)*legendre(n,x), [-1, 1]) + 0.222222222222222 + +**Differential equation** + +The Legendre polynomials satisfy the differential equation + +.. math :: + + ((1-x^2) y')' + n(n+1) y' = 0. + +We can verify this numerically:: + + >>> n = 3.6 + >>> x = 0.73 + >>> P = legendre + >>> A = diff(lambda t: (1-t**2)*diff(lambda u: P(n,u), t), x) + >>> B = n*(n+1)*P(n,x) + >>> nprint(A+B,1) + 9.0e-16 + +""" + + +legenp = r""" +Calculates the (associated) Legendre function of the first kind of +degree *n* and order *m*, `P_n^m(z)`. Taking `m = 0` gives the ordinary +Legendre function of the first kind, `P_n(z)`. The parameters may be +complex numbers. + +In terms of the Gauss hypergeometric function, the (associated) Legendre +function is defined as + +.. math :: + + P_n^m(z) = \frac{1}{\Gamma(1-m)} \frac{(1+z)^{m/2}}{(1-z)^{m/2}} + \,_2F_1\left(-n, n+1, 1-m, \frac{1-z}{2}\right). + +With *type=3* instead of *type=2*, the alternative +definition + +.. math :: + + \hat{P}_n^m(z) = \frac{1}{\Gamma(1-m)} \frac{(z+1)^{m/2}}{(z-1)^{m/2}} + \,_2F_1\left(-n, n+1, 1-m, \frac{1-z}{2}\right). + +is used. These functions correspond respectively to ``LegendreP[n,m,2,z]`` +and ``LegendreP[n,m,3,z]`` in Mathematica. + +The general solution of the (associated) Legendre differential equation + +.. math :: + + (1-z^2) f''(z) - 2zf'(z) + \left(n(n+1)-\frac{m^2}{1-z^2}\right)f(z) = 0 + +is given by `C_1 P_n^m(z) + C_2 Q_n^m(z)` for arbitrary constants +`C_1`, `C_2`, where `Q_n^m(z)` is a Legendre function of the +second kind as implemented by :func:`~mpmath.legenq`. + +**Examples** + +Evaluation for arbitrary parameters and arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> legenp(2, 0, 10); legendre(2, 10) + 149.5 + 149.5 + >>> legenp(-2, 0.5, 2.5) + (1.972260393822275434196053 - 1.972260393822275434196053j) + >>> legenp(2+3j, 1-j, -0.5+4j) + (-3.335677248386698208736542 - 5.663270217461022307645625j) + >>> chop(legenp(3, 2, -1.5, type=2)) + 28.125 + >>> chop(legenp(3, 2, -1.5, type=3)) + -28.125 + +Verifying the associated Legendre differential equation:: + + >>> n, m = 2, -0.5 + >>> C1, C2 = 1, -3 + >>> f = lambda z: C1*legenp(n,m,z) + C2*legenq(n,m,z) + >>> deq = lambda z: (1-z**2)*diff(f,z,2) - 2*z*diff(f,z) + \ + ... (n*(n+1)-m**2/(1-z**2))*f(z) + >>> for z in [0, 2, -1.5, 0.5+2j]: + ... chop(deq(mpmathify(z))) + ... + 0.0 + 0.0 + 0.0 + 0.0 +""" + +legenq = r""" +Calculates the (associated) Legendre function of the second kind of +degree *n* and order *m*, `Q_n^m(z)`. Taking `m = 0` gives the ordinary +Legendre function of the second kind, `Q_n(z)`. The parameters may be +complex numbers. + +The Legendre functions of the second kind give a second set of +solutions to the (associated) Legendre differential equation. +(See :func:`~mpmath.legenp`.) +Unlike the Legendre functions of the first kind, they are not +polynomials of `z` for integer `n`, `m` but rational or logarithmic +functions with poles at `z = \pm 1`. + +There are various ways to define Legendre functions of +the second kind, giving rise to different complex structure. +A version can be selected using the *type* keyword argument. +The *type=2* and *type=3* functions are given respectively by + +.. math :: + + Q_n^m(z) = \frac{\pi}{2 \sin(\pi m)} + \left( \cos(\pi m) P_n^m(z) - + \frac{\Gamma(1+m+n)}{\Gamma(1-m+n)} P_n^{-m}(z)\right) + + \hat{Q}_n^m(z) = \frac{\pi}{2 \sin(\pi m)} e^{\pi i m} + \left( \hat{P}_n^m(z) - + \frac{\Gamma(1+m+n)}{\Gamma(1-m+n)} \hat{P}_n^{-m}(z)\right) + +where `P` and `\hat{P}` are the *type=2* and *type=3* Legendre functions +of the first kind. The formulas above should be understood as limits +when `m` is an integer. + +These functions correspond to ``LegendreQ[n,m,2,z]`` (or ``LegendreQ[n,m,z]``) +and ``LegendreQ[n,m,3,z]`` in Mathematica. The *type=3* function +is essentially the same as the function defined in +Abramowitz & Stegun (eq. 8.1.3) but with `(z+1)^{m/2}(z-1)^{m/2}` instead +of `(z^2-1)^{m/2}`, giving slightly different branches. + +**Examples** + +Evaluation for arbitrary parameters and arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> legenq(2, 0, 0.5) + -0.8186632680417568557122028 + >>> legenq(-1.5, -2, 2.5) + (0.6655964618250228714288277 + 0.3937692045497259717762649j) + >>> legenq(2-j, 3+4j, -6+5j) + (-10001.95256487468541686564 - 6011.691337610097577791134j) + +Different versions of the function:: + + >>> legenq(2, 1, 0.5) + 0.7298060598018049369381857 + >>> legenq(2, 1, 1.5) + (-7.902916572420817192300921 + 0.1998650072605976600724502j) + >>> legenq(2, 1, 0.5, type=3) + (2.040524284763495081918338 - 0.7298060598018049369381857j) + >>> chop(legenq(2, 1, 1.5, type=3)) + -0.1998650072605976600724502 + +""" + +chebyt = r""" +``chebyt(n, x)`` evaluates the Chebyshev polynomial of the first +kind `T_n(x)`, defined by the identity + +.. math :: + + T_n(\cos x) = \cos(n x). + +The Chebyshev polynomials of the first kind are a special +case of the Jacobi polynomials, and by extension of the +hypergeometric function `\,_2F_1`. They can thus also be +evaluated for nonintegral `n`. + +**Plots** + +.. literalinclude :: /plots/chebyt.py +.. image :: /plots/chebyt.png + +**Basic evaluation** + +The coefficients of the `n`-th polynomial can be recovered +using using degree-`n` Taylor expansion:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> for n in range(5): + ... nprint(chop(taylor(lambda x: chebyt(n, x), 0, n))) + ... + [1.0] + [0.0, 1.0] + [-1.0, 0.0, 2.0] + [0.0, -3.0, 0.0, 4.0] + [1.0, 0.0, -8.0, 0.0, 8.0] + +**Orthogonality** + +The Chebyshev polynomials of the first kind are orthogonal +on the interval `[-1, 1]` with respect to the weight +function `w(x) = 1/\sqrt{1-x^2}`:: + + >>> f = lambda x: chebyt(m,x)*chebyt(n,x)/sqrt(1-x**2) + >>> m, n = 3, 4 + >>> nprint(quad(f, [-1, 1]),1) + 0.0 + >>> m, n = 4, 4 + >>> quad(f, [-1, 1]) + 1.57079632596448 + +""" + +chebyu = r""" +``chebyu(n, x)`` evaluates the Chebyshev polynomial of the second +kind `U_n(x)`, defined by the identity + +.. math :: + + U_n(\cos x) = \frac{\sin((n+1)x)}{\sin(x)}. + +The Chebyshev polynomials of the second kind are a special +case of the Jacobi polynomials, and by extension of the +hypergeometric function `\,_2F_1`. They can thus also be +evaluated for nonintegral `n`. + +**Plots** + +.. literalinclude :: /plots/chebyu.py +.. image :: /plots/chebyu.png + +**Basic evaluation** + +The coefficients of the `n`-th polynomial can be recovered +using using degree-`n` Taylor expansion:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> for n in range(5): + ... nprint(chop(taylor(lambda x: chebyu(n, x), 0, n))) + ... + [1.0] + [0.0, 2.0] + [-1.0, 0.0, 4.0] + [0.0, -4.0, 0.0, 8.0] + [1.0, 0.0, -12.0, 0.0, 16.0] + +**Orthogonality** + +The Chebyshev polynomials of the second kind are orthogonal +on the interval `[-1, 1]` with respect to the weight +function `w(x) = \sqrt{1-x^2}`:: + + >>> f = lambda x: chebyu(m,x)*chebyu(n,x)*sqrt(1-x**2) + >>> m, n = 3, 4 + >>> quad(f, [-1, 1]) + 0.0 + >>> m, n = 4, 4 + >>> quad(f, [-1, 1]) + 1.5707963267949 +""" + +besselj = r""" +``besselj(n, x, derivative=0)`` gives the Bessel function of the first kind +`J_n(x)`. Bessel functions of the first kind are defined as +solutions of the differential equation + +.. math :: + + x^2 y'' + x y' + (x^2 - n^2) y = 0 + +which appears, among other things, when solving the radial +part of Laplace's equation in cylindrical coordinates. This +equation has two solutions for given `n`, where the +`J_n`-function is the solution that is nonsingular at `x = 0`. +For positive integer `n`, `J_n(x)` behaves roughly like a sine +(odd `n`) or cosine (even `n`) multiplied by a magnitude factor +that decays slowly as `x \to \pm\infty`. + +Generally, `J_n` is a special case of the hypergeometric +function `\,_0F_1`: + +.. math :: + + J_n(x) = \frac{x^n}{2^n \Gamma(n+1)} + \,_0F_1\left(n+1,-\frac{x^2}{4}\right) + +With *derivative* = `m \ne 0`, the `m`-th derivative + +.. math :: + + \frac{d^m}{dx^m} J_n(x) + +is computed. + +**Plots** + +.. literalinclude :: /plots/besselj.py +.. image :: /plots/besselj.png +.. literalinclude :: /plots/besselj_c.py +.. image :: /plots/besselj_c.png + +**Examples** + +Evaluation is supported for arbitrary arguments, and at +arbitrary precision:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> besselj(2, 1000) + -0.024777229528606 + >>> besselj(4, 0.75) + 0.000801070086542314 + >>> besselj(2, 1000j) + (-2.48071721019185e+432 + 6.41567059811949e-437j) + >>> mp.dps = 25 + >>> besselj(0.75j, 3+4j) + (-2.778118364828153309919653 - 1.5863603889018621585533j) + >>> mp.dps = 50 + >>> besselj(1, pi) + 0.28461534317975275734531059968613140570981118184947 + +Arguments may be large:: + + >>> mp.dps = 25 + >>> besselj(0, 10000) + -0.007096160353388801477265164 + >>> besselj(0, 10**10) + 0.000002175591750246891726859055 + >>> besselj(2, 10**100) + 7.337048736538615712436929e-51 + >>> besselj(2, 10**5*j) + (-3.540725411970948860173735e+43426 + 4.4949812409615803110051e-43433j) + +The Bessel functions of the first kind satisfy simple +symmetries around `x = 0`:: + + >>> mp.dps = 15 + >>> nprint([besselj(n,0) for n in range(5)]) + [1.0, 0.0, 0.0, 0.0, 0.0] + >>> nprint([besselj(n,pi) for n in range(5)]) + [-0.304242, 0.284615, 0.485434, 0.333458, 0.151425] + >>> nprint([besselj(n,-pi) for n in range(5)]) + [-0.304242, -0.284615, 0.485434, -0.333458, 0.151425] + +Roots of Bessel functions are often used:: + + >>> nprint([findroot(j0, k) for k in [2, 5, 8, 11, 14]]) + [2.40483, 5.52008, 8.65373, 11.7915, 14.9309] + >>> nprint([findroot(j1, k) for k in [3, 7, 10, 13, 16]]) + [3.83171, 7.01559, 10.1735, 13.3237, 16.4706] + +The roots are not periodic, but the distance between successive +roots asymptotically approaches `2 \pi`. Bessel functions of +the first kind have the following normalization:: + + >>> quadosc(j0, [0, inf], period=2*pi) + 1.0 + >>> quadosc(j1, [0, inf], period=2*pi) + 1.0 + +For `n = 1/2` or `n = -1/2`, the Bessel function reduces to a +trigonometric function:: + + >>> x = 10 + >>> besselj(0.5, x), sqrt(2/(pi*x))*sin(x) + (-0.13726373575505, -0.13726373575505) + >>> besselj(-0.5, x), sqrt(2/(pi*x))*cos(x) + (-0.211708866331398, -0.211708866331398) + +Derivatives of any order can be computed (negative orders +correspond to integration):: + + >>> mp.dps = 25 + >>> besselj(0, 7.5, 1) + -0.1352484275797055051822405 + >>> diff(lambda x: besselj(0,x), 7.5) + -0.1352484275797055051822405 + >>> besselj(0, 7.5, 10) + -0.1377811164763244890135677 + >>> diff(lambda x: besselj(0,x), 7.5, 10) + -0.1377811164763244890135677 + >>> besselj(0,7.5,-1) - besselj(0,3.5,-1) + -0.1241343240399987693521378 + >>> quad(j0, [3.5, 7.5]) + -0.1241343240399987693521378 + +Differentiation with a noninteger order gives the fractional derivative +in the sense of the Riemann-Liouville differintegral, as computed by +:func:`~mpmath.differint`:: + + >>> mp.dps = 15 + >>> besselj(1, 3.5, 0.75) + -0.385977722939384 + >>> differint(lambda x: besselj(1, x), 3.5, 0.75) + -0.385977722939384 + +""" + +besseli = r""" +``besseli(n, x, derivative=0)`` gives the modified Bessel function of the +first kind, + +.. math :: + + I_n(x) = i^{-n} J_n(ix). + +With *derivative* = `m \ne 0`, the `m`-th derivative + +.. math :: + + \frac{d^m}{dx^m} I_n(x) + +is computed. + +**Plots** + +.. literalinclude :: /plots/besseli.py +.. image :: /plots/besseli.png +.. literalinclude :: /plots/besseli_c.py +.. image :: /plots/besseli_c.png + +**Examples** + +Some values of `I_n(x)`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> besseli(0,0) + 1.0 + >>> besseli(1,0) + 0.0 + >>> besseli(0,1) + 1.266065877752008335598245 + >>> besseli(3.5, 2+3j) + (-0.2904369752642538144289025 - 0.4469098397654815837307006j) + +Arguments may be large:: + + >>> besseli(2, 1000) + 2.480717210191852440616782e+432 + >>> besseli(2, 10**10) + 4.299602851624027900335391e+4342944813 + >>> besseli(2, 6000+10000j) + (-2.114650753239580827144204e+2603 + 4.385040221241629041351886e+2602j) + +For integers `n`, the following integral representation holds:: + + >>> mp.dps = 15 + >>> n = 3 + >>> x = 2.3 + >>> quad(lambda t: exp(x*cos(t))*cos(n*t), [0,pi])/pi + 0.349223221159309 + >>> besseli(n,x) + 0.349223221159309 + +Derivatives and antiderivatives of any order can be computed:: + + >>> mp.dps = 25 + >>> besseli(2, 7.5, 1) + 195.8229038931399062565883 + >>> diff(lambda x: besseli(2,x), 7.5) + 195.8229038931399062565883 + >>> besseli(2, 7.5, 10) + 153.3296508971734525525176 + >>> diff(lambda x: besseli(2,x), 7.5, 10) + 153.3296508971734525525176 + >>> besseli(2,7.5,-1) - besseli(2,3.5,-1) + 202.5043900051930141956876 + >>> quad(lambda x: besseli(2,x), [3.5, 7.5]) + 202.5043900051930141956876 + +""" + +bessely = r""" +``bessely(n, x, derivative=0)`` gives the Bessel function of the second kind, + +.. math :: + + Y_n(x) = \frac{J_n(x) \cos(\pi n) - J_{-n}(x)}{\sin(\pi n)}. + +For `n` an integer, this formula should be understood as a +limit. With *derivative* = `m \ne 0`, the `m`-th derivative + +.. math :: + + \frac{d^m}{dx^m} Y_n(x) + +is computed. + +**Plots** + +.. literalinclude :: /plots/bessely.py +.. image :: /plots/bessely.png +.. literalinclude :: /plots/bessely_c.py +.. image :: /plots/bessely_c.png + +**Examples** + +Some values of `Y_n(x)`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> bessely(0,0), bessely(1,0), bessely(2,0) + (-inf, -inf, -inf) + >>> bessely(1, pi) + 0.3588729167767189594679827 + >>> bessely(0.5, 3+4j) + (9.242861436961450520325216 - 3.085042824915332562522402j) + +Arguments may be large:: + + >>> bessely(0, 10000) + 0.00364780555898660588668872 + >>> bessely(2.5, 10**50) + -4.8952500412050989295774e-26 + >>> bessely(2.5, -10**50) + (0.0 + 4.8952500412050989295774e-26j) + +Derivatives and antiderivatives of any order can be computed:: + + >>> bessely(2, 3.5, 1) + 0.3842618820422660066089231 + >>> diff(lambda x: bessely(2, x), 3.5) + 0.3842618820422660066089231 + >>> bessely(0.5, 3.5, 1) + -0.2066598304156764337900417 + >>> diff(lambda x: bessely(0.5, x), 3.5) + -0.2066598304156764337900417 + >>> diff(lambda x: bessely(2, x), 0.5, 10) + -208173867409.5547350101511 + >>> bessely(2, 0.5, 10) + -208173867409.5547350101511 + >>> bessely(2, 100.5, 100) + 0.02668487547301372334849043 + >>> quad(lambda x: bessely(2,x), [1,3]) + -1.377046859093181969213262 + >>> bessely(2,3,-1) - bessely(2,1,-1) + -1.377046859093181969213262 + +""" + +besselk = r""" +``besselk(n, x)`` gives the modified Bessel function of the +second kind, + +.. math :: + + K_n(x) = \frac{\pi}{2} \frac{I_{-n}(x)-I_{n}(x)}{\sin(\pi n)} + +For `n` an integer, this formula should be understood as a +limit. + +**Plots** + +.. literalinclude :: /plots/besselk.py +.. image :: /plots/besselk.png +.. literalinclude :: /plots/besselk_c.py +.. image :: /plots/besselk_c.png + +**Examples** + +Evaluation is supported for arbitrary complex arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> besselk(0,1) + 0.4210244382407083333356274 + >>> besselk(0, -1) + (0.4210244382407083333356274 - 3.97746326050642263725661j) + >>> besselk(3.5, 2+3j) + (-0.02090732889633760668464128 + 0.2464022641351420167819697j) + >>> besselk(2+3j, 0.5) + (0.9615816021726349402626083 + 0.1918250181801757416908224j) + +Arguments may be large:: + + >>> besselk(0, 100) + 4.656628229175902018939005e-45 + >>> besselk(1, 10**6) + 4.131967049321725588398296e-434298 + >>> besselk(1, 10**6*j) + (0.001140348428252385844876706 - 0.0005200017201681152909000961j) + >>> besselk(4.5, fmul(10**50, j, exact=True)) + (1.561034538142413947789221e-26 + 1.243554598118700063281496e-25j) + +The point `x = 0` is a singularity (logarithmic if `n = 0`):: + + >>> besselk(0,0) + +inf + >>> besselk(1,0) + +inf + >>> for n in range(-4, 5): + ... print(besselk(n, '1e-1000')) + ... + 4.8e+4001 + 8.0e+3000 + 2.0e+2000 + 1.0e+1000 + 2302.701024509704096466802 + 1.0e+1000 + 2.0e+2000 + 8.0e+3000 + 4.8e+4001 + +""" + +hankel1 = r""" +``hankel1(n,x)`` computes the Hankel function of the first kind, +which is the complex combination of Bessel functions given by + +.. math :: + + H_n^{(1)}(x) = J_n(x) + i Y_n(x). + +**Plots** + +.. literalinclude :: /plots/hankel1.py +.. image :: /plots/hankel1.png +.. literalinclude :: /plots/hankel1_c.py +.. image :: /plots/hankel1_c.png + +**Examples** + +The Hankel function is generally complex-valued:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> hankel1(2, pi) + (0.4854339326315091097054957 - 0.0999007139290278787734903j) + >>> hankel1(3.5, pi) + (0.2340002029630507922628888 - 0.6419643823412927142424049j) +""" + +hankel2 = r""" +``hankel2(n,x)`` computes the Hankel function of the second kind, +which is the complex combination of Bessel functions given by + +.. math :: + + H_n^{(2)}(x) = J_n(x) - i Y_n(x). + +**Plots** + +.. literalinclude :: /plots/hankel2.py +.. image :: /plots/hankel2.png +.. literalinclude :: /plots/hankel2_c.py +.. image :: /plots/hankel2_c.png + +**Examples** + +The Hankel function is generally complex-valued:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> hankel2(2, pi) + (0.4854339326315091097054957 + 0.0999007139290278787734903j) + >>> hankel2(3.5, pi) + (0.2340002029630507922628888 + 0.6419643823412927142424049j) +""" + +lambertw = r""" +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 `W_k(z)`, indexed by `k \in \mathbb{Z}`. Each branch +gives a different solution `w` of the equation `z = w \exp(w)`. +All branches are supported by :func:`~mpmath.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`. + +The definition, implementation and choice of branches +is based on [Corless]_. + +**Plots** + +.. literalinclude :: /plots/lambertw.py +.. image :: /plots/lambertw.png +.. literalinclude :: /plots/lambertw_c.py +.. image :: /plots/lambertw_c.png + +**Basic examples** + +The Lambert W function is the inverse of `w \exp(w)`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> w = lambertw(1) + >>> w + 0.5671432904097838729999687 + >>> w*exp(w) + 1.0 + +Any branch gives a valid inverse:: + + >>> w = lambertw(1, k=3) + >>> w + (-2.853581755409037807206819 + 17.11353553941214591260783j) + >>> w = lambertw(1, k=25) + >>> w + (-5.047020464221569709378686 + 155.4763860949415867162066j) + >>> chop(w*exp(w)) + 1.0 + +**Applications to equation-solving** + +The Lambert W function may be used to solve various kinds of +equations, such as finding the value of the infinite power +tower `z^{z^{z^{\ldots}}}`:: + + >>> def tower(z, n): + ... if n == 0: + ... return z + ... return z ** tower(z, n-1) + ... + >>> tower(mpf(0.5), 100) + 0.6411857445049859844862005 + >>> -lambertw(-log(0.5))/log(0.5) + 0.6411857445049859844862005 + +**Properties** + +The Lambert W function grows roughly like the natural logarithm +for large arguments:: + + >>> lambertw(1000); log(1000) + 5.249602852401596227126056 + 6.907755278982137052053974 + >>> lambertw(10**100); log(10**100) + 224.8431064451185015393731 + 230.2585092994045684017991 + +The principal branch of the Lambert W function has a rational +Taylor series expansion around `z = 0`:: + + >>> nprint(taylor(lambertw, 0, 6), 10) + [0.0, 1.0, -1.0, 1.5, -2.666666667, 5.208333333, -10.8] + +Some special values and limits are:: + + >>> lambertw(0) + 0.0 + >>> lambertw(1) + 0.5671432904097838729999687 + >>> lambertw(e) + 1.0 + >>> lambertw(inf) + +inf + >>> lambertw(0, k=-1) + -inf + >>> lambertw(0, k=3) + -inf + >>> lambertw(inf, k=2) + (+inf + 12.56637061435917295385057j) + >>> lambertw(inf, k=3) + (+inf + 18.84955592153875943077586j) + >>> lambertw(-inf, k=3) + (+inf + 21.9911485751285526692385j) + +The `k = 0` and `k = -1` branches join at `z = -1/e` where +`W(z) = -1` for both branches. Since `-1/e` can only be represented +approximately with binary floating-point numbers, evaluating the +Lambert W function at this point only gives `-1` approximately:: + + >>> lambertw(-1/e, 0) + -0.9999999999998371330228251 + >>> lambertw(-1/e, -1) + -1.000000000000162866977175 + +If `-1/e` happens to round in the negative direction, there might be +a small imaginary part:: + + >>> mp.dps = 15 + >>> lambertw(-1/e) + (-1.0 + 8.22007971483662e-9j) + >>> lambertw(-1/e+eps) + -0.999999966242188 + +**References** + +1. [Corless]_ +""" + +barnesg = r""" +Evaluates the Barnes G-function, which generalizes the +superfactorial (:func:`~mpmath.superfac`) and by extension also the +hyperfactorial (:func:`~mpmath.hyperfac`) to the complex numbers +in an analogous way to how the gamma function generalizes +the ordinary factorial. + +The Barnes G-function may be defined in terms of a Weierstrass +product: + +.. math :: + + G(z+1) = (2\pi)^{z/2} e^{-[z(z+1)+\gamma z^2]/2} + \prod_{n=1}^\infty + \left[\left(1+\frac{z}{n}\right)^ne^{-z+z^2/(2n)}\right] + +For positive integers `n`, we have have relation to superfactorials +`G(n) = \mathrm{sf}(n-2) = 0! \cdot 1! \cdots (n-2)!`. + +**Examples** + +Some elementary values and limits of the Barnes G-function:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> barnesg(1), barnesg(2), barnesg(3) + (1.0, 1.0, 1.0) + >>> barnesg(4) + 2.0 + >>> barnesg(5) + 12.0 + >>> barnesg(6) + 288.0 + >>> barnesg(7) + 34560.0 + >>> barnesg(8) + 24883200.0 + >>> barnesg(inf) + +inf + >>> barnesg(0), barnesg(-1), barnesg(-2) + (0.0, 0.0, 0.0) + +Closed-form values are known for some rational arguments:: + + >>> barnesg('1/2') + 0.603244281209446 + >>> sqrt(exp(0.25+log(2)/12)/sqrt(pi)/glaisher**3) + 0.603244281209446 + >>> barnesg('1/4') + 0.29375596533861 + >>> nthroot(exp('3/8')/exp(catalan/pi)/ + ... gamma(0.25)**3/sqrt(glaisher)**9, 4) + 0.29375596533861 + +The Barnes G-function satisfies the functional equation +`G(z+1) = \Gamma(z) G(z)`:: + + >>> z = pi + >>> barnesg(z+1) + 2.39292119327948 + >>> gamma(z)*barnesg(z) + 2.39292119327948 + +The asymptotic growth rate of the Barnes G-function is related to +the Glaisher-Kinkelin constant:: + + >>> limit(lambda n: barnesg(n+1)/(n**(n**2/2-mpf(1)/12)* + ... (2*pi)**(n/2)*exp(-3*n**2/4)), inf) + 0.847536694177301 + >>> exp('1/12')/glaisher + 0.847536694177301 + +The Barnes G-function can be differentiated in closed form:: + + >>> z = 3 + >>> diff(barnesg, z) + 0.264507203401607 + >>> barnesg(z)*((z-1)*psi(0,z)-z+(log(2*pi)+1)/2) + 0.264507203401607 + +Evaluation is supported for arbitrary arguments and at arbitrary +precision:: + + >>> barnesg(6.5) + 2548.7457695685 + >>> barnesg(-pi) + 0.00535976768353037 + >>> barnesg(3+4j) + (-0.000676375932234244 - 4.42236140124728e-5j) + >>> mp.dps = 50 + >>> barnesg(1/sqrt(2)) + 0.81305501090451340843586085064413533788206204124732 + >>> q = barnesg(10j) + >>> q.real + 0.000000000021852360840356557241543036724799812371995850552234 + >>> q.imag + -0.00000000000070035335320062304849020654215545839053210041457588 + >>> mp.dps = 15 + >>> barnesg(100) + 3.10361006263698e+6626 + >>> barnesg(-101) + 0.0 + >>> barnesg(-10.5) + 5.94463017605008e+25 + >>> barnesg(-10000.5) + -6.14322868174828e+167480422 + >>> barnesg(1000j) + (5.21133054865546e-1173597 + 4.27461836811016e-1173597j) + >>> barnesg(-1000+1000j) + (2.43114569750291e+1026623 + 2.24851410674842e+1026623j) + + +**References** + +1. Whittaker & Watson, *A Course of Modern Analysis*, + Cambridge University Press, 4th edition (1927), p.264 +2. http://en.wikipedia.org/wiki/Barnes_G-function +3. http://mathworld.wolfram.com/BarnesG-Function.html + +""" + +superfac = r""" +Computes the superfactorial, defined as the product of +consecutive factorials + +.. math :: + + \mathrm{sf}(n) = \prod_{k=1}^n k! + +For general complex `z`, `\mathrm{sf}(z)` is defined +in terms of the Barnes G-function (see :func:`~mpmath.barnesg`). + +**Examples** + +The first few superfactorials are (OEIS A000178):: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> for n in range(10): + ... print("%s %s" % (n, superfac(n))) + ... + 0 1.0 + 1 1.0 + 2 2.0 + 3 12.0 + 4 288.0 + 5 34560.0 + 6 24883200.0 + 7 125411328000.0 + 8 5.05658474496e+15 + 9 1.83493347225108e+21 + +Superfactorials grow very rapidly:: + + >>> superfac(1000) + 3.24570818422368e+1177245 + >>> superfac(10**10) + 2.61398543581249e+467427913956904067453 + +Evaluation is supported for arbitrary arguments:: + + >>> mp.dps = 25 + >>> superfac(pi) + 17.20051550121297985285333 + >>> superfac(2+3j) + (-0.005915485633199789627466468 + 0.008156449464604044948738263j) + >>> diff(superfac, 1) + 0.2645072034016070205673056 + +**References** + +1. http://oeis.org/A000178 + +""" + + +hyperfac = r""" +Computes the hyperfactorial, defined for integers as the product + +.. math :: + + H(n) = \prod_{k=1}^n k^k. + + +The hyperfactorial satisfies the recurrence formula `H(z) = z^z H(z-1)`. +It can be defined more generally in terms of the Barnes G-function (see +:func:`~mpmath.barnesg`) and the gamma function by the formula + +.. math :: + + H(z) = \frac{\Gamma(z+1)^z}{G(z)}. + +The extension to complex numbers can also be done via +the integral representation + +.. math :: + + H(z) = (2\pi)^{-z/2} \exp \left[ + {z+1 \choose 2} + \int_0^z \log(t!)\,dt + \right]. + +**Examples** + +The rapidly-growing sequence of hyperfactorials begins +(OEIS A002109):: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> for n in range(10): + ... print("%s %s" % (n, hyperfac(n))) + ... + 0 1.0 + 1 1.0 + 2 4.0 + 3 108.0 + 4 27648.0 + 5 86400000.0 + 6 4031078400000.0 + 7 3.3197663987712e+18 + 8 5.56964379417266e+25 + 9 2.15779412229419e+34 + +Some even larger hyperfactorials are:: + + >>> hyperfac(1000) + 5.46458120882585e+1392926 + >>> hyperfac(10**10) + 4.60408207642219e+489142638002418704309 + +The hyperfactorial can be evaluated for arbitrary arguments:: + + >>> hyperfac(0.5) + 0.880449235173423 + >>> diff(hyperfac, 1) + 0.581061466795327 + >>> hyperfac(pi) + 205.211134637462 + >>> hyperfac(-10+1j) + (3.01144471378225e+46 - 2.45285242480185e+46j) + +The recurrence property of the hyperfactorial holds +generally:: + + >>> z = 3-4*j + >>> hyperfac(z) + (-4.49795891462086e-7 - 6.33262283196162e-7j) + >>> z**z * hyperfac(z-1) + (-4.49795891462086e-7 - 6.33262283196162e-7j) + >>> z = mpf(-0.6) + >>> chop(z**z * hyperfac(z-1)) + 1.28170142849352 + >>> hyperfac(z) + 1.28170142849352 + +The hyperfactorial may also be computed using the integral +definition:: + + >>> z = 2.5 + >>> hyperfac(z) + 15.9842119922237 + >>> (2*pi)**(-z/2)*exp(binomial(z+1,2) + + ... quad(lambda t: loggamma(t+1), [0, z])) + 15.9842119922237 + +:func:`~mpmath.hyperfac` supports arbitrary-precision evaluation:: + + >>> mp.dps = 50 + >>> hyperfac(10) + 215779412229418562091680268288000000000000000.0 + >>> hyperfac(1/sqrt(2)) + 0.89404818005227001975423476035729076375705084390942 + +**References** + +1. http://oeis.org/A002109 +2. http://mathworld.wolfram.com/Hyperfactorial.html + +""" + +rgamma = r""" +Computes the reciprocal of the gamma function, `1/\Gamma(z)`. This +function evaluates to zero at the poles +of the gamma function, `z = 0, -1, -2, \ldots`. + +**Examples** + +Basic examples:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> rgamma(1) + 1.0 + >>> rgamma(4) + 0.1666666666666666666666667 + >>> rgamma(0); rgamma(-1) + 0.0 + 0.0 + >>> rgamma(1000) + 2.485168143266784862783596e-2565 + >>> rgamma(inf) + 0.0 + +A definite integral that can be evaluated in terms of elementary +integrals:: + + >>> quad(rgamma, [0,inf]) + 2.807770242028519365221501 + >>> e + quad(lambda t: exp(-t)/(pi**2+log(t)**2), [0,inf]) + 2.807770242028519365221501 +""" + +loggamma = r""" +Computes the principal branch of the log-gamma function, +`\ln \Gamma(z)`. Unlike `\ln(\Gamma(z))`, which has infinitely many +complex branch cuts, the principal log-gamma function only has a single +branch cut along the negative half-axis. The principal branch +continuously matches the asymptotic Stirling expansion + +.. math :: + + \ln \Gamma(z) \sim \frac{\ln(2 \pi)}{2} + + \left(z-\frac{1}{2}\right) \ln(z) - z + O(z^{-1}). + +The real parts of both functions agree, but their imaginary +parts generally differ by `2 n \pi` for some `n \in \mathbb{Z}`. +They coincide for `z \in \mathbb{R}, z > 0`. + +Computationally, it is advantageous to use :func:`~mpmath.loggamma` +instead of :func:`~mpmath.gamma` for extremely large arguments. + +**Examples** + +Comparing with `\ln(\Gamma(z))`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> loggamma('13.2'); log(gamma('13.2')) + 20.49400419456603678498394 + 20.49400419456603678498394 + >>> loggamma(3+4j) + (-1.756626784603784110530604 + 4.742664438034657928194889j) + >>> log(gamma(3+4j)) + (-1.756626784603784110530604 - 1.540520869144928548730397j) + >>> log(gamma(3+4j)) + 2*pi*j + (-1.756626784603784110530604 + 4.742664438034657928194889j) + +Note the imaginary parts for negative arguments:: + + >>> loggamma(-0.5); loggamma(-1.5); loggamma(-2.5) + (1.265512123484645396488946 - 3.141592653589793238462643j) + (0.8600470153764810145109327 - 6.283185307179586476925287j) + (-0.05624371649767405067259453 - 9.42477796076937971538793j) + +Some special values:: + + >>> loggamma(1); loggamma(2) + 0.0 + 0.0 + >>> loggamma(3); +ln2 + 0.6931471805599453094172321 + 0.6931471805599453094172321 + >>> loggamma(3.5); log(15*sqrt(pi)/8) + 1.200973602347074224816022 + 1.200973602347074224816022 + >>> loggamma(inf) + +inf + +Huge arguments are permitted:: + + >>> loggamma('1e30') + 6.807755278982137052053974e+31 + >>> loggamma('1e300') + 6.897755278982137052053974e+302 + >>> loggamma('1e3000') + 6.906755278982137052053974e+3003 + >>> loggamma('1e100000000000000000000') + 2.302585092994045684007991e+100000000000000000020 + >>> loggamma('1e30j') + (-1.570796326794896619231322e+30 + 6.807755278982137052053974e+31j) + >>> loggamma('1e300j') + (-1.570796326794896619231322e+300 + 6.897755278982137052053974e+302j) + >>> loggamma('1e3000j') + (-1.570796326794896619231322e+3000 + 6.906755278982137052053974e+3003j) + +The log-gamma function can be integrated analytically +on any interval of unit length:: + + >>> z = 0 + >>> quad(loggamma, [z,z+1]); log(2*pi)/2 + 0.9189385332046727417803297 + 0.9189385332046727417803297 + >>> z = 3+4j + >>> quad(loggamma, [z,z+1]); (log(z)-1)*z + log(2*pi)/2 + (-0.9619286014994750641314421 + 5.219637303741238195688575j) + (-0.9619286014994750641314421 + 5.219637303741238195688575j) + +The derivatives of the log-gamma function are given by the +polygamma function (:func:`~mpmath.psi`):: + + >>> diff(loggamma, -4+3j); psi(0, -4+3j) + (1.688493531222971393607153 + 2.554898911356806978892748j) + (1.688493531222971393607153 + 2.554898911356806978892748j) + >>> diff(loggamma, -4+3j, 2); psi(1, -4+3j) + (-0.1539414829219882371561038 - 0.1020485197430267719746479j) + (-0.1539414829219882371561038 - 0.1020485197430267719746479j) + +The log-gamma function satisfies an additive form of the +recurrence relation for the ordinary gamma function:: + + >>> z = 2+3j + >>> loggamma(z); loggamma(z+1) - log(z) + (-2.092851753092733349564189 + 2.302396543466867626153708j) + (-2.092851753092733349564189 + 2.302396543466867626153708j) + +""" + +siegeltheta = r""" +Computes the Riemann-Siegel theta function, + +.. math :: + + \theta(t) = \frac{ + \log\Gamma\left(\frac{1+2it}{4}\right) - + \log\Gamma\left(\frac{1-2it}{4}\right) + }{2i} - \frac{\log \pi}{2} t. + +The Riemann-Siegel theta function is important in +providing the phase factor for the Z-function +(see :func:`~mpmath.siegelz`). Evaluation is supported for real and +complex arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> siegeltheta(0) + 0.0 + >>> siegeltheta(inf) + +inf + >>> siegeltheta(-inf) + -inf + >>> siegeltheta(1) + -1.767547952812290388302216 + >>> siegeltheta(10+0.25j) + (-3.068638039426838572528867 + 0.05804937947429712998395177j) + +Arbitrary derivatives may be computed with derivative = k + + >>> siegeltheta(1234, derivative=2) + 0.0004051864079114053109473741 + >>> diff(siegeltheta, 1234, n=2) + 0.0004051864079114053109473741 + + +The Riemann-Siegel theta function has odd symmetry around `t = 0`, +two local extreme points and three real roots including 0 (located +symmetrically):: + + >>> nprint(chop(taylor(siegeltheta, 0, 5))) + [0.0, -2.68609, 0.0, 2.69433, 0.0, -6.40218] + >>> findroot(diffun(siegeltheta), 7) + 6.28983598883690277966509 + >>> findroot(siegeltheta, 20) + 17.84559954041086081682634 + +For large `t`, there is a famous asymptotic formula +for `\theta(t)`, to first order given by:: + + >>> t = mpf(10**6) + >>> siegeltheta(t) + 5488816.353078403444882823 + >>> -t*log(2*pi/t)/2-t/2 + 5488816.745777464310273645 +""" + +grampoint = r""" +Gives the `n`-th Gram point `g_n`, defined as the solution +to the equation `\theta(g_n) = \pi n` where `\theta(t)` +is the Riemann-Siegel theta function (:func:`~mpmath.siegeltheta`). + +The first few Gram points are:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> grampoint(0) + 17.84559954041086081682634 + >>> grampoint(1) + 23.17028270124630927899664 + >>> grampoint(2) + 27.67018221781633796093849 + >>> grampoint(3) + 31.71797995476405317955149 + +Checking the definition:: + + >>> siegeltheta(grampoint(3)) + 9.42477796076937971538793 + >>> 3*pi + 9.42477796076937971538793 + +A large Gram point:: + + >>> grampoint(10**10) + 3293531632.728335454561153 + +Gram points are useful when studying the Z-function +(:func:`~mpmath.siegelz`). See the documentation of that function +for additional examples. + +:func:`~mpmath.grampoint` can solve the defining equation for +nonintegral `n`. There is a fixed point where `g(x) = x`:: + + >>> findroot(lambda x: grampoint(x) - x, 10000) + 9146.698193171459265866198 + +**References** + +1. http://mathworld.wolfram.com/GramPoint.html + +""" + +siegelz = r""" +Computes the Z-function, also known as the Riemann-Siegel Z function, + +.. math :: + + Z(t) = e^{i \theta(t)} \zeta(1/2+it) + +where `\zeta(s)` is the Riemann zeta function (:func:`~mpmath.zeta`) +and where `\theta(t)` denotes the Riemann-Siegel theta function +(see :func:`~mpmath.siegeltheta`). + +Evaluation is supported for real and complex arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> siegelz(1) + -0.7363054628673177346778998 + >>> siegelz(3+4j) + (-0.1852895764366314976003936 - 0.2773099198055652246992479j) + +The first four derivatives are supported, using the +optional *derivative* keyword argument:: + + >>> siegelz(1234567, derivative=3) + 56.89689348495089294249178 + >>> diff(siegelz, 1234567, n=3) + 56.89689348495089294249178 + + +The Z-function has a Maclaurin expansion:: + + >>> nprint(chop(taylor(siegelz, 0, 4))) + [-1.46035, 0.0, 2.73588, 0.0, -8.39357] + +The Z-function `Z(t)` is equal to `\pm |\zeta(s)|` on the +critical line `s = 1/2+it` (i.e. for real arguments `t` +to `Z`). Its zeros coincide with those of the Riemann zeta +function:: + + >>> findroot(siegelz, 14) + 14.13472514173469379045725 + >>> findroot(siegelz, 20) + 21.02203963877155499262848 + >>> findroot(zeta, 0.5+14j) + (0.5 + 14.13472514173469379045725j) + >>> findroot(zeta, 0.5+20j) + (0.5 + 21.02203963877155499262848j) + +Since the Z-function is real-valued on the critical line +(and unlike `|\zeta(s)|` analytic), it is useful for +investigating the zeros of the Riemann zeta function. +For example, one can use a root-finding algorithm based +on sign changes:: + + >>> findroot(siegelz, [100, 200], solver='bisect') + 176.4414342977104188888926 + +To locate roots, Gram points `g_n` which can be computed +by :func:`~mpmath.grampoint` are useful. If `(-1)^n Z(g_n)` is +positive for two consecutive `n`, then `Z(t)` must have +a zero between those points:: + + >>> g10 = grampoint(10) + >>> g11 = grampoint(11) + >>> (-1)**10 * siegelz(g10) > 0 + True + >>> (-1)**11 * siegelz(g11) > 0 + True + >>> findroot(siegelz, [g10, g11], solver='bisect') + 56.44624769706339480436776 + >>> g10, g11 + (54.67523744685325626632663, 57.54516517954725443703014) + +""" + +riemannr = r""" +Evaluates the Riemann R function, a smooth approximation of the +prime counting function `\pi(x)` (see :func:`~mpmath.primepi`). The Riemann +R function gives a fast numerical approximation useful e.g. to +roughly estimate the number of primes in a given interval. + +The Riemann R function is computed using the rapidly convergent Gram +series, + +.. math :: + + R(x) = 1 + \sum_{k=1}^{\infty} + \frac{\log^k x}{k k! \zeta(k+1)}. + +From the Gram series, one sees that the Riemann R function is a +well-defined analytic function (except for a branch cut along +the negative real half-axis); it can be evaluated for arbitrary +real or complex arguments. + +The Riemann R function gives a very accurate approximation +of the prime counting function. For example, it is wrong by at +most 2 for `x < 1000`, and for `x = 10^9` differs from the exact +value of `\pi(x)` by 79, or less than two parts in a million. +It is about 10 times more accurate than the logarithmic integral +estimate (see :func:`~mpmath.li`), which however is even faster to evaluate. +It is orders of magnitude more accurate than the extremely +fast `x/\log x` estimate. + +**Examples** + +For small arguments, the Riemann R function almost exactly +gives the prime counting function if rounded to the nearest +integer:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> primepi(50), riemannr(50) + (15, 14.9757023241462) + >>> max(abs(primepi(n)-int(round(riemannr(n)))) for n in range(100)) + 1 + >>> max(abs(primepi(n)-int(round(riemannr(n)))) for n in range(300)) + 2 + +The Riemann R function can be evaluated for arguments far too large +for exact determination of `\pi(x)` to be computationally +feasible with any presently known algorithm:: + + >>> riemannr(10**30) + 1.46923988977204e+28 + >>> riemannr(10**100) + 4.3619719871407e+97 + >>> riemannr(10**1000) + 4.3448325764012e+996 + +A comparison of the Riemann R function and logarithmic integral estimates +for `\pi(x)` using exact values of `\pi(10^n)` up to `n = 9`. +The fractional error is shown in parentheses:: + + >>> exact = [4,25,168,1229,9592,78498,664579,5761455,50847534] + >>> for n, p in enumerate(exact): + ... n += 1 + ... r, l = riemannr(10**n), li(10**n) + ... rerr, lerr = nstr((r-p)/p,3), nstr((l-p)/p,3) + ... print("%i %i %s(%s) %s(%s)" % (n, p, r, rerr, l, lerr)) + ... + 1 4 4.56458314100509(0.141) 6.1655995047873(0.541) + 2 25 25.6616332669242(0.0265) 30.1261415840796(0.205) + 3 168 168.359446281167(0.00214) 177.609657990152(0.0572) + 4 1229 1226.93121834343(-0.00168) 1246.13721589939(0.0139) + 5 9592 9587.43173884197(-0.000476) 9629.8090010508(0.00394) + 6 78498 78527.3994291277(0.000375) 78627.5491594622(0.00165) + 7 664579 664667.447564748(0.000133) 664918.405048569(0.000511) + 8 5761455 5761551.86732017(1.68e-5) 5762209.37544803(0.000131) + 9 50847534 50847455.4277214(-1.55e-6) 50849234.9570018(3.35e-5) + +The derivative of the Riemann R function gives the approximate +probability for a number of magnitude `x` to be prime:: + + >>> diff(riemannr, 1000) + 0.141903028110784 + >>> mpf(primepi(1050) - primepi(950)) / 100 + 0.15 + +Evaluation is supported for arbitrary arguments and at arbitrary +precision:: + + >>> mp.dps = 30 + >>> riemannr(7.5) + 3.72934743264966261918857135136 + >>> riemannr(-4+2j) + (-0.551002208155486427591793957644 + 2.16966398138119450043195899746j) + +""" + +primepi = r""" +Evaluates the prime counting function, `\pi(x)`, which gives +the number of primes less than or equal to `x`. The argument +`x` may be fractional. + +The prime counting function is very expensive to evaluate +precisely for large `x`, and the present implementation is +not optimized in any way. For numerical approximation of the +prime counting function, it is better to use :func:`~mpmath.primepi2` +or :func:`~mpmath.riemannr`. + +Some values of the prime counting function:: + + >>> from mpmath import * + >>> [primepi(k) for k in range(20)] + [0, 0, 1, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 8] + >>> primepi(3.5) + 2 + >>> primepi(100000) + 9592 + +""" + +primepi2 = r""" +Returns an interval (as an ``mpi`` instance) providing bounds +for the value of the prime counting function `\pi(x)`. For small +`x`, :func:`~mpmath.primepi2` returns an exact interval based on +the output of :func:`~mpmath.primepi`. For `x > 2656`, a loose interval +based on Schoenfeld's inequality + +.. math :: + + |\pi(x) - \mathrm{li}(x)| < \frac{\sqrt x \log x}{8 \pi} + +is returned. This estimate is rigorous assuming the truth of +the Riemann hypothesis, and can be computed very quickly. + +**Examples** + +Exact values of the prime counting function for small `x`:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> iv.dps = 15; iv.pretty = True + >>> primepi2(10) + [4.0, 4.0] + >>> primepi2(100) + [25.0, 25.0] + >>> primepi2(1000) + [168.0, 168.0] + +Loose intervals are generated for moderately large `x`: + + >>> primepi2(10000), primepi(10000) + ([1209.0, 1283.0], 1229) + >>> primepi2(50000), primepi(50000) + ([5070.0, 5263.0], 5133) + +As `x` increases, the absolute error gets worse while the relative +error improves. The exact value of `\pi(10^{23})` is +1925320391606803968923, and :func:`~mpmath.primepi2` gives 9 significant +digits:: + + >>> p = primepi2(10**23) + >>> p + [1.9253203909477020467e+21, 1.925320392280406229e+21] + >>> mpf(p.delta) / mpf(p.a) + 6.9219865355293e-10 + +A more precise, nonrigorous estimate for `\pi(x)` can be +obtained using the Riemann R function (:func:`~mpmath.riemannr`). +For large enough `x`, the value returned by :func:`~mpmath.primepi2` +essentially amounts to a small perturbation of the value returned by +:func:`~mpmath.riemannr`:: + + >>> primepi2(10**100) + [4.3619719871407024816e+97, 4.3619719871407032404e+97] + >>> riemannr(10**100) + 4.3619719871407e+97 +""" + +primezeta = r""" +Computes the prime zeta function, which is defined +in analogy with the Riemann zeta function (:func:`~mpmath.zeta`) +as + +.. math :: + + P(s) = \sum_p \frac{1}{p^s} + +where the sum is taken over all prime numbers `p`. Although +this sum only converges for `\mathrm{Re}(s) > 1`, the +function is defined by analytic continuation in the +half-plane `\mathrm{Re}(s) > 0`. + +**Examples** + +Arbitrary-precision evaluation for real and complex arguments is +supported:: + + >>> from mpmath import * + >>> mp.dps = 30; mp.pretty = True + >>> primezeta(2) + 0.452247420041065498506543364832 + >>> primezeta(pi) + 0.15483752698840284272036497397 + >>> mp.dps = 50 + >>> primezeta(3) + 0.17476263929944353642311331466570670097541212192615 + >>> mp.dps = 20 + >>> primezeta(3+4j) + (-0.12085382601645763295 - 0.013370403397787023602j) + +The prime zeta function has a logarithmic pole at `s = 1`, +with residue equal to the difference of the Mertens and +Euler constants:: + + >>> primezeta(1) + +inf + >>> extradps(25)(lambda x: primezeta(1+x)+log(x))(+eps) + -0.31571845205389007685 + >>> mertens-euler + -0.31571845205389007685 + +The analytic continuation to `0 < \mathrm{Re}(s) \le 1` +is implemented. In this strip the function exhibits +very complex behavior; on the unit interval, it has poles at +`1/n` for every squarefree integer `n`:: + + >>> primezeta(0.5) # Pole at s = 1/2 + (-inf + 3.1415926535897932385j) + >>> primezeta(0.25) + (-1.0416106801757269036 + 0.52359877559829887308j) + >>> primezeta(0.5+10j) + (0.54892423556409790529 + 0.45626803423487934264j) + +Although evaluation works in principle for any `\mathrm{Re}(s) > 0`, +it should be noted that the evaluation time increases exponentially +as `s` approaches the imaginary axis. + +For large `\mathrm{Re}(s)`, `P(s)` is asymptotic to `2^{-s}`:: + + >>> primezeta(inf) + 0.0 + >>> primezeta(10), mpf(2)**-10 + (0.00099360357443698021786, 0.0009765625) + >>> primezeta(1000) + 9.3326361850321887899e-302 + >>> primezeta(1000+1000j) + (-3.8565440833654995949e-302 - 8.4985390447553234305e-302j) + +**References** + +Carl-Erik Froberg, "On the prime zeta function", +BIT 8 (1968), pp. 187-202. + +""" + +bernpoly = r""" +Evaluates the Bernoulli polynomial `B_n(z)`. + +The first few Bernoulli polynomials are:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> for n in range(6): + ... nprint(chop(taylor(lambda x: bernpoly(n,x), 0, n))) + ... + [1.0] + [-0.5, 1.0] + [0.166667, -1.0, 1.0] + [0.0, 0.5, -1.5, 1.0] + [-0.0333333, 0.0, 1.0, -2.0, 1.0] + [0.0, -0.166667, 0.0, 1.66667, -2.5, 1.0] + +At `z = 0`, the Bernoulli polynomial evaluates to a +Bernoulli number (see :func:`~mpmath.bernoulli`):: + + >>> bernpoly(12, 0), bernoulli(12) + (-0.253113553113553, -0.253113553113553) + >>> bernpoly(13, 0), bernoulli(13) + (0.0, 0.0) + +Evaluation is accurate for large `n` and small `z`:: + + >>> mp.dps = 25 + >>> bernpoly(100, 0.5) + 2.838224957069370695926416e+78 + >>> bernpoly(1000, 10.5) + 5.318704469415522036482914e+1769 + +""" + +polylog = r""" +Computes the polylogarithm, defined by the sum + +.. math :: + + \mathrm{Li}_s(z) = \sum_{k=1}^{\infty} \frac{z^k}{k^s}. + +This series is convergent only for `|z| < 1`, so elsewhere +the analytic continuation is implied. + +The polylogarithm should not be confused with the logarithmic +integral (also denoted by Li or li), which is implemented +as :func:`~mpmath.li`. + +**Examples** + +The polylogarithm satisfies a huge number of functional identities. +A sample of polylogarithm evaluations is shown below:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> polylog(1,0.5), log(2) + (0.693147180559945, 0.693147180559945) + >>> polylog(2,0.5), (pi**2-6*log(2)**2)/12 + (0.582240526465012, 0.582240526465012) + >>> polylog(2,-phi), -log(phi)**2-pi**2/10 + (-1.21852526068613, -1.21852526068613) + >>> polylog(3,0.5), 7*zeta(3)/8-pi**2*log(2)/12+log(2)**3/6 + (0.53721319360804, 0.53721319360804) + +:func:`~mpmath.polylog` can evaluate the analytic continuation of the +polylogarithm when `s` is an integer:: + + >>> polylog(2, 10) + (0.536301287357863 - 7.23378441241546j) + >>> polylog(2, -10) + -4.1982778868581 + >>> polylog(2, 10j) + (-3.05968879432873 + 3.71678149306807j) + >>> polylog(-2, 10) + -0.150891632373114 + >>> polylog(-2, -10) + 0.067618332081142 + >>> polylog(-2, 10j) + (0.0384353698579347 + 0.0912451798066779j) + +Some more examples, with arguments on the unit circle (note that +the series definition cannot be used for computation here):: + + >>> polylog(2,j) + (-0.205616758356028 + 0.915965594177219j) + >>> j*catalan-pi**2/48 + (-0.205616758356028 + 0.915965594177219j) + >>> polylog(3,exp(2*pi*j/3)) + (-0.534247512515375 + 0.765587078525922j) + >>> -4*zeta(3)/9 + 2*j*pi**3/81 + (-0.534247512515375 + 0.765587078525921j) + +Polylogarithms of different order are related by integration +and differentiation:: + + >>> s, z = 3, 0.5 + >>> polylog(s+1, z) + 0.517479061673899 + >>> quad(lambda t: polylog(s,t)/t, [0, z]) + 0.517479061673899 + >>> z*diff(lambda t: polylog(s+2,t), z) + 0.517479061673899 + +Taylor series expansions around `z = 0` are:: + + >>> for n in range(-3, 4): + ... nprint(taylor(lambda x: polylog(n,x), 0, 5)) + ... + [0.0, 1.0, 8.0, 27.0, 64.0, 125.0] + [0.0, 1.0, 4.0, 9.0, 16.0, 25.0] + [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] + [0.0, 1.0, 1.0, 1.0, 1.0, 1.0] + [0.0, 1.0, 0.5, 0.333333, 0.25, 0.2] + [0.0, 1.0, 0.25, 0.111111, 0.0625, 0.04] + [0.0, 1.0, 0.125, 0.037037, 0.015625, 0.008] + +The series defining the polylogarithm is simultaneously +a Taylor series and an L-series. For certain values of `z`, the +polylogarithm reduces to a pure zeta function:: + + >>> polylog(pi, 1), zeta(pi) + (1.17624173838258, 1.17624173838258) + >>> polylog(pi, -1), -altzeta(pi) + (-0.909670702980385, -0.909670702980385) + +Evaluation for arbitrary, nonintegral `s` is supported +for `z` within the unit circle: + + >>> polylog(3+4j, 0.25) + (0.24258605789446 - 0.00222938275488344j) + >>> nsum(lambda k: 0.25**k / k**(3+4j), [1,inf]) + (0.24258605789446 - 0.00222938275488344j) + +It is also supported outside of the unit circle:: + + >>> polylog(1+j, 20+40j) + (-7.1421172179728 - 3.92726697721369j) + >>> polylog(1+j, 200+400j) + (-5.41934747194626 - 9.94037752563927j) + +**References** + +1. Richard Crandall, "Note on fast polylogarithm computation" + http://www.reed.edu/physics/faculty/crandall/papers/Polylog.pdf +2. http://en.wikipedia.org/wiki/Polylogarithm +3. http://mathworld.wolfram.com/Polylogarithm.html + +""" + +bell = r""" +For `n` a nonnegative integer, ``bell(n,x)`` evaluates the Bell +polynomial `B_n(x)`, the first few of which are + +.. math :: + + B_0(x) = 1 + + B_1(x) = x + + B_2(x) = x^2+x + + B_3(x) = x^3+3x^2+x + +If `x = 1` or :func:`~mpmath.bell` is called with only one argument, it +gives the `n`-th Bell number `B_n`, which is the number of +partitions of a set with `n` elements. By setting the precision to +at least `\log_{10} B_n` digits, :func:`~mpmath.bell` provides fast +calculation of exact Bell numbers. + +In general, :func:`~mpmath.bell` computes + +.. math :: + + B_n(x) = e^{-x} \left(\mathrm{sinc}(\pi n) + E_n(x)\right) + +where `E_n(x)` is the generalized exponential function implemented +by :func:`~mpmath.polyexp`. This is an extension of Dobinski's formula [1], +where the modification is the sinc term ensuring that `B_n(x)` is +continuous in `n`; :func:`~mpmath.bell` can thus be evaluated, +differentiated, etc for arbitrary complex arguments. + +**Examples** + +Simple evaluations:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> bell(0, 2.5) + 1.0 + >>> bell(1, 2.5) + 2.5 + >>> bell(2, 2.5) + 8.75 + +Evaluation for arbitrary complex arguments:: + + >>> bell(5.75+1j, 2-3j) + (-10767.71345136587098445143 - 15449.55065599872579097221j) + +The first few Bell polynomials:: + + >>> for k in range(7): + ... nprint(taylor(lambda x: bell(k,x), 0, k)) + ... + [1.0] + [0.0, 1.0] + [0.0, 1.0, 1.0] + [0.0, 1.0, 3.0, 1.0] + [0.0, 1.0, 7.0, 6.0, 1.0] + [0.0, 1.0, 15.0, 25.0, 10.0, 1.0] + [0.0, 1.0, 31.0, 90.0, 65.0, 15.0, 1.0] + +The first few Bell numbers and complementary Bell numbers:: + + >>> [int(bell(k)) for k in range(10)] + [1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147] + >>> [int(bell(k,-1)) for k in range(10)] + [1, -1, 0, 1, 1, -2, -9, -9, 50, 267] + +Large Bell numbers:: + + >>> mp.dps = 50 + >>> bell(50) + 185724268771078270438257767181908917499221852770.0 + >>> bell(50,-1) + -29113173035759403920216141265491160286912.0 + +Some even larger values:: + + >>> mp.dps = 25 + >>> bell(1000,-1) + -1.237132026969293954162816e+1869 + >>> bell(1000) + 2.989901335682408421480422e+1927 + >>> bell(1000,2) + 6.591553486811969380442171e+1987 + >>> bell(1000,100.5) + 9.101014101401543575679639e+2529 + +A determinant identity satisfied by Bell numbers:: + + >>> mp.dps = 15 + >>> N = 8 + >>> det([[bell(k+j) for j in range(N)] for k in range(N)]) + 125411328000.0 + >>> superfac(N-1) + 125411328000.0 + +**References** + +1. http://mathworld.wolfram.com/DobinskisFormula.html + +""" + +polyexp = r""" +Evaluates the polyexponential function, defined for arbitrary +complex `s`, `z` by the series + +.. math :: + + E_s(z) = \sum_{k=1}^{\infty} \frac{k^s}{k!} z^k. + +`E_s(z)` is constructed from the exponential function analogously +to how the polylogarithm is constructed from the ordinary +logarithm; as a function of `s` (with `z` fixed), `E_s` is an L-series +It is an entire function of both `s` and `z`. + +The polyexponential function provides a generalization of the +Bell polynomials `B_n(x)` (see :func:`~mpmath.bell`) to noninteger orders `n`. +In terms of the Bell polynomials, + +.. math :: + + E_s(z) = e^z B_s(z) - \mathrm{sinc}(\pi s). + +Note that `B_n(x)` and `e^{-x} E_n(x)` are identical if `n` +is a nonzero integer, but not otherwise. In particular, they differ +at `n = 0`. + +**Examples** + +Evaluating a series:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> nsum(lambda k: sqrt(k)/fac(k), [1,inf]) + 2.101755547733791780315904 + >>> polyexp(0.5,1) + 2.101755547733791780315904 + +Evaluation for arbitrary arguments:: + + >>> polyexp(-3-4j, 2.5+2j) + (2.351660261190434618268706 + 1.202966666673054671364215j) + +Evaluation is accurate for tiny function values:: + + >>> polyexp(4, -100) + 3.499471750566824369520223e-36 + +If `n` is a nonpositive integer, `E_n` reduces to a special +instance of the hypergeometric function `\,_pF_q`:: + + >>> n = 3 + >>> x = pi + >>> polyexp(-n,x) + 4.042192318847986561771779 + >>> x*hyper([1]*(n+1), [2]*(n+1), x) + 4.042192318847986561771779 + +""" + +cyclotomic = r""" +Evaluates the cyclotomic polynomial `\Phi_n(x)`, defined by + +.. math :: + + \Phi_n(x) = \prod_{\zeta} (x - \zeta) + +where `\zeta` ranges over all primitive `n`-th roots of unity +(see :func:`~mpmath.unitroots`). An equivalent representation, used +for computation, is + +.. math :: + + \Phi_n(x) = \prod_{d\mid n}(x^d-1)^{\mu(n/d)} = \Phi_n(x) + +where `\mu(m)` denotes the Moebius function. The cyclotomic +polynomials are integer polynomials, the first of which can be +written explicitly as + +.. math :: + + \Phi_0(x) = 1 + + \Phi_1(x) = x - 1 + + \Phi_2(x) = x + 1 + + \Phi_3(x) = x^3 + x^2 + 1 + + \Phi_4(x) = x^2 + 1 + + \Phi_5(x) = x^4 + x^3 + x^2 + x + 1 + + \Phi_6(x) = x^2 - x + 1 + +**Examples** + +The coefficients of low-order cyclotomic polynomials can be recovered +using Taylor expansion:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> for n in range(9): + ... p = chop(taylor(lambda x: cyclotomic(n,x), 0, 10)) + ... print("%s %s" % (n, nstr(p[:10+1-p[::-1].index(1)]))) + ... + 0 [1.0] + 1 [-1.0, 1.0] + 2 [1.0, 1.0] + 3 [1.0, 1.0, 1.0] + 4 [1.0, 0.0, 1.0] + 5 [1.0, 1.0, 1.0, 1.0, 1.0] + 6 [1.0, -1.0, 1.0] + 7 [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] + 8 [1.0, 0.0, 0.0, 0.0, 1.0] + +The definition as a product over primitive roots may be checked +by computing the product explicitly (for a real argument, this +method will generally introduce numerical noise in the imaginary +part):: + + >>> mp.dps = 25 + >>> z = 3+4j + >>> cyclotomic(10, z) + (-419.0 - 360.0j) + >>> fprod(z-r for r in unitroots(10, primitive=True)) + (-419.0 - 360.0j) + >>> z = 3 + >>> cyclotomic(10, z) + 61.0 + >>> fprod(z-r for r in unitroots(10, primitive=True)) + (61.0 - 3.146045605088568607055454e-25j) + +Up to permutation, the roots of a given cyclotomic polynomial +can be checked to agree with the list of primitive roots:: + + >>> p = taylor(lambda x: cyclotomic(6,x), 0, 6)[:3] + >>> for r in polyroots(p[::-1]): + ... print(r) + ... + (0.5 - 0.8660254037844386467637232j) + (0.5 + 0.8660254037844386467637232j) + >>> + >>> for r in unitroots(6, primitive=True): + ... print(r) + ... + (0.5 + 0.8660254037844386467637232j) + (0.5 - 0.8660254037844386467637232j) + +""" + +meijerg = r""" +Evaluates the Meijer G-function, defined as + +.. math :: + + G^{m,n}_{p,q} \left( \left. \begin{matrix} + a_1, \dots, a_n ; a_{n+1} \dots a_p \\ + b_1, \dots, b_m ; b_{m+1} \dots b_q + \end{matrix}\; \right| \; z ; r \right) = + \frac{1}{2 \pi i} \int_L + \frac{\prod_{j=1}^m \Gamma(b_j+s) \prod_{j=1}^n\Gamma(1-a_j-s)} + {\prod_{j=n+1}^{p}\Gamma(a_j+s) \prod_{j=m+1}^q \Gamma(1-b_j-s)} + z^{-s/r} ds + +for an appropriate choice of the contour `L` (see references). + +There are `p` elements `a_j`. +The argument *a_s* should be a pair of lists, the first containing the +`n` elements `a_1, \ldots, a_n` and the second containing +the `p-n` elements `a_{n+1}, \ldots a_p`. + +There are `q` elements `b_j`. +The argument *b_s* should be a pair of lists, the first containing the +`m` elements `b_1, \ldots, b_m` and the second containing +the `q-m` elements `b_{m+1}, \ldots b_q`. + +The implicit tuple `(m, n, p, q)` constitutes the order or degree of the +Meijer G-function, and is determined by the lengths of the coefficient +vectors. Confusingly, the indices in this tuple appear in a different order +from the coefficients, but this notation is standard. The many examples +given below should hopefully clear up any potential confusion. + +**Algorithm** + +The Meijer G-function is evaluated as a combination of hypergeometric series. +There are two versions of the function, which can be selected with +the optional *series* argument. + +*series=1* uses a sum of `m` `\,_pF_{q-1}` functions of `z` + +*series=2* uses a sum of `n` `\,_qF_{p-1}` functions of `1/z` + +The default series is chosen based on the degree and `|z|` in order +to be consistent with Mathematica's. This definition of the Meijer G-function +has a discontinuity at `|z| = 1` for some orders, which can +be avoided by explicitly specifying a series. + +Keyword arguments are forwarded to :func:`~mpmath.hypercomb`. + +**Examples** + +Many standard functions are special cases of the Meijer G-function +(possibly rescaled and/or with branch cut corrections). We define +some test parameters:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> a = mpf(0.75) + >>> b = mpf(1.5) + >>> z = mpf(2.25) + +The exponential function: +`e^z = G^{1,0}_{0,1} \left( \left. \begin{matrix} - \\ 0 \end{matrix} \; +\right| \; -z \right)` + + >>> meijerg([[],[]], [[0],[]], -z) + 9.487735836358525720550369 + >>> exp(z) + 9.487735836358525720550369 + +The natural logarithm: +`\log(1+z) = G^{1,2}_{2,2} \left( \left. \begin{matrix} 1, 1 \\ 1, 0 +\end{matrix} \; \right| \; -z \right)` + + >>> meijerg([[1,1],[]], [[1],[0]], z) + 1.178654996341646117219023 + >>> log(1+z) + 1.178654996341646117219023 + +A rational function: +`\frac{z}{z+1} = G^{1,2}_{2,2} \left( \left. \begin{matrix} 1, 1 \\ 1, 1 +\end{matrix} \; \right| \; z \right)` + + >>> meijerg([[1,1],[]], [[1],[1]], z) + 0.6923076923076923076923077 + >>> z/(z+1) + 0.6923076923076923076923077 + +The sine and cosine functions: + +`\frac{1}{\sqrt \pi} \sin(2 \sqrt z) = G^{1,0}_{0,2} \left( \left. \begin{matrix} +- \\ \frac{1}{2}, 0 \end{matrix} \; \right| \; z \right)` + +`\frac{1}{\sqrt \pi} \cos(2 \sqrt z) = G^{1,0}_{0,2} \left( \left. \begin{matrix} +- \\ 0, \frac{1}{2} \end{matrix} \; \right| \; z \right)` + + >>> meijerg([[],[]], [[0.5],[0]], (z/2)**2) + 0.4389807929218676682296453 + >>> sin(z)/sqrt(pi) + 0.4389807929218676682296453 + >>> meijerg([[],[]], [[0],[0.5]], (z/2)**2) + -0.3544090145996275423331762 + >>> cos(z)/sqrt(pi) + -0.3544090145996275423331762 + +Bessel functions: + +`J_a(2 \sqrt z) = G^{1,0}_{0,2} \left( \left. +\begin{matrix} - \\ \frac{a}{2}, -\frac{a}{2} +\end{matrix} \; \right| \; z \right)` + +`Y_a(2 \sqrt z) = G^{2,0}_{1,3} \left( \left. +\begin{matrix} \frac{-a-1}{2} \\ \frac{a}{2}, -\frac{a}{2}, \frac{-a-1}{2} +\end{matrix} \; \right| \; z \right)` + +`(-z)^{a/2} z^{-a/2} I_a(2 \sqrt z) = G^{1,0}_{0,2} \left( \left. +\begin{matrix} - \\ \frac{a}{2}, -\frac{a}{2} +\end{matrix} \; \right| \; -z \right)` + +`2 K_a(2 \sqrt z) = G^{2,0}_{0,2} \left( \left. +\begin{matrix} - \\ \frac{a}{2}, -\frac{a}{2} +\end{matrix} \; \right| \; z \right)` + +As the example with the Bessel *I* function shows, a branch +factor is required for some arguments when inverting the square root. + + >>> meijerg([[],[]], [[a/2],[-a/2]], (z/2)**2) + 0.5059425789597154858527264 + >>> besselj(a,z) + 0.5059425789597154858527264 + >>> meijerg([[],[(-a-1)/2]], [[a/2,-a/2],[(-a-1)/2]], (z/2)**2) + 0.1853868950066556941442559 + >>> bessely(a, z) + 0.1853868950066556941442559 + >>> meijerg([[],[]], [[a/2],[-a/2]], -(z/2)**2) + (0.8685913322427653875717476 + 2.096964974460199200551738j) + >>> (-z)**(a/2) / z**(a/2) * besseli(a, z) + (0.8685913322427653875717476 + 2.096964974460199200551738j) + >>> 0.5*meijerg([[],[]], [[a/2,-a/2],[]], (z/2)**2) + 0.09334163695597828403796071 + >>> besselk(a,z) + 0.09334163695597828403796071 + +Error functions: + +`\sqrt{\pi} z^{2(a-1)} \mathrm{erfc}(z) = G^{2,0}_{1,2} \left( \left. +\begin{matrix} a \\ a-1, a-\frac{1}{2} +\end{matrix} \; \right| \; z, \frac{1}{2} \right)` + + >>> meijerg([[],[a]], [[a-1,a-0.5],[]], z, 0.5) + 0.00172839843123091957468712 + >>> sqrt(pi) * z**(2*a-2) * erfc(z) + 0.00172839843123091957468712 + +A Meijer G-function of higher degree, (1,1,2,3): + + >>> meijerg([[a],[b]], [[a],[b,a-1]], z) + 1.55984467443050210115617 + >>> sin((b-a)*pi)/pi*(exp(z)-1)*z**(a-1) + 1.55984467443050210115617 + +A Meijer G-function of still higher degree, (4,1,2,4), that can +be expanded as a messy combination of exponential integrals: + + >>> meijerg([[a],[2*b-a]], [[b,a,b-0.5,-1-a+2*b],[]], z) + 0.3323667133658557271898061 + >>> chop(4**(a-b+1)*sqrt(pi)*gamma(2*b-2*a)*z**a*\ + ... expint(2*b-2*a, -2*sqrt(-z))*expint(2*b-2*a, 2*sqrt(-z))) + 0.3323667133658557271898061 + +In the following case, different series give different values:: + + >>> chop(meijerg([[1],[0.25]],[[3],[0.5]],-2)) + -0.06417628097442437076207337 + >>> meijerg([[1],[0.25]],[[3],[0.5]],-2,series=1) + 0.1428699426155117511873047 + >>> chop(meijerg([[1],[0.25]],[[3],[0.5]],-2,series=2)) + -0.06417628097442437076207337 + +**References** + +1. http://en.wikipedia.org/wiki/Meijer_G-function + +2. http://mathworld.wolfram.com/MeijerG-Function.html + +3. http://functions.wolfram.com/HypergeometricFunctions/MeijerG/ + +4. http://functions.wolfram.com/HypergeometricFunctions/MeijerG1/ + +""" + +clsin = r""" +Computes the Clausen sine function, defined formally by the series + +.. math :: + + \mathrm{Cl}_s(z) = \sum_{k=1}^{\infty} \frac{\sin(kz)}{k^s}. + +The special case `\mathrm{Cl}_2(z)` (i.e. ``clsin(2,z)``) is the classical +"Clausen function". More generally, the Clausen function is defined for +complex `s` and `z`, even when the series does not converge. The +Clausen function is related to the polylogarithm (:func:`~mpmath.polylog`) as + +.. math :: + + \mathrm{Cl}_s(z) = \frac{1}{2i}\left(\mathrm{Li}_s\left(e^{iz}\right) - + \mathrm{Li}_s\left(e^{-iz}\right)\right) + + = \mathrm{Im}\left[\mathrm{Li}_s(e^{iz})\right] \quad (s, z \in \mathbb{R}), + +and this representation can be taken to provide the analytic continuation of the +series. The complementary function :func:`~mpmath.clcos` gives the corresponding +cosine sum. + +**Examples** + +Evaluation for arbitrarily chosen `s` and `z`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> s, z = 3, 4 + >>> clsin(s, z); nsum(lambda k: sin(z*k)/k**s, [1,inf]) + -0.6533010136329338746275795 + -0.6533010136329338746275795 + +Using `z + \pi` instead of `z` gives an alternating series:: + + >>> clsin(s, z+pi) + 0.8860032351260589402871624 + >>> nsum(lambda k: (-1)**k*sin(z*k)/k**s, [1,inf]) + 0.8860032351260589402871624 + +With `s = 1`, the sum can be expressed in closed form +using elementary functions:: + + >>> z = 1 + sqrt(3) + >>> clsin(1, z) + 0.2047709230104579724675985 + >>> chop((log(1-exp(-j*z)) - log(1-exp(j*z)))/(2*j)) + 0.2047709230104579724675985 + >>> nsum(lambda k: sin(k*z)/k, [1,inf]) + 0.2047709230104579724675985 + +The classical Clausen function `\mathrm{Cl}_2(\theta)` gives the +value of the integral `\int_0^{\theta} -\ln(2\sin(x/2)) dx` for +`0 < \theta < 2 \pi`:: + + >>> cl2 = lambda t: clsin(2, t) + >>> cl2(3.5) + -0.2465045302347694216534255 + >>> -quad(lambda x: ln(2*sin(0.5*x)), [0, 3.5]) + -0.2465045302347694216534255 + +This function is symmetric about `\theta = \pi` with zeros and extreme +points:: + + >>> cl2(0); cl2(pi/3); chop(cl2(pi)); cl2(5*pi/3); chop(cl2(2*pi)) + 0.0 + 1.014941606409653625021203 + 0.0 + -1.014941606409653625021203 + 0.0 + +Catalan's constant is a special value:: + + >>> cl2(pi/2) + 0.9159655941772190150546035 + >>> +catalan + 0.9159655941772190150546035 + +The Clausen sine function can be expressed in closed form when +`s` is an odd integer (becoming zero when `s` < 0):: + + >>> z = 1 + sqrt(2) + >>> clsin(1, z); (pi-z)/2 + 0.3636895456083490948304773 + 0.3636895456083490948304773 + >>> clsin(3, z); pi**2/6*z - pi*z**2/4 + z**3/12 + 0.5661751584451144991707161 + 0.5661751584451144991707161 + >>> clsin(-1, z) + 0.0 + >>> clsin(-3, z) + 0.0 + +It can also be expressed in closed form for even integer `s \le 0`, +providing a finite sum for series such as +`\sin(z) + \sin(2z) + \sin(3z) + \ldots`:: + + >>> z = 1 + sqrt(2) + >>> clsin(0, z) + 0.1903105029507513881275865 + >>> cot(z/2)/2 + 0.1903105029507513881275865 + >>> clsin(-2, z) + -0.1089406163841548817581392 + >>> -cot(z/2)*csc(z/2)**2/4 + -0.1089406163841548817581392 + +Call with ``pi=True`` to multiply `z` by `\pi` exactly:: + + >>> clsin(3, 3*pi) + -8.892316224968072424732898e-26 + >>> clsin(3, 3, pi=True) + 0.0 + +Evaluation for complex `s`, `z` in a nonconvergent case:: + + >>> s, z = -1-j, 1+2j + >>> clsin(s, z) + (-0.593079480117379002516034 + 0.9038644233367868273362446j) + >>> extraprec(20)(nsum)(lambda k: sin(k*z)/k**s, [1,inf]) + (-0.593079480117379002516034 + 0.9038644233367868273362446j) + +""" + +clcos = r""" +Computes the Clausen cosine function, defined formally by the series + +.. math :: + + \mathrm{\widetilde{Cl}}_s(z) = \sum_{k=1}^{\infty} \frac{\cos(kz)}{k^s}. + +This function is complementary to the Clausen sine function +:func:`~mpmath.clsin`. In terms of the polylogarithm, + +.. math :: + + \mathrm{\widetilde{Cl}}_s(z) = + \frac{1}{2}\left(\mathrm{Li}_s\left(e^{iz}\right) + + \mathrm{Li}_s\left(e^{-iz}\right)\right) + + = \mathrm{Re}\left[\mathrm{Li}_s(e^{iz})\right] \quad (s, z \in \mathbb{R}). + +**Examples** + +Evaluation for arbitrarily chosen `s` and `z`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> s, z = 3, 4 + >>> clcos(s, z); nsum(lambda k: cos(z*k)/k**s, [1,inf]) + -0.6518926267198991308332759 + -0.6518926267198991308332759 + +Using `z + \pi` instead of `z` gives an alternating series:: + + >>> s, z = 3, 0.5 + >>> clcos(s, z+pi) + -0.8155530586502260817855618 + >>> nsum(lambda k: (-1)**k*cos(z*k)/k**s, [1,inf]) + -0.8155530586502260817855618 + +With `s = 1`, the sum can be expressed in closed form +using elementary functions:: + + >>> z = 1 + sqrt(3) + >>> clcos(1, z) + -0.6720334373369714849797918 + >>> chop(-0.5*(log(1-exp(j*z))+log(1-exp(-j*z)))) + -0.6720334373369714849797918 + >>> -log(abs(2*sin(0.5*z))) # Equivalent to above when z is real + -0.6720334373369714849797918 + >>> nsum(lambda k: cos(k*z)/k, [1,inf]) + -0.6720334373369714849797918 + +It can also be expressed in closed form when `s` is an even integer. +For example, + + >>> clcos(2,z) + -0.7805359025135583118863007 + >>> pi**2/6 - pi*z/2 + z**2/4 + -0.7805359025135583118863007 + +The case `s = 0` gives the renormalized sum of +`\cos(z) + \cos(2z) + \cos(3z) + \ldots` (which happens to be the same for +any value of `z`):: + + >>> clcos(0, z) + -0.5 + >>> nsum(lambda k: cos(k*z), [1,inf]) + -0.5 + +Also the sums + +.. math :: + + \cos(z) + 2\cos(2z) + 3\cos(3z) + \ldots + +and + +.. math :: + + \cos(z) + 2^n \cos(2z) + 3^n \cos(3z) + \ldots + +for higher integer powers `n = -s` can be done in closed form. They are zero +when `n` is positive and even (`s` negative and even):: + + >>> clcos(-1, z); 1/(2*cos(z)-2) + -0.2607829375240542480694126 + -0.2607829375240542480694126 + >>> clcos(-3, z); (2+cos(z))*csc(z/2)**4/8 + 0.1472635054979944390848006 + 0.1472635054979944390848006 + >>> clcos(-2, z); clcos(-4, z); clcos(-6, z) + 0.0 + 0.0 + 0.0 + +With `z = \pi`, the series reduces to that of the Riemann zeta function +(more generally, if `z = p \pi/q`, it is a finite sum over Hurwitz zeta +function values):: + + >>> clcos(2.5, 0); zeta(2.5) + 1.34148725725091717975677 + 1.34148725725091717975677 + >>> clcos(2.5, pi); -altzeta(2.5) + -0.8671998890121841381913472 + -0.8671998890121841381913472 + +Call with ``pi=True`` to multiply `z` by `\pi` exactly:: + + >>> clcos(-3, 2*pi) + 2.997921055881167659267063e+102 + >>> clcos(-3, 2, pi=True) + 0.008333333333333333333333333 + +Evaluation for complex `s`, `z` in a nonconvergent case:: + + >>> s, z = -1-j, 1+2j + >>> clcos(s, z) + (0.9407430121562251476136807 + 0.715826296033590204557054j) + >>> extraprec(20)(nsum)(lambda k: cos(k*z)/k**s, [1,inf]) + (0.9407430121562251476136807 + 0.715826296033590204557054j) + +""" + +whitm = r""" +Evaluates the Whittaker function `M(k,m,z)`, which gives a solution +to the Whittaker differential equation + +.. math :: + + \frac{d^2f}{dz^2} + \left(-\frac{1}{4}+\frac{k}{z}+ + \frac{(\frac{1}{4}-m^2)}{z^2}\right) f = 0. + +A second solution is given by :func:`~mpmath.whitw`. + +The Whittaker functions are defined in Abramowitz & Stegun, section 13.1. +They are alternate forms of the confluent hypergeometric functions +`\,_1F_1` and `U`: + +.. math :: + + M(k,m,z) = e^{-\frac{1}{2}z} z^{\frac{1}{2}+m} + \,_1F_1(\tfrac{1}{2}+m-k, 1+2m, z) + + W(k,m,z) = e^{-\frac{1}{2}z} z^{\frac{1}{2}+m} + U(\tfrac{1}{2}+m-k, 1+2m, z). + +**Examples** + +Evaluation for arbitrary real and complex arguments is supported:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> whitm(1, 1, 1) + 0.7302596799460411820509668 + >>> whitm(1, 1, -1) + (0.0 - 1.417977827655098025684246j) + >>> whitm(j, j/2, 2+3j) + (3.245477713363581112736478 - 0.822879187542699127327782j) + >>> whitm(2, 3, 100000) + 4.303985255686378497193063e+21707 + +Evaluation at zero:: + + >>> whitm(1,-1,0); whitm(1,-0.5,0); whitm(1,0,0) + +inf + nan + 0.0 + +We can verify that :func:`~mpmath.whitm` numerically satisfies the +differential equation for arbitrarily chosen values:: + + >>> k = mpf(0.25) + >>> m = mpf(1.5) + >>> f = lambda z: whitm(k,m,z) + >>> for z in [-1, 2.5, 3, 1+2j]: + ... chop(diff(f,z,2) + (-0.25 + k/z + (0.25-m**2)/z**2)*f(z)) + ... + 0.0 + 0.0 + 0.0 + 0.0 + +An integral involving both :func:`~mpmath.whitm` and :func:`~mpmath.whitw`, +verifying evaluation along the real axis:: + + >>> quad(lambda x: exp(-x)*whitm(3,2,x)*whitw(1,-2,x), [0,inf]) + 3.438869842576800225207341 + >>> 128/(21*sqrt(pi)) + 3.438869842576800225207341 + +""" + +whitw = r""" +Evaluates the Whittaker function `W(k,m,z)`, which gives a second +solution to the Whittaker differential equation. (See :func:`~mpmath.whitm`.) + +**Examples** + +Evaluation for arbitrary real and complex arguments is supported:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> whitw(1, 1, 1) + 1.19532063107581155661012 + >>> whitw(1, 1, -1) + (-0.9424875979222187313924639 - 0.2607738054097702293308689j) + >>> whitw(j, j/2, 2+3j) + (0.1782899315111033879430369 - 0.01609578360403649340169406j) + >>> whitw(2, 3, 100000) + 1.887705114889527446891274e-21705 + >>> whitw(-1, -1, 100) + 1.905250692824046162462058e-24 + +Evaluation at zero:: + + >>> for m in [-1, -0.5, 0, 0.5, 1]: + ... whitw(1, m, 0) + ... + +inf + nan + 0.0 + nan + +inf + +We can verify that :func:`~mpmath.whitw` numerically satisfies the +differential equation for arbitrarily chosen values:: + + >>> k = mpf(0.25) + >>> m = mpf(1.5) + >>> f = lambda z: whitw(k,m,z) + >>> for z in [-1, 2.5, 3, 1+2j]: + ... chop(diff(f,z,2) + (-0.25 + k/z + (0.25-m**2)/z**2)*f(z)) + ... + 0.0 + 0.0 + 0.0 + 0.0 + +""" + +ber = r""" +Computes the Kelvin function ber, which for real arguments gives the real part +of the Bessel J function of a rotated argument + +.. math :: + + J_n\left(x e^{3\pi i/4}\right) = \mathrm{ber}_n(x) + i \mathrm{bei}_n(x). + +The imaginary part is given by :func:`~mpmath.bei`. + +**Plots** + +.. literalinclude :: /plots/ber.py +.. image :: /plots/ber.png + +**Examples** + +Verifying the defining relation:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> n, x = 2, 3.5 + >>> ber(n,x) + 1.442338852571888752631129 + >>> bei(n,x) + -0.948359035324558320217678 + >>> besselj(n, x*root(1,8,3)) + (1.442338852571888752631129 - 0.948359035324558320217678j) + +The ber and bei functions are also defined by analytic continuation +for complex arguments:: + + >>> ber(1+j, 2+3j) + (4.675445984756614424069563 - 15.84901771719130765656316j) + >>> bei(1+j, 2+3j) + (15.83886679193707699364398 + 4.684053288183046528703611j) + +""" + +bei = r""" +Computes the Kelvin function bei, which for real arguments gives the +imaginary part of the Bessel J function of a rotated argument. +See :func:`~mpmath.ber`. +""" + +ker = r""" +Computes the Kelvin function ker, which for real arguments gives the real part +of the (rescaled) Bessel K function of a rotated argument + +.. math :: + + e^{-\pi i/2} K_n\left(x e^{3\pi i/4}\right) = \mathrm{ker}_n(x) + i \mathrm{kei}_n(x). + +The imaginary part is given by :func:`~mpmath.kei`. + +**Plots** + +.. literalinclude :: /plots/ker.py +.. image :: /plots/ker.png + +**Examples** + +Verifying the defining relation:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> n, x = 2, 4.5 + >>> ker(n,x) + 0.02542895201906369640249801 + >>> kei(n,x) + -0.02074960467222823237055351 + >>> exp(-n*pi*j/2) * besselk(n, x*root(1,8,1)) + (0.02542895201906369640249801 - 0.02074960467222823237055351j) + +The ker and kei functions are also defined by analytic continuation +for complex arguments:: + + >>> ker(1+j, 3+4j) + (1.586084268115490421090533 - 2.939717517906339193598719j) + >>> kei(1+j, 3+4j) + (-2.940403256319453402690132 - 1.585621643835618941044855j) + +""" + +kei = r""" +Computes the Kelvin function kei, which for real arguments gives the +imaginary part of the (rescaled) Bessel K function of a rotated argument. +See :func:`~mpmath.ker`. +""" + +struveh = r""" +Gives the Struve function + +.. math :: + + \,\mathbf{H}_n(z) = + \sum_{k=0}^\infty \frac{(-1)^k}{\Gamma(k+\frac{3}{2}) + \Gamma(k+n+\frac{3}{2})} {\left({\frac{z}{2}}\right)}^{2k+n+1} + +which is a solution to the Struve differential equation + +.. math :: + + z^2 f''(z) + z f'(z) + (z^2-n^2) f(z) = \frac{2 z^{n+1}}{\pi (2n-1)!!}. + +**Examples** + +Evaluation for arbitrary real and complex arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> struveh(0, 3.5) + 0.3608207733778295024977797 + >>> struveh(-1, 10) + -0.255212719726956768034732 + >>> struveh(1, -100.5) + 0.5819566816797362287502246 + >>> struveh(2.5, 10000000000000) + 3153915652525200060.308937 + >>> struveh(2.5, -10000000000000) + (0.0 - 3153915652525200060.308937j) + >>> struveh(1+j, 1000000+4000000j) + (-3.066421087689197632388731e+1737173 - 1.596619701076529803290973e+1737173j) + +A Struve function of half-integer order is elementary; for example: + + >>> z = 3 + >>> struveh(0.5, 3) + 0.9167076867564138178671595 + >>> sqrt(2/(pi*z))*(1-cos(z)) + 0.9167076867564138178671595 + +Numerically verifying the differential equation:: + + >>> z = mpf(4.5) + >>> n = 3 + >>> f = lambda z: struveh(n,z) + >>> lhs = z**2*diff(f,z,2) + z*diff(f,z) + (z**2-n**2)*f(z) + >>> rhs = 2*z**(n+1)/fac2(2*n-1)/pi + >>> lhs + 17.40359302709875496632744 + >>> rhs + 17.40359302709875496632744 + +""" + +struvel = r""" +Gives the modified Struve function + +.. math :: + + \,\mathbf{L}_n(z) = -i e^{-n\pi i/2} \mathbf{H}_n(i z) + +which solves to the modified Struve differential equation + +.. math :: + + z^2 f''(z) + z f'(z) - (z^2+n^2) f(z) = \frac{2 z^{n+1}}{\pi (2n-1)!!}. + +**Examples** + +Evaluation for arbitrary real and complex arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> struvel(0, 3.5) + 7.180846515103737996249972 + >>> struvel(-1, 10) + 2670.994904980850550721511 + >>> struvel(1, -100.5) + 1.757089288053346261497686e+42 + >>> struvel(2.5, 10000000000000) + 4.160893281017115450519948e+4342944819025 + >>> struvel(2.5, -10000000000000) + (0.0 - 4.160893281017115450519948e+4342944819025j) + >>> struvel(1+j, 700j) + (-0.1721150049480079451246076 + 0.1240770953126831093464055j) + >>> struvel(1+j, 1000000+4000000j) + (-2.973341637511505389128708e+434290 - 5.164633059729968297147448e+434290j) + +Numerically verifying the differential equation:: + + >>> z = mpf(3.5) + >>> n = 3 + >>> f = lambda z: struvel(n,z) + >>> lhs = z**2*diff(f,z,2) + z*diff(f,z) - (z**2+n**2)*f(z) + >>> rhs = 2*z**(n+1)/fac2(2*n-1)/pi + >>> lhs + 6.368850306060678353018165 + >>> rhs + 6.368850306060678353018165 +""" + +appellf1 = r""" +Gives the Appell F1 hypergeometric function of two variables, + +.. math :: + + F_1(a,b_1,b_2,c,x,y) = \sum_{m=0}^{\infty} \sum_{n=0}^{\infty} + \frac{(a)_{m+n} (b_1)_m (b_2)_n}{(c)_{m+n}} + \frac{x^m y^n}{m! n!}. + +This series is only generally convergent when `|x| < 1` and `|y| < 1`, +although :func:`~mpmath.appellf1` can evaluate an analytic continuation +with respecto to either variable, and sometimes both. + +**Examples** + +Evaluation is supported for real and complex parameters:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> appellf1(1,0,0.5,1,0.5,0.25) + 1.154700538379251529018298 + >>> appellf1(1,1+j,0.5,1,0.5,0.5j) + (1.138403860350148085179415 + 1.510544741058517621110615j) + +For some integer parameters, the F1 series reduces to a polynomial:: + + >>> appellf1(2,-4,-3,1,2,5) + -816.0 + >>> appellf1(-5,1,2,1,4,5) + -20528.0 + +The analytic continuation with respect to either `x` or `y`, +and sometimes with respect to both, can be evaluated:: + + >>> appellf1(2,3,4,5,100,0.5) + (0.0006231042714165329279738662 + 0.0000005769149277148425774499857j) + >>> appellf1('1.1', '0.3', '0.2+2j', '0.4', '0.2', 1.5+3j) + (-0.1782604566893954897128702 + 0.002472407104546216117161499j) + >>> appellf1(1,2,3,4,10,12) + -0.07122993830066776374929313 + +For certain arguments, F1 reduces to an ordinary hypergeometric function:: + + >>> appellf1(1,2,3,5,0.5,0.25) + 1.547902270302684019335555 + >>> 4*hyp2f1(1,2,5,'1/3')/3 + 1.547902270302684019335555 + >>> appellf1(1,2,3,4,0,1.5) + (-1.717202506168937502740238 - 2.792526803190927323077905j) + >>> hyp2f1(1,3,4,1.5) + (-1.717202506168937502740238 - 2.792526803190927323077905j) + +The F1 function satisfies a system of partial differential equations:: + + >>> a,b1,b2,c,x,y = map(mpf, [1,0.5,0.25,1.125,0.25,-0.25]) + >>> F = lambda x,y: appellf1(a,b1,b2,c,x,y) + >>> chop(x*(1-x)*diff(F,(x,y),(2,0)) + + ... y*(1-x)*diff(F,(x,y),(1,1)) + + ... (c-(a+b1+1)*x)*diff(F,(x,y),(1,0)) - + ... b1*y*diff(F,(x,y),(0,1)) - + ... a*b1*F(x,y)) + 0.0 + >>> + >>> chop(y*(1-y)*diff(F,(x,y),(0,2)) + + ... x*(1-y)*diff(F,(x,y),(1,1)) + + ... (c-(a+b2+1)*y)*diff(F,(x,y),(0,1)) - + ... b2*x*diff(F,(x,y),(1,0)) - + ... a*b2*F(x,y)) + 0.0 + +The Appell F1 function allows for closed-form evaluation of various +integrals, such as any integral of the form +`\int x^r (x+a)^p (x+b)^q dx`:: + + >>> def integral(a,b,p,q,r,x1,x2): + ... a,b,p,q,r,x1,x2 = map(mpmathify, [a,b,p,q,r,x1,x2]) + ... f = lambda x: x**r * (x+a)**p * (x+b)**q + ... def F(x): + ... v = x**(r+1)/(r+1) * (a+x)**p * (b+x)**q + ... v *= (1+x/a)**(-p) + ... v *= (1+x/b)**(-q) + ... v *= appellf1(r+1,-p,-q,2+r,-x/a,-x/b) + ... return v + ... print("Num. quad: %s" % quad(f, [x1,x2])) + ... print("Appell F1: %s" % (F(x2)-F(x1))) + ... + >>> integral('1/5','4/3','-2','3','1/2',0,1) + Num. quad: 9.073335358785776206576981 + Appell F1: 9.073335358785776206576981 + >>> integral('3/2','4/3','-2','3','1/2',0,1) + Num. quad: 1.092829171999626454344678 + Appell F1: 1.092829171999626454344678 + >>> integral('3/2','4/3','-2','3','1/2',12,25) + Num. quad: 1106.323225040235116498927 + Appell F1: 1106.323225040235116498927 + +Also incomplete elliptic integrals fall into this category [1]:: + + >>> def E(z, m): + ... if (pi/2).ae(z): + ... return ellipe(m) + ... return 2*round(re(z)/pi)*ellipe(m) + mpf(-1)**round(re(z)/pi)*\ + ... sin(z)*appellf1(0.5,0.5,-0.5,1.5,sin(z)**2,m*sin(z)**2) + ... + >>> z, m = 1, 0.5 + >>> E(z,m); quad(lambda t: sqrt(1-m*sin(t)**2), [0,pi/4,3*pi/4,z]) + 0.9273298836244400669659042 + 0.9273298836244400669659042 + >>> z, m = 3, 2 + >>> E(z,m); quad(lambda t: sqrt(1-m*sin(t)**2), [0,pi/4,3*pi/4,z]) + (1.057495752337234229715836 + 1.198140234735592207439922j) + (1.057495752337234229715836 + 1.198140234735592207439922j) + +**References** + +1. [WolframFunctions]_ http://functions.wolfram.com/EllipticIntegrals/EllipticE2/26/01/ +2. [SrivastavaKarlsson]_ +3. [CabralRosetti]_ +4. [Vidunas]_ +5. [Slater]_ + +""" + +angerj = r""" +Gives the Anger function + +.. math :: + + \mathbf{J}_{\nu}(z) = \frac{1}{\pi} + \int_0^{\pi} \cos(\nu t - z \sin t) dt + +which is an entire function of both the parameter `\nu` and +the argument `z`. It solves the inhomogeneous Bessel differential +equation + +.. math :: + + f''(z) + \frac{1}{z}f'(z) + \left(1-\frac{\nu^2}{z^2}\right) f(z) + = \frac{(z-\nu)}{\pi z^2} \sin(\pi \nu). + +**Examples** + +Evaluation for real and complex parameter and argument:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> angerj(2,3) + 0.4860912605858910769078311 + >>> angerj(-3+4j, 2+5j) + (-5033.358320403384472395612 + 585.8011892476145118551756j) + >>> angerj(3.25, 1e6j) + (4.630743639715893346570743e+434290 - 1.117960409887505906848456e+434291j) + >>> angerj(-1.5, 1e6) + 0.0002795719747073879393087011 + +The Anger function coincides with the Bessel J-function when `\nu` +is an integer:: + + >>> angerj(1,3); besselj(1,3) + 0.3390589585259364589255146 + 0.3390589585259364589255146 + >>> angerj(1.5,3); besselj(1.5,3) + 0.4088969848691080859328847 + 0.4777182150870917715515015 + +Verifying the differential equation:: + + >>> v,z = mpf(2.25), 0.75 + >>> f = lambda z: angerj(v,z) + >>> diff(f,z,2) + diff(f,z)/z + (1-(v/z)**2)*f(z) + -0.6002108774380707130367995 + >>> (z-v)/(pi*z**2) * sinpi(v) + -0.6002108774380707130367995 + +Verifying the integral representation:: + + >>> angerj(v,z) + 0.1145380759919333180900501 + >>> quad(lambda t: cos(v*t-z*sin(t))/pi, [0,pi]) + 0.1145380759919333180900501 + +**References** + +1. [DLMF]_ section 11.10: Anger-Weber Functions +""" + +webere = r""" +Gives the Weber function + +.. math :: + + \mathbf{E}_{\nu}(z) = \frac{1}{\pi} + \int_0^{\pi} \sin(\nu t - z \sin t) dt + +which is an entire function of both the parameter `\nu` and +the argument `z`. It solves the inhomogeneous Bessel differential +equation + +.. math :: + + f''(z) + \frac{1}{z}f'(z) + \left(1-\frac{\nu^2}{z^2}\right) f(z) + = -\frac{1}{\pi z^2} (z+\nu+(z-\nu)\cos(\pi \nu)). + +**Examples** + +Evaluation for real and complex parameter and argument:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> webere(2,3) + -0.1057668973099018425662646 + >>> webere(-3+4j, 2+5j) + (-585.8081418209852019290498 - 5033.314488899926921597203j) + >>> webere(3.25, 1e6j) + (-1.117960409887505906848456e+434291 - 4.630743639715893346570743e+434290j) + >>> webere(3.25, 1e6) + -0.00002812518265894315604914453 + +Up to addition of a rational function of `z`, the Weber function coincides +with the Struve H-function when `\nu` is an integer:: + + >>> webere(1,3); 2/pi-struveh(1,3) + -0.3834897968188690177372881 + -0.3834897968188690177372881 + >>> webere(5,3); 26/(35*pi)-struveh(5,3) + 0.2009680659308154011878075 + 0.2009680659308154011878075 + +Verifying the differential equation:: + + >>> v,z = mpf(2.25), 0.75 + >>> f = lambda z: webere(v,z) + >>> diff(f,z,2) + diff(f,z)/z + (1-(v/z)**2)*f(z) + -1.097441848875479535164627 + >>> -(z+v+(z-v)*cospi(v))/(pi*z**2) + -1.097441848875479535164627 + +Verifying the integral representation:: + + >>> webere(v,z) + 0.1486507351534283744485421 + >>> quad(lambda t: sin(v*t-z*sin(t))/pi, [0,pi]) + 0.1486507351534283744485421 + +**References** + +1. [DLMF]_ section 11.10: Anger-Weber Functions +""" + +lommels1 = r""" +Gives the Lommel function `s_{\mu,\nu}` or `s^{(1)}_{\mu,\nu}` + +.. math :: + + s_{\mu,\nu}(z) = \frac{z^{\mu+1}}{(\mu-\nu+1)(\mu+\nu+1)} + \,_1F_2\left(1; \frac{\mu-\nu+3}{2}, \frac{\mu+\nu+3}{2}; + -\frac{z^2}{4} \right) + +which solves the inhomogeneous Bessel equation + +.. math :: + + z^2 f''(z) + z f'(z) + (z^2-\nu^2) f(z) = z^{\mu+1}. + +A second solution is given by :func:`~mpmath.lommels2`. + +**Plots** + +.. literalinclude :: /plots/lommels1.py +.. image :: /plots/lommels1.png + +**Examples** + +An integral representation:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> u,v,z = 0.25, 0.125, mpf(0.75) + >>> lommels1(u,v,z) + 0.4276243877565150372999126 + >>> (bessely(v,z)*quad(lambda t: t**u*besselj(v,t), [0,z]) - \ + ... besselj(v,z)*quad(lambda t: t**u*bessely(v,t), [0,z]))*(pi/2) + 0.4276243877565150372999126 + +A special value:: + + >>> lommels1(v,v,z) + 0.5461221367746048054932553 + >>> gamma(v+0.5)*sqrt(pi)*power(2,v-1)*struveh(v,z) + 0.5461221367746048054932553 + +Verifying the differential equation:: + + >>> f = lambda z: lommels1(u,v,z) + >>> z**2*diff(f,z,2) + z*diff(f,z) + (z**2-v**2)*f(z) + 0.6979536443265746992059141 + >>> z**(u+1) + 0.6979536443265746992059141 + +**References** + +1. [GradshteynRyzhik]_ +2. [Weisstein]_ http://mathworld.wolfram.com/LommelFunction.html +""" + +lommels2 = r""" +Gives the second Lommel function `S_{\mu,\nu}` or `s^{(2)}_{\mu,\nu}` + +.. math :: + + S_{\mu,\nu}(z) = s_{\mu,\nu}(z) + 2^{\mu-1} + \Gamma\left(\tfrac{1}{2}(\mu-\nu+1)\right) + \Gamma\left(\tfrac{1}{2}(\mu+\nu+1)\right) \times + + \left[\sin(\tfrac{1}{2}(\mu-\nu)\pi) J_{\nu}(z) - + \cos(\tfrac{1}{2}(\mu-\nu)\pi) Y_{\nu}(z) + \right] + +which solves the same differential equation as +:func:`~mpmath.lommels1`. + +**Plots** + +.. literalinclude :: /plots/lommels2.py +.. image :: /plots/lommels2.png + +**Examples** + +For large `|z|`, `S_{\mu,\nu} \sim z^{\mu-1}`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> lommels2(10,2,30000) + 1.968299831601008419949804e+40 + >>> power(30000,9) + 1.9683e+40 + +A special value:: + + >>> u,v,z = 0.5, 0.125, mpf(0.75) + >>> lommels2(v,v,z) + 0.9589683199624672099969765 + >>> (struveh(v,z)-bessely(v,z))*power(2,v-1)*sqrt(pi)*gamma(v+0.5) + 0.9589683199624672099969765 + +Verifying the differential equation:: + + >>> f = lambda z: lommels2(u,v,z) + >>> z**2*diff(f,z,2) + z*diff(f,z) + (z**2-v**2)*f(z) + 0.6495190528383289850727924 + >>> z**(u+1) + 0.6495190528383289850727924 + +**References** + +1. [GradshteynRyzhik]_ +2. [Weisstein]_ http://mathworld.wolfram.com/LommelFunction.html +""" + +appellf2 = r""" +Gives the Appell F2 hypergeometric function of two variables + +.. math :: + + F_2(a,b_1,b_2,c_1,c_2,x,y) = \sum_{m=0}^{\infty} \sum_{n=0}^{\infty} + \frac{(a)_{m+n} (b_1)_m (b_2)_n}{(c_1)_m (c_2)_n} + \frac{x^m y^n}{m! n!}. + +The series is generally absolutely convergent for `|x| + |y| < 1`. + +**Examples** + +Evaluation for real and complex arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> appellf2(1,2,3,4,5,0.25,0.125) + 1.257417193533135344785602 + >>> appellf2(1,-3,-4,2,3,2,3) + -42.8 + >>> appellf2(0.5,0.25,-0.25,2,3,0.25j,0.25) + (0.9880539519421899867041719 + 0.01497616165031102661476978j) + >>> chop(appellf2(1,1+j,1-j,3j,-3j,0.25,0.25)) + 1.201311219287411337955192 + >>> appellf2(1,1,1,4,6,0.125,16) + (-0.09455532250274744282125152 - 0.7647282253046207836769297j) + +A transformation formula:: + + >>> a,b1,b2,c1,c2,x,y = map(mpf, [1,2,0.5,0.25,1.625,-0.125,0.125]) + >>> appellf2(a,b1,b2,c1,c2,x,y) + 0.2299211717841180783309688 + >>> (1-x)**(-a)*appellf2(a,c1-b1,b2,c1,c2,x/(x-1),y/(1-x)) + 0.2299211717841180783309688 + +A system of partial differential equations satisfied by F2:: + + >>> a,b1,b2,c1,c2,x,y = map(mpf, [1,0.5,0.25,1.125,1.5,0.0625,-0.0625]) + >>> F = lambda x,y: appellf2(a,b1,b2,c1,c2,x,y) + >>> chop(x*(1-x)*diff(F,(x,y),(2,0)) - + ... x*y*diff(F,(x,y),(1,1)) + + ... (c1-(a+b1+1)*x)*diff(F,(x,y),(1,0)) - + ... b1*y*diff(F,(x,y),(0,1)) - + ... a*b1*F(x,y)) + 0.0 + >>> chop(y*(1-y)*diff(F,(x,y),(0,2)) - + ... x*y*diff(F,(x,y),(1,1)) + + ... (c2-(a+b2+1)*y)*diff(F,(x,y),(0,1)) - + ... b2*x*diff(F,(x,y),(1,0)) - + ... a*b2*F(x,y)) + 0.0 + +**References** + +See references for :func:`~mpmath.appellf1`. +""" + +appellf3 = r""" +Gives the Appell F3 hypergeometric function of two variables + +.. math :: + + F_3(a_1,a_2,b_1,b_2,c,x,y) = \sum_{m=0}^{\infty} \sum_{n=0}^{\infty} + \frac{(a_1)_m (a_2)_n (b_1)_m (b_2)_n}{(c)_{m+n}} + \frac{x^m y^n}{m! n!}. + +The series is generally absolutely convergent for `|x| < 1, |y| < 1`. + +**Examples** + +Evaluation for various parameters and variables:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> appellf3(1,2,3,4,5,0.5,0.25) + 2.221557778107438938158705 + >>> appellf3(1,2,3,4,5,6,0); hyp2f1(1,3,5,6) + (-0.5189554589089861284537389 - 0.1454441043328607980769742j) + (-0.5189554589089861284537389 - 0.1454441043328607980769742j) + >>> appellf3(1,-2,-3,1,1,4,6) + -17.4 + >>> appellf3(1,2,-3,1,1,4,6) + (17.7876136773677356641825 + 19.54768762233649126154534j) + >>> appellf3(1,2,-3,1,1,6,4) + (85.02054175067929402953645 + 148.4402528821177305173599j) + >>> chop(appellf3(1+j,2,1-j,2,3,0.25,0.25)) + 1.719992169545200286696007 + +Many transformations and evaluations for special combinations +of the parameters are possible, e.g.: + + >>> a,b,c,x,y = map(mpf, [0.5,0.25,0.125,0.125,-0.125]) + >>> appellf3(a,c-a,b,c-b,c,x,y) + 1.093432340896087107444363 + >>> (1-y)**(a+b-c)*hyp2f1(a,b,c,x+y-x*y) + 1.093432340896087107444363 + >>> x**2*appellf3(1,1,1,1,3,x,-x) + 0.01568646277445385390945083 + >>> polylog(2,x**2) + 0.01568646277445385390945083 + >>> a1,a2,b1,b2,c,x = map(mpf, [0.5,0.25,0.125,0.5,4.25,0.125]) + >>> appellf3(a1,a2,b1,b2,c,x,1) + 1.03947361709111140096947 + >>> gammaprod([c,c-a2-b2],[c-a2,c-b2])*hyp3f2(a1,b1,c-a2-b2,c-a2,c-b2,x) + 1.03947361709111140096947 + +The Appell F3 function satisfies a pair of partial +differential equations:: + + >>> a1,a2,b1,b2,c,x,y = map(mpf, [0.5,0.25,0.125,0.5,0.625,0.0625,-0.0625]) + >>> F = lambda x,y: appellf3(a1,a2,b1,b2,c,x,y) + >>> chop(x*(1-x)*diff(F,(x,y),(2,0)) + + ... y*diff(F,(x,y),(1,1)) + + ... (c-(a1+b1+1)*x)*diff(F,(x,y),(1,0)) - + ... a1*b1*F(x,y)) + 0.0 + >>> chop(y*(1-y)*diff(F,(x,y),(0,2)) + + ... x*diff(F,(x,y),(1,1)) + + ... (c-(a2+b2+1)*y)*diff(F,(x,y),(0,1)) - + ... a2*b2*F(x,y)) + 0.0 + +**References** + +See references for :func:`~mpmath.appellf1`. +""" + +appellf4 = r""" +Gives the Appell F4 hypergeometric function of two variables + +.. math :: + + F_4(a,b,c_1,c_2,x,y) = \sum_{m=0}^{\infty} \sum_{n=0}^{\infty} + \frac{(a)_{m+n} (b)_{m+n}}{(c_1)_m (c_2)_n} + \frac{x^m y^n}{m! n!}. + +The series is generally absolutely convergent for +`\sqrt{|x|} + \sqrt{|y|} < 1`. + +**Examples** + +Evaluation for various parameters and arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> appellf4(1,1,2,2,0.25,0.125) + 1.286182069079718313546608 + >>> appellf4(-2,-3,4,5,4,5) + 34.8 + >>> appellf4(5,4,2,3,0.25j,-0.125j) + (-0.2585967215437846642163352 + 2.436102233553582711818743j) + +Reduction to `\,_2F_1` in a special case:: + + >>> a,b,c,x,y = map(mpf, [0.5,0.25,0.125,0.125,-0.125]) + >>> appellf4(a,b,c,a+b-c+1,x*(1-y),y*(1-x)) + 1.129143488466850868248364 + >>> hyp2f1(a,b,c,x)*hyp2f1(a,b,a+b-c+1,y) + 1.129143488466850868248364 + +A system of partial differential equations satisfied by F4:: + + >>> a,b,c1,c2,x,y = map(mpf, [1,0.5,0.25,1.125,0.0625,-0.0625]) + >>> F = lambda x,y: appellf4(a,b,c1,c2,x,y) + >>> chop(x*(1-x)*diff(F,(x,y),(2,0)) - + ... y**2*diff(F,(x,y),(0,2)) - + ... 2*x*y*diff(F,(x,y),(1,1)) + + ... (c1-(a+b+1)*x)*diff(F,(x,y),(1,0)) - + ... ((a+b+1)*y)*diff(F,(x,y),(0,1)) - + ... a*b*F(x,y)) + 0.0 + >>> chop(y*(1-y)*diff(F,(x,y),(0,2)) - + ... x**2*diff(F,(x,y),(2,0)) - + ... 2*x*y*diff(F,(x,y),(1,1)) + + ... (c2-(a+b+1)*y)*diff(F,(x,y),(0,1)) - + ... ((a+b+1)*x)*diff(F,(x,y),(1,0)) - + ... a*b*F(x,y)) + 0.0 + +**References** + +See references for :func:`~mpmath.appellf1`. +""" + +zeta = r""" +Computes the Riemann zeta function + +.. math :: + + \zeta(s) = 1+\frac{1}{2^s}+\frac{1}{3^s}+\frac{1}{4^s}+\ldots + +or, with `a \ne 1`, the more general Hurwitz zeta function + +.. math :: + + \zeta(s,a) = \sum_{k=0}^\infty \frac{1}{(a+k)^s}. + +Optionally, ``zeta(s, a, n)`` computes the `n`-th derivative with +respect to `s`, + +.. math :: + + \zeta^{(n)}(s,a) = (-1)^n \sum_{k=0}^\infty \frac{\log^n(a+k)}{(a+k)^s}. + +Although these series only converge for `\Re(s) > 1`, the Riemann and Hurwitz +zeta functions are defined through analytic continuation for arbitrary +complex `s \ne 1` (`s = 1` is a pole). + +The implementation uses three algorithms: the Borwein algorithm for +the Riemann zeta function when `s` is close to the real line; +the Riemann-Siegel formula for the Riemann zeta function when `s` is +large imaginary, and Euler-Maclaurin summation in all other cases. +The reflection formula for `\Re(s) < 0` is implemented in some cases. +The algorithm can be chosen with ``method = 'borwein'``, +``method='riemann-siegel'`` or ``method = 'euler-maclaurin'``. + +The parameter `a` is usually a rational number `a = p/q`, and may be specified +as such by passing an integer tuple `(p, q)`. Evaluation is supported for +arbitrary complex `a`, but may be slow and/or inaccurate when `\Re(s) < 0` for +nonrational `a` or when computing derivatives. + +**Examples** + +Some values of the Riemann zeta function:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> zeta(2); pi**2 / 6 + 1.644934066848226436472415 + 1.644934066848226436472415 + >>> zeta(0) + -0.5 + >>> zeta(-1) + -0.08333333333333333333333333 + >>> zeta(-2) + 0.0 + +For large positive `s`, `\zeta(s)` rapidly approaches 1:: + + >>> zeta(50) + 1.000000000000000888178421 + >>> zeta(100) + 1.0 + >>> zeta(inf) + 1.0 + >>> 1-sum((zeta(k)-1)/k for k in range(2,85)); +euler + 0.5772156649015328606065121 + 0.5772156649015328606065121 + >>> nsum(lambda k: zeta(k)-1, [2, inf]) + 1.0 + +Evaluation is supported for complex `s` and `a`: + + >>> zeta(-3+4j) + (-0.03373057338827757067584698 + 0.2774499251557093745297677j) + >>> zeta(2+3j, -1+j) + (389.6841230140842816370741 + 295.2674610150305334025962j) + +The Riemann zeta function has so-called nontrivial zeros on +the critical line `s = 1/2 + it`:: + + >>> findroot(zeta, 0.5+14j); zetazero(1) + (0.5 + 14.13472514173469379045725j) + (0.5 + 14.13472514173469379045725j) + >>> findroot(zeta, 0.5+21j); zetazero(2) + (0.5 + 21.02203963877155499262848j) + (0.5 + 21.02203963877155499262848j) + >>> findroot(zeta, 0.5+25j); zetazero(3) + (0.5 + 25.01085758014568876321379j) + (0.5 + 25.01085758014568876321379j) + >>> chop(zeta(zetazero(10))) + 0.0 + +Evaluation on and near the critical line is supported for large +heights `t` by means of the Riemann-Siegel formula (currently +for `a = 1`, `n \le 4`):: + + >>> zeta(0.5+100000j) + (1.073032014857753132114076 + 5.780848544363503984261041j) + >>> zeta(0.75+1000000j) + (0.9535316058375145020351559 + 0.9525945894834273060175651j) + >>> zeta(0.5+10000000j) + (11.45804061057709254500227 - 8.643437226836021723818215j) + >>> zeta(0.5+100000000j, derivative=1) + (51.12433106710194942681869 + 43.87221167872304520599418j) + >>> zeta(0.5+100000000j, derivative=2) + (-444.2760822795430400549229 - 896.3789978119185981665403j) + >>> zeta(0.5+100000000j, derivative=3) + (3230.72682687670422215339 + 14374.36950073615897616781j) + >>> zeta(0.5+100000000j, derivative=4) + (-11967.35573095046402130602 - 218945.7817789262839266148j) + >>> zeta(1+10000000j) # off the line + (2.859846483332530337008882 + 0.491808047480981808903986j) + >>> zeta(1+10000000j, derivative=1) + (-4.333835494679647915673205 - 0.08405337962602933636096103j) + >>> zeta(1+10000000j, derivative=4) + (453.2764822702057701894278 - 581.963625832768189140995j) + +For investigation of the zeta function zeros, the Riemann-Siegel +Z-function is often more convenient than working with the Riemann +zeta function directly (see :func:`~mpmath.siegelz`). + +Some values of the Hurwitz zeta function:: + + >>> zeta(2, 3); -5./4 + pi**2/6 + 0.3949340668482264364724152 + 0.3949340668482264364724152 + >>> zeta(2, (3,4)); pi**2 - 8*catalan + 2.541879647671606498397663 + 2.541879647671606498397663 + +For positive integer values of `s`, the Hurwitz zeta function is +equivalent to a polygamma function (except for a normalizing factor):: + + >>> zeta(4, (1,5)); psi(3, '1/5')/6 + 625.5408324774542966919938 + 625.5408324774542966919938 + +Evaluation of derivatives:: + + >>> zeta(0, 3+4j, 1); loggamma(3+4j) - ln(2*pi)/2 + (-2.675565317808456852310934 + 4.742664438034657928194889j) + (-2.675565317808456852310934 + 4.742664438034657928194889j) + >>> zeta(2, 1, 20) + 2432902008176640000.000242 + >>> zeta(3+4j, 5.5+2j, 4) + (-0.140075548947797130681075 - 0.3109263360275413251313634j) + >>> zeta(0.5+100000j, 1, 4) + (-10407.16081931495861539236 + 13777.78669862804508537384j) + >>> zeta(-100+0.5j, (1,3), derivative=4) + (4.007180821099823942702249e+79 + 4.916117957092593868321778e+78j) + +Generating a Taylor series at `s = 2` using derivatives:: + + >>> for k in range(11): print("%s * (s-2)^%i" % (zeta(2,1,k)/fac(k), k)) + ... + 1.644934066848226436472415 * (s-2)^0 + -0.9375482543158437537025741 * (s-2)^1 + 0.9946401171494505117104293 * (s-2)^2 + -1.000024300473840810940657 * (s-2)^3 + 1.000061933072352565457512 * (s-2)^4 + -1.000006869443931806408941 * (s-2)^5 + 1.000000173233769531820592 * (s-2)^6 + -0.9999999569989868493432399 * (s-2)^7 + 0.9999999937218844508684206 * (s-2)^8 + -0.9999999996355013916608284 * (s-2)^9 + 1.000000000004610645020747 * (s-2)^10 + +Evaluation at zero and for negative integer `s`:: + + >>> zeta(0, 10) + -9.5 + >>> zeta(-2, (2,3)); mpf(1)/81 + 0.01234567901234567901234568 + 0.01234567901234567901234568 + >>> zeta(-3+4j, (5,4)) + (0.2899236037682695182085988 + 0.06561206166091757973112783j) + >>> zeta(-3.25, 1/pi) + -0.0005117269627574430494396877 + >>> zeta(-3.5, pi, 1) + 11.156360390440003294709 + >>> zeta(-100.5, (8,3)) + -4.68162300487989766727122e+77 + >>> zeta(-10.5, (-8,3)) + (-0.01521913704446246609237979 + 29907.72510874248161608216j) + >>> zeta(-1000.5, (-8,3)) + (1.031911949062334538202567e+1770 + 1.519555750556794218804724e+426j) + >>> zeta(-1+j, 3+4j) + (-16.32988355630802510888631 - 22.17706465801374033261383j) + >>> zeta(-1+j, 3+4j, 2) + (32.48985276392056641594055 - 51.11604466157397267043655j) + >>> diff(lambda s: zeta(s, 3+4j), -1+j, 2) + (32.48985276392056641594055 - 51.11604466157397267043655j) + +**References** + +1. http://mathworld.wolfram.com/RiemannZetaFunction.html + +2. http://mathworld.wolfram.com/HurwitzZetaFunction.html + +3. [BorweinZeta]_ + +""" + +dirichlet = r""" +Evaluates the Dirichlet L-function + +.. math :: + + L(s,\chi) = \sum_{k=1}^\infty \frac{\chi(k)}{k^s}. + +where `\chi` is a periodic sequence of length `q` which should be supplied +in the form of a list `[\chi(0), \chi(1), \ldots, \chi(q-1)]`. +Strictly, `\chi` should be a Dirichlet character, but any periodic +sequence will work. + +For example, ``dirichlet(s, [1])`` gives the ordinary +Riemann zeta function and ``dirichlet(s, [-1,1])`` gives +the alternating zeta function (Dirichlet eta function). + +Also the derivative with respect to `s` (currently only a first +derivative) can be evaluated. + +**Examples** + +The ordinary Riemann zeta function:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> dirichlet(3, [1]); zeta(3) + 1.202056903159594285399738 + 1.202056903159594285399738 + >>> dirichlet(1, [1]) + +inf + +The alternating zeta function:: + + >>> dirichlet(1, [-1,1]); ln(2) + 0.6931471805599453094172321 + 0.6931471805599453094172321 + +The following defines the Dirichlet beta function +`\beta(s) = \sum_{k=0}^\infty \frac{(-1)^k}{(2k+1)^s}` and verifies +several values of this function:: + + >>> B = lambda s, d=0: dirichlet(s, [0, 1, 0, -1], d) + >>> B(0); 1./2 + 0.5 + 0.5 + >>> B(1); pi/4 + 0.7853981633974483096156609 + 0.7853981633974483096156609 + >>> B(2); +catalan + 0.9159655941772190150546035 + 0.9159655941772190150546035 + >>> B(2,1); diff(B, 2) + 0.08158073611659279510291217 + 0.08158073611659279510291217 + >>> B(-1,1); 2*catalan/pi + 0.5831218080616375602767689 + 0.5831218080616375602767689 + >>> B(0,1); log(gamma(0.25)**2/(2*pi*sqrt(2))) + 0.3915943927068367764719453 + 0.3915943927068367764719454 + >>> B(1,1); 0.25*pi*(euler+2*ln2+3*ln(pi)-4*ln(gamma(0.25))) + 0.1929013167969124293631898 + 0.1929013167969124293631898 + +A custom L-series of period 3:: + + >>> dirichlet(2, [2,0,1]) + 0.7059715047839078092146831 + >>> 2*nsum(lambda k: (3*k)**-2, [1,inf]) + \ + ... nsum(lambda k: (3*k+2)**-2, [0,inf]) + 0.7059715047839078092146831 + +""" + +coulombf = r""" +Calculates the regular Coulomb wave function + +.. math :: + + F_l(\eta,z) = C_l(\eta) z^{l+1} e^{-iz} \,_1F_1(l+1-i\eta, 2l+2, 2iz) + +where the normalization constant `C_l(\eta)` is as calculated by +:func:`~mpmath.coulombc`. This function solves the differential equation + +.. math :: + + f''(z) + \left(1-\frac{2\eta}{z}-\frac{l(l+1)}{z^2}\right) f(z) = 0. + +A second linearly independent solution is given by the irregular +Coulomb wave function `G_l(\eta,z)` (see :func:`~mpmath.coulombg`) +and thus the general solution is +`f(z) = C_1 F_l(\eta,z) + C_2 G_l(\eta,z)` for arbitrary +constants `C_1`, `C_2`. +Physically, the Coulomb wave functions give the radial solution +to the Schrodinger equation for a point particle in a `1/z` potential; `z` is +then the radius and `l`, `\eta` are quantum numbers. + +The Coulomb wave functions with real parameters are defined +in Abramowitz & Stegun, section 14. However, all parameters are permitted +to be complex in this implementation (see references). + +**Plots** + +.. literalinclude :: /plots/coulombf.py +.. image :: /plots/coulombf.png +.. literalinclude :: /plots/coulombf_c.py +.. image :: /plots/coulombf_c.png + +**Examples** + +Evaluation is supported for arbitrary magnitudes of `z`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> coulombf(2, 1.5, 3.5) + 0.4080998961088761187426445 + >>> coulombf(-2, 1.5, 3.5) + 0.7103040849492536747533465 + >>> coulombf(2, 1.5, '1e-10') + 4.143324917492256448770769e-33 + >>> coulombf(2, 1.5, 1000) + 0.4482623140325567050716179 + >>> coulombf(2, 1.5, 10**10) + -0.066804196437694360046619 + +Verifying the differential equation:: + + >>> l, eta, z = 2, 3, mpf(2.75) + >>> A, B = 1, 2 + >>> f = lambda z: A*coulombf(l,eta,z) + B*coulombg(l,eta,z) + >>> chop(diff(f,z,2) + (1-2*eta/z - l*(l+1)/z**2)*f(z)) + 0.0 + +A Wronskian relation satisfied by the Coulomb wave functions:: + + >>> l = 2 + >>> eta = 1.5 + >>> F = lambda z: coulombf(l,eta,z) + >>> G = lambda z: coulombg(l,eta,z) + >>> for z in [3.5, -1, 2+3j]: + ... chop(diff(F,z)*G(z) - F(z)*diff(G,z)) + ... + 1.0 + 1.0 + 1.0 + +Another Wronskian relation:: + + >>> F = coulombf + >>> G = coulombg + >>> for z in [3.5, -1, 2+3j]: + ... chop(F(l-1,eta,z)*G(l,eta,z)-F(l,eta,z)*G(l-1,eta,z) - l/sqrt(l**2+eta**2)) + ... + 0.0 + 0.0 + 0.0 + +An integral identity connecting the regular and irregular wave functions:: + + >>> l, eta, z = 4+j, 2-j, 5+2j + >>> coulombf(l,eta,z) + j*coulombg(l,eta,z) + (0.7997977752284033239714479 + 0.9294486669502295512503127j) + >>> g = lambda t: exp(-t)*t**(l-j*eta)*(t+2*j*z)**(l+j*eta) + >>> j*exp(-j*z)*z**(-l)/fac(2*l+1)/coulombc(l,eta)*quad(g, [0,inf]) + (0.7997977752284033239714479 + 0.9294486669502295512503127j) + +Some test case with complex parameters, taken from Michel [2]:: + + >>> mp.dps = 15 + >>> coulombf(1+0.1j, 50+50j, 100.156) + (-1.02107292320897e+15 - 2.83675545731519e+15j) + >>> coulombg(1+0.1j, 50+50j, 100.156) + (2.83675545731519e+15 - 1.02107292320897e+15j) + >>> coulombf(1e-5j, 10+1e-5j, 0.1+1e-6j) + (4.30566371247811e-14 - 9.03347835361657e-19j) + >>> coulombg(1e-5j, 10+1e-5j, 0.1+1e-6j) + (778709182061.134 + 18418936.2660553j) + +The following reproduces a table in Abramowitz & Stegun, at twice +the precision:: + + >>> mp.dps = 10 + >>> eta = 2; z = 5 + >>> for l in [5, 4, 3, 2, 1, 0]: + ... print("%s %s %s" % (l, coulombf(l,eta,z), + ... diff(lambda z: coulombf(l,eta,z), z))) + ... + 5 0.09079533488 0.1042553261 + 4 0.2148205331 0.2029591779 + 3 0.4313159311 0.320534053 + 2 0.7212774133 0.3952408216 + 1 0.9935056752 0.3708676452 + 0 1.143337392 0.2937960375 + +**References** + +1. I.J. Thompson & A.R. Barnett, "Coulomb and Bessel Functions of Complex + Arguments and Order", J. Comp. Phys., vol 64, no. 2, June 1986. + +2. N. Michel, "Precise Coulomb wave functions for a wide range of + complex `l`, `\eta` and `z`", http://arxiv.org/abs/physics/0702051v1 + +""" + +coulombg = r""" +Calculates the irregular Coulomb wave function + +.. math :: + + G_l(\eta,z) = \frac{F_l(\eta,z) \cos(\chi) - F_{-l-1}(\eta,z)}{\sin(\chi)} + +where `\chi = \sigma_l - \sigma_{-l-1} - (l+1/2) \pi` +and `\sigma_l(\eta) = (\ln \Gamma(1+l+i\eta)-\ln \Gamma(1+l-i\eta))/(2i)`. + +See :func:`~mpmath.coulombf` for additional information. + +**Plots** + +.. literalinclude :: /plots/coulombg.py +.. image :: /plots/coulombg.png +.. literalinclude :: /plots/coulombg_c.py +.. image :: /plots/coulombg_c.png + +**Examples** + +Evaluation is supported for arbitrary magnitudes of `z`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> coulombg(-2, 1.5, 3.5) + 1.380011900612186346255524 + >>> coulombg(2, 1.5, 3.5) + 1.919153700722748795245926 + >>> coulombg(-2, 1.5, '1e-10') + 201126715824.7329115106793 + >>> coulombg(-2, 1.5, 1000) + 0.1802071520691149410425512 + >>> coulombg(-2, 1.5, 10**10) + 0.652103020061678070929794 + +The following reproduces a table in Abramowitz & Stegun, +at twice the precision:: + + >>> mp.dps = 10 + >>> eta = 2; z = 5 + >>> for l in [1, 2, 3, 4, 5]: + ... print("%s %s %s" % (l, coulombg(l,eta,z), + ... -diff(lambda z: coulombg(l,eta,z), z))) + ... + 1 1.08148276 0.6028279961 + 2 1.496877075 0.5661803178 + 3 2.048694714 0.7959909551 + 4 3.09408669 1.731802374 + 5 5.629840456 4.549343289 + +Evaluation close to the singularity at `z = 0`:: + + >>> mp.dps = 15 + >>> coulombg(0,10,1) + 3088184933.67358 + >>> coulombg(0,10,'1e-10') + 5554866000719.8 + >>> coulombg(0,10,'1e-100') + 5554866221524.1 + +Evaluation with a half-integer value for `l`:: + + >>> coulombg(1.5, 1, 10) + 0.852320038297334 +""" + +coulombc = r""" +Gives the normalizing Gamow constant for Coulomb wave functions, + +.. math :: + + C_l(\eta) = 2^l \exp\left(-\pi \eta/2 + [\ln \Gamma(1+l+i\eta) + + \ln \Gamma(1+l-i\eta)]/2 - \ln \Gamma(2l+2)\right), + +where the log gamma function with continuous imaginary part +away from the negative half axis (see :func:`~mpmath.loggamma`) is implied. + +This function is used internally for the calculation of +Coulomb wave functions, and automatically cached to make multiple +evaluations with fixed `l`, `\eta` fast. +""" + +ellipfun = r""" +Computes any of the Jacobi elliptic functions, defined +in terms of Jacobi theta functions as + +.. math :: + + \mathrm{sn}(u,m) = \frac{\vartheta_3(0,q)}{\vartheta_2(0,q)} + \frac{\vartheta_1(t,q)}{\vartheta_4(t,q)} + + \mathrm{cn}(u,m) = \frac{\vartheta_4(0,q)}{\vartheta_2(0,q)} + \frac{\vartheta_2(t,q)}{\vartheta_4(t,q)} + + \mathrm{dn}(u,m) = \frac{\vartheta_4(0,q)}{\vartheta_3(0,q)} + \frac{\vartheta_3(t,q)}{\vartheta_4(t,q)}, + +or more generally computes a ratio of two such functions. Here +`t = u/\vartheta_3(0,q)^2`, and `q = q(m)` denotes the nome (see +:func:`~mpmath.nome`). Optionally, you can specify the nome directly +instead of `m` by passing ``q=``, or you can directly +specify the elliptic parameter `k` with ``k=``. + +The first argument should be a two-character string specifying the +function using any combination of ``'s'``, ``'c'``, ``'d'``, ``'n'``. These +letters respectively denote the basic functions +`\mathrm{sn}(u,m)`, `\mathrm{cn}(u,m)`, `\mathrm{dn}(u,m)`, and `1`. +The identifier specifies the ratio of two such functions. +For example, ``'ns'`` identifies the function + +.. math :: + + \mathrm{ns}(u,m) = \frac{1}{\mathrm{sn}(u,m)} + +and ``'cd'`` identifies the function + +.. math :: + + \mathrm{cd}(u,m) = \frac{\mathrm{cn}(u,m)}{\mathrm{dn}(u,m)}. + +If called with only the first argument, a function object +evaluating the chosen function for given arguments is returned. + +**Examples** + +Basic evaluation:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> ellipfun('cd', 3.5, 0.5) + -0.9891101840595543931308394 + >>> ellipfun('cd', 3.5, q=0.25) + 0.07111979240214668158441418 + +The sn-function is doubly periodic in the complex plane with periods +`4 K(m)` and `2 i K(1-m)` (see :func:`~mpmath.ellipk`):: + + >>> sn = ellipfun('sn') + >>> sn(2, 0.25) + 0.9628981775982774425751399 + >>> sn(2+4*ellipk(0.25), 0.25) + 0.9628981775982774425751399 + >>> chop(sn(2+2*j*ellipk(1-0.25), 0.25)) + 0.9628981775982774425751399 + +The cn-function is doubly periodic with periods `4 K(m)` and `2 K(m) + 2 i K(1-m)`:: + + >>> cn = ellipfun('cn') + >>> cn(2, 0.25) + -0.2698649654510865792581416 + >>> cn(2+4*ellipk(0.25), 0.25) + -0.2698649654510865792581416 + >>> chop(cn(2+2*ellipk(0.25)+2*j*ellipk(1-0.25), 0.25)) + -0.2698649654510865792581416 + +The dn-function is doubly periodic with periods `2 K(m)` and `4 i K(1-m)`:: + + >>> dn = ellipfun('dn') + >>> dn(2, 0.25) + 0.8764740583123262286931578 + >>> dn(2+2*ellipk(0.25), 0.25) + 0.8764740583123262286931578 + >>> chop(dn(2+4*j*ellipk(1-0.25), 0.25)) + 0.8764740583123262286931578 + +""" + + +jtheta = r""" +Computes the Jacobi theta function `\vartheta_n(z, q)`, where +`n = 1, 2, 3, 4`, defined by the infinite series: + +.. math :: + + \vartheta_1(z,q) = 2 q^{1/4} \sum_{n=0}^{\infty} + (-1)^n q^{n^2+n\,} \sin((2n+1)z) + + \vartheta_2(z,q) = 2 q^{1/4} \sum_{n=0}^{\infty} + q^{n^{2\,} + n} \cos((2n+1)z) + + \vartheta_3(z,q) = 1 + 2 \sum_{n=1}^{\infty} + q^{n^2\,} \cos(2 n z) + + \vartheta_4(z,q) = 1 + 2 \sum_{n=1}^{\infty} + (-q)^{n^2\,} \cos(2 n z) + +The theta functions are functions of two variables: + +* `z` is the *argument*, an arbitrary real or complex number + +* `q` is the *nome*, which must be a real or complex number + in the unit disk (i.e. `|q| < 1`). For `|q| \ll 1`, the + series converge very quickly, so the Jacobi theta functions + can efficiently be evaluated to high precision. + +The compact notations `\vartheta_n(q) = \vartheta_n(0,q)` +and `\vartheta_n = \vartheta_n(0,q)` are also frequently +encountered. Finally, Jacobi theta functions are frequently +considered as functions of the half-period ratio `\tau` +and then usually denoted by `\vartheta_n(z|\tau)`. + +Optionally, ``jtheta(n, z, q, derivative=d)`` with `d > 0` computes +a `d`-th derivative with respect to `z`. + +**Examples and basic properties** + +Considered as functions of `z`, the Jacobi theta functions may be +viewed as generalizations of the ordinary trigonometric functions +cos and sin. They are periodic functions:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> jtheta(1, 0.25, '0.2') + 0.2945120798627300045053104 + >>> jtheta(1, 0.25 + 2*pi, '0.2') + 0.2945120798627300045053104 + +Indeed, the series defining the theta functions are essentially +trigonometric Fourier series. The coefficients can be retrieved +using :func:`~mpmath.fourier`:: + + >>> mp.dps = 10 + >>> nprint(fourier(lambda x: jtheta(2, x, 0.5), [-pi, pi], 4)) + ([0.0, 1.68179, 0.0, 0.420448, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0]) + +The Jacobi theta functions are also so-called quasiperiodic +functions of `z` and `\tau`, meaning that for fixed `\tau`, +`\vartheta_n(z, q)` and `\vartheta_n(z+\pi \tau, q)` are the same +except for an exponential factor:: + + >>> mp.dps = 25 + >>> tau = 3*j/10 + >>> q = exp(pi*j*tau) + >>> z = 10 + >>> jtheta(4, z+tau*pi, q) + (-0.682420280786034687520568 + 1.526683999721399103332021j) + >>> -exp(-2*j*z)/q * jtheta(4, z, q) + (-0.682420280786034687520568 + 1.526683999721399103332021j) + +The Jacobi theta functions satisfy a huge number of other +functional equations, such as the following identity (valid for +any `q`):: + + >>> q = mpf(3)/10 + >>> jtheta(3,0,q)**4 + 6.823744089352763305137427 + >>> jtheta(2,0,q)**4 + jtheta(4,0,q)**4 + 6.823744089352763305137427 + +Extensive listings of identities satisfied by the Jacobi theta +functions can be found in standard reference works. + +The Jacobi theta functions are related to the gamma function +for special arguments:: + + >>> jtheta(3, 0, exp(-pi)) + 1.086434811213308014575316 + >>> pi**(1/4.) / gamma(3/4.) + 1.086434811213308014575316 + +:func:`~mpmath.jtheta` supports arbitrary precision evaluation and complex +arguments:: + + >>> mp.dps = 50 + >>> jtheta(4, sqrt(2), 0.5) + 2.0549510717571539127004115835148878097035750653737 + >>> mp.dps = 25 + >>> jtheta(4, 1+2j, (1+j)/5) + (7.180331760146805926356634 - 1.634292858119162417301683j) + +Evaluation of derivatives:: + + >>> mp.dps = 25 + >>> jtheta(1, 7, 0.25, 1); diff(lambda z: jtheta(1, z, 0.25), 7) + 1.209857192844475388637236 + 1.209857192844475388637236 + >>> jtheta(1, 7, 0.25, 2); diff(lambda z: jtheta(1, z, 0.25), 7, 2) + -0.2598718791650217206533052 + -0.2598718791650217206533052 + >>> jtheta(2, 7, 0.25, 1); diff(lambda z: jtheta(2, z, 0.25), 7) + -1.150231437070259644461474 + -1.150231437070259644461474 + >>> jtheta(2, 7, 0.25, 2); diff(lambda z: jtheta(2, z, 0.25), 7, 2) + -0.6226636990043777445898114 + -0.6226636990043777445898114 + >>> jtheta(3, 7, 0.25, 1); diff(lambda z: jtheta(3, z, 0.25), 7) + -0.9990312046096634316587882 + -0.9990312046096634316587882 + >>> jtheta(3, 7, 0.25, 2); diff(lambda z: jtheta(3, z, 0.25), 7, 2) + -0.1530388693066334936151174 + -0.1530388693066334936151174 + >>> jtheta(4, 7, 0.25, 1); diff(lambda z: jtheta(4, z, 0.25), 7) + 0.9820995967262793943571139 + 0.9820995967262793943571139 + >>> jtheta(4, 7, 0.25, 2); diff(lambda z: jtheta(4, z, 0.25), 7, 2) + 0.3936902850291437081667755 + 0.3936902850291437081667755 + +**Possible issues** + +For `|q| \ge 1` or `\Im(\tau) \le 0`, :func:`~mpmath.jtheta` raises +``ValueError``. This exception is also raised for `|q|` extremely +close to 1 (or equivalently `\tau` very close to 0), since the +series would converge too slowly:: + + >>> jtheta(1, 10, 0.99999999 * exp(0.5*j)) + Traceback (most recent call last): + ... + ValueError: abs(q) > THETA_Q_LIM = 1.000000 + +""" + +eulernum = r""" +Gives the `n`-th Euler number, defined as the `n`-th derivative of +`\mathrm{sech}(t) = 1/\cosh(t)` evaluated at `t = 0`. Equivalently, the +Euler numbers give the coefficients of the Taylor series + +.. math :: + + \mathrm{sech}(t) = \sum_{n=0}^{\infty} \frac{E_n}{n!} t^n. + +The Euler numbers are closely related to Bernoulli numbers +and Bernoulli polynomials. They can also be evaluated in terms of +Euler polynomials (see :func:`~mpmath.eulerpoly`) as `E_n = 2^n E_n(1/2)`. + +**Examples** + +Computing the first few Euler numbers and verifying that they +agree with the Taylor series:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> [eulernum(n) for n in range(11)] + [1.0, 0.0, -1.0, 0.0, 5.0, 0.0, -61.0, 0.0, 1385.0, 0.0, -50521.0] + >>> chop(diffs(sech, 0, 10)) + [1.0, 0.0, -1.0, 0.0, 5.0, 0.0, -61.0, 0.0, 1385.0, 0.0, -50521.0] + +Euler numbers grow very rapidly. :func:`~mpmath.eulernum` efficiently +computes numerical approximations for large indices:: + + >>> eulernum(50) + -6.053285248188621896314384e+54 + >>> eulernum(1000) + 3.887561841253070615257336e+2371 + >>> eulernum(10**20) + 4.346791453661149089338186e+1936958564106659551331 + +Comparing with an asymptotic formula for the Euler numbers:: + + >>> n = 10**5 + >>> (-1)**(n//2) * 8 * sqrt(n/(2*pi)) * (2*n/(pi*e))**n + 3.69919063017432362805663e+436961 + >>> eulernum(n) + 3.699193712834466537941283e+436961 + +Pass ``exact=True`` to obtain exact values of Euler numbers as integers:: + + >>> print(eulernum(50, exact=True)) + -6053285248188621896314383785111649088103498225146815121 + >>> print(eulernum(200, exact=True) % 10**10) + 1925859625 + >>> eulernum(1001, exact=True) + 0 +""" + +eulerpoly = r""" +Evaluates the Euler polynomial `E_n(z)`, defined by the generating function +representation + +.. math :: + + \frac{2e^{zt}}{e^t+1} = \sum_{n=0}^\infty E_n(z) \frac{t^n}{n!}. + +The Euler polynomials may also be represented in terms of +Bernoulli polynomials (see :func:`~mpmath.bernpoly`) using various formulas, for +example + +.. math :: + + E_n(z) = \frac{2}{n+1} \left( + B_n(z)-2^{n+1}B_n\left(\frac{z}{2}\right) + \right). + +Special values include the Euler numbers `E_n = 2^n E_n(1/2)` (see +:func:`~mpmath.eulernum`). + +**Examples** + +Computing the coefficients of the first few Euler polynomials:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> for n in range(6): + ... chop(taylor(lambda z: eulerpoly(n,z), 0, n)) + ... + [1.0] + [-0.5, 1.0] + [0.0, -1.0, 1.0] + [0.25, 0.0, -1.5, 1.0] + [0.0, 1.0, 0.0, -2.0, 1.0] + [-0.5, 0.0, 2.5, 0.0, -2.5, 1.0] + +Evaluation for arbitrary `z`:: + + >>> eulerpoly(2,3) + 6.0 + >>> eulerpoly(5,4) + 423.5 + >>> eulerpoly(35, 11111111112) + 3.994957561486776072734601e+351 + >>> eulerpoly(4, 10+20j) + (-47990.0 - 235980.0j) + >>> eulerpoly(2, '-3.5e-5') + 0.000035001225 + >>> eulerpoly(3, 0.5) + 0.0 + >>> eulerpoly(55, -10**80) + -1.0e+4400 + >>> eulerpoly(5, -inf) + -inf + >>> eulerpoly(6, -inf) + +inf + +Computing Euler numbers:: + + >>> 2**26 * eulerpoly(26,0.5) + -4087072509293123892361.0 + >>> eulernum(26) + -4087072509293123892361.0 + +Evaluation is accurate for large `n` and small `z`:: + + >>> eulerpoly(100, 0.5) + 2.29047999988194114177943e+108 + >>> eulerpoly(1000, 10.5) + 3.628120031122876847764566e+2070 + >>> eulerpoly(10000, 10.5) + 1.149364285543783412210773e+30688 +""" + +spherharm = r""" +Evaluates the spherical harmonic `Y_l^m(\theta,\phi)`, + +.. math :: + + Y_l^m(\theta,\phi) = \sqrt{\frac{2l+1}{4\pi}\frac{(l-m)!}{(l+m)!}} + P_l^m(\cos \theta) e^{i m \phi} + +where `P_l^m` is an associated Legendre function (see :func:`~mpmath.legenp`). + +Here `\theta \in [0, \pi]` denotes the polar coordinate (ranging +from the north pole to the south pole) and `\phi \in [0, 2 \pi]` denotes the +azimuthal coordinate on a sphere. Care should be used since many different +conventions for spherical coordinate variables are used. + +Usually spherical harmonics are considered for `l \in \mathbb{N}`, +`m \in \mathbb{Z}`, `|m| \le l`. More generally, `l,m,\theta,\phi` +are permitted to be complex numbers. + +.. note :: + + :func:`~mpmath.spherharm` returns a complex number, even if the value is + purely real. + +**Plots** + +.. literalinclude :: /plots/spherharm40.py + +`Y_{4,0}`: + +.. image :: /plots/spherharm40.png + +`Y_{4,1}`: + +.. image :: /plots/spherharm41.png + +`Y_{4,2}`: + +.. image :: /plots/spherharm42.png + +`Y_{4,3}`: + +.. image :: /plots/spherharm43.png + +`Y_{4,4}`: + +.. image :: /plots/spherharm44.png + +**Examples** + +Some low-order spherical harmonics with reference values:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> theta = pi/4 + >>> phi = pi/3 + >>> spherharm(0,0,theta,phi); 0.5*sqrt(1/pi)*expj(0) + (0.2820947917738781434740397 + 0.0j) + (0.2820947917738781434740397 + 0.0j) + >>> spherharm(1,-1,theta,phi); 0.5*sqrt(3/(2*pi))*expj(-phi)*sin(theta) + (0.1221506279757299803965962 - 0.2115710938304086076055298j) + (0.1221506279757299803965962 - 0.2115710938304086076055298j) + >>> spherharm(1,0,theta,phi); 0.5*sqrt(3/pi)*cos(theta)*expj(0) + (0.3454941494713354792652446 + 0.0j) + (0.3454941494713354792652446 + 0.0j) + >>> spherharm(1,1,theta,phi); -0.5*sqrt(3/(2*pi))*expj(phi)*sin(theta) + (-0.1221506279757299803965962 - 0.2115710938304086076055298j) + (-0.1221506279757299803965962 - 0.2115710938304086076055298j) + +With the normalization convention used, the spherical harmonics are orthonormal +on the unit sphere:: + + >>> sphere = [0,pi], [0,2*pi] + >>> dS = lambda t,p: fp.sin(t) # differential element + >>> Y1 = lambda t,p: fp.spherharm(l1,m1,t,p) + >>> Y2 = lambda t,p: fp.conj(fp.spherharm(l2,m2,t,p)) + >>> l1 = l2 = 3; m1 = m2 = 2 + >>> fp.chop(fp.quad(lambda t,p: Y1(t,p)*Y2(t,p)*dS(t,p), *sphere)) + 1.0000000000000007 + >>> m2 = 1 # m1 != m2 + >>> print(fp.chop(fp.quad(lambda t,p: Y1(t,p)*Y2(t,p)*dS(t,p), *sphere))) + 0.0 + +Evaluation is accurate for large orders:: + + >>> spherharm(1000,750,0.5,0.25) + (3.776445785304252879026585e-102 - 5.82441278771834794493484e-102j) + +Evaluation works with complex parameter values:: + + >>> spherharm(1+j, 2j, 2+3j, -0.5j) + (64.44922331113759992154992 + 1981.693919841408089681743j) +""" + +scorergi = r""" +Evaluates the Scorer function + +.. math :: + + \operatorname{Gi}(z) = + \operatorname{Ai}(z) \int_0^z \operatorname{Bi}(t) dt + + \operatorname{Bi}(z) \int_z^{\infty} \operatorname{Ai}(t) dt + +which gives a particular solution to the inhomogeneous Airy +differential equation `f''(z) - z f(z) = 1/\pi`. Another +particular solution is given by the Scorer Hi-function +(:func:`~mpmath.scorerhi`). The two functions are related as +`\operatorname{Gi}(z) + \operatorname{Hi}(z) = \operatorname{Bi}(z)`. + +**Plots** + +.. literalinclude :: /plots/gi.py +.. image :: /plots/gi.png +.. literalinclude :: /plots/gi_c.py +.. image :: /plots/gi_c.png + +**Examples** + +Some values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> scorergi(0); 1/(power(3,'7/6')*gamma('2/3')) + 0.2049755424820002450503075 + 0.2049755424820002450503075 + >>> diff(scorergi, 0); 1/(power(3,'5/6')*gamma('1/3')) + 0.1494294524512754526382746 + 0.1494294524512754526382746 + >>> scorergi(+inf); scorergi(-inf) + 0.0 + 0.0 + >>> scorergi(1) + 0.2352184398104379375986902 + >>> scorergi(-1) + -0.1166722172960152826494198 + +Evaluation for large arguments:: + + >>> scorergi(10) + 0.03189600510067958798062034 + >>> scorergi(100) + 0.003183105228162961476590531 + >>> scorergi(1000000) + 0.0000003183098861837906721743873 + >>> 1/(pi*1000000) + 0.0000003183098861837906715377675 + >>> scorergi(-1000) + -0.08358288400262780392338014 + >>> scorergi(-100000) + 0.02886866118619660226809581 + >>> scorergi(50+10j) + (0.0061214102799778578790984 - 0.001224335676457532180747917j) + >>> scorergi(-50-10j) + (5.236047850352252236372551e+29 - 3.08254224233701381482228e+29j) + >>> scorergi(100000j) + (-8.806659285336231052679025e+6474077 + 8.684731303500835514850962e+6474077j) + +Verifying the connection between Gi and Hi:: + + >>> z = 0.25 + >>> scorergi(z) + scorerhi(z) + 0.7287469039362150078694543 + >>> airybi(z) + 0.7287469039362150078694543 + +Verifying the differential equation:: + + >>> for z in [-3.4, 0, 2.5, 1+2j]: + ... chop(diff(scorergi,z,2) - z*scorergi(z)) + ... + -0.3183098861837906715377675 + -0.3183098861837906715377675 + -0.3183098861837906715377675 + -0.3183098861837906715377675 + +Verifying the integral representation:: + + >>> z = 0.5 + >>> scorergi(z) + 0.2447210432765581976910539 + >>> Ai,Bi = airyai,airybi + >>> Bi(z)*(Ai(inf,-1)-Ai(z,-1)) + Ai(z)*(Bi(z,-1)-Bi(0,-1)) + 0.2447210432765581976910539 + +**References** + +1. [DLMF]_ section 9.12: Scorer Functions + +""" + +scorerhi = r""" +Evaluates the second Scorer function + +.. math :: + + \operatorname{Hi}(z) = + \operatorname{Bi}(z) \int_{-\infty}^z \operatorname{Ai}(t) dt - + \operatorname{Ai}(z) \int_{-\infty}^z \operatorname{Bi}(t) dt + +which gives a particular solution to the inhomogeneous Airy +differential equation `f''(z) - z f(z) = 1/\pi`. See also +:func:`~mpmath.scorergi`. + +**Plots** + +.. literalinclude :: /plots/hi.py +.. image :: /plots/hi.png +.. literalinclude :: /plots/hi_c.py +.. image :: /plots/hi_c.png + +**Examples** + +Some values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> scorerhi(0); 2/(power(3,'7/6')*gamma('2/3')) + 0.4099510849640004901006149 + 0.4099510849640004901006149 + >>> diff(scorerhi,0); 2/(power(3,'5/6')*gamma('1/3')) + 0.2988589049025509052765491 + 0.2988589049025509052765491 + >>> scorerhi(+inf); scorerhi(-inf) + +inf + 0.0 + >>> scorerhi(1) + 0.9722051551424333218376886 + >>> scorerhi(-1) + 0.2206696067929598945381098 + +Evaluation for large arguments:: + + >>> scorerhi(10) + 455641153.5163291358991077 + >>> scorerhi(100) + 6.041223996670201399005265e+288 + >>> scorerhi(1000000) + 7.138269638197858094311122e+289529652 + >>> scorerhi(-10) + 0.0317685352825022727415011 + >>> scorerhi(-100) + 0.003183092495767499864680483 + >>> scorerhi(100j) + (-6.366197716545672122983857e-9 + 0.003183098861710582761688475j) + >>> scorerhi(50+50j) + (-5.322076267321435669290334e+63 + 1.478450291165243789749427e+65j) + >>> scorerhi(-1000-1000j) + (0.0001591549432510502796565538 - 0.000159154943091895334973109j) + +Verifying the differential equation:: + + >>> for z in [-3.4, 0, 2, 1+2j]: + ... chop(diff(scorerhi,z,2) - z*scorerhi(z)) + ... + 0.3183098861837906715377675 + 0.3183098861837906715377675 + 0.3183098861837906715377675 + 0.3183098861837906715377675 + +Verifying the integral representation:: + + >>> z = 0.5 + >>> scorerhi(z) + 0.6095559998265972956089949 + >>> Ai,Bi = airyai,airybi + >>> Bi(z)*(Ai(z,-1)-Ai(-inf,-1)) - Ai(z)*(Bi(z,-1)-Bi(-inf,-1)) + 0.6095559998265972956089949 + +""" + + +stirling1 = r""" +Gives the Stirling number of the first kind `s(n,k)`, defined by + +.. math :: + + x(x-1)(x-2)\cdots(x-n+1) = \sum_{k=0}^n s(n,k) x^k. + +The value is computed using an integer recurrence. The implementation +is not optimized for approximating large values quickly. + +**Examples** + +Comparing with the generating function:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> taylor(lambda x: ff(x, 5), 0, 5) + [0.0, 24.0, -50.0, 35.0, -10.0, 1.0] + >>> [stirling1(5, k) for k in range(6)] + [0.0, 24.0, -50.0, 35.0, -10.0, 1.0] + +Recurrence relation:: + + >>> n, k = 5, 3 + >>> stirling1(n+1,k) + n*stirling1(n,k) - stirling1(n,k-1) + 0.0 + +The matrices of Stirling numbers of first and second kind are inverses +of each other:: + + >>> A = matrix(5, 5); B = matrix(5, 5) + >>> for n in range(5): + ... for k in range(5): + ... A[n,k] = stirling1(n,k) + ... B[n,k] = stirling2(n,k) + ... + >>> A * B + [1.0 0.0 0.0 0.0 0.0] + [0.0 1.0 0.0 0.0 0.0] + [0.0 0.0 1.0 0.0 0.0] + [0.0 0.0 0.0 1.0 0.0] + [0.0 0.0 0.0 0.0 1.0] + +Pass ``exact=True`` to obtain exact values of Stirling numbers as integers:: + + >>> stirling1(42, 5) + -2.864498971768501633736628e+50 + >>> print(stirling1(42, 5, exact=True)) + -286449897176850163373662803014001546235808317440000 + +""" + +stirling2 = r""" +Gives the Stirling number of the second kind `S(n,k)`, defined by + +.. math :: + + x^n = \sum_{k=0}^n S(n,k) x(x-1)(x-2)\cdots(x-k+1) + +The value is computed using integer arithmetic to evaluate a power sum. +The implementation is not optimized for approximating large values quickly. + +**Examples** + +Comparing with the generating function:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> taylor(lambda x: sum(stirling2(5,k) * ff(x,k) for k in range(6)), 0, 5) + [0.0, 0.0, 0.0, 0.0, 0.0, 1.0] + +Recurrence relation:: + + >>> n, k = 5, 3 + >>> stirling2(n+1,k) - k*stirling2(n,k) - stirling2(n,k-1) + 0.0 + +Pass ``exact=True`` to obtain exact values of Stirling numbers as integers:: + + >>> stirling2(52, 10) + 2.641822121003543906807485e+45 + >>> print(stirling2(52, 10, exact=True)) + 2641822121003543906807485307053638921722527655 + + +""" + +squarew = r""" +Computes the square wave function using the definition: + +.. math:: + x(t) = A(-1)^{\left\lfloor{2t / P}\right\rfloor} + +where `P` is the period of the wave and `A` is the amplitude. + +**Examples** + +Square wave with period = 2, amplitude = 1 :: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> squarew(0,1,2) + 1.0 + >>> squarew(0.5,1,2) + 1.0 + >>> squarew(1,1,2) + -1.0 + >>> squarew(1.5,1,2) + -1.0 + >>> squarew(2,1,2) + 1.0 +""" + +trianglew = r""" +Computes the triangle wave function using the definition: + +.. math:: + x(t) = 2A\left(\frac{1}{2}-\left|1-2 \operatorname{frac}\left(\frac{x}{P}+\frac{1}{4}\right)\right|\right) + +where :math:`\operatorname{frac}\left(\frac{t}{T}\right) = \frac{t}{T}-\left\lfloor{\frac{t}{T}}\right\rfloor` +, `P` is the period of the wave, and `A` is the amplitude. + +**Examples** + +Triangle wave with period = 2, amplitude = 1 :: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> trianglew(0,1,2) + 0.0 + >>> trianglew(0.25,1,2) + 0.5 + >>> trianglew(0.5,1,2) + 1.0 + >>> trianglew(1,1,2) + 0.0 + >>> trianglew(1.5,1,2) + -1.0 + >>> trianglew(2,1,2) + 0.0 +""" + +sawtoothw = r""" +Computes the sawtooth wave function using the definition: + +.. math:: + x(t) = A\operatorname{frac}\left(\frac{t}{T}\right) + +where :math:`\operatorname{frac}\left(\frac{t}{T}\right) = \frac{t}{T}-\left\lfloor{\frac{t}{T}}\right\rfloor`, +`P` is the period of the wave, and `A` is the amplitude. + +**Examples** + +Sawtooth wave with period = 2, amplitude = 1 :: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> sawtoothw(0,1,2) + 0.0 + >>> sawtoothw(0.5,1,2) + 0.25 + >>> sawtoothw(1,1,2) + 0.5 + >>> sawtoothw(1.5,1,2) + 0.75 + >>> sawtoothw(2,1,2) + 0.0 +""" + +unit_triangle = r""" +Computes the unit triangle using the definition: + +.. math:: + x(t) = A(-\left| t \right| + 1) + +where `A` is the amplitude. + +**Examples** + +Unit triangle with amplitude = 1 :: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> unit_triangle(-1,1) + 0.0 + >>> unit_triangle(-0.5,1) + 0.5 + >>> unit_triangle(0,1) + 1.0 + >>> unit_triangle(0.5,1) + 0.5 + >>> unit_triangle(1,1) + 0.0 +""" + +sigmoid = r""" +Computes the sigmoid function using the definition: + +.. math:: + x(t) = \frac{A}{1 + e^{-t}} + +where `A` is the amplitude. + +**Examples** + +Sigmoid function with amplitude = 1 :: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> sigmoid(-1,1) + 0.2689414213699951207488408 + >>> sigmoid(-0.5,1) + 0.3775406687981454353610994 + >>> sigmoid(0,1) + 0.5 + >>> sigmoid(0.5,1) + 0.6224593312018545646389006 + >>> sigmoid(1,1) + 0.7310585786300048792511592 + +""" diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/__init__.py b/venv/lib/python3.10/site-packages/mpmath/functions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5896ed0579eceab086dc5c67eaa649b6061a53dc --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/functions/__init__.py @@ -0,0 +1,14 @@ +from . import functions +# Hack to update methods +from . import factorials +from . import hypergeometric +from . import expintegrals +from . import bessel +from . import orthogonal +from . import theta +from . import elliptic +from . import signals +from . import zeta +from . import rszeta +from . import zetazeros +from . import qfunctions diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..800eec34a5a5a0953fdb961ff74eb91dd3722177 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/bessel.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/bessel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd91db9cfb99445d7fc0a75f952960fa9003580d Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/bessel.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/elliptic.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/elliptic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d089c82aecd1cd9f5e9db7c6f327e4613575578 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/elliptic.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/expintegrals.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/expintegrals.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71aa81448de1e73b6b9e2dbbb28353c0ed2ab1a0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/expintegrals.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/factorials.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/factorials.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff7a83297c7a09daac200183dfea8b297d585825 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/factorials.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/functions.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/functions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c9f74897fc76c0f57b582c80646cc724cf384b0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/functions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/hypergeometric.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/hypergeometric.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..806034da99512609ebddf9b2367e133eca898736 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/hypergeometric.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/orthogonal.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/orthogonal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23850b12621facd55aca7a46f43520102e86b5fc Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/orthogonal.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/qfunctions.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/qfunctions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2972607593b7f304ac2bc787915e85d7b4616414 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/qfunctions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/rszeta.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/rszeta.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b7cd4b5c181cb5c63c02696c374655ce3cbffb7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/rszeta.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/signals.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/signals.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc92e011c96beaa6e376b1830a976fb9e1ee540a Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/signals.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/theta.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/theta.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a21c8abc7baaa4a47d906d36c177ed41e34b489 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/theta.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/zeta.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/zeta.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1f092cb294dba6b32ce0039a17ca09093c68e9a Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/zeta.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/zetazeros.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/zetazeros.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17e74b4843b740456fb45030a85ae256b72b56b3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/functions/__pycache__/zetazeros.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/bessel.py b/venv/lib/python3.10/site-packages/mpmath/functions/bessel.py new file mode 100644 index 0000000000000000000000000000000000000000..8b41d87bb0118de61d5561433dabcb181f872f84 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/functions/bessel.py @@ -0,0 +1,1108 @@ +from .functions import defun, defun_wrapped + +@defun +def j0(ctx, x): + """Computes the Bessel function `J_0(x)`. See :func:`~mpmath.besselj`.""" + return ctx.besselj(0, x) + +@defun +def j1(ctx, x): + """Computes the Bessel function `J_1(x)`. See :func:`~mpmath.besselj`.""" + return ctx.besselj(1, x) + +@defun +def besselj(ctx, n, z, derivative=0, **kwargs): + if type(n) is int: + n_isint = True + else: + n = ctx.convert(n) + n_isint = ctx.isint(n) + if n_isint: + n = int(ctx._re(n)) + if n_isint and n < 0: + return (-1)**n * ctx.besselj(-n, z, derivative, **kwargs) + z = ctx.convert(z) + M = ctx.mag(z) + if derivative: + d = ctx.convert(derivative) + # TODO: the integer special-casing shouldn't be necessary. + # However, the hypergeometric series gets inaccurate for large d + # because of inaccurate pole cancellation at a pole far from + # zero (needs to be fixed in hypercomb or hypsum) + if ctx.isint(d) and d >= 0: + d = int(d) + orig = ctx.prec + try: + ctx.prec += 15 + v = ctx.fsum((-1)**k * ctx.binomial(d,k) * ctx.besselj(2*k+n-d,z) + for k in range(d+1)) + finally: + ctx.prec = orig + v *= ctx.mpf(2)**(-d) + else: + def h(n,d): + r = ctx.fmul(ctx.fmul(z, z, prec=ctx.prec+M), -0.25, exact=True) + B = [0.5*(n-d+1), 0.5*(n-d+2)] + T = [([2,ctx.pi,z],[d-2*n,0.5,n-d],[],B,[(n+1)*0.5,(n+2)*0.5],B+[n+1],r)] + return T + v = ctx.hypercomb(h, [n,d], **kwargs) + else: + # Fast case: J_n(x), n int, appropriate magnitude for fixed-point calculation + if (not derivative) and n_isint and abs(M) < 10 and abs(n) < 20: + try: + return ctx._besselj(n, z) + except NotImplementedError: + pass + if not z: + if not n: + v = ctx.one + n+z + elif ctx.re(n) > 0: + v = n*z + else: + v = ctx.inf + z + n + else: + #v = 0 + orig = ctx.prec + try: + # XXX: workaround for accuracy in low level hypergeometric series + # when alternating, large arguments + ctx.prec += min(3*abs(M), ctx.prec) + w = ctx.fmul(z, 0.5, exact=True) + def h(n): + r = ctx.fneg(ctx.fmul(w, w, prec=max(0,ctx.prec+M)), exact=True) + return [([w], [n], [], [n+1], [], [n+1], r)] + v = ctx.hypercomb(h, [n], **kwargs) + finally: + ctx.prec = orig + v = +v + return v + +@defun +def besseli(ctx, n, z, derivative=0, **kwargs): + n = ctx.convert(n) + z = ctx.convert(z) + if not z: + if derivative: + raise ValueError + if not n: + # I(0,0) = 1 + return 1+n+z + if ctx.isint(n): + return 0*(n+z) + r = ctx.re(n) + if r == 0: + return ctx.nan*(n+z) + elif r > 0: + return 0*(n+z) + else: + return ctx.inf+(n+z) + M = ctx.mag(z) + if derivative: + d = ctx.convert(derivative) + def h(n,d): + r = ctx.fmul(ctx.fmul(z, z, prec=ctx.prec+M), 0.25, exact=True) + B = [0.5*(n-d+1), 0.5*(n-d+2), n+1] + T = [([2,ctx.pi,z],[d-2*n,0.5,n-d],[n+1],B,[(n+1)*0.5,(n+2)*0.5],B,r)] + return T + v = ctx.hypercomb(h, [n,d], **kwargs) + else: + def h(n): + w = ctx.fmul(z, 0.5, exact=True) + r = ctx.fmul(w, w, prec=max(0,ctx.prec+M)) + return [([w], [n], [], [n+1], [], [n+1], r)] + v = ctx.hypercomb(h, [n], **kwargs) + return v + +@defun_wrapped +def bessely(ctx, n, z, derivative=0, **kwargs): + if not z: + if derivative: + # Not implemented + raise ValueError + if not n: + # ~ log(z/2) + return -ctx.inf + (n+z) + if ctx.im(n): + return ctx.nan * (n+z) + r = ctx.re(n) + q = n+0.5 + if ctx.isint(q): + if n > 0: + return -ctx.inf + (n+z) + else: + return 0 * (n+z) + if r < 0 and int(ctx.floor(q)) % 2: + return ctx.inf + (n+z) + else: + return ctx.ninf + (n+z) + # XXX: use hypercomb + ctx.prec += 10 + m, d = ctx.nint_distance(n) + if d < -ctx.prec: + h = +ctx.eps + ctx.prec *= 2 + n += h + elif d < 0: + ctx.prec -= d + # TODO: avoid cancellation for imaginary arguments + cos, sin = ctx.cospi_sinpi(n) + return (ctx.besselj(n,z,derivative,**kwargs)*cos - \ + ctx.besselj(-n,z,derivative,**kwargs))/sin + +@defun_wrapped +def besselk(ctx, n, z, **kwargs): + if not z: + return ctx.inf + M = ctx.mag(z) + if M < 1: + # Represent as limit definition + def h(n): + r = (z/2)**2 + T1 = [z, 2], [-n, n-1], [n], [], [], [1-n], r + T2 = [z, 2], [n, -n-1], [-n], [], [], [1+n], r + return T1, T2 + # We could use the limit definition always, but it leads + # to very bad cancellation (of exponentially large terms) + # for large real z + # Instead represent in terms of 2F0 + else: + ctx.prec += M + def h(n): + return [([ctx.pi/2, z, ctx.exp(-z)], [0.5,-0.5,1], [], [], \ + [n+0.5, 0.5-n], [], -1/(2*z))] + return ctx.hypercomb(h, [n], **kwargs) + +@defun_wrapped +def hankel1(ctx,n,x,**kwargs): + return ctx.besselj(n,x,**kwargs) + ctx.j*ctx.bessely(n,x,**kwargs) + +@defun_wrapped +def hankel2(ctx,n,x,**kwargs): + return ctx.besselj(n,x,**kwargs) - ctx.j*ctx.bessely(n,x,**kwargs) + +@defun_wrapped +def whitm(ctx,k,m,z,**kwargs): + if z == 0: + # M(k,m,z) = 0^(1/2+m) + if ctx.re(m) > -0.5: + return z + elif ctx.re(m) < -0.5: + return ctx.inf + z + else: + return ctx.nan * z + x = ctx.fmul(-0.5, z, exact=True) + y = 0.5+m + return ctx.exp(x) * z**y * ctx.hyp1f1(y-k, 1+2*m, z, **kwargs) + +@defun_wrapped +def whitw(ctx,k,m,z,**kwargs): + if z == 0: + g = abs(ctx.re(m)) + if g < 0.5: + return z + elif g > 0.5: + return ctx.inf + z + else: + return ctx.nan * z + x = ctx.fmul(-0.5, z, exact=True) + y = 0.5+m + return ctx.exp(x) * z**y * ctx.hyperu(y-k, 1+2*m, z, **kwargs) + +@defun +def hyperu(ctx, a, b, z, **kwargs): + a, atype = ctx._convert_param(a) + b, btype = ctx._convert_param(b) + z = ctx.convert(z) + if not z: + if ctx.re(b) <= 1: + return ctx.gammaprod([1-b],[a-b+1]) + else: + return ctx.inf + z + bb = 1+a-b + bb, bbtype = ctx._convert_param(bb) + try: + orig = ctx.prec + try: + ctx.prec += 10 + v = ctx.hypsum(2, 0, (atype, bbtype), [a, bb], -1/z, maxterms=ctx.prec) + return v / z**a + finally: + ctx.prec = orig + except ctx.NoConvergence: + pass + def h(a,b): + w = ctx.sinpi(b) + T1 = ([ctx.pi,w],[1,-1],[],[a-b+1,b],[a],[b],z) + T2 = ([-ctx.pi,w,z],[1,-1,1-b],[],[a,2-b],[a-b+1],[2-b],z) + return T1, T2 + return ctx.hypercomb(h, [a,b], **kwargs) + +@defun +def struveh(ctx,n,z, **kwargs): + n = ctx.convert(n) + z = ctx.convert(z) + # http://functions.wolfram.com/Bessel-TypeFunctions/StruveH/26/01/02/ + def h(n): + return [([z/2, 0.5*ctx.sqrt(ctx.pi)], [n+1, -1], [], [n+1.5], [1], [1.5, n+1.5], -(z/2)**2)] + return ctx.hypercomb(h, [n], **kwargs) + +@defun +def struvel(ctx,n,z, **kwargs): + n = ctx.convert(n) + z = ctx.convert(z) + # http://functions.wolfram.com/Bessel-TypeFunctions/StruveL/26/01/02/ + def h(n): + return [([z/2, 0.5*ctx.sqrt(ctx.pi)], [n+1, -1], [], [n+1.5], [1], [1.5, n+1.5], (z/2)**2)] + return ctx.hypercomb(h, [n], **kwargs) + +def _anger(ctx,which,v,z,**kwargs): + v = ctx._convert_param(v)[0] + z = ctx.convert(z) + def h(v): + b = ctx.mpq_1_2 + u = v*b + m = b*3 + a1,a2,b1,b2 = m-u, m+u, 1-u, 1+u + c, s = ctx.cospi_sinpi(u) + if which == 0: + A, B = [b*z, s], [c] + if which == 1: + A, B = [b*z, -c], [s] + w = ctx.square_exp_arg(z, mult=-0.25) + T1 = A, [1, 1], [], [a1,a2], [1], [a1,a2], w + T2 = B, [1], [], [b1,b2], [1], [b1,b2], w + return T1, T2 + return ctx.hypercomb(h, [v], **kwargs) + +@defun +def angerj(ctx, v, z, **kwargs): + return _anger(ctx, 0, v, z, **kwargs) + +@defun +def webere(ctx, v, z, **kwargs): + return _anger(ctx, 1, v, z, **kwargs) + +@defun +def lommels1(ctx, u, v, z, **kwargs): + u = ctx._convert_param(u)[0] + v = ctx._convert_param(v)[0] + z = ctx.convert(z) + def h(u,v): + b = ctx.mpq_1_2 + w = ctx.square_exp_arg(z, mult=-0.25) + return ([u-v+1, u+v+1, z], [-1, -1, u+1], [], [], [1], \ + [b*(u-v+3),b*(u+v+3)], w), + return ctx.hypercomb(h, [u,v], **kwargs) + +@defun +def lommels2(ctx, u, v, z, **kwargs): + u = ctx._convert_param(u)[0] + v = ctx._convert_param(v)[0] + z = ctx.convert(z) + # Asymptotic expansion (GR p. 947) -- need to be careful + # not to use for small arguments + # def h(u,v): + # b = ctx.mpq_1_2 + # w = -(z/2)**(-2) + # return ([z], [u-1], [], [], [b*(1-u+v)], [b*(1-u-v)], w), + def h(u,v): + b = ctx.mpq_1_2 + w = ctx.square_exp_arg(z, mult=-0.25) + T1 = [u-v+1, u+v+1, z], [-1, -1, u+1], [], [], [1], [b*(u-v+3),b*(u+v+3)], w + T2 = [2, z], [u+v-1, -v], [v, b*(u+v+1)], [b*(v-u+1)], [], [1-v], w + T3 = [2, z], [u-v-1, v], [-v, b*(u-v+1)], [b*(1-u-v)], [], [1+v], w + #c1 = ctx.cospi((u-v)*b) + #c2 = ctx.cospi((u+v)*b) + #s = ctx.sinpi(v) + #r1 = (u-v+1)*b + #r2 = (u+v+1)*b + #T2 = [c1, s, z, 2], [1, -1, -v, v], [], [-v+1], [], [-v+1], w + #T3 = [-c2, s, z, 2], [1, -1, v, -v], [], [v+1], [], [v+1], w + #T2 = [c1, s, z, 2], [1, -1, -v, v+u-1], [r1, r2], [-v+1], [], [-v+1], w + #T3 = [-c2, s, z, 2], [1, -1, v, -v+u-1], [r1, r2], [v+1], [], [v+1], w + return T1, T2, T3 + return ctx.hypercomb(h, [u,v], **kwargs) + +@defun +def ber(ctx, n, z, **kwargs): + n = ctx.convert(n) + z = ctx.convert(z) + # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinBer2/26/01/02/0001/ + def h(n): + r = -(z/4)**4 + cos, sin = ctx.cospi_sinpi(-0.75*n) + T1 = [cos, z/2], [1, n], [], [n+1], [], [0.5, 0.5*(n+1), 0.5*n+1], r + T2 = [sin, z/2], [1, n+2], [], [n+2], [], [1.5, 0.5*(n+3), 0.5*n+1], r + return T1, T2 + return ctx.hypercomb(h, [n], **kwargs) + +@defun +def bei(ctx, n, z, **kwargs): + n = ctx.convert(n) + z = ctx.convert(z) + # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinBei2/26/01/02/0001/ + def h(n): + r = -(z/4)**4 + cos, sin = ctx.cospi_sinpi(0.75*n) + T1 = [cos, z/2], [1, n+2], [], [n+2], [], [1.5, 0.5*(n+3), 0.5*n+1], r + T2 = [sin, z/2], [1, n], [], [n+1], [], [0.5, 0.5*(n+1), 0.5*n+1], r + return T1, T2 + return ctx.hypercomb(h, [n], **kwargs) + +@defun +def ker(ctx, n, z, **kwargs): + n = ctx.convert(n) + z = ctx.convert(z) + # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinKer2/26/01/02/0001/ + def h(n): + r = -(z/4)**4 + cos1, sin1 = ctx.cospi_sinpi(0.25*n) + cos2, sin2 = ctx.cospi_sinpi(0.75*n) + T1 = [2, z, 4*cos1], [-n-3, n, 1], [-n], [], [], [0.5, 0.5*(1+n), 0.5*(n+2)], r + T2 = [2, z, -sin1], [-n-3, 2+n, 1], [-n-1], [], [], [1.5, 0.5*(3+n), 0.5*(n+2)], r + T3 = [2, z, 4*cos2], [n-3, -n, 1], [n], [], [], [0.5, 0.5*(1-n), 1-0.5*n], r + T4 = [2, z, -sin2], [n-3, 2-n, 1], [n-1], [], [], [1.5, 0.5*(3-n), 1-0.5*n], r + return T1, T2, T3, T4 + return ctx.hypercomb(h, [n], **kwargs) + +@defun +def kei(ctx, n, z, **kwargs): + n = ctx.convert(n) + z = ctx.convert(z) + # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinKei2/26/01/02/0001/ + def h(n): + r = -(z/4)**4 + cos1, sin1 = ctx.cospi_sinpi(0.75*n) + cos2, sin2 = ctx.cospi_sinpi(0.25*n) + T1 = [-cos1, 2, z], [1, n-3, 2-n], [n-1], [], [], [1.5, 0.5*(3-n), 1-0.5*n], r + T2 = [-sin1, 2, z], [1, n-1, -n], [n], [], [], [0.5, 0.5*(1-n), 1-0.5*n], r + T3 = [-sin2, 2, z], [1, -n-1, n], [-n], [], [], [0.5, 0.5*(n+1), 0.5*(n+2)], r + T4 = [-cos2, 2, z], [1, -n-3, n+2], [-n-1], [], [], [1.5, 0.5*(n+3), 0.5*(n+2)], r + return T1, T2, T3, T4 + return ctx.hypercomb(h, [n], **kwargs) + +# TODO: do this more generically? +def c_memo(f): + name = f.__name__ + def f_wrapped(ctx): + cache = ctx._misc_const_cache + prec = ctx.prec + p,v = cache.get(name, (-1,0)) + if p >= prec: + return +v + else: + cache[name] = (prec, f(ctx)) + return cache[name][1] + return f_wrapped + +@c_memo +def _airyai_C1(ctx): + return 1 / (ctx.cbrt(9) * ctx.gamma(ctx.mpf(2)/3)) + +@c_memo +def _airyai_C2(ctx): + return -1 / (ctx.cbrt(3) * ctx.gamma(ctx.mpf(1)/3)) + +@c_memo +def _airybi_C1(ctx): + return 1 / (ctx.nthroot(3,6) * ctx.gamma(ctx.mpf(2)/3)) + +@c_memo +def _airybi_C2(ctx): + return ctx.nthroot(3,6) / ctx.gamma(ctx.mpf(1)/3) + +def _airybi_n2_inf(ctx): + prec = ctx.prec + try: + v = ctx.power(3,'2/3')*ctx.gamma('2/3')/(2*ctx.pi) + finally: + ctx.prec = prec + return +v + +# Derivatives at z = 0 +# TODO: could be expressed more elegantly using triple factorials +def _airyderiv_0(ctx, z, n, ntype, which): + if ntype == 'Z': + if n < 0: + return z + r = ctx.mpq_1_3 + prec = ctx.prec + try: + ctx.prec += 10 + v = ctx.gamma((n+1)*r) * ctx.power(3,n*r) / ctx.pi + if which == 0: + v *= ctx.sinpi(2*(n+1)*r) + v /= ctx.power(3,'2/3') + else: + v *= abs(ctx.sinpi(2*(n+1)*r)) + v /= ctx.power(3,'1/6') + finally: + ctx.prec = prec + return +v + z + else: + # singular (does the limit exist?) + raise NotImplementedError + +@defun +def airyai(ctx, z, derivative=0, **kwargs): + z = ctx.convert(z) + if derivative: + n, ntype = ctx._convert_param(derivative) + else: + n = 0 + # Values at infinities + if not ctx.isnormal(z) and z: + if n and ntype == 'Z': + if n == -1: + if z == ctx.inf: + return ctx.mpf(1)/3 + 1/z + if z == ctx.ninf: + return ctx.mpf(-2)/3 + 1/z + if n < -1: + if z == ctx.inf: + return z + if z == ctx.ninf: + return (-1)**n * (-z) + if (not n) and z == ctx.inf or z == ctx.ninf: + return 1/z + # TODO: limits + raise ValueError("essential singularity of Ai(z)") + # Account for exponential scaling + if z: + extraprec = max(0, int(1.5*ctx.mag(z))) + else: + extraprec = 0 + if n: + if n == 1: + def h(): + # http://functions.wolfram.com/03.07.06.0005.01 + if ctx._re(z) > 4: + ctx.prec += extraprec + w = z**1.5; r = -0.75/w; u = -2*w/3 + ctx.prec -= extraprec + C = -ctx.exp(u)/(2*ctx.sqrt(ctx.pi))*ctx.nthroot(z,4) + return ([C],[1],[],[],[(-1,6),(7,6)],[],r), + # http://functions.wolfram.com/03.07.26.0001.01 + else: + ctx.prec += extraprec + w = z**3 / 9 + ctx.prec -= extraprec + C1 = _airyai_C1(ctx) * 0.5 + C2 = _airyai_C2(ctx) + T1 = [C1,z],[1,2],[],[],[],[ctx.mpq_5_3],w + T2 = [C2],[1],[],[],[],[ctx.mpq_1_3],w + return T1, T2 + return ctx.hypercomb(h, [], **kwargs) + else: + if z == 0: + return _airyderiv_0(ctx, z, n, ntype, 0) + # http://functions.wolfram.com/03.05.20.0004.01 + def h(n): + ctx.prec += extraprec + w = z**3/9 + ctx.prec -= extraprec + q13,q23,q43 = ctx.mpq_1_3, ctx.mpq_2_3, ctx.mpq_4_3 + a1=q13; a2=1; b1=(1-n)*q13; b2=(2-n)*q13; b3=1-n*q13 + T1 = [3, z], [n-q23, -n], [a1], [b1,b2,b3], \ + [a1,a2], [b1,b2,b3], w + a1=q23; b1=(2-n)*q13; b2=1-n*q13; b3=(4-n)*q13 + T2 = [3, z, -z], [n-q43, -n, 1], [a1], [b1,b2,b3], \ + [a1,a2], [b1,b2,b3], w + return T1, T2 + v = ctx.hypercomb(h, [n], **kwargs) + if ctx._is_real_type(z) and ctx.isint(n): + v = ctx._re(v) + return v + else: + def h(): + if ctx._re(z) > 4: + # We could use 1F1, but it results in huge cancellation; + # the following expansion is better. + # TODO: asymptotic series for derivatives + ctx.prec += extraprec + w = z**1.5; r = -0.75/w; u = -2*w/3 + ctx.prec -= extraprec + C = ctx.exp(u)/(2*ctx.sqrt(ctx.pi)*ctx.nthroot(z,4)) + return ([C],[1],[],[],[(1,6),(5,6)],[],r), + else: + ctx.prec += extraprec + w = z**3 / 9 + ctx.prec -= extraprec + C1 = _airyai_C1(ctx) + C2 = _airyai_C2(ctx) + T1 = [C1],[1],[],[],[],[ctx.mpq_2_3],w + T2 = [z*C2],[1],[],[],[],[ctx.mpq_4_3],w + return T1, T2 + return ctx.hypercomb(h, [], **kwargs) + +@defun +def airybi(ctx, z, derivative=0, **kwargs): + z = ctx.convert(z) + if derivative: + n, ntype = ctx._convert_param(derivative) + else: + n = 0 + # Values at infinities + if not ctx.isnormal(z) and z: + if n and ntype == 'Z': + if z == ctx.inf: + return z + if z == ctx.ninf: + if n == -1: + return 1/z + if n == -2: + return _airybi_n2_inf(ctx) + if n < -2: + return (-1)**n * (-z) + if not n: + if z == ctx.inf: + return z + if z == ctx.ninf: + return 1/z + # TODO: limits + raise ValueError("essential singularity of Bi(z)") + if z: + extraprec = max(0, int(1.5*ctx.mag(z))) + else: + extraprec = 0 + if n: + if n == 1: + # http://functions.wolfram.com/03.08.26.0001.01 + def h(): + ctx.prec += extraprec + w = z**3 / 9 + ctx.prec -= extraprec + C1 = _airybi_C1(ctx)*0.5 + C2 = _airybi_C2(ctx) + T1 = [C1,z],[1,2],[],[],[],[ctx.mpq_5_3],w + T2 = [C2],[1],[],[],[],[ctx.mpq_1_3],w + return T1, T2 + return ctx.hypercomb(h, [], **kwargs) + else: + if z == 0: + return _airyderiv_0(ctx, z, n, ntype, 1) + def h(n): + ctx.prec += extraprec + w = z**3/9 + ctx.prec -= extraprec + q13,q23,q43 = ctx.mpq_1_3, ctx.mpq_2_3, ctx.mpq_4_3 + q16 = ctx.mpq_1_6 + q56 = ctx.mpq_5_6 + a1=q13; a2=1; b1=(1-n)*q13; b2=(2-n)*q13; b3=1-n*q13 + T1 = [3, z], [n-q16, -n], [a1], [b1,b2,b3], \ + [a1,a2], [b1,b2,b3], w + a1=q23; b1=(2-n)*q13; b2=1-n*q13; b3=(4-n)*q13 + T2 = [3, z], [n-q56, 1-n], [a1], [b1,b2,b3], \ + [a1,a2], [b1,b2,b3], w + return T1, T2 + v = ctx.hypercomb(h, [n], **kwargs) + if ctx._is_real_type(z) and ctx.isint(n): + v = ctx._re(v) + return v + else: + def h(): + ctx.prec += extraprec + w = z**3 / 9 + ctx.prec -= extraprec + C1 = _airybi_C1(ctx) + C2 = _airybi_C2(ctx) + T1 = [C1],[1],[],[],[],[ctx.mpq_2_3],w + T2 = [z*C2],[1],[],[],[],[ctx.mpq_4_3],w + return T1, T2 + return ctx.hypercomb(h, [], **kwargs) + +def _airy_zero(ctx, which, k, derivative, complex=False): + # Asymptotic formulas are given in DLMF section 9.9 + def U(t): return t**(2/3.)*(1-7/(t**2*48)) + def T(t): return t**(2/3.)*(1+5/(t**2*48)) + k = int(k) + if k < 1: + raise ValueError("k cannot be less than 1") + if not derivative in (0,1): + raise ValueError("Derivative should lie between 0 and 1") + if which == 0: + if derivative: + return ctx.findroot(lambda z: ctx.airyai(z,1), + -U(3*ctx.pi*(4*k-3)/8)) + return ctx.findroot(ctx.airyai, -T(3*ctx.pi*(4*k-1)/8)) + if which == 1 and complex == False: + if derivative: + return ctx.findroot(lambda z: ctx.airybi(z,1), + -U(3*ctx.pi*(4*k-1)/8)) + return ctx.findroot(ctx.airybi, -T(3*ctx.pi*(4*k-3)/8)) + if which == 1 and complex == True: + if derivative: + t = 3*ctx.pi*(4*k-3)/8 + 0.75j*ctx.ln2 + s = ctx.expjpi(ctx.mpf(1)/3) * T(t) + return ctx.findroot(lambda z: ctx.airybi(z,1), s) + t = 3*ctx.pi*(4*k-1)/8 + 0.75j*ctx.ln2 + s = ctx.expjpi(ctx.mpf(1)/3) * U(t) + return ctx.findroot(ctx.airybi, s) + +@defun +def airyaizero(ctx, k, derivative=0): + return _airy_zero(ctx, 0, k, derivative, False) + +@defun +def airybizero(ctx, k, derivative=0, complex=False): + return _airy_zero(ctx, 1, k, derivative, complex) + +def _scorer(ctx, z, which, kwargs): + z = ctx.convert(z) + if ctx.isinf(z): + if z == ctx.inf: + if which == 0: return 1/z + if which == 1: return z + if z == ctx.ninf: + return 1/z + raise ValueError("essential singularity") + if z: + extraprec = max(0, int(1.5*ctx.mag(z))) + else: + extraprec = 0 + if kwargs.get('derivative'): + raise NotImplementedError + # Direct asymptotic expansions, to avoid + # exponentially large cancellation + try: + if ctx.mag(z) > 3: + if which == 0 and abs(ctx.arg(z)) < ctx.pi/3 * 0.999: + def h(): + return (([ctx.pi,z],[-1,-1],[],[],[(1,3),(2,3),1],[],9/z**3),) + return ctx.hypercomb(h, [], maxterms=ctx.prec, force_series=True) + if which == 1 and abs(ctx.arg(-z)) < 2*ctx.pi/3 * 0.999: + def h(): + return (([-ctx.pi,z],[-1,-1],[],[],[(1,3),(2,3),1],[],9/z**3),) + return ctx.hypercomb(h, [], maxterms=ctx.prec, force_series=True) + except ctx.NoConvergence: + pass + def h(): + A = ctx.airybi(z, **kwargs)/3 + B = -2*ctx.pi + if which == 1: + A *= 2 + B *= -1 + ctx.prec += extraprec + w = z**3/9 + ctx.prec -= extraprec + T1 = [A], [1], [], [], [], [], 0 + T2 = [B,z], [-1,2], [], [], [1], [ctx.mpq_4_3,ctx.mpq_5_3], w + return T1, T2 + return ctx.hypercomb(h, [], **kwargs) + +@defun +def scorergi(ctx, z, **kwargs): + return _scorer(ctx, z, 0, kwargs) + +@defun +def scorerhi(ctx, z, **kwargs): + return _scorer(ctx, z, 1, kwargs) + +@defun_wrapped +def coulombc(ctx, l, eta, _cache={}): + if (l, eta) in _cache and _cache[l,eta][0] >= ctx.prec: + return +_cache[l,eta][1] + G3 = ctx.loggamma(2*l+2) + G1 = ctx.loggamma(1+l+ctx.j*eta) + G2 = ctx.loggamma(1+l-ctx.j*eta) + v = 2**l * ctx.exp((-ctx.pi*eta+G1+G2)/2 - G3) + if not (ctx.im(l) or ctx.im(eta)): + v = ctx.re(v) + _cache[l,eta] = (ctx.prec, v) + return v + +@defun_wrapped +def coulombf(ctx, l, eta, z, w=1, chop=True, **kwargs): + # Regular Coulomb wave function + # Note: w can be either 1 or -1; the other may be better in some cases + # TODO: check that chop=True chops when and only when it should + #ctx.prec += 10 + def h(l, eta): + try: + jw = ctx.j*w + jwz = ctx.fmul(jw, z, exact=True) + jwz2 = ctx.fmul(jwz, -2, exact=True) + C = ctx.coulombc(l, eta) + T1 = [C, z, ctx.exp(jwz)], [1, l+1, 1], [], [], [1+l+jw*eta], \ + [2*l+2], jwz2 + except ValueError: + T1 = [0], [-1], [], [], [], [], 0 + return (T1,) + v = ctx.hypercomb(h, [l,eta], **kwargs) + if chop and (not ctx.im(l)) and (not ctx.im(eta)) and (not ctx.im(z)) and \ + (ctx.re(z) >= 0): + v = ctx.re(v) + return v + +@defun_wrapped +def _coulomb_chi(ctx, l, eta, _cache={}): + if (l, eta) in _cache and _cache[l,eta][0] >= ctx.prec: + return _cache[l,eta][1] + def terms(): + l2 = -l-1 + jeta = ctx.j*eta + return [ctx.loggamma(1+l+jeta) * (-0.5j), + ctx.loggamma(1+l-jeta) * (0.5j), + ctx.loggamma(1+l2+jeta) * (0.5j), + ctx.loggamma(1+l2-jeta) * (-0.5j), + -(l+0.5)*ctx.pi] + v = ctx.sum_accurately(terms, 1) + _cache[l,eta] = (ctx.prec, v) + return v + +@defun_wrapped +def coulombg(ctx, l, eta, z, w=1, chop=True, **kwargs): + # Irregular Coulomb wave function + # Note: w can be either 1 or -1; the other may be better in some cases + # TODO: check that chop=True chops when and only when it should + if not ctx._im(l): + l = ctx._re(l) # XXX: for isint + def h(l, eta): + # Force perturbation for integers and half-integers + if ctx.isint(l*2): + T1 = [0], [-1], [], [], [], [], 0 + return (T1,) + l2 = -l-1 + try: + chi = ctx._coulomb_chi(l, eta) + jw = ctx.j*w + s = ctx.sin(chi); c = ctx.cos(chi) + C1 = ctx.coulombc(l,eta) + C2 = ctx.coulombc(l2,eta) + u = ctx.exp(jw*z) + x = -2*jw*z + T1 = [s, C1, z, u, c], [-1, 1, l+1, 1, 1], [], [], \ + [1+l+jw*eta], [2*l+2], x + T2 = [-s, C2, z, u], [-1, 1, l2+1, 1], [], [], \ + [1+l2+jw*eta], [2*l2+2], x + return T1, T2 + except ValueError: + T1 = [0], [-1], [], [], [], [], 0 + return (T1,) + v = ctx.hypercomb(h, [l,eta], **kwargs) + if chop and (not ctx._im(l)) and (not ctx._im(eta)) and (not ctx._im(z)) and \ + (ctx._re(z) >= 0): + v = ctx._re(v) + return v + +def mcmahon(ctx,kind,prime,v,m): + """ + Computes an estimate for the location of the Bessel function zero + j_{v,m}, y_{v,m}, j'_{v,m} or y'_{v,m} using McMahon's asymptotic + expansion (Abramowitz & Stegun 9.5.12-13, DLMF 20.21(vi)). + + Returns (r,err) where r is the estimated location of the root + and err is a positive number estimating the error of the + asymptotic expansion. + """ + u = 4*v**2 + if kind == 1 and not prime: b = (4*m+2*v-1)*ctx.pi/4 + if kind == 2 and not prime: b = (4*m+2*v-3)*ctx.pi/4 + if kind == 1 and prime: b = (4*m+2*v-3)*ctx.pi/4 + if kind == 2 and prime: b = (4*m+2*v-1)*ctx.pi/4 + if not prime: + s1 = b + s2 = -(u-1)/(8*b) + s3 = -4*(u-1)*(7*u-31)/(3*(8*b)**3) + s4 = -32*(u-1)*(83*u**2-982*u+3779)/(15*(8*b)**5) + s5 = -64*(u-1)*(6949*u**3-153855*u**2+1585743*u-6277237)/(105*(8*b)**7) + if prime: + s1 = b + s2 = -(u+3)/(8*b) + s3 = -4*(7*u**2+82*u-9)/(3*(8*b)**3) + s4 = -32*(83*u**3+2075*u**2-3039*u+3537)/(15*(8*b)**5) + s5 = -64*(6949*u**4+296492*u**3-1248002*u**2+7414380*u-5853627)/(105*(8*b)**7) + terms = [s1,s2,s3,s4,s5] + s = s1 + err = 0.0 + for i in range(1,len(terms)): + if abs(terms[i]) < abs(terms[i-1]): + s += terms[i] + else: + err = abs(terms[i]) + if i == len(terms)-1: + err = abs(terms[-1]) + return s, err + +def generalized_bisection(ctx,f,a,b,n): + """ + Given f known to have exactly n simple roots within [a,b], + return a list of n intervals isolating the roots + and having opposite signs at the endpoints. + + TODO: this can be optimized, e.g. by reusing evaluation points. + """ + if n < 1: + raise ValueError("n cannot be less than 1") + N = n+1 + points = [] + signs = [] + while 1: + points = ctx.linspace(a,b,N) + signs = [ctx.sign(f(x)) for x in points] + ok_intervals = [(points[i],points[i+1]) for i in range(N-1) \ + if signs[i]*signs[i+1] == -1] + if len(ok_intervals) == n: + return ok_intervals + N = N*2 + +def find_in_interval(ctx, f, ab): + return ctx.findroot(f, ab, solver='illinois', verify=False) + +def bessel_zero(ctx, kind, prime, v, m, isoltol=0.01, _interval_cache={}): + prec = ctx.prec + workprec = max(prec, ctx.mag(v), ctx.mag(m))+10 + try: + ctx.prec = workprec + v = ctx.mpf(v) + m = int(m) + prime = int(prime) + if v < 0: + raise ValueError("v cannot be negative") + if m < 1: + raise ValueError("m cannot be less than 1") + if not prime in (0,1): + raise ValueError("prime should lie between 0 and 1") + if kind == 1: + if prime: f = lambda x: ctx.besselj(v,x,derivative=1) + else: f = lambda x: ctx.besselj(v,x) + if kind == 2: + if prime: f = lambda x: ctx.bessely(v,x,derivative=1) + else: f = lambda x: ctx.bessely(v,x) + # The first root of J' is very close to 0 for small + # orders, and this needs to be special-cased + if kind == 1 and prime and m == 1: + if v == 0: + return ctx.zero + if v <= 1: + # TODO: use v <= j'_{v,1} < y_{v,1}? + r = 2*ctx.sqrt(v*(1+v)/(v+2)) + return find_in_interval(ctx, f, (r/10, 2*r)) + if (kind,prime,v,m) in _interval_cache: + return find_in_interval(ctx, f, _interval_cache[kind,prime,v,m]) + r, err = mcmahon(ctx, kind, prime, v, m) + if err < isoltol: + return find_in_interval(ctx, f, (r-isoltol, r+isoltol)) + # An x such that 0 < x < r_{v,1} + if kind == 1 and not prime: low = 2.4 + if kind == 1 and prime: low = 1.8 + if kind == 2 and not prime: low = 0.8 + if kind == 2 and prime: low = 2.0 + n = m+1 + while 1: + r1, err = mcmahon(ctx, kind, prime, v, n) + if err < isoltol: + r2, err2 = mcmahon(ctx, kind, prime, v, n+1) + intervals = generalized_bisection(ctx, f, low, 0.5*(r1+r2), n) + for k, ab in enumerate(intervals): + _interval_cache[kind,prime,v,k+1] = ab + return find_in_interval(ctx, f, intervals[m-1]) + else: + n = n*2 + finally: + ctx.prec = prec + +@defun +def besseljzero(ctx, v, m, derivative=0): + r""" + For a real order `\nu \ge 0` and a positive integer `m`, returns + `j_{\nu,m}`, the `m`-th positive zero of the Bessel function of the + first kind `J_{\nu}(z)` (see :func:`~mpmath.besselj`). Alternatively, + with *derivative=1*, gives the first nonnegative simple zero + `j'_{\nu,m}` of `J'_{\nu}(z)`. + + The indexing convention is that used by Abramowitz & Stegun + and the DLMF. Note the special case `j'_{0,1} = 0`, while all other + zeros are positive. In effect, only simple zeros are counted + (all zeros of Bessel functions are simple except possibly `z = 0`) + and `j_{\nu,m}` becomes a monotonic function of both `\nu` + and `m`. + + The zeros are interlaced according to the inequalities + + .. math :: + + j'_{\nu,k} < j_{\nu,k} < j'_{\nu,k+1} + + j_{\nu,1} < j_{\nu+1,2} < j_{\nu,2} < j_{\nu+1,2} < j_{\nu,3} < \cdots + + **Examples** + + Initial zeros of the Bessel functions `J_0(z), J_1(z), J_2(z)`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> besseljzero(0,1); besseljzero(0,2); besseljzero(0,3) + 2.404825557695772768621632 + 5.520078110286310649596604 + 8.653727912911012216954199 + >>> besseljzero(1,1); besseljzero(1,2); besseljzero(1,3) + 3.831705970207512315614436 + 7.01558666981561875353705 + 10.17346813506272207718571 + >>> besseljzero(2,1); besseljzero(2,2); besseljzero(2,3) + 5.135622301840682556301402 + 8.417244140399864857783614 + 11.61984117214905942709415 + + Initial zeros of `J'_0(z), J'_1(z), J'_2(z)`:: + + 0.0 + 3.831705970207512315614436 + 7.01558666981561875353705 + >>> besseljzero(1,1,1); besseljzero(1,2,1); besseljzero(1,3,1) + 1.84118378134065930264363 + 5.331442773525032636884016 + 8.536316366346285834358961 + >>> besseljzero(2,1,1); besseljzero(2,2,1); besseljzero(2,3,1) + 3.054236928227140322755932 + 6.706133194158459146634394 + 9.969467823087595793179143 + + Zeros with large index:: + + >>> besseljzero(0,100); besseljzero(0,1000); besseljzero(0,10000) + 313.3742660775278447196902 + 3140.807295225078628895545 + 31415.14114171350798533666 + >>> besseljzero(5,100); besseljzero(5,1000); besseljzero(5,10000) + 321.1893195676003157339222 + 3148.657306813047523500494 + 31422.9947255486291798943 + >>> besseljzero(0,100,1); besseljzero(0,1000,1); besseljzero(0,10000,1) + 311.8018681873704508125112 + 3139.236339643802482833973 + 31413.57032947022399485808 + + Zeros of functions with large order:: + + >>> besseljzero(50,1) + 57.11689916011917411936228 + >>> besseljzero(50,2) + 62.80769876483536093435393 + >>> besseljzero(50,100) + 388.6936600656058834640981 + >>> besseljzero(50,1,1) + 52.99764038731665010944037 + >>> besseljzero(50,2,1) + 60.02631933279942589882363 + >>> besseljzero(50,100,1) + 387.1083151608726181086283 + + Zeros of functions with fractional order:: + + >>> besseljzero(0.5,1); besseljzero(1.5,1); besseljzero(2.25,4) + 3.141592653589793238462643 + 4.493409457909064175307881 + 15.15657692957458622921634 + + Both `J_{\nu}(z)` and `J'_{\nu}(z)` can be expressed as infinite + products over their zeros:: + + >>> v,z = 2, mpf(1) + >>> (z/2)**v/gamma(v+1) * \ + ... nprod(lambda k: 1-(z/besseljzero(v,k))**2, [1,inf]) + ... + 0.1149034849319004804696469 + >>> besselj(v,z) + 0.1149034849319004804696469 + >>> (z/2)**(v-1)/2/gamma(v) * \ + ... nprod(lambda k: 1-(z/besseljzero(v,k,1))**2, [1,inf]) + ... + 0.2102436158811325550203884 + >>> besselj(v,z,1) + 0.2102436158811325550203884 + + """ + return +bessel_zero(ctx, 1, derivative, v, m) + +@defun +def besselyzero(ctx, v, m, derivative=0): + r""" + For a real order `\nu \ge 0` and a positive integer `m`, returns + `y_{\nu,m}`, the `m`-th positive zero of the Bessel function of the + second kind `Y_{\nu}(z)` (see :func:`~mpmath.bessely`). Alternatively, + with *derivative=1*, gives the first positive zero `y'_{\nu,m}` of + `Y'_{\nu}(z)`. + + The zeros are interlaced according to the inequalities + + .. math :: + + y_{\nu,k} < y'_{\nu,k} < y_{\nu,k+1} + + y_{\nu,1} < y_{\nu+1,2} < y_{\nu,2} < y_{\nu+1,2} < y_{\nu,3} < \cdots + + **Examples** + + Initial zeros of the Bessel functions `Y_0(z), Y_1(z), Y_2(z)`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> besselyzero(0,1); besselyzero(0,2); besselyzero(0,3) + 0.8935769662791675215848871 + 3.957678419314857868375677 + 7.086051060301772697623625 + >>> besselyzero(1,1); besselyzero(1,2); besselyzero(1,3) + 2.197141326031017035149034 + 5.429681040794135132772005 + 8.596005868331168926429606 + >>> besselyzero(2,1); besselyzero(2,2); besselyzero(2,3) + 3.384241767149593472701426 + 6.793807513268267538291167 + 10.02347797936003797850539 + + Initial zeros of `Y'_0(z), Y'_1(z), Y'_2(z)`:: + + >>> besselyzero(0,1,1); besselyzero(0,2,1); besselyzero(0,3,1) + 2.197141326031017035149034 + 5.429681040794135132772005 + 8.596005868331168926429606 + >>> besselyzero(1,1,1); besselyzero(1,2,1); besselyzero(1,3,1) + 3.683022856585177699898967 + 6.941499953654175655751944 + 10.12340465543661307978775 + >>> besselyzero(2,1,1); besselyzero(2,2,1); besselyzero(2,3,1) + 5.002582931446063945200176 + 8.350724701413079526349714 + 11.57419546521764654624265 + + Zeros with large index:: + + >>> besselyzero(0,100); besselyzero(0,1000); besselyzero(0,10000) + 311.8034717601871549333419 + 3139.236498918198006794026 + 31413.57034538691205229188 + >>> besselyzero(5,100); besselyzero(5,1000); besselyzero(5,10000) + 319.6183338562782156235062 + 3147.086508524556404473186 + 31421.42392920214673402828 + >>> besselyzero(0,100,1); besselyzero(0,1000,1); besselyzero(0,10000,1) + 313.3726705426359345050449 + 3140.807136030340213610065 + 31415.14112579761578220175 + + Zeros of functions with large order:: + + >>> besselyzero(50,1) + 53.50285882040036394680237 + >>> besselyzero(50,2) + 60.11244442774058114686022 + >>> besselyzero(50,100) + 387.1096509824943957706835 + >>> besselyzero(50,1,1) + 56.96290427516751320063605 + >>> besselyzero(50,2,1) + 62.74888166945933944036623 + >>> besselyzero(50,100,1) + 388.6923300548309258355475 + + Zeros of functions with fractional order:: + + >>> besselyzero(0.5,1); besselyzero(1.5,1); besselyzero(2.25,4) + 1.570796326794896619231322 + 2.798386045783887136720249 + 13.56721208770735123376018 + + """ + return +bessel_zero(ctx, 2, derivative, v, m) diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/elliptic.py b/venv/lib/python3.10/site-packages/mpmath/functions/elliptic.py new file mode 100644 index 0000000000000000000000000000000000000000..1e198697fa042b7cc8bcba9e9e770f5c8106dad6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/functions/elliptic.py @@ -0,0 +1,1431 @@ +r""" +Elliptic functions historically comprise the elliptic integrals +and their inverses, and originate from the problem of computing the +arc length of an ellipse. From a more modern point of view, +an elliptic function is defined as a doubly periodic function, i.e. +a function which satisfies + +.. math :: + + f(z + 2 \omega_1) = f(z + 2 \omega_2) = f(z) + +for some half-periods `\omega_1, \omega_2` with +`\mathrm{Im}[\omega_1 / \omega_2] > 0`. The canonical elliptic +functions are the Jacobi elliptic functions. More broadly, this section +includes quasi-doubly periodic functions (such as the Jacobi theta +functions) and other functions useful in the study of elliptic functions. + +Many different conventions for the arguments of +elliptic functions are in use. It is even standard to use +different parameterizations for different functions in the same +text or software (and mpmath is no exception). +The usual parameters are the elliptic nome `q`, which usually +must satisfy `|q| < 1`; the elliptic parameter `m` (an arbitrary +complex number); the elliptic modulus `k` (an arbitrary complex +number); and the half-period ratio `\tau`, which usually must +satisfy `\mathrm{Im}[\tau] > 0`. +These quantities can be expressed in terms of each other +using the following relations: + +.. math :: + + m = k^2 + +.. math :: + + \tau = i \frac{K(1-m)}{K(m)} + +.. math :: + + q = e^{i \pi \tau} + +.. math :: + + k = \frac{\vartheta_2^2(q)}{\vartheta_3^2(q)} + +In addition, an alternative definition is used for the nome in +number theory, which we here denote by q-bar: + +.. math :: + + \bar{q} = q^2 = e^{2 i \pi \tau} + +For convenience, mpmath provides functions to convert +between the various parameters (:func:`~mpmath.qfrom`, :func:`~mpmath.mfrom`, +:func:`~mpmath.kfrom`, :func:`~mpmath.taufrom`, :func:`~mpmath.qbarfrom`). + +**References** + +1. [AbramowitzStegun]_ + +2. [WhittakerWatson]_ + +""" + +from .functions import defun, defun_wrapped + +@defun_wrapped +def eta(ctx, tau): + r""" + Returns the Dedekind eta function of tau in the upper half-plane. + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> eta(1j); gamma(0.25) / (2*pi**0.75) + (0.7682254223260566590025942 + 0.0j) + 0.7682254223260566590025942 + >>> tau = sqrt(2) + sqrt(5)*1j + >>> eta(-1/tau); sqrt(-1j*tau) * eta(tau) + (0.9022859908439376463573294 + 0.07985093673948098408048575j) + (0.9022859908439376463573295 + 0.07985093673948098408048575j) + >>> eta(tau+1); exp(pi*1j/12) * eta(tau) + (0.4493066139717553786223114 + 0.3290014793877986663915939j) + (0.4493066139717553786223114 + 0.3290014793877986663915939j) + >>> f = lambda z: diff(eta, z) / eta(z) + >>> chop(36*diff(f,tau)**2 - 24*diff(f,tau,2)*f(tau) + diff(f,tau,3)) + 0.0 + + """ + if ctx.im(tau) <= 0.0: + raise ValueError("eta is only defined in the upper half-plane") + q = ctx.expjpi(tau/12) + return q * ctx.qp(q**24) + +def nome(ctx, m): + m = ctx.convert(m) + if not m: + return m + if m == ctx.one: + return m + if ctx.isnan(m): + return m + if ctx.isinf(m): + if m == ctx.ninf: + return type(m)(-1) + else: + return ctx.mpc(-1) + a = ctx.ellipk(ctx.one-m) + b = ctx.ellipk(m) + v = ctx.exp(-ctx.pi*a/b) + if not ctx._im(m) and ctx._re(m) < 1: + if ctx._is_real_type(m): + return v.real + else: + return v.real + 0j + elif m == 2: + v = ctx.mpc(0, v.imag) + return v + +@defun_wrapped +def qfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None): + r""" + Returns the elliptic nome `q`, given any of `q, m, k, \tau, \bar{q}`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> qfrom(q=0.25) + 0.25 + >>> qfrom(m=mfrom(q=0.25)) + 0.25 + >>> qfrom(k=kfrom(q=0.25)) + 0.25 + >>> qfrom(tau=taufrom(q=0.25)) + (0.25 + 0.0j) + >>> qfrom(qbar=qbarfrom(q=0.25)) + 0.25 + + """ + if q is not None: + return ctx.convert(q) + if m is not None: + return nome(ctx, m) + if k is not None: + return nome(ctx, ctx.convert(k)**2) + if tau is not None: + return ctx.expjpi(tau) + if qbar is not None: + return ctx.sqrt(qbar) + +@defun_wrapped +def qbarfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None): + r""" + Returns the number-theoretic nome `\bar q`, given any of + `q, m, k, \tau, \bar{q}`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> qbarfrom(qbar=0.25) + 0.25 + >>> qbarfrom(q=qfrom(qbar=0.25)) + 0.25 + >>> qbarfrom(m=extraprec(20)(mfrom)(qbar=0.25)) # ill-conditioned + 0.25 + >>> qbarfrom(k=extraprec(20)(kfrom)(qbar=0.25)) # ill-conditioned + 0.25 + >>> qbarfrom(tau=taufrom(qbar=0.25)) + (0.25 + 0.0j) + + """ + if qbar is not None: + return ctx.convert(qbar) + if q is not None: + return ctx.convert(q) ** 2 + if m is not None: + return nome(ctx, m) ** 2 + if k is not None: + return nome(ctx, ctx.convert(k)**2) ** 2 + if tau is not None: + return ctx.expjpi(2*tau) + +@defun_wrapped +def taufrom(ctx, q=None, m=None, k=None, tau=None, qbar=None): + r""" + Returns the elliptic half-period ratio `\tau`, given any of + `q, m, k, \tau, \bar{q}`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> taufrom(tau=0.5j) + (0.0 + 0.5j) + >>> taufrom(q=qfrom(tau=0.5j)) + (0.0 + 0.5j) + >>> taufrom(m=mfrom(tau=0.5j)) + (0.0 + 0.5j) + >>> taufrom(k=kfrom(tau=0.5j)) + (0.0 + 0.5j) + >>> taufrom(qbar=qbarfrom(tau=0.5j)) + (0.0 + 0.5j) + + """ + if tau is not None: + return ctx.convert(tau) + if m is not None: + m = ctx.convert(m) + return ctx.j*ctx.ellipk(1-m)/ctx.ellipk(m) + if k is not None: + k = ctx.convert(k) + return ctx.j*ctx.ellipk(1-k**2)/ctx.ellipk(k**2) + if q is not None: + return ctx.log(q) / (ctx.pi*ctx.j) + if qbar is not None: + qbar = ctx.convert(qbar) + return ctx.log(qbar) / (2*ctx.pi*ctx.j) + +@defun_wrapped +def kfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None): + r""" + Returns the elliptic modulus `k`, given any of + `q, m, k, \tau, \bar{q}`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> kfrom(k=0.25) + 0.25 + >>> kfrom(m=mfrom(k=0.25)) + 0.25 + >>> kfrom(q=qfrom(k=0.25)) + 0.25 + >>> kfrom(tau=taufrom(k=0.25)) + (0.25 + 0.0j) + >>> kfrom(qbar=qbarfrom(k=0.25)) + 0.25 + + As `q \to 1` and `q \to -1`, `k` rapidly approaches + `1` and `i \infty` respectively:: + + >>> kfrom(q=0.75) + 0.9999999999999899166471767 + >>> kfrom(q=-0.75) + (0.0 + 7041781.096692038332790615j) + >>> kfrom(q=1) + 1 + >>> kfrom(q=-1) + (0.0 + +infj) + """ + if k is not None: + return ctx.convert(k) + if m is not None: + return ctx.sqrt(m) + if tau is not None: + q = ctx.expjpi(tau) + if qbar is not None: + q = ctx.sqrt(qbar) + if q == 1: + return q + if q == -1: + return ctx.mpc(0,'inf') + return (ctx.jtheta(2,0,q)/ctx.jtheta(3,0,q))**2 + +@defun_wrapped +def mfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None): + r""" + Returns the elliptic parameter `m`, given any of + `q, m, k, \tau, \bar{q}`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> mfrom(m=0.25) + 0.25 + >>> mfrom(q=qfrom(m=0.25)) + 0.25 + >>> mfrom(k=kfrom(m=0.25)) + 0.25 + >>> mfrom(tau=taufrom(m=0.25)) + (0.25 + 0.0j) + >>> mfrom(qbar=qbarfrom(m=0.25)) + 0.25 + + As `q \to 1` and `q \to -1`, `m` rapidly approaches + `1` and `-\infty` respectively:: + + >>> mfrom(q=0.75) + 0.9999999999999798332943533 + >>> mfrom(q=-0.75) + -49586681013729.32611558353 + >>> mfrom(q=1) + 1.0 + >>> mfrom(q=-1) + -inf + + The inverse nome as a function of `q` has an integer + Taylor series expansion:: + + >>> taylor(lambda q: mfrom(q), 0, 7) + [0.0, 16.0, -128.0, 704.0, -3072.0, 11488.0, -38400.0, 117632.0] + + """ + if m is not None: + return m + if k is not None: + return k**2 + if tau is not None: + q = ctx.expjpi(tau) + if qbar is not None: + q = ctx.sqrt(qbar) + if q == 1: + return ctx.convert(q) + if q == -1: + return q*ctx.inf + v = (ctx.jtheta(2,0,q)/ctx.jtheta(3,0,q))**4 + if ctx._is_real_type(q) and q < 0: + v = v.real + return v + +jacobi_spec = { + 'sn' : ([3],[2],[1],[4], 'sin', 'tanh'), + 'cn' : ([4],[2],[2],[4], 'cos', 'sech'), + 'dn' : ([4],[3],[3],[4], '1', 'sech'), + 'ns' : ([2],[3],[4],[1], 'csc', 'coth'), + 'nc' : ([2],[4],[4],[2], 'sec', 'cosh'), + 'nd' : ([3],[4],[4],[3], '1', 'cosh'), + 'sc' : ([3],[4],[1],[2], 'tan', 'sinh'), + 'sd' : ([3,3],[2,4],[1],[3], 'sin', 'sinh'), + 'cd' : ([3],[2],[2],[3], 'cos', '1'), + 'cs' : ([4],[3],[2],[1], 'cot', 'csch'), + 'dc' : ([2],[3],[3],[2], 'sec', '1'), + 'ds' : ([2,4],[3,3],[3],[1], 'csc', 'csch'), + 'cc' : None, + 'ss' : None, + 'nn' : None, + 'dd' : None +} + +@defun +def ellipfun(ctx, kind, u=None, m=None, q=None, k=None, tau=None): + try: + S = jacobi_spec[kind] + except KeyError: + raise ValueError("First argument must be a two-character string " + "containing 's', 'c', 'd' or 'n', e.g.: 'sn'") + if u is None: + def f(*args, **kwargs): + return ctx.ellipfun(kind, *args, **kwargs) + f.__name__ = kind + return f + prec = ctx.prec + try: + ctx.prec += 10 + u = ctx.convert(u) + q = ctx.qfrom(m=m, q=q, k=k, tau=tau) + if S is None: + v = ctx.one + 0*q*u + elif q == ctx.zero: + if S[4] == '1': v = ctx.one + else: v = getattr(ctx, S[4])(u) + v += 0*q*u + elif q == ctx.one: + if S[5] == '1': v = ctx.one + else: v = getattr(ctx, S[5])(u) + v += 0*q*u + else: + t = u / ctx.jtheta(3, 0, q)**2 + v = ctx.one + for a in S[0]: v *= ctx.jtheta(a, 0, q) + for b in S[1]: v /= ctx.jtheta(b, 0, q) + for c in S[2]: v *= ctx.jtheta(c, t, q) + for d in S[3]: v /= ctx.jtheta(d, t, q) + finally: + ctx.prec = prec + return +v + +@defun_wrapped +def kleinj(ctx, tau=None, **kwargs): + r""" + Evaluates the Klein j-invariant, which is a modular function defined for + `\tau` in the upper half-plane as + + .. math :: + + J(\tau) = \frac{g_2^3(\tau)}{g_2^3(\tau) - 27 g_3^2(\tau)} + + where `g_2` and `g_3` are the modular invariants of the Weierstrass + elliptic function, + + .. math :: + + g_2(\tau) = 60 \sum_{(m,n) \in \mathbb{Z}^2 \setminus (0,0)} (m \tau+n)^{-4} + + g_3(\tau) = 140 \sum_{(m,n) \in \mathbb{Z}^2 \setminus (0,0)} (m \tau+n)^{-6}. + + An alternative, common notation is that of the j-function + `j(\tau) = 1728 J(\tau)`. + + **Plots** + + .. literalinclude :: /plots/kleinj.py + .. image :: /plots/kleinj.png + .. literalinclude :: /plots/kleinj2.py + .. image :: /plots/kleinj2.png + + **Examples** + + Verifying the functional equation `J(\tau) = J(\tau+1) = J(-\tau^{-1})`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> tau = 0.625+0.75*j + >>> tau = 0.625+0.75*j + >>> kleinj(tau) + (-0.1507492166511182267125242 + 0.07595948379084571927228948j) + >>> kleinj(tau+1) + (-0.1507492166511182267125242 + 0.07595948379084571927228948j) + >>> kleinj(-1/tau) + (-0.1507492166511182267125242 + 0.07595948379084571927228946j) + + The j-function has a famous Laurent series expansion in terms of the nome + `\bar{q}`, `j(\tau) = \bar{q}^{-1} + 744 + 196884\bar{q} + \ldots`:: + + >>> mp.dps = 15 + >>> taylor(lambda q: 1728*q*kleinj(qbar=q), 0, 5, singular=True) + [1.0, 744.0, 196884.0, 21493760.0, 864299970.0, 20245856256.0] + + The j-function admits exact evaluation at special algebraic points + related to the Heegner numbers 1, 2, 3, 7, 11, 19, 43, 67, 163:: + + >>> @extraprec(10) + ... def h(n): + ... v = (1+sqrt(n)*j) + ... if n > 2: + ... v *= 0.5 + ... return v + ... + >>> mp.dps = 25 + >>> for n in [1,2,3,7,11,19,43,67,163]: + ... n, chop(1728*kleinj(h(n))) + ... + (1, 1728.0) + (2, 8000.0) + (3, 0.0) + (7, -3375.0) + (11, -32768.0) + (19, -884736.0) + (43, -884736000.0) + (67, -147197952000.0) + (163, -262537412640768000.0) + + Also at other special points, the j-function assumes explicit + algebraic values, e.g.:: + + >>> chop(1728*kleinj(j*sqrt(5))) + 1264538.909475140509320227 + >>> identify(cbrt(_)) # note: not simplified + '((100+sqrt(13520))/2)' + >>> (50+26*sqrt(5))**3 + 1264538.909475140509320227 + + """ + q = ctx.qfrom(tau=tau, **kwargs) + t2 = ctx.jtheta(2,0,q) + t3 = ctx.jtheta(3,0,q) + t4 = ctx.jtheta(4,0,q) + P = (t2**8 + t3**8 + t4**8)**3 + Q = 54*(t2*t3*t4)**8 + return P/Q + + +def RF_calc(ctx, x, y, z, r): + if y == z: return RC_calc(ctx, x, y, r) + if x == z: return RC_calc(ctx, y, x, r) + if x == y: return RC_calc(ctx, z, x, r) + if not (ctx.isnormal(x) and ctx.isnormal(y) and ctx.isnormal(z)): + if ctx.isnan(x) or ctx.isnan(y) or ctx.isnan(z): + return x*y*z + if ctx.isinf(x) or ctx.isinf(y) or ctx.isinf(z): + return ctx.zero + xm,ym,zm = x,y,z + A0 = Am = (x+y+z)/3 + Q = ctx.root(3*r, -6) * max(abs(A0-x),abs(A0-y),abs(A0-z)) + g = ctx.mpf(0.25) + pow4 = ctx.one + while 1: + xs = ctx.sqrt(xm) + ys = ctx.sqrt(ym) + zs = ctx.sqrt(zm) + lm = xs*ys + xs*zs + ys*zs + Am1 = (Am+lm)*g + xm, ym, zm = (xm+lm)*g, (ym+lm)*g, (zm+lm)*g + if pow4 * Q < abs(Am): + break + Am = Am1 + pow4 *= g + t = pow4/Am + X = (A0-x)*t + Y = (A0-y)*t + Z = -X-Y + E2 = X*Y-Z**2 + E3 = X*Y*Z + return ctx.power(Am,-0.5) * (9240-924*E2+385*E2**2+660*E3-630*E2*E3)/9240 + +def RC_calc(ctx, x, y, r, pv=True): + if not (ctx.isnormal(x) and ctx.isnormal(y)): + if ctx.isinf(x) or ctx.isinf(y): + return 1/(x*y) + if y == 0: + return ctx.inf + if x == 0: + return ctx.pi / ctx.sqrt(y) / 2 + raise ValueError + # Cauchy principal value + if pv and ctx._im(y) == 0 and ctx._re(y) < 0: + return ctx.sqrt(x/(x-y)) * RC_calc(ctx, x-y, -y, r) + if x == y: + return 1/ctx.sqrt(x) + extraprec = 2*max(0,-ctx.mag(x-y)+ctx.mag(x)) + ctx.prec += extraprec + if ctx._is_real_type(x) and ctx._is_real_type(y): + x = ctx._re(x) + y = ctx._re(y) + a = ctx.sqrt(x/y) + if x < y: + b = ctx.sqrt(y-x) + v = ctx.acos(a)/b + else: + b = ctx.sqrt(x-y) + v = ctx.acosh(a)/b + else: + sx = ctx.sqrt(x) + sy = ctx.sqrt(y) + v = ctx.acos(sx/sy)/(ctx.sqrt((1-x/y))*sy) + ctx.prec -= extraprec + return v + +def RJ_calc(ctx, x, y, z, p, r, integration): + """ + With integration == 0, computes RJ only using Carlson's algorithm + (may be wrong for some values). + With integration == 1, uses an initial integration to make sure + Carlson's algorithm is correct. + With integration == 2, uses only integration. + """ + if not (ctx.isnormal(x) and ctx.isnormal(y) and \ + ctx.isnormal(z) and ctx.isnormal(p)): + if ctx.isnan(x) or ctx.isnan(y) or ctx.isnan(z) or ctx.isnan(p): + return x*y*z + if ctx.isinf(x) or ctx.isinf(y) or ctx.isinf(z) or ctx.isinf(p): + return ctx.zero + if not p: + return ctx.inf + if (not x) + (not y) + (not z) > 1: + return ctx.inf + # Check conditions and fall back on integration for argument + # reduction if needed. The following conditions might be needlessly + # restrictive. + initial_integral = ctx.zero + if integration >= 1: + ok = (x.real >= 0 and y.real >= 0 and z.real >= 0 and p.real > 0) + if not ok: + if x == p or y == p or z == p: + ok = True + if not ok: + if p.imag != 0 or p.real >= 0: + if (x.imag == 0 and x.real >= 0 and ctx.conj(y) == z): + ok = True + if (y.imag == 0 and y.real >= 0 and ctx.conj(x) == z): + ok = True + if (z.imag == 0 and z.real >= 0 and ctx.conj(x) == y): + ok = True + if not ok or (integration == 2): + N = ctx.ceil(-min(x.real, y.real, z.real, p.real)) + 1 + # Integrate around any singularities + if all((t.imag >= 0 or t.real > 0) for t in [x, y, z, p]): + margin = ctx.j + elif all((t.imag < 0 or t.real > 0) for t in [x, y, z, p]): + margin = -ctx.j + else: + margin = 1 + # Go through the upper half-plane, but low enough that any + # parameter starting in the lower plane doesn't cross the + # branch cut + for t in [x, y, z, p]: + if t.imag >= 0 or t.real > 0: + continue + margin = min(margin, abs(t.imag) * 0.5) + margin *= ctx.j + N += margin + F = lambda t: 1/(ctx.sqrt(t+x)*ctx.sqrt(t+y)*ctx.sqrt(t+z)*(t+p)) + if integration == 2: + return 1.5 * ctx.quadsubdiv(F, [0, N, ctx.inf]) + initial_integral = 1.5 * ctx.quadsubdiv(F, [0, N]) + x += N; y += N; z += N; p += N + xm,ym,zm,pm = x,y,z,p + A0 = Am = (x + y + z + 2*p)/5 + delta = (p-x)*(p-y)*(p-z) + Q = ctx.root(0.25*r, -6) * max(abs(A0-x),abs(A0-y),abs(A0-z),abs(A0-p)) + g = ctx.mpf(0.25) + pow4 = ctx.one + S = 0 + while 1: + sx = ctx.sqrt(xm) + sy = ctx.sqrt(ym) + sz = ctx.sqrt(zm) + sp = ctx.sqrt(pm) + lm = sx*sy + sx*sz + sy*sz + Am1 = (Am+lm)*g + xm = (xm+lm)*g; ym = (ym+lm)*g; zm = (zm+lm)*g; pm = (pm+lm)*g + dm = (sp+sx) * (sp+sy) * (sp+sz) + em = delta * pow4**3 / dm**2 + if pow4 * Q < abs(Am): + break + T = RC_calc(ctx, ctx.one, ctx.one+em, r) * pow4 / dm + S += T + pow4 *= g + Am = Am1 + t = pow4 / Am + X = (A0-x)*t + Y = (A0-y)*t + Z = (A0-z)*t + P = (-X-Y-Z)/2 + E2 = X*Y + X*Z + Y*Z - 3*P**2 + E3 = X*Y*Z + 2*E2*P + 4*P**3 + E4 = (2*X*Y*Z + E2*P + 3*P**3)*P + E5 = X*Y*Z*P**2 + P = 24024 - 5148*E2 + 2457*E2**2 + 4004*E3 - 4158*E2*E3 - 3276*E4 + 2772*E5 + Q = 24024 + v1 = pow4 * ctx.power(Am, -1.5) * P/Q + v2 = 6*S + return initial_integral + v1 + v2 + +@defun +def elliprf(ctx, x, y, z): + r""" + Evaluates the Carlson symmetric elliptic integral of the first kind + + .. math :: + + R_F(x,y,z) = \frac{1}{2} + \int_0^{\infty} \frac{dt}{\sqrt{(t+x)(t+y)(t+z)}} + + which is defined for `x,y,z \notin (-\infty,0)`, and with + at most one of `x,y,z` being zero. + + For real `x,y,z \ge 0`, the principal square root is taken in the integrand. + For complex `x,y,z`, the principal square root is taken as `t \to \infty` + and as `t \to 0` non-principal branches are chosen as necessary so as to + make the integrand continuous. + + **Examples** + + Some basic values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> elliprf(0,1,1); pi/2 + 1.570796326794896619231322 + 1.570796326794896619231322 + >>> elliprf(0,1,inf) + 0.0 + >>> elliprf(1,1,1) + 1.0 + >>> elliprf(2,2,2)**2 + 0.5 + >>> elliprf(1,0,0); elliprf(0,0,1); elliprf(0,1,0); elliprf(0,0,0) + +inf + +inf + +inf + +inf + + Representing complete elliptic integrals in terms of `R_F`:: + + >>> m = mpf(0.75) + >>> ellipk(m); elliprf(0,1-m,1) + 2.156515647499643235438675 + 2.156515647499643235438675 + >>> ellipe(m); elliprf(0,1-m,1)-m*elliprd(0,1-m,1)/3 + 1.211056027568459524803563 + 1.211056027568459524803563 + + Some symmetries and argument transformations:: + + >>> x,y,z = 2,3,4 + >>> elliprf(x,y,z); elliprf(y,x,z); elliprf(z,y,x) + 0.5840828416771517066928492 + 0.5840828416771517066928492 + 0.5840828416771517066928492 + >>> k = mpf(100000) + >>> elliprf(k*x,k*y,k*z); k**(-0.5) * elliprf(x,y,z) + 0.001847032121923321253219284 + 0.001847032121923321253219284 + >>> l = sqrt(x*y) + sqrt(y*z) + sqrt(z*x) + >>> elliprf(x,y,z); 2*elliprf(x+l,y+l,z+l) + 0.5840828416771517066928492 + 0.5840828416771517066928492 + >>> elliprf((x+l)/4,(y+l)/4,(z+l)/4) + 0.5840828416771517066928492 + + Comparing with numerical integration:: + + >>> x,y,z = 2,3,4 + >>> elliprf(x,y,z) + 0.5840828416771517066928492 + >>> f = lambda t: 0.5*((t+x)*(t+y)*(t+z))**(-0.5) + >>> q = extradps(25)(quad) + >>> q(f, [0,inf]) + 0.5840828416771517066928492 + + With the following arguments, the square root in the integrand becomes + discontinuous at `t = 1/2` if the principal branch is used. To obtain + the right value, `-\sqrt{r}` must be taken instead of `\sqrt{r}` + on `t \in (0, 1/2)`:: + + >>> x,y,z = j-1,j,0 + >>> elliprf(x,y,z) + (0.7961258658423391329305694 - 1.213856669836495986430094j) + >>> -q(f, [0,0.5]) + q(f, [0.5,inf]) + (0.7961258658423391329305694 - 1.213856669836495986430094j) + + The so-called *first lemniscate constant*, a transcendental number:: + + >>> elliprf(0,1,2) + 1.31102877714605990523242 + >>> extradps(25)(quad)(lambda t: 1/sqrt(1-t**4), [0,1]) + 1.31102877714605990523242 + >>> gamma('1/4')**2/(4*sqrt(2*pi)) + 1.31102877714605990523242 + + **References** + + 1. [Carlson]_ + 2. [DLMF]_ Chapter 19. Elliptic Integrals + + """ + x = ctx.convert(x) + y = ctx.convert(y) + z = ctx.convert(z) + prec = ctx.prec + try: + ctx.prec += 20 + tol = ctx.eps * 2**10 + v = RF_calc(ctx, x, y, z, tol) + finally: + ctx.prec = prec + return +v + +@defun +def elliprc(ctx, x, y, pv=True): + r""" + Evaluates the degenerate Carlson symmetric elliptic integral + of the first kind + + .. math :: + + R_C(x,y) = R_F(x,y,y) = + \frac{1}{2} \int_0^{\infty} \frac{dt}{(t+y) \sqrt{(t+x)}}. + + If `y \in (-\infty,0)`, either a value defined by continuity, + or with *pv=True* the Cauchy principal value, can be computed. + + If `x \ge 0, y > 0`, the value can be expressed in terms of + elementary functions as + + .. math :: + + R_C(x,y) = + \begin{cases} + \dfrac{1}{\sqrt{y-x}} + \cos^{-1}\left(\sqrt{\dfrac{x}{y}}\right), & x < y \\ + \dfrac{1}{\sqrt{y}}, & x = y \\ + \dfrac{1}{\sqrt{x-y}} + \cosh^{-1}\left(\sqrt{\dfrac{x}{y}}\right), & x > y \\ + \end{cases}. + + **Examples** + + Some special values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> elliprc(1,2)*4; elliprc(0,1)*2; +pi + 3.141592653589793238462643 + 3.141592653589793238462643 + 3.141592653589793238462643 + >>> elliprc(1,0) + +inf + >>> elliprc(5,5)**2 + 0.2 + >>> elliprc(1,inf); elliprc(inf,1); elliprc(inf,inf) + 0.0 + 0.0 + 0.0 + + Comparing with the elementary closed-form solution:: + + >>> elliprc('1/3', '1/5'); sqrt(7.5)*acosh(sqrt('5/3')) + 2.041630778983498390751238 + 2.041630778983498390751238 + >>> elliprc('1/5', '1/3'); sqrt(7.5)*acos(sqrt('3/5')) + 1.875180765206547065111085 + 1.875180765206547065111085 + + Comparing with numerical integration:: + + >>> q = extradps(25)(quad) + >>> elliprc(2, -3, pv=True) + 0.3333969101113672670749334 + >>> elliprc(2, -3, pv=False) + (0.3333969101113672670749334 + 0.7024814731040726393156375j) + >>> 0.5*q(lambda t: 1/(sqrt(t+2)*(t-3)), [0,3-j,6,inf]) + (0.3333969101113672670749334 + 0.7024814731040726393156375j) + + """ + x = ctx.convert(x) + y = ctx.convert(y) + prec = ctx.prec + try: + ctx.prec += 20 + tol = ctx.eps * 2**10 + v = RC_calc(ctx, x, y, tol, pv) + finally: + ctx.prec = prec + return +v + +@defun +def elliprj(ctx, x, y, z, p, integration=1): + r""" + Evaluates the Carlson symmetric elliptic integral of the third kind + + .. math :: + + R_J(x,y,z,p) = \frac{3}{2} + \int_0^{\infty} \frac{dt}{(t+p)\sqrt{(t+x)(t+y)(t+z)}}. + + Like :func:`~mpmath.elliprf`, the branch of the square root in the integrand + is defined so as to be continuous along the path of integration for + complex values of the arguments. + + **Examples** + + Some values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> elliprj(1,1,1,1) + 1.0 + >>> elliprj(2,2,2,2); 1/(2*sqrt(2)) + 0.3535533905932737622004222 + 0.3535533905932737622004222 + >>> elliprj(0,1,2,2) + 1.067937989667395702268688 + >>> 3*(2*gamma('5/4')**2-pi**2/gamma('1/4')**2)/(sqrt(2*pi)) + 1.067937989667395702268688 + >>> elliprj(0,1,1,2); 3*pi*(2-sqrt(2))/4 + 1.380226776765915172432054 + 1.380226776765915172432054 + >>> elliprj(1,3,2,0); elliprj(0,1,1,0); elliprj(0,0,0,0) + +inf + +inf + +inf + >>> elliprj(1,inf,1,0); elliprj(1,1,1,inf) + 0.0 + 0.0 + >>> chop(elliprj(1+j, 1-j, 1, 1)) + 0.8505007163686739432927844 + + Scale transformation:: + + >>> x,y,z,p = 2,3,4,5 + >>> k = mpf(100000) + >>> elliprj(k*x,k*y,k*z,k*p); k**(-1.5)*elliprj(x,y,z,p) + 4.521291677592745527851168e-9 + 4.521291677592745527851168e-9 + + Comparing with numerical integration:: + + >>> elliprj(1,2,3,4) + 0.2398480997495677621758617 + >>> f = lambda t: 1/((t+4)*sqrt((t+1)*(t+2)*(t+3))) + >>> 1.5*quad(f, [0,inf]) + 0.2398480997495677621758617 + >>> elliprj(1,2+1j,3,4-2j) + (0.216888906014633498739952 + 0.04081912627366673332369512j) + >>> f = lambda t: 1/((t+4-2j)*sqrt((t+1)*(t+2+1j)*(t+3))) + >>> 1.5*quad(f, [0,inf]) + (0.216888906014633498739952 + 0.04081912627366673332369511j) + + """ + x = ctx.convert(x) + y = ctx.convert(y) + z = ctx.convert(z) + p = ctx.convert(p) + prec = ctx.prec + try: + ctx.prec += 20 + tol = ctx.eps * 2**10 + v = RJ_calc(ctx, x, y, z, p, tol, integration) + finally: + ctx.prec = prec + return +v + +@defun +def elliprd(ctx, x, y, z): + r""" + Evaluates the degenerate Carlson symmetric elliptic integral + of the third kind or Carlson elliptic integral of the + second kind `R_D(x,y,z) = R_J(x,y,z,z)`. + + See :func:`~mpmath.elliprj` for additional information. + + **Examples** + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> elliprd(1,2,3) + 0.2904602810289906442326534 + >>> elliprj(1,2,3,3) + 0.2904602810289906442326534 + + The so-called *second lemniscate constant*, a transcendental number:: + + >>> elliprd(0,2,1)/3 + 0.5990701173677961037199612 + >>> extradps(25)(quad)(lambda t: t**2/sqrt(1-t**4), [0,1]) + 0.5990701173677961037199612 + >>> gamma('3/4')**2/sqrt(2*pi) + 0.5990701173677961037199612 + + """ + return ctx.elliprj(x,y,z,z) + +@defun +def elliprg(ctx, x, y, z): + r""" + Evaluates the Carlson completely symmetric elliptic integral + of the second kind + + .. math :: + + R_G(x,y,z) = \frac{1}{4} \int_0^{\infty} + \frac{t}{\sqrt{(t+x)(t+y)(t+z)}} + \left( \frac{x}{t+x} + \frac{y}{t+y} + \frac{z}{t+z}\right) dt. + + **Examples** + + Evaluation for real and complex arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> elliprg(0,1,1)*4; +pi + 3.141592653589793238462643 + 3.141592653589793238462643 + >>> elliprg(0,0.5,1) + 0.6753219405238377512600874 + >>> chop(elliprg(1+j, 1-j, 2)) + 1.172431327676416604532822 + + A double integral that can be evaluated in terms of `R_G`:: + + >>> x,y,z = 2,3,4 + >>> def f(t,u): + ... st = fp.sin(t); ct = fp.cos(t) + ... su = fp.sin(u); cu = fp.cos(u) + ... return (x*(st*cu)**2 + y*(st*su)**2 + z*ct**2)**0.5 * st + ... + >>> nprint(mpf(fp.quad(f, [0,fp.pi], [0,2*fp.pi])/(4*fp.pi)), 13) + 1.725503028069 + >>> nprint(elliprg(x,y,z), 13) + 1.725503028069 + + """ + x = ctx.convert(x) + y = ctx.convert(y) + z = ctx.convert(z) + zeros = (not x) + (not y) + (not z) + if zeros == 3: + return (x+y+z)*0 + if zeros == 2: + if x: return 0.5*ctx.sqrt(x) + if y: return 0.5*ctx.sqrt(y) + return 0.5*ctx.sqrt(z) + if zeros == 1: + if not z: + x, z = z, x + def terms(): + T1 = 0.5*z*ctx.elliprf(x,y,z) + T2 = -0.5*(x-z)*(y-z)*ctx.elliprd(x,y,z)/3 + T3 = 0.5*ctx.sqrt(x)*ctx.sqrt(y)/ctx.sqrt(z) + return T1,T2,T3 + return ctx.sum_accurately(terms) + + +@defun_wrapped +def ellipf(ctx, phi, m): + r""" + Evaluates the Legendre incomplete elliptic integral of the first kind + + .. math :: + + F(\phi,m) = \int_0^{\phi} \frac{dt}{\sqrt{1-m \sin^2 t}} + + or equivalently + + .. math :: + + F(\phi,m) = \int_0^{\sin \phi} + \frac{dt}{\left(\sqrt{1-t^2}\right)\left(\sqrt{1-mt^2}\right)}. + + The function reduces to a complete elliptic integral of the first kind + (see :func:`~mpmath.ellipk`) when `\phi = \frac{\pi}{2}`; that is, + + .. math :: + + F\left(\frac{\pi}{2}, m\right) = K(m). + + In the defining integral, it is assumed that the principal branch + of the square root is taken and that the path of integration avoids + crossing any branch cuts. Outside `-\pi/2 \le \Re(\phi) \le \pi/2`, + the function extends quasi-periodically as + + .. math :: + + F(\phi + n \pi, m) = 2 n K(m) + F(\phi,m), n \in \mathbb{Z}. + + **Plots** + + .. literalinclude :: /plots/ellipf.py + .. image :: /plots/ellipf.png + + **Examples** + + Basic values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> ellipf(0,1) + 0.0 + >>> ellipf(0,0) + 0.0 + >>> ellipf(1,0); ellipf(2+3j,0) + 1.0 + (2.0 + 3.0j) + >>> ellipf(1,1); log(sec(1)+tan(1)) + 1.226191170883517070813061 + 1.226191170883517070813061 + >>> ellipf(pi/2, -0.5); ellipk(-0.5) + 1.415737208425956198892166 + 1.415737208425956198892166 + >>> ellipf(pi/2+eps, 1); ellipf(-pi/2-eps, 1) + +inf + +inf + >>> ellipf(1.5, 1) + 3.340677542798311003320813 + + Comparing with numerical integration:: + + >>> z,m = 0.5, 1.25 + >>> ellipf(z,m) + 0.5287219202206327872978255 + >>> quad(lambda t: (1-m*sin(t)**2)**(-0.5), [0,z]) + 0.5287219202206327872978255 + + The arguments may be complex numbers:: + + >>> ellipf(3j, 0.5) + (0.0 + 1.713602407841590234804143j) + >>> ellipf(3+4j, 5-6j) + (1.269131241950351323305741 - 0.3561052815014558335412538j) + >>> z,m = 2+3j, 1.25 + >>> k = 1011 + >>> ellipf(z+pi*k,m); ellipf(z,m) + 2*k*ellipk(m) + (4086.184383622179764082821 - 3003.003538923749396546871j) + (4086.184383622179764082821 - 3003.003538923749396546871j) + + For `|\Re(z)| < \pi/2`, the function can be expressed as a + hypergeometric series of two variables + (see :func:`~mpmath.appellf1`):: + + >>> z,m = 0.5, 0.25 + >>> ellipf(z,m) + 0.5050887275786480788831083 + >>> sin(z)*appellf1(0.5,0.5,0.5,1.5,sin(z)**2,m*sin(z)**2) + 0.5050887275786480788831083 + + """ + z = phi + if not (ctx.isnormal(z) and ctx.isnormal(m)): + if m == 0: + return z + m + if z == 0: + return z * m + if m == ctx.inf or m == ctx.ninf: return z/m + raise ValueError + x = z.real + ctx.prec += max(0, ctx.mag(x)) + pi = +ctx.pi + away = abs(x) > pi/2 + if m == 1: + if away: + return ctx.inf + if away: + d = ctx.nint(x/pi) + z = z-pi*d + P = 2*d*ctx.ellipk(m) + else: + P = 0 + c, s = ctx.cos_sin(z) + return s * ctx.elliprf(c**2, 1-m*s**2, 1) + P + +@defun_wrapped +def ellipe(ctx, *args): + r""" + Called with a single argument `m`, evaluates the Legendre complete + elliptic integral of the second kind, `E(m)`, defined by + + .. math :: E(m) = \int_0^{\pi/2} \sqrt{1-m \sin^2 t} \, dt \,=\, + \frac{\pi}{2} + \,_2F_1\left(\frac{1}{2}, -\frac{1}{2}, 1, m\right). + + Called with two arguments `\phi, m`, evaluates the incomplete elliptic + integral of the second kind + + .. math :: + + E(\phi,m) = \int_0^{\phi} \sqrt{1-m \sin^2 t} \, dt = + \int_0^{\sin z} + \frac{\sqrt{1-mt^2}}{\sqrt{1-t^2}} \, dt. + + The incomplete integral reduces to a complete integral when + `\phi = \frac{\pi}{2}`; that is, + + .. math :: + + E\left(\frac{\pi}{2}, m\right) = E(m). + + In the defining integral, it is assumed that the principal branch + of the square root is taken and that the path of integration avoids + crossing any branch cuts. Outside `-\pi/2 \le \Re(z) \le \pi/2`, + the function extends quasi-periodically as + + .. math :: + + E(\phi + n \pi, m) = 2 n E(m) + E(\phi,m), n \in \mathbb{Z}. + + **Plots** + + .. literalinclude :: /plots/ellipe.py + .. image :: /plots/ellipe.png + + **Examples for the complete integral** + + Basic values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> ellipe(0) + 1.570796326794896619231322 + >>> ellipe(1) + 1.0 + >>> ellipe(-1) + 1.910098894513856008952381 + >>> ellipe(2) + (0.5990701173677961037199612 + 0.5990701173677961037199612j) + >>> ellipe(inf) + (0.0 + +infj) + >>> ellipe(-inf) + +inf + + Verifying the defining integral and hypergeometric + representation:: + + >>> ellipe(0.5) + 1.350643881047675502520175 + >>> quad(lambda t: sqrt(1-0.5*sin(t)**2), [0, pi/2]) + 1.350643881047675502520175 + >>> pi/2*hyp2f1(0.5,-0.5,1,0.5) + 1.350643881047675502520175 + + Evaluation is supported for arbitrary complex `m`:: + + >>> ellipe(0.5+0.25j) + (1.360868682163129682716687 - 0.1238733442561786843557315j) + >>> ellipe(3+4j) + (1.499553520933346954333612 - 1.577879007912758274533309j) + + A definite integral:: + + >>> quad(ellipe, [0,1]) + 1.333333333333333333333333 + + **Examples for the incomplete integral** + + Basic values and limits:: + + >>> ellipe(0,1) + 0.0 + >>> ellipe(0,0) + 0.0 + >>> ellipe(1,0) + 1.0 + >>> ellipe(2+3j,0) + (2.0 + 3.0j) + >>> ellipe(1,1); sin(1) + 0.8414709848078965066525023 + 0.8414709848078965066525023 + >>> ellipe(pi/2, -0.5); ellipe(-0.5) + 1.751771275694817862026502 + 1.751771275694817862026502 + >>> ellipe(pi/2, 1); ellipe(-pi/2, 1) + 1.0 + -1.0 + >>> ellipe(1.5, 1) + 0.9974949866040544309417234 + + Comparing with numerical integration:: + + >>> z,m = 0.5, 1.25 + >>> ellipe(z,m) + 0.4740152182652628394264449 + >>> quad(lambda t: sqrt(1-m*sin(t)**2), [0,z]) + 0.4740152182652628394264449 + + The arguments may be complex numbers:: + + >>> ellipe(3j, 0.5) + (0.0 + 7.551991234890371873502105j) + >>> ellipe(3+4j, 5-6j) + (24.15299022574220502424466 + 75.2503670480325997418156j) + >>> k = 35 + >>> z,m = 2+3j, 1.25 + >>> ellipe(z+pi*k,m); ellipe(z,m) + 2*k*ellipe(m) + (48.30138799412005235090766 + 17.47255216721987688224357j) + (48.30138799412005235090766 + 17.47255216721987688224357j) + + For `|\Re(z)| < \pi/2`, the function can be expressed as a + hypergeometric series of two variables + (see :func:`~mpmath.appellf1`):: + + >>> z,m = 0.5, 0.25 + >>> ellipe(z,m) + 0.4950017030164151928870375 + >>> sin(z)*appellf1(0.5,0.5,-0.5,1.5,sin(z)**2,m*sin(z)**2) + 0.4950017030164151928870376 + + """ + if len(args) == 1: + return ctx._ellipe(args[0]) + else: + phi, m = args + z = phi + if not (ctx.isnormal(z) and ctx.isnormal(m)): + if m == 0: + return z + m + if z == 0: + return z * m + if m == ctx.inf or m == ctx.ninf: + return ctx.inf + raise ValueError + x = z.real + ctx.prec += max(0, ctx.mag(x)) + pi = +ctx.pi + away = abs(x) > pi/2 + if away: + d = ctx.nint(x/pi) + z = z-pi*d + P = 2*d*ctx.ellipe(m) + else: + P = 0 + def terms(): + c, s = ctx.cos_sin(z) + x = c**2 + y = 1-m*s**2 + RF = ctx.elliprf(x, y, 1) + RD = ctx.elliprd(x, y, 1) + return s*RF, -m*s**3*RD/3 + return ctx.sum_accurately(terms) + P + +@defun_wrapped +def ellippi(ctx, *args): + r""" + Called with three arguments `n, \phi, m`, evaluates the Legendre + incomplete elliptic integral of the third kind + + .. math :: + + \Pi(n; \phi, m) = \int_0^{\phi} + \frac{dt}{(1-n \sin^2 t) \sqrt{1-m \sin^2 t}} = + \int_0^{\sin \phi} + \frac{dt}{(1-nt^2) \sqrt{1-t^2} \sqrt{1-mt^2}}. + + Called with two arguments `n, m`, evaluates the complete + elliptic integral of the third kind + `\Pi(n,m) = \Pi(n; \frac{\pi}{2},m)`. + + In the defining integral, it is assumed that the principal branch + of the square root is taken and that the path of integration avoids + crossing any branch cuts. Outside `-\pi/2 \le \Re(\phi) \le \pi/2`, + the function extends quasi-periodically as + + .. math :: + + \Pi(n,\phi+k\pi,m) = 2k\Pi(n,m) + \Pi(n,\phi,m), k \in \mathbb{Z}. + + **Plots** + + .. literalinclude :: /plots/ellippi.py + .. image :: /plots/ellippi.png + + **Examples for the complete integral** + + Some basic values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> ellippi(0,-5); ellipk(-5) + 0.9555039270640439337379334 + 0.9555039270640439337379334 + >>> ellippi(inf,2) + 0.0 + >>> ellippi(2,inf) + 0.0 + >>> abs(ellippi(1,5)) + +inf + >>> abs(ellippi(0.25,1)) + +inf + + Evaluation in terms of simpler functions:: + + >>> ellippi(0.25,0.25); ellipe(0.25)/(1-0.25) + 1.956616279119236207279727 + 1.956616279119236207279727 + >>> ellippi(3,0); pi/(2*sqrt(-2)) + (0.0 - 1.11072073453959156175397j) + (0.0 - 1.11072073453959156175397j) + >>> ellippi(-3,0); pi/(2*sqrt(4)) + 0.7853981633974483096156609 + 0.7853981633974483096156609 + + **Examples for the incomplete integral** + + Basic values and limits:: + + >>> ellippi(0.25,-0.5); ellippi(0.25,pi/2,-0.5) + 1.622944760954741603710555 + 1.622944760954741603710555 + >>> ellippi(1,0,1) + 0.0 + >>> ellippi(inf,0,1) + 0.0 + >>> ellippi(0,0.25,0.5); ellipf(0.25,0.5) + 0.2513040086544925794134591 + 0.2513040086544925794134591 + >>> ellippi(1,1,1); (log(sec(1)+tan(1))+sec(1)*tan(1))/2 + 2.054332933256248668692452 + 2.054332933256248668692452 + >>> ellippi(0.25, 53*pi/2, 0.75); 53*ellippi(0.25,0.75) + 135.240868757890840755058 + 135.240868757890840755058 + >>> ellippi(0.5,pi/4,0.5); 2*ellipe(pi/4,0.5)-1/sqrt(3) + 0.9190227391656969903987269 + 0.9190227391656969903987269 + + Complex arguments are supported:: + + >>> ellippi(0.5, 5+6j-2*pi, -7-8j) + (-0.3612856620076747660410167 + 0.5217735339984807829755815j) + + Some degenerate cases:: + + >>> ellippi(1,1) + +inf + >>> ellippi(1,0) + +inf + >>> ellippi(1,2,0) + +inf + >>> ellippi(1,2,1) + +inf + >>> ellippi(1,0,1) + 0.0 + + """ + if len(args) == 2: + n, m = args + complete = True + z = phi = ctx.pi/2 + else: + n, phi, m = args + complete = False + z = phi + if not (ctx.isnormal(n) and ctx.isnormal(z) and ctx.isnormal(m)): + if ctx.isnan(n) or ctx.isnan(z) or ctx.isnan(m): + raise ValueError + if complete: + if m == 0: + if n == 1: + return ctx.inf + return ctx.pi/(2*ctx.sqrt(1-n)) + if n == 0: return ctx.ellipk(m) + if ctx.isinf(n) or ctx.isinf(m): return ctx.zero + else: + if z == 0: return z + if ctx.isinf(n): return ctx.zero + if ctx.isinf(m): return ctx.zero + if ctx.isinf(n) or ctx.isinf(z) or ctx.isinf(m): + raise ValueError + if complete: + if m == 1: + if n == 1: + return ctx.inf + return -ctx.inf/ctx.sign(n-1) + away = False + else: + x = z.real + ctx.prec += max(0, ctx.mag(x)) + pi = +ctx.pi + away = abs(x) > pi/2 + if away: + d = ctx.nint(x/pi) + z = z-pi*d + P = 2*d*ctx.ellippi(n,m) + if ctx.isinf(P): + return ctx.inf + else: + P = 0 + def terms(): + if complete: + c, s = ctx.zero, ctx.one + else: + c, s = ctx.cos_sin(z) + x = c**2 + y = 1-m*s**2 + RF = ctx.elliprf(x, y, 1) + RJ = ctx.elliprj(x, y, 1, 1-n*s**2) + return s*RF, n*s**3*RJ/3 + return ctx.sum_accurately(terms) + P diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/expintegrals.py b/venv/lib/python3.10/site-packages/mpmath/functions/expintegrals.py new file mode 100644 index 0000000000000000000000000000000000000000..0dee8356c0386819d8f0421fded476ee77229359 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/functions/expintegrals.py @@ -0,0 +1,425 @@ +from .functions import defun, defun_wrapped + +@defun_wrapped +def _erf_complex(ctx, z): + z2 = ctx.square_exp_arg(z, -1) + #z2 = -z**2 + v = (2/ctx.sqrt(ctx.pi))*z * ctx.hyp1f1((1,2),(3,2), z2) + if not ctx._re(z): + v = ctx._im(v)*ctx.j + return v + +@defun_wrapped +def _erfc_complex(ctx, z): + if ctx.re(z) > 2: + z2 = ctx.square_exp_arg(z) + nz2 = ctx.fneg(z2, exact=True) + v = ctx.exp(nz2)/ctx.sqrt(ctx.pi) * ctx.hyperu((1,2),(1,2), z2) + else: + v = 1 - ctx._erf_complex(z) + if not ctx._re(z): + v = 1+ctx._im(v)*ctx.j + return v + +@defun +def erf(ctx, z): + z = ctx.convert(z) + if ctx._is_real_type(z): + try: + return ctx._erf(z) + except NotImplementedError: + pass + if ctx._is_complex_type(z) and not z.imag: + try: + return type(z)(ctx._erf(z.real)) + except NotImplementedError: + pass + return ctx._erf_complex(z) + +@defun +def erfc(ctx, z): + z = ctx.convert(z) + if ctx._is_real_type(z): + try: + return ctx._erfc(z) + except NotImplementedError: + pass + if ctx._is_complex_type(z) and not z.imag: + try: + return type(z)(ctx._erfc(z.real)) + except NotImplementedError: + pass + return ctx._erfc_complex(z) + +@defun +def square_exp_arg(ctx, z, mult=1, reciprocal=False): + prec = ctx.prec*4+20 + if reciprocal: + z2 = ctx.fmul(z, z, prec=prec) + z2 = ctx.fdiv(ctx.one, z2, prec=prec) + else: + z2 = ctx.fmul(z, z, prec=prec) + if mult != 1: + z2 = ctx.fmul(z2, mult, exact=True) + return z2 + +@defun_wrapped +def erfi(ctx, z): + if not z: + return z + z2 = ctx.square_exp_arg(z) + v = (2/ctx.sqrt(ctx.pi)*z) * ctx.hyp1f1((1,2), (3,2), z2) + if not ctx._re(z): + v = ctx._im(v)*ctx.j + return v + +@defun_wrapped +def erfinv(ctx, x): + xre = ctx._re(x) + if (xre != x) or (xre < -1) or (xre > 1): + return ctx.bad_domain("erfinv(x) is defined only for -1 <= x <= 1") + x = xre + #if ctx.isnan(x): return x + if not x: return x + if x == 1: return ctx.inf + if x == -1: return ctx.ninf + if abs(x) < 0.9: + a = 0.53728*x**3 + 0.813198*x + else: + # An asymptotic formula + u = ctx.ln(2/ctx.pi/(abs(x)-1)**2) + a = ctx.sign(x) * ctx.sqrt(u - ctx.ln(u))/ctx.sqrt(2) + ctx.prec += 10 + return ctx.findroot(lambda t: ctx.erf(t)-x, a) + +@defun_wrapped +def npdf(ctx, x, mu=0, sigma=1): + sigma = ctx.convert(sigma) + return ctx.exp(-(x-mu)**2/(2*sigma**2)) / (sigma*ctx.sqrt(2*ctx.pi)) + +@defun_wrapped +def ncdf(ctx, x, mu=0, sigma=1): + a = (x-mu)/(sigma*ctx.sqrt(2)) + if a < 0: + return ctx.erfc(-a)/2 + else: + return (1+ctx.erf(a))/2 + +@defun_wrapped +def betainc(ctx, a, b, x1=0, x2=1, regularized=False): + if x1 == x2: + v = 0 + elif not x1: + if x1 == 0 and x2 == 1: + v = ctx.beta(a, b) + else: + v = x2**a * ctx.hyp2f1(a, 1-b, a+1, x2) / a + else: + m, d = ctx.nint_distance(a) + if m <= 0: + if d < -ctx.prec: + h = +ctx.eps + ctx.prec *= 2 + a += h + elif d < -4: + ctx.prec -= d + s1 = x2**a * ctx.hyp2f1(a,1-b,a+1,x2) + s2 = x1**a * ctx.hyp2f1(a,1-b,a+1,x1) + v = (s1 - s2) / a + if regularized: + v /= ctx.beta(a,b) + return v + +@defun +def gammainc(ctx, z, a=0, b=None, regularized=False): + regularized = bool(regularized) + z = ctx.convert(z) + if a is None: + a = ctx.zero + lower_modified = False + else: + a = ctx.convert(a) + lower_modified = a != ctx.zero + if b is None: + b = ctx.inf + upper_modified = False + else: + b = ctx.convert(b) + upper_modified = b != ctx.inf + # Complete gamma function + if not (upper_modified or lower_modified): + if regularized: + if ctx.re(z) < 0: + return ctx.inf + elif ctx.re(z) > 0: + return ctx.one + else: + return ctx.nan + return ctx.gamma(z) + if a == b: + return ctx.zero + # Standardize + if ctx.re(a) > ctx.re(b): + return -ctx.gammainc(z, b, a, regularized) + # Generalized gamma + if upper_modified and lower_modified: + return +ctx._gamma3(z, a, b, regularized) + # Upper gamma + elif lower_modified: + return ctx._upper_gamma(z, a, regularized) + # Lower gamma + elif upper_modified: + return ctx._lower_gamma(z, b, regularized) + +@defun +def _lower_gamma(ctx, z, b, regularized=False): + # Pole + if ctx.isnpint(z): + return type(z)(ctx.inf) + G = [z] * regularized + negb = ctx.fneg(b, exact=True) + def h(z): + T1 = [ctx.exp(negb), b, z], [1, z, -1], [], G, [1], [1+z], b + return (T1,) + return ctx.hypercomb(h, [z]) + +@defun +def _upper_gamma(ctx, z, a, regularized=False): + # Fast integer case, when available + if ctx.isint(z): + try: + if regularized: + # Gamma pole + if ctx.isnpint(z): + return type(z)(ctx.zero) + orig = ctx.prec + try: + ctx.prec += 10 + return ctx._gamma_upper_int(z, a) / ctx.gamma(z) + finally: + ctx.prec = orig + else: + return ctx._gamma_upper_int(z, a) + except NotImplementedError: + pass + # hypercomb is unable to detect the exact zeros, so handle them here + if z == 2 and a == -1: + return (z+a)*0 + if z == 3 and (a == -1-1j or a == -1+1j): + return (z+a)*0 + nega = ctx.fneg(a, exact=True) + G = [z] * regularized + # Use 2F0 series when possible; fall back to lower gamma representation + try: + def h(z): + r = z-1 + return [([ctx.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)] + return ctx.hypercomb(h, [z], force_series=True) + except ctx.NoConvergence: + def h(z): + T1 = [], [1, z-1], [z], G, [], [], 0 + T2 = [-ctx.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a + return T1, T2 + return ctx.hypercomb(h, [z]) + +@defun +def _gamma3(ctx, z, a, b, regularized=False): + pole = ctx.isnpint(z) + if regularized and pole: + return ctx.zero + try: + ctx.prec += 15 + # We don't know in advance whether it's better to write as a difference + # of lower or upper gamma functions, so try both + T1 = ctx.gammainc(z, a, regularized=regularized) + T2 = ctx.gammainc(z, b, regularized=regularized) + R = T1 - T2 + if ctx.mag(R) - max(ctx.mag(T1), ctx.mag(T2)) > -10: + return R + if not pole: + T1 = ctx.gammainc(z, 0, b, regularized=regularized) + T2 = ctx.gammainc(z, 0, a, regularized=regularized) + R = T1 - T2 + # May be ok, but should probably at least print a warning + # about possible cancellation + if 1: #ctx.mag(R) - max(ctx.mag(T1), ctx.mag(T2)) > -10: + return R + finally: + ctx.prec -= 15 + raise NotImplementedError + +@defun_wrapped +def expint(ctx, n, z): + if ctx.isint(n) and ctx._is_real_type(z): + try: + return ctx._expint_int(n, z) + except NotImplementedError: + pass + if ctx.isnan(n) or ctx.isnan(z): + return z*n + if z == ctx.inf: + return 1/z + if z == 0: + # integral from 1 to infinity of t^n + if ctx.re(n) <= 1: + # TODO: reasonable sign of infinity + return type(z)(ctx.inf) + else: + return ctx.one/(n-1) + if n == 0: + return ctx.exp(-z)/z + if n == -1: + return ctx.exp(-z)*(z+1)/z**2 + return z**(n-1) * ctx.gammainc(1-n, z) + +@defun_wrapped +def li(ctx, z, offset=False): + if offset: + if z == 2: + return ctx.zero + return ctx.ei(ctx.ln(z)) - ctx.ei(ctx.ln2) + if not z: + return z + if z == 1: + return ctx.ninf + return ctx.ei(ctx.ln(z)) + +@defun +def ei(ctx, z): + try: + return ctx._ei(z) + except NotImplementedError: + return ctx._ei_generic(z) + +@defun_wrapped +def _ei_generic(ctx, z): + # Note: the following is currently untested because mp and fp + # both use special-case ei code + if z == ctx.inf: + return z + if z == ctx.ninf: + return ctx.zero + if ctx.mag(z) > 1: + try: + r = ctx.one/z + v = ctx.exp(z)*ctx.hyper([1,1],[],r, + maxterms=ctx.prec, force_series=True)/z + im = ctx._im(z) + if im > 0: + v += ctx.pi*ctx.j + if im < 0: + v -= ctx.pi*ctx.j + return v + except ctx.NoConvergence: + pass + v = z*ctx.hyp2f2(1,1,2,2,z) + ctx.euler + if ctx._im(z): + v += 0.5*(ctx.log(z) - ctx.log(ctx.one/z)) + else: + v += ctx.log(abs(z)) + return v + +@defun +def e1(ctx, z): + try: + return ctx._e1(z) + except NotImplementedError: + return ctx.expint(1, z) + +@defun +def ci(ctx, z): + try: + return ctx._ci(z) + except NotImplementedError: + return ctx._ci_generic(z) + +@defun_wrapped +def _ci_generic(ctx, z): + if ctx.isinf(z): + if z == ctx.inf: return ctx.zero + if z == ctx.ninf: return ctx.pi*1j + jz = ctx.fmul(ctx.j,z,exact=True) + njz = ctx.fneg(jz,exact=True) + v = 0.5*(ctx.ei(jz) + ctx.ei(njz)) + zreal = ctx._re(z) + zimag = ctx._im(z) + if zreal == 0: + if zimag > 0: v += ctx.pi*0.5j + if zimag < 0: v -= ctx.pi*0.5j + if zreal < 0: + if zimag >= 0: v += ctx.pi*1j + if zimag < 0: v -= ctx.pi*1j + if ctx._is_real_type(z) and zreal > 0: + v = ctx._re(v) + return v + +@defun +def si(ctx, z): + try: + return ctx._si(z) + except NotImplementedError: + return ctx._si_generic(z) + +@defun_wrapped +def _si_generic(ctx, z): + if ctx.isinf(z): + if z == ctx.inf: return 0.5*ctx.pi + if z == ctx.ninf: return -0.5*ctx.pi + # Suffers from cancellation near 0 + if ctx.mag(z) >= -1: + jz = ctx.fmul(ctx.j,z,exact=True) + njz = ctx.fneg(jz,exact=True) + v = (-0.5j)*(ctx.ei(jz) - ctx.ei(njz)) + zreal = ctx._re(z) + if zreal > 0: + v -= 0.5*ctx.pi + if zreal < 0: + v += 0.5*ctx.pi + if ctx._is_real_type(z): + v = ctx._re(v) + return v + else: + return z*ctx.hyp1f2((1,2),(3,2),(3,2),-0.25*z*z) + +@defun_wrapped +def chi(ctx, z): + nz = ctx.fneg(z, exact=True) + v = 0.5*(ctx.ei(z) + ctx.ei(nz)) + zreal = ctx._re(z) + zimag = ctx._im(z) + if zimag > 0: + v += ctx.pi*0.5j + elif zimag < 0: + v -= ctx.pi*0.5j + elif zreal < 0: + v += ctx.pi*1j + return v + +@defun_wrapped +def shi(ctx, z): + # Suffers from cancellation near 0 + if ctx.mag(z) >= -1: + nz = ctx.fneg(z, exact=True) + v = 0.5*(ctx.ei(z) - ctx.ei(nz)) + zimag = ctx._im(z) + if zimag > 0: v -= 0.5j*ctx.pi + if zimag < 0: v += 0.5j*ctx.pi + return v + else: + return z * ctx.hyp1f2((1,2),(3,2),(3,2),0.25*z*z) + +@defun_wrapped +def fresnels(ctx, z): + if z == ctx.inf: + return ctx.mpf(0.5) + if z == ctx.ninf: + return ctx.mpf(-0.5) + return ctx.pi*z**3/6*ctx.hyp1f2((3,4),(3,2),(7,4),-ctx.pi**2*z**4/16) + +@defun_wrapped +def fresnelc(ctx, z): + if z == ctx.inf: + return ctx.mpf(0.5) + if z == ctx.ninf: + return ctx.mpf(-0.5) + return z*ctx.hyp1f2((1,4),(1,2),(5,4),-ctx.pi**2*z**4/16) diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/factorials.py b/venv/lib/python3.10/site-packages/mpmath/functions/factorials.py new file mode 100644 index 0000000000000000000000000000000000000000..9259e40b95bf1c908a7ad98b59bbb33528606b07 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/functions/factorials.py @@ -0,0 +1,187 @@ +from ..libmp.backend import xrange +from .functions import defun, defun_wrapped + +@defun +def gammaprod(ctx, a, b, _infsign=False): + a = [ctx.convert(x) for x in a] + b = [ctx.convert(x) for x in b] + poles_num = [] + poles_den = [] + regular_num = [] + regular_den = [] + for x in a: [regular_num, poles_num][ctx.isnpint(x)].append(x) + for x in b: [regular_den, poles_den][ctx.isnpint(x)].append(x) + # One more pole in numerator or denominator gives 0 or inf + if len(poles_num) < len(poles_den): return ctx.zero + if len(poles_num) > len(poles_den): + # Get correct sign of infinity for x+h, h -> 0 from above + # XXX: hack, this should be done properly + if _infsign: + a = [x and x*(1+ctx.eps) or x+ctx.eps for x in poles_num] + b = [x and x*(1+ctx.eps) or x+ctx.eps for x in poles_den] + return ctx.sign(ctx.gammaprod(a+regular_num,b+regular_den)) * ctx.inf + else: + return ctx.inf + # All poles cancel + # lim G(i)/G(j) = (-1)**(i+j) * gamma(1-j) / gamma(1-i) + p = ctx.one + orig = ctx.prec + try: + ctx.prec = orig + 15 + while poles_num: + i = poles_num.pop() + j = poles_den.pop() + p *= (-1)**(i+j) * ctx.gamma(1-j) / ctx.gamma(1-i) + for x in regular_num: p *= ctx.gamma(x) + for x in regular_den: p /= ctx.gamma(x) + finally: + ctx.prec = orig + return +p + +@defun +def beta(ctx, x, y): + x = ctx.convert(x) + y = ctx.convert(y) + if ctx.isinf(y): + x, y = y, x + if ctx.isinf(x): + if x == ctx.inf and not ctx._im(y): + if y == ctx.ninf: + return ctx.nan + if y > 0: + return ctx.zero + if ctx.isint(y): + return ctx.nan + if y < 0: + return ctx.sign(ctx.gamma(y)) * ctx.inf + return ctx.nan + xy = ctx.fadd(x, y, prec=2*ctx.prec) + return ctx.gammaprod([x, y], [xy]) + +@defun +def binomial(ctx, n, k): + n1 = ctx.fadd(n, 1, prec=2*ctx.prec) + k1 = ctx.fadd(k, 1, prec=2*ctx.prec) + nk1 = ctx.fsub(n1, k, prec=2*ctx.prec) + return ctx.gammaprod([n1], [k1, nk1]) + +@defun +def rf(ctx, x, n): + xn = ctx.fadd(x, n, prec=2*ctx.prec) + return ctx.gammaprod([xn], [x]) + +@defun +def ff(ctx, x, n): + x1 = ctx.fadd(x, 1, prec=2*ctx.prec) + xn1 = ctx.fadd(ctx.fsub(x, n, prec=2*ctx.prec), 1, prec=2*ctx.prec) + return ctx.gammaprod([x1], [xn1]) + +@defun_wrapped +def fac2(ctx, x): + if ctx.isinf(x): + if x == ctx.inf: + return x + return ctx.nan + return 2**(x/2)*(ctx.pi/2)**((ctx.cospi(x)-1)/4)*ctx.gamma(x/2+1) + +@defun_wrapped +def barnesg(ctx, z): + if ctx.isinf(z): + if z == ctx.inf: + return z + return ctx.nan + if ctx.isnan(z): + return z + if (not ctx._im(z)) and ctx._re(z) <= 0 and ctx.isint(ctx._re(z)): + return z*0 + # Account for size (would not be needed if computing log(G)) + if abs(z) > 5: + ctx.dps += 2*ctx.log(abs(z),2) + # Reflection formula + if ctx.re(z) < -ctx.dps: + w = 1-z + pi2 = 2*ctx.pi + u = ctx.expjpi(2*w) + v = ctx.j*ctx.pi/12 - ctx.j*ctx.pi*w**2/2 + w*ctx.ln(1-u) - \ + ctx.j*ctx.polylog(2, u)/pi2 + v = ctx.barnesg(2-z)*ctx.exp(v)/pi2**w + if ctx._is_real_type(z): + v = ctx._re(v) + return v + # Estimate terms for asymptotic expansion + # TODO: fixme, obviously + N = ctx.dps // 2 + 5 + G = 1 + while abs(z) < N or ctx.re(z) < 1: + G /= ctx.gamma(z) + z += 1 + z -= 1 + s = ctx.mpf(1)/12 + s -= ctx.log(ctx.glaisher) + s += z*ctx.log(2*ctx.pi)/2 + s += (z**2/2-ctx.mpf(1)/12)*ctx.log(z) + s -= 3*z**2/4 + z2k = z2 = z**2 + for k in xrange(1, N+1): + t = ctx.bernoulli(2*k+2) / (4*k*(k+1)*z2k) + if abs(t) < ctx.eps: + #print k, N # check how many terms were needed + break + z2k *= z2 + s += t + #if k == N: + # print "warning: series for barnesg failed to converge", ctx.dps + return G*ctx.exp(s) + +@defun +def superfac(ctx, z): + return ctx.barnesg(z+2) + +@defun_wrapped +def hyperfac(ctx, z): + # XXX: estimate needed extra bits accurately + if z == ctx.inf: + return z + if abs(z) > 5: + extra = 4*int(ctx.log(abs(z),2)) + else: + extra = 0 + ctx.prec += extra + if not ctx._im(z) and ctx._re(z) < 0 and ctx.isint(ctx._re(z)): + n = int(ctx.re(z)) + h = ctx.hyperfac(-n-1) + if ((n+1)//2) & 1: + h = -h + if ctx._is_complex_type(z): + return h + 0j + return h + zp1 = z+1 + # Wrong branch cut + #v = ctx.gamma(zp1)**z + #ctx.prec -= extra + #return v / ctx.barnesg(zp1) + v = ctx.exp(z*ctx.loggamma(zp1)) + ctx.prec -= extra + return v / ctx.barnesg(zp1) + +''' +@defun +def psi0(ctx, z): + """Shortcut for psi(0,z) (the digamma function)""" + return ctx.psi(0, z) + +@defun +def psi1(ctx, z): + """Shortcut for psi(1,z) (the trigamma function)""" + return ctx.psi(1, z) + +@defun +def psi2(ctx, z): + """Shortcut for psi(2,z) (the tetragamma function)""" + return ctx.psi(2, z) + +@defun +def psi3(ctx, z): + """Shortcut for psi(3,z) (the pentagamma function)""" + return ctx.psi(3, z) +''' diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/functions.py b/venv/lib/python3.10/site-packages/mpmath/functions/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..4cdf5dd921418db10847ea75b32f8e6dfacdba64 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/functions/functions.py @@ -0,0 +1,645 @@ +from ..libmp.backend import xrange + +class SpecialFunctions(object): + """ + This class implements special functions using high-level code. + + Elementary and some other functions (e.g. gamma function, basecase + hypergeometric series) are assumed to be predefined by the context as + "builtins" or "low-level" functions. + """ + defined_functions = {} + + # The series for the Jacobi theta functions converge for |q| < 1; + # in the current implementation they throw a ValueError for + # abs(q) > THETA_Q_LIM + THETA_Q_LIM = 1 - 10**-7 + + def __init__(self): + cls = self.__class__ + for name in cls.defined_functions: + f, wrap = cls.defined_functions[name] + cls._wrap_specfun(name, f, wrap) + + self.mpq_1 = self._mpq((1,1)) + self.mpq_0 = self._mpq((0,1)) + self.mpq_1_2 = self._mpq((1,2)) + self.mpq_3_2 = self._mpq((3,2)) + self.mpq_1_4 = self._mpq((1,4)) + self.mpq_1_16 = self._mpq((1,16)) + self.mpq_3_16 = self._mpq((3,16)) + self.mpq_5_2 = self._mpq((5,2)) + self.mpq_3_4 = self._mpq((3,4)) + self.mpq_7_4 = self._mpq((7,4)) + self.mpq_5_4 = self._mpq((5,4)) + self.mpq_1_3 = self._mpq((1,3)) + self.mpq_2_3 = self._mpq((2,3)) + self.mpq_4_3 = self._mpq((4,3)) + self.mpq_1_6 = self._mpq((1,6)) + self.mpq_5_6 = self._mpq((5,6)) + self.mpq_5_3 = self._mpq((5,3)) + + self._misc_const_cache = {} + + self._aliases.update({ + 'phase' : 'arg', + 'conjugate' : 'conj', + 'nthroot' : 'root', + 'polygamma' : 'psi', + 'hurwitz' : 'zeta', + #'digamma' : 'psi0', + #'trigamma' : 'psi1', + #'tetragamma' : 'psi2', + #'pentagamma' : 'psi3', + 'fibonacci' : 'fib', + 'factorial' : 'fac', + }) + + self.zetazero_memoized = self.memoize(self.zetazero) + + # Default -- do nothing + @classmethod + def _wrap_specfun(cls, name, f, wrap): + setattr(cls, name, f) + + # Optional fast versions of common functions in common cases. + # If not overridden, default (generic hypergeometric series) + # implementations will be used + def _besselj(ctx, n, z): raise NotImplementedError + def _erf(ctx, z): raise NotImplementedError + def _erfc(ctx, z): raise NotImplementedError + def _gamma_upper_int(ctx, z, a): raise NotImplementedError + def _expint_int(ctx, n, z): raise NotImplementedError + def _zeta(ctx, s): raise NotImplementedError + def _zetasum_fast(ctx, s, a, n, derivatives, reflect): raise NotImplementedError + def _ei(ctx, z): raise NotImplementedError + def _e1(ctx, z): raise NotImplementedError + def _ci(ctx, z): raise NotImplementedError + def _si(ctx, z): raise NotImplementedError + def _altzeta(ctx, s): raise NotImplementedError + +def defun_wrapped(f): + SpecialFunctions.defined_functions[f.__name__] = f, True + return f + +def defun(f): + SpecialFunctions.defined_functions[f.__name__] = f, False + return f + +def defun_static(f): + setattr(SpecialFunctions, f.__name__, f) + return f + +@defun_wrapped +def cot(ctx, z): return ctx.one / ctx.tan(z) + +@defun_wrapped +def sec(ctx, z): return ctx.one / ctx.cos(z) + +@defun_wrapped +def csc(ctx, z): return ctx.one / ctx.sin(z) + +@defun_wrapped +def coth(ctx, z): return ctx.one / ctx.tanh(z) + +@defun_wrapped +def sech(ctx, z): return ctx.one / ctx.cosh(z) + +@defun_wrapped +def csch(ctx, z): return ctx.one / ctx.sinh(z) + +@defun_wrapped +def acot(ctx, z): + if not z: + return ctx.pi * 0.5 + else: + return ctx.atan(ctx.one / z) + +@defun_wrapped +def asec(ctx, z): return ctx.acos(ctx.one / z) + +@defun_wrapped +def acsc(ctx, z): return ctx.asin(ctx.one / z) + +@defun_wrapped +def acoth(ctx, z): + if not z: + return ctx.pi * 0.5j + else: + return ctx.atanh(ctx.one / z) + + +@defun_wrapped +def asech(ctx, z): return ctx.acosh(ctx.one / z) + +@defun_wrapped +def acsch(ctx, z): return ctx.asinh(ctx.one / z) + +@defun +def sign(ctx, x): + x = ctx.convert(x) + if not x or ctx.isnan(x): + return x + if ctx._is_real_type(x): + if x > 0: + return ctx.one + else: + return -ctx.one + return x / abs(x) + +@defun +def agm(ctx, a, b=1): + if b == 1: + return ctx.agm1(a) + a = ctx.convert(a) + b = ctx.convert(b) + return ctx._agm(a, b) + +@defun_wrapped +def sinc(ctx, x): + if ctx.isinf(x): + return 1/x + if not x: + return x+1 + return ctx.sin(x)/x + +@defun_wrapped +def sincpi(ctx, x): + if ctx.isinf(x): + return 1/x + if not x: + return x+1 + return ctx.sinpi(x)/(ctx.pi*x) + +# TODO: tests; improve implementation +@defun_wrapped +def expm1(ctx, x): + if not x: + return ctx.zero + # exp(x) - 1 ~ x + if ctx.mag(x) < -ctx.prec: + return x + 0.5*x**2 + # TODO: accurately eval the smaller of the real/imag parts + return ctx.sum_accurately(lambda: iter([ctx.exp(x),-1]),1) + +@defun_wrapped +def log1p(ctx, x): + if not x: + return ctx.zero + if ctx.mag(x) < -ctx.prec: + return x - 0.5*x**2 + return ctx.log(ctx.fadd(1, x, prec=2*ctx.prec)) + +@defun_wrapped +def powm1(ctx, x, y): + mag = ctx.mag + one = ctx.one + w = x**y - one + M = mag(w) + # Only moderate cancellation + if M > -8: + return w + # Check for the only possible exact cases + if not w: + if (not y) or (x in (1, -1, 1j, -1j) and ctx.isint(y)): + return w + x1 = x - one + magy = mag(y) + lnx = ctx.ln(x) + # Small y: x^y - 1 ~ log(x)*y + O(log(x)^2 * y^2) + if magy + mag(lnx) < -ctx.prec: + return lnx*y + (lnx*y)**2/2 + # TODO: accurately eval the smaller of the real/imag part + return ctx.sum_accurately(lambda: iter([x**y, -1]), 1) + +@defun +def _rootof1(ctx, k, n): + k = int(k) + n = int(n) + k %= n + if not k: + return ctx.one + elif 2*k == n: + return -ctx.one + elif 4*k == n: + return ctx.j + elif 4*k == 3*n: + return -ctx.j + return ctx.expjpi(2*ctx.mpf(k)/n) + +@defun +def root(ctx, x, n, k=0): + n = int(n) + x = ctx.convert(x) + if k: + # Special case: there is an exact real root + if (n & 1 and 2*k == n-1) and (not ctx.im(x)) and (ctx.re(x) < 0): + return -ctx.root(-x, n) + # Multiply by root of unity + prec = ctx.prec + try: + ctx.prec += 10 + v = ctx.root(x, n, 0) * ctx._rootof1(k, n) + finally: + ctx.prec = prec + return +v + return ctx._nthroot(x, n) + +@defun +def unitroots(ctx, n, primitive=False): + gcd = ctx._gcd + prec = ctx.prec + try: + ctx.prec += 10 + if primitive: + v = [ctx._rootof1(k,n) for k in range(n) if gcd(k,n) == 1] + else: + # TODO: this can be done *much* faster + v = [ctx._rootof1(k,n) for k in range(n)] + finally: + ctx.prec = prec + return [+x for x in v] + +@defun +def arg(ctx, x): + x = ctx.convert(x) + re = ctx._re(x) + im = ctx._im(x) + return ctx.atan2(im, re) + +@defun +def fabs(ctx, x): + return abs(ctx.convert(x)) + +@defun +def re(ctx, x): + x = ctx.convert(x) + if hasattr(x, "real"): # py2.5 doesn't have .real/.imag for all numbers + return x.real + return x + +@defun +def im(ctx, x): + x = ctx.convert(x) + if hasattr(x, "imag"): # py2.5 doesn't have .real/.imag for all numbers + return x.imag + return ctx.zero + +@defun +def conj(ctx, x): + x = ctx.convert(x) + try: + return x.conjugate() + except AttributeError: + return x + +@defun +def polar(ctx, z): + return (ctx.fabs(z), ctx.arg(z)) + +@defun_wrapped +def rect(ctx, r, phi): + return r * ctx.mpc(*ctx.cos_sin(phi)) + +@defun +def log(ctx, x, b=None): + if b is None: + return ctx.ln(x) + wp = ctx.prec + 20 + return ctx.ln(x, prec=wp) / ctx.ln(b, prec=wp) + +@defun +def log10(ctx, x): + return ctx.log(x, 10) + +@defun +def fmod(ctx, x, y): + return ctx.convert(x) % ctx.convert(y) + +@defun +def degrees(ctx, x): + return x / ctx.degree + +@defun +def radians(ctx, x): + return x * ctx.degree + +def _lambertw_special(ctx, z, k): + # W(0,0) = 0; all other branches are singular + if not z: + if not k: + return z + return ctx.ninf + z + if z == ctx.inf: + if k == 0: + return z + else: + return z + 2*k*ctx.pi*ctx.j + if z == ctx.ninf: + return (-z) + (2*k+1)*ctx.pi*ctx.j + # Some kind of nan or complex inf/nan? + return ctx.ln(z) + +import math +import cmath + +def _lambertw_approx_hybrid(z, k): + imag_sign = 0 + if hasattr(z, "imag"): + x = float(z.real) + y = z.imag + if y: + imag_sign = (-1) ** (y < 0) + y = float(y) + else: + x = float(z) + y = 0.0 + imag_sign = 0 + # hack to work regardless of whether Python supports -0.0 + if not y: + y = 0.0 + z = complex(x,y) + if k == 0: + if -4.0 < y < 4.0 and -1.0 < x < 2.5: + if imag_sign: + # Taylor series in upper/lower half-plane + if y > 1.00: return (0.876+0.645j) + (0.118-0.174j)*(z-(0.75+2.5j)) + if y > 0.25: return (0.505+0.204j) + (0.375-0.132j)*(z-(0.75+0.5j)) + if y < -1.00: return (0.876-0.645j) + (0.118+0.174j)*(z-(0.75-2.5j)) + if y < -0.25: return (0.505-0.204j) + (0.375+0.132j)*(z-(0.75-0.5j)) + # Taylor series near -1 + if x < -0.5: + if imag_sign >= 0: + return (-0.318+1.34j) + (-0.697-0.593j)*(z+1) + else: + return (-0.318-1.34j) + (-0.697+0.593j)*(z+1) + # return real type + r = -0.367879441171442 + if (not imag_sign) and x > r: + z = x + # Singularity near -1/e + if x < -0.2: + return -1 + 2.33164398159712*(z-r)**0.5 - 1.81218788563936*(z-r) + # Taylor series near 0 + if x < 0.5: return z + # Simple linear approximation + return 0.2 + 0.3*z + if (not imag_sign) and x > 0.0: + L1 = math.log(x); L2 = math.log(L1) + else: + L1 = cmath.log(z); L2 = cmath.log(L1) + elif k == -1: + # return real type + r = -0.367879441171442 + if (not imag_sign) and r < x < 0.0: + z = x + if (imag_sign >= 0) and y < 0.1 and -0.6 < x < -0.2: + return -1 - 2.33164398159712*(z-r)**0.5 - 1.81218788563936*(z-r) + if (not imag_sign) and -0.2 <= x < 0.0: + L1 = math.log(-x) + return L1 - math.log(-L1) + else: + if imag_sign == -1 and (not y) and x < 0.0: + L1 = cmath.log(z) - 3.1415926535897932j + else: + L1 = cmath.log(z) - 6.2831853071795865j + L2 = cmath.log(L1) + return L1 - L2 + L2/L1 + L2*(L2-2)/(2*L1**2) + +def _lambertw_series(ctx, z, k, tol): + """ + Return rough approximation for W_k(z) from an asymptotic series, + sufficiently accurate for the Halley iteration to converge to + the correct value. + """ + magz = ctx.mag(z) + if (-10 < magz < 900) and (-1000 < k < 1000): + # Near the branch point at -1/e + if magz < 1 and abs(z+0.36787944117144) < 0.05: + if k == 0 or (k == -1 and ctx._im(z) >= 0) or \ + (k == 1 and ctx._im(z) < 0): + delta = ctx.sum_accurately(lambda: [z, ctx.exp(-1)]) + cancellation = -ctx.mag(delta) + ctx.prec += cancellation + # Use series given in Corless et al. + p = ctx.sqrt(2*(ctx.e*z+1)) + ctx.prec -= cancellation + u = {0:ctx.mpf(-1), 1:ctx.mpf(1)} + a = {0:ctx.mpf(2), 1:ctx.mpf(-1)} + if k != 0: + p = -p + s = ctx.zero + # The series converges, so we could use it directly, but unless + # *extremely* close, it is better to just use the first few + # terms to get a good approximation for the iteration + for l in xrange(max(2,cancellation)): + if l not in u: + a[l] = ctx.fsum(u[j]*u[l+1-j] for j in xrange(2,l)) + u[l] = (l-1)*(u[l-2]/2+a[l-2]/4)/(l+1)-a[l]/2-u[l-1]/(l+1) + term = u[l] * p**l + s += term + if ctx.mag(term) < -tol: + return s, True + l += 1 + ctx.prec += cancellation//2 + return s, False + if k == 0 or k == -1: + return _lambertw_approx_hybrid(z, k), False + if k == 0: + if magz < -1: + return z*(1-z), False + L1 = ctx.ln(z) + L2 = ctx.ln(L1) + elif k == -1 and (not ctx._im(z)) and (-0.36787944117144 < ctx._re(z) < 0): + L1 = ctx.ln(-z) + return L1 - ctx.ln(-L1), False + else: + # This holds both as z -> 0 and z -> inf. + # Relative error is O(1/log(z)). + L1 = ctx.ln(z) + 2j*ctx.pi*k + L2 = ctx.ln(L1) + return L1 - L2 + L2/L1 + L2*(L2-2)/(2*L1**2), False + +@defun +def lambertw(ctx, z, k=0): + z = ctx.convert(z) + k = int(k) + if not ctx.isnormal(z): + return _lambertw_special(ctx, z, k) + prec = ctx.prec + ctx.prec += 20 + ctx.mag(k or 1) + wp = ctx.prec + tol = wp - 5 + w, done = _lambertw_series(ctx, z, k, tol) + if not done: + # Use Halley iteration to solve w*exp(w) = z + two = ctx.mpf(2) + for i in xrange(100): + ew = ctx.exp(w) + wew = w*ew + wewz = wew-z + wn = w - wewz/(wew+ew-(w+two)*wewz/(two*w+two)) + if ctx.mag(wn-w) <= ctx.mag(wn) - tol: + w = wn + break + else: + w = wn + if i == 100: + ctx.warn("Lambert W iteration failed to converge for z = %s" % z) + ctx.prec = prec + return +w + +@defun_wrapped +def bell(ctx, n, x=1): + x = ctx.convert(x) + if not n: + if ctx.isnan(x): + return x + return type(x)(1) + if ctx.isinf(x) or ctx.isinf(n) or ctx.isnan(x) or ctx.isnan(n): + return x**n + if n == 1: return x + if n == 2: return x*(x+1) + if x == 0: return ctx.sincpi(n) + return _polyexp(ctx, n, x, True) / ctx.exp(x) + +def _polyexp(ctx, n, x, extra=False): + def _terms(): + if extra: + yield ctx.sincpi(n) + t = x + k = 1 + while 1: + yield k**n * t + k += 1 + t = t*x/k + return ctx.sum_accurately(_terms, check_step=4) + +@defun_wrapped +def polyexp(ctx, s, z): + if ctx.isinf(z) or ctx.isinf(s) or ctx.isnan(z) or ctx.isnan(s): + return z**s + if z == 0: return z*s + if s == 0: return ctx.expm1(z) + if s == 1: return ctx.exp(z)*z + if s == 2: return ctx.exp(z)*z*(z+1) + return _polyexp(ctx, s, z) + +@defun_wrapped +def cyclotomic(ctx, n, z): + n = int(n) + if n < 0: + raise ValueError("n cannot be negative") + p = ctx.one + if n == 0: + return p + if n == 1: + return z - p + if n == 2: + return z + p + # Use divisor product representation. Unfortunately, this sometimes + # includes singularities for roots of unity, which we have to cancel out. + # Matching zeros/poles pairwise, we have (1-z^a)/(1-z^b) ~ a/b + O(z-1). + a_prod = 1 + b_prod = 1 + num_zeros = 0 + num_poles = 0 + for d in range(1,n+1): + if not n % d: + w = ctx.moebius(n//d) + # Use powm1 because it is important that we get 0 only + # if it really is exactly 0 + b = -ctx.powm1(z, d) + if b: + p *= b**w + else: + if w == 1: + a_prod *= d + num_zeros += 1 + elif w == -1: + b_prod *= d + num_poles += 1 + #print n, num_zeros, num_poles + if num_zeros: + if num_zeros > num_poles: + p *= 0 + else: + p *= a_prod + p /= b_prod + return p + +@defun +def mangoldt(ctx, n): + r""" + Evaluates the von Mangoldt function `\Lambda(n) = \log p` + if `n = p^k` a power of a prime, and `\Lambda(n) = 0` otherwise. + + **Examples** + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> [mangoldt(n) for n in range(-2,3)] + [0.0, 0.0, 0.0, 0.0, 0.6931471805599453094172321] + >>> mangoldt(6) + 0.0 + >>> mangoldt(7) + 1.945910149055313305105353 + >>> mangoldt(8) + 0.6931471805599453094172321 + >>> fsum(mangoldt(n) for n in range(101)) + 94.04531122935739224600493 + >>> fsum(mangoldt(n) for n in range(10001)) + 10013.39669326311478372032 + + """ + n = int(n) + if n < 2: + return ctx.zero + if n % 2 == 0: + # Must be a power of two + if n & (n-1) == 0: + return +ctx.ln2 + else: + return ctx.zero + # TODO: the following could be generalized into a perfect + # power testing function + # --- + # Look for a small factor + for p in (3,5,7,11,13,17,19,23,29,31): + if not n % p: + q, r = n // p, 0 + while q > 1: + q, r = divmod(q, p) + if r: + return ctx.zero + return ctx.ln(p) + if ctx.isprime(n): + return ctx.ln(n) + # Obviously, we could use arbitrary-precision arithmetic for this... + if n > 10**30: + raise NotImplementedError + k = 2 + while 1: + p = int(n**(1./k) + 0.5) + if p < 2: + return ctx.zero + if p ** k == n: + if ctx.isprime(p): + return ctx.ln(p) + k += 1 + +@defun +def stirling1(ctx, n, k, exact=False): + v = ctx._stirling1(int(n), int(k)) + if exact: + return int(v) + else: + return ctx.mpf(v) + +@defun +def stirling2(ctx, n, k, exact=False): + v = ctx._stirling2(int(n), int(k)) + if exact: + return int(v) + else: + return ctx.mpf(v) diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/hypergeometric.py b/venv/lib/python3.10/site-packages/mpmath/functions/hypergeometric.py new file mode 100644 index 0000000000000000000000000000000000000000..ddb50cbf3ea6daa5982678d3c26157a67a7d7945 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/functions/hypergeometric.py @@ -0,0 +1,1413 @@ +from ..libmp.backend import xrange +from .functions import defun, defun_wrapped + +def _check_need_perturb(ctx, terms, prec, discard_known_zeros): + perturb = recompute = False + extraprec = 0 + discard = [] + for term_index, term in enumerate(terms): + w_s, c_s, alpha_s, beta_s, a_s, b_s, z = term + have_singular_nongamma_weight = False + # Avoid division by zero in leading factors (TODO: + # also check for near division by zero?) + for k, w in enumerate(w_s): + if not w: + if ctx.re(c_s[k]) <= 0 and c_s[k]: + perturb = recompute = True + have_singular_nongamma_weight = True + pole_count = [0, 0, 0] + # Check for gamma and series poles and near-poles + for data_index, data in enumerate([alpha_s, beta_s, b_s]): + for i, x in enumerate(data): + n, d = ctx.nint_distance(x) + # Poles + if n > 0: + continue + if d == ctx.ninf: + # OK if we have a polynomial + # ------------------------------ + ok = False + if data_index == 2: + for u in a_s: + if ctx.isnpint(u) and u >= int(n): + ok = True + break + if ok: + continue + pole_count[data_index] += 1 + # ------------------------------ + #perturb = recompute = True + #return perturb, recompute, extraprec + elif d < -4: + extraprec += -d + recompute = True + if discard_known_zeros and pole_count[1] > pole_count[0] + pole_count[2] \ + and not have_singular_nongamma_weight: + discard.append(term_index) + elif sum(pole_count): + perturb = recompute = True + return perturb, recompute, extraprec, discard + +_hypercomb_msg = """ +hypercomb() failed to converge to the requested %i bits of accuracy +using a working precision of %i bits. The function value may be zero or +infinite; try passing zeroprec=N or infprec=M to bound finite values between +2^(-N) and 2^M. Otherwise try a higher maxprec or maxterms. +""" + +@defun +def hypercomb(ctx, function, params=[], discard_known_zeros=True, **kwargs): + orig = ctx.prec + sumvalue = ctx.zero + dist = ctx.nint_distance + ninf = ctx.ninf + orig_params = params[:] + verbose = kwargs.get('verbose', False) + maxprec = kwargs.get('maxprec', ctx._default_hyper_maxprec(orig)) + kwargs['maxprec'] = maxprec # For calls to hypsum + zeroprec = kwargs.get('zeroprec') + infprec = kwargs.get('infprec') + perturbed_reference_value = None + hextra = 0 + try: + while 1: + ctx.prec += 10 + if ctx.prec > maxprec: + raise ValueError(_hypercomb_msg % (orig, ctx.prec)) + orig2 = ctx.prec + params = orig_params[:] + terms = function(*params) + if verbose: + print() + print("ENTERING hypercomb main loop") + print("prec =", ctx.prec) + print("hextra", hextra) + perturb, recompute, extraprec, discard = \ + _check_need_perturb(ctx, terms, orig, discard_known_zeros) + ctx.prec += extraprec + if perturb: + if "hmag" in kwargs: + hmag = kwargs["hmag"] + elif ctx._fixed_precision: + hmag = int(ctx.prec*0.3) + else: + hmag = orig + 10 + hextra + h = ctx.ldexp(ctx.one, -hmag) + ctx.prec = orig2 + 10 + hmag + 10 + for k in range(len(params)): + params[k] += h + # Heuristically ensure that the perturbations + # are "independent" so that two perturbations + # don't accidentally cancel each other out + # in a subtraction. + h += h/(k+1) + if recompute: + terms = function(*params) + if discard_known_zeros: + terms = [term for (i, term) in enumerate(terms) if i not in discard] + if not terms: + return ctx.zero + evaluated_terms = [] + for term_index, term_data in enumerate(terms): + w_s, c_s, alpha_s, beta_s, a_s, b_s, z = term_data + if verbose: + print() + print(" Evaluating term %i/%i : %iF%i" % \ + (term_index+1, len(terms), len(a_s), len(b_s))) + print(" powers", ctx.nstr(w_s), ctx.nstr(c_s)) + print(" gamma", ctx.nstr(alpha_s), ctx.nstr(beta_s)) + print(" hyper", ctx.nstr(a_s), ctx.nstr(b_s)) + print(" z", ctx.nstr(z)) + #v = ctx.hyper(a_s, b_s, z, **kwargs) + #for a in alpha_s: v *= ctx.gamma(a) + #for b in beta_s: v *= ctx.rgamma(b) + #for w, c in zip(w_s, c_s): v *= ctx.power(w, c) + v = ctx.fprod([ctx.hyper(a_s, b_s, z, **kwargs)] + \ + [ctx.gamma(a) for a in alpha_s] + \ + [ctx.rgamma(b) for b in beta_s] + \ + [ctx.power(w,c) for (w,c) in zip(w_s,c_s)]) + if verbose: + print(" Value:", v) + evaluated_terms.append(v) + + if len(terms) == 1 and (not perturb): + sumvalue = evaluated_terms[0] + break + + if ctx._fixed_precision: + sumvalue = ctx.fsum(evaluated_terms) + break + + sumvalue = ctx.fsum(evaluated_terms) + term_magnitudes = [ctx.mag(x) for x in evaluated_terms] + max_magnitude = max(term_magnitudes) + sum_magnitude = ctx.mag(sumvalue) + cancellation = max_magnitude - sum_magnitude + if verbose: + print() + print(" Cancellation:", cancellation, "bits") + print(" Increased precision:", ctx.prec - orig, "bits") + + precision_ok = cancellation < ctx.prec - orig + + if zeroprec is None: + zero_ok = False + else: + zero_ok = max_magnitude - ctx.prec < -zeroprec + if infprec is None: + inf_ok = False + else: + inf_ok = max_magnitude > infprec + + if precision_ok and (not perturb) or ctx.isnan(cancellation): + break + elif precision_ok: + if perturbed_reference_value is None: + hextra += 20 + perturbed_reference_value = sumvalue + continue + elif ctx.mag(sumvalue - perturbed_reference_value) <= \ + ctx.mag(sumvalue) - orig: + break + elif zero_ok: + sumvalue = ctx.zero + break + elif inf_ok: + sumvalue = ctx.inf + break + elif 'hmag' in kwargs: + break + else: + hextra *= 2 + perturbed_reference_value = sumvalue + # Increase precision + else: + increment = min(max(cancellation, orig//2), max(extraprec,orig)) + ctx.prec += increment + if verbose: + print(" Must start over with increased precision") + continue + finally: + ctx.prec = orig + return +sumvalue + +@defun +def hyper(ctx, a_s, b_s, z, **kwargs): + """ + Hypergeometric function, general case. + """ + z = ctx.convert(z) + p = len(a_s) + q = len(b_s) + a_s = [ctx._convert_param(a) for a in a_s] + b_s = [ctx._convert_param(b) for b in b_s] + # Reduce degree by eliminating common parameters + if kwargs.get('eliminate', True): + elim_nonpositive = kwargs.get('eliminate_all', False) + i = 0 + while i < q and a_s: + b = b_s[i] + if b in a_s and (elim_nonpositive or not ctx.isnpint(b[0])): + a_s.remove(b) + b_s.remove(b) + p -= 1 + q -= 1 + else: + i += 1 + # Handle special cases + if p == 0: + if q == 1: return ctx._hyp0f1(b_s, z, **kwargs) + elif q == 0: return ctx.exp(z) + elif p == 1: + if q == 1: return ctx._hyp1f1(a_s, b_s, z, **kwargs) + elif q == 2: return ctx._hyp1f2(a_s, b_s, z, **kwargs) + elif q == 0: return ctx._hyp1f0(a_s[0][0], z) + elif p == 2: + if q == 1: return ctx._hyp2f1(a_s, b_s, z, **kwargs) + elif q == 2: return ctx._hyp2f2(a_s, b_s, z, **kwargs) + elif q == 3: return ctx._hyp2f3(a_s, b_s, z, **kwargs) + elif q == 0: return ctx._hyp2f0(a_s, b_s, z, **kwargs) + elif p == q+1: + return ctx._hypq1fq(p, q, a_s, b_s, z, **kwargs) + elif p > q+1 and not kwargs.get('force_series'): + return ctx._hyp_borel(p, q, a_s, b_s, z, **kwargs) + coeffs, types = zip(*(a_s+b_s)) + return ctx.hypsum(p, q, types, coeffs, z, **kwargs) + +@defun +def hyp0f1(ctx,b,z,**kwargs): + return ctx.hyper([],[b],z,**kwargs) + +@defun +def hyp1f1(ctx,a,b,z,**kwargs): + return ctx.hyper([a],[b],z,**kwargs) + +@defun +def hyp1f2(ctx,a1,b1,b2,z,**kwargs): + return ctx.hyper([a1],[b1,b2],z,**kwargs) + +@defun +def hyp2f1(ctx,a,b,c,z,**kwargs): + return ctx.hyper([a,b],[c],z,**kwargs) + +@defun +def hyp2f2(ctx,a1,a2,b1,b2,z,**kwargs): + return ctx.hyper([a1,a2],[b1,b2],z,**kwargs) + +@defun +def hyp2f3(ctx,a1,a2,b1,b2,b3,z,**kwargs): + return ctx.hyper([a1,a2],[b1,b2,b3],z,**kwargs) + +@defun +def hyp2f0(ctx,a,b,z,**kwargs): + return ctx.hyper([a,b],[],z,**kwargs) + +@defun +def hyp3f2(ctx,a1,a2,a3,b1,b2,z,**kwargs): + return ctx.hyper([a1,a2,a3],[b1,b2],z,**kwargs) + +@defun_wrapped +def _hyp1f0(ctx, a, z): + return (1-z) ** (-a) + +@defun +def _hyp0f1(ctx, b_s, z, **kwargs): + (b, btype), = b_s + if z: + magz = ctx.mag(z) + else: + magz = 0 + if magz >= 8 and not kwargs.get('force_series'): + try: + # http://functions.wolfram.com/HypergeometricFunctions/ + # Hypergeometric0F1/06/02/03/0004/ + # TODO: handle the all-real case more efficiently! + # TODO: figure out how much precision is needed (exponential growth) + orig = ctx.prec + try: + ctx.prec += 12 + magz//2 + def h(): + w = ctx.sqrt(-z) + jw = ctx.j*w + u = 1/(4*jw) + c = ctx.mpq_1_2 - b + E = ctx.exp(2*jw) + T1 = ([-jw,E], [c,-1], [], [], [b-ctx.mpq_1_2, ctx.mpq_3_2-b], [], -u) + T2 = ([jw,E], [c,1], [], [], [b-ctx.mpq_1_2, ctx.mpq_3_2-b], [], u) + return T1, T2 + v = ctx.hypercomb(h, [], force_series=True) + v = ctx.gamma(b)/(2*ctx.sqrt(ctx.pi))*v + finally: + ctx.prec = orig + if ctx._is_real_type(b) and ctx._is_real_type(z): + v = ctx._re(v) + return +v + except ctx.NoConvergence: + pass + return ctx.hypsum(0, 1, (btype,), [b], z, **kwargs) + +@defun +def _hyp1f1(ctx, a_s, b_s, z, **kwargs): + (a, atype), = a_s + (b, btype), = b_s + if not z: + return ctx.one+z + magz = ctx.mag(z) + if magz >= 7 and not (ctx.isint(a) and ctx.re(a) <= 0): + if ctx.isinf(z): + if ctx.sign(a) == ctx.sign(b) == ctx.sign(z) == 1: + return ctx.inf + return ctx.nan * z + try: + try: + ctx.prec += magz + sector = ctx._im(z) < 0 + def h(a,b): + if sector: + E = ctx.expjpi(ctx.fneg(a, exact=True)) + else: + E = ctx.expjpi(a) + rz = 1/z + T1 = ([E,z], [1,-a], [b], [b-a], [a, 1+a-b], [], -rz) + T2 = ([ctx.exp(z),z], [1,a-b], [b], [a], [b-a, 1-a], [], rz) + return T1, T2 + v = ctx.hypercomb(h, [a,b], force_series=True) + if ctx._is_real_type(a) and ctx._is_real_type(b) and ctx._is_real_type(z): + v = ctx._re(v) + return +v + except ctx.NoConvergence: + pass + finally: + ctx.prec -= magz + v = ctx.hypsum(1, 1, (atype, btype), [a, b], z, **kwargs) + return v + +def _hyp2f1_gosper(ctx,a,b,c,z,**kwargs): + # Use Gosper's recurrence + # See http://www.math.utexas.edu/pipermail/maxima/2006/000126.html + _a,_b,_c,_z = a, b, c, z + orig = ctx.prec + maxprec = kwargs.get('maxprec', 100*orig) + extra = 10 + while 1: + ctx.prec = orig + extra + #a = ctx.convert(_a) + #b = ctx.convert(_b) + #c = ctx.convert(_c) + z = ctx.convert(_z) + d = ctx.mpf(0) + e = ctx.mpf(1) + f = ctx.mpf(0) + k = 0 + # Common subexpression elimination, unfortunately making + # things a bit unreadable. The formula is quite messy to begin + # with, though... + abz = a*b*z + ch = c * ctx.mpq_1_2 + c1h = (c+1) * ctx.mpq_1_2 + nz = 1-z + g = z/nz + abg = a*b*g + cba = c-b-a + z2 = z-2 + tol = -ctx.prec - 10 + nstr = ctx.nstr + nprint = ctx.nprint + mag = ctx.mag + maxmag = ctx.ninf + while 1: + kch = k+ch + kakbz = (k+a)*(k+b)*z / (4*(k+1)*kch*(k+c1h)) + d1 = kakbz*(e-(k+cba)*d*g) + e1 = kakbz*(d*abg+(k+c)*e) + ft = d*(k*(cba*z+k*z2-c)-abz)/(2*kch*nz) + f1 = f + e - ft + maxmag = max(maxmag, mag(f1)) + if mag(f1-f) < tol: + break + d, e, f = d1, e1, f1 + k += 1 + cancellation = maxmag - mag(f1) + if cancellation < extra: + break + else: + extra += cancellation + if extra > maxprec: + raise ctx.NoConvergence + return f1 + +@defun +def _hyp2f1(ctx, a_s, b_s, z, **kwargs): + (a, atype), (b, btype) = a_s + (c, ctype), = b_s + if z == 1: + # TODO: the following logic can be simplified + convergent = ctx.re(c-a-b) > 0 + finite = (ctx.isint(a) and a <= 0) or (ctx.isint(b) and b <= 0) + zerodiv = ctx.isint(c) and c <= 0 and not \ + ((ctx.isint(a) and c <= a <= 0) or (ctx.isint(b) and c <= b <= 0)) + #print "bz", a, b, c, z, convergent, finite, zerodiv + # Gauss's theorem gives the value if convergent + if (convergent or finite) and not zerodiv: + return ctx.gammaprod([c, c-a-b], [c-a, c-b], _infsign=True) + # Otherwise, there is a pole and we take the + # sign to be that when approaching from below + # XXX: this evaluation is not necessarily correct in all cases + return ctx.hyp2f1(a,b,c,1-ctx.eps*2) * ctx.inf + + # Equal to 1 (first term), unless there is a subsequent + # division by zero + if not z: + # Division by zero but power of z is higher than + # first order so cancels + if c or a == 0 or b == 0: + return 1+z + # Indeterminate + return ctx.nan + + # Hit zero denominator unless numerator goes to 0 first + if ctx.isint(c) and c <= 0: + if (ctx.isint(a) and c <= a <= 0) or \ + (ctx.isint(b) and c <= b <= 0): + pass + else: + # Pole in series + return ctx.inf + + absz = abs(z) + + # Fast case: standard series converges rapidly, + # possibly in finitely many terms + if absz <= 0.8 or (ctx.isint(a) and a <= 0 and a >= -1000) or \ + (ctx.isint(b) and b <= 0 and b >= -1000): + return ctx.hypsum(2, 1, (atype, btype, ctype), [a, b, c], z, **kwargs) + + orig = ctx.prec + try: + ctx.prec += 10 + + # Use 1/z transformation + if absz >= 1.3: + def h(a,b): + t = ctx.mpq_1-c; ab = a-b; rz = 1/z + T1 = ([-z],[-a], [c,-ab],[b,c-a], [a,t+a],[ctx.mpq_1+ab], rz) + T2 = ([-z],[-b], [c,ab],[a,c-b], [b,t+b],[ctx.mpq_1-ab], rz) + return T1, T2 + v = ctx.hypercomb(h, [a,b], **kwargs) + + # Use 1-z transformation + elif abs(1-z) <= 0.75: + def h(a,b): + t = c-a-b; ca = c-a; cb = c-b; rz = 1-z + T1 = [], [], [c,t], [ca,cb], [a,b], [1-t], rz + T2 = [rz], [t], [c,a+b-c], [a,b], [ca,cb], [1+t], rz + return T1, T2 + v = ctx.hypercomb(h, [a,b], **kwargs) + + # Use z/(z-1) transformation + elif abs(z/(z-1)) <= 0.75: + v = ctx.hyp2f1(a, c-b, c, z/(z-1)) / (1-z)**a + + # Remaining part of unit circle + else: + v = _hyp2f1_gosper(ctx,a,b,c,z,**kwargs) + + finally: + ctx.prec = orig + return +v + +@defun +def _hypq1fq(ctx, p, q, a_s, b_s, z, **kwargs): + r""" + Evaluates 3F2, 4F3, 5F4, ... + """ + a_s, a_types = zip(*a_s) + b_s, b_types = zip(*b_s) + a_s = list(a_s) + b_s = list(b_s) + absz = abs(z) + ispoly = False + for a in a_s: + if ctx.isint(a) and a <= 0: + ispoly = True + break + # Direct summation + if absz < 1 or ispoly: + try: + return ctx.hypsum(p, q, a_types+b_types, a_s+b_s, z, **kwargs) + except ctx.NoConvergence: + if absz > 1.1 or ispoly: + raise + # Use expansion at |z-1| -> 0. + # Reference: Wolfgang Buhring, "Generalized Hypergeometric Functions at + # Unit Argument", Proc. Amer. Math. Soc., Vol. 114, No. 1 (Jan. 1992), + # pp.145-153 + # The current implementation has several problems: + # 1. We only implement it for 3F2. The expansion coefficients are + # given by extremely messy nested sums in the higher degree cases + # (see reference). Is efficient sequential generation of the coefficients + # possible in the > 3F2 case? + # 2. Although the series converges, it may do so slowly, so we need + # convergence acceleration. The acceleration implemented by + # nsum does not always help, so results returned are sometimes + # inaccurate! Can we do better? + # 3. We should check conditions for convergence, and possibly + # do a better job of cancelling out gamma poles if possible. + if z == 1: + # XXX: should also check for division by zero in the + # denominator of the series (cf. hyp2f1) + S = ctx.re(sum(b_s)-sum(a_s)) + if S <= 0: + #return ctx.hyper(a_s, b_s, 1-ctx.eps*2, **kwargs) * ctx.inf + return ctx.hyper(a_s, b_s, 0.9, **kwargs) * ctx.inf + if (p,q) == (3,2) and abs(z-1) < 0.05: # and kwargs.get('sum1') + #print "Using alternate summation (experimental)" + a1,a2,a3 = a_s + b1,b2 = b_s + u = b1+b2-a3 + initial = ctx.gammaprod([b2-a3,b1-a3,a1,a2],[b2-a3,b1-a3,1,u]) + def term(k, _cache={0:initial}): + u = b1+b2-a3+k + if k in _cache: + t = _cache[k] + else: + t = _cache[k-1] + t *= (b1+k-a3-1)*(b2+k-a3-1) + t /= k*(u-1) + _cache[k] = t + return t * ctx.hyp2f1(a1,a2,u,z) + try: + S = ctx.nsum(term, [0,ctx.inf], verbose=kwargs.get('verbose'), + strict=kwargs.get('strict', True)) + return S * ctx.gammaprod([b1,b2],[a1,a2,a3]) + except ctx.NoConvergence: + pass + # Try to use convergence acceleration on and close to the unit circle. + # Problem: the convergence acceleration degenerates as |z-1| -> 0, + # except for special cases. Everywhere else, the Shanks transformation + # is very efficient. + if absz < 1.1 and ctx._re(z) <= 1: + + def term(kk, _cache={0:ctx.one}): + k = int(kk) + if k != kk: + t = z ** ctx.mpf(kk) / ctx.fac(kk) + for a in a_s: t *= ctx.rf(a,kk) + for b in b_s: t /= ctx.rf(b,kk) + return t + if k in _cache: + return _cache[k] + t = term(k-1) + m = k-1 + for j in xrange(p): t *= (a_s[j]+m) + for j in xrange(q): t /= (b_s[j]+m) + t *= z + t /= k + _cache[k] = t + return t + + sum_method = kwargs.get('sum_method', 'r+s+e') + + try: + return ctx.nsum(term, [0,ctx.inf], verbose=kwargs.get('verbose'), + strict=kwargs.get('strict', True), + method=sum_method.replace('e','')) + except ctx.NoConvergence: + if 'e' not in sum_method: + raise + pass + + if kwargs.get('verbose'): + print("Attempting Euler-Maclaurin summation") + + + """ + Somewhat slower version (one diffs_exp for each factor). + However, this would be faster with fast direct derivatives + of the gamma function. + + def power_diffs(k0): + r = 0 + l = ctx.log(z) + while 1: + yield z**ctx.mpf(k0) * l**r + r += 1 + + def loggamma_diffs(x, reciprocal=False): + sign = (-1) ** reciprocal + yield sign * ctx.loggamma(x) + i = 0 + while 1: + yield sign * ctx.psi(i,x) + i += 1 + + def hyper_diffs(k0): + b2 = b_s + [1] + A = [ctx.diffs_exp(loggamma_diffs(a+k0)) for a in a_s] + B = [ctx.diffs_exp(loggamma_diffs(b+k0,True)) for b in b2] + Z = [power_diffs(k0)] + C = ctx.gammaprod([b for b in b2], [a for a in a_s]) + for d in ctx.diffs_prod(A + B + Z): + v = C * d + yield v + """ + + def log_diffs(k0): + b2 = b_s + [1] + yield sum(ctx.loggamma(a+k0) for a in a_s) - \ + sum(ctx.loggamma(b+k0) for b in b2) + k0*ctx.log(z) + i = 0 + while 1: + v = sum(ctx.psi(i,a+k0) for a in a_s) - \ + sum(ctx.psi(i,b+k0) for b in b2) + if i == 0: + v += ctx.log(z) + yield v + i += 1 + + def hyper_diffs(k0): + C = ctx.gammaprod([b for b in b_s], [a for a in a_s]) + for d in ctx.diffs_exp(log_diffs(k0)): + v = C * d + yield v + + tol = ctx.eps / 1024 + prec = ctx.prec + try: + trunc = 50 * ctx.dps + ctx.prec += 20 + for i in xrange(5): + head = ctx.fsum(term(k) for k in xrange(trunc)) + tail, err = ctx.sumem(term, [trunc, ctx.inf], tol=tol, + adiffs=hyper_diffs(trunc), + verbose=kwargs.get('verbose'), + error=True, + _fast_abort=True) + if err < tol: + v = head + tail + break + trunc *= 2 + # Need to increase precision because calculation of + # derivatives may be inaccurate + ctx.prec += ctx.prec//2 + if i == 4: + raise ctx.NoConvergence(\ + "Euler-Maclaurin summation did not converge") + finally: + ctx.prec = prec + return +v + + # Use 1/z transformation + # http://functions.wolfram.com/HypergeometricFunctions/ + # HypergeometricPFQ/06/01/05/02/0004/ + def h(*args): + a_s = list(args[:p]) + b_s = list(args[p:]) + Ts = [] + recz = ctx.one/z + negz = ctx.fneg(z, exact=True) + for k in range(q+1): + ak = a_s[k] + C = [negz] + Cp = [-ak] + Gn = b_s + [ak] + [a_s[j]-ak for j in range(q+1) if j != k] + Gd = a_s + [b_s[j]-ak for j in range(q)] + Fn = [ak] + [ak-b_s[j]+1 for j in range(q)] + Fd = [1-a_s[j]+ak for j in range(q+1) if j != k] + Ts.append((C, Cp, Gn, Gd, Fn, Fd, recz)) + return Ts + return ctx.hypercomb(h, a_s+b_s, **kwargs) + +@defun +def _hyp_borel(ctx, p, q, a_s, b_s, z, **kwargs): + if a_s: + a_s, a_types = zip(*a_s) + a_s = list(a_s) + else: + a_s, a_types = [], () + if b_s: + b_s, b_types = zip(*b_s) + b_s = list(b_s) + else: + b_s, b_types = [], () + kwargs['maxterms'] = kwargs.get('maxterms', ctx.prec) + try: + return ctx.hypsum(p, q, a_types+b_types, a_s+b_s, z, **kwargs) + except ctx.NoConvergence: + pass + prec = ctx.prec + try: + tol = kwargs.get('asymp_tol', ctx.eps/4) + ctx.prec += 10 + # hypsum is has a conservative tolerance. So we try again: + def term(k, cache={0:ctx.one}): + if k in cache: + return cache[k] + t = term(k-1) + for a in a_s: t *= (a+(k-1)) + for b in b_s: t /= (b+(k-1)) + t *= z + t /= k + cache[k] = t + return t + s = ctx.one + for k in xrange(1, ctx.prec): + t = term(k) + s += t + if abs(t) <= tol: + return s + finally: + ctx.prec = prec + if p <= q+3: + contour = kwargs.get('contour') + if not contour: + if ctx.arg(z) < 0.25: + u = z / max(1, abs(z)) + if ctx.arg(z) >= 0: + contour = [0, 2j, (2j+2)/u, 2/u, ctx.inf] + else: + contour = [0, -2j, (-2j+2)/u, 2/u, ctx.inf] + #contour = [0, 2j/z, 2/z, ctx.inf] + #contour = [0, 2j, 2/z, ctx.inf] + #contour = [0, 2j, ctx.inf] + else: + contour = [0, ctx.inf] + quad_kwargs = kwargs.get('quad_kwargs', {}) + def g(t): + return ctx.exp(-t)*ctx.hyper(a_s, b_s+[1], t*z) + I, err = ctx.quad(g, contour, error=True, **quad_kwargs) + if err <= abs(I)*ctx.eps*8: + return I + raise ctx.NoConvergence + + +@defun +def _hyp2f2(ctx, a_s, b_s, z, **kwargs): + (a1, a1type), (a2, a2type) = a_s + (b1, b1type), (b2, b2type) = b_s + + absz = abs(z) + magz = ctx.mag(z) + orig = ctx.prec + + # Asymptotic expansion is ~ exp(z) + asymp_extraprec = magz + + # Asymptotic series is in terms of 3F1 + can_use_asymptotic = (not kwargs.get('force_series')) and \ + (ctx.mag(absz) > 3) + + # TODO: much of the following could be shared with 2F3 instead of + # copypasted + if can_use_asymptotic: + #print "using asymp" + try: + try: + ctx.prec += asymp_extraprec + # http://functions.wolfram.com/HypergeometricFunctions/ + # Hypergeometric2F2/06/02/02/0002/ + def h(a1,a2,b1,b2): + X = a1+a2-b1-b2 + A2 = a1+a2 + B2 = b1+b2 + c = {} + c[0] = ctx.one + c[1] = (A2-1)*X+b1*b2-a1*a2 + s1 = 0 + k = 0 + tprev = 0 + while 1: + if k not in c: + uu1 = 1-B2+2*a1+a1**2+2*a2+a2**2-A2*B2+a1*a2+b1*b2+(2*B2-3*(A2+1))*k+2*k**2 + uu2 = (k-A2+b1-1)*(k-A2+b2-1)*(k-X-2) + c[k] = ctx.one/k * (uu1*c[k-1]-uu2*c[k-2]) + t1 = c[k] * z**(-k) + if abs(t1) < 0.1*ctx.eps: + #print "Convergence :)" + break + # Quit if the series doesn't converge quickly enough + if k > 5 and abs(tprev) / abs(t1) < 1.5: + #print "No convergence :(" + raise ctx.NoConvergence + s1 += t1 + tprev = t1 + k += 1 + S = ctx.exp(z)*s1 + T1 = [z,S], [X,1], [b1,b2],[a1,a2],[],[],0 + T2 = [-z],[-a1],[b1,b2,a2-a1],[a2,b1-a1,b2-a1],[a1,a1-b1+1,a1-b2+1],[a1-a2+1],-1/z + T3 = [-z],[-a2],[b1,b2,a1-a2],[a1,b1-a2,b2-a2],[a2,a2-b1+1,a2-b2+1],[-a1+a2+1],-1/z + return T1, T2, T3 + v = ctx.hypercomb(h, [a1,a2,b1,b2], force_series=True, maxterms=4*ctx.prec) + if sum(ctx._is_real_type(u) for u in [a1,a2,b1,b2,z]) == 5: + v = ctx.re(v) + return v + except ctx.NoConvergence: + pass + finally: + ctx.prec = orig + + return ctx.hypsum(2, 2, (a1type, a2type, b1type, b2type), [a1, a2, b1, b2], z, **kwargs) + + + +@defun +def _hyp1f2(ctx, a_s, b_s, z, **kwargs): + (a1, a1type), = a_s + (b1, b1type), (b2, b2type) = b_s + + absz = abs(z) + magz = ctx.mag(z) + orig = ctx.prec + + # Asymptotic expansion is ~ exp(sqrt(z)) + asymp_extraprec = z and magz//2 + + # Asymptotic series is in terms of 3F0 + can_use_asymptotic = (not kwargs.get('force_series')) and \ + (ctx.mag(absz) > 19) and \ + (ctx.sqrt(absz) > 1.5*orig) # and \ + # ctx._hyp_check_convergence([a1, a1-b1+1, a1-b2+1], [], + # 1/absz, orig+40+asymp_extraprec) + + # TODO: much of the following could be shared with 2F3 instead of + # copypasted + if can_use_asymptotic: + #print "using asymp" + try: + try: + ctx.prec += asymp_extraprec + # http://functions.wolfram.com/HypergeometricFunctions/ + # Hypergeometric1F2/06/02/03/ + def h(a1,b1,b2): + X = ctx.mpq_1_2*(a1-b1-b2+ctx.mpq_1_2) + c = {} + c[0] = ctx.one + c[1] = 2*(ctx.mpq_1_4*(3*a1+b1+b2-2)*(a1-b1-b2)+b1*b2-ctx.mpq_3_16) + c[2] = 2*(b1*b2+ctx.mpq_1_4*(a1-b1-b2)*(3*a1+b1+b2-2)-ctx.mpq_3_16)**2+\ + ctx.mpq_1_16*(-16*(2*a1-3)*b1*b2 + \ + 4*(a1-b1-b2)*(-8*a1**2+11*a1+b1+b2-2)-3) + s1 = 0 + s2 = 0 + k = 0 + tprev = 0 + while 1: + if k not in c: + uu1 = (3*k**2+(-6*a1+2*b1+2*b2-4)*k + 3*a1**2 - \ + (b1-b2)**2 - 2*a1*(b1+b2-2) + ctx.mpq_1_4) + uu2 = (k-a1+b1-b2-ctx.mpq_1_2)*(k-a1-b1+b2-ctx.mpq_1_2)*\ + (k-a1+b1+b2-ctx.mpq_5_2) + c[k] = ctx.one/(2*k)*(uu1*c[k-1]-uu2*c[k-2]) + w = c[k] * (-z)**(-0.5*k) + t1 = (-ctx.j)**k * ctx.mpf(2)**(-k) * w + t2 = ctx.j**k * ctx.mpf(2)**(-k) * w + if abs(t1) < 0.1*ctx.eps: + #print "Convergence :)" + break + # Quit if the series doesn't converge quickly enough + if k > 5 and abs(tprev) / abs(t1) < 1.5: + #print "No convergence :(" + raise ctx.NoConvergence + s1 += t1 + s2 += t2 + tprev = t1 + k += 1 + S = ctx.expj(ctx.pi*X+2*ctx.sqrt(-z))*s1 + \ + ctx.expj(-(ctx.pi*X+2*ctx.sqrt(-z)))*s2 + T1 = [0.5*S, ctx.pi, -z], [1, -0.5, X], [b1, b2], [a1],\ + [], [], 0 + T2 = [-z], [-a1], [b1,b2],[b1-a1,b2-a1], \ + [a1,a1-b1+1,a1-b2+1], [], 1/z + return T1, T2 + v = ctx.hypercomb(h, [a1,b1,b2], force_series=True, maxterms=4*ctx.prec) + if sum(ctx._is_real_type(u) for u in [a1,b1,b2,z]) == 4: + v = ctx.re(v) + return v + except ctx.NoConvergence: + pass + finally: + ctx.prec = orig + + #print "not using asymp" + return ctx.hypsum(1, 2, (a1type, b1type, b2type), [a1, b1, b2], z, **kwargs) + + + +@defun +def _hyp2f3(ctx, a_s, b_s, z, **kwargs): + (a1, a1type), (a2, a2type) = a_s + (b1, b1type), (b2, b2type), (b3, b3type) = b_s + + absz = abs(z) + magz = ctx.mag(z) + + # Asymptotic expansion is ~ exp(sqrt(z)) + asymp_extraprec = z and magz//2 + orig = ctx.prec + + # Asymptotic series is in terms of 4F1 + # The square root below empirically provides a plausible criterion + # for the leading series to converge + can_use_asymptotic = (not kwargs.get('force_series')) and \ + (ctx.mag(absz) > 19) and (ctx.sqrt(absz) > 1.5*orig) + + if can_use_asymptotic: + #print "using asymp" + try: + try: + ctx.prec += asymp_extraprec + # http://functions.wolfram.com/HypergeometricFunctions/ + # Hypergeometric2F3/06/02/03/01/0002/ + def h(a1,a2,b1,b2,b3): + X = ctx.mpq_1_2*(a1+a2-b1-b2-b3+ctx.mpq_1_2) + A2 = a1+a2 + B3 = b1+b2+b3 + A = a1*a2 + B = b1*b2+b3*b2+b1*b3 + R = b1*b2*b3 + c = {} + c[0] = ctx.one + c[1] = 2*(B - A + ctx.mpq_1_4*(3*A2+B3-2)*(A2-B3) - ctx.mpq_3_16) + c[2] = ctx.mpq_1_2*c[1]**2 + ctx.mpq_1_16*(-16*(2*A2-3)*(B-A) + 32*R +\ + 4*(-8*A2**2 + 11*A2 + 8*A + B3 - 2)*(A2-B3)-3) + s1 = 0 + s2 = 0 + k = 0 + tprev = 0 + while 1: + if k not in c: + uu1 = (k-2*X-3)*(k-2*X-2*b1-1)*(k-2*X-2*b2-1)*\ + (k-2*X-2*b3-1) + uu2 = (4*(k-1)**3 - 6*(4*X+B3)*(k-1)**2 + \ + 2*(24*X**2+12*B3*X+4*B+B3-1)*(k-1) - 32*X**3 - \ + 24*B3*X**2 - 4*B - 8*R - 4*(4*B+B3-1)*X + 2*B3-1) + uu3 = (5*(k-1)**2+2*(-10*X+A2-3*B3+3)*(k-1)+2*c[1]) + c[k] = ctx.one/(2*k)*(uu1*c[k-3]-uu2*c[k-2]+uu3*c[k-1]) + w = c[k] * ctx.power(-z, -0.5*k) + t1 = (-ctx.j)**k * ctx.mpf(2)**(-k) * w + t2 = ctx.j**k * ctx.mpf(2)**(-k) * w + if abs(t1) < 0.1*ctx.eps: + break + # Quit if the series doesn't converge quickly enough + if k > 5 and abs(tprev) / abs(t1) < 1.5: + raise ctx.NoConvergence + s1 += t1 + s2 += t2 + tprev = t1 + k += 1 + S = ctx.expj(ctx.pi*X+2*ctx.sqrt(-z))*s1 + \ + ctx.expj(-(ctx.pi*X+2*ctx.sqrt(-z)))*s2 + T1 = [0.5*S, ctx.pi, -z], [1, -0.5, X], [b1, b2, b3], [a1, a2],\ + [], [], 0 + T2 = [-z], [-a1], [b1,b2,b3,a2-a1],[a2,b1-a1,b2-a1,b3-a1], \ + [a1,a1-b1+1,a1-b2+1,a1-b3+1], [a1-a2+1], 1/z + T3 = [-z], [-a2], [b1,b2,b3,a1-a2],[a1,b1-a2,b2-a2,b3-a2], \ + [a2,a2-b1+1,a2-b2+1,a2-b3+1],[-a1+a2+1], 1/z + return T1, T2, T3 + v = ctx.hypercomb(h, [a1,a2,b1,b2,b3], force_series=True, maxterms=4*ctx.prec) + if sum(ctx._is_real_type(u) for u in [a1,a2,b1,b2,b3,z]) == 6: + v = ctx.re(v) + return v + except ctx.NoConvergence: + pass + finally: + ctx.prec = orig + + return ctx.hypsum(2, 3, (a1type, a2type, b1type, b2type, b3type), [a1, a2, b1, b2, b3], z, **kwargs) + +@defun +def _hyp2f0(ctx, a_s, b_s, z, **kwargs): + (a, atype), (b, btype) = a_s + # We want to try aggressively to use the asymptotic expansion, + # and fall back only when absolutely necessary + try: + kwargsb = kwargs.copy() + kwargsb['maxterms'] = kwargsb.get('maxterms', ctx.prec) + return ctx.hypsum(2, 0, (atype,btype), [a,b], z, **kwargsb) + except ctx.NoConvergence: + if kwargs.get('force_series'): + raise + pass + def h(a, b): + w = ctx.sinpi(b) + rz = -1/z + T1 = ([ctx.pi,w,rz],[1,-1,a],[],[a-b+1,b],[a],[b],rz) + T2 = ([-ctx.pi,w,rz],[1,-1,1+a-b],[],[a,2-b],[a-b+1],[2-b],rz) + return T1, T2 + return ctx.hypercomb(h, [a, 1+a-b], **kwargs) + +@defun +def meijerg(ctx, a_s, b_s, z, r=1, series=None, **kwargs): + an, ap = a_s + bm, bq = b_s + n = len(an) + p = n + len(ap) + m = len(bm) + q = m + len(bq) + a = an+ap + b = bm+bq + a = [ctx.convert(_) for _ in a] + b = [ctx.convert(_) for _ in b] + z = ctx.convert(z) + if series is None: + if p < q: series = 1 + if p > q: series = 2 + if p == q: + if m+n == p and abs(z) > 1: + series = 2 + else: + series = 1 + if kwargs.get('verbose'): + print("Meijer G m,n,p,q,series =", m,n,p,q,series) + if series == 1: + def h(*args): + a = args[:p] + b = args[p:] + terms = [] + for k in range(m): + bases = [z] + expts = [b[k]/r] + gn = [b[j]-b[k] for j in range(m) if j != k] + gn += [1-a[j]+b[k] for j in range(n)] + gd = [a[j]-b[k] for j in range(n,p)] + gd += [1-b[j]+b[k] for j in range(m,q)] + hn = [1-a[j]+b[k] for j in range(p)] + hd = [1-b[j]+b[k] for j in range(q) if j != k] + hz = (-ctx.one)**(p-m-n) * z**(ctx.one/r) + terms.append((bases, expts, gn, gd, hn, hd, hz)) + return terms + else: + def h(*args): + a = args[:p] + b = args[p:] + terms = [] + for k in range(n): + bases = [z] + if r == 1: + expts = [a[k]-1] + else: + expts = [(a[k]-1)/ctx.convert(r)] + gn = [a[k]-a[j] for j in range(n) if j != k] + gn += [1-a[k]+b[j] for j in range(m)] + gd = [a[k]-b[j] for j in range(m,q)] + gd += [1-a[k]+a[j] for j in range(n,p)] + hn = [1-a[k]+b[j] for j in range(q)] + hd = [1+a[j]-a[k] for j in range(p) if j != k] + hz = (-ctx.one)**(q-m-n) / z**(ctx.one/r) + terms.append((bases, expts, gn, gd, hn, hd, hz)) + return terms + return ctx.hypercomb(h, a+b, **kwargs) + +@defun_wrapped +def appellf1(ctx,a,b1,b2,c,x,y,**kwargs): + # Assume x smaller + # We will use x for the outer loop + if abs(x) > abs(y): + x, y = y, x + b1, b2 = b2, b1 + def ok(x): + return abs(x) < 0.99 + # Finite cases + if ctx.isnpint(a): + pass + elif ctx.isnpint(b1): + pass + elif ctx.isnpint(b2): + x, y, b1, b2 = y, x, b2, b1 + else: + #print x, y + # Note: ok if |y| > 1, because + # 2F1 implements analytic continuation + if not ok(x): + u1 = (x-y)/(x-1) + if not ok(u1): + raise ValueError("Analytic continuation not implemented") + #print "Using analytic continuation" + return (1-x)**(-b1)*(1-y)**(c-a-b2)*\ + ctx.appellf1(c-a,b1,c-b1-b2,c,u1,y,**kwargs) + return ctx.hyper2d({'m+n':[a],'m':[b1],'n':[b2]}, {'m+n':[c]}, x,y, **kwargs) + +@defun +def appellf2(ctx,a,b1,b2,c1,c2,x,y,**kwargs): + # TODO: continuation + return ctx.hyper2d({'m+n':[a],'m':[b1],'n':[b2]}, + {'m':[c1],'n':[c2]}, x,y, **kwargs) + +@defun +def appellf3(ctx,a1,a2,b1,b2,c,x,y,**kwargs): + outer_polynomial = ctx.isnpint(a1) or ctx.isnpint(b1) + inner_polynomial = ctx.isnpint(a2) or ctx.isnpint(b2) + if not outer_polynomial: + if inner_polynomial or abs(x) > abs(y): + x, y = y, x + a1,a2,b1,b2 = a2,a1,b2,b1 + return ctx.hyper2d({'m':[a1,b1],'n':[a2,b2]}, {'m+n':[c]},x,y,**kwargs) + +@defun +def appellf4(ctx,a,b,c1,c2,x,y,**kwargs): + # TODO: continuation + return ctx.hyper2d({'m+n':[a,b]}, {'m':[c1],'n':[c2]},x,y,**kwargs) + +@defun +def hyper2d(ctx, a, b, x, y, **kwargs): + r""" + Sums the generalized 2D hypergeometric series + + .. math :: + + \sum_{m=0}^{\infty} \sum_{n=0}^{\infty} + \frac{P((a),m,n)}{Q((b),m,n)} + \frac{x^m y^n} {m! n!} + + where `(a) = (a_1,\ldots,a_r)`, `(b) = (b_1,\ldots,b_s)` and where + `P` and `Q` are products of rising factorials such as `(a_j)_n` or + `(a_j)_{m+n}`. `P` and `Q` are specified in the form of dicts, with + the `m` and `n` dependence as keys and parameter lists as values. + The supported rising factorials are given in the following table + (note that only a few are supported in `Q`): + + +------------+-------------------+--------+ + | Key | Rising factorial | `Q` | + +============+===================+========+ + | ``'m'`` | `(a_j)_m` | Yes | + +------------+-------------------+--------+ + | ``'n'`` | `(a_j)_n` | Yes | + +------------+-------------------+--------+ + | ``'m+n'`` | `(a_j)_{m+n}` | Yes | + +------------+-------------------+--------+ + | ``'m-n'`` | `(a_j)_{m-n}` | No | + +------------+-------------------+--------+ + | ``'n-m'`` | `(a_j)_{n-m}` | No | + +------------+-------------------+--------+ + | ``'2m+n'`` | `(a_j)_{2m+n}` | No | + +------------+-------------------+--------+ + | ``'2m-n'`` | `(a_j)_{2m-n}` | No | + +------------+-------------------+--------+ + | ``'2n-m'`` | `(a_j)_{2n-m}` | No | + +------------+-------------------+--------+ + + For example, the Appell F1 and F4 functions + + .. math :: + + F_1 = \sum_{m=0}^{\infty} \sum_{n=0}^{\infty} + \frac{(a)_{m+n} (b)_m (c)_n}{(d)_{m+n}} + \frac{x^m y^n}{m! n!} + + F_4 = \sum_{m=0}^{\infty} \sum_{n=0}^{\infty} + \frac{(a)_{m+n} (b)_{m+n}}{(c)_m (d)_{n}} + \frac{x^m y^n}{m! n!} + + can be represented respectively as + + ``hyper2d({'m+n':[a], 'm':[b], 'n':[c]}, {'m+n':[d]}, x, y)`` + + ``hyper2d({'m+n':[a,b]}, {'m':[c], 'n':[d]}, x, y)`` + + More generally, :func:`~mpmath.hyper2d` can evaluate any of the 34 distinct + convergent second-order (generalized Gaussian) hypergeometric + series enumerated by Horn, as well as the Kampe de Feriet + function. + + The series is computed by rewriting it so that the inner + series (i.e. the series containing `n` and `y`) has the form of an + ordinary generalized hypergeometric series and thereby can be + evaluated efficiently using :func:`~mpmath.hyper`. If possible, + manually swapping `x` and `y` and the corresponding parameters + can sometimes give better results. + + **Examples** + + Two separable cases: a product of two geometric series, and a + product of two Gaussian hypergeometric functions:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> x, y = mpf(0.25), mpf(0.5) + >>> hyper2d({'m':1,'n':1}, {}, x,y) + 2.666666666666666666666667 + >>> 1/(1-x)/(1-y) + 2.666666666666666666666667 + >>> hyper2d({'m':[1,2],'n':[3,4]}, {'m':[5],'n':[6]}, x,y) + 4.164358531238938319669856 + >>> hyp2f1(1,2,5,x)*hyp2f1(3,4,6,y) + 4.164358531238938319669856 + + Some more series that can be done in closed form:: + + >>> hyper2d({'m':1,'n':1},{'m+n':1},x,y) + 2.013417124712514809623881 + >>> (exp(x)*x-exp(y)*y)/(x-y) + 2.013417124712514809623881 + + Six of the 34 Horn functions, G1-G3 and H1-H3:: + + >>> from mpmath import * + >>> mp.dps = 10; mp.pretty = True + >>> x, y = 0.0625, 0.125 + >>> a1,a2,b1,b2,c1,c2,d = 1.1,-1.2,-1.3,-1.4,1.5,-1.6,1.7 + >>> hyper2d({'m+n':a1,'n-m':b1,'m-n':b2},{},x,y) # G1 + 1.139090746 + >>> nsum(lambda m,n: rf(a1,m+n)*rf(b1,n-m)*rf(b2,m-n)*\ + ... x**m*y**n/fac(m)/fac(n), [0,inf], [0,inf]) + 1.139090746 + >>> hyper2d({'m':a1,'n':a2,'n-m':b1,'m-n':b2},{},x,y) # G2 + 0.9503682696 + >>> nsum(lambda m,n: rf(a1,m)*rf(a2,n)*rf(b1,n-m)*rf(b2,m-n)*\ + ... x**m*y**n/fac(m)/fac(n), [0,inf], [0,inf]) + 0.9503682696 + >>> hyper2d({'2n-m':a1,'2m-n':a2},{},x,y) # G3 + 1.029372029 + >>> nsum(lambda m,n: rf(a1,2*n-m)*rf(a2,2*m-n)*\ + ... x**m*y**n/fac(m)/fac(n), [0,inf], [0,inf]) + 1.029372029 + >>> hyper2d({'m-n':a1,'m+n':b1,'n':c1},{'m':d},x,y) # H1 + -1.605331256 + >>> nsum(lambda m,n: rf(a1,m-n)*rf(b1,m+n)*rf(c1,n)/rf(d,m)*\ + ... x**m*y**n/fac(m)/fac(n), [0,inf], [0,inf]) + -1.605331256 + >>> hyper2d({'m-n':a1,'m':b1,'n':[c1,c2]},{'m':d},x,y) # H2 + -2.35405404 + >>> nsum(lambda m,n: rf(a1,m-n)*rf(b1,m)*rf(c1,n)*rf(c2,n)/rf(d,m)*\ + ... x**m*y**n/fac(m)/fac(n), [0,inf], [0,inf]) + -2.35405404 + >>> hyper2d({'2m+n':a1,'n':b1},{'m+n':c1},x,y) # H3 + 0.974479074 + >>> nsum(lambda m,n: rf(a1,2*m+n)*rf(b1,n)/rf(c1,m+n)*\ + ... x**m*y**n/fac(m)/fac(n), [0,inf], [0,inf]) + 0.974479074 + + **References** + + 1. [SrivastavaKarlsson]_ + 2. [Weisstein]_ http://mathworld.wolfram.com/HornFunction.html + 3. [Weisstein]_ http://mathworld.wolfram.com/AppellHypergeometricFunction.html + + """ + x = ctx.convert(x) + y = ctx.convert(y) + def parse(dct, key): + args = dct.pop(key, []) + try: + args = list(args) + except TypeError: + args = [args] + return [ctx.convert(arg) for arg in args] + a_s = dict(a) + b_s = dict(b) + a_m = parse(a, 'm') + a_n = parse(a, 'n') + a_m_add_n = parse(a, 'm+n') + a_m_sub_n = parse(a, 'm-n') + a_n_sub_m = parse(a, 'n-m') + a_2m_add_n = parse(a, '2m+n') + a_2m_sub_n = parse(a, '2m-n') + a_2n_sub_m = parse(a, '2n-m') + b_m = parse(b, 'm') + b_n = parse(b, 'n') + b_m_add_n = parse(b, 'm+n') + if a: raise ValueError("unsupported key: %r" % a.keys()[0]) + if b: raise ValueError("unsupported key: %r" % b.keys()[0]) + s = 0 + outer = ctx.one + m = ctx.mpf(0) + ok_count = 0 + prec = ctx.prec + maxterms = kwargs.get('maxterms', 20*prec) + try: + ctx.prec += 10 + tol = +ctx.eps + while 1: + inner_sign = 1 + outer_sign = 1 + inner_a = list(a_n) + inner_b = list(b_n) + outer_a = [a+m for a in a_m] + outer_b = [b+m for b in b_m] + # (a)_{m+n} = (a)_m (a+m)_n + for a in a_m_add_n: + a = a+m + inner_a.append(a) + outer_a.append(a) + # (b)_{m+n} = (b)_m (b+m)_n + for b in b_m_add_n: + b = b+m + inner_b.append(b) + outer_b.append(b) + # (a)_{n-m} = (a-m)_n / (a-m)_m + for a in a_n_sub_m: + inner_a.append(a-m) + outer_b.append(a-m-1) + # (a)_{m-n} = (-1)^(m+n) (1-a-m)_m / (1-a-m)_n + for a in a_m_sub_n: + inner_sign *= (-1) + outer_sign *= (-1)**(m) + inner_b.append(1-a-m) + outer_a.append(-a-m) + # (a)_{2m+n} = (a)_{2m} (a+2m)_n + for a in a_2m_add_n: + inner_a.append(a+2*m) + outer_a.append((a+2*m)*(1+a+2*m)) + # (a)_{2m-n} = (-1)^(2m+n) (1-a-2m)_{2m} / (1-a-2m)_n + for a in a_2m_sub_n: + inner_sign *= (-1) + inner_b.append(1-a-2*m) + outer_a.append((a+2*m)*(1+a+2*m)) + # (a)_{2n-m} = 4^n ((a-m)/2)_n ((a-m+1)/2)_n / (a-m)_m + for a in a_2n_sub_m: + inner_sign *= 4 + inner_a.append(0.5*(a-m)) + inner_a.append(0.5*(a-m+1)) + outer_b.append(a-m-1) + inner = ctx.hyper(inner_a, inner_b, inner_sign*y, + zeroprec=ctx.prec, **kwargs) + term = outer * inner * outer_sign + if abs(term) < tol: + ok_count += 1 + else: + ok_count = 0 + if ok_count >= 3 or not outer: + break + s += term + for a in outer_a: outer *= a + for b in outer_b: outer /= b + m += 1 + outer = outer * x / m + if m > maxterms: + raise ctx.NoConvergence("maxterms exceeded in hyper2d") + finally: + ctx.prec = prec + return +s + +""" +@defun +def kampe_de_feriet(ctx,a,b,c,d,e,f,x,y,**kwargs): + return ctx.hyper2d({'m+n':a,'m':b,'n':c}, + {'m+n':d,'m':e,'n':f}, x,y, **kwargs) +""" + +@defun +def bihyper(ctx, a_s, b_s, z, **kwargs): + r""" + Evaluates the bilateral hypergeometric series + + .. math :: + + \,_AH_B(a_1, \ldots, a_k; b_1, \ldots, b_B; z) = + \sum_{n=-\infty}^{\infty} + \frac{(a_1)_n \ldots (a_A)_n} + {(b_1)_n \ldots (b_B)_n} \, z^n + + where, for direct convergence, `A = B` and `|z| = 1`, although a + regularized sum exists more generally by considering the + bilateral series as a sum of two ordinary hypergeometric + functions. In order for the series to make sense, none of the + parameters may be integers. + + **Examples** + + The value of `\,_2H_2` at `z = 1` is given by Dougall's formula:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> a,b,c,d = 0.5, 1.5, 2.25, 3.25 + >>> bihyper([a,b],[c,d],1) + -14.49118026212345786148847 + >>> gammaprod([c,d,1-a,1-b,c+d-a-b-1],[c-a,d-a,c-b,d-b]) + -14.49118026212345786148847 + + The regularized function `\,_1H_0` can be expressed as the + sum of one `\,_2F_0` function and one `\,_1F_1` function:: + + >>> a = mpf(0.25) + >>> z = mpf(0.75) + >>> bihyper([a], [], z) + (0.2454393389657273841385582 + 0.2454393389657273841385582j) + >>> hyper([a,1],[],z) + (hyper([1],[1-a],-1/z)-1) + (0.2454393389657273841385582 + 0.2454393389657273841385582j) + >>> hyper([a,1],[],z) + hyper([1],[2-a],-1/z)/z/(a-1) + (0.2454393389657273841385582 + 0.2454393389657273841385582j) + + **References** + + 1. [Slater]_ (chapter 6: "Bilateral Series", pp. 180-189) + 2. [Wikipedia]_ http://en.wikipedia.org/wiki/Bilateral_hypergeometric_series + + """ + z = ctx.convert(z) + c_s = a_s + b_s + p = len(a_s) + q = len(b_s) + if (p, q) == (0,0) or (p, q) == (1,1): + return ctx.zero * z + neg = (p-q) % 2 + def h(*c_s): + a_s = list(c_s[:p]) + b_s = list(c_s[p:]) + aa_s = [2-b for b in b_s] + bb_s = [2-a for a in a_s] + rp = [(-1)**neg * z] + [1-b for b in b_s] + [1-a for a in a_s] + rc = [-1] + [1]*len(b_s) + [-1]*len(a_s) + T1 = [], [], [], [], a_s + [1], b_s, z + T2 = rp, rc, [], [], aa_s + [1], bb_s, (-1)**neg / z + return T1, T2 + return ctx.hypercomb(h, c_s, **kwargs) diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/orthogonal.py b/venv/lib/python3.10/site-packages/mpmath/functions/orthogonal.py new file mode 100644 index 0000000000000000000000000000000000000000..aa33d8bd78290f55a970e78dab7a317d5f652dee --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/functions/orthogonal.py @@ -0,0 +1,493 @@ +from .functions import defun, defun_wrapped + +def _hermite_param(ctx, n, z, parabolic_cylinder): + """ + Combined calculation of the Hermite polynomial H_n(z) (and its + generalization to complex n) and the parabolic cylinder + function D. + """ + n, ntyp = ctx._convert_param(n) + z = ctx.convert(z) + q = -ctx.mpq_1_2 + # For re(z) > 0, 2F0 -- http://functions.wolfram.com/ + # HypergeometricFunctions/HermiteHGeneral/06/02/0009/ + # Otherwise, there is a reflection formula + # 2F0 + http://functions.wolfram.com/HypergeometricFunctions/ + # HermiteHGeneral/16/01/01/0006/ + # + # TODO: + # An alternative would be to use + # http://functions.wolfram.com/HypergeometricFunctions/ + # HermiteHGeneral/06/02/0006/ + # + # Also, the 1F1 expansion + # http://functions.wolfram.com/HypergeometricFunctions/ + # HermiteHGeneral/26/01/02/0001/ + # should probably be used for tiny z + if not z: + T1 = [2, ctx.pi], [n, 0.5], [], [q*(n-1)], [], [], 0 + if parabolic_cylinder: + T1[1][0] += q*n + return T1, + can_use_2f0 = ctx.isnpint(-n) or ctx.re(z) > 0 or \ + (ctx.re(z) == 0 and ctx.im(z) > 0) + expprec = ctx.prec*4 + 20 + if parabolic_cylinder: + u = ctx.fmul(ctx.fmul(z,z,prec=expprec), -0.25, exact=True) + w = ctx.fmul(z, ctx.sqrt(0.5,prec=expprec), prec=expprec) + else: + w = z + w2 = ctx.fmul(w, w, prec=expprec) + rw2 = ctx.fdiv(1, w2, prec=expprec) + nrw2 = ctx.fneg(rw2, exact=True) + nw = ctx.fneg(w, exact=True) + if can_use_2f0: + T1 = [2, w], [n, n], [], [], [q*n, q*(n-1)], [], nrw2 + terms = [T1] + else: + T1 = [2, nw], [n, n], [], [], [q*n, q*(n-1)], [], nrw2 + T2 = [2, ctx.pi, nw], [n+2, 0.5, 1], [], [q*n], [q*(n-1)], [1-q], w2 + terms = [T1,T2] + # Multiply by prefactor for D_n + if parabolic_cylinder: + expu = ctx.exp(u) + for i in range(len(terms)): + terms[i][1][0] += q*n + terms[i][0].append(expu) + terms[i][1].append(1) + return tuple(terms) + +@defun +def hermite(ctx, n, z, **kwargs): + return ctx.hypercomb(lambda: _hermite_param(ctx, n, z, 0), [], **kwargs) + +@defun +def pcfd(ctx, n, z, **kwargs): + r""" + Gives the parabolic cylinder function in Whittaker's notation + `D_n(z) = U(-n-1/2, z)` (see :func:`~mpmath.pcfu`). + It solves the differential equation + + .. math :: + + y'' + \left(n + \frac{1}{2} - \frac{1}{4} z^2\right) y = 0. + + and can be represented in terms of Hermite polynomials + (see :func:`~mpmath.hermite`) as + + .. math :: + + D_n(z) = 2^{-n/2} e^{-z^2/4} H_n\left(\frac{z}{\sqrt{2}}\right). + + **Plots** + + .. literalinclude :: /plots/pcfd.py + .. image :: /plots/pcfd.png + + **Examples** + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> pcfd(0,0); pcfd(1,0); pcfd(2,0); pcfd(3,0) + 1.0 + 0.0 + -1.0 + 0.0 + >>> pcfd(4,0); pcfd(-3,0) + 3.0 + 0.6266570686577501256039413 + >>> pcfd('1/2', 2+3j) + (-5.363331161232920734849056 - 3.858877821790010714163487j) + >>> pcfd(2, -10) + 1.374906442631438038871515e-9 + + Verifying the differential equation:: + + >>> n = mpf(2.5) + >>> y = lambda z: pcfd(n,z) + >>> z = 1.75 + >>> chop(diff(y,z,2) + (n+0.5-0.25*z**2)*y(z)) + 0.0 + + Rational Taylor series expansion when `n` is an integer:: + + >>> taylor(lambda z: pcfd(5,z), 0, 7) + [0.0, 15.0, 0.0, -13.75, 0.0, 3.96875, 0.0, -0.6015625] + + """ + return ctx.hypercomb(lambda: _hermite_param(ctx, n, z, 1), [], **kwargs) + +@defun +def pcfu(ctx, a, z, **kwargs): + r""" + Gives the parabolic cylinder function `U(a,z)`, which may be + defined for `\Re(z) > 0` in terms of the confluent + U-function (see :func:`~mpmath.hyperu`) by + + .. math :: + + U(a,z) = 2^{-\frac{1}{4}-\frac{a}{2}} e^{-\frac{1}{4} z^2} + U\left(\frac{a}{2}+\frac{1}{4}, + \frac{1}{2}, \frac{1}{2}z^2\right) + + or, for arbitrary `z`, + + .. math :: + + e^{-\frac{1}{4}z^2} U(a,z) = + U(a,0) \,_1F_1\left(-\tfrac{a}{2}+\tfrac{1}{4}; + \tfrac{1}{2}; -\tfrac{1}{2}z^2\right) + + U'(a,0) z \,_1F_1\left(-\tfrac{a}{2}+\tfrac{3}{4}; + \tfrac{3}{2}; -\tfrac{1}{2}z^2\right). + + **Examples** + + Connection to other functions:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> z = mpf(3) + >>> pcfu(0.5,z) + 0.03210358129311151450551963 + >>> sqrt(pi/2)*exp(z**2/4)*erfc(z/sqrt(2)) + 0.03210358129311151450551963 + >>> pcfu(0.5,-z) + 23.75012332835297233711255 + >>> sqrt(pi/2)*exp(z**2/4)*erfc(-z/sqrt(2)) + 23.75012332835297233711255 + >>> pcfu(0.5,-z) + 23.75012332835297233711255 + >>> sqrt(pi/2)*exp(z**2/4)*erfc(-z/sqrt(2)) + 23.75012332835297233711255 + + """ + n, _ = ctx._convert_param(a) + return ctx.pcfd(-n-ctx.mpq_1_2, z) + +@defun +def pcfv(ctx, a, z, **kwargs): + r""" + Gives the parabolic cylinder function `V(a,z)`, which can be + represented in terms of :func:`~mpmath.pcfu` as + + .. math :: + + V(a,z) = \frac{\Gamma(a+\tfrac{1}{2}) (U(a,-z)-\sin(\pi a) U(a,z)}{\pi}. + + **Examples** + + Wronskian relation between `U` and `V`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> a, z = 2, 3 + >>> pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z) + 0.7978845608028653558798921 + >>> sqrt(2/pi) + 0.7978845608028653558798921 + >>> a, z = 2.5, 3 + >>> pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z) + 0.7978845608028653558798921 + >>> a, z = 0.25, -1 + >>> pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z) + 0.7978845608028653558798921 + >>> a, z = 2+1j, 2+3j + >>> chop(pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z)) + 0.7978845608028653558798921 + + """ + n, ntype = ctx._convert_param(a) + z = ctx.convert(z) + q = ctx.mpq_1_2 + r = ctx.mpq_1_4 + if ntype == 'Q' and ctx.isint(n*2): + # Faster for half-integers + def h(): + jz = ctx.fmul(z, -1j, exact=True) + T1terms = _hermite_param(ctx, -n-q, z, 1) + T2terms = _hermite_param(ctx, n-q, jz, 1) + for T in T1terms: + T[0].append(1j) + T[1].append(1) + T[3].append(q-n) + u = ctx.expjpi((q*n-r)) * ctx.sqrt(2/ctx.pi) + for T in T2terms: + T[0].append(u) + T[1].append(1) + return T1terms + T2terms + v = ctx.hypercomb(h, [], **kwargs) + if ctx._is_real_type(n) and ctx._is_real_type(z): + v = ctx._re(v) + return v + else: + def h(n): + w = ctx.square_exp_arg(z, -0.25) + u = ctx.square_exp_arg(z, 0.5) + e = ctx.exp(w) + l = [ctx.pi, q, ctx.exp(w)] + Y1 = l, [-q, n*q+r, 1], [r-q*n], [], [q*n+r], [q], u + Y2 = l + [z], [-q, n*q-r, 1, 1], [1-r-q*n], [], [q*n+1-r], [1+q], u + c, s = ctx.cospi_sinpi(r+q*n) + Y1[0].append(s) + Y2[0].append(c) + for Y in (Y1, Y2): + Y[1].append(1) + Y[3].append(q-n) + return Y1, Y2 + return ctx.hypercomb(h, [n], **kwargs) + + +@defun +def pcfw(ctx, a, z, **kwargs): + r""" + Gives the parabolic cylinder function `W(a,z)` defined in (DLMF 12.14). + + **Examples** + + Value at the origin:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> a = mpf(0.25) + >>> pcfw(a,0) + 0.9722833245718180765617104 + >>> power(2,-0.75)*sqrt(abs(gamma(0.25+0.5j*a)/gamma(0.75+0.5j*a))) + 0.9722833245718180765617104 + >>> diff(pcfw,(a,0),(0,1)) + -0.5142533944210078966003624 + >>> -power(2,-0.25)*sqrt(abs(gamma(0.75+0.5j*a)/gamma(0.25+0.5j*a))) + -0.5142533944210078966003624 + + """ + n, _ = ctx._convert_param(a) + z = ctx.convert(z) + def terms(): + phi2 = ctx.arg(ctx.gamma(0.5 + ctx.j*n)) + phi2 = (ctx.loggamma(0.5+ctx.j*n) - ctx.loggamma(0.5-ctx.j*n))/2j + rho = ctx.pi/8 + 0.5*phi2 + # XXX: cancellation computing k + k = ctx.sqrt(1 + ctx.exp(2*ctx.pi*n)) - ctx.exp(ctx.pi*n) + C = ctx.sqrt(k/2) * ctx.exp(0.25*ctx.pi*n) + yield C * ctx.expj(rho) * ctx.pcfu(ctx.j*n, z*ctx.expjpi(-0.25)) + yield C * ctx.expj(-rho) * ctx.pcfu(-ctx.j*n, z*ctx.expjpi(0.25)) + v = ctx.sum_accurately(terms) + if ctx._is_real_type(n) and ctx._is_real_type(z): + v = ctx._re(v) + return v + +""" +Even/odd PCFs. Useful? + +@defun +def pcfy1(ctx, a, z, **kwargs): + a, _ = ctx._convert_param(n) + z = ctx.convert(z) + def h(): + w = ctx.square_exp_arg(z) + w1 = ctx.fmul(w, -0.25, exact=True) + w2 = ctx.fmul(w, 0.5, exact=True) + e = ctx.exp(w1) + return [e], [1], [], [], [ctx.mpq_1_2*a+ctx.mpq_1_4], [ctx.mpq_1_2], w2 + return ctx.hypercomb(h, [], **kwargs) + +@defun +def pcfy2(ctx, a, z, **kwargs): + a, _ = ctx._convert_param(n) + z = ctx.convert(z) + def h(): + w = ctx.square_exp_arg(z) + w1 = ctx.fmul(w, -0.25, exact=True) + w2 = ctx.fmul(w, 0.5, exact=True) + e = ctx.exp(w1) + return [e, z], [1, 1], [], [], [ctx.mpq_1_2*a+ctx.mpq_3_4], \ + [ctx.mpq_3_2], w2 + return ctx.hypercomb(h, [], **kwargs) +""" + +@defun_wrapped +def gegenbauer(ctx, n, a, z, **kwargs): + # Special cases: a+0.5, a*2 poles + if ctx.isnpint(a): + return 0*(z+n) + if ctx.isnpint(a+0.5): + # TODO: something else is required here + # E.g.: gegenbauer(-2, -0.5, 3) == -12 + if ctx.isnpint(n+1): + raise NotImplementedError("Gegenbauer function with two limits") + def h(a): + a2 = 2*a + T = [], [], [n+a2], [n+1, a2], [-n, n+a2], [a+0.5], 0.5*(1-z) + return [T] + return ctx.hypercomb(h, [a], **kwargs) + def h(n): + a2 = 2*a + T = [], [], [n+a2], [n+1, a2], [-n, n+a2], [a+0.5], 0.5*(1-z) + return [T] + return ctx.hypercomb(h, [n], **kwargs) + +@defun_wrapped +def jacobi(ctx, n, a, b, x, **kwargs): + if not ctx.isnpint(a): + def h(n): + return (([], [], [a+n+1], [n+1, a+1], [-n, a+b+n+1], [a+1], (1-x)*0.5),) + return ctx.hypercomb(h, [n], **kwargs) + if not ctx.isint(b): + def h(n, a): + return (([], [], [-b], [n+1, -b-n], [-n, a+b+n+1], [b+1], (x+1)*0.5),) + return ctx.hypercomb(h, [n, a], **kwargs) + # XXX: determine appropriate limit + return ctx.binomial(n+a,n) * ctx.hyp2f1(-n,1+n+a+b,a+1,(1-x)/2, **kwargs) + +@defun_wrapped +def laguerre(ctx, n, a, z, **kwargs): + # XXX: limits, poles + #if ctx.isnpint(n): + # return 0*(a+z) + def h(a): + return (([], [], [a+n+1], [a+1, n+1], [-n], [a+1], z),) + return ctx.hypercomb(h, [a], **kwargs) + +@defun_wrapped +def legendre(ctx, n, x, **kwargs): + if ctx.isint(n): + n = int(n) + # Accuracy near zeros + if (n + (n < 0)) & 1: + if not x: + return x + mag = ctx.mag(x) + if mag < -2*ctx.prec-10: + return x + if mag < -5: + ctx.prec += -mag + return ctx.hyp2f1(-n,n+1,1,(1-x)/2, **kwargs) + +@defun +def legenp(ctx, n, m, z, type=2, **kwargs): + # Legendre function, 1st kind + n = ctx.convert(n) + m = ctx.convert(m) + # Faster + if not m: + return ctx.legendre(n, z, **kwargs) + # TODO: correct evaluation at singularities + if type == 2: + def h(n,m): + g = m*0.5 + T = [1+z, 1-z], [g, -g], [], [1-m], [-n, n+1], [1-m], 0.5*(1-z) + return (T,) + return ctx.hypercomb(h, [n,m], **kwargs) + if type == 3: + def h(n,m): + g = m*0.5 + T = [z+1, z-1], [g, -g], [], [1-m], [-n, n+1], [1-m], 0.5*(1-z) + return (T,) + return ctx.hypercomb(h, [n,m], **kwargs) + raise ValueError("requires type=2 or type=3") + +@defun +def legenq(ctx, n, m, z, type=2, **kwargs): + # Legendre function, 2nd kind + n = ctx.convert(n) + m = ctx.convert(m) + z = ctx.convert(z) + if z in (1, -1): + #if ctx.isint(m): + # return ctx.nan + #return ctx.inf # unsigned + return ctx.nan + if type == 2: + def h(n, m): + cos, sin = ctx.cospi_sinpi(m) + s = 2 * sin / ctx.pi + c = cos + a = 1+z + b = 1-z + u = m/2 + w = (1-z)/2 + T1 = [s, c, a, b], [-1, 1, u, -u], [], [1-m], \ + [-n, n+1], [1-m], w + T2 = [-s, a, b], [-1, -u, u], [n+m+1], [n-m+1, m+1], \ + [-n, n+1], [m+1], w + return T1, T2 + return ctx.hypercomb(h, [n, m], **kwargs) + if type == 3: + # The following is faster when there only is a single series + # Note: not valid for -1 < z < 0 (?) + if abs(z) > 1: + def h(n, m): + T1 = [ctx.expjpi(m), 2, ctx.pi, z, z-1, z+1], \ + [1, -n-1, 0.5, -n-m-1, 0.5*m, 0.5*m], \ + [n+m+1], [n+1.5], \ + [0.5*(2+n+m), 0.5*(1+n+m)], [n+1.5], z**(-2) + return [T1] + return ctx.hypercomb(h, [n, m], **kwargs) + else: + # not valid for 1 < z < inf ? + def h(n, m): + s = 2 * ctx.sinpi(m) / ctx.pi + c = ctx.expjpi(m) + a = 1+z + b = z-1 + u = m/2 + w = (1-z)/2 + T1 = [s, c, a, b], [-1, 1, u, -u], [], [1-m], \ + [-n, n+1], [1-m], w + T2 = [-s, c, a, b], [-1, 1, -u, u], [n+m+1], [n-m+1, m+1], \ + [-n, n+1], [m+1], w + return T1, T2 + return ctx.hypercomb(h, [n, m], **kwargs) + raise ValueError("requires type=2 or type=3") + +@defun_wrapped +def chebyt(ctx, n, x, **kwargs): + if (not x) and ctx.isint(n) and int(ctx._re(n)) % 2 == 1: + return x * 0 + return ctx.hyp2f1(-n,n,(1,2),(1-x)/2, **kwargs) + +@defun_wrapped +def chebyu(ctx, n, x, **kwargs): + if (not x) and ctx.isint(n) and int(ctx._re(n)) % 2 == 1: + return x * 0 + return (n+1) * ctx.hyp2f1(-n, n+2, (3,2), (1-x)/2, **kwargs) + +@defun +def spherharm(ctx, l, m, theta, phi, **kwargs): + l = ctx.convert(l) + m = ctx.convert(m) + theta = ctx.convert(theta) + phi = ctx.convert(phi) + l_isint = ctx.isint(l) + l_natural = l_isint and l >= 0 + m_isint = ctx.isint(m) + if l_isint and l < 0 and m_isint: + return ctx.spherharm(-(l+1), m, theta, phi, **kwargs) + if theta == 0 and m_isint and m < 0: + return ctx.zero * 1j + if l_natural and m_isint: + if abs(m) > l: + return ctx.zero * 1j + # http://functions.wolfram.com/Polynomials/ + # SphericalHarmonicY/26/01/02/0004/ + def h(l,m): + absm = abs(m) + C = [-1, ctx.expj(m*phi), + (2*l+1)*ctx.fac(l+absm)/ctx.pi/ctx.fac(l-absm), + ctx.sin(theta)**2, + ctx.fac(absm), 2] + P = [0.5*m*(ctx.sign(m)+1), 1, 0.5, 0.5*absm, -1, -absm-1] + return ((C, P, [], [], [absm-l, l+absm+1], [absm+1], + ctx.sin(0.5*theta)**2),) + else: + # http://functions.wolfram.com/HypergeometricFunctions/ + # SphericalHarmonicYGeneral/26/01/02/0001/ + def h(l,m): + if ctx.isnpint(l-m+1) or ctx.isnpint(l+m+1) or ctx.isnpint(1-m): + return (([0], [-1], [], [], [], [], 0),) + cos, sin = ctx.cos_sin(0.5*theta) + C = [0.5*ctx.expj(m*phi), (2*l+1)/ctx.pi, + ctx.gamma(l-m+1), ctx.gamma(l+m+1), + cos**2, sin**2] + P = [1, 0.5, 0.5, -0.5, 0.5*m, -0.5*m] + return ((C, P, [], [1-m], [-l,l+1], [1-m], sin**2),) + return ctx.hypercomb(h, [l,m], **kwargs) diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/qfunctions.py b/venv/lib/python3.10/site-packages/mpmath/functions/qfunctions.py new file mode 100644 index 0000000000000000000000000000000000000000..5a20e53a8b6fa0d8fbc9ad098614d2694998f49a --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/functions/qfunctions.py @@ -0,0 +1,280 @@ +from .functions import defun, defun_wrapped + +@defun +def qp(ctx, a, q=None, n=None, **kwargs): + r""" + Evaluates the q-Pochhammer symbol (or q-rising factorial) + + .. math :: + + (a; q)_n = \prod_{k=0}^{n-1} (1-a q^k) + + where `n = \infty` is permitted if `|q| < 1`. Called with two arguments, + ``qp(a,q)`` computes `(a;q)_{\infty}`; with a single argument, ``qp(q)`` + computes `(q;q)_{\infty}`. The special case + + .. math :: + + \phi(q) = (q; q)_{\infty} = \prod_{k=1}^{\infty} (1-q^k) = + \sum_{k=-\infty}^{\infty} (-1)^k q^{(3k^2-k)/2} + + is also known as the Euler function, or (up to a factor `q^{-1/24}`) + the Dedekind eta function. + + **Examples** + + If `n` is a positive integer, the function amounts to a finite product:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> qp(2,3,5) + -725305.0 + >>> fprod(1-2*3**k for k in range(5)) + -725305.0 + >>> qp(2,3,0) + 1.0 + + Complex arguments are allowed:: + + >>> qp(2-1j, 0.75j) + (0.4628842231660149089976379 + 4.481821753552703090628793j) + + The regular Pochhammer symbol `(a)_n` is obtained in the + following limit as `q \to 1`:: + + >>> a, n = 4, 7 + >>> limit(lambda q: qp(q**a,q,n) / (1-q)**n, 1) + 604800.0 + >>> rf(a,n) + 604800.0 + + The Taylor series of the reciprocal Euler function gives + the partition function `P(n)`, i.e. the number of ways of writing + `n` as a sum of positive integers:: + + >>> taylor(lambda q: 1/qp(q), 0, 10) + [1.0, 1.0, 2.0, 3.0, 5.0, 7.0, 11.0, 15.0, 22.0, 30.0, 42.0] + + Special values include:: + + >>> qp(0) + 1.0 + >>> findroot(diffun(qp), -0.4) # location of maximum + -0.4112484791779547734440257 + >>> qp(_) + 1.228348867038575112586878 + + The q-Pochhammer symbol is related to the Jacobi theta functions. + For example, the following identity holds:: + + >>> q = mpf(0.5) # arbitrary + >>> qp(q) + 0.2887880950866024212788997 + >>> root(3,-2)*root(q,-24)*jtheta(2,pi/6,root(q,6)) + 0.2887880950866024212788997 + + """ + a = ctx.convert(a) + if n is None: + n = ctx.inf + else: + n = ctx.convert(n) + if n < 0: + raise ValueError("n cannot be negative") + if q is None: + q = a + else: + q = ctx.convert(q) + if n == 0: + return ctx.one + 0*(a+q) + infinite = (n == ctx.inf) + same = (a == q) + if infinite: + if abs(q) >= 1: + if same and (q == -1 or q == 1): + return ctx.zero * q + raise ValueError("q-function only defined for |q| < 1") + elif q == 0: + return ctx.one - a + maxterms = kwargs.get('maxterms', 50*ctx.prec) + if infinite and same: + # Euler's pentagonal theorem + def terms(): + t = 1 + yield t + k = 1 + x1 = q + x2 = q**2 + while 1: + yield (-1)**k * x1 + yield (-1)**k * x2 + x1 *= q**(3*k+1) + x2 *= q**(3*k+2) + k += 1 + if k > maxterms: + raise ctx.NoConvergence + return ctx.sum_accurately(terms) + # return ctx.nprod(lambda k: 1-a*q**k, [0,n-1]) + def factors(): + k = 0 + r = ctx.one + while 1: + yield 1 - a*r + r *= q + k += 1 + if k >= n: + return + if k > maxterms: + raise ctx.NoConvergence + return ctx.mul_accurately(factors) + +@defun_wrapped +def qgamma(ctx, z, q, **kwargs): + r""" + Evaluates the q-gamma function + + .. math :: + + \Gamma_q(z) = \frac{(q; q)_{\infty}}{(q^z; q)_{\infty}} (1-q)^{1-z}. + + + **Examples** + + Evaluation for real and complex arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> qgamma(4,0.75) + 4.046875 + >>> qgamma(6,6) + 121226245.0 + >>> qgamma(3+4j, 0.5j) + (0.1663082382255199834630088 + 0.01952474576025952984418217j) + + The q-gamma function satisfies a functional equation similar + to that of the ordinary gamma function:: + + >>> q = mpf(0.25) + >>> z = mpf(2.5) + >>> qgamma(z+1,q) + 1.428277424823760954685912 + >>> (1-q**z)/(1-q)*qgamma(z,q) + 1.428277424823760954685912 + + """ + if abs(q) > 1: + return ctx.qgamma(z,1/q)*q**((z-2)*(z-1)*0.5) + return ctx.qp(q, q, None, **kwargs) / \ + ctx.qp(q**z, q, None, **kwargs) * (1-q)**(1-z) + +@defun_wrapped +def qfac(ctx, z, q, **kwargs): + r""" + Evaluates the q-factorial, + + .. math :: + + [n]_q! = (1+q)(1+q+q^2)\cdots(1+q+\cdots+q^{n-1}) + + or more generally + + .. math :: + + [z]_q! = \frac{(q;q)_z}{(1-q)^z}. + + **Examples** + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> qfac(0,0) + 1.0 + >>> qfac(4,3) + 2080.0 + >>> qfac(5,6) + 121226245.0 + >>> qfac(1+1j, 2+1j) + (0.4370556551322672478613695 + 0.2609739839216039203708921j) + + """ + if ctx.isint(z) and ctx._re(z) > 0: + n = int(ctx._re(z)) + return ctx.qp(q, q, n, **kwargs) / (1-q)**n + return ctx.qgamma(z+1, q, **kwargs) + +@defun +def qhyper(ctx, a_s, b_s, q, z, **kwargs): + r""" + Evaluates the basic hypergeometric series or hypergeometric q-series + + .. math :: + + \,_r\phi_s \left[\begin{matrix} + a_1 & a_2 & \ldots & a_r \\ + b_1 & b_2 & \ldots & b_s + \end{matrix} ; q,z \right] = + \sum_{n=0}^\infty + \frac{(a_1;q)_n, \ldots, (a_r;q)_n} + {(b_1;q)_n, \ldots, (b_s;q)_n} + \left((-1)^n q^{n\choose 2}\right)^{1+s-r} + \frac{z^n}{(q;q)_n} + + where `(a;q)_n` denotes the q-Pochhammer symbol (see :func:`~mpmath.qp`). + + **Examples** + + Evaluation works for real and complex arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> qhyper([0.5], [2.25], 0.25, 4) + -0.1975849091263356009534385 + >>> qhyper([0.5], [2.25], 0.25-0.25j, 4) + (2.806330244925716649839237 + 3.568997623337943121769938j) + >>> qhyper([1+j], [2,3+0.5j], 0.25, 3+4j) + (9.112885171773400017270226 - 1.272756997166375050700388j) + + Comparing with a summation of the defining series, using + :func:`~mpmath.nsum`:: + + >>> b, q, z = 3, 0.25, 0.5 + >>> qhyper([], [b], q, z) + 0.6221136748254495583228324 + >>> nsum(lambda n: z**n / qp(q,q,n)/qp(b,q,n) * q**(n*(n-1)), [0,inf]) + 0.6221136748254495583228324 + + """ + #a_s = [ctx._convert_param(a)[0] for a in a_s] + #b_s = [ctx._convert_param(b)[0] for b in b_s] + #q = ctx._convert_param(q)[0] + a_s = [ctx.convert(a) for a in a_s] + b_s = [ctx.convert(b) for b in b_s] + q = ctx.convert(q) + z = ctx.convert(z) + r = len(a_s) + s = len(b_s) + d = 1+s-r + maxterms = kwargs.get('maxterms', 50*ctx.prec) + def terms(): + t = ctx.one + yield t + qk = 1 + k = 0 + x = 1 + while 1: + for a in a_s: + p = 1 - a*qk + t *= p + for b in b_s: + p = 1 - b*qk + if not p: + raise ValueError + t /= p + t *= z + x *= (-1)**d * qk ** d + qk *= q + t /= (1 - qk) + k += 1 + yield t * x + if k > maxterms: + raise ctx.NoConvergence + return ctx.sum_accurately(terms) diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/rszeta.py b/venv/lib/python3.10/site-packages/mpmath/functions/rszeta.py new file mode 100644 index 0000000000000000000000000000000000000000..19e2c9a251b81bafe8cf77a2b0180636b1078ee4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/functions/rszeta.py @@ -0,0 +1,1403 @@ +""" +--------------------------------------------------------------------- +.. sectionauthor:: Juan Arias de Reyna + +This module implements zeta-related functions using the Riemann-Siegel +expansion: zeta_offline(s,k=0) + +* coef(J, eps): Need in the computation of Rzeta(s,k) + +* Rzeta_simul(s, der=0) computes Rzeta^(k)(s) and Rzeta^(k)(1-s) simultaneously + for 0 <= k <= der. Used by zeta_offline and z_offline + +* Rzeta_set(s, derivatives) computes Rzeta^(k)(s) for given derivatives, used by + z_half(t,k) and zeta_half + +* z_offline(w,k): Z(w) and its derivatives of order k <= 4 +* z_half(t,k): Z(t) (Riemann Siegel function) and its derivatives of order k <= 4 +* zeta_offline(s): zeta(s) and its derivatives of order k<= 4 +* zeta_half(1/2+it,k): zeta(s) and its derivatives of order k<= 4 + +* rs_zeta(s,k=0) Computes zeta^(k)(s) Unifies zeta_half and zeta_offline +* rs_z(w,k=0) Computes Z^(k)(w) Unifies z_offline and z_half +---------------------------------------------------------------------- + +This program uses Riemann-Siegel expansion even to compute +zeta(s) on points s = sigma + i t with sigma arbitrary not +necessarily equal to 1/2. + +It is founded on a new deduction of the formula, with rigorous +and sharp bounds for the terms and rest of this expansion. + +More information on the papers: + + J. Arias de Reyna, High Precision Computation of Riemann's + Zeta Function by the Riemann-Siegel Formula I, II + + We refer to them as I, II. + + In them we shall find detailed explanation of all the + procedure. + +The program uses Riemann-Siegel expansion. +This is useful when t is big, ( say t > 10000 ). +The precision is limited, roughly it can compute zeta(sigma+it) +with an error less than exp(-c t) for some constant c depending +on sigma. The program gives an error when the Riemann-Siegel +formula can not compute to the wanted precision. + +""" + +import math + +class RSCache(object): + def __init__(ctx): + ctx._rs_cache = [0, 10, {}, {}] + +from .functions import defun + +#-------------------------------------------------------------------------------# +# # +# coef(ctx, J, eps, _cache=[0, 10, {} ] ) # +# # +#-------------------------------------------------------------------------------# + +# This function computes the coefficients c[n] defined on (I, equation (47)) +# but see also (II, section 3.14). +# +# Since these coefficients are very difficult to compute we save the values +# in a cache. So if we compute several values of the functions Rzeta(s) for +# near values of s, we do not recompute these coefficients. +# +# c[n] are the Taylor coefficients of the function: +# +# F(z):= (exp(pi*j*(z*z/2+3/8))-j* sqrt(2) cos(pi*z/2))/(2*cos(pi *z)) +# +# + +def _coef(ctx, J, eps): + r""" + Computes the coefficients `c_n` for `0\le n\le 2J` with error less than eps + + **Definition** + + The coefficients c_n are defined by + + .. math :: + + \begin{equation} + F(z)=\frac{e^{\pi i + \bigl(\frac{z^2}{2}+\frac38\bigr)}-i\sqrt{2}\cos\frac{\pi}{2}z}{2\cos\pi + z}=\sum_{n=0}^\infty c_{2n} z^{2n} + \end{equation} + + they are computed applying the relation + + .. math :: + + \begin{multline} + c_{2n}=-\frac{i}{\sqrt{2}}\Bigl(\frac{\pi}{2}\Bigr)^{2n} + \sum_{k=0}^n\frac{(-1)^k}{(2k)!} + 2^{2n-2k}\frac{(-1)^{n-k}E_{2n-2k}}{(2n-2k)!}+\\ + +e^{3\pi i/8}\sum_{j=0}^n(-1)^j\frac{ + E_{2j}}{(2j)!}\frac{i^{n-j}\pi^{n+j}}{(n-j)!2^{n-j+1}}. + \end{multline} + """ + + newJ = J+2 # compute more coefficients that are needed + neweps6 = eps/2. # compute with a slight more precision that are needed + + # PREPARATION FOR THE COMPUTATION OF V(N) AND W(N) + # See II Section 3.16 + # + # Computing the exponent wpvw of the error II equation (81) + wpvw = max(ctx.mag(10*(newJ+3)), 4*newJ+5-ctx.mag(neweps6)) + + # Preparation of Euler numbers (we need until the 2*RS_NEWJ) + E = ctx._eulernum(2*newJ) + + # Now we have in the cache all the needed Euler numbers. + # + # Computing the powers of pi + # + # We need to compute the powers pi**n for 1<= n <= 2*J + # with relative error less than 2**(-wpvw) + # it is easy to show that this is obtained + # taking wppi as the least d with + # 2**d>40*J and 2**d> 4.24 *newJ + 2**wpvw + # In II Section 3.9 we need also that + # wppi > wptcoef[0], and that the powers + # here computed 0<= k <= 2*newJ are more + # than those needed there that are 2*L-2. + # so we need J >= L this will be checked + # before computing tcoef[] + wppi = max(ctx.mag(40*newJ), ctx.mag(newJ)+3 +wpvw) + ctx.prec = wppi + pipower = {} + pipower[0] = ctx.one + pipower[1] = ctx.pi + for n in range(2,2*newJ+1): + pipower[n] = pipower[n-1]*ctx.pi + + # COMPUTING THE COEFFICIENTS v(n) AND w(n) + # see II equation (61) and equations (81) and (82) + ctx.prec = wpvw+2 + v={} + w={} + for n in range(0,newJ+1): + va = (-1)**n * ctx._eulernum(2*n) + va = ctx.mpf(va)/ctx.fac(2*n) + v[n]=va*pipower[2*n] + for n in range(0,2*newJ+1): + wa = ctx.one/ctx.fac(n) + wa=wa/(2**n) + w[n]=wa*pipower[n] + + # COMPUTATION OF THE CONVOLUTIONS RS_P1 AND RS_P2 + # See II Section 3.16 + ctx.prec = 15 + wpp1a = 9 - ctx.mag(neweps6) + P1 = {} + for n in range(0,newJ+1): + ctx.prec = 15 + wpp1 = max(ctx.mag(10*(n+4)),4*n+wpp1a) + ctx.prec = wpp1 + sump = 0 + for k in range(0,n+1): + sump += ((-1)**k) * v[k]*w[2*n-2*k] + P1[n]=((-1)**(n+1))*ctx.j*sump + P2={} + for n in range(0,newJ+1): + ctx.prec = 15 + wpp2 = max(ctx.mag(10*(n+4)),4*n+wpp1a) + ctx.prec = wpp2 + sump = 0 + for k in range(0,n+1): + sump += (ctx.j**(n-k)) * v[k]*w[n-k] + P2[n]=sump + # COMPUTING THE COEFFICIENTS c[2n] + # See II Section 3.14 + ctx.prec = 15 + wpc0 = 5 - ctx.mag(neweps6) + wpc = max(6,4*newJ+wpc0) + ctx.prec = wpc + mu = ctx.sqrt(ctx.mpf('2'))/2 + nu = ctx.expjpi(3./8)/2 + c={} + for n in range(0,newJ): + ctx.prec = 15 + wpc = max(6,4*n+wpc0) + ctx.prec = wpc + c[2*n] = mu*P1[n]+nu*P2[n] + for n in range(1,2*newJ,2): + c[n] = 0 + return [newJ, neweps6, c, pipower] + +def coef(ctx, J, eps): + _cache = ctx._rs_cache + if J <= _cache[0] and eps >= _cache[1]: + return _cache[2], _cache[3] + orig = ctx._mp.prec + try: + data = _coef(ctx._mp, J, eps) + finally: + ctx._mp.prec = orig + if ctx is not ctx._mp: + data[2] = dict((k,ctx.convert(v)) for (k,v) in data[2].items()) + data[3] = dict((k,ctx.convert(v)) for (k,v) in data[3].items()) + ctx._rs_cache[:] = data + return ctx._rs_cache[2], ctx._rs_cache[3] + +#-------------------------------------------------------------------------------# +# # +# Rzeta_simul(s,k=0) # +# # +#-------------------------------------------------------------------------------# +# This function return a list with the values: +# Rzeta(sigma+it), conj(Rzeta(1-sigma+it)),Rzeta'(sigma+it), conj(Rzeta'(1-sigma+it)), +# .... , Rzeta^{(k)}(sigma+it), conj(Rzeta^{(k)}(1-sigma+it)) +# +# Useful to compute the function zeta(s) and Z(w) or its derivatives. +# + +def aux_M_Fp(ctx, xA, xeps4, a, xB1, xL): + # COMPUTING M NUMBER OF DERIVATIVES Fp[m] TO COMPUTE + # See II Section 3.11 equations (47) and (48) + aux1 = 126.0657606*xA/xeps4 # 126.06.. = 316/sqrt(2*pi) + aux1 = ctx.ln(aux1) + aux2 = (2*ctx.ln(ctx.pi)+ctx.ln(xB1)+ctx.ln(a))/3 -ctx.ln(2*ctx.pi)/2 + m = 3*xL-3 + aux3= (ctx.loggamma(m+1)-ctx.loggamma(m/3.0+2))/2 -ctx.loggamma((m+1)/2.) + while((aux1 < m*aux2+ aux3)and (m>1)): + m = m - 1 + aux3 = (ctx.loggamma(m+1)-ctx.loggamma(m/3.0+2))/2 -ctx.loggamma((m+1)/2.) + xM = m + return xM + +def aux_J_needed(ctx, xA, xeps4, a, xB1, xM): + # DETERMINATION OF J THE NUMBER OF TERMS NEEDED + # IN THE TAYLOR SERIES OF F. + # See II Section 3.11 equation (49)) + # Only determine one + h1 = xeps4/(632*xA) + h2 = xB1*a * 126.31337419529260248 # = pi^2*e^2*sqrt(3) + h2 = h1 * ctx.power((h2/xM**2),(xM-1)/3) / xM + h3 = min(h1,h2) + return h3 + +def Rzeta_simul(ctx, s, der=0): + # First we take the value of ctx.prec + wpinitial = ctx.prec + + # INITIALIZATION + # Take the real and imaginary part of s + t = ctx._im(s) + xsigma = ctx._re(s) + ysigma = 1 - xsigma + + # Now compute several parameter that appear on the program + ctx.prec = 15 + a = ctx.sqrt(t/(2*ctx.pi)) + xasigma = a ** xsigma + yasigma = a ** ysigma + + # We need a simple bound A1 < asigma (see II Section 3.1 and 3.3) + xA1=ctx.power(2, ctx.mag(xasigma)-1) + yA1=ctx.power(2, ctx.mag(yasigma)-1) + + # We compute various epsilon's (see II end of Section 3.1) + eps = ctx.power(2, -wpinitial) + eps1 = eps/6. + xeps2 = eps * xA1/3. + yeps2 = eps * yA1/3. + + # COMPUTING SOME COEFFICIENTS THAT DEPENDS + # ON sigma + # constant b and c (see I Theorem 2 formula (26) ) + # coefficients A and B1 (see I Section 6.1 equation (50)) + # + # here we not need high precision + ctx.prec = 15 + if xsigma > 0: + xb = 2. + xc = math.pow(9,xsigma)/4.44288 + # 4.44288 =(math.sqrt(2)*math.pi) + xA = math.pow(9,xsigma) + xB1 = 1 + else: + xb = 2.25158 # math.sqrt( (3-2* math.log(2))*math.pi ) + xc = math.pow(2,-xsigma)/4.44288 + xA = math.pow(2,-xsigma) + xB1 = 1.10789 # = 2*sqrt(1-log(2)) + + if(ysigma > 0): + yb = 2. + yc = math.pow(9,ysigma)/4.44288 + # 4.44288 =(math.sqrt(2)*math.pi) + yA = math.pow(9,ysigma) + yB1 = 1 + else: + yb = 2.25158 # math.sqrt( (3-2* math.log(2))*math.pi ) + yc = math.pow(2,-ysigma)/4.44288 + yA = math.pow(2,-ysigma) + yB1 = 1.10789 # = 2*sqrt(1-log(2)) + + # COMPUTING L THE NUMBER OF TERMS NEEDED IN THE RIEMANN-SIEGEL + # CORRECTION + # See II Section 3.2 + ctx.prec = 15 + xL = 1 + while 3*xc*ctx.gamma(xL*0.5) * ctx.power(xb*a,-xL) >= xeps2: + xL = xL+1 + xL = max(2,xL) + yL = 1 + while 3*yc*ctx.gamma(yL*0.5) * ctx.power(yb*a,-yL) >= yeps2: + yL = yL+1 + yL = max(2,yL) + + # The number L has to satify some conditions. + # If not RS can not compute Rzeta(s) with the prescribed precision + # (see II, Section 3.2 condition (20) ) and + # (II, Section 3.3 condition (22) ). Also we have added + # an additional technical condition in Section 3.17 Proposition 17 + if ((3*xL >= 2*a*a/25.) or (3*xL+2+xsigma<0) or (abs(xsigma) > a/2.) or \ + (3*yL >= 2*a*a/25.) or (3*yL+2+ysigma<0) or (abs(ysigma) > a/2.)): + ctx.prec = wpinitial + raise NotImplementedError("Riemann-Siegel can not compute with such precision") + + # We take the maximum of the two values + L = max(xL, yL) + + # INITIALIZATION (CONTINUATION) + # + # eps3 is the constant defined on (II, Section 3.5 equation (27) ) + # each term of the RS correction must be computed with error <= eps3 + xeps3 = xeps2/(4*xL) + yeps3 = yeps2/(4*yL) + + # eps4 is defined on (II Section 3.6 equation (30) ) + # each component of the formula (II Section 3.6 equation (29) ) + # must be computed with error <= eps4 + xeps4 = xeps3/(3*xL) + yeps4 = yeps3/(3*yL) + + # COMPUTING M NUMBER OF DERIVATIVES Fp[m] TO COMPUTE + xM = aux_M_Fp(ctx, xA, xeps4, a, xB1, xL) + yM = aux_M_Fp(ctx, yA, yeps4, a, yB1, yL) + M = max(xM, yM) + + # COMPUTING NUMBER OF TERMS J NEEDED + h3 = aux_J_needed(ctx, xA, xeps4, a, xB1, xM) + h4 = aux_J_needed(ctx, yA, yeps4, a, yB1, yM) + h3 = min(h3,h4) + J = 12 + jvalue = (2*ctx.pi)**J / ctx.gamma(J+1) + while jvalue > h3: + J = J+1 + jvalue = (2*ctx.pi)*jvalue/J + + # COMPUTING eps5[m] for 1 <= m <= 21 + # See II Section 10 equation (43) + # We choose the minimum of the two possibilities + eps5={} + xforeps5 = math.pi*math.pi*xB1*a + yforeps5 = math.pi*math.pi*yB1*a + for m in range(0,22): + xaux1 = math.pow(xforeps5, m/3)/(316.*xA) + yaux1 = math.pow(yforeps5, m/3)/(316.*yA) + aux1 = min(xaux1, yaux1) + aux2 = ctx.gamma(m+1)/ctx.gamma(m/3.0+0.5) + aux2 = math.sqrt(aux2) + eps5[m] = (aux1*aux2*min(xeps4,yeps4)) + + # COMPUTING wpfp + # See II Section 3.13 equation (59) + twenty = min(3*L-3, 21)+1 + aux = 6812*J + wpfp = ctx.mag(44*J) + for m in range(0,twenty): + wpfp = max(wpfp, ctx.mag(aux*ctx.gamma(m+1)/eps5[m])) + + # COMPUTING N AND p + # See II Section + ctx.prec = wpfp + ctx.mag(t)+20 + a = ctx.sqrt(t/(2*ctx.pi)) + N = ctx.floor(a) + p = 1-2*(a-N) + + # now we get a rounded version of p + # to the precision wpfp + # this possibly is not necessary + num=ctx.floor(p*(ctx.mpf('2')**wpfp)) + difference = p * (ctx.mpf('2')**wpfp)-num + if (difference < 0.5): + num = num + else: + num = num+1 + p = ctx.convert(num * (ctx.mpf('2')**(-wpfp))) + + # COMPUTING THE COEFFICIENTS c[n] = cc[n] + # We shall use the notation cc[n], since there is + # a constant that is called c + # See II Section 3.14 + # We compute the coefficients and also save then in a + # cache. The bulk of the computation is passed to + # the function coef() + # + # eps6 is defined in II Section 3.13 equation (58) + eps6 = ctx.power(ctx.convert(2*ctx.pi), J)/(ctx.gamma(J+1)*3*J) + + # Now we compute the coefficients + cc = {} + cont = {} + cont, pipowers = coef(ctx, J, eps6) + cc=cont.copy() # we need a copy since we have to change his values. + Fp={} # this is the adequate locus of this + for n in range(M, 3*L-2): + Fp[n] = 0 + Fp={} + ctx.prec = wpfp + for m in range(0,M+1): + sumP = 0 + for k in range(2*J-m-1,-1,-1): + sumP = (sumP * p)+ cc[k] + Fp[m] = sumP + # preparation of the new coefficients + for k in range(0,2*J-m-1): + cc[k] = (k+1)* cc[k+1] + + # COMPUTING THE NUMBERS xd[u,n,k], yd[u,n,k] + # See II Section 3.17 + # + # First we compute the working precisions xwpd[k] + # Se II equation (92) + xwpd={} + d1 = max(6,ctx.mag(40*L*L)) + xd2 = 13+ctx.mag((1+abs(xsigma))*xA)-ctx.mag(xeps4)-1 + xconst = ctx.ln(8/(ctx.pi*ctx.pi*a*a*xB1*xB1)) /2 + for n in range(0,L): + xd3 = ctx.mag(ctx.sqrt(ctx.gamma(n-0.5)))-ctx.floor(n*xconst)+xd2 + xwpd[n]=max(xd3,d1) + + # procedure of II Section 3.17 + ctx.prec = xwpd[1]+10 + xpsigma = 1-(2*xsigma) + xd = {} + xd[0,0,-2]=0; xd[0,0,-1]=0; xd[0,0,0]=1; xd[0,0,1]=0 + xd[0,-1,-2]=0; xd[0,-1,-1]=0; xd[0,-1,0]=1; xd[0,-1,1]=0 + for n in range(1,L): + ctx.prec = xwpd[n]+10 + for k in range(0,3*n//2+1): + m = 3*n-2*k + if(m!=0): + m1 = ctx.one/m + c1= m1/4 + c2=(xpsigma*m1)/2 + c3=-(m+1) + xd[0,n,k]=c3*xd[0,n-1,k-2]+c1*xd[0,n-1,k]+c2*xd[0,n-1,k-1] + else: + xd[0,n,k]=0 + for r in range(0,k): + add=xd[0,n,r]*(ctx.mpf('1.0')*ctx.fac(2*k-2*r)/ctx.fac(k-r)) + xd[0,n,k] -= ((-1)**(k-r))*add + xd[0,n,-2]=0; xd[0,n,-1]=0; xd[0,n,3*n//2+1]=0 + for mu in range(-2,der+1): + for n in range(-2,L): + for k in range(-3,max(1,3*n//2+2)): + if( (mu<0)or (n<0) or(k<0)or (k>3*n//2)): + xd[mu,n,k] = 0 + for mu in range(1,der+1): + for n in range(0,L): + ctx.prec = xwpd[n]+10 + for k in range(0,3*n//2+1): + aux=(2*mu-2)*xd[mu-2,n-2,k-3]+2*(xsigma+n-2)*xd[mu-1,n-2,k-3] + xd[mu,n,k] = aux - xd[mu-1,n-1,k-1] + + # Now we compute the working precisions ywpd[k] + # Se II equation (92) + ywpd={} + d1 = max(6,ctx.mag(40*L*L)) + yd2 = 13+ctx.mag((1+abs(ysigma))*yA)-ctx.mag(yeps4)-1 + yconst = ctx.ln(8/(ctx.pi*ctx.pi*a*a*yB1*yB1)) /2 + for n in range(0,L): + yd3 = ctx.mag(ctx.sqrt(ctx.gamma(n-0.5)))-ctx.floor(n*yconst)+yd2 + ywpd[n]=max(yd3,d1) + + # procedure of II Section 3.17 + ctx.prec = ywpd[1]+10 + ypsigma = 1-(2*ysigma) + yd = {} + yd[0,0,-2]=0; yd[0,0,-1]=0; yd[0,0,0]=1; yd[0,0,1]=0 + yd[0,-1,-2]=0; yd[0,-1,-1]=0; yd[0,-1,0]=1; yd[0,-1,1]=0 + for n in range(1,L): + ctx.prec = ywpd[n]+10 + for k in range(0,3*n//2+1): + m = 3*n-2*k + if(m!=0): + m1 = ctx.one/m + c1= m1/4 + c2=(ypsigma*m1)/2 + c3=-(m+1) + yd[0,n,k]=c3*yd[0,n-1,k-2]+c1*yd[0,n-1,k]+c2*yd[0,n-1,k-1] + else: + yd[0,n,k]=0 + for r in range(0,k): + add=yd[0,n,r]*(ctx.mpf('1.0')*ctx.fac(2*k-2*r)/ctx.fac(k-r)) + yd[0,n,k] -= ((-1)**(k-r))*add + yd[0,n,-2]=0; yd[0,n,-1]=0; yd[0,n,3*n//2+1]=0 + + for mu in range(-2,der+1): + for n in range(-2,L): + for k in range(-3,max(1,3*n//2+2)): + if( (mu<0)or (n<0) or(k<0)or (k>3*n//2)): + yd[mu,n,k] = 0 + for mu in range(1,der+1): + for n in range(0,L): + ctx.prec = ywpd[n]+10 + for k in range(0,3*n//2+1): + aux=(2*mu-2)*yd[mu-2,n-2,k-3]+2*(ysigma+n-2)*yd[mu-1,n-2,k-3] + yd[mu,n,k] = aux - yd[mu-1,n-1,k-1] + + # COMPUTING THE COEFFICIENTS xtcoef[k,l] + # See II Section 3.9 + # + # computing the needed wp + xwptcoef={} + xwpterm={} + ctx.prec = 15 + c1 = ctx.mag(40*(L+2)) + xc2 = ctx.mag(68*(L+2)*xA) + xc4 = ctx.mag(xB1*a*math.sqrt(ctx.pi))-1 + for k in range(0,L): + xc3 = xc2 - k*xc4+ctx.mag(ctx.fac(k+0.5))/2. + xwptcoef[k] = (max(c1,xc3-ctx.mag(xeps4)+1)+1 +20)*1.5 + xwpterm[k] = (max(c1,ctx.mag(L+2)+xc3-ctx.mag(xeps3)+1)+1 +20) + ywptcoef={} + ywpterm={} + ctx.prec = 15 + c1 = ctx.mag(40*(L+2)) + yc2 = ctx.mag(68*(L+2)*yA) + yc4 = ctx.mag(yB1*a*math.sqrt(ctx.pi))-1 + for k in range(0,L): + yc3 = yc2 - k*yc4+ctx.mag(ctx.fac(k+0.5))/2. + ywptcoef[k] = ((max(c1,yc3-ctx.mag(yeps4)+1))+10)*1.5 + ywpterm[k] = (max(c1,ctx.mag(L+2)+yc3-ctx.mag(yeps3)+1)+1)+10 + + # check of power of pi + # computing the fortcoef[mu,k,ell] + xfortcoef={} + for mu in range(0,der+1): + for k in range(0,L): + for ell in range(-2,3*k//2+1): + xfortcoef[mu,k,ell]=0 + for mu in range(0,der+1): + for k in range(0,L): + ctx.prec = xwptcoef[k] + for ell in range(0,3*k//2+1): + xfortcoef[mu,k,ell]=xd[mu,k,ell]*Fp[3*k-2*ell]/pipowers[2*k-ell] + xfortcoef[mu,k,ell]=xfortcoef[mu,k,ell]/((2*ctx.j)**ell) + + def trunc_a(t): + wp = ctx.prec + ctx.prec = wp + 2 + aa = ctx.sqrt(t/(2*ctx.pi)) + ctx.prec = wp + return aa + + # computing the tcoef[k,ell] + xtcoef={} + for mu in range(0,der+1): + for k in range(0,L): + for ell in range(-2,3*k//2+1): + xtcoef[mu,k,ell]=0 + ctx.prec = max(xwptcoef[0],ywptcoef[0])+3 + aa= trunc_a(t) + la = -ctx.ln(aa) + + for chi in range(0,der+1): + for k in range(0,L): + ctx.prec = xwptcoef[k] + for ell in range(0,3*k//2+1): + xtcoef[chi,k,ell] =0 + for mu in range(0, chi+1): + tcoefter=ctx.binomial(chi,mu)*ctx.power(la,mu)*xfortcoef[chi-mu,k,ell] + xtcoef[chi,k,ell] += tcoefter + + # COMPUTING THE COEFFICIENTS ytcoef[k,l] + # See II Section 3.9 + # + # computing the needed wp + # check of power of pi + # computing the fortcoef[mu,k,ell] + yfortcoef={} + for mu in range(0,der+1): + for k in range(0,L): + for ell in range(-2,3*k//2+1): + yfortcoef[mu,k,ell]=0 + for mu in range(0,der+1): + for k in range(0,L): + ctx.prec = ywptcoef[k] + for ell in range(0,3*k//2+1): + yfortcoef[mu,k,ell]=yd[mu,k,ell]*Fp[3*k-2*ell]/pipowers[2*k-ell] + yfortcoef[mu,k,ell]=yfortcoef[mu,k,ell]/((2*ctx.j)**ell) + # computing the tcoef[k,ell] + ytcoef={} + for chi in range(0,der+1): + for k in range(0,L): + for ell in range(-2,3*k//2+1): + ytcoef[chi,k,ell]=0 + for chi in range(0,der+1): + for k in range(0,L): + ctx.prec = ywptcoef[k] + for ell in range(0,3*k//2+1): + ytcoef[chi,k,ell] =0 + for mu in range(0, chi+1): + tcoefter=ctx.binomial(chi,mu)*ctx.power(la,mu)*yfortcoef[chi-mu,k,ell] + ytcoef[chi,k,ell] += tcoefter + + # COMPUTING tv[k,ell] + # See II Section 3.8 + # + # a has a good value + ctx.prec = max(xwptcoef[0], ywptcoef[0])+2 + av = {} + av[0] = 1 + av[1] = av[0]/a + + ctx.prec = max(xwptcoef[0],ywptcoef[0]) + for k in range(2,L): + av[k] = av[k-1] * av[1] + + # Computing the quotients + xtv = {} + for chi in range(0,der+1): + for k in range(0,L): + ctx.prec = xwptcoef[k] + for ell in range(0,3*k//2+1): + xtv[chi,k,ell] = xtcoef[chi,k,ell]* av[k] + # Computing the quotients + ytv = {} + for chi in range(0,der+1): + for k in range(0,L): + ctx.prec = ywptcoef[k] + for ell in range(0,3*k//2+1): + ytv[chi,k,ell] = ytcoef[chi,k,ell]* av[k] + + # COMPUTING THE TERMS xterm[k] + # See II Section 3.6 + xterm = {} + for chi in range(0,der+1): + for n in range(0,L): + ctx.prec = xwpterm[n] + te = 0 + for k in range(0, 3*n//2+1): + te += xtv[chi,n,k] + xterm[chi,n] = te + + # COMPUTING THE TERMS yterm[k] + # See II Section 3.6 + yterm = {} + for chi in range(0,der+1): + for n in range(0,L): + ctx.prec = ywpterm[n] + te = 0 + for k in range(0, 3*n//2+1): + te += ytv[chi,n,k] + yterm[chi,n] = te + + # COMPUTING rssum + # See II Section 3.5 + xrssum={} + ctx.prec=15 + xrsbound = math.sqrt(ctx.pi) * xc /(xb*a) + ctx.prec=15 + xwprssum = ctx.mag(4.4*((L+3)**2)*xrsbound / xeps2) + xwprssum = max(xwprssum, ctx.mag(10*(L+1))) + ctx.prec = xwprssum + for chi in range(0,der+1): + xrssum[chi] = 0 + for k in range(1,L+1): + xrssum[chi] += xterm[chi,L-k] + yrssum={} + ctx.prec=15 + yrsbound = math.sqrt(ctx.pi) * yc /(yb*a) + ctx.prec=15 + ywprssum = ctx.mag(4.4*((L+3)**2)*yrsbound / yeps2) + ywprssum = max(ywprssum, ctx.mag(10*(L+1))) + ctx.prec = ywprssum + for chi in range(0,der+1): + yrssum[chi] = 0 + for k in range(1,L+1): + yrssum[chi] += yterm[chi,L-k] + + # COMPUTING S3 + # See II Section 3.19 + ctx.prec = 15 + A2 = 2**(max(ctx.mag(abs(xrssum[0])), ctx.mag(abs(yrssum[0])))) + eps8 = eps/(3*A2) + T = t *ctx.ln(t/(2*ctx.pi)) + xwps3 = 5 + ctx.mag((1+(2/eps8)*ctx.power(a,-xsigma))*T) + ywps3 = 5 + ctx.mag((1+(2/eps8)*ctx.power(a,-ysigma))*T) + + ctx.prec = max(xwps3, ywps3) + + tpi = t/(2*ctx.pi) + arg = (t/2)*ctx.ln(tpi)-(t/2)-ctx.pi/8 + U = ctx.expj(-arg) + a = trunc_a(t) + xasigma = ctx.power(a, -xsigma) + yasigma = ctx.power(a, -ysigma) + xS3 = ((-1)**(N-1)) * xasigma * U + yS3 = ((-1)**(N-1)) * yasigma * U + + # COMPUTING S1 the zetasum + # See II Section 3.18 + ctx.prec = 15 + xwpsum = 4+ ctx.mag((N+ctx.power(N,1-xsigma))*ctx.ln(N) /eps1) + ywpsum = 4+ ctx.mag((N+ctx.power(N,1-ysigma))*ctx.ln(N) /eps1) + wpsum = max(xwpsum, ywpsum) + + ctx.prec = wpsum +10 + ''' + # This can be improved + xS1={} + yS1={} + for chi in range(0,der+1): + xS1[chi] = 0 + yS1[chi] = 0 + for n in range(1,int(N)+1): + ln = ctx.ln(n) + xexpn = ctx.exp(-ln*(xsigma+ctx.j*t)) + yexpn = ctx.conj(1/(n*xexpn)) + for chi in range(0,der+1): + pown = ctx.power(-ln, chi) + xterm = pown*xexpn + yterm = pown*yexpn + xS1[chi] += xterm + yS1[chi] += yterm + ''' + xS1, yS1 = ctx._zetasum(s, 1, int(N)-1, range(0,der+1), True) + + # END OF COMPUTATION of xrz, yrz + # See II Section 3.1 + ctx.prec = 15 + xabsS1 = abs(xS1[der]) + xabsS2 = abs(xrssum[der] * xS3) + xwpend = max(6, wpinitial+ctx.mag(6*(3*xabsS1+7*xabsS2) ) ) + + ctx.prec = xwpend + xrz={} + for chi in range(0,der+1): + xrz[chi] = xS1[chi]+xrssum[chi]*xS3 + + ctx.prec = 15 + yabsS1 = abs(yS1[der]) + yabsS2 = abs(yrssum[der] * yS3) + ywpend = max(6, wpinitial+ctx.mag(6*(3*yabsS1+7*yabsS2) ) ) + + ctx.prec = ywpend + yrz={} + for chi in range(0,der+1): + yrz[chi] = yS1[chi]+yrssum[chi]*yS3 + yrz[chi] = ctx.conj(yrz[chi]) + ctx.prec = wpinitial + return xrz, yrz + +def Rzeta_set(ctx, s, derivatives=[0]): + r""" + Computes several derivatives of the auxiliary function of Riemann `R(s)`. + + **Definition** + + The function is defined by + + .. math :: + + \begin{equation} + {\mathop{\mathcal R }\nolimits}(s)= + \int_{0\swarrow1}\frac{x^{-s} e^{\pi i x^2}}{e^{\pi i x}- + e^{-\pi i x}}\,dx + \end{equation} + + To this function we apply the Riemann-Siegel expansion. + """ + der = max(derivatives) + # First we take the value of ctx.prec + # During the computation we will change ctx.prec, and finally we will + # restaurate the initial value + wpinitial = ctx.prec + # Take the real and imaginary part of s + t = ctx._im(s) + sigma = ctx._re(s) + # Now compute several parameter that appear on the program + ctx.prec = 15 + a = ctx.sqrt(t/(2*ctx.pi)) # Careful + asigma = ctx.power(a, sigma) # Careful + # We need a simple bound A1 < asigma (see II Section 3.1 and 3.3) + A1 = ctx.power(2, ctx.mag(asigma)-1) + # We compute various epsilon's (see II end of Section 3.1) + eps = ctx.power(2, -wpinitial) + eps1 = eps/6. + eps2 = eps * A1/3. + # COMPUTING SOME COEFFICIENTS THAT DEPENDS + # ON sigma + # constant b and c (see I Theorem 2 formula (26) ) + # coefficients A and B1 (see I Section 6.1 equation (50)) + # here we not need high precision + ctx.prec = 15 + if sigma > 0: + b = 2. + c = math.pow(9,sigma)/4.44288 + # 4.44288 =(math.sqrt(2)*math.pi) + A = math.pow(9,sigma) + B1 = 1 + else: + b = 2.25158 # math.sqrt( (3-2* math.log(2))*math.pi ) + c = math.pow(2,-sigma)/4.44288 + A = math.pow(2,-sigma) + B1 = 1.10789 # = 2*sqrt(1-log(2)) + # COMPUTING L THE NUMBER OF TERMS NEEDED IN THE RIEMANN-SIEGEL + # CORRECTION + # See II Section 3.2 + ctx.prec = 15 + L = 1 + while 3*c*ctx.gamma(L*0.5) * ctx.power(b*a,-L) >= eps2: + L = L+1 + L = max(2,L) + # The number L has to satify some conditions. + # If not RS can not compute Rzeta(s) with the prescribed precision + # (see II, Section 3.2 condition (20) ) and + # (II, Section 3.3 condition (22) ). Also we have added + # an additional technical condition in Section 3.17 Proposition 17 + if ((3*L >= 2*a*a/25.) or (3*L+2+sigma<0) or (abs(sigma)> a/2.)): + #print 'Error Riemann-Siegel can not compute with such precision' + ctx.prec = wpinitial + raise NotImplementedError("Riemann-Siegel can not compute with such precision") + + # INITIALIZATION (CONTINUATION) + # + # eps3 is the constant defined on (II, Section 3.5 equation (27) ) + # each term of the RS correction must be computed with error <= eps3 + eps3 = eps2/(4*L) + + # eps4 is defined on (II Section 3.6 equation (30) ) + # each component of the formula (II Section 3.6 equation (29) ) + # must be computed with error <= eps4 + eps4 = eps3/(3*L) + + # COMPUTING M. NUMBER OF DERIVATIVES Fp[m] TO COMPUTE + M = aux_M_Fp(ctx, A, eps4, a, B1, L) + Fp = {} + for n in range(M, 3*L-2): + Fp[n] = 0 + + # But I have not seen an instance of M != 3*L-3 + # + # DETERMINATION OF J THE NUMBER OF TERMS NEEDED + # IN THE TAYLOR SERIES OF F. + # See II Section 3.11 equation (49)) + h1 = eps4/(632*A) + h2 = ctx.pi*ctx.pi*B1*a *ctx.sqrt(3)*math.e*math.e + h2 = h1 * ctx.power((h2/M**2),(M-1)/3) / M + h3 = min(h1,h2) + J=12 + jvalue = (2*ctx.pi)**J / ctx.gamma(J+1) + while jvalue > h3: + J = J+1 + jvalue = (2*ctx.pi)*jvalue/J + + # COMPUTING eps5[m] for 1 <= m <= 21 + # See II Section 10 equation (43) + eps5={} + foreps5 = math.pi*math.pi*B1*a + for m in range(0,22): + aux1 = math.pow(foreps5, m/3)/(316.*A) + aux2 = ctx.gamma(m+1)/ctx.gamma(m/3.0+0.5) + aux2 = math.sqrt(aux2) + eps5[m] = aux1*aux2*eps4 + + # COMPUTING wpfp + # See II Section 3.13 equation (59) + twenty = min(3*L-3, 21)+1 + aux = 6812*J + wpfp = ctx.mag(44*J) + for m in range(0, twenty): + wpfp = max(wpfp, ctx.mag(aux*ctx.gamma(m+1)/eps5[m])) + # COMPUTING N AND p + # See II Section + ctx.prec = wpfp + ctx.mag(t) + 20 + a = ctx.sqrt(t/(2*ctx.pi)) + N = ctx.floor(a) + p = 1-2*(a-N) + + # now we get a rounded version of p to the precision wpfp + # this possibly is not necessary + num = ctx.floor(p*(ctx.mpf(2)**wpfp)) + difference = p * (ctx.mpf(2)**wpfp)-num + if difference < 0.5: + num = num + else: + num = num+1 + p = ctx.convert(num * (ctx.mpf(2)**(-wpfp))) + + # COMPUTING THE COEFFICIENTS c[n] = cc[n] + # We shall use the notation cc[n], since there is + # a constant that is called c + # See II Section 3.14 + # We compute the coefficients and also save then in a + # cache. The bulk of the computation is passed to + # the function coef() + # + # eps6 is defined in II Section 3.13 equation (58) + eps6 = ctx.power(2*ctx.pi, J)/(ctx.gamma(J+1)*3*J) + + # Now we compute the coefficients + cc={} + cont={} + cont, pipowers = coef(ctx, J, eps6) + cc = cont.copy() # we need a copy since we have + Fp={} + for n in range(M, 3*L-2): + Fp[n] = 0 + ctx.prec = wpfp + for m in range(0,M+1): + sumP = 0 + for k in range(2*J-m-1,-1,-1): + sumP = (sumP * p) + cc[k] + Fp[m] = sumP + # preparation of the new coefficients + for k in range(0, 2*J-m-1): + cc[k] = (k+1) * cc[k+1] + + # COMPUTING THE NUMBERS d[n,k] + # See II Section 3.17 + + # First we compute the working precisions wpd[k] + # Se II equation (92) + wpd = {} + d1 = max(6, ctx.mag(40*L*L)) + d2 = 13+ctx.mag((1+abs(sigma))*A)-ctx.mag(eps4)-1 + const = ctx.ln(8/(ctx.pi*ctx.pi*a*a*B1*B1)) /2 + for n in range(0,L): + d3 = ctx.mag(ctx.sqrt(ctx.gamma(n-0.5)))-ctx.floor(n*const)+d2 + wpd[n] = max(d3,d1) + + # procedure of II Section 3.17 + ctx.prec = wpd[1]+10 + psigma = 1-(2*sigma) + d = {} + d[0,0,-2]=0; d[0,0,-1]=0; d[0,0,0]=1; d[0,0,1]=0 + d[0,-1,-2]=0; d[0,-1,-1]=0; d[0,-1,0]=1; d[0,-1,1]=0 + for n in range(1,L): + ctx.prec = wpd[n]+10 + for k in range(0,3*n//2+1): + m = 3*n-2*k + if (m!=0): + m1 = ctx.one/m + c1 = m1/4 + c2 = (psigma*m1)/2 + c3 = -(m+1) + d[0,n,k] = c3*d[0,n-1,k-2]+c1*d[0,n-1,k]+c2*d[0,n-1,k-1] + else: + d[0,n,k]=0 + for r in range(0,k): + add = d[0,n,r]*(ctx.one*ctx.fac(2*k-2*r)/ctx.fac(k-r)) + d[0,n,k] -= ((-1)**(k-r))*add + d[0,n,-2]=0; d[0,n,-1]=0; d[0,n,3*n//2+1]=0 + + for mu in range(-2,der+1): + for n in range(-2,L): + for k in range(-3,max(1,3*n//2+2)): + if ((mu<0)or (n<0) or(k<0)or (k>3*n//2)): + d[mu,n,k] = 0 + + for mu in range(1,der+1): + for n in range(0,L): + ctx.prec = wpd[n]+10 + for k in range(0,3*n//2+1): + aux=(2*mu-2)*d[mu-2,n-2,k-3]+2*(sigma+n-2)*d[mu-1,n-2,k-3] + d[mu,n,k] = aux - d[mu-1,n-1,k-1] + + # COMPUTING THE COEFFICIENTS t[k,l] + # See II Section 3.9 + # + # computing the needed wp + wptcoef = {} + wpterm = {} + ctx.prec = 15 + c1 = ctx.mag(40*(L+2)) + c2 = ctx.mag(68*(L+2)*A) + c4 = ctx.mag(B1*a*math.sqrt(ctx.pi))-1 + for k in range(0,L): + c3 = c2 - k*c4+ctx.mag(ctx.fac(k+0.5))/2. + wptcoef[k] = max(c1,c3-ctx.mag(eps4)+1)+1 +10 + wpterm[k] = max(c1,ctx.mag(L+2)+c3-ctx.mag(eps3)+1)+1 +10 + + # check of power of pi + + # computing the fortcoef[mu,k,ell] + fortcoef={} + for mu in derivatives: + for k in range(0,L): + for ell in range(-2,3*k//2+1): + fortcoef[mu,k,ell]=0 + + for mu in derivatives: + for k in range(0,L): + ctx.prec = wptcoef[k] + for ell in range(0,3*k//2+1): + fortcoef[mu,k,ell]=d[mu,k,ell]*Fp[3*k-2*ell]/pipowers[2*k-ell] + fortcoef[mu,k,ell]=fortcoef[mu,k,ell]/((2*ctx.j)**ell) + + def trunc_a(t): + wp = ctx.prec + ctx.prec = wp + 2 + aa = ctx.sqrt(t/(2*ctx.pi)) + ctx.prec = wp + return aa + + # computing the tcoef[chi,k,ell] + tcoef={} + for chi in derivatives: + for k in range(0,L): + for ell in range(-2,3*k//2+1): + tcoef[chi,k,ell]=0 + ctx.prec = wptcoef[0]+3 + aa = trunc_a(t) + la = -ctx.ln(aa) + + for chi in derivatives: + for k in range(0,L): + ctx.prec = wptcoef[k] + for ell in range(0,3*k//2+1): + tcoef[chi,k,ell] = 0 + for mu in range(0, chi+1): + tcoefter = ctx.binomial(chi,mu) * la**mu * \ + fortcoef[chi-mu,k,ell] + tcoef[chi,k,ell] += tcoefter + + # COMPUTING tv[k,ell] + # See II Section 3.8 + + # Computing the powers av[k] = a**(-k) + ctx.prec = wptcoef[0] + 2 + + # a has a good value of a. + # See II Section 3.6 + av = {} + av[0] = 1 + av[1] = av[0]/a + + ctx.prec = wptcoef[0] + for k in range(2,L): + av[k] = av[k-1] * av[1] + + # Computing the quotients + tv = {} + for chi in derivatives: + for k in range(0,L): + ctx.prec = wptcoef[k] + for ell in range(0,3*k//2+1): + tv[chi,k,ell] = tcoef[chi,k,ell]* av[k] + + # COMPUTING THE TERMS term[k] + # See II Section 3.6 + term = {} + for chi in derivatives: + for n in range(0,L): + ctx.prec = wpterm[n] + te = 0 + for k in range(0, 3*n//2+1): + te += tv[chi,n,k] + term[chi,n] = te + + # COMPUTING rssum + # See II Section 3.5 + rssum={} + ctx.prec=15 + rsbound = math.sqrt(ctx.pi) * c /(b*a) + ctx.prec=15 + wprssum = ctx.mag(4.4*((L+3)**2)*rsbound / eps2) + wprssum = max(wprssum, ctx.mag(10*(L+1))) + ctx.prec = wprssum + for chi in derivatives: + rssum[chi] = 0 + for k in range(1,L+1): + rssum[chi] += term[chi,L-k] + + # COMPUTING S3 + # See II Section 3.19 + ctx.prec = 15 + A2 = 2**(ctx.mag(rssum[0])) + eps8 = eps/(3* A2) + T = t * ctx.ln(t/(2*ctx.pi)) + wps3 = 5 + ctx.mag((1+(2/eps8)*ctx.power(a,-sigma))*T) + + ctx.prec = wps3 + tpi = t/(2*ctx.pi) + arg = (t/2)*ctx.ln(tpi)-(t/2)-ctx.pi/8 + U = ctx.expj(-arg) + a = trunc_a(t) + asigma = ctx.power(a, -sigma) + S3 = ((-1)**(N-1)) * asigma * U + + # COMPUTING S1 the zetasum + # See II Section 3.18 + ctx.prec = 15 + wpsum = 4 + ctx.mag((N+ctx.power(N,1-sigma))*ctx.ln(N)/eps1) + + ctx.prec = wpsum + 10 + ''' + # This can be improved + S1 = {} + for chi in derivatives: + S1[chi] = 0 + for n in range(1,int(N)+1): + ln = ctx.ln(n) + expn = ctx.exp(-ln*(sigma+ctx.j*t)) + for chi in derivatives: + term = ctx.power(-ln, chi)*expn + S1[chi] += term + ''' + S1 = ctx._zetasum(s, 1, int(N)-1, derivatives)[0] + + # END OF COMPUTATION + # See II Section 3.1 + ctx.prec = 15 + absS1 = abs(S1[der]) + absS2 = abs(rssum[der] * S3) + wpend = max(6, wpinitial + ctx.mag(6*(3*absS1+7*absS2))) + ctx.prec = wpend + rz = {} + for chi in derivatives: + rz[chi] = S1[chi]+rssum[chi]*S3 + ctx.prec = wpinitial + return rz + + +def z_half(ctx,t,der=0): + r""" + z_half(t,der=0) Computes Z^(der)(t) + """ + s=ctx.mpf('0.5')+ctx.j*t + wpinitial = ctx.prec + ctx.prec = 15 + tt = t/(2*ctx.pi) + wptheta = wpinitial +1 + ctx.mag(3*(tt**1.5)*ctx.ln(tt)) + wpz = wpinitial + 1 + ctx.mag(12*tt*ctx.ln(tt)) + ctx.prec = wptheta + theta = ctx.siegeltheta(t) + ctx.prec = wpz + rz = Rzeta_set(ctx,s, range(der+1)) + if der > 0: ps1 = ctx._re(ctx.psi(0,s/2)/2 - ctx.ln(ctx.pi)/2) + if der > 1: ps2 = ctx._re(ctx.j*ctx.psi(1,s/2)/4) + if der > 2: ps3 = ctx._re(-ctx.psi(2,s/2)/8) + if der > 3: ps4 = ctx._re(-ctx.j*ctx.psi(3,s/2)/16) + exptheta = ctx.expj(theta) + if der == 0: + z = 2*exptheta*rz[0] + if der == 1: + zf = 2j*exptheta + z = zf*(ps1*rz[0]+rz[1]) + if der == 2: + zf = 2 * exptheta + z = -zf*(2*rz[1]*ps1+rz[0]*ps1**2+rz[2]-ctx.j*rz[0]*ps2) + if der == 3: + zf = -2j*exptheta + z = 3*rz[1]*ps1**2+rz[0]*ps1**3+3*ps1*rz[2] + z = zf*(z-3j*rz[1]*ps2-3j*rz[0]*ps1*ps2+rz[3]-rz[0]*ps3) + if der == 4: + zf = 2*exptheta + z = 4*rz[1]*ps1**3+rz[0]*ps1**4+6*ps1**2*rz[2] + z = z-12j*rz[1]*ps1*ps2-6j*rz[0]*ps1**2*ps2-6j*rz[2]*ps2-3*rz[0]*ps2*ps2 + z = z + 4*ps1*rz[3]-4*rz[1]*ps3-4*rz[0]*ps1*ps3+rz[4]+ctx.j*rz[0]*ps4 + z = zf*z + ctx.prec = wpinitial + return ctx._re(z) + +def zeta_half(ctx, s, k=0): + """ + zeta_half(s,k=0) Computes zeta^(k)(s) when Re s = 0.5 + """ + wpinitial = ctx.prec + sigma = ctx._re(s) + t = ctx._im(s) + #--- compute wptheta, wpR, wpbasic --- + ctx.prec = 53 + # X see II Section 3.21 (109) and (110) + if sigma > 0: + X = ctx.sqrt(abs(s)) + else: + X = (2*ctx.pi)**(sigma-1) * abs(1-s)**(0.5-sigma) + # M1 see II Section 3.21 (111) and (112) + if sigma > 0: + M1 = 2*ctx.sqrt(t/(2*ctx.pi)) + else: + M1 = 4 * t * X + # T see II Section 3.21 (113) + abst = abs(0.5-s) + T = 2* abst*math.log(abst) + # computing wpbasic, wptheta, wpR see II Section 3.21 + wpbasic = max(6,3+ctx.mag(t)) + wpbasic2 = 2+ctx.mag(2.12*M1+21.2*M1*X+1.3*M1*X*T)+wpinitial+1 + wpbasic = max(wpbasic, wpbasic2) + wptheta = max(4, 3+ctx.mag(2.7*M1*X)+wpinitial+1) + wpR = 3+ctx.mag(1.1+2*X)+wpinitial+1 + ctx.prec = wptheta + theta = ctx.siegeltheta(t-ctx.j*(sigma-ctx.mpf('0.5'))) + if k > 0: ps1 = (ctx._re(ctx.psi(0,s/2)))/2 - ctx.ln(ctx.pi)/2 + if k > 1: ps2 = -(ctx._im(ctx.psi(1,s/2)))/4 + if k > 2: ps3 = -(ctx._re(ctx.psi(2,s/2)))/8 + if k > 3: ps4 = (ctx._im(ctx.psi(3,s/2)))/16 + ctx.prec = wpR + xrz = Rzeta_set(ctx,s,range(k+1)) + yrz={} + for chi in range(0,k+1): + yrz[chi] = ctx.conj(xrz[chi]) + ctx.prec = wpbasic + exptheta = ctx.expj(-2*theta) + if k==0: + zv = xrz[0]+exptheta*yrz[0] + if k==1: + zv1 = -yrz[1] - 2*yrz[0]*ps1 + zv = xrz[1] + exptheta*zv1 + if k==2: + zv1 = 4*yrz[1]*ps1+4*yrz[0]*(ps1**2)+yrz[2]+2j*yrz[0]*ps2 + zv = xrz[2]+exptheta*zv1 + if k==3: + zv1 = -12*yrz[1]*ps1**2-8*yrz[0]*ps1**3-6*yrz[2]*ps1-6j*yrz[1]*ps2 + zv1 = zv1 - 12j*yrz[0]*ps1*ps2-yrz[3]+2*yrz[0]*ps3 + zv = xrz[3]+exptheta*zv1 + if k == 4: + zv1 = 32*yrz[1]*ps1**3 +16*yrz[0]*ps1**4+24*yrz[2]*ps1**2 + zv1 = zv1 +48j*yrz[1]*ps1*ps2+48j*yrz[0]*(ps1**2)*ps2 + zv1 = zv1+12j*yrz[2]*ps2-12*yrz[0]*ps2**2+8*yrz[3]*ps1-8*yrz[1]*ps3 + zv1 = zv1-16*yrz[0]*ps1*ps3+yrz[4]-2j*yrz[0]*ps4 + zv = xrz[4]+exptheta*zv1 + ctx.prec = wpinitial + return zv + +def zeta_offline(ctx, s, k=0): + """ + Computes zeta^(k)(s) off the line + """ + wpinitial = ctx.prec + sigma = ctx._re(s) + t = ctx._im(s) + #--- compute wptheta, wpR, wpbasic --- + ctx.prec = 53 + # X see II Section 3.21 (109) and (110) + if sigma > 0: + X = ctx.power(abs(s), 0.5) + else: + X = ctx.power(2*ctx.pi, sigma-1)*ctx.power(abs(1-s),0.5-sigma) + # M1 see II Section 3.21 (111) and (112) + if (sigma > 0): + M1 = 2*ctx.sqrt(t/(2*ctx.pi)) + else: + M1 = 4 * t * X + # M2 see II Section 3.21 (111) and (112) + if (1-sigma > 0): + M2 = 2*ctx.sqrt(t/(2*ctx.pi)) + else: + M2 = 4*t*ctx.power(2*ctx.pi, -sigma)*ctx.power(abs(s),sigma-0.5) + # T see II Section 3.21 (113) + abst = abs(0.5-s) + T = 2* abst*math.log(abst) + # computing wpbasic, wptheta, wpR see II Section 3.21 + wpbasic = max(6,3+ctx.mag(t)) + wpbasic2 = 2+ctx.mag(2.12*M1+21.2*M2*X+1.3*M2*X*T)+wpinitial+1 + wpbasic = max(wpbasic, wpbasic2) + wptheta = max(4, 3+ctx.mag(2.7*M2*X)+wpinitial+1) + wpR = 3+ctx.mag(1.1+2*X)+wpinitial+1 + ctx.prec = wptheta + theta = ctx.siegeltheta(t-ctx.j*(sigma-ctx.mpf('0.5'))) + s1 = s + s2 = ctx.conj(1-s1) + ctx.prec = wpR + xrz, yrz = Rzeta_simul(ctx, s, k) + if k > 0: ps1 = (ctx.psi(0,s1/2)+ctx.psi(0,(1-s1)/2))/4 - ctx.ln(ctx.pi)/2 + if k > 1: ps2 = ctx.j*(ctx.psi(1,s1/2)-ctx.psi(1,(1-s1)/2))/8 + if k > 2: ps3 = -(ctx.psi(2,s1/2)+ctx.psi(2,(1-s1)/2))/16 + if k > 3: ps4 = -ctx.j*(ctx.psi(3,s1/2)-ctx.psi(3,(1-s1)/2))/32 + ctx.prec = wpbasic + exptheta = ctx.expj(-2*theta) + if k == 0: + zv = xrz[0]+exptheta*yrz[0] + if k == 1: + zv1 = -yrz[1]-2*yrz[0]*ps1 + zv = xrz[1]+exptheta*zv1 + if k == 2: + zv1 = 4*yrz[1]*ps1+4*yrz[0]*(ps1**2) +yrz[2]+2j*yrz[0]*ps2 + zv = xrz[2]+exptheta*zv1 + if k == 3: + zv1 = -12*yrz[1]*ps1**2 -8*yrz[0]*ps1**3-6*yrz[2]*ps1-6j*yrz[1]*ps2 + zv1 = zv1 - 12j*yrz[0]*ps1*ps2-yrz[3]+2*yrz[0]*ps3 + zv = xrz[3]+exptheta*zv1 + if k == 4: + zv1 = 32*yrz[1]*ps1**3 +16*yrz[0]*ps1**4+24*yrz[2]*ps1**2 + zv1 = zv1 +48j*yrz[1]*ps1*ps2+48j*yrz[0]*(ps1**2)*ps2 + zv1 = zv1+12j*yrz[2]*ps2-12*yrz[0]*ps2**2+8*yrz[3]*ps1-8*yrz[1]*ps3 + zv1 = zv1-16*yrz[0]*ps1*ps3+yrz[4]-2j*yrz[0]*ps4 + zv = xrz[4]+exptheta*zv1 + ctx.prec = wpinitial + return zv + +def z_offline(ctx, w, k=0): + r""" + Computes Z(w) and its derivatives off the line + """ + s = ctx.mpf('0.5')+ctx.j*w + s1 = s + s2 = ctx.conj(1-s1) + wpinitial = ctx.prec + ctx.prec = 35 + # X see II Section 3.21 (109) and (110) + # M1 see II Section 3.21 (111) and (112) + if (ctx._re(s1) >= 0): + M1 = 2*ctx.sqrt(ctx._im(s1)/(2 * ctx.pi)) + X = ctx.sqrt(abs(s1)) + else: + X = (2*ctx.pi)**(ctx._re(s1)-1) * abs(1-s1)**(0.5-ctx._re(s1)) + M1 = 4 * ctx._im(s1)*X + # M2 see II Section 3.21 (111) and (112) + if (ctx._re(s2) >= 0): + M2 = 2*ctx.sqrt(ctx._im(s2)/(2 * ctx.pi)) + else: + M2 = 4 * ctx._im(s2)*(2*ctx.pi)**(ctx._re(s2)-1)*abs(1-s2)**(0.5-ctx._re(s2)) + # T see II Section 3.21 Prop. 27 + T = 2*abs(ctx.siegeltheta(w)) + # defining some precisions + # see II Section 3.22 (115), (116), (117) + aux1 = ctx.sqrt(X) + aux2 = aux1*(M1+M2) + aux3 = 3 +wpinitial + wpbasic = max(6, 3+ctx.mag(T), ctx.mag(aux2*(26+2*T))+aux3) + wptheta = max(4,ctx.mag(2.04*aux2)+aux3) + wpR = ctx.mag(4*aux1)+aux3 + # now the computations + ctx.prec = wptheta + theta = ctx.siegeltheta(w) + ctx.prec = wpR + xrz, yrz = Rzeta_simul(ctx,s,k) + pta = 0.25 + 0.5j*w + ptb = 0.25 - 0.5j*w + if k > 0: ps1 = 0.25*(ctx.psi(0,pta)+ctx.psi(0,ptb)) - ctx.ln(ctx.pi)/2 + if k > 1: ps2 = (1j/8)*(ctx.psi(1,pta)-ctx.psi(1,ptb)) + if k > 2: ps3 = (-1./16)*(ctx.psi(2,pta)+ctx.psi(2,ptb)) + if k > 3: ps4 = (-1j/32)*(ctx.psi(3,pta)-ctx.psi(3,ptb)) + ctx.prec = wpbasic + exptheta = ctx.expj(theta) + if k == 0: + zv = exptheta*xrz[0]+yrz[0]/exptheta + j = ctx.j + if k == 1: + zv = j*exptheta*(xrz[1]+xrz[0]*ps1)-j*(yrz[1]+yrz[0]*ps1)/exptheta + if k == 2: + zv = exptheta*(-2*xrz[1]*ps1-xrz[0]*ps1**2-xrz[2]+j*xrz[0]*ps2) + zv =zv + (-2*yrz[1]*ps1-yrz[0]*ps1**2-yrz[2]-j*yrz[0]*ps2)/exptheta + if k == 3: + zv1 = -3*xrz[1]*ps1**2-xrz[0]*ps1**3-3*xrz[2]*ps1+j*3*xrz[1]*ps2 + zv1 = (zv1+ 3j*xrz[0]*ps1*ps2-xrz[3]+xrz[0]*ps3)*j*exptheta + zv2 = 3*yrz[1]*ps1**2+yrz[0]*ps1**3+3*yrz[2]*ps1+j*3*yrz[1]*ps2 + zv2 = j*(zv2 + 3j*yrz[0]*ps1*ps2+ yrz[3]-yrz[0]*ps3)/exptheta + zv = zv1+zv2 + if k == 4: + zv1 = 4*xrz[1]*ps1**3+xrz[0]*ps1**4 + 6*xrz[2]*ps1**2 + zv1 = zv1-12j*xrz[1]*ps1*ps2-6j*xrz[0]*ps1**2*ps2-6j*xrz[2]*ps2 + zv1 = zv1-3*xrz[0]*ps2*ps2+4*xrz[3]*ps1-4*xrz[1]*ps3-4*xrz[0]*ps1*ps3 + zv1 = zv1+xrz[4]+j*xrz[0]*ps4 + zv2 = 4*yrz[1]*ps1**3+yrz[0]*ps1**4 + 6*yrz[2]*ps1**2 + zv2 = zv2+12j*yrz[1]*ps1*ps2+6j*yrz[0]*ps1**2*ps2+6j*yrz[2]*ps2 + zv2 = zv2-3*yrz[0]*ps2*ps2+4*yrz[3]*ps1-4*yrz[1]*ps3-4*yrz[0]*ps1*ps3 + zv2 = zv2+yrz[4]-j*yrz[0]*ps4 + zv = exptheta*zv1+zv2/exptheta + ctx.prec = wpinitial + return zv + +@defun +def rs_zeta(ctx, s, derivative=0, **kwargs): + if derivative > 4: + raise NotImplementedError + s = ctx.convert(s) + re = ctx._re(s); im = ctx._im(s) + if im < 0: + z = ctx.conj(ctx.rs_zeta(ctx.conj(s), derivative)) + return z + critical_line = (re == 0.5) + if critical_line: + return zeta_half(ctx, s, derivative) + else: + return zeta_offline(ctx, s, derivative) + +@defun +def rs_z(ctx, w, derivative=0): + w = ctx.convert(w) + re = ctx._re(w); im = ctx._im(w) + if re < 0: + return rs_z(ctx, -w, derivative) + critical_line = (im == 0) + if critical_line : + return z_half(ctx, w, derivative) + else: + return z_offline(ctx, w, derivative) diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/signals.py b/venv/lib/python3.10/site-packages/mpmath/functions/signals.py new file mode 100644 index 0000000000000000000000000000000000000000..6fadafb2dbb44fe19a2defa8d807d81d7c8e2789 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/functions/signals.py @@ -0,0 +1,32 @@ +from .functions import defun_wrapped + +@defun_wrapped +def squarew(ctx, t, amplitude=1, period=1): + P = period + A = amplitude + return A*((-1)**ctx.floor(2*t/P)) + +@defun_wrapped +def trianglew(ctx, t, amplitude=1, period=1): + A = amplitude + P = period + + return 2*A*(0.5 - ctx.fabs(1 - 2*ctx.frac(t/P + 0.25))) + +@defun_wrapped +def sawtoothw(ctx, t, amplitude=1, period=1): + A = amplitude + P = period + return A*ctx.frac(t/P) + +@defun_wrapped +def unit_triangle(ctx, t, amplitude=1): + A = amplitude + if t <= -1 or t >= 1: + return ctx.zero + return A*(-ctx.fabs(t) + 1) + +@defun_wrapped +def sigmoid(ctx, t, amplitude=1): + A = amplitude + return A / (1 + ctx.exp(-t)) diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/theta.py b/venv/lib/python3.10/site-packages/mpmath/functions/theta.py new file mode 100644 index 0000000000000000000000000000000000000000..2b3d8323a163a43186b85417a1b40f3b656c30d0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/functions/theta.py @@ -0,0 +1,1049 @@ +from .functions import defun, defun_wrapped + +@defun +def _jacobi_theta2(ctx, z, q): + extra1 = 10 + extra2 = 20 + # the loops below break when the fixed precision quantities + # a and b go to zero; + # right shifting small negative numbers by wp one obtains -1, not zero, + # so the condition a**2 + b**2 > MIN is used to break the loops. + MIN = 2 + if z == ctx.zero: + if (not ctx._im(q)): + wp = ctx.prec + extra1 + x = ctx.to_fixed(ctx._re(q), wp) + x2 = (x*x) >> wp + a = b = x2 + s = x2 + while abs(a) > MIN: + b = (b*x2) >> wp + a = (a*b) >> wp + s += a + s = (1 << (wp+1)) + (s << 1) + s = ctx.ldexp(s, -wp) + else: + wp = ctx.prec + extra1 + xre = ctx.to_fixed(ctx._re(q), wp) + xim = ctx.to_fixed(ctx._im(q), wp) + x2re = (xre*xre - xim*xim) >> wp + x2im = (xre*xim) >> (wp-1) + are = bre = x2re + aim = bim = x2im + sre = (1< MIN: + bre, bim = (bre * x2re - bim * x2im) >> wp, \ + (bre * x2im + bim * x2re) >> wp + are, aim = (are * bre - aim * bim) >> wp, \ + (are * bim + aim * bre) >> wp + sre += are + sim += aim + sre = (sre << 1) + sim = (sim << 1) + sre = ctx.ldexp(sre, -wp) + sim = ctx.ldexp(sim, -wp) + s = ctx.mpc(sre, sim) + else: + if (not ctx._im(q)) and (not ctx._im(z)): + wp = ctx.prec + extra1 + x = ctx.to_fixed(ctx._re(q), wp) + x2 = (x*x) >> wp + a = b = x2 + c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp) + cn = c1 = ctx.to_fixed(c1, wp) + sn = s1 = ctx.to_fixed(s1, wp) + c2 = (c1*c1 - s1*s1) >> wp + s2 = (c1 * s1) >> (wp - 1) + cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp + s = c1 + ((a * cn) >> wp) + while abs(a) > MIN: + b = (b*x2) >> wp + a = (a*b) >> wp + cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp + s += (a * cn) >> wp + s = (s << 1) + s = ctx.ldexp(s, -wp) + s *= ctx.nthroot(q, 4) + return s + # case z real, q complex + elif not ctx._im(z): + wp = ctx.prec + extra2 + xre = ctx.to_fixed(ctx._re(q), wp) + xim = ctx.to_fixed(ctx._im(q), wp) + x2re = (xre*xre - xim*xim) >> wp + x2im = (xre*xim) >> (wp - 1) + are = bre = x2re + aim = bim = x2im + c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp) + cn = c1 = ctx.to_fixed(c1, wp) + sn = s1 = ctx.to_fixed(s1, wp) + c2 = (c1*c1 - s1*s1) >> wp + s2 = (c1 * s1) >> (wp - 1) + cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp + sre = c1 + ((are * cn) >> wp) + sim = ((aim * cn) >> wp) + while are**2 + aim**2 > MIN: + bre, bim = (bre * x2re - bim * x2im) >> wp, \ + (bre * x2im + bim * x2re) >> wp + are, aim = (are * bre - aim * bim) >> wp, \ + (are * bim + aim * bre) >> wp + cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp + sre += ((are * cn) >> wp) + sim += ((aim * cn) >> wp) + sre = (sre << 1) + sim = (sim << 1) + sre = ctx.ldexp(sre, -wp) + sim = ctx.ldexp(sim, -wp) + s = ctx.mpc(sre, sim) + #case z complex, q real + elif not ctx._im(q): + wp = ctx.prec + extra2 + x = ctx.to_fixed(ctx._re(q), wp) + x2 = (x*x) >> wp + a = b = x2 + prec0 = ctx.prec + ctx.prec = wp + c1, s1 = ctx.cos_sin(z) + ctx.prec = prec0 + cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) + cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) + snre = s1re = ctx.to_fixed(ctx._re(s1), wp) + snim = s1im = ctx.to_fixed(ctx._im(s1), wp) + #c2 = (c1*c1 - s1*s1) >> wp + c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp + c2im = (c1re*c1im - s1re*s1im) >> (wp - 1) + #s2 = (c1 * s1) >> (wp - 1) + s2re = (c1re*s1re - c1im*s1im) >> (wp - 1) + s2im = (c1re*s1im + c1im*s1re) >> (wp - 1) + #cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp + t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp + t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp + t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp + t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp + cnre = t1 + cnim = t2 + snre = t3 + snim = t4 + sre = c1re + ((a * cnre) >> wp) + sim = c1im + ((a * cnim) >> wp) + while abs(a) > MIN: + b = (b*x2) >> wp + a = (a*b) >> wp + t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp + t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp + t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp + t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp + cnre = t1 + cnim = t2 + snre = t3 + snim = t4 + sre += ((a * cnre) >> wp) + sim += ((a * cnim) >> wp) + sre = (sre << 1) + sim = (sim << 1) + sre = ctx.ldexp(sre, -wp) + sim = ctx.ldexp(sim, -wp) + s = ctx.mpc(sre, sim) + # case z and q complex + else: + wp = ctx.prec + extra2 + xre = ctx.to_fixed(ctx._re(q), wp) + xim = ctx.to_fixed(ctx._im(q), wp) + x2re = (xre*xre - xim*xim) >> wp + x2im = (xre*xim) >> (wp - 1) + are = bre = x2re + aim = bim = x2im + prec0 = ctx.prec + ctx.prec = wp + # cos(z), sin(z) with z complex + c1, s1 = ctx.cos_sin(z) + ctx.prec = prec0 + cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) + cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) + snre = s1re = ctx.to_fixed(ctx._re(s1), wp) + snim = s1im = ctx.to_fixed(ctx._im(s1), wp) + c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp + c2im = (c1re*c1im - s1re*s1im) >> (wp - 1) + s2re = (c1re*s1re - c1im*s1im) >> (wp - 1) + s2im = (c1re*s1im + c1im*s1re) >> (wp - 1) + t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp + t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp + t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp + t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp + cnre = t1 + cnim = t2 + snre = t3 + snim = t4 + n = 1 + termre = c1re + termim = c1im + sre = c1re + ((are * cnre - aim * cnim) >> wp) + sim = c1im + ((are * cnim + aim * cnre) >> wp) + n = 3 + termre = ((are * cnre - aim * cnim) >> wp) + termim = ((are * cnim + aim * cnre) >> wp) + sre = c1re + ((are * cnre - aim * cnim) >> wp) + sim = c1im + ((are * cnim + aim * cnre) >> wp) + n = 5 + while are**2 + aim**2 > MIN: + bre, bim = (bre * x2re - bim * x2im) >> wp, \ + (bre * x2im + bim * x2re) >> wp + are, aim = (are * bre - aim * bim) >> wp, \ + (are * bim + aim * bre) >> wp + #cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp + t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp + t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp + t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp + t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp + cnre = t1 + cnim = t2 + snre = t3 + snim = t4 + termre = ((are * cnre - aim * cnim) >> wp) + termim = ((aim * cnre + are * cnim) >> wp) + sre += ((are * cnre - aim * cnim) >> wp) + sim += ((aim * cnre + are * cnim) >> wp) + n += 2 + sre = (sre << 1) + sim = (sim << 1) + sre = ctx.ldexp(sre, -wp) + sim = ctx.ldexp(sim, -wp) + s = ctx.mpc(sre, sim) + s *= ctx.nthroot(q, 4) + return s + +@defun +def _djacobi_theta2(ctx, z, q, nd): + MIN = 2 + extra1 = 10 + extra2 = 20 + if (not ctx._im(q)) and (not ctx._im(z)): + wp = ctx.prec + extra1 + x = ctx.to_fixed(ctx._re(q), wp) + x2 = (x*x) >> wp + a = b = x2 + c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp) + cn = c1 = ctx.to_fixed(c1, wp) + sn = s1 = ctx.to_fixed(s1, wp) + c2 = (c1*c1 - s1*s1) >> wp + s2 = (c1 * s1) >> (wp - 1) + cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp + if (nd&1): + s = s1 + ((a * sn * 3**nd) >> wp) + else: + s = c1 + ((a * cn * 3**nd) >> wp) + n = 2 + while abs(a) > MIN: + b = (b*x2) >> wp + a = (a*b) >> wp + cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp + if nd&1: + s += (a * sn * (2*n+1)**nd) >> wp + else: + s += (a * cn * (2*n+1)**nd) >> wp + n += 1 + s = -(s << 1) + s = ctx.ldexp(s, -wp) + # case z real, q complex + elif not ctx._im(z): + wp = ctx.prec + extra2 + xre = ctx.to_fixed(ctx._re(q), wp) + xim = ctx.to_fixed(ctx._im(q), wp) + x2re = (xre*xre - xim*xim) >> wp + x2im = (xre*xim) >> (wp - 1) + are = bre = x2re + aim = bim = x2im + c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp) + cn = c1 = ctx.to_fixed(c1, wp) + sn = s1 = ctx.to_fixed(s1, wp) + c2 = (c1*c1 - s1*s1) >> wp + s2 = (c1 * s1) >> (wp - 1) + cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp + if (nd&1): + sre = s1 + ((are * sn * 3**nd) >> wp) + sim = ((aim * sn * 3**nd) >> wp) + else: + sre = c1 + ((are * cn * 3**nd) >> wp) + sim = ((aim * cn * 3**nd) >> wp) + n = 5 + while are**2 + aim**2 > MIN: + bre, bim = (bre * x2re - bim * x2im) >> wp, \ + (bre * x2im + bim * x2re) >> wp + are, aim = (are * bre - aim * bim) >> wp, \ + (are * bim + aim * bre) >> wp + cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp + + if (nd&1): + sre += ((are * sn * n**nd) >> wp) + sim += ((aim * sn * n**nd) >> wp) + else: + sre += ((are * cn * n**nd) >> wp) + sim += ((aim * cn * n**nd) >> wp) + n += 2 + sre = -(sre << 1) + sim = -(sim << 1) + sre = ctx.ldexp(sre, -wp) + sim = ctx.ldexp(sim, -wp) + s = ctx.mpc(sre, sim) + #case z complex, q real + elif not ctx._im(q): + wp = ctx.prec + extra2 + x = ctx.to_fixed(ctx._re(q), wp) + x2 = (x*x) >> wp + a = b = x2 + prec0 = ctx.prec + ctx.prec = wp + c1, s1 = ctx.cos_sin(z) + ctx.prec = prec0 + cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) + cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) + snre = s1re = ctx.to_fixed(ctx._re(s1), wp) + snim = s1im = ctx.to_fixed(ctx._im(s1), wp) + #c2 = (c1*c1 - s1*s1) >> wp + c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp + c2im = (c1re*c1im - s1re*s1im) >> (wp - 1) + #s2 = (c1 * s1) >> (wp - 1) + s2re = (c1re*s1re - c1im*s1im) >> (wp - 1) + s2im = (c1re*s1im + c1im*s1re) >> (wp - 1) + #cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp + t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp + t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp + t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp + t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp + cnre = t1 + cnim = t2 + snre = t3 + snim = t4 + if (nd&1): + sre = s1re + ((a * snre * 3**nd) >> wp) + sim = s1im + ((a * snim * 3**nd) >> wp) + else: + sre = c1re + ((a * cnre * 3**nd) >> wp) + sim = c1im + ((a * cnim * 3**nd) >> wp) + n = 5 + while abs(a) > MIN: + b = (b*x2) >> wp + a = (a*b) >> wp + t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp + t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp + t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp + t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp + cnre = t1 + cnim = t2 + snre = t3 + snim = t4 + if (nd&1): + sre += ((a * snre * n**nd) >> wp) + sim += ((a * snim * n**nd) >> wp) + else: + sre += ((a * cnre * n**nd) >> wp) + sim += ((a * cnim * n**nd) >> wp) + n += 2 + sre = -(sre << 1) + sim = -(sim << 1) + sre = ctx.ldexp(sre, -wp) + sim = ctx.ldexp(sim, -wp) + s = ctx.mpc(sre, sim) + # case z and q complex + else: + wp = ctx.prec + extra2 + xre = ctx.to_fixed(ctx._re(q), wp) + xim = ctx.to_fixed(ctx._im(q), wp) + x2re = (xre*xre - xim*xim) >> wp + x2im = (xre*xim) >> (wp - 1) + are = bre = x2re + aim = bim = x2im + prec0 = ctx.prec + ctx.prec = wp + # cos(2*z), sin(2*z) with z complex + c1, s1 = ctx.cos_sin(z) + ctx.prec = prec0 + cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) + cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) + snre = s1re = ctx.to_fixed(ctx._re(s1), wp) + snim = s1im = ctx.to_fixed(ctx._im(s1), wp) + c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp + c2im = (c1re*c1im - s1re*s1im) >> (wp - 1) + s2re = (c1re*s1re - c1im*s1im) >> (wp - 1) + s2im = (c1re*s1im + c1im*s1re) >> (wp - 1) + t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp + t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp + t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp + t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp + cnre = t1 + cnim = t2 + snre = t3 + snim = t4 + if (nd&1): + sre = s1re + (((are * snre - aim * snim) * 3**nd) >> wp) + sim = s1im + (((are * snim + aim * snre)* 3**nd) >> wp) + else: + sre = c1re + (((are * cnre - aim * cnim) * 3**nd) >> wp) + sim = c1im + (((are * cnim + aim * cnre)* 3**nd) >> wp) + n = 5 + while are**2 + aim**2 > MIN: + bre, bim = (bre * x2re - bim * x2im) >> wp, \ + (bre * x2im + bim * x2re) >> wp + are, aim = (are * bre - aim * bim) >> wp, \ + (are * bim + aim * bre) >> wp + #cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp + t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp + t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp + t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp + t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp + cnre = t1 + cnim = t2 + snre = t3 + snim = t4 + if (nd&1): + sre += (((are * snre - aim * snim) * n**nd) >> wp) + sim += (((aim * snre + are * snim) * n**nd) >> wp) + else: + sre += (((are * cnre - aim * cnim) * n**nd) >> wp) + sim += (((aim * cnre + are * cnim) * n**nd) >> wp) + n += 2 + sre = -(sre << 1) + sim = -(sim << 1) + sre = ctx.ldexp(sre, -wp) + sim = ctx.ldexp(sim, -wp) + s = ctx.mpc(sre, sim) + s *= ctx.nthroot(q, 4) + if (nd&1): + return (-1)**(nd//2) * s + else: + return (-1)**(1 + nd//2) * s + +@defun +def _jacobi_theta3(ctx, z, q): + extra1 = 10 + extra2 = 20 + MIN = 2 + if z == ctx.zero: + if not ctx._im(q): + wp = ctx.prec + extra1 + x = ctx.to_fixed(ctx._re(q), wp) + s = x + a = b = x + x2 = (x*x) >> wp + while abs(a) > MIN: + b = (b*x2) >> wp + a = (a*b) >> wp + s += a + s = (1 << wp) + (s << 1) + s = ctx.ldexp(s, -wp) + return s + else: + wp = ctx.prec + extra1 + xre = ctx.to_fixed(ctx._re(q), wp) + xim = ctx.to_fixed(ctx._im(q), wp) + x2re = (xre*xre - xim*xim) >> wp + x2im = (xre*xim) >> (wp - 1) + sre = are = bre = xre + sim = aim = bim = xim + while are**2 + aim**2 > MIN: + bre, bim = (bre * x2re - bim * x2im) >> wp, \ + (bre * x2im + bim * x2re) >> wp + are, aim = (are * bre - aim * bim) >> wp, \ + (are * bim + aim * bre) >> wp + sre += are + sim += aim + sre = (1 << wp) + (sre << 1) + sim = (sim << 1) + sre = ctx.ldexp(sre, -wp) + sim = ctx.ldexp(sim, -wp) + s = ctx.mpc(sre, sim) + return s + else: + if (not ctx._im(q)) and (not ctx._im(z)): + s = 0 + wp = ctx.prec + extra1 + x = ctx.to_fixed(ctx._re(q), wp) + a = b = x + x2 = (x*x) >> wp + c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp) + c1 = ctx.to_fixed(c1, wp) + s1 = ctx.to_fixed(s1, wp) + cn = c1 + sn = s1 + s += (a * cn) >> wp + while abs(a) > MIN: + b = (b*x2) >> wp + a = (a*b) >> wp + cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp + s += (a * cn) >> wp + s = (1 << wp) + (s << 1) + s = ctx.ldexp(s, -wp) + return s + # case z real, q complex + elif not ctx._im(z): + wp = ctx.prec + extra2 + xre = ctx.to_fixed(ctx._re(q), wp) + xim = ctx.to_fixed(ctx._im(q), wp) + x2re = (xre*xre - xim*xim) >> wp + x2im = (xre*xim) >> (wp - 1) + are = bre = xre + aim = bim = xim + c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp) + c1 = ctx.to_fixed(c1, wp) + s1 = ctx.to_fixed(s1, wp) + cn = c1 + sn = s1 + sre = (are * cn) >> wp + sim = (aim * cn) >> wp + while are**2 + aim**2 > MIN: + bre, bim = (bre * x2re - bim * x2im) >> wp, \ + (bre * x2im + bim * x2re) >> wp + are, aim = (are * bre - aim * bim) >> wp, \ + (are * bim + aim * bre) >> wp + cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp + sre += (are * cn) >> wp + sim += (aim * cn) >> wp + sre = (1 << wp) + (sre << 1) + sim = (sim << 1) + sre = ctx.ldexp(sre, -wp) + sim = ctx.ldexp(sim, -wp) + s = ctx.mpc(sre, sim) + return s + #case z complex, q real + elif not ctx._im(q): + wp = ctx.prec + extra2 + x = ctx.to_fixed(ctx._re(q), wp) + a = b = x + x2 = (x*x) >> wp + prec0 = ctx.prec + ctx.prec = wp + c1, s1 = ctx.cos_sin(2*z) + ctx.prec = prec0 + cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) + cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) + snre = s1re = ctx.to_fixed(ctx._re(s1), wp) + snim = s1im = ctx.to_fixed(ctx._im(s1), wp) + sre = (a * cnre) >> wp + sim = (a * cnim) >> wp + while abs(a) > MIN: + b = (b*x2) >> wp + a = (a*b) >> wp + t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp + t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp + t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp + t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp + cnre = t1 + cnim = t2 + snre = t3 + snim = t4 + sre += (a * cnre) >> wp + sim += (a * cnim) >> wp + sre = (1 << wp) + (sre << 1) + sim = (sim << 1) + sre = ctx.ldexp(sre, -wp) + sim = ctx.ldexp(sim, -wp) + s = ctx.mpc(sre, sim) + return s + # case z and q complex + else: + wp = ctx.prec + extra2 + xre = ctx.to_fixed(ctx._re(q), wp) + xim = ctx.to_fixed(ctx._im(q), wp) + x2re = (xre*xre - xim*xim) >> wp + x2im = (xre*xim) >> (wp - 1) + are = bre = xre + aim = bim = xim + prec0 = ctx.prec + ctx.prec = wp + # cos(2*z), sin(2*z) with z complex + c1, s1 = ctx.cos_sin(2*z) + ctx.prec = prec0 + cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) + cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) + snre = s1re = ctx.to_fixed(ctx._re(s1), wp) + snim = s1im = ctx.to_fixed(ctx._im(s1), wp) + sre = (are * cnre - aim * cnim) >> wp + sim = (aim * cnre + are * cnim) >> wp + while are**2 + aim**2 > MIN: + bre, bim = (bre * x2re - bim * x2im) >> wp, \ + (bre * x2im + bim * x2re) >> wp + are, aim = (are * bre - aim * bim) >> wp, \ + (are * bim + aim * bre) >> wp + t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp + t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp + t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp + t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp + cnre = t1 + cnim = t2 + snre = t3 + snim = t4 + sre += (are * cnre - aim * cnim) >> wp + sim += (aim * cnre + are * cnim) >> wp + sre = (1 << wp) + (sre << 1) + sim = (sim << 1) + sre = ctx.ldexp(sre, -wp) + sim = ctx.ldexp(sim, -wp) + s = ctx.mpc(sre, sim) + return s + +@defun +def _djacobi_theta3(ctx, z, q, nd): + """nd=1,2,3 order of the derivative with respect to z""" + MIN = 2 + extra1 = 10 + extra2 = 20 + if (not ctx._im(q)) and (not ctx._im(z)): + s = 0 + wp = ctx.prec + extra1 + x = ctx.to_fixed(ctx._re(q), wp) + a = b = x + x2 = (x*x) >> wp + c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp) + c1 = ctx.to_fixed(c1, wp) + s1 = ctx.to_fixed(s1, wp) + cn = c1 + sn = s1 + if (nd&1): + s += (a * sn) >> wp + else: + s += (a * cn) >> wp + n = 2 + while abs(a) > MIN: + b = (b*x2) >> wp + a = (a*b) >> wp + cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp + if nd&1: + s += (a * sn * n**nd) >> wp + else: + s += (a * cn * n**nd) >> wp + n += 1 + s = -(s << (nd+1)) + s = ctx.ldexp(s, -wp) + # case z real, q complex + elif not ctx._im(z): + wp = ctx.prec + extra2 + xre = ctx.to_fixed(ctx._re(q), wp) + xim = ctx.to_fixed(ctx._im(q), wp) + x2re = (xre*xre - xim*xim) >> wp + x2im = (xre*xim) >> (wp - 1) + are = bre = xre + aim = bim = xim + c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp) + c1 = ctx.to_fixed(c1, wp) + s1 = ctx.to_fixed(s1, wp) + cn = c1 + sn = s1 + if (nd&1): + sre = (are * sn) >> wp + sim = (aim * sn) >> wp + else: + sre = (are * cn) >> wp + sim = (aim * cn) >> wp + n = 2 + while are**2 + aim**2 > MIN: + bre, bim = (bre * x2re - bim * x2im) >> wp, \ + (bre * x2im + bim * x2re) >> wp + are, aim = (are * bre - aim * bim) >> wp, \ + (are * bim + aim * bre) >> wp + cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp + if nd&1: + sre += (are * sn * n**nd) >> wp + sim += (aim * sn * n**nd) >> wp + else: + sre += (are * cn * n**nd) >> wp + sim += (aim * cn * n**nd) >> wp + n += 1 + sre = -(sre << (nd+1)) + sim = -(sim << (nd+1)) + sre = ctx.ldexp(sre, -wp) + sim = ctx.ldexp(sim, -wp) + s = ctx.mpc(sre, sim) + #case z complex, q real + elif not ctx._im(q): + wp = ctx.prec + extra2 + x = ctx.to_fixed(ctx._re(q), wp) + a = b = x + x2 = (x*x) >> wp + prec0 = ctx.prec + ctx.prec = wp + c1, s1 = ctx.cos_sin(2*z) + ctx.prec = prec0 + cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) + cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) + snre = s1re = ctx.to_fixed(ctx._re(s1), wp) + snim = s1im = ctx.to_fixed(ctx._im(s1), wp) + if (nd&1): + sre = (a * snre) >> wp + sim = (a * snim) >> wp + else: + sre = (a * cnre) >> wp + sim = (a * cnim) >> wp + n = 2 + while abs(a) > MIN: + b = (b*x2) >> wp + a = (a*b) >> wp + t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp + t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp + t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp + t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp + cnre = t1 + cnim = t2 + snre = t3 + snim = t4 + if (nd&1): + sre += (a * snre * n**nd) >> wp + sim += (a * snim * n**nd) >> wp + else: + sre += (a * cnre * n**nd) >> wp + sim += (a * cnim * n**nd) >> wp + n += 1 + sre = -(sre << (nd+1)) + sim = -(sim << (nd+1)) + sre = ctx.ldexp(sre, -wp) + sim = ctx.ldexp(sim, -wp) + s = ctx.mpc(sre, sim) + # case z and q complex + else: + wp = ctx.prec + extra2 + xre = ctx.to_fixed(ctx._re(q), wp) + xim = ctx.to_fixed(ctx._im(q), wp) + x2re = (xre*xre - xim*xim) >> wp + x2im = (xre*xim) >> (wp - 1) + are = bre = xre + aim = bim = xim + prec0 = ctx.prec + ctx.prec = wp + # cos(2*z), sin(2*z) with z complex + c1, s1 = ctx.cos_sin(2*z) + ctx.prec = prec0 + cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) + cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) + snre = s1re = ctx.to_fixed(ctx._re(s1), wp) + snim = s1im = ctx.to_fixed(ctx._im(s1), wp) + if (nd&1): + sre = (are * snre - aim * snim) >> wp + sim = (aim * snre + are * snim) >> wp + else: + sre = (are * cnre - aim * cnim) >> wp + sim = (aim * cnre + are * cnim) >> wp + n = 2 + while are**2 + aim**2 > MIN: + bre, bim = (bre * x2re - bim * x2im) >> wp, \ + (bre * x2im + bim * x2re) >> wp + are, aim = (are * bre - aim * bim) >> wp, \ + (are * bim + aim * bre) >> wp + t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp + t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp + t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp + t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp + cnre = t1 + cnim = t2 + snre = t3 + snim = t4 + if(nd&1): + sre += ((are * snre - aim * snim) * n**nd) >> wp + sim += ((aim * snre + are * snim) * n**nd) >> wp + else: + sre += ((are * cnre - aim * cnim) * n**nd) >> wp + sim += ((aim * cnre + are * cnim) * n**nd) >> wp + n += 1 + sre = -(sre << (nd+1)) + sim = -(sim << (nd+1)) + sre = ctx.ldexp(sre, -wp) + sim = ctx.ldexp(sim, -wp) + s = ctx.mpc(sre, sim) + if (nd&1): + return (-1)**(nd//2) * s + else: + return (-1)**(1 + nd//2) * s + +@defun +def _jacobi_theta2a(ctx, z, q): + """ + case ctx._im(z) != 0 + theta(2, z, q) = + q**1/4 * Sum(q**(n*n + n) * exp(j*(2*n + 1)*z), n=-inf, inf) + max term for minimum (2*n+1)*log(q).real - 2* ctx._im(z) + n0 = int(ctx._im(z)/log(q).real - 1/2) + theta(2, z, q) = + q**1/4 * Sum(q**(n*n + n) * exp(j*(2*n + 1)*z), n=n0, inf) + + q**1/4 * Sum(q**(n*n + n) * exp(j*(2*n + 1)*z), n, n0-1, -inf) + """ + n = n0 = int(ctx._im(z)/ctx._re(ctx.log(q)) - 1/2) + e2 = ctx.expj(2*z) + e = e0 = ctx.expj((2*n+1)*z) + a = q**(n*n + n) + # leading term + term = a * e + s = term + eps1 = ctx.eps*abs(term) + while 1: + n += 1 + e = e * e2 + term = q**(n*n + n) * e + if abs(term) < eps1: + break + s += term + e = e0 + e2 = ctx.expj(-2*z) + n = n0 + while 1: + n -= 1 + e = e * e2 + term = q**(n*n + n) * e + if abs(term) < eps1: + break + s += term + s = s * ctx.nthroot(q, 4) + return s + +@defun +def _jacobi_theta3a(ctx, z, q): + """ + case ctx._im(z) != 0 + theta3(z, q) = Sum(q**(n*n) * exp(j*2*n*z), n, -inf, inf) + max term for n*abs(log(q).real) + ctx._im(z) ~= 0 + n0 = int(- ctx._im(z)/abs(log(q).real)) + """ + n = n0 = int(-ctx._im(z)/abs(ctx._re(ctx.log(q)))) + e2 = ctx.expj(2*z) + e = e0 = ctx.expj(2*n*z) + s = term = q**(n*n) * e + eps1 = ctx.eps*abs(term) + while 1: + n += 1 + e = e * e2 + term = q**(n*n) * e + if abs(term) < eps1: + break + s += term + e = e0 + e2 = ctx.expj(-2*z) + n = n0 + while 1: + n -= 1 + e = e * e2 + term = q**(n*n) * e + if abs(term) < eps1: + break + s += term + return s + +@defun +def _djacobi_theta2a(ctx, z, q, nd): + """ + case ctx._im(z) != 0 + dtheta(2, z, q, nd) = + j* q**1/4 * Sum(q**(n*n + n) * (2*n+1)*exp(j*(2*n + 1)*z), n=-inf, inf) + max term for (2*n0+1)*log(q).real - 2* ctx._im(z) ~= 0 + n0 = int(ctx._im(z)/log(q).real - 1/2) + """ + n = n0 = int(ctx._im(z)/ctx._re(ctx.log(q)) - 1/2) + e2 = ctx.expj(2*z) + e = e0 = ctx.expj((2*n + 1)*z) + a = q**(n*n + n) + # leading term + term = (2*n+1)**nd * a * e + s = term + eps1 = ctx.eps*abs(term) + while 1: + n += 1 + e = e * e2 + term = (2*n+1)**nd * q**(n*n + n) * e + if abs(term) < eps1: + break + s += term + e = e0 + e2 = ctx.expj(-2*z) + n = n0 + while 1: + n -= 1 + e = e * e2 + term = (2*n+1)**nd * q**(n*n + n) * e + if abs(term) < eps1: + break + s += term + return ctx.j**nd * s * ctx.nthroot(q, 4) + +@defun +def _djacobi_theta3a(ctx, z, q, nd): + """ + case ctx._im(z) != 0 + djtheta3(z, q, nd) = (2*j)**nd * + Sum(q**(n*n) * n**nd * exp(j*2*n*z), n, -inf, inf) + max term for minimum n*abs(log(q).real) + ctx._im(z) + """ + n = n0 = int(-ctx._im(z)/abs(ctx._re(ctx.log(q)))) + e2 = ctx.expj(2*z) + e = e0 = ctx.expj(2*n*z) + a = q**(n*n) * e + s = term = n**nd * a + if n != 0: + eps1 = ctx.eps*abs(term) + else: + eps1 = ctx.eps*abs(a) + while 1: + n += 1 + e = e * e2 + a = q**(n*n) * e + term = n**nd * a + if n != 0: + aterm = abs(term) + else: + aterm = abs(a) + if aterm < eps1: + break + s += term + e = e0 + e2 = ctx.expj(-2*z) + n = n0 + while 1: + n -= 1 + e = e * e2 + a = q**(n*n) * e + term = n**nd * a + if n != 0: + aterm = abs(term) + else: + aterm = abs(a) + if aterm < eps1: + break + s += term + return (2*ctx.j)**nd * s + +@defun +def jtheta(ctx, n, z, q, derivative=0): + if derivative: + return ctx._djtheta(n, z, q, derivative) + + z = ctx.convert(z) + q = ctx.convert(q) + + # Implementation note + # If ctx._im(z) is close to zero, _jacobi_theta2 and _jacobi_theta3 + # are used, + # which compute the series starting from n=0 using fixed precision + # numbers; + # otherwise _jacobi_theta2a and _jacobi_theta3a are used, which compute + # the series starting from n=n0, which is the largest term. + + # TODO: write _jacobi_theta2a and _jacobi_theta3a using fixed-point + + if abs(q) > ctx.THETA_Q_LIM: + raise ValueError('abs(q) > THETA_Q_LIM = %f' % ctx.THETA_Q_LIM) + + extra = 10 + if z: + M = ctx.mag(z) + if M > 5 or (n == 1 and M < -5): + extra += 2*abs(M) + cz = 0.5 + extra2 = 50 + prec0 = ctx.prec + try: + ctx.prec += extra + if n == 1: + if ctx._im(z): + if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): + ctx.dps += extra2 + res = ctx._jacobi_theta2(z - ctx.pi/2, q) + else: + ctx.dps += 10 + res = ctx._jacobi_theta2a(z - ctx.pi/2, q) + else: + res = ctx._jacobi_theta2(z - ctx.pi/2, q) + elif n == 2: + if ctx._im(z): + if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): + ctx.dps += extra2 + res = ctx._jacobi_theta2(z, q) + else: + ctx.dps += 10 + res = ctx._jacobi_theta2a(z, q) + else: + res = ctx._jacobi_theta2(z, q) + elif n == 3: + if ctx._im(z): + if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): + ctx.dps += extra2 + res = ctx._jacobi_theta3(z, q) + else: + ctx.dps += 10 + res = ctx._jacobi_theta3a(z, q) + else: + res = ctx._jacobi_theta3(z, q) + elif n == 4: + if ctx._im(z): + if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): + ctx.dps += extra2 + res = ctx._jacobi_theta3(z, -q) + else: + ctx.dps += 10 + res = ctx._jacobi_theta3a(z, -q) + else: + res = ctx._jacobi_theta3(z, -q) + else: + raise ValueError + finally: + ctx.prec = prec0 + return res + +@defun +def _djtheta(ctx, n, z, q, derivative=1): + z = ctx.convert(z) + q = ctx.convert(q) + nd = int(derivative) + + if abs(q) > ctx.THETA_Q_LIM: + raise ValueError('abs(q) > THETA_Q_LIM = %f' % ctx.THETA_Q_LIM) + extra = 10 + ctx.prec * nd // 10 + if z: + M = ctx.mag(z) + if M > 5 or (n != 1 and M < -5): + extra += 2*abs(M) + cz = 0.5 + extra2 = 50 + prec0 = ctx.prec + try: + ctx.prec += extra + if n == 1: + if ctx._im(z): + if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): + ctx.dps += extra2 + res = ctx._djacobi_theta2(z - ctx.pi/2, q, nd) + else: + ctx.dps += 10 + res = ctx._djacobi_theta2a(z - ctx.pi/2, q, nd) + else: + res = ctx._djacobi_theta2(z - ctx.pi/2, q, nd) + elif n == 2: + if ctx._im(z): + if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): + ctx.dps += extra2 + res = ctx._djacobi_theta2(z, q, nd) + else: + ctx.dps += 10 + res = ctx._djacobi_theta2a(z, q, nd) + else: + res = ctx._djacobi_theta2(z, q, nd) + elif n == 3: + if ctx._im(z): + if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): + ctx.dps += extra2 + res = ctx._djacobi_theta3(z, q, nd) + else: + ctx.dps += 10 + res = ctx._djacobi_theta3a(z, q, nd) + else: + res = ctx._djacobi_theta3(z, q, nd) + elif n == 4: + if ctx._im(z): + if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): + ctx.dps += extra2 + res = ctx._djacobi_theta3(z, -q, nd) + else: + ctx.dps += 10 + res = ctx._djacobi_theta3a(z, -q, nd) + else: + res = ctx._djacobi_theta3(z, -q, nd) + else: + raise ValueError + finally: + ctx.prec = prec0 + return +res diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/zeta.py b/venv/lib/python3.10/site-packages/mpmath/functions/zeta.py new file mode 100644 index 0000000000000000000000000000000000000000..d7ede50d95e5b6eff511619620c934529942cbdd --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/functions/zeta.py @@ -0,0 +1,1154 @@ +from __future__ import print_function + +from ..libmp.backend import xrange +from .functions import defun, defun_wrapped, defun_static + +@defun +def stieltjes(ctx, n, a=1): + n = ctx.convert(n) + a = ctx.convert(a) + if n < 0: + return ctx.bad_domain("Stieltjes constants defined for n >= 0") + if hasattr(ctx, "stieltjes_cache"): + stieltjes_cache = ctx.stieltjes_cache + else: + stieltjes_cache = ctx.stieltjes_cache = {} + if a == 1: + if n == 0: + return +ctx.euler + if n in stieltjes_cache: + prec, s = stieltjes_cache[n] + if prec >= ctx.prec: + return +s + mag = 1 + def f(x): + xa = x/a + v = (xa-ctx.j)*ctx.ln(a-ctx.j*x)**n/(1+xa**2)/(ctx.exp(2*ctx.pi*x)-1) + return ctx._re(v) / mag + orig = ctx.prec + try: + # Normalize integrand by approx. magnitude to + # speed up quadrature (which uses absolute error) + if n > 50: + ctx.prec = 20 + mag = ctx.quad(f, [0,ctx.inf], maxdegree=3) + ctx.prec = orig + 10 + int(n**0.5) + s = ctx.quad(f, [0,ctx.inf], maxdegree=20) + v = ctx.ln(a)**n/(2*a) - ctx.ln(a)**(n+1)/(n+1) + 2*s/a*mag + finally: + ctx.prec = orig + if a == 1 and ctx.isint(n): + stieltjes_cache[n] = (ctx.prec, v) + return +v + +@defun_wrapped +def siegeltheta(ctx, t, derivative=0): + d = int(derivative) + if (t == ctx.inf or t == ctx.ninf): + if d < 2: + if t == ctx.ninf and d == 0: + return ctx.ninf + return ctx.inf + else: + return ctx.zero + if d == 0: + if ctx._im(t): + # XXX: cancellation occurs + a = ctx.loggamma(0.25+0.5j*t) + b = ctx.loggamma(0.25-0.5j*t) + return -ctx.ln(ctx.pi)/2*t - 0.5j*(a-b) + else: + if ctx.isinf(t): + return t + return ctx._im(ctx.loggamma(0.25+0.5j*t)) - ctx.ln(ctx.pi)/2*t + if d > 0: + a = (-0.5j)**(d-1)*ctx.polygamma(d-1, 0.25-0.5j*t) + b = (0.5j)**(d-1)*ctx.polygamma(d-1, 0.25+0.5j*t) + if ctx._im(t): + if d == 1: + return -0.5*ctx.log(ctx.pi)+0.25*(a+b) + else: + return 0.25*(a+b) + else: + if d == 1: + return ctx._re(-0.5*ctx.log(ctx.pi)+0.25*(a+b)) + else: + return ctx._re(0.25*(a+b)) + +@defun_wrapped +def grampoint(ctx, n): + # asymptotic expansion, from + # http://mathworld.wolfram.com/GramPoint.html + g = 2*ctx.pi*ctx.exp(1+ctx.lambertw((8*n+1)/(8*ctx.e))) + return ctx.findroot(lambda t: ctx.siegeltheta(t)-ctx.pi*n, g) + + +@defun_wrapped +def siegelz(ctx, t, **kwargs): + d = int(kwargs.get("derivative", 0)) + t = ctx.convert(t) + t1 = ctx._re(t) + t2 = ctx._im(t) + prec = ctx.prec + try: + if abs(t1) > 500*prec and t2**2 < t1: + v = ctx.rs_z(t, d) + if ctx._is_real_type(t): + return ctx._re(v) + return v + except NotImplementedError: + pass + ctx.prec += 21 + e1 = ctx.expj(ctx.siegeltheta(t)) + z = ctx.zeta(0.5+ctx.j*t) + if d == 0: + v = e1*z + ctx.prec=prec + if ctx._is_real_type(t): + return ctx._re(v) + return +v + z1 = ctx.zeta(0.5+ctx.j*t, derivative=1) + theta1 = ctx.siegeltheta(t, derivative=1) + if d == 1: + v = ctx.j*e1*(z1+z*theta1) + ctx.prec=prec + if ctx._is_real_type(t): + return ctx._re(v) + return +v + z2 = ctx.zeta(0.5+ctx.j*t, derivative=2) + theta2 = ctx.siegeltheta(t, derivative=2) + comb1 = theta1**2-ctx.j*theta2 + if d == 2: + def terms(): + return [2*z1*theta1, z2, z*comb1] + v = ctx.sum_accurately(terms, 1) + v = -e1*v + ctx.prec = prec + if ctx._is_real_type(t): + return ctx._re(v) + return +v + ctx.prec += 10 + z3 = ctx.zeta(0.5+ctx.j*t, derivative=3) + theta3 = ctx.siegeltheta(t, derivative=3) + comb2 = theta1**3-3*ctx.j*theta1*theta2-theta3 + if d == 3: + def terms(): + return [3*theta1*z2, 3*z1*comb1, z3+z*comb2] + v = ctx.sum_accurately(terms, 1) + v = -ctx.j*e1*v + ctx.prec = prec + if ctx._is_real_type(t): + return ctx._re(v) + return +v + z4 = ctx.zeta(0.5+ctx.j*t, derivative=4) + theta4 = ctx.siegeltheta(t, derivative=4) + def terms(): + return [theta1**4, -6*ctx.j*theta1**2*theta2, -3*theta2**2, + -4*theta1*theta3, ctx.j*theta4] + comb3 = ctx.sum_accurately(terms, 1) + if d == 4: + def terms(): + return [6*theta1**2*z2, -6*ctx.j*z2*theta2, 4*theta1*z3, + 4*z1*comb2, z4, z*comb3] + v = ctx.sum_accurately(terms, 1) + v = e1*v + ctx.prec = prec + if ctx._is_real_type(t): + return ctx._re(v) + return +v + if d > 4: + h = lambda x: ctx.siegelz(x, derivative=4) + return ctx.diff(h, t, n=d-4) + + +_zeta_zeros = [ +14.134725142,21.022039639,25.010857580,30.424876126,32.935061588, +37.586178159,40.918719012,43.327073281,48.005150881,49.773832478, +52.970321478,56.446247697,59.347044003,60.831778525,65.112544048, +67.079810529,69.546401711,72.067157674,75.704690699,77.144840069, +79.337375020,82.910380854,84.735492981,87.425274613,88.809111208, +92.491899271,94.651344041,95.870634228,98.831194218,101.317851006, +103.725538040,105.446623052,107.168611184,111.029535543,111.874659177, +114.320220915,116.226680321,118.790782866,121.370125002,122.946829294, +124.256818554,127.516683880,129.578704200,131.087688531,133.497737203, +134.756509753,138.116042055,139.736208952,141.123707404,143.111845808, +146.000982487,147.422765343,150.053520421,150.925257612,153.024693811, +156.112909294,157.597591818,158.849988171,161.188964138,163.030709687, +165.537069188,167.184439978,169.094515416,169.911976479,173.411536520, +174.754191523,176.441434298,178.377407776,179.916484020,182.207078484, +184.874467848,185.598783678,187.228922584,189.416158656,192.026656361, +193.079726604,195.265396680,196.876481841,198.015309676,201.264751944, +202.493594514,204.189671803,205.394697202,207.906258888,209.576509717, +211.690862595,213.347919360,214.547044783,216.169538508,219.067596349, +220.714918839,221.430705555,224.007000255,224.983324670,227.421444280, +229.337413306,231.250188700,231.987235253,233.693404179,236.524229666, +] + +def _load_zeta_zeros(url): + import urllib + d = urllib.urlopen(url) + L = [float(x) for x in d.readlines()] + # Sanity check + assert round(L[0]) == 14 + _zeta_zeros[:] = L + +@defun +def oldzetazero(ctx, n, url='http://www.dtc.umn.edu/~odlyzko/zeta_tables/zeros1'): + n = int(n) + if n < 0: + return ctx.zetazero(-n).conjugate() + if n == 0: + raise ValueError("n must be nonzero") + if n > len(_zeta_zeros) and n <= 100000: + _load_zeta_zeros(url) + if n > len(_zeta_zeros): + raise NotImplementedError("n too large for zetazeros") + return ctx.mpc(0.5, ctx.findroot(ctx.siegelz, _zeta_zeros[n-1])) + +@defun_wrapped +def riemannr(ctx, x): + if x == 0: + return ctx.zero + # Check if a simple asymptotic estimate is accurate enough + if abs(x) > 1000: + a = ctx.li(x) + b = 0.5*ctx.li(ctx.sqrt(x)) + if abs(b) < abs(a)*ctx.eps: + return a + if abs(x) < 0.01: + # XXX + ctx.prec += int(-ctx.log(abs(x),2)) + # Sum Gram's series + s = t = ctx.one + u = ctx.ln(x) + k = 1 + while abs(t) > abs(s)*ctx.eps: + t = t * u / k + s += t / (k * ctx._zeta_int(k+1)) + k += 1 + return s + +@defun_static +def primepi(ctx, x): + x = int(x) + if x < 2: + return 0 + return len(ctx.list_primes(x)) + +# TODO: fix the interface wrt contexts +@defun_wrapped +def primepi2(ctx, x): + x = int(x) + if x < 2: + return ctx._iv.zero + if x < 2657: + return ctx._iv.mpf(ctx.primepi(x)) + mid = ctx.li(x) + # Schoenfeld's estimate for x >= 2657, assuming RH + err = ctx.sqrt(x,rounding='u')*ctx.ln(x,rounding='u')/8/ctx.pi(rounding='d') + a = ctx.floor((ctx._iv.mpf(mid)-err).a, rounding='d') + b = ctx.ceil((ctx._iv.mpf(mid)+err).b, rounding='u') + return ctx._iv.mpf([a,b]) + +@defun_wrapped +def primezeta(ctx, s): + if ctx.isnan(s): + return s + if ctx.re(s) <= 0: + raise ValueError("prime zeta function defined only for re(s) > 0") + if s == 1: + return ctx.inf + if s == 0.5: + return ctx.mpc(ctx.ninf, ctx.pi) + r = ctx.re(s) + if r > ctx.prec: + return 0.5**s + else: + wp = ctx.prec + int(r) + def terms(): + orig = ctx.prec + # zeta ~ 1+eps; need to set precision + # to get logarithm accurately + k = 0 + while 1: + k += 1 + u = ctx.moebius(k) + if not u: + continue + ctx.prec = wp + t = u*ctx.ln(ctx.zeta(k*s))/k + if not t: + return + #print ctx.prec, ctx.nstr(t) + ctx.prec = orig + yield t + return ctx.sum_accurately(terms) + +# TODO: for bernpoly and eulerpoly, ensure that all exact zeros are covered + +@defun_wrapped +def bernpoly(ctx, n, z): + # Slow implementation: + #return sum(ctx.binomial(n,k)*ctx.bernoulli(k)*z**(n-k) for k in xrange(0,n+1)) + n = int(n) + if n < 0: + raise ValueError("Bernoulli polynomials only defined for n >= 0") + if z == 0 or (z == 1 and n > 1): + return ctx.bernoulli(n) + if z == 0.5: + return (ctx.ldexp(1,1-n)-1)*ctx.bernoulli(n) + if n <= 3: + if n == 0: return z ** 0 + if n == 1: return z - 0.5 + if n == 2: return (6*z*(z-1)+1)/6 + if n == 3: return z*(z*(z-1.5)+0.5) + if ctx.isinf(z): + return z ** n + if ctx.isnan(z): + return z + if abs(z) > 2: + def terms(): + t = ctx.one + yield t + r = ctx.one/z + k = 1 + while k <= n: + t = t*(n+1-k)/k*r + if not (k > 2 and k & 1): + yield t*ctx.bernoulli(k) + k += 1 + return ctx.sum_accurately(terms) * z**n + else: + def terms(): + yield ctx.bernoulli(n) + t = ctx.one + k = 1 + while k <= n: + t = t*(n+1-k)/k * z + m = n-k + if not (m > 2 and m & 1): + yield t*ctx.bernoulli(m) + k += 1 + return ctx.sum_accurately(terms) + +@defun_wrapped +def eulerpoly(ctx, n, z): + n = int(n) + if n < 0: + raise ValueError("Euler polynomials only defined for n >= 0") + if n <= 2: + if n == 0: return z ** 0 + if n == 1: return z - 0.5 + if n == 2: return z*(z-1) + if ctx.isinf(z): + return z**n + if ctx.isnan(z): + return z + m = n+1 + if z == 0: + return -2*(ctx.ldexp(1,m)-1)*ctx.bernoulli(m)/m * z**0 + if z == 1: + return 2*(ctx.ldexp(1,m)-1)*ctx.bernoulli(m)/m * z**0 + if z == 0.5: + if n % 2: + return ctx.zero + # Use exact code for Euler numbers + if n < 100 or n*ctx.mag(0.46839865*n) < ctx.prec*0.25: + return ctx.ldexp(ctx._eulernum(n), -n) + # http://functions.wolfram.com/Polynomials/EulerE2/06/01/02/01/0002/ + def terms(): + t = ctx.one + k = 0 + w = ctx.ldexp(1,n+2) + while 1: + v = n-k+1 + if not (v > 2 and v & 1): + yield (2-w)*ctx.bernoulli(v)*t + k += 1 + if k > n: + break + t = t*z*(n-k+2)/k + w *= 0.5 + return ctx.sum_accurately(terms) / m + +@defun +def eulernum(ctx, n, exact=False): + n = int(n) + if exact: + return int(ctx._eulernum(n)) + if n < 100: + return ctx.mpf(ctx._eulernum(n)) + if n % 2: + return ctx.zero + return ctx.ldexp(ctx.eulerpoly(n,0.5), n) + +# TODO: this should be implemented low-level +def polylog_series(ctx, s, z): + tol = +ctx.eps + l = ctx.zero + k = 1 + zk = z + while 1: + term = zk / k**s + l += term + if abs(term) < tol: + break + zk *= z + k += 1 + return l + +def polylog_continuation(ctx, n, z): + if n < 0: + return z*0 + twopij = 2j * ctx.pi + a = -twopij**n/ctx.fac(n) * ctx.bernpoly(n, ctx.ln(z)/twopij) + if ctx._is_real_type(z) and z < 0: + a = ctx._re(a) + if ctx._im(z) < 0 or (ctx._im(z) == 0 and ctx._re(z) >= 1): + a -= twopij*ctx.ln(z)**(n-1)/ctx.fac(n-1) + return a + +def polylog_unitcircle(ctx, n, z): + tol = +ctx.eps + if n > 1: + l = ctx.zero + logz = ctx.ln(z) + logmz = ctx.one + m = 0 + while 1: + if (n-m) != 1: + term = ctx.zeta(n-m) * logmz / ctx.fac(m) + if term and abs(term) < tol: + break + l += term + logmz *= logz + m += 1 + l += ctx.ln(z)**(n-1)/ctx.fac(n-1)*(ctx.harmonic(n-1)-ctx.ln(-ctx.ln(z))) + elif n < 1: # else + l = ctx.fac(-n)*(-ctx.ln(z))**(n-1) + logz = ctx.ln(z) + logkz = ctx.one + k = 0 + while 1: + b = ctx.bernoulli(k-n+1) + if b: + term = b*logkz/(ctx.fac(k)*(k-n+1)) + if abs(term) < tol: + break + l -= term + logkz *= logz + k += 1 + else: + raise ValueError + if ctx._is_real_type(z) and z < 0: + l = ctx._re(l) + return l + +def polylog_general(ctx, s, z): + v = ctx.zero + u = ctx.ln(z) + if not abs(u) < 5: # theoretically |u| < 2*pi + j = ctx.j + v = 1-s + y = ctx.ln(-z)/(2*ctx.pi*j) + return ctx.gamma(v)*(j**v*ctx.zeta(v,0.5+y) + j**-v*ctx.zeta(v,0.5-y))/(2*ctx.pi)**v + t = 1 + k = 0 + while 1: + term = ctx.zeta(s-k) * t + if abs(term) < ctx.eps: + break + v += term + k += 1 + t *= u + t /= k + return ctx.gamma(1-s)*(-u)**(s-1) + v + +@defun_wrapped +def polylog(ctx, s, z): + s = ctx.convert(s) + z = ctx.convert(z) + if z == 1: + return ctx.zeta(s) + if z == -1: + return -ctx.altzeta(s) + if s == 0: + return z/(1-z) + if s == 1: + return -ctx.ln(1-z) + if s == -1: + return z/(1-z)**2 + if abs(z) <= 0.75 or (not ctx.isint(s) and abs(z) < 0.9): + return polylog_series(ctx, s, z) + if abs(z) >= 1.4 and ctx.isint(s): + return (-1)**(s+1)*polylog_series(ctx, s, 1/z) + polylog_continuation(ctx, int(ctx.re(s)), z) + if ctx.isint(s): + return polylog_unitcircle(ctx, int(ctx.re(s)), z) + return polylog_general(ctx, s, z) + +@defun_wrapped +def clsin(ctx, s, z, pi=False): + if ctx.isint(s) and s < 0 and int(s) % 2 == 1: + return z*0 + if pi: + a = ctx.expjpi(z) + else: + a = ctx.expj(z) + if ctx._is_real_type(z) and ctx._is_real_type(s): + return ctx.im(ctx.polylog(s,a)) + b = 1/a + return (-0.5j)*(ctx.polylog(s,a) - ctx.polylog(s,b)) + +@defun_wrapped +def clcos(ctx, s, z, pi=False): + if ctx.isint(s) and s < 0 and int(s) % 2 == 0: + return z*0 + if pi: + a = ctx.expjpi(z) + else: + a = ctx.expj(z) + if ctx._is_real_type(z) and ctx._is_real_type(s): + return ctx.re(ctx.polylog(s,a)) + b = 1/a + return 0.5*(ctx.polylog(s,a) + ctx.polylog(s,b)) + +@defun +def altzeta(ctx, s, **kwargs): + try: + return ctx._altzeta(s, **kwargs) + except NotImplementedError: + return ctx._altzeta_generic(s) + +@defun_wrapped +def _altzeta_generic(ctx, s): + if s == 1: + return ctx.ln2 + 0*s + return -ctx.powm1(2, 1-s) * ctx.zeta(s) + +@defun +def zeta(ctx, s, a=1, derivative=0, method=None, **kwargs): + d = int(derivative) + if a == 1 and not (d or method): + try: + return ctx._zeta(s, **kwargs) + except NotImplementedError: + pass + s = ctx.convert(s) + prec = ctx.prec + method = kwargs.get('method') + verbose = kwargs.get('verbose') + if (not s) and (not derivative): + return ctx.mpf(0.5) - ctx._convert_param(a)[0] + if a == 1 and method != 'euler-maclaurin': + im = abs(ctx._im(s)) + re = abs(ctx._re(s)) + #if (im < prec or method == 'borwein') and not derivative: + # try: + # if verbose: + # print "zeta: Attempting to use the Borwein algorithm" + # return ctx._zeta(s, **kwargs) + # except NotImplementedError: + # if verbose: + # print "zeta: Could not use the Borwein algorithm" + # pass + if abs(im) > 500*prec and 10*re < prec and derivative <= 4 or \ + method == 'riemann-siegel': + try: # py2.4 compatible try block + try: + if verbose: + print("zeta: Attempting to use the Riemann-Siegel algorithm") + return ctx.rs_zeta(s, derivative, **kwargs) + except NotImplementedError: + if verbose: + print("zeta: Could not use the Riemann-Siegel algorithm") + pass + finally: + ctx.prec = prec + if s == 1: + return ctx.inf + abss = abs(s) + if abss == ctx.inf: + if ctx.re(s) == ctx.inf: + if d == 0: + return ctx.one + return ctx.zero + return s*0 + elif ctx.isnan(abss): + return 1/s + if ctx.re(s) > 2*ctx.prec and a == 1 and not derivative: + return ctx.one + ctx.power(2, -s) + return +ctx._hurwitz(s, a, d, **kwargs) + +@defun +def _hurwitz(ctx, s, a=1, d=0, **kwargs): + prec = ctx.prec + verbose = kwargs.get('verbose') + try: + extraprec = 10 + ctx.prec += extraprec + # We strongly want to special-case rational a + a, atype = ctx._convert_param(a) + if ctx.re(s) < 0: + if verbose: + print("zeta: Attempting reflection formula") + try: + return _hurwitz_reflection(ctx, s, a, d, atype) + except NotImplementedError: + pass + if verbose: + print("zeta: Reflection formula failed") + if verbose: + print("zeta: Using the Euler-Maclaurin algorithm") + while 1: + ctx.prec = prec + extraprec + T1, T2 = _hurwitz_em(ctx, s, a, d, prec+10, verbose) + cancellation = ctx.mag(T1) - ctx.mag(T1+T2) + if verbose: + print("Term 1:", T1) + print("Term 2:", T2) + print("Cancellation:", cancellation, "bits") + if cancellation < extraprec: + return T1 + T2 + else: + extraprec = max(2*extraprec, min(cancellation + 5, 100*prec)) + if extraprec > kwargs.get('maxprec', 100*prec): + raise ctx.NoConvergence("zeta: too much cancellation") + finally: + ctx.prec = prec + +def _hurwitz_reflection(ctx, s, a, d, atype): + # TODO: implement for derivatives + if d != 0: + raise NotImplementedError + res = ctx.re(s) + negs = -s + # Integer reflection formula + if ctx.isnpint(s): + n = int(res) + if n <= 0: + return ctx.bernpoly(1-n, a) / (n-1) + if not (atype == 'Q' or atype == 'Z'): + raise NotImplementedError + t = 1-s + # We now require a to be standardized + v = 0 + shift = 0 + b = a + while ctx.re(b) > 1: + b -= 1 + v -= b**negs + shift -= 1 + while ctx.re(b) <= 0: + v += b**negs + b += 1 + shift += 1 + # Rational reflection formula + try: + p, q = a._mpq_ + except: + assert a == int(a) + p = int(a) + q = 1 + p += shift*q + assert 1 <= p <= q + g = ctx.fsum(ctx.cospi(t/2-2*k*b)*ctx._hurwitz(t,(k,q)) \ + for k in range(1,q+1)) + g *= 2*ctx.gamma(t)/(2*ctx.pi*q)**t + v += g + return v + +def _hurwitz_em(ctx, s, a, d, prec, verbose): + # May not be converted at this point + a = ctx.convert(a) + tol = -prec + # Estimate number of terms for Euler-Maclaurin summation; could be improved + M1 = 0 + M2 = prec // 3 + N = M2 + lsum = 0 + # This speeds up the recurrence for derivatives + if ctx.isint(s): + s = int(ctx._re(s)) + s1 = s-1 + while 1: + # Truncated L-series + l = ctx._zetasum(s, M1+a, M2-M1-1, [d])[0][0] + #if d: + # l = ctx.fsum((-ctx.ln(n+a))**d * (n+a)**negs for n in range(M1,M2)) + #else: + # l = ctx.fsum((n+a)**negs for n in range(M1,M2)) + lsum += l + M2a = M2+a + logM2a = ctx.ln(M2a) + logM2ad = logM2a**d + logs = [logM2ad] + logr = 1/logM2a + rM2a = 1/M2a + M2as = M2a**(-s) + if d: + tailsum = ctx.gammainc(d+1, s1*logM2a) / s1**(d+1) + else: + tailsum = 1/((s1)*(M2a)**s1) + tailsum += 0.5 * logM2ad * M2as + U = [1] + r = M2as + fact = 2 + for j in range(1, N+1): + # TODO: the following could perhaps be tidied a bit + j2 = 2*j + if j == 1: + upds = [1] + else: + upds = [j2-2, j2-1] + for m in upds: + D = min(m,d+1) + if m <= d: + logs.append(logs[-1] * logr) + Un = [0]*(D+1) + for i in xrange(D): Un[i] = (1-m-s)*U[i] + for i in xrange(1,D+1): Un[i] += (d-(i-1))*U[i-1] + U = Un + r *= rM2a + t = ctx.fdot(U, logs) * r * ctx.bernoulli(j2)/(-fact) + tailsum += t + if ctx.mag(t) < tol: + return lsum, (-1)**d * tailsum + fact *= (j2+1)*(j2+2) + if verbose: + print("Sum range:", M1, M2, "term magnitude", ctx.mag(t), "tolerance", tol) + M1, M2 = M2, M2*2 + if ctx.re(s) < 0: + N += N//2 + + + +@defun +def _zetasum(ctx, s, a, n, derivatives=[0], reflect=False): + """ + Returns [xd0,xd1,...,xdr], [yd0,yd1,...ydr] where + + xdk = D^k ( 1/a^s + 1/(a+1)^s + ... + 1/(a+n)^s ) + ydk = D^k conj( 1/a^(1-s) + 1/(a+1)^(1-s) + ... + 1/(a+n)^(1-s) ) + + D^k = kth derivative with respect to s, k ranges over the given list of + derivatives (which should consist of either a single element + or a range 0,1,...r). If reflect=False, the ydks are not computed. + """ + #print "zetasum", s, a, n + # don't use the fixed-point code if there are large exponentials + if abs(ctx.re(s)) < 0.5 * ctx.prec: + try: + return ctx._zetasum_fast(s, a, n, derivatives, reflect) + except NotImplementedError: + pass + negs = ctx.fneg(s, exact=True) + have_derivatives = derivatives != [0] + have_one_derivative = len(derivatives) == 1 + if not reflect: + if not have_derivatives: + return [ctx.fsum((a+k)**negs for k in xrange(n+1))], [] + if have_one_derivative: + d = derivatives[0] + x = ctx.fsum(ctx.ln(a+k)**d * (a+k)**negs for k in xrange(n+1)) + return [(-1)**d * x], [] + maxd = max(derivatives) + if not have_one_derivative: + derivatives = range(maxd+1) + xs = [ctx.zero for d in derivatives] + if reflect: + ys = [ctx.zero for d in derivatives] + else: + ys = [] + for k in xrange(n+1): + w = a + k + xterm = w ** negs + if reflect: + yterm = ctx.conj(ctx.one / (w * xterm)) + if have_derivatives: + logw = -ctx.ln(w) + if have_one_derivative: + logw = logw ** maxd + xs[0] += xterm * logw + if reflect: + ys[0] += yterm * logw + else: + t = ctx.one + for d in derivatives: + xs[d] += xterm * t + if reflect: + ys[d] += yterm * t + t *= logw + else: + xs[0] += xterm + if reflect: + ys[0] += yterm + return xs, ys + +@defun +def dirichlet(ctx, s, chi=[1], derivative=0): + s = ctx.convert(s) + q = len(chi) + d = int(derivative) + if d > 2: + raise NotImplementedError("arbitrary order derivatives") + prec = ctx.prec + try: + ctx.prec += 10 + if s == 1: + have_pole = True + for x in chi: + if x and x != 1: + have_pole = False + h = +ctx.eps + ctx.prec *= 2*(d+1) + s += h + if have_pole: + return +ctx.inf + z = ctx.zero + for p in range(1,q+1): + if chi[p%q]: + if d == 1: + z += chi[p%q] * (ctx.zeta(s, (p,q), 1) - \ + ctx.zeta(s, (p,q))*ctx.log(q)) + else: + z += chi[p%q] * ctx.zeta(s, (p,q)) + z /= q**s + finally: + ctx.prec = prec + return +z + + +def secondzeta_main_term(ctx, s, a, **kwargs): + tol = ctx.eps + f = lambda n: ctx.gammainc(0.5*s, a*gamm**2, regularized=True)*gamm**(-s) + totsum = term = ctx.zero + mg = ctx.inf + n = 0 + while mg > tol: + totsum += term + n += 1 + gamm = ctx.im(ctx.zetazero_memoized(n)) + term = f(n) + mg = abs(term) + err = 0 + if kwargs.get("error"): + sg = ctx.re(s) + err = 0.5*ctx.pi**(-1)*max(1,sg)*a**(sg-0.5)*ctx.log(gamm/(2*ctx.pi))*\ + ctx.gammainc(-0.5, a*gamm**2)/abs(ctx.gamma(s/2)) + err = abs(err) + return +totsum, err, n + +def secondzeta_prime_term(ctx, s, a, **kwargs): + tol = ctx.eps + f = lambda n: ctx.gammainc(0.5*(1-s),0.25*ctx.log(n)**2 * a**(-1))*\ + ((0.5*ctx.log(n))**(s-1))*ctx.mangoldt(n)/ctx.sqrt(n)/\ + (2*ctx.gamma(0.5*s)*ctx.sqrt(ctx.pi)) + totsum = term = ctx.zero + mg = ctx.inf + n = 1 + while mg > tol or n < 9: + totsum += term + n += 1 + term = f(n) + if term == 0: + mg = ctx.inf + else: + mg = abs(term) + if kwargs.get("error"): + err = mg + return +totsum, err, n + +def secondzeta_exp_term(ctx, s, a): + if ctx.isint(s) and ctx.re(s) <= 0: + m = int(round(ctx.re(s))) + if not m & 1: + return ctx.mpf('-0.25')**(-m//2) + tol = ctx.eps + f = lambda n: (0.25*a)**n/((n+0.5*s)*ctx.fac(n)) + totsum = ctx.zero + term = f(0) + mg = ctx.inf + n = 0 + while mg > tol: + totsum += term + n += 1 + term = f(n) + mg = abs(term) + v = a**(0.5*s)*totsum/ctx.gamma(0.5*s) + return v + +def secondzeta_singular_term(ctx, s, a, **kwargs): + factor = a**(0.5*(s-1))/(4*ctx.sqrt(ctx.pi)*ctx.gamma(0.5*s)) + extraprec = ctx.mag(factor) + ctx.prec += extraprec + factor = a**(0.5*(s-1))/(4*ctx.sqrt(ctx.pi)*ctx.gamma(0.5*s)) + tol = ctx.eps + f = lambda n: ctx.bernpoly(n,0.75)*(4*ctx.sqrt(a))**n*\ + ctx.gamma(0.5*n)/((s+n-1)*ctx.fac(n)) + totsum = ctx.zero + mg1 = ctx.inf + n = 1 + term = f(n) + mg2 = abs(term) + while mg2 > tol and mg2 <= mg1: + totsum += term + n += 1 + term = f(n) + totsum += term + n +=1 + term = f(n) + mg1 = mg2 + mg2 = abs(term) + totsum += term + pole = -2*(s-1)**(-2)+(ctx.euler+ctx.log(16*ctx.pi**2*a))*(s-1)**(-1) + st = factor*(pole+totsum) + err = 0 + if kwargs.get("error"): + if not ((mg2 > tol) and (mg2 <= mg1)): + if mg2 <= tol: + err = ctx.mpf(10)**int(ctx.log(abs(factor*tol),10)) + if mg2 > mg1: + err = ctx.mpf(10)**int(ctx.log(abs(factor*mg1),10)) + err = max(err, ctx.eps*1.) + ctx.prec -= extraprec + return +st, err + +@defun +def secondzeta(ctx, s, a = 0.015, **kwargs): + r""" + Evaluates the secondary zeta function `Z(s)`, defined for + `\mathrm{Re}(s)>1` by + + .. math :: + + Z(s) = \sum_{n=1}^{\infty} \frac{1}{\tau_n^s} + + where `\frac12+i\tau_n` runs through the zeros of `\zeta(s)` with + imaginary part positive. + + `Z(s)` extends to a meromorphic function on `\mathbb{C}` with a + double pole at `s=1` and simple poles at the points `-2n` for + `n=0`, 1, 2, ... + + **Examples** + + >>> from mpmath import * + >>> mp.pretty = True; mp.dps = 15 + >>> secondzeta(2) + 0.023104993115419 + >>> xi = lambda s: 0.5*s*(s-1)*pi**(-0.5*s)*gamma(0.5*s)*zeta(s) + >>> Xi = lambda t: xi(0.5+t*j) + >>> chop(-0.5*diff(Xi,0,n=2)/Xi(0)) + 0.023104993115419 + + We may ask for an approximate error value:: + + >>> secondzeta(0.5+100j, error=True) + ((-0.216272011276718 - 0.844952708937228j), 2.22044604925031e-16) + + The function has poles at the negative odd integers, + and dyadic rational values at the negative even integers:: + + >>> mp.dps = 30 + >>> secondzeta(-8) + -0.67236328125 + >>> secondzeta(-7) + +inf + + **Implementation notes** + + The function is computed as sum of four terms `Z(s)=A(s)-P(s)+E(s)-S(s)` + respectively main, prime, exponential and singular terms. + The main term `A(s)` is computed from the zeros of zeta. + The prime term depends on the von Mangoldt function. + The singular term is responsible for the poles of the function. + + The four terms depends on a small parameter `a`. We may change the + value of `a`. Theoretically this has no effect on the sum of the four + terms, but in practice may be important. + + A smaller value of the parameter `a` makes `A(s)` depend on + a smaller number of zeros of zeta, but `P(s)` uses more values of + von Mangoldt function. + + We may also add a verbose option to obtain data about the + values of the four terms. + + >>> mp.dps = 10 + >>> secondzeta(0.5 + 40j, error=True, verbose=True) + main term = (-30190318549.138656312556 - 13964804384.624622876523j) + computed using 19 zeros of zeta + prime term = (132717176.89212754625045 + 188980555.17563978290601j) + computed using 9 values of the von Mangoldt function + exponential term = (542447428666.07179812536 + 362434922978.80192435203j) + singular term = (512124392939.98154322355 + 348281138038.65531023921j) + ((0.059471043 + 0.3463514534j), 1.455191523e-11) + + >>> secondzeta(0.5 + 40j, a=0.04, error=True, verbose=True) + main term = (-151962888.19606243907725 - 217930683.90210294051982j) + computed using 9 zeros of zeta + prime term = (2476659342.3038722372461 + 28711581821.921627163136j) + computed using 37 values of the von Mangoldt function + exponential term = (178506047114.7838188264 + 819674143244.45677330576j) + singular term = (175877424884.22441310708 + 790744630738.28669174871j) + ((0.059471043 + 0.3463514534j), 1.455191523e-11) + + Notice the great cancellation between the four terms. Changing `a`, the + four terms are very different numbers but the cancellation gives + the good value of Z(s). + + **References** + + A. Voros, Zeta functions for the Riemann zeros, Ann. Institute Fourier, + 53, (2003) 665--699. + + A. Voros, Zeta functions over Zeros of Zeta Functions, Lecture Notes + of the Unione Matematica Italiana, Springer, 2009. + """ + s = ctx.convert(s) + a = ctx.convert(a) + tol = ctx.eps + if ctx.isint(s) and ctx.re(s) <= 1: + if abs(s-1) < tol*1000: + return ctx.inf + m = int(round(ctx.re(s))) + if m & 1: + return ctx.inf + else: + return ((-1)**(-m//2)*\ + ctx.fraction(8-ctx.eulernum(-m,exact=True),2**(-m+3))) + prec = ctx.prec + try: + t3 = secondzeta_exp_term(ctx, s, a) + extraprec = max(ctx.mag(t3),0) + ctx.prec += extraprec + 3 + t1, r1, gt = secondzeta_main_term(ctx,s,a,error='True', verbose='True') + t2, r2, pt = secondzeta_prime_term(ctx,s,a,error='True', verbose='True') + t4, r4 = secondzeta_singular_term(ctx,s,a,error='True') + t3 = secondzeta_exp_term(ctx, s, a) + err = r1+r2+r4 + t = t1-t2+t3-t4 + if kwargs.get("verbose"): + print('main term =', t1) + print(' computed using', gt, 'zeros of zeta') + print('prime term =', t2) + print(' computed using', pt, 'values of the von Mangoldt function') + print('exponential term =', t3) + print('singular term =', t4) + finally: + ctx.prec = prec + if kwargs.get("error"): + w = max(ctx.mag(abs(t)),0) + err = max(err*2**w, ctx.eps*1.*2**w) + return +t, err + return +t + + +@defun_wrapped +def lerchphi(ctx, z, s, a): + r""" + Gives the Lerch transcendent, defined for `|z| < 1` and + `\Re{a} > 0` by + + .. math :: + + \Phi(z,s,a) = \sum_{k=0}^{\infty} \frac{z^k}{(a+k)^s} + + and generally by the recurrence `\Phi(z,s,a) = z \Phi(z,s,a+1) + a^{-s}` + along with the integral representation valid for `\Re{a} > 0` + + .. math :: + + \Phi(z,s,a) = \frac{1}{2 a^s} + + \int_0^{\infty} \frac{z^t}{(a+t)^s} dt - + 2 \int_0^{\infty} \frac{\sin(t \log z - s + \operatorname{arctan}(t/a)}{(a^2 + t^2)^{s/2} + (e^{2 \pi t}-1)} dt. + + The Lerch transcendent generalizes the Hurwitz zeta function :func:`zeta` + (`z = 1`) and the polylogarithm :func:`polylog` (`a = 1`). + + **Examples** + + Several evaluations in terms of simpler functions:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> lerchphi(-1,2,0.5); 4*catalan + 3.663862376708876060218414 + 3.663862376708876060218414 + >>> diff(lerchphi, (-1,-2,1), (0,1,0)); 7*zeta(3)/(4*pi**2) + 0.2131391994087528954617607 + 0.2131391994087528954617607 + >>> lerchphi(-4,1,1); log(5)/4 + 0.4023594781085250936501898 + 0.4023594781085250936501898 + >>> lerchphi(-3+2j,1,0.5); 2*atanh(sqrt(-3+2j))/sqrt(-3+2j) + (1.142423447120257137774002 + 0.2118232380980201350495795j) + (1.142423447120257137774002 + 0.2118232380980201350495795j) + + Evaluation works for complex arguments and `|z| \ge 1`:: + + >>> lerchphi(1+2j, 3-j, 4+2j) + (0.002025009957009908600539469 + 0.003327897536813558807438089j) + >>> lerchphi(-2,2,-2.5) + -12.28676272353094275265944 + >>> lerchphi(10,10,10) + (-4.462130727102185701817349e-11 - 1.575172198981096218823481e-12j) + >>> lerchphi(10,10,-10.5) + (112658784011940.5605789002 - 498113185.5756221777743631j) + + Some degenerate cases:: + + >>> lerchphi(0,1,2) + 0.5 + >>> lerchphi(0,1,-2) + -0.5 + + Reduction to simpler functions:: + + >>> lerchphi(1, 4.25+1j, 1) + (1.044674457556746668033975 - 0.04674508654012658932271226j) + >>> zeta(4.25+1j) + (1.044674457556746668033975 - 0.04674508654012658932271226j) + >>> lerchphi(1 - 0.5**10, 4.25+1j, 1) + (1.044629338021507546737197 - 0.04667768813963388181708101j) + >>> lerchphi(3, 4, 1) + (1.249503297023366545192592 - 0.2314252413375664776474462j) + >>> polylog(4, 3) / 3 + (1.249503297023366545192592 - 0.2314252413375664776474462j) + >>> lerchphi(3, 4, 1 - 0.5**10) + (1.253978063946663945672674 - 0.2316736622836535468765376j) + + **References** + + 1. [DLMF]_ section 25.14 + + """ + if z == 0: + return a ** (-s) + # Faster, but these cases are useful for testing right now + if z == 1: + return ctx.zeta(s, a) + if a == 1: + return ctx.polylog(s, z) / z + if ctx.re(a) < 1: + if ctx.isnpint(a): + raise ValueError("Lerch transcendent complex infinity") + m = int(ctx.ceil(1-ctx.re(a))) + v = ctx.zero + zpow = ctx.one + for n in xrange(m): + v += zpow / (a+n)**s + zpow *= z + return zpow * ctx.lerchphi(z,s, a+m) + v + g = ctx.ln(z) + v = 1/(2*a**s) + ctx.gammainc(1-s, -a*g) * (-g)**(s-1) / z**a + h = s / 2 + r = 2*ctx.pi + f = lambda t: ctx.sin(s*ctx.atan(t/a)-t*g) / \ + ((a**2+t**2)**h * ctx.expm1(r*t)) + v += 2*ctx.quad(f, [0, ctx.inf]) + if not ctx.im(z) and not ctx.im(s) and not ctx.im(a) and ctx.re(z) < 1: + v = ctx.chop(v) + return v diff --git a/venv/lib/python3.10/site-packages/mpmath/functions/zetazeros.py b/venv/lib/python3.10/site-packages/mpmath/functions/zetazeros.py new file mode 100644 index 0000000000000000000000000000000000000000..37c11a29426b0114053ae61664541f7ae7de95d8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/functions/zetazeros.py @@ -0,0 +1,1018 @@ +""" +The function zetazero(n) computes the n-th nontrivial zero of zeta(s). + +The general strategy is to locate a block of Gram intervals B where we +know exactly the number of zeros contained and which of those zeros +is that which we search. + +If n <= 400 000 000 we know exactly the Rosser exceptions, contained +in a list in this file. Hence for n<=400 000 000 we simply +look at these list of exceptions. If our zero is implicated in one of +these exceptions we have our block B. In other case we simply locate +the good Rosser block containing our zero. + +For n > 400 000 000 we apply the method of Turing, as complemented by +Lehman, Brent and Trudgian to find a suitable B. +""" + +from .functions import defun, defun_wrapped + +def find_rosser_block_zero(ctx, n): + """for n<400 000 000 determines a block were one find our zero""" + for k in range(len(_ROSSER_EXCEPTIONS)//2): + a=_ROSSER_EXCEPTIONS[2*k][0] + b=_ROSSER_EXCEPTIONS[2*k][1] + if ((a<= n-2) and (n-1 <= b)): + t0 = ctx.grampoint(a) + t1 = ctx.grampoint(b) + v0 = ctx._fp.siegelz(t0) + v1 = ctx._fp.siegelz(t1) + my_zero_number = n-a-1 + zero_number_block = b-a + pattern = _ROSSER_EXCEPTIONS[2*k+1] + return (my_zero_number, [a,b], [t0,t1], [v0,v1]) + k = n-2 + t,v,b = compute_triple_tvb(ctx, k) + T = [t] + V = [v] + while b < 0: + k -= 1 + t,v,b = compute_triple_tvb(ctx, k) + T.insert(0,t) + V.insert(0,v) + my_zero_number = n-k-1 + m = n-1 + t,v,b = compute_triple_tvb(ctx, m) + T.append(t) + V.append(v) + while b < 0: + m += 1 + t,v,b = compute_triple_tvb(ctx, m) + T.append(t) + V.append(v) + return (my_zero_number, [k,m], T, V) + +def wpzeros(t): + """Precision needed to compute higher zeros""" + wp = 53 + if t > 3*10**8: + wp = 63 + if t > 10**11: + wp = 70 + if t > 10**14: + wp = 83 + return wp + +def separate_zeros_in_block(ctx, zero_number_block, T, V, limitloop=None, + fp_tolerance=None): + """Separate the zeros contained in the block T, limitloop + determines how long one must search""" + if limitloop is None: + limitloop = ctx.inf + loopnumber = 0 + variations = count_variations(V) + while ((variations < zero_number_block) and (loopnumber 0): + alpha = ctx.sqrt(u/v) + b= (alpha*a+b2)/(alpha+1) + else: + b = (a+b2)/2 + if fp_tolerance < 10: + w = ctx._fp.siegelz(b) + if abs(w)ITERATION_LIMIT)and(loopnumber>2)and(variations+2==zero_number_block): + dtMax=0 + dtSec=0 + kMax = 0 + for k1 in range(1,len(T)): + dt = T[k1]-T[k1-1] + if dt > dtMax: + kMax=k1 + dtSec = dtMax + dtMax = dt + elif (dtdtSec): + dtSec = dt + if dtMax>3*dtSec: + f = lambda x: ctx.rs_z(x,derivative=1) + t0=T[kMax-1] + t1 = T[kMax] + t=ctx.findroot(f, (t0,t1), solver ='illinois',verify=False, verbose=False) + v = ctx.siegelz(t) + if (t0 2*wpz: + index +=1 + precs = [precs[0] // 2 +3+2*index] + precs + ctx.prec = precs[0] + guard + r = ctx.findroot(lambda x:ctx.siegelz(x), (t0,t1), solver ='illinois', verbose=False) + #print "first step at", ctx.dps, "digits" + z=ctx.mpc(0.5,r) + for prec in precs[1:]: + ctx.prec = prec + guard + #print "refining to", ctx.dps, "digits" + znew = z - ctx.zeta(z) / ctx.zeta(z, derivative=1) + #print "difference", ctx.nstr(abs(z-znew)) + z=ctx.mpc(0.5,ctx.im(znew)) + return ctx.im(z) + +def sure_number_block(ctx, n): + """The number of good Rosser blocks needed to apply + Turing method + References: + R. P. Brent, On the Zeros of the Riemann Zeta Function + in the Critical Strip, Math. Comp. 33 (1979) 1361--1372 + T. Trudgian, Improvements to Turing Method, Math. Comp.""" + if n < 9*10**5: + return(2) + g = ctx.grampoint(n-100) + lg = ctx._fp.ln(g) + brent = 0.0061 * lg**2 +0.08*lg + trudgian = 0.0031 * lg**2 +0.11*lg + N = ctx.ceil(min(brent,trudgian)) + N = int(N) + return N + +def compute_triple_tvb(ctx, n): + t = ctx.grampoint(n) + v = ctx._fp.siegelz(t) + if ctx.mag(abs(v))400 000 000""" + sb = sure_number_block(ctx, n) + number_goodblocks = 0 + m2 = n-1 + t, v, b = compute_triple_tvb(ctx, m2) + Tf = [t] + Vf = [v] + while b < 0: + m2 += 1 + t,v,b = compute_triple_tvb(ctx, m2) + Tf.append(t) + Vf.append(v) + goodpoints = [m2] + T = [t] + V = [v] + while number_goodblocks < 2*sb: + m2 += 1 + t, v, b = compute_triple_tvb(ctx, m2) + T.append(t) + V.append(v) + while b < 0: + m2 += 1 + t,v,b = compute_triple_tvb(ctx, m2) + T.append(t) + V.append(v) + goodpoints.append(m2) + zn = len(T)-1 + A, B, separated =\ + separate_zeros_in_block(ctx, zn, T, V, limitloop=ITERATION_LIMIT, + fp_tolerance=fp_tolerance) + Tf.pop() + Tf.extend(A) + Vf.pop() + Vf.extend(B) + if separated: + number_goodblocks += 1 + else: + number_goodblocks = 0 + T = [t] + V = [v] + # Now the same procedure to the left + number_goodblocks = 0 + m2 = n-2 + t, v, b = compute_triple_tvb(ctx, m2) + Tf.insert(0,t) + Vf.insert(0,v) + while b < 0: + m2 -= 1 + t,v,b = compute_triple_tvb(ctx, m2) + Tf.insert(0,t) + Vf.insert(0,v) + goodpoints.insert(0,m2) + T = [t] + V = [v] + while number_goodblocks < 2*sb: + m2 -= 1 + t, v, b = compute_triple_tvb(ctx, m2) + T.insert(0,t) + V.insert(0,v) + while b < 0: + m2 -= 1 + t,v,b = compute_triple_tvb(ctx, m2) + T.insert(0,t) + V.insert(0,v) + goodpoints.insert(0,m2) + zn = len(T)-1 + A, B, separated =\ + separate_zeros_in_block(ctx, zn, T, V, limitloop=ITERATION_LIMIT, fp_tolerance=fp_tolerance) + A.pop() + Tf = A+Tf + B.pop() + Vf = B+Vf + if separated: + number_goodblocks += 1 + else: + number_goodblocks = 0 + T = [t] + V = [v] + r = goodpoints[2*sb] + lg = len(goodpoints) + s = goodpoints[lg-2*sb-1] + tr, vr, br = compute_triple_tvb(ctx, r) + ar = Tf.index(tr) + ts, vs, bs = compute_triple_tvb(ctx, s) + as1 = Tf.index(ts) + T = Tf[ar:as1+1] + V = Vf[ar:as1+1] + zn = s-r + A, B, separated =\ + separate_zeros_in_block(ctx, zn,T,V,limitloop=ITERATION_LIMIT, fp_tolerance=fp_tolerance) + if separated: + return (n-r-1,[r,s],A,B) + q = goodpoints[sb] + lg = len(goodpoints) + t = goodpoints[lg-sb-1] + tq, vq, bq = compute_triple_tvb(ctx, q) + aq = Tf.index(tq) + tt, vt, bt = compute_triple_tvb(ctx, t) + at = Tf.index(tt) + T = Tf[aq:at+1] + V = Vf[aq:at+1] + return (n-q-1,[q,t],T,V) + +def count_variations(V): + count = 0 + vold = V[0] + for n in range(1, len(V)): + vnew = V[n] + if vold*vnew < 0: + count +=1 + vold = vnew + return count + +def pattern_construct(ctx, block, T, V): + pattern = '(' + a = block[0] + b = block[1] + t0,v0,b0 = compute_triple_tvb(ctx, a) + k = 0 + k0 = 0 + for n in range(a+1,b+1): + t1,v1,b1 = compute_triple_tvb(ctx, n) + lgT =len(T) + while (k < lgT) and (T[k] <= t1): + k += 1 + L = V[k0:k] + L.append(v1) + L.insert(0,v0) + count = count_variations(L) + pattern = pattern + ("%s" % count) + if b1 > 0: + pattern = pattern + ')(' + k0 = k + t0,v0,b0 = t1,v1,b1 + pattern = pattern[:-1] + return pattern + +@defun +def zetazero(ctx, n, info=False, round=True): + r""" + Computes the `n`-th nontrivial zero of `\zeta(s)` on the critical line, + i.e. returns an approximation of the `n`-th largest complex number + `s = \frac{1}{2} + ti` for which `\zeta(s) = 0`. Equivalently, the + imaginary part `t` is a zero of the Z-function (:func:`~mpmath.siegelz`). + + **Examples** + + The first few zeros:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> zetazero(1) + (0.5 + 14.13472514173469379045725j) + >>> zetazero(2) + (0.5 + 21.02203963877155499262848j) + >>> zetazero(20) + (0.5 + 77.14484006887480537268266j) + + Verifying that the values are zeros:: + + >>> for n in range(1,5): + ... s = zetazero(n) + ... chop(zeta(s)), chop(siegelz(s.imag)) + ... + (0.0, 0.0) + (0.0, 0.0) + (0.0, 0.0) + (0.0, 0.0) + + Negative indices give the conjugate zeros (`n = 0` is undefined):: + + >>> zetazero(-1) + (0.5 - 14.13472514173469379045725j) + + :func:`~mpmath.zetazero` supports arbitrarily large `n` and arbitrary precision:: + + >>> mp.dps = 15 + >>> zetazero(1234567) + (0.5 + 727690.906948208j) + >>> mp.dps = 50 + >>> zetazero(1234567) + (0.5 + 727690.9069482075392389420041147142092708393819935j) + >>> chop(zeta(_)/_) + 0.0 + + with *info=True*, :func:`~mpmath.zetazero` gives additional information:: + + >>> mp.dps = 15 + >>> zetazero(542964976,info=True) + ((0.5 + 209039046.578535j), [542964969, 542964978], 6, '(013111110)') + + This means that the zero is between Gram points 542964969 and 542964978; + it is the 6-th zero between them. Finally (01311110) is the pattern + of zeros in this interval. The numbers indicate the number of zeros + in each Gram interval (Rosser blocks between parenthesis). In this case + there is only one Rosser block of length nine. + """ + n = int(n) + if n < 0: + return ctx.zetazero(-n).conjugate() + if n == 0: + raise ValueError("n must be nonzero") + wpinitial = ctx.prec + try: + wpz, fp_tolerance = comp_fp_tolerance(ctx, n) + ctx.prec = wpz + if n < 400000000: + my_zero_number, block, T, V =\ + find_rosser_block_zero(ctx, n) + else: + my_zero_number, block, T, V =\ + search_supergood_block(ctx, n, fp_tolerance) + zero_number_block = block[1]-block[0] + T, V, separated = separate_zeros_in_block(ctx, zero_number_block, T, V, + limitloop=ctx.inf, fp_tolerance=fp_tolerance) + if info: + pattern = pattern_construct(ctx,block,T,V) + prec = max(wpinitial, wpz) + t = separate_my_zero(ctx, my_zero_number, zero_number_block,T,V,prec) + v = ctx.mpc(0.5,t) + finally: + ctx.prec = wpinitial + if round: + v =+v + if info: + return (v,block,my_zero_number,pattern) + else: + return v + +def gram_index(ctx, t): + if t > 10**13: + wp = 3*ctx.log(t, 10) + else: + wp = 0 + prec = ctx.prec + try: + ctx.prec += wp + h = int(ctx.siegeltheta(t)/ctx.pi) + finally: + ctx.prec = prec + return(h) + +def count_to(ctx, t, T, V): + count = 0 + vold = V[0] + told = T[0] + tnew = T[1] + k = 1 + while tnew < t: + vnew = V[k] + if vold*vnew < 0: + count += 1 + vold = vnew + k += 1 + tnew = T[k] + a = ctx.siegelz(t) + if a*vold < 0: + count += 1 + return count + +def comp_fp_tolerance(ctx, n): + wpz = wpzeros(n*ctx.log(n)) + if n < 15*10**8: + fp_tolerance = 0.0005 + elif n <= 10**14: + fp_tolerance = 0.1 + else: + fp_tolerance = 100 + return wpz, fp_tolerance + +@defun +def nzeros(ctx, t): + r""" + Computes the number of zeros of the Riemann zeta function in + `(0,1) \times (0,t]`, usually denoted by `N(t)`. + + **Examples** + + The first zero has imaginary part between 14 and 15:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> nzeros(14) + 0 + >>> nzeros(15) + 1 + >>> zetazero(1) + (0.5 + 14.1347251417347j) + + Some closely spaced zeros:: + + >>> nzeros(10**7) + 21136125 + >>> zetazero(21136125) + (0.5 + 9999999.32718175j) + >>> zetazero(21136126) + (0.5 + 10000000.2400236j) + >>> nzeros(545439823.215) + 1500000001 + >>> zetazero(1500000001) + (0.5 + 545439823.201985j) + >>> zetazero(1500000002) + (0.5 + 545439823.325697j) + + This confirms the data given by J. van de Lune, + H. J. J. te Riele and D. T. Winter in 1986. + """ + if t < 14.1347251417347: + return 0 + x = gram_index(ctx, t) + k = int(ctx.floor(x)) + wpinitial = ctx.prec + wpz, fp_tolerance = comp_fp_tolerance(ctx, k) + ctx.prec = wpz + a = ctx.siegelz(t) + if k == -1 and a < 0: + return 0 + elif k == -1 and a > 0: + return 1 + if k+2 < 400000000: + Rblock = find_rosser_block_zero(ctx, k+2) + else: + Rblock = search_supergood_block(ctx, k+2, fp_tolerance) + n1, n2 = Rblock[1] + if n2-n1 == 1: + b = Rblock[3][0] + if a*b > 0: + ctx.prec = wpinitial + return k+1 + else: + ctx.prec = wpinitial + return k+2 + my_zero_number,block, T, V = Rblock + zero_number_block = n2-n1 + T, V, separated = separate_zeros_in_block(ctx,\ + zero_number_block, T, V,\ + limitloop=ctx.inf,\ + fp_tolerance=fp_tolerance) + n = count_to(ctx, t, T, V) + ctx.prec = wpinitial + return n+n1+1 + +@defun_wrapped +def backlunds(ctx, t): + r""" + Computes the function + `S(t) = \operatorname{arg} \zeta(\frac{1}{2} + it) / \pi`. + + See Titchmarsh Section 9.3 for details of the definition. + + **Examples** + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> backlunds(217.3) + 0.16302205431184 + + Generally, the value is a small number. At Gram points it is an integer, + frequently equal to 0:: + + >>> chop(backlunds(grampoint(200))) + 0.0 + >>> backlunds(extraprec(10)(grampoint)(211)) + 1.0 + >>> backlunds(extraprec(10)(grampoint)(232)) + -1.0 + + The number of zeros of the Riemann zeta function up to height `t` + satisfies `N(t) = \theta(t)/\pi + 1 + S(t)` (see :func:nzeros` and + :func:`siegeltheta`):: + + >>> t = 1234.55 + >>> nzeros(t) + 842 + >>> siegeltheta(t)/pi+1+backlunds(t) + 842.0 + + """ + return ctx.nzeros(t)-1-ctx.siegeltheta(t)/ctx.pi + + +""" +_ROSSER_EXCEPTIONS is a list of all exceptions to +Rosser's rule for n <= 400 000 000. + +Alternately the entry is of type [n,m], or a string. +The string is the zero pattern of the Block and the relevant +adjacent. For example (010)3 corresponds to a block +composed of three Gram intervals, the first ant third without +a zero and the intermediate with a zero. The next Gram interval +contain three zeros. So that in total we have 4 zeros in 4 Gram +blocks. n and m are the indices of the Gram points of this +interval of four Gram intervals. The Rosser exception is therefore +formed by the three Gram intervals that are signaled between +parenthesis. + +We have included also some Rosser's exceptions beyond n=400 000 000 +that are noted in the literature by some reason. + +The list is composed from the data published in the references: + +R. P. Brent, J. van de Lune, H. J. J. te Riele, D. T. Winter, +'On the Zeros of the Riemann Zeta Function in the Critical Strip. II', +Math. Comp. 39 (1982) 681--688. +See also Corrigenda in Math. Comp. 46 (1986) 771. + +J. van de Lune, H. J. J. te Riele, +'On the Zeros of the Riemann Zeta Function in the Critical Strip. III', +Math. Comp. 41 (1983) 759--767. +See also Corrigenda in Math. Comp. 46 (1986) 771. + +J. van de Lune, +'Sums of Equal Powers of Positive Integers', +Dissertation, +Vrije Universiteit te Amsterdam, Centrum voor Wiskunde en Informatica, +Amsterdam, 1984. + +Thanks to the authors all this papers and those others that have +contributed to make this possible. +""" + + + + + + + +_ROSSER_EXCEPTIONS = \ +[[13999525, 13999528], '(00)3', +[30783329, 30783332], '(00)3', +[30930926, 30930929], '3(00)', +[37592215, 37592218], '(00)3', +[40870156, 40870159], '(00)3', +[43628107, 43628110], '(00)3', +[46082042, 46082045], '(00)3', +[46875667, 46875670], '(00)3', +[49624540, 49624543], '3(00)', +[50799238, 50799241], '(00)3', +[55221453, 55221456], '3(00)', +[56948779, 56948782], '3(00)', +[60515663, 60515666], '(00)3', +[61331766, 61331770], '(00)40', +[69784843, 69784846], '3(00)', +[75052114, 75052117], '(00)3', +[79545240, 79545243], '3(00)', +[79652247, 79652250], '3(00)', +[83088043, 83088046], '(00)3', +[83689522, 83689525], '3(00)', +[85348958, 85348961], '(00)3', +[86513820, 86513823], '(00)3', +[87947596, 87947599], '3(00)', +[88600095, 88600098], '(00)3', +[93681183, 93681186], '(00)3', +[100316551, 100316554], '3(00)', +[100788444, 100788447], '(00)3', +[106236172, 106236175], '(00)3', +[106941327, 106941330], '3(00)', +[107287955, 107287958], '(00)3', +[107532016, 107532019], '3(00)', +[110571044, 110571047], '(00)3', +[111885253, 111885256], '3(00)', +[113239783, 113239786], '(00)3', +[120159903, 120159906], '(00)3', +[121424391, 121424394], '3(00)', +[121692931, 121692934], '3(00)', +[121934170, 121934173], '3(00)', +[122612848, 122612851], '3(00)', +[126116567, 126116570], '(00)3', +[127936513, 127936516], '(00)3', +[128710277, 128710280], '3(00)', +[129398902, 129398905], '3(00)', +[130461096, 130461099], '3(00)', +[131331947, 131331950], '3(00)', +[137334071, 137334074], '3(00)', +[137832603, 137832606], '(00)3', +[138799471, 138799474], '3(00)', +[139027791, 139027794], '(00)3', +[141617806, 141617809], '(00)3', +[144454931, 144454934], '(00)3', +[145402379, 145402382], '3(00)', +[146130245, 146130248], '3(00)', +[147059770, 147059773], '(00)3', +[147896099, 147896102], '3(00)', +[151097113, 151097116], '(00)3', +[152539438, 152539441], '(00)3', +[152863168, 152863171], '3(00)', +[153522726, 153522729], '3(00)', +[155171524, 155171527], '3(00)', +[155366607, 155366610], '(00)3', +[157260686, 157260689], '3(00)', +[157269224, 157269227], '(00)3', +[157755123, 157755126], '(00)3', +[158298484, 158298487], '3(00)', +[160369050, 160369053], '3(00)', +[162962787, 162962790], '(00)3', +[163724709, 163724712], '(00)3', +[164198113, 164198116], '3(00)', +[164689301, 164689305], '(00)40', +[164880228, 164880231], '3(00)', +[166201932, 166201935], '(00)3', +[168573836, 168573839], '(00)3', +[169750763, 169750766], '(00)3', +[170375507, 170375510], '(00)3', +[170704879, 170704882], '3(00)', +[172000992, 172000995], '3(00)', +[173289941, 173289944], '(00)3', +[173737613, 173737616], '3(00)', +[174102513, 174102516], '(00)3', +[174284990, 174284993], '(00)3', +[174500513, 174500516], '(00)3', +[175710609, 175710612], '(00)3', +[176870843, 176870846], '3(00)', +[177332732, 177332735], '3(00)', +[177902861, 177902864], '3(00)', +[179979095, 179979098], '(00)3', +[181233726, 181233729], '3(00)', +[181625435, 181625438], '(00)3', +[182105255, 182105259], '22(00)', +[182223559, 182223562], '3(00)', +[191116404, 191116407], '3(00)', +[191165599, 191165602], '3(00)', +[191297535, 191297539], '(00)22', +[192485616, 192485619], '(00)3', +[193264634, 193264638], '22(00)', +[194696968, 194696971], '(00)3', +[195876805, 195876808], '(00)3', +[195916548, 195916551], '3(00)', +[196395160, 196395163], '3(00)', +[196676303, 196676306], '(00)3', +[197889882, 197889885], '3(00)', +[198014122, 198014125], '(00)3', +[199235289, 199235292], '(00)3', +[201007375, 201007378], '(00)3', +[201030605, 201030608], '3(00)', +[201184290, 201184293], '3(00)', +[201685414, 201685418], '(00)22', +[202762875, 202762878], '3(00)', +[202860957, 202860960], '3(00)', +[203832577, 203832580], '3(00)', +[205880544, 205880547], '(00)3', +[206357111, 206357114], '(00)3', +[207159767, 207159770], '3(00)', +[207167343, 207167346], '3(00)', +[207482539, 207482543], '3(010)', +[207669540, 207669543], '3(00)', +[208053426, 208053429], '(00)3', +[208110027, 208110030], '3(00)', +[209513826, 209513829], '3(00)', +[212623522, 212623525], '(00)3', +[213841715, 213841718], '(00)3', +[214012333, 214012336], '(00)3', +[214073567, 214073570], '(00)3', +[215170600, 215170603], '3(00)', +[215881039, 215881042], '3(00)', +[216274604, 216274607], '3(00)', +[216957120, 216957123], '3(00)', +[217323208, 217323211], '(00)3', +[218799264, 218799267], '(00)3', +[218803557, 218803560], '3(00)', +[219735146, 219735149], '(00)3', +[219830062, 219830065], '3(00)', +[219897904, 219897907], '(00)3', +[221205545, 221205548], '(00)3', +[223601929, 223601932], '(00)3', +[223907076, 223907079], '3(00)', +[223970397, 223970400], '(00)3', +[224874044, 224874048], '22(00)', +[225291157, 225291160], '(00)3', +[227481734, 227481737], '(00)3', +[228006442, 228006445], '3(00)', +[228357900, 228357903], '(00)3', +[228386399, 228386402], '(00)3', +[228907446, 228907449], '(00)3', +[228984552, 228984555], '3(00)', +[229140285, 229140288], '3(00)', +[231810024, 231810027], '(00)3', +[232838062, 232838065], '3(00)', +[234389088, 234389091], '3(00)', +[235588194, 235588197], '(00)3', +[236645695, 236645698], '(00)3', +[236962876, 236962879], '3(00)', +[237516723, 237516727], '04(00)', +[240004911, 240004914], '(00)3', +[240221306, 240221309], '3(00)', +[241389213, 241389217], '(010)3', +[241549003, 241549006], '(00)3', +[241729717, 241729720], '(00)3', +[241743684, 241743687], '3(00)', +[243780200, 243780203], '3(00)', +[243801317, 243801320], '(00)3', +[244122072, 244122075], '(00)3', +[244691224, 244691227], '3(00)', +[244841577, 244841580], '(00)3', +[245813461, 245813464], '(00)3', +[246299475, 246299478], '(00)3', +[246450176, 246450179], '3(00)', +[249069349, 249069352], '(00)3', +[250076378, 250076381], '(00)3', +[252442157, 252442160], '3(00)', +[252904231, 252904234], '3(00)', +[255145220, 255145223], '(00)3', +[255285971, 255285974], '3(00)', +[256713230, 256713233], '(00)3', +[257992082, 257992085], '(00)3', +[258447955, 258447959], '22(00)', +[259298045, 259298048], '3(00)', +[262141503, 262141506], '(00)3', +[263681743, 263681746], '3(00)', +[266527881, 266527885], '(010)3', +[266617122, 266617125], '(00)3', +[266628044, 266628047], '3(00)', +[267305763, 267305766], '(00)3', +[267388404, 267388407], '3(00)', +[267441672, 267441675], '3(00)', +[267464886, 267464889], '(00)3', +[267554907, 267554910], '3(00)', +[269787480, 269787483], '(00)3', +[270881434, 270881437], '(00)3', +[270997583, 270997586], '3(00)', +[272096378, 272096381], '3(00)', +[272583009, 272583012], '(00)3', +[274190881, 274190884], '3(00)', +[274268747, 274268750], '(00)3', +[275297429, 275297432], '3(00)', +[275545476, 275545479], '3(00)', +[275898479, 275898482], '3(00)', +[275953000, 275953003], '(00)3', +[277117197, 277117201], '(00)22', +[277447310, 277447313], '3(00)', +[279059657, 279059660], '3(00)', +[279259144, 279259147], '3(00)', +[279513636, 279513639], '3(00)', +[279849069, 279849072], '3(00)', +[280291419, 280291422], '(00)3', +[281449425, 281449428], '3(00)', +[281507953, 281507956], '3(00)', +[281825600, 281825603], '(00)3', +[282547093, 282547096], '3(00)', +[283120963, 283120966], '3(00)', +[283323493, 283323496], '(00)3', +[284764535, 284764538], '3(00)', +[286172639, 286172642], '3(00)', +[286688824, 286688827], '(00)3', +[287222172, 287222175], '3(00)', +[287235534, 287235537], '3(00)', +[287304861, 287304864], '3(00)', +[287433571, 287433574], '(00)3', +[287823551, 287823554], '(00)3', +[287872422, 287872425], '3(00)', +[288766615, 288766618], '3(00)', +[290122963, 290122966], '3(00)', +[290450849, 290450853], '(00)22', +[291426141, 291426144], '3(00)', +[292810353, 292810356], '3(00)', +[293109861, 293109864], '3(00)', +[293398054, 293398057], '3(00)', +[294134426, 294134429], '3(00)', +[294216438, 294216441], '(00)3', +[295367141, 295367144], '3(00)', +[297834111, 297834114], '3(00)', +[299099969, 299099972], '3(00)', +[300746958, 300746961], '3(00)', +[301097423, 301097426], '(00)3', +[301834209, 301834212], '(00)3', +[302554791, 302554794], '(00)3', +[303497445, 303497448], '3(00)', +[304165344, 304165347], '3(00)', +[304790218, 304790222], '3(010)', +[305302352, 305302355], '(00)3', +[306785996, 306785999], '3(00)', +[307051443, 307051446], '3(00)', +[307481539, 307481542], '3(00)', +[308605569, 308605572], '3(00)', +[309237610, 309237613], '3(00)', +[310509287, 310509290], '(00)3', +[310554057, 310554060], '3(00)', +[310646345, 310646348], '3(00)', +[311274896, 311274899], '(00)3', +[311894272, 311894275], '3(00)', +[312269470, 312269473], '(00)3', +[312306601, 312306605], '(00)40', +[312683193, 312683196], '3(00)', +[314499804, 314499807], '3(00)', +[314636802, 314636805], '(00)3', +[314689897, 314689900], '3(00)', +[314721319, 314721322], '3(00)', +[316132890, 316132893], '3(00)', +[316217470, 316217474], '(010)3', +[316465705, 316465708], '3(00)', +[316542790, 316542793], '(00)3', +[320822347, 320822350], '3(00)', +[321733242, 321733245], '3(00)', +[324413970, 324413973], '(00)3', +[325950140, 325950143], '(00)3', +[326675884, 326675887], '(00)3', +[326704208, 326704211], '3(00)', +[327596247, 327596250], '3(00)', +[328123172, 328123175], '3(00)', +[328182212, 328182215], '(00)3', +[328257498, 328257501], '3(00)', +[328315836, 328315839], '(00)3', +[328800974, 328800977], '(00)3', +[328998509, 328998512], '3(00)', +[329725370, 329725373], '(00)3', +[332080601, 332080604], '(00)3', +[332221246, 332221249], '(00)3', +[332299899, 332299902], '(00)3', +[332532822, 332532825], '(00)3', +[333334544, 333334548], '(00)22', +[333881266, 333881269], '3(00)', +[334703267, 334703270], '3(00)', +[334875138, 334875141], '3(00)', +[336531451, 336531454], '3(00)', +[336825907, 336825910], '(00)3', +[336993167, 336993170], '(00)3', +[337493998, 337494001], '3(00)', +[337861034, 337861037], '3(00)', +[337899191, 337899194], '(00)3', +[337958123, 337958126], '(00)3', +[342331982, 342331985], '3(00)', +[342676068, 342676071], '3(00)', +[347063781, 347063784], '3(00)', +[347697348, 347697351], '3(00)', +[347954319, 347954322], '3(00)', +[348162775, 348162778], '3(00)', +[349210702, 349210705], '(00)3', +[349212913, 349212916], '3(00)', +[349248650, 349248653], '(00)3', +[349913500, 349913503], '3(00)', +[350891529, 350891532], '3(00)', +[351089323, 351089326], '3(00)', +[351826158, 351826161], '3(00)', +[352228580, 352228583], '(00)3', +[352376244, 352376247], '3(00)', +[352853758, 352853761], '(00)3', +[355110439, 355110442], '(00)3', +[355808090, 355808094], '(00)40', +[355941556, 355941559], '3(00)', +[356360231, 356360234], '(00)3', +[356586657, 356586660], '3(00)', +[356892926, 356892929], '(00)3', +[356908232, 356908235], '3(00)', +[357912730, 357912733], '3(00)', +[358120344, 358120347], '3(00)', +[359044096, 359044099], '(00)3', +[360819357, 360819360], '3(00)', +[361399662, 361399666], '(010)3', +[362361315, 362361318], '(00)3', +[363610112, 363610115], '(00)3', +[363964804, 363964807], '3(00)', +[364527375, 364527378], '(00)3', +[365090327, 365090330], '(00)3', +[365414539, 365414542], '3(00)', +[366738474, 366738477], '3(00)', +[368714778, 368714783], '04(010)', +[368831545, 368831548], '(00)3', +[368902387, 368902390], '(00)3', +[370109769, 370109772], '3(00)', +[370963333, 370963336], '3(00)', +[372541136, 372541140], '3(010)', +[372681562, 372681565], '(00)3', +[373009410, 373009413], '(00)3', +[373458970, 373458973], '3(00)', +[375648658, 375648661], '3(00)', +[376834728, 376834731], '3(00)', +[377119945, 377119948], '(00)3', +[377335703, 377335706], '(00)3', +[378091745, 378091748], '3(00)', +[379139522, 379139525], '3(00)', +[380279160, 380279163], '(00)3', +[380619442, 380619445], '3(00)', +[381244231, 381244234], '3(00)', +[382327446, 382327450], '(010)3', +[382357073, 382357076], '3(00)', +[383545479, 383545482], '3(00)', +[384363766, 384363769], '(00)3', +[384401786, 384401790], '22(00)', +[385198212, 385198215], '3(00)', +[385824476, 385824479], '(00)3', +[385908194, 385908197], '3(00)', +[386946806, 386946809], '3(00)', +[387592175, 387592179], '22(00)', +[388329293, 388329296], '(00)3', +[388679566, 388679569], '3(00)', +[388832142, 388832145], '3(00)', +[390087103, 390087106], '(00)3', +[390190926, 390190930], '(00)22', +[390331207, 390331210], '3(00)', +[391674495, 391674498], '3(00)', +[391937831, 391937834], '3(00)', +[391951632, 391951636], '(00)22', +[392963986, 392963989], '(00)3', +[393007921, 393007924], '3(00)', +[393373210, 393373213], '3(00)', +[393759572, 393759575], '(00)3', +[394036662, 394036665], '(00)3', +[395813866, 395813869], '(00)3', +[395956690, 395956693], '3(00)', +[396031670, 396031673], '3(00)', +[397076433, 397076436], '3(00)', +[397470601, 397470604], '3(00)', +[398289458, 398289461], '3(00)', +# +[368714778, 368714783], '04(010)', +[437953499, 437953504], '04(010)', +[526196233, 526196238], '032(00)', +[744719566, 744719571], '(010)40', +[750375857, 750375862], '032(00)', +[958241932, 958241937], '04(010)', +[983377342, 983377347], '(00)410', +[1003780080, 1003780085], '04(010)', +[1070232754, 1070232759], '(00)230', +[1209834865, 1209834870], '032(00)', +[1257209100, 1257209105], '(00)410', +[1368002233, 1368002238], '(00)230' +] diff --git a/venv/lib/python3.10/site-packages/mpmath/identification.py b/venv/lib/python3.10/site-packages/mpmath/identification.py new file mode 100644 index 0000000000000000000000000000000000000000..226f62d3fe9cacedbd9ba2b1e66ff0ad017fa604 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/identification.py @@ -0,0 +1,844 @@ +""" +Implements the PSLQ algorithm for integer relation detection, +and derivative algorithms for constant recognition. +""" + +from .libmp.backend import xrange +from .libmp import int_types, sqrt_fixed + +# round to nearest integer (can be done more elegantly...) +def round_fixed(x, prec): + return ((x + (1<<(prec-1))) >> prec) << prec + +class IdentificationMethods(object): + pass + + +def pslq(ctx, x, tol=None, maxcoeff=1000, maxsteps=100, verbose=False): + r""" + Given a vector of real numbers `x = [x_0, x_1, ..., x_n]`, ``pslq(x)`` + uses the PSLQ algorithm to find a list of integers + `[c_0, c_1, ..., c_n]` such that + + .. math :: + + |c_1 x_1 + c_2 x_2 + ... + c_n x_n| < \mathrm{tol} + + and such that `\max |c_k| < \mathrm{maxcoeff}`. If no such vector + exists, :func:`~mpmath.pslq` returns ``None``. The tolerance defaults to + 3/4 of the working precision. + + **Examples** + + Find rational approximations for `\pi`:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> pslq([-1, pi], tol=0.01) + [22, 7] + >>> pslq([-1, pi], tol=0.001) + [355, 113] + >>> mpf(22)/7; mpf(355)/113; +pi + 3.14285714285714 + 3.14159292035398 + 3.14159265358979 + + Pi is not a rational number with denominator less than 1000:: + + >>> pslq([-1, pi]) + >>> + + To within the standard precision, it can however be approximated + by at least one rational number with denominator less than `10^{12}`:: + + >>> p, q = pslq([-1, pi], maxcoeff=10**12) + >>> print(p); print(q) + 238410049439 + 75888275702 + >>> mpf(p)/q + 3.14159265358979 + + The PSLQ algorithm can be applied to long vectors. For example, + we can investigate the rational (in)dependence of integer square + roots:: + + >>> mp.dps = 30 + >>> pslq([sqrt(n) for n in range(2, 5+1)]) + >>> + >>> pslq([sqrt(n) for n in range(2, 6+1)]) + >>> + >>> pslq([sqrt(n) for n in range(2, 8+1)]) + [2, 0, 0, 0, 0, 0, -1] + + **Machin formulas** + + A famous formula for `\pi` is Machin's, + + .. math :: + + \frac{\pi}{4} = 4 \operatorname{acot} 5 - \operatorname{acot} 239 + + There are actually infinitely many formulas of this type. Two + others are + + .. math :: + + \frac{\pi}{4} = \operatorname{acot} 1 + + \frac{\pi}{4} = 12 \operatorname{acot} 49 + 32 \operatorname{acot} 57 + + 5 \operatorname{acot} 239 + 12 \operatorname{acot} 110443 + + We can easily verify the formulas using the PSLQ algorithm:: + + >>> mp.dps = 30 + >>> pslq([pi/4, acot(1)]) + [1, -1] + >>> pslq([pi/4, acot(5), acot(239)]) + [1, -4, 1] + >>> pslq([pi/4, acot(49), acot(57), acot(239), acot(110443)]) + [1, -12, -32, 5, -12] + + We could try to generate a custom Machin-like formula by running + the PSLQ algorithm with a few inverse cotangent values, for example + acot(2), acot(3) ... acot(10). Unfortunately, there is a linear + dependence among these values, resulting in only that dependence + being detected, with a zero coefficient for `\pi`:: + + >>> pslq([pi] + [acot(n) for n in range(2,11)]) + [0, 1, -1, 0, 0, 0, -1, 0, 0, 0] + + We get better luck by removing linearly dependent terms:: + + >>> pslq([pi] + [acot(n) for n in range(2,11) if n not in (3, 5)]) + [1, -8, 0, 0, 4, 0, 0, 0] + + In other words, we found the following formula:: + + >>> 8*acot(2) - 4*acot(7) + 3.14159265358979323846264338328 + >>> +pi + 3.14159265358979323846264338328 + + **Algorithm** + + This is a fairly direct translation to Python of the pseudocode given by + David Bailey, "The PSLQ Integer Relation Algorithm": + http://www.cecm.sfu.ca/organics/papers/bailey/paper/html/node3.html + + The present implementation uses fixed-point instead of floating-point + arithmetic, since this is significantly (about 7x) faster. + """ + + n = len(x) + if n < 2: + raise ValueError("n cannot be less than 2") + + # At too low precision, the algorithm becomes meaningless + prec = ctx.prec + if prec < 53: + raise ValueError("prec cannot be less than 53") + + if verbose and prec // max(2,n) < 5: + print("Warning: precision for PSLQ may be too low") + + target = int(prec * 0.75) + + if tol is None: + tol = ctx.mpf(2)**(-target) + else: + tol = ctx.convert(tol) + + extra = 60 + prec += extra + + if verbose: + print("PSLQ using prec %i and tol %s" % (prec, ctx.nstr(tol))) + + tol = ctx.to_fixed(tol, prec) + assert tol + + # Convert to fixed-point numbers. The dummy None is added so we can + # use 1-based indexing. (This just allows us to be consistent with + # Bailey's indexing. The algorithm is 100 lines long, so debugging + # a single wrong index can be painful.) + x = [None] + [ctx.to_fixed(ctx.mpf(xk), prec) for xk in x] + + # Sanity check on magnitudes + minx = min(abs(xx) for xx in x[1:]) + if not minx: + raise ValueError("PSLQ requires a vector of nonzero numbers") + if minx < tol//100: + if verbose: + print("STOPPING: (one number is too small)") + return None + + g = sqrt_fixed((4<> prec) + s[k] = sqrt_fixed(t, prec) + t = s[1] + y = x[:] + for k in xrange(1, n+1): + y[k] = (x[k] << prec) // t + s[k] = (s[k] << prec) // t + # step 3 + for i in xrange(1, n+1): + for j in xrange(i+1, n): + H[i,j] = 0 + if i <= n-1: + if s[i]: + H[i,i] = (s[i+1] << prec) // s[i] + else: + H[i,i] = 0 + for j in range(1, i): + sjj1 = s[j]*s[j+1] + if sjj1: + H[i,j] = ((-y[i]*y[j])<> prec) + for k in xrange(1, j+1): + H[i,k] = H[i,k] - (t*H[j,k] >> prec) + for k in xrange(1, n+1): + A[i,k] = A[i,k] - (t*A[j,k] >> prec) + B[k,j] = B[k,j] + (t*B[k,i] >> prec) + # Main algorithm + for REP in range(maxsteps): + # Step 1 + m = -1 + szmax = -1 + for i in range(1, n): + h = H[i,i] + sz = (g**i * abs(h)) >> (prec*(i-1)) + if sz > szmax: + m = i + szmax = sz + # Step 2 + y[m], y[m+1] = y[m+1], y[m] + for i in xrange(1,n+1): H[m,i], H[m+1,i] = H[m+1,i], H[m,i] + for i in xrange(1,n+1): A[m,i], A[m+1,i] = A[m+1,i], A[m,i] + for i in xrange(1,n+1): B[i,m], B[i,m+1] = B[i,m+1], B[i,m] + # Step 3 + if m <= n - 2: + t0 = sqrt_fixed((H[m,m]**2 + H[m,m+1]**2)>>prec, prec) + # A zero element probably indicates that the precision has + # been exhausted. XXX: this could be spurious, due to + # using fixed-point arithmetic + if not t0: + break + t1 = (H[m,m] << prec) // t0 + t2 = (H[m,m+1] << prec) // t0 + for i in xrange(m, n+1): + t3 = H[i,m] + t4 = H[i,m+1] + H[i,m] = (t1*t3+t2*t4) >> prec + H[i,m+1] = (-t2*t3+t1*t4) >> prec + # Step 4 + for i in xrange(m+1, n+1): + for j in xrange(min(i-1, m+1), 0, -1): + try: + t = round_fixed((H[i,j] << prec)//H[j,j], prec) + # Precision probably exhausted + except ZeroDivisionError: + break + y[j] = y[j] + ((t*y[i]) >> prec) + for k in xrange(1, j+1): + H[i,k] = H[i,k] - (t*H[j,k] >> prec) + for k in xrange(1, n+1): + A[i,k] = A[i,k] - (t*A[j,k] >> prec) + B[k,j] = B[k,j] + (t*B[k,i] >> prec) + # Until a relation is found, the error typically decreases + # slowly (e.g. a factor 1-10) with each step TODO: we could + # compare err from two successive iterations. If there is a + # large drop (several orders of magnitude), that indicates a + # "high quality" relation was detected. Reporting this to + # the user somehow might be useful. + best_err = maxcoeff<> prec) for j in \ + range(1,n+1)] + if max(abs(v) for v in vec) < maxcoeff: + if verbose: + print("FOUND relation at iter %i/%i, error: %s" % \ + (REP, maxsteps, ctx.nstr(err / ctx.mpf(2)**prec, 1))) + return vec + best_err = min(err, best_err) + # Calculate a lower bound for the norm. We could do this + # more exactly (using the Euclidean norm) but there is probably + # no practical benefit. + recnorm = max(abs(h) for h in H.values()) + if recnorm: + norm = ((1 << (2*prec)) // recnorm) >> prec + norm //= 100 + else: + norm = ctx.inf + if verbose: + print("%i/%i: Error: %8s Norm: %s" % \ + (REP, maxsteps, ctx.nstr(best_err / ctx.mpf(2)**prec, 1), norm)) + if norm >= maxcoeff: + break + if verbose: + print("CANCELLING after step %i/%i." % (REP, maxsteps)) + print("Could not find an integer relation. Norm bound: %s" % norm) + return None + +def findpoly(ctx, x, n=1, **kwargs): + r""" + ``findpoly(x, n)`` returns the coefficients of an integer + polynomial `P` of degree at most `n` such that `P(x) \approx 0`. + If no polynomial having `x` as a root can be found, + :func:`~mpmath.findpoly` returns ``None``. + + :func:`~mpmath.findpoly` works by successively calling :func:`~mpmath.pslq` with + the vectors `[1, x]`, `[1, x, x^2]`, `[1, x, x^2, x^3]`, ..., + `[1, x, x^2, .., x^n]` as input. Keyword arguments given to + :func:`~mpmath.findpoly` are forwarded verbatim to :func:`~mpmath.pslq`. In + particular, you can specify a tolerance for `P(x)` with ``tol`` + and a maximum permitted coefficient size with ``maxcoeff``. + + For large values of `n`, it is recommended to run :func:`~mpmath.findpoly` + at high precision; preferably 50 digits or more. + + **Examples** + + By default (degree `n = 1`), :func:`~mpmath.findpoly` simply finds a linear + polynomial with a rational root:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> findpoly(0.7) + [-10, 7] + + The generated coefficient list is valid input to ``polyval`` and + ``polyroots``:: + + >>> nprint(polyval(findpoly(phi, 2), phi), 1) + -2.0e-16 + >>> for r in polyroots(findpoly(phi, 2)): + ... print(r) + ... + -0.618033988749895 + 1.61803398874989 + + Numbers of the form `m + n \sqrt p` for integers `(m, n, p)` are + solutions to quadratic equations. As we find here, `1+\sqrt 2` + is a root of the polynomial `x^2 - 2x - 1`:: + + >>> findpoly(1+sqrt(2), 2) + [1, -2, -1] + >>> findroot(lambda x: x**2 - 2*x - 1, 1) + 2.4142135623731 + + Despite only containing square roots, the following number results + in a polynomial of degree 4:: + + >>> findpoly(sqrt(2)+sqrt(3), 4) + [1, 0, -10, 0, 1] + + In fact, `x^4 - 10x^2 + 1` is the *minimal polynomial* of + `r = \sqrt 2 + \sqrt 3`, meaning that a rational polynomial of + lower degree having `r` as a root does not exist. Given sufficient + precision, :func:`~mpmath.findpoly` will usually find the correct + minimal polynomial of a given algebraic number. + + **Non-algebraic numbers** + + If :func:`~mpmath.findpoly` fails to find a polynomial with given + coefficient size and tolerance constraints, that means no such + polynomial exists. + + We can verify that `\pi` is not an algebraic number of degree 3 with + coefficients less than 1000:: + + >>> mp.dps = 15 + >>> findpoly(pi, 3) + >>> + + It is always possible to find an algebraic approximation of a number + using one (or several) of the following methods: + + 1. Increasing the permitted degree + 2. Allowing larger coefficients + 3. Reducing the tolerance + + One example of each method is shown below:: + + >>> mp.dps = 15 + >>> findpoly(pi, 4) + [95, -545, 863, -183, -298] + >>> findpoly(pi, 3, maxcoeff=10000) + [836, -1734, -2658, -457] + >>> findpoly(pi, 3, tol=1e-7) + [-4, 22, -29, -2] + + It is unknown whether Euler's constant is transcendental (or even + irrational). We can use :func:`~mpmath.findpoly` to check that if is + an algebraic number, its minimal polynomial must have degree + at least 7 and a coefficient of magnitude at least 1000000:: + + >>> mp.dps = 200 + >>> findpoly(euler, 6, maxcoeff=10**6, tol=1e-100, maxsteps=1000) + >>> + + Note that the high precision and strict tolerance is necessary + for such high-degree runs, since otherwise unwanted low-accuracy + approximations will be detected. It may also be necessary to set + maxsteps high to prevent a premature exit (before the coefficient + bound has been reached). Running with ``verbose=True`` to get an + idea what is happening can be useful. + """ + x = ctx.mpf(x) + if n < 1: + raise ValueError("n cannot be less than 1") + if x == 0: + return [1, 0] + xs = [ctx.mpf(1)] + for i in range(1,n+1): + xs.append(x**i) + a = ctx.pslq(xs, **kwargs) + if a is not None: + return a[::-1] + +def fracgcd(p, q): + x, y = p, q + while y: + x, y = y, x % y + if x != 1: + p //= x + q //= x + if q == 1: + return p + return p, q + +def pslqstring(r, constants): + q = r[0] + r = r[1:] + s = [] + for i in range(len(r)): + p = r[i] + if p: + z = fracgcd(-p,q) + cs = constants[i][1] + if cs == '1': + cs = '' + else: + cs = '*' + cs + if isinstance(z, int_types): + if z > 0: term = str(z) + cs + else: term = ("(%s)" % z) + cs + else: + term = ("(%s/%s)" % z) + cs + s.append(term) + s = ' + '.join(s) + if '+' in s or '*' in s: + s = '(' + s + ')' + return s or '0' + +def prodstring(r, constants): + q = r[0] + r = r[1:] + num = [] + den = [] + for i in range(len(r)): + p = r[i] + if p: + z = fracgcd(-p,q) + cs = constants[i][1] + if isinstance(z, int_types): + if abs(z) == 1: t = cs + else: t = '%s**%s' % (cs, abs(z)) + ([num,den][z<0]).append(t) + else: + t = '%s**(%s/%s)' % (cs, abs(z[0]), z[1]) + ([num,den][z[0]<0]).append(t) + num = '*'.join(num) + den = '*'.join(den) + if num and den: return "(%s)/(%s)" % (num, den) + if num: return num + if den: return "1/(%s)" % den + +def quadraticstring(ctx,t,a,b,c): + if c < 0: + a,b,c = -a,-b,-c + u1 = (-b+ctx.sqrt(b**2-4*a*c))/(2*c) + u2 = (-b-ctx.sqrt(b**2-4*a*c))/(2*c) + if abs(u1-t) < abs(u2-t): + if b: s = '((%s+sqrt(%s))/%s)' % (-b,b**2-4*a*c,2*c) + else: s = '(sqrt(%s)/%s)' % (-4*a*c,2*c) + else: + if b: s = '((%s-sqrt(%s))/%s)' % (-b,b**2-4*a*c,2*c) + else: s = '(-sqrt(%s)/%s)' % (-4*a*c,2*c) + return s + +# Transformation y = f(x,c), with inverse function x = f(y,c) +# The third entry indicates whether the transformation is +# redundant when c = 1 +transforms = [ + (lambda ctx,x,c: x*c, '$y/$c', 0), + (lambda ctx,x,c: x/c, '$c*$y', 1), + (lambda ctx,x,c: c/x, '$c/$y', 0), + (lambda ctx,x,c: (x*c)**2, 'sqrt($y)/$c', 0), + (lambda ctx,x,c: (x/c)**2, '$c*sqrt($y)', 1), + (lambda ctx,x,c: (c/x)**2, '$c/sqrt($y)', 0), + (lambda ctx,x,c: c*x**2, 'sqrt($y)/sqrt($c)', 1), + (lambda ctx,x,c: x**2/c, 'sqrt($c)*sqrt($y)', 1), + (lambda ctx,x,c: c/x**2, 'sqrt($c)/sqrt($y)', 1), + (lambda ctx,x,c: ctx.sqrt(x*c), '$y**2/$c', 0), + (lambda ctx,x,c: ctx.sqrt(x/c), '$c*$y**2', 1), + (lambda ctx,x,c: ctx.sqrt(c/x), '$c/$y**2', 0), + (lambda ctx,x,c: c*ctx.sqrt(x), '$y**2/$c**2', 1), + (lambda ctx,x,c: ctx.sqrt(x)/c, '$c**2*$y**2', 1), + (lambda ctx,x,c: c/ctx.sqrt(x), '$c**2/$y**2', 1), + (lambda ctx,x,c: ctx.exp(x*c), 'log($y)/$c', 0), + (lambda ctx,x,c: ctx.exp(x/c), '$c*log($y)', 1), + (lambda ctx,x,c: ctx.exp(c/x), '$c/log($y)', 0), + (lambda ctx,x,c: c*ctx.exp(x), 'log($y/$c)', 1), + (lambda ctx,x,c: ctx.exp(x)/c, 'log($c*$y)', 1), + (lambda ctx,x,c: c/ctx.exp(x), 'log($c/$y)', 0), + (lambda ctx,x,c: ctx.ln(x*c), 'exp($y)/$c', 0), + (lambda ctx,x,c: ctx.ln(x/c), '$c*exp($y)', 1), + (lambda ctx,x,c: ctx.ln(c/x), '$c/exp($y)', 0), + (lambda ctx,x,c: c*ctx.ln(x), 'exp($y/$c)', 1), + (lambda ctx,x,c: ctx.ln(x)/c, 'exp($c*$y)', 1), + (lambda ctx,x,c: c/ctx.ln(x), 'exp($c/$y)', 0), +] + +def identify(ctx, x, constants=[], tol=None, maxcoeff=1000, full=False, + verbose=False): + r""" + Given a real number `x`, ``identify(x)`` attempts to find an exact + formula for `x`. This formula is returned as a string. If no match + is found, ``None`` is returned. With ``full=True``, a list of + matching formulas is returned. + + As a simple example, :func:`~mpmath.identify` will find an algebraic + formula for the golden ratio:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> identify(phi) + '((1+sqrt(5))/2)' + + :func:`~mpmath.identify` can identify simple algebraic numbers and simple + combinations of given base constants, as well as certain basic + transformations thereof. More specifically, :func:`~mpmath.identify` + looks for the following: + + 1. Fractions + 2. Quadratic algebraic numbers + 3. Rational linear combinations of the base constants + 4. Any of the above after first transforming `x` into `f(x)` where + `f(x)` is `1/x`, `\sqrt x`, `x^2`, `\log x` or `\exp x`, either + directly or with `x` or `f(x)` multiplied or divided by one of + the base constants + 5. Products of fractional powers of the base constants and + small integers + + Base constants can be given as a list of strings representing mpmath + expressions (:func:`~mpmath.identify` will ``eval`` the strings to numerical + values and use the original strings for the output), or as a dict of + formula:value pairs. + + In order not to produce spurious results, :func:`~mpmath.identify` should + be used with high precision; preferably 50 digits or more. + + **Examples** + + Simple identifications can be performed safely at standard + precision. Here the default recognition of rational, algebraic, + and exp/log of algebraic numbers is demonstrated:: + + >>> mp.dps = 15 + >>> identify(0.22222222222222222) + '(2/9)' + >>> identify(1.9662210973805663) + 'sqrt(((24+sqrt(48))/8))' + >>> identify(4.1132503787829275) + 'exp((sqrt(8)/2))' + >>> identify(0.881373587019543) + 'log(((2+sqrt(8))/2))' + + By default, :func:`~mpmath.identify` does not recognize `\pi`. At standard + precision it finds a not too useful approximation. At slightly + increased precision, this approximation is no longer accurate + enough and :func:`~mpmath.identify` more correctly returns ``None``:: + + >>> identify(pi) + '(2**(176/117)*3**(20/117)*5**(35/39))/(7**(92/117))' + >>> mp.dps = 30 + >>> identify(pi) + >>> + + Numbers such as `\pi`, and simple combinations of user-defined + constants, can be identified if they are provided explicitly:: + + >>> identify(3*pi-2*e, ['pi', 'e']) + '(3*pi + (-2)*e)' + + Here is an example using a dict of constants. Note that the + constants need not be "atomic"; :func:`~mpmath.identify` can just + as well express the given number in terms of expressions + given by formulas:: + + >>> identify(pi+e, {'a':pi+2, 'b':2*e}) + '((-2) + 1*a + (1/2)*b)' + + Next, we attempt some identifications with a set of base constants. + It is necessary to increase the precision a bit. + + >>> mp.dps = 50 + >>> base = ['sqrt(2)','pi','log(2)'] + >>> identify(0.25, base) + '(1/4)' + >>> identify(3*pi + 2*sqrt(2) + 5*log(2)/7, base) + '(2*sqrt(2) + 3*pi + (5/7)*log(2))' + >>> identify(exp(pi+2), base) + 'exp((2 + 1*pi))' + >>> identify(1/(3+sqrt(2)), base) + '((3/7) + (-1/7)*sqrt(2))' + >>> identify(sqrt(2)/(3*pi+4), base) + 'sqrt(2)/(4 + 3*pi)' + >>> identify(5**(mpf(1)/3)*pi*log(2)**2, base) + '5**(1/3)*pi*log(2)**2' + + An example of an erroneous solution being found when too low + precision is used:: + + >>> mp.dps = 15 + >>> identify(1/(3*pi-4*e+sqrt(8)), ['pi', 'e', 'sqrt(2)']) + '((11/25) + (-158/75)*pi + (76/75)*e + (44/15)*sqrt(2))' + >>> mp.dps = 50 + >>> identify(1/(3*pi-4*e+sqrt(8)), ['pi', 'e', 'sqrt(2)']) + '1/(3*pi + (-4)*e + 2*sqrt(2))' + + **Finding approximate solutions** + + The tolerance ``tol`` defaults to 3/4 of the working precision. + Lowering the tolerance is useful for finding approximate matches. + We can for example try to generate approximations for pi:: + + >>> mp.dps = 15 + >>> identify(pi, tol=1e-2) + '(22/7)' + >>> identify(pi, tol=1e-3) + '(355/113)' + >>> identify(pi, tol=1e-10) + '(5**(339/269))/(2**(64/269)*3**(13/269)*7**(92/269))' + + With ``full=True``, and by supplying a few base constants, + ``identify`` can generate almost endless lists of approximations + for any number (the output below has been truncated to show only + the first few):: + + >>> for p in identify(pi, ['e', 'catalan'], tol=1e-5, full=True): + ... print(p) + ... # doctest: +ELLIPSIS + e/log((6 + (-4/3)*e)) + (3**3*5*e*catalan**2)/(2*7**2) + sqrt(((-13) + 1*e + 22*catalan)) + log(((-6) + 24*e + 4*catalan)/e) + exp(catalan*((-1/5) + (8/15)*e)) + catalan*(6 + (-6)*e + 15*catalan) + sqrt((5 + 26*e + (-3)*catalan))/e + e*sqrt(((-27) + 2*e + 25*catalan)) + log(((-1) + (-11)*e + 59*catalan)) + ((3/20) + (21/20)*e + (3/20)*catalan) + ... + + The numerical values are roughly as close to `\pi` as permitted by the + specified tolerance: + + >>> e/log(6-4*e/3) + 3.14157719846001 + >>> 135*e*catalan**2/98 + 3.14166950419369 + >>> sqrt(e-13+22*catalan) + 3.14158000062992 + >>> log(24*e-6+4*catalan)-1 + 3.14158791577159 + + **Symbolic processing** + + The output formula can be evaluated as a Python expression. + Note however that if fractions (like '2/3') are present in + the formula, Python's :func:`~mpmath.eval()` may erroneously perform + integer division. Note also that the output is not necessarily + in the algebraically simplest form:: + + >>> identify(sqrt(2)) + '(sqrt(8)/2)' + + As a solution to both problems, consider using SymPy's + :func:`~mpmath.sympify` to convert the formula into a symbolic expression. + SymPy can be used to pretty-print or further simplify the formula + symbolically:: + + >>> from sympy import sympify # doctest: +SKIP + >>> sympify(identify(sqrt(2))) # doctest: +SKIP + 2**(1/2) + + Sometimes :func:`~mpmath.identify` can simplify an expression further than + a symbolic algorithm:: + + >>> from sympy import simplify # doctest: +SKIP + >>> x = sympify('-1/(-3/2+(1/2)*5**(1/2))*(3/2-1/2*5**(1/2))**(1/2)') # doctest: +SKIP + >>> x # doctest: +SKIP + (3/2 - 5**(1/2)/2)**(-1/2) + >>> x = simplify(x) # doctest: +SKIP + >>> x # doctest: +SKIP + 2/(6 - 2*5**(1/2))**(1/2) + >>> mp.dps = 30 # doctest: +SKIP + >>> x = sympify(identify(x.evalf(30))) # doctest: +SKIP + >>> x # doctest: +SKIP + 1/2 + 5**(1/2)/2 + + (In fact, this functionality is available directly in SymPy as the + function :func:`~mpmath.nsimplify`, which is essentially a wrapper for + :func:`~mpmath.identify`.) + + **Miscellaneous issues and limitations** + + The input `x` must be a real number. All base constants must be + positive real numbers and must not be rationals or rational linear + combinations of each other. + + The worst-case computation time grows quickly with the number of + base constants. Already with 3 or 4 base constants, + :func:`~mpmath.identify` may require several seconds to finish. To search + for relations among a large number of constants, you should + consider using :func:`~mpmath.pslq` directly. + + The extended transformations are applied to x, not the constants + separately. As a result, ``identify`` will for example be able to + recognize ``exp(2*pi+3)`` with ``pi`` given as a base constant, but + not ``2*exp(pi)+3``. It will be able to recognize the latter if + ``exp(pi)`` is given explicitly as a base constant. + + """ + + solutions = [] + + def addsolution(s): + if verbose: print("Found: ", s) + solutions.append(s) + + x = ctx.mpf(x) + + # Further along, x will be assumed positive + if x == 0: + if full: return ['0'] + else: return '0' + if x < 0: + sol = ctx.identify(-x, constants, tol, maxcoeff, full, verbose) + if sol is None: + return sol + if full: + return ["-(%s)"%s for s in sol] + else: + return "-(%s)" % sol + + if tol: + tol = ctx.mpf(tol) + else: + tol = ctx.eps**0.7 + M = maxcoeff + + if constants: + if isinstance(constants, dict): + constants = [(ctx.mpf(v), name) for (name, v) in sorted(constants.items())] + else: + namespace = dict((name, getattr(ctx,name)) for name in dir(ctx)) + constants = [(eval(p, namespace), p) for p in constants] + else: + constants = [] + + # We always want to find at least rational terms + if 1 not in [value for (name, value) in constants]: + constants = [(ctx.mpf(1), '1')] + constants + + # PSLQ with simple algebraic and functional transformations + for ft, ftn, red in transforms: + for c, cn in constants: + if red and cn == '1': + continue + t = ft(ctx,x,c) + # Prevent exponential transforms from wreaking havoc + if abs(t) > M**2 or abs(t) < tol: + continue + # Linear combination of base constants + r = ctx.pslq([t] + [a[0] for a in constants], tol, M) + s = None + if r is not None and max(abs(uw) for uw in r) <= M and r[0]: + s = pslqstring(r, constants) + # Quadratic algebraic numbers + else: + q = ctx.pslq([ctx.one, t, t**2], tol, M) + if q is not None and len(q) == 3 and q[2]: + aa, bb, cc = q + if max(abs(aa),abs(bb),abs(cc)) <= M: + s = quadraticstring(ctx,t,aa,bb,cc) + if s: + if cn == '1' and ('/$c' in ftn): + s = ftn.replace('$y', s).replace('/$c', '') + else: + s = ftn.replace('$y', s).replace('$c', cn) + addsolution(s) + if not full: return solutions[0] + + if verbose: + print(".") + + # Check for a direct multiplicative formula + if x != 1: + # Allow fractional powers of fractions + ilogs = [2,3,5,7] + # Watch out for existing fractional powers of fractions + logs = [] + for a, s in constants: + if not sum(bool(ctx.findpoly(ctx.ln(a)/ctx.ln(i),1)) for i in ilogs): + logs.append((ctx.ln(a), s)) + logs = [(ctx.ln(i),str(i)) for i in ilogs] + logs + r = ctx.pslq([ctx.ln(x)] + [a[0] for a in logs], tol, M) + if r is not None and max(abs(uw) for uw in r) <= M and r[0]: + addsolution(prodstring(r, logs)) + if not full: return solutions[0] + + if full: + return sorted(solutions, key=len) + else: + return None + +IdentificationMethods.pslq = pslq +IdentificationMethods.findpoly = findpoly +IdentificationMethods.identify = identify + + +if __name__ == '__main__': + import doctest + doctest.testmod() diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/__init__.py b/venv/lib/python3.10/site-packages/mpmath/libmp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1573114afc4fbce73f2ba9d2ddc99882c00027c0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/libmp/__init__.py @@ -0,0 +1,77 @@ +from .libmpf import (prec_to_dps, dps_to_prec, repr_dps, + round_down, round_up, round_floor, round_ceiling, round_nearest, + to_pickable, from_pickable, ComplexResult, + fzero, fnzero, fone, fnone, ftwo, ften, fhalf, fnan, finf, fninf, + math_float_inf, round_int, normalize, normalize1, + from_man_exp, from_int, to_man_exp, to_int, mpf_ceil, mpf_floor, + mpf_nint, mpf_frac, + from_float, from_npfloat, from_Decimal, to_float, from_rational, to_rational, to_fixed, + mpf_rand, mpf_eq, mpf_hash, mpf_cmp, mpf_lt, mpf_le, mpf_gt, mpf_ge, + mpf_pos, mpf_neg, mpf_abs, mpf_sign, mpf_add, mpf_sub, mpf_sum, + mpf_mul, mpf_mul_int, mpf_shift, mpf_frexp, + mpf_div, mpf_rdiv_int, mpf_mod, mpf_pow_int, + mpf_perturb, + to_digits_exp, to_str, str_to_man_exp, from_str, from_bstr, to_bstr, + mpf_sqrt, mpf_hypot) + +from .libmpc import (mpc_one, mpc_zero, mpc_two, mpc_half, + mpc_is_inf, mpc_is_infnan, mpc_to_str, mpc_to_complex, mpc_hash, + mpc_conjugate, mpc_is_nonzero, mpc_add, mpc_add_mpf, + mpc_sub, mpc_sub_mpf, mpc_pos, mpc_neg, mpc_shift, mpc_abs, + mpc_arg, mpc_floor, mpc_ceil, mpc_nint, mpc_frac, mpc_mul, mpc_square, + mpc_mul_mpf, mpc_mul_imag_mpf, mpc_mul_int, + mpc_div, mpc_div_mpf, mpc_reciprocal, mpc_mpf_div, + complex_int_pow, mpc_pow, mpc_pow_mpf, mpc_pow_int, + mpc_sqrt, mpc_nthroot, mpc_cbrt, mpc_exp, mpc_log, mpc_cos, mpc_sin, + mpc_tan, mpc_cos_pi, mpc_sin_pi, mpc_cosh, mpc_sinh, mpc_tanh, + mpc_atan, mpc_acos, mpc_asin, mpc_asinh, mpc_acosh, mpc_atanh, + mpc_fibonacci, mpf_expj, mpf_expjpi, mpc_expj, mpc_expjpi, + mpc_cos_sin, mpc_cos_sin_pi) + +from .libelefun import (ln2_fixed, mpf_ln2, ln10_fixed, mpf_ln10, + pi_fixed, mpf_pi, e_fixed, mpf_e, phi_fixed, mpf_phi, + degree_fixed, mpf_degree, + mpf_pow, mpf_nthroot, mpf_cbrt, log_int_fixed, agm_fixed, + mpf_log, mpf_log_hypot, mpf_exp, mpf_cos_sin, mpf_cos, mpf_sin, mpf_tan, + mpf_cos_sin_pi, mpf_cos_pi, mpf_sin_pi, mpf_cosh_sinh, + mpf_cosh, mpf_sinh, mpf_tanh, mpf_atan, mpf_atan2, mpf_asin, + mpf_acos, mpf_asinh, mpf_acosh, mpf_atanh, mpf_fibonacci) + +from .libhyper import (NoConvergence, make_hyp_summator, + mpf_erf, mpf_erfc, mpf_ei, mpc_ei, mpf_e1, mpc_e1, mpf_expint, + mpf_ci_si, mpf_ci, mpf_si, mpc_ci, mpc_si, mpf_besseljn, + mpc_besseljn, mpf_agm, mpf_agm1, mpc_agm, mpc_agm1, + mpf_ellipk, mpc_ellipk, mpf_ellipe, mpc_ellipe) + +from .gammazeta import (catalan_fixed, mpf_catalan, + khinchin_fixed, mpf_khinchin, glaisher_fixed, mpf_glaisher, + apery_fixed, mpf_apery, euler_fixed, mpf_euler, mertens_fixed, + mpf_mertens, twinprime_fixed, mpf_twinprime, + mpf_bernoulli, bernfrac, mpf_gamma_int, + mpf_factorial, mpc_factorial, mpf_gamma, mpc_gamma, + mpf_loggamma, mpc_loggamma, mpf_rgamma, mpc_rgamma, + mpf_harmonic, mpc_harmonic, mpf_psi0, mpc_psi0, + mpf_psi, mpc_psi, mpf_zeta_int, mpf_zeta, mpc_zeta, + mpf_altzeta, mpc_altzeta, mpf_zetasum, mpc_zetasum) + +from .libmpi import (mpi_str, + mpi_from_str, mpi_to_str, + mpi_eq, mpi_ne, + mpi_lt, mpi_le, mpi_gt, mpi_ge, + mpi_add, mpi_sub, mpi_delta, mpi_mid, + mpi_pos, mpi_neg, mpi_abs, mpi_mul, mpi_div, mpi_exp, + mpi_log, mpi_sqrt, mpi_pow_int, mpi_pow, mpi_cos_sin, + mpi_cos, mpi_sin, mpi_tan, mpi_cot, + mpi_atan, mpi_atan2, + mpci_pos, mpci_neg, mpci_add, mpci_sub, mpci_mul, mpci_div, mpci_pow, + mpci_abs, mpci_pow, mpci_exp, mpci_log, mpci_cos, mpci_sin, + mpi_gamma, mpci_gamma, mpi_loggamma, mpci_loggamma, + mpi_rgamma, mpci_rgamma, mpi_factorial, mpci_factorial) + +from .libintmath import (trailing, bitcount, numeral, bin_to_radix, + isqrt, isqrt_small, isqrt_fast, sqrt_fixed, sqrtrem, ifib, ifac, + list_primes, isprime, moebius, gcd, eulernum, stirling1, stirling2) + +from .backend import (gmpy, sage, BACKEND, STRICT, MPZ, MPZ_TYPE, + MPZ_ZERO, MPZ_ONE, MPZ_TWO, MPZ_THREE, MPZ_FIVE, int_types, + HASH_MODULUS, HASH_BITS) diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebfb66646196f63f0976dd93c784722bcb6b04fb Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/backend.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/backend.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fc40eec45c2acf13d43e25ef9ce8e8e9ba3fba2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/backend.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/gammazeta.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/gammazeta.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..251b26cd8f349fd001c6e4c8b5e2740cabbff714 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/gammazeta.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libelefun.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libelefun.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f6d1792a8ee2c5724ab829cee8e80cc39ee70b7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libelefun.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libhyper.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libhyper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a59155e95b13ac4fe7dbf4bae5c036a69aae62bd Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libhyper.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libintmath.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libintmath.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7578e6a4063e16b3be4d03bbae08dbed8ab5d68 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libintmath.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libmpc.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libmpc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c34831afa573bc1eaf3bcbf7bfcbdcb1baa5a97 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libmpc.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libmpf.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libmpf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40b8c4ed3b02119696ee6ada5229d3357c50c7fb Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libmpf.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libmpi.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libmpi.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4eba4dda3d7240ead3bcfa37f57c944ff3ec387a Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/libmp/__pycache__/libmpi.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/backend.py b/venv/lib/python3.10/site-packages/mpmath/libmp/backend.py new file mode 100644 index 0000000000000000000000000000000000000000..5610221290a05078f21f09df3c1a76b0e4ccdc02 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/libmp/backend.py @@ -0,0 +1,115 @@ +import os +import sys + +#----------------------------------------------------------------------------# +# Support GMPY for high-speed large integer arithmetic. # +# # +# To allow an external module to handle arithmetic, we need to make sure # +# that all high-precision variables are declared of the correct type. MPZ # +# is the constructor for the high-precision type. It defaults to Python's # +# long type but can be assinged another type, typically gmpy.mpz. # +# # +# MPZ must be used for the mantissa component of an mpf and must be used # +# for internal fixed-point operations. # +# # +# Side-effects # +# 1) "is" cannot be used to test for special values. Must use "==". # +# 2) There are bugs in GMPY prior to v1.02 so we must use v1.03 or later. # +#----------------------------------------------------------------------------# + +# So we can import it from this module +gmpy = None +sage = None +sage_utils = None + +if sys.version_info[0] < 3: + python3 = False +else: + python3 = True + +BACKEND = 'python' + +if not python3: + MPZ = long + xrange = xrange + basestring = basestring + + def exec_(_code_, _globs_=None, _locs_=None): + """Execute code in a namespace.""" + if _globs_ is None: + frame = sys._getframe(1) + _globs_ = frame.f_globals + if _locs_ is None: + _locs_ = frame.f_locals + del frame + elif _locs_ is None: + _locs_ = _globs_ + exec("""exec _code_ in _globs_, _locs_""") +else: + MPZ = int + xrange = range + basestring = str + + import builtins + exec_ = getattr(builtins, "exec") + +# Define constants for calculating hash on Python 3.2. +if sys.version_info >= (3, 2): + HASH_MODULUS = sys.hash_info.modulus + if sys.hash_info.width == 32: + HASH_BITS = 31 + else: + HASH_BITS = 61 +else: + HASH_MODULUS = None + HASH_BITS = None + +if 'MPMATH_NOGMPY' not in os.environ: + try: + try: + import gmpy2 as gmpy + except ImportError: + try: + import gmpy + except ImportError: + raise ImportError + if gmpy.version() >= '1.03': + BACKEND = 'gmpy' + MPZ = gmpy.mpz + except: + pass + +if ('MPMATH_NOSAGE' not in os.environ and 'SAGE_ROOT' in os.environ or + 'MPMATH_SAGE' in os.environ): + try: + import sage.all + import sage.libs.mpmath.utils as _sage_utils + sage = sage.all + sage_utils = _sage_utils + BACKEND = 'sage' + MPZ = sage.Integer + except: + pass + +if 'MPMATH_STRICT' in os.environ: + STRICT = True +else: + STRICT = False + +MPZ_TYPE = type(MPZ(0)) +MPZ_ZERO = MPZ(0) +MPZ_ONE = MPZ(1) +MPZ_TWO = MPZ(2) +MPZ_THREE = MPZ(3) +MPZ_FIVE = MPZ(5) + +try: + if BACKEND == 'python': + int_types = (int, long) + else: + int_types = (int, long, MPZ_TYPE) +except NameError: + if BACKEND == 'python': + int_types = (int,) + else: + int_types = (int, MPZ_TYPE) diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/gammazeta.py b/venv/lib/python3.10/site-packages/mpmath/libmp/gammazeta.py new file mode 100644 index 0000000000000000000000000000000000000000..3b05cc63c5f00e6c76d8383853dba06f15e46030 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/libmp/gammazeta.py @@ -0,0 +1,2167 @@ +""" +----------------------------------------------------------------------- +This module implements gamma- and zeta-related functions: + +* Bernoulli numbers +* Factorials +* The gamma function +* Polygamma functions +* Harmonic numbers +* The Riemann zeta function +* Constants related to these functions + +----------------------------------------------------------------------- +""" + +import math +import sys + +from .backend import xrange +from .backend import MPZ, MPZ_ZERO, MPZ_ONE, MPZ_THREE, gmpy + +from .libintmath import list_primes, ifac, ifac2, moebius + +from .libmpf import (\ + round_floor, round_ceiling, round_down, round_up, + round_nearest, round_fast, + lshift, sqrt_fixed, isqrt_fast, + fzero, fone, fnone, fhalf, ftwo, finf, fninf, fnan, + from_int, to_int, to_fixed, from_man_exp, from_rational, + mpf_pos, mpf_neg, mpf_abs, mpf_add, mpf_sub, + mpf_mul, mpf_mul_int, mpf_div, mpf_sqrt, mpf_pow_int, + mpf_rdiv_int, + mpf_perturb, mpf_le, mpf_lt, mpf_gt, mpf_shift, + negative_rnd, reciprocal_rnd, + bitcount, to_float, mpf_floor, mpf_sign, ComplexResult +) + +from .libelefun import (\ + constant_memo, + def_mpf_constant, + mpf_pi, pi_fixed, ln2_fixed, log_int_fixed, mpf_ln2, + mpf_exp, mpf_log, mpf_pow, mpf_cosh, + mpf_cos_sin, mpf_cosh_sinh, mpf_cos_sin_pi, mpf_cos_pi, mpf_sin_pi, + ln_sqrt2pi_fixed, mpf_ln_sqrt2pi, sqrtpi_fixed, mpf_sqrtpi, + cos_sin_fixed, exp_fixed +) + +from .libmpc import (\ + mpc_zero, mpc_one, mpc_half, mpc_two, + mpc_abs, mpc_shift, mpc_pos, mpc_neg, + mpc_add, mpc_sub, mpc_mul, mpc_div, + mpc_add_mpf, mpc_mul_mpf, mpc_div_mpf, mpc_mpf_div, + mpc_mul_int, mpc_pow_int, + mpc_log, mpc_exp, mpc_pow, + mpc_cos_pi, mpc_sin_pi, + mpc_reciprocal, mpc_square, + mpc_sub_mpf +) + + + +# Catalan's constant is computed using Lupas's rapidly convergent series +# (listed on http://mathworld.wolfram.com/CatalansConstant.html) +# oo +# ___ n-1 8n 2 3 2 +# 1 \ (-1) 2 (40n - 24n + 3) [(2n)!] (n!) +# K = --- ) ----------------------------------------- +# 64 /___ 3 2 +# n (2n-1) [(4n)!] +# n = 1 + +@constant_memo +def catalan_fixed(prec): + prec = prec + 20 + a = one = MPZ_ONE << prec + s, t, n = 0, 1, 1 + while t: + a *= 32 * n**3 * (2*n-1) + a //= (3-16*n+16*n**2)**2 + t = a * (-1)**(n-1) * (40*n**2-24*n+3) // (n**3 * (2*n-1)) + s += t + n += 1 + return s >> (20 + 6) + +# Khinchin's constant is relatively difficult to compute. Here +# we use the rational zeta series + +# oo 2*n-1 +# ___ ___ +# \ ` zeta(2*n)-1 \ ` (-1)^(k+1) +# log(K)*log(2) = ) ------------ ) ---------- +# /___. n /___. k +# n = 1 k = 1 + +# which adds half a digit per term. The essential trick for achieving +# reasonable efficiency is to recycle both the values of the zeta +# function (essentially Bernoulli numbers) and the partial terms of +# the inner sum. + +# An alternative might be to use K = 2*exp[1/log(2) X] where + +# / 1 1 [ pi*x*(1-x^2) ] +# X = | ------ log [ ------------ ]. +# / 0 x(1+x) [ sin(pi*x) ] + +# and integrate numerically. In practice, this seems to be slightly +# slower than the zeta series at high precision. + +@constant_memo +def khinchin_fixed(prec): + wp = int(prec + prec**0.5 + 15) + s = MPZ_ZERO + fac = from_int(4) + t = ONE = MPZ_ONE << wp + pi = mpf_pi(wp) + pipow = twopi2 = mpf_shift(mpf_mul(pi, pi, wp), 2) + n = 1 + while 1: + zeta2n = mpf_abs(mpf_bernoulli(2*n, wp)) + zeta2n = mpf_mul(zeta2n, pipow, wp) + zeta2n = mpf_div(zeta2n, fac, wp) + zeta2n = to_fixed(zeta2n, wp) + term = (((zeta2n - ONE) * t) // n) >> wp + if term < 100: + break + #if not n % 10: + # print n, math.log(int(abs(term))) + s += term + t += ONE//(2*n+1) - ONE//(2*n) + n += 1 + fac = mpf_mul_int(fac, (2*n)*(2*n-1), wp) + pipow = mpf_mul(pipow, twopi2, wp) + s = (s << wp) // ln2_fixed(wp) + K = mpf_exp(from_man_exp(s, -wp), wp) + K = to_fixed(K, prec) + return K + + +# Glaisher's constant is defined as A = exp(1/2 - zeta'(-1)). +# One way to compute it would be to perform direct numerical +# differentiation, but computing arbitrary Riemann zeta function +# values at high precision is expensive. We instead use the formula + +# A = exp((6 (-zeta'(2))/pi^2 + log 2 pi + gamma)/12) + +# and compute zeta'(2) from the series representation + +# oo +# ___ +# \ log k +# -zeta'(2) = ) ----- +# /___ 2 +# k +# k = 2 + +# This series converges exceptionally slowly, but can be accelerated +# using Euler-Maclaurin formula. The important insight is that the +# E-M integral can be done in closed form and that the high order +# are given by + +# n / \ +# d | log x | a + b log x +# --- | ----- | = ----------- +# n | 2 | 2 + n +# dx \ x / x + +# where a and b are integers given by a simple recurrence. Note +# that just one logarithm is needed. However, lots of integer +# logarithms are required for the initial summation. + +# This algorithm could possibly be turned into a faster algorithm +# for general evaluation of zeta(s) or zeta'(s); this should be +# looked into. + +@constant_memo +def glaisher_fixed(prec): + wp = prec + 30 + # Number of direct terms to sum before applying the Euler-Maclaurin + # formula to the tail. TODO: choose more intelligently + N = int(0.33*prec + 5) + ONE = MPZ_ONE << wp + # Euler-Maclaurin, step 1: sum log(k)/k**2 for k from 2 to N-1 + s = MPZ_ZERO + for k in range(2, N): + #print k, N + s += log_int_fixed(k, wp) // k**2 + logN = log_int_fixed(N, wp) + #logN = to_fixed(mpf_log(from_int(N), wp+20), wp) + # E-M step 2: integral of log(x)/x**2 from N to inf + s += (ONE + logN) // N + # E-M step 3: endpoint correction term f(N)/2 + s += logN // (N**2 * 2) + # E-M step 4: the series of derivatives + pN = N**3 + a = 1 + b = -2 + j = 3 + fac = from_int(2) + k = 1 + while 1: + # D(2*k-1) * B(2*k) / fac(2*k) [D(n) = nth derivative] + D = ((a << wp) + b*logN) // pN + D = from_man_exp(D, -wp) + B = mpf_bernoulli(2*k, wp) + term = mpf_mul(B, D, wp) + term = mpf_div(term, fac, wp) + term = to_fixed(term, wp) + if abs(term) < 100: + break + #if not k % 10: + # print k, math.log(int(abs(term)), 10) + s -= term + # Advance derivative twice + a, b, pN, j = b-a*j, -j*b, pN*N, j+1 + a, b, pN, j = b-a*j, -j*b, pN*N, j+1 + k += 1 + fac = mpf_mul_int(fac, (2*k)*(2*k-1), wp) + # A = exp((6*s/pi**2 + log(2*pi) + euler)/12) + pi = pi_fixed(wp) + s *= 6 + s = (s << wp) // (pi**2 >> wp) + s += euler_fixed(wp) + s += to_fixed(mpf_log(from_man_exp(2*pi, -wp), wp), wp) + s //= 12 + A = mpf_exp(from_man_exp(s, -wp), wp) + return to_fixed(A, prec) + +# Apery's constant can be computed using the very rapidly convergent +# series +# oo +# ___ 2 10 +# \ n 205 n + 250 n + 77 (n!) +# zeta(3) = ) (-1) ------------------- ---------- +# /___ 64 5 +# n = 0 ((2n+1)!) + +@constant_memo +def apery_fixed(prec): + prec += 20 + d = MPZ_ONE << prec + term = MPZ(77) << prec + n = 1 + s = MPZ_ZERO + while term: + s += term + d *= (n**10) + d //= (((2*n+1)**5) * (2*n)**5) + term = (-1)**n * (205*(n**2) + 250*n + 77) * d + n += 1 + return s >> (20 + 6) + +""" +Euler's constant (gamma) is computed using the Brent-McMillan formula, +gamma ~= I(n)/J(n) - log(n), where + + I(n) = sum_{k=0,1,2,...} (n**k / k!)**2 * H(k) + J(n) = sum_{k=0,1,2,...} (n**k / k!)**2 + H(k) = 1 + 1/2 + 1/3 + ... + 1/k + +The error is bounded by O(exp(-4n)). Choosing n to be a power +of two, 2**p, the logarithm becomes particularly easy to calculate.[1] + +We use the formulation of Algorithm 3.9 in [2] to make the summation +more efficient. + +Reference: +[1] Xavier Gourdon & Pascal Sebah, The Euler constant: gamma +http://numbers.computation.free.fr/Constants/Gamma/gamma.pdf + +[2] [BorweinBailey]_ +""" + +@constant_memo +def euler_fixed(prec): + extra = 30 + prec += extra + # choose p such that exp(-4*(2**p)) < 2**-n + p = int(math.log((prec/4) * math.log(2), 2)) + 1 + n = 2**p + A = U = -p*ln2_fixed(prec) + B = V = MPZ_ONE << prec + k = 1 + while 1: + B = B*n**2//k**2 + A = (A*n**2//k + B)//k + U += A + V += B + if max(abs(A), abs(B)) < 100: + break + k += 1 + return (U<<(prec-extra))//V + +# Use zeta accelerated formulas for the Mertens and twin +# prime constants; see +# http://mathworld.wolfram.com/MertensConstant.html +# http://mathworld.wolfram.com/TwinPrimesConstant.html + +@constant_memo +def mertens_fixed(prec): + wp = prec + 20 + m = 2 + s = mpf_euler(wp) + while 1: + t = mpf_zeta_int(m, wp) + if t == fone: + break + t = mpf_log(t, wp) + t = mpf_mul_int(t, moebius(m), wp) + t = mpf_div(t, from_int(m), wp) + s = mpf_add(s, t) + m += 1 + return to_fixed(s, prec) + +@constant_memo +def twinprime_fixed(prec): + def I(n): + return sum(moebius(d)<<(n//d) for d in xrange(1,n+1) if not n%d)//n + wp = 2*prec + 30 + res = fone + primes = [from_rational(1,p,wp) for p in [2,3,5,7]] + ppowers = [mpf_mul(p,p,wp) for p in primes] + n = 2 + while 1: + a = mpf_zeta_int(n, wp) + for i in range(4): + a = mpf_mul(a, mpf_sub(fone, ppowers[i]), wp) + ppowers[i] = mpf_mul(ppowers[i], primes[i], wp) + a = mpf_pow_int(a, -I(n), wp) + if mpf_pos(a, prec+10, 'n') == fone: + break + #from libmpf import to_str + #print n, to_str(mpf_sub(fone, a), 6) + res = mpf_mul(res, a, wp) + n += 1 + res = mpf_mul(res, from_int(3*15*35), wp) + res = mpf_div(res, from_int(4*16*36), wp) + return to_fixed(res, prec) + + +mpf_euler = def_mpf_constant(euler_fixed) +mpf_apery = def_mpf_constant(apery_fixed) +mpf_khinchin = def_mpf_constant(khinchin_fixed) +mpf_glaisher = def_mpf_constant(glaisher_fixed) +mpf_catalan = def_mpf_constant(catalan_fixed) +mpf_mertens = def_mpf_constant(mertens_fixed) +mpf_twinprime = def_mpf_constant(twinprime_fixed) + + +#-----------------------------------------------------------------------# +# # +# Bernoulli numbers # +# # +#-----------------------------------------------------------------------# + +MAX_BERNOULLI_CACHE = 3000 + + +r""" +Small Bernoulli numbers and factorials are used in numerous summations, +so it is critical for speed that sequential computation is fast and that +values are cached up to a fairly high threshold. + +On the other hand, we also want to support fast computation of isolated +large numbers. Currently, no such acceleration is provided for integer +factorials (though it is for large floating-point factorials, which are +computed via gamma if the precision is low enough). + +For sequential computation of Bernoulli numbers, we use Ramanujan's formula + + / n + 3 \ + B = (A(n) - S(n)) / | | + n \ n / + +where A(n) = (n+3)/3 when n = 0 or 2 (mod 6), A(n) = -(n+3)/6 +when n = 4 (mod 6), and + + [n/6] + ___ + \ / n + 3 \ + S(n) = ) | | * B + /___ \ n - 6*k / n-6*k + k = 1 + +For isolated large Bernoulli numbers, we use the Riemann zeta function +to calculate a numerical value for B_n. The von Staudt-Clausen theorem +can then be used to optionally find the exact value of the +numerator and denominator. +""" + +bernoulli_cache = {} +f3 = from_int(3) +f6 = from_int(6) + +def bernoulli_size(n): + """Accurately estimate the size of B_n (even n > 2 only)""" + lgn = math.log(n,2) + return int(2.326 + 0.5*lgn + n*(lgn - 4.094)) + +BERNOULLI_PREC_CUTOFF = bernoulli_size(MAX_BERNOULLI_CACHE) + +def mpf_bernoulli(n, prec, rnd=None): + """Computation of Bernoulli numbers (numerically)""" + if n < 2: + if n < 0: + raise ValueError("Bernoulli numbers only defined for n >= 0") + if n == 0: + return fone + if n == 1: + return mpf_neg(fhalf) + # For odd n > 1, the Bernoulli numbers are zero + if n & 1: + return fzero + # If precision is extremely high, we can save time by computing + # the Bernoulli number at a lower precision that is sufficient to + # obtain the exact fraction, round to the exact fraction, and + # convert the fraction back to an mpf value at the original precision + if prec > BERNOULLI_PREC_CUTOFF and prec > bernoulli_size(n)*1.1 + 1000: + p, q = bernfrac(n) + return from_rational(p, q, prec, rnd or round_floor) + if n > MAX_BERNOULLI_CACHE: + return mpf_bernoulli_huge(n, prec, rnd) + wp = prec + 30 + # Reuse nearby precisions + wp += 32 - (prec & 31) + cached = bernoulli_cache.get(wp) + if cached: + numbers, state = cached + if n in numbers: + if not rnd: + return numbers[n] + return mpf_pos(numbers[n], prec, rnd) + m, bin, bin1 = state + if n - m > 10: + return mpf_bernoulli_huge(n, prec, rnd) + else: + if n > 10: + return mpf_bernoulli_huge(n, prec, rnd) + numbers = {0:fone} + m, bin, bin1 = state = [2, MPZ(10), MPZ_ONE] + bernoulli_cache[wp] = (numbers, state) + while m <= n: + #print m + case = m % 6 + # Accurately estimate size of B_m so we can use + # fixed point math without using too much precision + szbm = bernoulli_size(m) + s = 0 + sexp = max(0, szbm) - wp + if m < 6: + a = MPZ_ZERO + else: + a = bin1 + for j in xrange(1, m//6+1): + usign, uman, uexp, ubc = u = numbers[m-6*j] + if usign: + uman = -uman + s += lshift(a*uman, uexp-sexp) + # Update inner binomial coefficient + j6 = 6*j + a *= ((m-5-j6)*(m-4-j6)*(m-3-j6)*(m-2-j6)*(m-1-j6)*(m-j6)) + a //= ((4+j6)*(5+j6)*(6+j6)*(7+j6)*(8+j6)*(9+j6)) + if case == 0: b = mpf_rdiv_int(m+3, f3, wp) + if case == 2: b = mpf_rdiv_int(m+3, f3, wp) + if case == 4: b = mpf_rdiv_int(-m-3, f6, wp) + s = from_man_exp(s, sexp, wp) + b = mpf_div(mpf_sub(b, s, wp), from_int(bin), wp) + numbers[m] = b + m += 2 + # Update outer binomial coefficient + bin = bin * ((m+2)*(m+3)) // (m*(m-1)) + if m > 6: + bin1 = bin1 * ((2+m)*(3+m)) // ((m-7)*(m-6)) + state[:] = [m, bin, bin1] + return numbers[n] + +def mpf_bernoulli_huge(n, prec, rnd=None): + wp = prec + 10 + piprec = wp + int(math.log(n,2)) + v = mpf_gamma_int(n+1, wp) + v = mpf_mul(v, mpf_zeta_int(n, wp), wp) + v = mpf_mul(v, mpf_pow_int(mpf_pi(piprec), -n, wp)) + v = mpf_shift(v, 1-n) + if not n & 3: + v = mpf_neg(v) + return mpf_pos(v, prec, rnd or round_fast) + +def bernfrac(n): + r""" + Returns a tuple of integers `(p, q)` such that `p/q = B_n` exactly, + where `B_n` denotes the `n`-th Bernoulli number. The fraction is + always reduced to lowest terms. Note that for `n > 1` and `n` odd, + `B_n = 0`, and `(0, 1)` is returned. + + **Examples** + + The first few Bernoulli numbers are exactly:: + + >>> from mpmath import * + >>> for n in range(15): + ... p, q = bernfrac(n) + ... print("%s %s/%s" % (n, p, q)) + ... + 0 1/1 + 1 -1/2 + 2 1/6 + 3 0/1 + 4 -1/30 + 5 0/1 + 6 1/42 + 7 0/1 + 8 -1/30 + 9 0/1 + 10 5/66 + 11 0/1 + 12 -691/2730 + 13 0/1 + 14 7/6 + + This function works for arbitrarily large `n`:: + + >>> p, q = bernfrac(10**4) + >>> print(q) + 2338224387510 + >>> print(len(str(p))) + 27692 + >>> mp.dps = 15 + >>> print(mpf(p) / q) + -9.04942396360948e+27677 + >>> print(bernoulli(10**4)) + -9.04942396360948e+27677 + + .. note :: + + :func:`~mpmath.bernoulli` computes a floating-point approximation + directly, without computing the exact fraction first. + This is much faster for large `n`. + + **Algorithm** + + :func:`~mpmath.bernfrac` works by computing the value of `B_n` numerically + and then using the von Staudt-Clausen theorem [1] to reconstruct + the exact fraction. For large `n`, this is significantly faster than + computing `B_1, B_2, \ldots, B_2` recursively with exact arithmetic. + The implementation has been tested for `n = 10^m` up to `m = 6`. + + In practice, :func:`~mpmath.bernfrac` appears to be about three times + slower than the specialized program calcbn.exe [2] + + **References** + + 1. MathWorld, von Staudt-Clausen Theorem: + http://mathworld.wolfram.com/vonStaudt-ClausenTheorem.html + + 2. The Bernoulli Number Page: + http://www.bernoulli.org/ + + """ + n = int(n) + if n < 3: + return [(1, 1), (-1, 2), (1, 6)][n] + if n & 1: + return (0, 1) + q = 1 + for k in list_primes(n+1): + if not (n % (k-1)): + q *= k + prec = bernoulli_size(n) + int(math.log(q,2)) + 20 + b = mpf_bernoulli(n, prec) + p = mpf_mul(b, from_int(q)) + pint = to_int(p, round_nearest) + return (pint, q) + + +#-----------------------------------------------------------------------# +# # +# Polygamma functions # +# # +#-----------------------------------------------------------------------# + +r""" +For all polygamma (psi) functions, we use the Euler-Maclaurin summation +formula. It looks slightly different in the m = 0 and m > 0 cases. + +For m = 0, we have + oo + ___ B + (0) 1 \ 2 k -2 k + psi (z) ~ log z + --- - ) ------ z + 2 z /___ (2 k)! + k = 1 + +Experiment shows that the minimum term of the asymptotic series +reaches 2^(-p) when Re(z) > 0.11*p. So we simply use the recurrence +for psi (equivalent, in fact, to summing to the first few terms +directly before applying E-M) to obtain z large enough. + +Since, very crudely, log z ~= 1 for Re(z) > 1, we can use +fixed-point arithmetic (if z is extremely large, log(z) itself +is a sufficient approximation, so we can stop there already). + +For Re(z) << 0, we could use recurrence, but this is of course +inefficient for large negative z, so there we use the +reflection formula instead. + +For m > 0, we have + + N - 1 + ___ + ~~~(m) [ \ 1 ] 1 1 + psi (z) ~ [ ) -------- ] + ---------- + -------- + + [ /___ m+1 ] m+1 m + k = 1 (z+k) ] 2 (z+N) m (z+N) + + oo + ___ B + \ 2 k (m+1) (m+2) ... (m+2k-1) + + ) ------ ------------------------ + /___ (2 k)! m + 2 k + k = 1 (z+N) + +where ~~~ denotes the function rescaled by 1/((-1)^(m+1) m!). + +Here again N is chosen to make z+N large enough for the minimum +term in the last series to become smaller than eps. + +TODO: the current estimation of N for m > 0 is *very suboptimal*. + +TODO: implement the reflection formula for m > 0, Re(z) << 0. +It is generally a combination of multiple cotangents. Need to +figure out a reasonably simple way to generate these formulas +on the fly. + +TODO: maybe use exact algorithms to compute psi for integral +and certain rational arguments, as this can be much more +efficient. (On the other hand, the availability of these +special values provides a convenient way to test the general +algorithm.) +""" + +# Harmonic numbers are just shifted digamma functions +# We should calculate these exactly when x is an integer +# and when doing so is faster. + +def mpf_harmonic(x, prec, rnd): + if x in (fzero, fnan, finf): + return x + a = mpf_psi0(mpf_add(fone, x, prec+5), prec) + return mpf_add(a, mpf_euler(prec+5, rnd), prec, rnd) + +def mpc_harmonic(z, prec, rnd): + if z[1] == fzero: + return (mpf_harmonic(z[0], prec, rnd), fzero) + a = mpc_psi0(mpc_add_mpf(z, fone, prec+5), prec) + return mpc_add_mpf(a, mpf_euler(prec+5, rnd), prec, rnd) + +def mpf_psi0(x, prec, rnd=round_fast): + """ + Computation of the digamma function (psi function of order 0) + of a real argument. + """ + sign, man, exp, bc = x + wp = prec + 10 + if not man: + if x == finf: return x + if x == fninf or x == fnan: return fnan + if x == fzero or (exp >= 0 and sign): + raise ValueError("polygamma pole") + # Near 0 -- fixed-point arithmetic becomes bad + if exp+bc < -5: + v = mpf_psi0(mpf_add(x, fone, prec, rnd), prec, rnd) + return mpf_sub(v, mpf_div(fone, x, wp, rnd), prec, rnd) + # Reflection formula + if sign and exp+bc > 3: + c, s = mpf_cos_sin_pi(x, wp) + q = mpf_mul(mpf_div(c, s, wp), mpf_pi(wp), wp) + p = mpf_psi0(mpf_sub(fone, x, wp), wp) + return mpf_sub(p, q, prec, rnd) + # The logarithmic term is accurate enough + if (not sign) and bc + exp > wp: + return mpf_log(mpf_sub(x, fone, wp), prec, rnd) + # Initial recurrence to obtain a large enough x + m = to_int(x) + n = int(0.11*wp) + 2 + s = MPZ_ZERO + x = to_fixed(x, wp) + one = MPZ_ONE << wp + if m < n: + for k in xrange(m, n): + s -= (one << wp) // x + x += one + x -= one + # Logarithmic term + s += to_fixed(mpf_log(from_man_exp(x, -wp, wp), wp), wp) + # Endpoint term in Euler-Maclaurin expansion + s += (one << wp) // (2*x) + # Euler-Maclaurin remainder sum + x2 = (x*x) >> wp + t = one + prev = 0 + k = 1 + while 1: + t = (t*x2) >> wp + bsign, bman, bexp, bbc = mpf_bernoulli(2*k, wp) + offset = (bexp + 2*wp) + if offset >= 0: term = (bman << offset) // (t*(2*k)) + else: term = (bman >> (-offset)) // (t*(2*k)) + if k & 1: s -= term + else: s += term + if k > 2 and term >= prev: + break + prev = term + k += 1 + return from_man_exp(s, -wp, wp, rnd) + +def mpc_psi0(z, prec, rnd=round_fast): + """ + Computation of the digamma function (psi function of order 0) + of a complex argument. + """ + re, im = z + # Fall back to the real case + if im == fzero: + return (mpf_psi0(re, prec, rnd), fzero) + wp = prec + 20 + sign, man, exp, bc = re + # Reflection formula + if sign and exp+bc > 3: + c = mpc_cos_pi(z, wp) + s = mpc_sin_pi(z, wp) + q = mpc_mul_mpf(mpc_div(c, s, wp), mpf_pi(wp), wp) + p = mpc_psi0(mpc_sub(mpc_one, z, wp), wp) + return mpc_sub(p, q, prec, rnd) + # Just the logarithmic term + if (not sign) and bc + exp > wp: + return mpc_log(mpc_sub(z, mpc_one, wp), prec, rnd) + # Initial recurrence to obtain a large enough z + w = to_int(re) + n = int(0.11*wp) + 2 + s = mpc_zero + if w < n: + for k in xrange(w, n): + s = mpc_sub(s, mpc_reciprocal(z, wp), wp) + z = mpc_add_mpf(z, fone, wp) + z = mpc_sub(z, mpc_one, wp) + # Logarithmic and endpoint term + s = mpc_add(s, mpc_log(z, wp), wp) + s = mpc_add(s, mpc_div(mpc_half, z, wp), wp) + # Euler-Maclaurin remainder sum + z2 = mpc_square(z, wp) + t = mpc_one + prev = mpc_zero + szprev = fzero + k = 1 + eps = mpf_shift(fone, -wp+2) + while 1: + t = mpc_mul(t, z2, wp) + bern = mpf_bernoulli(2*k, wp) + term = mpc_mpf_div(bern, mpc_mul_int(t, 2*k, wp), wp) + s = mpc_sub(s, term, wp) + szterm = mpc_abs(term, 10) + if k > 2 and (mpf_le(szterm, eps) or mpf_le(szprev, szterm)): + break + prev = term + szprev = szterm + k += 1 + return s + +# Currently unoptimized +def mpf_psi(m, x, prec, rnd=round_fast): + """ + Computation of the polygamma function of arbitrary integer order + m >= 0, for a real argument x. + """ + if m == 0: + return mpf_psi0(x, prec, rnd=round_fast) + return mpc_psi(m, (x, fzero), prec, rnd)[0] + +def mpc_psi(m, z, prec, rnd=round_fast): + """ + Computation of the polygamma function of arbitrary integer order + m >= 0, for a complex argument z. + """ + if m == 0: + return mpc_psi0(z, prec, rnd) + re, im = z + wp = prec + 20 + sign, man, exp, bc = re + if not im[1]: + if im in (finf, fninf, fnan): + return (fnan, fnan) + if not man: + if re == finf and im == fzero: + return (fzero, fzero) + if re == fnan: + return (fnan, fnan) + # Recurrence + w = to_int(re) + n = int(0.4*wp + 4*m) + s = mpc_zero + if w < n: + for k in xrange(w, n): + t = mpc_pow_int(z, -m-1, wp) + s = mpc_add(s, t, wp) + z = mpc_add_mpf(z, fone, wp) + zm = mpc_pow_int(z, -m, wp) + z2 = mpc_pow_int(z, -2, wp) + # 1/m*(z+N)^m + integral_term = mpc_div_mpf(zm, from_int(m), wp) + s = mpc_add(s, integral_term, wp) + # 1/2*(z+N)^(-(m+1)) + s = mpc_add(s, mpc_mul_mpf(mpc_div(zm, z, wp), fhalf, wp), wp) + a = m + 1 + b = 2 + k = 1 + # Important: we want to sum up to the *relative* error, + # not the absolute error, because psi^(m)(z) might be tiny + magn = mpc_abs(s, 10) + magn = magn[2]+magn[3] + eps = mpf_shift(fone, magn-wp+2) + while 1: + zm = mpc_mul(zm, z2, wp) + bern = mpf_bernoulli(2*k, wp) + scal = mpf_mul_int(bern, a, wp) + scal = mpf_div(scal, from_int(b), wp) + term = mpc_mul_mpf(zm, scal, wp) + s = mpc_add(s, term, wp) + szterm = mpc_abs(term, 10) + if k > 2 and mpf_le(szterm, eps): + break + #print k, to_str(szterm, 10), to_str(eps, 10) + a *= (m+2*k)*(m+2*k+1) + b *= (2*k+1)*(2*k+2) + k += 1 + # Scale and sign factor + v = mpc_mul_mpf(s, mpf_gamma(from_int(m+1), wp), prec, rnd) + if not (m & 1): + v = mpf_neg(v[0]), mpf_neg(v[1]) + return v + + +#-----------------------------------------------------------------------# +# # +# Riemann zeta function # +# # +#-----------------------------------------------------------------------# + +r""" +We use zeta(s) = eta(s) / (1 - 2**(1-s)) and Borwein's approximation + + n-1 + ___ k + -1 \ (-1) (d_k - d_n) + eta(s) ~= ---- ) ------------------ + d_n /___ s + k = 0 (k + 1) +where + k + ___ i + \ (n + i - 1)! 4 + d_k = n ) ---------------. + /___ (n - i)! (2i)! + i = 0 + +If s = a + b*I, the absolute error for eta(s) is bounded by + + 3 (1 + 2|b|) + ------------ * exp(|b| pi/2) + n + (3+sqrt(8)) + +Disregarding the linear term, we have approximately, + + log(err) ~= log(exp(1.58*|b|)) - log(5.8**n) + log(err) ~= 1.58*|b| - log(5.8)*n + log(err) ~= 1.58*|b| - 1.76*n + log2(err) ~= 2.28*|b| - 2.54*n + +So for p bits, we should choose n > (p + 2.28*|b|) / 2.54. + +References: +----------- + +Peter Borwein, "An Efficient Algorithm for the Riemann Zeta Function" +http://www.cecm.sfu.ca/personal/pborwein/PAPERS/P117.ps + +http://en.wikipedia.org/wiki/Dirichlet_eta_function +""" + +borwein_cache = {} + +def borwein_coefficients(n): + if n in borwein_cache: + return borwein_cache[n] + ds = [MPZ_ZERO] * (n+1) + d = MPZ_ONE + s = ds[0] = MPZ_ONE + for i in range(1, n+1): + d = d * 4 * (n+i-1) * (n-i+1) + d //= ((2*i) * ((2*i)-1)) + s += d + ds[i] = s + borwein_cache[n] = ds + return ds + +ZETA_INT_CACHE_MAX_PREC = 1000 +zeta_int_cache = {} + +def mpf_zeta_int(s, prec, rnd=round_fast): + """ + Optimized computation of zeta(s) for an integer s. + """ + wp = prec + 20 + s = int(s) + if s in zeta_int_cache and zeta_int_cache[s][0] >= wp: + return mpf_pos(zeta_int_cache[s][1], prec, rnd) + if s < 2: + if s == 1: + raise ValueError("zeta(1) pole") + if not s: + return mpf_neg(fhalf) + return mpf_div(mpf_bernoulli(-s+1, wp), from_int(s-1), prec, rnd) + # 2^-s term vanishes? + if s >= wp: + return mpf_perturb(fone, 0, prec, rnd) + # 5^-s term vanishes? + elif s >= wp*0.431: + t = one = 1 << wp + t += 1 << (wp - s) + t += one // (MPZ_THREE ** s) + t += 1 << max(0, wp - s*2) + return from_man_exp(t, -wp, prec, rnd) + else: + # Fast enough to sum directly? + # Even better, we use the Euler product (idea stolen from pari) + m = (float(wp)/(s-1) + 1) + if m < 30: + needed_terms = int(2.0**m + 1) + if needed_terms < int(wp/2.54 + 5) / 10: + t = fone + for k in list_primes(needed_terms): + #print k, needed_terms + powprec = int(wp - s*math.log(k,2)) + if powprec < 2: + break + a = mpf_sub(fone, mpf_pow_int(from_int(k), -s, powprec), wp) + t = mpf_mul(t, a, wp) + return mpf_div(fone, t, wp) + # Use Borwein's algorithm + n = int(wp/2.54 + 5) + d = borwein_coefficients(n) + t = MPZ_ZERO + s = MPZ(s) + for k in xrange(n): + t += (((-1)**k * (d[k] - d[n])) << wp) // (k+1)**s + t = (t << wp) // (-d[n]) + t = (t << wp) // ((1 << wp) - (1 << (wp+1-s))) + if (s in zeta_int_cache and zeta_int_cache[s][0] < wp) or (s not in zeta_int_cache): + zeta_int_cache[s] = (wp, from_man_exp(t, -wp-wp)) + return from_man_exp(t, -wp-wp, prec, rnd) + +def mpf_zeta(s, prec, rnd=round_fast, alt=0): + sign, man, exp, bc = s + if not man: + if s == fzero: + if alt: + return fhalf + else: + return mpf_neg(fhalf) + if s == finf: + return fone + return fnan + wp = prec + 20 + # First term vanishes? + if (not sign) and (exp + bc > (math.log(wp,2) + 2)): + return mpf_perturb(fone, alt, prec, rnd) + # Optimize for integer arguments + elif exp >= 0: + if alt: + if s == fone: + return mpf_ln2(prec, rnd) + z = mpf_zeta_int(to_int(s), wp, negative_rnd[rnd]) + q = mpf_sub(fone, mpf_pow(ftwo, mpf_sub(fone, s, wp), wp), wp) + return mpf_mul(z, q, prec, rnd) + else: + return mpf_zeta_int(to_int(s), prec, rnd) + # Negative: use the reflection formula + # Borwein only proves the accuracy bound for x >= 1/2. However, based on + # tests, the accuracy without reflection is quite good even some distance + # to the left of 1/2. XXX: verify this. + if sign: + # XXX: could use the separate refl. formula for Dirichlet eta + if alt: + q = mpf_sub(fone, mpf_pow(ftwo, mpf_sub(fone, s, wp), wp), wp) + return mpf_mul(mpf_zeta(s, wp), q, prec, rnd) + # XXX: -1 should be done exactly + y = mpf_sub(fone, s, 10*wp) + a = mpf_gamma(y, wp) + b = mpf_zeta(y, wp) + c = mpf_sin_pi(mpf_shift(s, -1), wp) + wp2 = wp + max(0,exp+bc) + pi = mpf_pi(wp+wp2) + d = mpf_div(mpf_pow(mpf_shift(pi, 1), s, wp2), pi, wp2) + return mpf_mul(a,mpf_mul(b,mpf_mul(c,d,wp),wp),prec,rnd) + + # Near pole + r = mpf_sub(fone, s, wp) + asign, aman, aexp, abc = mpf_abs(r) + pole_dist = -2*(aexp+abc) + if pole_dist > wp: + if alt: + return mpf_ln2(prec, rnd) + else: + q = mpf_neg(mpf_div(fone, r, wp)) + return mpf_add(q, mpf_euler(wp), prec, rnd) + else: + wp += max(0, pole_dist) + + t = MPZ_ZERO + #wp += 16 - (prec & 15) + # Use Borwein's algorithm + n = int(wp/2.54 + 5) + d = borwein_coefficients(n) + t = MPZ_ZERO + sf = to_fixed(s, wp) + ln2 = ln2_fixed(wp) + for k in xrange(n): + u = (-sf*log_int_fixed(k+1, wp, ln2)) >> wp + #esign, eman, eexp, ebc = mpf_exp(u, wp) + #offset = eexp + wp + #if offset >= 0: + # w = ((d[k] - d[n]) * eman) << offset + #else: + # w = ((d[k] - d[n]) * eman) >> (-offset) + eman = exp_fixed(u, wp, ln2) + w = (d[k] - d[n]) * eman + if k & 1: + t -= w + else: + t += w + t = t // (-d[n]) + t = from_man_exp(t, -wp, wp) + if alt: + return mpf_pos(t, prec, rnd) + else: + q = mpf_sub(fone, mpf_pow(ftwo, mpf_sub(fone, s, wp), wp), wp) + return mpf_div(t, q, prec, rnd) + +def mpc_zeta(s, prec, rnd=round_fast, alt=0, force=False): + re, im = s + if im == fzero: + return mpf_zeta(re, prec, rnd, alt), fzero + + # slow for large s + if (not force) and mpf_gt(mpc_abs(s, 10), from_int(prec)): + raise NotImplementedError + + wp = prec + 20 + + # Near pole + r = mpc_sub(mpc_one, s, wp) + asign, aman, aexp, abc = mpc_abs(r, 10) + pole_dist = -2*(aexp+abc) + if pole_dist > wp: + if alt: + q = mpf_ln2(wp) + y = mpf_mul(q, mpf_euler(wp), wp) + g = mpf_shift(mpf_mul(q, q, wp), -1) + g = mpf_sub(y, g) + z = mpc_mul_mpf(r, mpf_neg(g), wp) + z = mpc_add_mpf(z, q, wp) + return mpc_pos(z, prec, rnd) + else: + q = mpc_neg(mpc_div(mpc_one, r, wp)) + q = mpc_add_mpf(q, mpf_euler(wp), wp) + return mpc_pos(q, prec, rnd) + else: + wp += max(0, pole_dist) + + # Reflection formula. To be rigorous, we should reflect to the left of + # re = 1/2 (see comments for mpf_zeta), but this leads to unnecessary + # slowdown for interesting values of s + if mpf_lt(re, fzero): + # XXX: could use the separate refl. formula for Dirichlet eta + if alt: + q = mpc_sub(mpc_one, mpc_pow(mpc_two, mpc_sub(mpc_one, s, wp), + wp), wp) + return mpc_mul(mpc_zeta(s, wp), q, prec, rnd) + # XXX: -1 should be done exactly + y = mpc_sub(mpc_one, s, 10*wp) + a = mpc_gamma(y, wp) + b = mpc_zeta(y, wp) + c = mpc_sin_pi(mpc_shift(s, -1), wp) + rsign, rman, rexp, rbc = re + isign, iman, iexp, ibc = im + mag = max(rexp+rbc, iexp+ibc) + wp2 = wp + max(0, mag) + pi = mpf_pi(wp+wp2) + pi2 = (mpf_shift(pi, 1), fzero) + d = mpc_div_mpf(mpc_pow(pi2, s, wp2), pi, wp2) + return mpc_mul(a,mpc_mul(b,mpc_mul(c,d,wp),wp),prec,rnd) + n = int(wp/2.54 + 5) + n += int(0.9*abs(to_int(im))) + d = borwein_coefficients(n) + ref = to_fixed(re, wp) + imf = to_fixed(im, wp) + tre = MPZ_ZERO + tim = MPZ_ZERO + one = MPZ_ONE << wp + one_2wp = MPZ_ONE << (2*wp) + critical_line = re == fhalf + ln2 = ln2_fixed(wp) + pi2 = pi_fixed(wp-1) + wp2 = wp+wp + for k in xrange(n): + log = log_int_fixed(k+1, wp, ln2) + # A square root is much cheaper than an exp + if critical_line: + w = one_2wp // isqrt_fast((k+1) << wp2) + else: + w = exp_fixed((-ref*log) >> wp, wp) + if k & 1: + w *= (d[n] - d[k]) + else: + w *= (d[k] - d[n]) + wre, wim = cos_sin_fixed((-imf*log)>>wp, wp, pi2) + tre += (w * wre) >> wp + tim += (w * wim) >> wp + tre //= (-d[n]) + tim //= (-d[n]) + tre = from_man_exp(tre, -wp, wp) + tim = from_man_exp(tim, -wp, wp) + if alt: + return mpc_pos((tre, tim), prec, rnd) + else: + q = mpc_sub(mpc_one, mpc_pow(mpc_two, r, wp), wp) + return mpc_div((tre, tim), q, prec, rnd) + +def mpf_altzeta(s, prec, rnd=round_fast): + return mpf_zeta(s, prec, rnd, 1) + +def mpc_altzeta(s, prec, rnd=round_fast): + return mpc_zeta(s, prec, rnd, 1) + +# Not optimized currently +mpf_zetasum = None + + +def pow_fixed(x, n, wp): + if n == 1: + return x + y = MPZ_ONE << wp + while n: + if n & 1: + y = (y*x) >> wp + n -= 1 + x = (x*x) >> wp + n //= 2 + return y + +# TODO: optimize / cleanup interface / unify with list_primes +sieve_cache = [] +primes_cache = [] +mult_cache = [] + +def primesieve(n): + global sieve_cache, primes_cache, mult_cache + if n < len(sieve_cache): + sieve = sieve_cache#[:n+1] + primes = primes_cache[:primes_cache.index(max(sieve))+1] + mult = mult_cache#[:n+1] + return sieve, primes, mult + sieve = [0] * (n+1) + mult = [0] * (n+1) + primes = list_primes(n) + for p in primes: + #sieve[p::p] = p + for k in xrange(p,n+1,p): + sieve[k] = p + for i, p in enumerate(sieve): + if i >= 2: + m = 1 + n = i // p + while not n % p: + n //= p + m += 1 + mult[i] = m + sieve_cache = sieve + primes_cache = primes + mult_cache = mult + return sieve, primes, mult + +def zetasum_sieved(critical_line, sre, sim, a, n, wp): + if a < 1: + raise ValueError("a cannot be less than 1") + sieve, primes, mult = primesieve(a+n) + basic_powers = {} + one = MPZ_ONE << wp + one_2wp = MPZ_ONE << (2*wp) + wp2 = wp+wp + ln2 = ln2_fixed(wp) + pi2 = pi_fixed(wp-1) + for p in primes: + if p*2 > a+n: + break + log = log_int_fixed(p, wp, ln2) + cos, sin = cos_sin_fixed((-sim*log)>>wp, wp, pi2) + if critical_line: + u = one_2wp // isqrt_fast(p<>wp, wp) + pre = (u*cos) >> wp + pim = (u*sin) >> wp + basic_powers[p] = [(pre, pim)] + tre, tim = pre, pim + for m in range(1,int(math.log(a+n,p)+0.01)+1): + tre, tim = ((pre*tre-pim*tim)>>wp), ((pim*tre+pre*tim)>>wp) + basic_powers[p].append((tre,tim)) + xre = MPZ_ZERO + xim = MPZ_ZERO + if a == 1: + xre += one + aa = max(a,2) + for k in xrange(aa, a+n+1): + p = sieve[k] + if p in basic_powers: + m = mult[k] + tre, tim = basic_powers[p][m-1] + while 1: + k //= p**m + if k == 1: + break + p = sieve[k] + m = mult[k] + pre, pim = basic_powers[p][m-1] + tre, tim = ((pre*tre-pim*tim)>>wp), ((pim*tre+pre*tim)>>wp) + else: + log = log_int_fixed(k, wp, ln2) + cos, sin = cos_sin_fixed((-sim*log)>>wp, wp, pi2) + if critical_line: + u = one_2wp // isqrt_fast(k<>wp, wp) + tre = (u*cos) >> wp + tim = (u*sin) >> wp + xre += tre + xim += tim + return xre, xim + +# Set to something large to disable +ZETASUM_SIEVE_CUTOFF = 10 + +def mpc_zetasum(s, a, n, derivatives, reflect, prec): + """ + Fast version of mp._zetasum, assuming s = complex, a = integer. + """ + + wp = prec + 10 + derivatives = list(derivatives) + have_derivatives = derivatives != [0] + have_one_derivative = len(derivatives) == 1 + + # parse s + sre, sim = s + critical_line = (sre == fhalf) + sre = to_fixed(sre, wp) + sim = to_fixed(sim, wp) + + if a > 0 and n > ZETASUM_SIEVE_CUTOFF and not have_derivatives \ + and not reflect and (n < 4e7 or sys.maxsize > 2**32): + re, im = zetasum_sieved(critical_line, sre, sim, a, n, wp) + xs = [(from_man_exp(re, -wp, prec, 'n'), from_man_exp(im, -wp, prec, 'n'))] + return xs, [] + + maxd = max(derivatives) + if not have_one_derivative: + derivatives = range(maxd+1) + + # x_d = 0, y_d = 0 + xre = [MPZ_ZERO for d in derivatives] + xim = [MPZ_ZERO for d in derivatives] + if reflect: + yre = [MPZ_ZERO for d in derivatives] + yim = [MPZ_ZERO for d in derivatives] + else: + yre = yim = [] + + one = MPZ_ONE << wp + one_2wp = MPZ_ONE << (2*wp) + + ln2 = ln2_fixed(wp) + pi2 = pi_fixed(wp-1) + wp2 = wp+wp + + for w in xrange(a, a+n+1): + log = log_int_fixed(w, wp, ln2) + cos, sin = cos_sin_fixed((-sim*log)>>wp, wp, pi2) + if critical_line: + u = one_2wp // isqrt_fast(w<>wp, wp) + xterm_re = (u * cos) >> wp + xterm_im = (u * sin) >> wp + if reflect: + reciprocal = (one_2wp // (u*w)) + yterm_re = (reciprocal * cos) >> wp + yterm_im = (reciprocal * sin) >> wp + + if have_derivatives: + if have_one_derivative: + log = pow_fixed(log, maxd, wp) + xre[0] += (xterm_re * log) >> wp + xim[0] += (xterm_im * log) >> wp + if reflect: + yre[0] += (yterm_re * log) >> wp + yim[0] += (yterm_im * log) >> wp + else: + t = MPZ_ONE << wp + for d in derivatives: + xre[d] += (xterm_re * t) >> wp + xim[d] += (xterm_im * t) >> wp + if reflect: + yre[d] += (yterm_re * t) >> wp + yim[d] += (yterm_im * t) >> wp + t = (t * log) >> wp + else: + xre[0] += xterm_re + xim[0] += xterm_im + if reflect: + yre[0] += yterm_re + yim[0] += yterm_im + if have_derivatives: + if have_one_derivative: + if maxd % 2: + xre[0] = -xre[0] + xim[0] = -xim[0] + if reflect: + yre[0] = -yre[0] + yim[0] = -yim[0] + else: + xre = [(-1)**d * xre[d] for d in derivatives] + xim = [(-1)**d * xim[d] for d in derivatives] + if reflect: + yre = [(-1)**d * yre[d] for d in derivatives] + yim = [(-1)**d * yim[d] for d in derivatives] + xs = [(from_man_exp(xa, -wp, prec, 'n'), from_man_exp(xb, -wp, prec, 'n')) + for (xa, xb) in zip(xre, xim)] + ys = [(from_man_exp(ya, -wp, prec, 'n'), from_man_exp(yb, -wp, prec, 'n')) + for (ya, yb) in zip(yre, yim)] + return xs, ys + + +#-----------------------------------------------------------------------# +# # +# The gamma function (NEW IMPLEMENTATION) # +# # +#-----------------------------------------------------------------------# + +# Higher means faster, but more precomputation time +MAX_GAMMA_TAYLOR_PREC = 5000 +# Need to derive higher bounds for Taylor series to go higher +assert MAX_GAMMA_TAYLOR_PREC < 15000 + +# Use Stirling's series if abs(x) > beta*prec +# Important: must be large enough for convergence! +GAMMA_STIRLING_BETA = 0.2 + +SMALL_FACTORIAL_CACHE_SIZE = 150 + +gamma_taylor_cache = {} +gamma_stirling_cache = {} + +small_factorial_cache = [from_int(ifac(n)) for \ + n in range(SMALL_FACTORIAL_CACHE_SIZE+1)] + +def zeta_array(N, prec): + """ + zeta(n) = A * pi**n / n! + B + + where A is a rational number (A = Bernoulli number + for n even) and B is an infinite sum over powers of exp(2*pi). + (B = 0 for n even). + + TODO: this is currently only used for gamma, but could + be very useful elsewhere. + """ + extra = 30 + wp = prec+extra + zeta_values = [MPZ_ZERO] * (N+2) + pi = pi_fixed(wp) + # STEP 1: + one = MPZ_ONE << wp + zeta_values[0] = -one//2 + f_2pi = mpf_shift(mpf_pi(wp),1) + exp_2pi_k = exp_2pi = mpf_exp(f_2pi, wp) + # Compute exponential series + # Store values of 1/(exp(2*pi*k)-1), + # exp(2*pi*k)/(exp(2*pi*k)-1)**2, 1/(exp(2*pi*k)-1)**2 + # pi*k*exp(2*pi*k)/(exp(2*pi*k)-1)**2 + exps3 = [] + k = 1 + while 1: + tp = wp - 9*k + if tp < 1: + break + # 1/(exp(2*pi*k-1) + q1 = mpf_div(fone, mpf_sub(exp_2pi_k, fone, tp), tp) + # pi*k*exp(2*pi*k)/(exp(2*pi*k)-1)**2 + q2 = mpf_mul(exp_2pi_k, mpf_mul(q1,q1,tp), tp) + q1 = to_fixed(q1, wp) + q2 = to_fixed(q2, wp) + q2 = (k * q2 * pi) >> wp + exps3.append((q1, q2)) + # Multiply for next round + exp_2pi_k = mpf_mul(exp_2pi_k, exp_2pi, wp) + k += 1 + # Exponential sum + for n in xrange(3, N+1, 2): + s = MPZ_ZERO + k = 1 + for e1, e2 in exps3: + if n%4 == 3: + t = e1 // k**n + else: + U = (n-1)//4 + t = (e1 + e2//U) // k**n + if not t: + break + s += t + k += 1 + zeta_values[n] = -2*s + # Even zeta values + B = [mpf_abs(mpf_bernoulli(k,wp)) for k in xrange(N+2)] + pi_pow = fpi = mpf_pow_int(mpf_shift(mpf_pi(wp), 1), 2, wp) + pi_pow = mpf_div(pi_pow, from_int(4), wp) + for n in xrange(2,N+2,2): + z = mpf_mul(B[n], pi_pow, wp) + zeta_values[n] = to_fixed(z, wp) + pi_pow = mpf_mul(pi_pow, fpi, wp) + pi_pow = mpf_div(pi_pow, from_int((n+1)*(n+2)), wp) + # Zeta sum + reciprocal_pi = (one << wp) // pi + for n in xrange(3, N+1, 4): + U = (n-3)//4 + s = zeta_values[4*U+4]*(4*U+7)//4 + for k in xrange(1, U+1): + s -= (zeta_values[4*k] * zeta_values[4*U+4-4*k]) >> wp + zeta_values[n] += (2*s*reciprocal_pi) >> wp + for n in xrange(5, N+1, 4): + U = (n-1)//4 + s = zeta_values[4*U+2]*(2*U+1) + for k in xrange(1, 2*U+1): + s += ((-1)**k*2*k* zeta_values[2*k] * zeta_values[4*U+2-2*k])>>wp + zeta_values[n] += ((s*reciprocal_pi)>>wp)//(2*U) + return [x>>extra for x in zeta_values] + +def gamma_taylor_coefficients(inprec): + """ + Gives the Taylor coefficients of 1/gamma(1+x) as + a list of fixed-point numbers. Enough coefficients are returned + to ensure that the series converges to the given precision + when x is in [0.5, 1.5]. + """ + # Reuse nearby cache values (small case) + if inprec < 400: + prec = inprec + (10-(inprec%10)) + elif inprec < 1000: + prec = inprec + (30-(inprec%30)) + else: + prec = inprec + if prec in gamma_taylor_cache: + return gamma_taylor_cache[prec], prec + + # Experimentally determined bounds + if prec < 1000: + N = int(prec**0.76 + 2) + else: + # Valid to at least 15000 bits + N = int(prec**0.787 + 2) + + # Reuse higher precision values + for cprec in gamma_taylor_cache: + if cprec > prec: + coeffs = [x>>(cprec-prec) for x in gamma_taylor_cache[cprec][-N:]] + if inprec < 1000: + gamma_taylor_cache[prec] = coeffs + return coeffs, prec + + # Cache at a higher precision (large case) + if prec > 1000: + prec = int(prec * 1.2) + + wp = prec + 20 + A = [0] * N + A[0] = MPZ_ZERO + A[1] = MPZ_ONE << wp + A[2] = euler_fixed(wp) + # SLOW, reference implementation + #zeta_values = [0,0]+[to_fixed(mpf_zeta_int(k,wp),wp) for k in xrange(2,N)] + zeta_values = zeta_array(N, wp) + for k in xrange(3, N): + a = (-A[2]*A[k-1])>>wp + for j in xrange(2,k): + a += ((-1)**j * zeta_values[j] * A[k-j]) >> wp + a //= (1-k) + A[k] = a + A = [a>>20 for a in A] + A = A[::-1] + A = A[:-1] + gamma_taylor_cache[prec] = A + #return A, prec + return gamma_taylor_coefficients(inprec) + +def gamma_fixed_taylor(xmpf, x, wp, prec, rnd, type): + # Determine nearest multiple of N/2 + #n = int(x >> (wp-1)) + #steps = (n-1)>>1 + nearest_int = ((x >> (wp-1)) + MPZ_ONE) >> 1 + one = MPZ_ONE << wp + coeffs, cwp = gamma_taylor_coefficients(wp) + if nearest_int > 0: + r = one + for i in xrange(nearest_int-1): + x -= one + r = (r*x) >> wp + x -= one + p = MPZ_ZERO + for c in coeffs: + p = c + ((x*p)>>wp) + p >>= (cwp-wp) + if type == 0: + return from_man_exp((r<> wp + x += one + p = MPZ_ZERO + for c in coeffs: + p = c + ((x*p)>>wp) + p >>= (cwp-wp) + if wp - bitcount(abs(x)) > 10: + # pass very close to 0, so do floating-point multiply + g = mpf_add(xmpf, from_int(-nearest_int)) # exact + r = from_man_exp(p*r,-wp-wp) + r = mpf_mul(r, g, wp) + if type == 0: + return mpf_div(fone, r, prec, rnd) + if type == 2: + return mpf_pos(r, prec, rnd) + if type == 3: + return mpf_log(mpf_abs(mpf_div(fone, r, wp)), prec, rnd) + else: + r = from_man_exp(x*p*r,-3*wp) + if type == 0: return mpf_div(fone, r, prec, rnd) + if type == 2: return mpf_pos(r, prec, rnd) + if type == 3: return mpf_neg(mpf_log(mpf_abs(r), prec, rnd)) + +def stirling_coefficient(n): + if n in gamma_stirling_cache: + return gamma_stirling_cache[n] + p, q = bernfrac(n) + q *= MPZ(n*(n-1)) + gamma_stirling_cache[n] = p, q, bitcount(abs(p)), bitcount(q) + return gamma_stirling_cache[n] + +def real_stirling_series(x, prec): + """ + Sums the rational part of Stirling's expansion, + + log(sqrt(2*pi)) - z + 1/(12*z) - 1/(360*z^3) + ... + + """ + t = (MPZ_ONE<<(prec+prec)) // x # t = 1/x + u = (t*t)>>prec # u = 1/x**2 + s = ln_sqrt2pi_fixed(prec) - x + # Add initial terms of Stirling's series + s += t//12; t = (t*u)>>prec + s -= t//360; t = (t*u)>>prec + s += t//1260; t = (t*u)>>prec + s -= t//1680; t = (t*u)>>prec + if not t: return s + s += t//1188; t = (t*u)>>prec + s -= 691*t//360360; t = (t*u)>>prec + s += t//156; t = (t*u)>>prec + if not t: return s + s -= 3617*t//122400; t = (t*u)>>prec + s += 43867*t//244188; t = (t*u)>>prec + s -= 174611*t//125400; t = (t*u)>>prec + if not t: return s + k = 22 + # From here on, the coefficients are growing, so we + # have to keep t at a roughly constant size + usize = bitcount(abs(u)) + tsize = bitcount(abs(t)) + texp = 0 + while 1: + p, q, pb, qb = stirling_coefficient(k) + term_mag = tsize + pb + texp + shift = -texp + m = pb - term_mag + if m > 0 and shift < m: + p >>= m + shift -= m + m = tsize - term_mag + if m > 0 and shift < m: + w = t >> m + shift -= m + else: + w = t + term = (t*p//q) >> shift + if not term: + break + s += term + t = (t*u) >> usize + texp -= (prec - usize) + k += 2 + return s + +def complex_stirling_series(x, y, prec): + # t = 1/z + _m = (x*x + y*y) >> prec + tre = (x << prec) // _m + tim = (-y << prec) // _m + # u = 1/z**2 + ure = (tre*tre - tim*tim) >> prec + uim = tim*tre >> (prec-1) + # s = log(sqrt(2*pi)) - z + sre = ln_sqrt2pi_fixed(prec) - x + sim = -y + + # Add initial terms of Stirling's series + sre += tre//12; sim += tim//12; + tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) + sre -= tre//360; sim -= tim//360; + tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) + sre += tre//1260; sim += tim//1260; + tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) + sre -= tre//1680; sim -= tim//1680; + tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) + if abs(tre) + abs(tim) < 5: return sre, sim + sre += tre//1188; sim += tim//1188; + tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) + sre -= 691*tre//360360; sim -= 691*tim//360360; + tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) + sre += tre//156; sim += tim//156; + tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) + if abs(tre) + abs(tim) < 5: return sre, sim + sre -= 3617*tre//122400; sim -= 3617*tim//122400; + tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) + sre += 43867*tre//244188; sim += 43867*tim//244188; + tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) + sre -= 174611*tre//125400; sim -= 174611*tim//125400; + tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) + if abs(tre) + abs(tim) < 5: return sre, sim + + k = 22 + # From here on, the coefficients are growing, so we + # have to keep t at a roughly constant size + usize = bitcount(max(abs(ure), abs(uim))) + tsize = bitcount(max(abs(tre), abs(tim))) + texp = 0 + while 1: + p, q, pb, qb = stirling_coefficient(k) + term_mag = tsize + pb + texp + shift = -texp + m = pb - term_mag + if m > 0 and shift < m: + p >>= m + shift -= m + m = tsize - term_mag + if m > 0 and shift < m: + wre = tre >> m + wim = tim >> m + shift -= m + else: + wre = tre + wim = tim + termre = (tre*p//q) >> shift + termim = (tim*p//q) >> shift + if abs(termre) + abs(termim) < 5: + break + sre += termre + sim += termim + tre, tim = ((tre*ure - tim*uim)>>usize), \ + ((tre*uim + tim*ure)>>usize) + texp -= (prec - usize) + k += 2 + return sre, sim + + +def mpf_gamma(x, prec, rnd='d', type=0): + """ + This function implements multipurpose evaluation of the gamma + function, G(x), as well as the following versions of the same: + + type = 0 -- G(x) [standard gamma function] + type = 1 -- G(x+1) = x*G(x+1) = x! [factorial] + type = 2 -- 1/G(x) [reciprocal gamma function] + type = 3 -- log(|G(x)|) [log-gamma function, real part] + """ + + # Specal values + sign, man, exp, bc = x + if not man: + if x == fzero: + if type == 1: return fone + if type == 2: return fzero + raise ValueError("gamma function pole") + if x == finf: + if type == 2: return fzero + return finf + return fnan + + # First of all, for log gamma, numbers can be well beyond the fixed-point + # range, so we must take care of huge numbers before e.g. trying + # to convert x to the nearest integer + if type == 3: + wp = prec+20 + if exp+bc > wp and not sign: + return mpf_sub(mpf_mul(x, mpf_log(x, wp), wp), x, prec, rnd) + + # We strongly want to special-case small integers + is_integer = exp >= 0 + if is_integer: + # Poles + if sign: + if type == 2: + return fzero + raise ValueError("gamma function pole") + # n = x + n = man << exp + if n < SMALL_FACTORIAL_CACHE_SIZE: + if type == 0: + return mpf_pos(small_factorial_cache[n-1], prec, rnd) + if type == 1: + return mpf_pos(small_factorial_cache[n], prec, rnd) + if type == 2: + return mpf_div(fone, small_factorial_cache[n-1], prec, rnd) + if type == 3: + return mpf_log(small_factorial_cache[n-1], prec, rnd) + else: + # floor(abs(x)) + n = int(man >> (-exp)) + + # Estimate size and precision + # Estimate log(gamma(|x|),2) as x*log(x,2) + mag = exp + bc + gamma_size = n*mag + + if type == 3: + wp = prec + 20 + else: + wp = prec + bitcount(gamma_size) + 20 + + # Very close to 0, pole + if mag < -wp: + if type == 0: + return mpf_sub(mpf_div(fone,x, wp),mpf_shift(fone,-wp),prec,rnd) + if type == 1: return mpf_sub(fone, x, prec, rnd) + if type == 2: return mpf_add(x, mpf_shift(fone,mag-wp), prec, rnd) + if type == 3: return mpf_neg(mpf_log(mpf_abs(x), prec, rnd)) + + # From now on, we assume having a gamma function + if type == 1: + return mpf_gamma(mpf_add(x, fone), prec, rnd, 0) + + # Special case integers (those not small enough to be caught above, + # but still small enough for an exact factorial to be faster + # than an approximate algorithm), and half-integers + if exp >= -1: + if is_integer: + if gamma_size < 10*wp: + if type == 0: + return from_int(ifac(n-1), prec, rnd) + if type == 2: + return from_rational(MPZ_ONE, ifac(n-1), prec, rnd) + if type == 3: + return mpf_log(from_int(ifac(n-1)), prec, rnd) + # half-integer + if n < 100 or gamma_size < 10*wp: + if sign: + w = sqrtpi_fixed(wp) + if n % 2: f = ifac2(2*n+1) + else: f = -ifac2(2*n+1) + if type == 0: + return mpf_shift(from_rational(w, f, prec, rnd), -wp+n+1) + if type == 2: + return mpf_shift(from_rational(f, w, prec, rnd), wp-n-1) + if type == 3: + return mpf_log(mpf_shift(from_rational(w, abs(f), + prec, rnd), -wp+n+1), prec, rnd) + elif n == 0: + if type == 0: return mpf_sqrtpi(prec, rnd) + if type == 2: return mpf_div(fone, mpf_sqrtpi(wp), prec, rnd) + if type == 3: return mpf_log(mpf_sqrtpi(wp), prec, rnd) + else: + w = sqrtpi_fixed(wp) + w = from_man_exp(w * ifac2(2*n-1), -wp-n) + if type == 0: return mpf_pos(w, prec, rnd) + if type == 2: return mpf_div(fone, w, prec, rnd) + if type == 3: return mpf_log(mpf_abs(w), prec, rnd) + + # Convert to fixed point + offset = exp + wp + if offset >= 0: absxman = man << offset + else: absxman = man >> (-offset) + + # For log gamma, provide accurate evaluation for x = 1+eps and 2+eps + if type == 3 and not sign: + one = MPZ_ONE << wp + one_dist = abs(absxman-one) + two_dist = abs(absxman-2*one) + cancellation = (wp - bitcount(min(one_dist, two_dist))) + if cancellation > 10: + xsub1 = mpf_sub(fone, x) + xsub2 = mpf_sub(ftwo, x) + xsub1mag = xsub1[2]+xsub1[3] + xsub2mag = xsub2[2]+xsub2[3] + if xsub1mag < -wp: + return mpf_mul(mpf_euler(wp), mpf_sub(fone, x), prec, rnd) + if xsub2mag < -wp: + return mpf_mul(mpf_sub(fone, mpf_euler(wp)), + mpf_sub(x, ftwo), prec, rnd) + # Proceed but increase precision + wp += max(-xsub1mag, -xsub2mag) + offset = exp + wp + if offset >= 0: absxman = man << offset + else: absxman = man >> (-offset) + + # Use Taylor series if appropriate + n_for_stirling = int(GAMMA_STIRLING_BETA*wp) + if n < max(100, n_for_stirling) and wp < MAX_GAMMA_TAYLOR_PREC: + if sign: + absxman = -absxman + return gamma_fixed_taylor(x, absxman, wp, prec, rnd, type) + + # Use Stirling's series + # First ensure that |x| is large enough for rapid convergence + xorig = x + + # Argument reduction + r = 0 + if n < n_for_stirling: + r = one = MPZ_ONE << wp + d = n_for_stirling - n + for k in xrange(d): + r = (r * absxman) >> wp + absxman += one + x = xabs = from_man_exp(absxman, -wp) + if sign: + x = mpf_neg(x) + else: + xabs = mpf_abs(x) + + # Asymptotic series + y = real_stirling_series(absxman, wp) + u = to_fixed(mpf_log(xabs, wp), wp) + u = ((absxman - (MPZ_ONE<<(wp-1))) * u) >> wp + y += u + w = from_man_exp(y, -wp) + + # Compute final value + if sign: + # Reflection formula + A = mpf_mul(mpf_sin_pi(xorig, wp), xorig, wp) + B = mpf_neg(mpf_pi(wp)) + if type == 0 or type == 2: + A = mpf_mul(A, mpf_exp(w, wp)) + if r: + B = mpf_mul(B, from_man_exp(r, -wp), wp) + if type == 0: + return mpf_div(B, A, prec, rnd) + if type == 2: + return mpf_div(A, B, prec, rnd) + if type == 3: + if r: + B = mpf_mul(B, from_man_exp(r, -wp), wp) + A = mpf_add(mpf_log(mpf_abs(A), wp), w, wp) + return mpf_sub(mpf_log(mpf_abs(B), wp), A, prec, rnd) + else: + if type == 0: + if r: + return mpf_div(mpf_exp(w, wp), + from_man_exp(r, -wp), prec, rnd) + return mpf_exp(w, prec, rnd) + if type == 2: + if r: + return mpf_div(from_man_exp(r, -wp), + mpf_exp(w, wp), prec, rnd) + return mpf_exp(mpf_neg(w), prec, rnd) + if type == 3: + if r: + return mpf_sub(w, mpf_log(from_man_exp(r,-wp), wp), prec, rnd) + return mpf_pos(w, prec, rnd) + + +def mpc_gamma(z, prec, rnd='d', type=0): + a, b = z + asign, aman, aexp, abc = a + bsign, bman, bexp, bbc = b + + if b == fzero: + # Imaginary part on negative half-axis for log-gamma function + if type == 3 and asign: + re = mpf_gamma(a, prec, rnd, 3) + n = (-aman) >> (-aexp) + im = mpf_mul_int(mpf_pi(prec+10), n, prec, rnd) + return re, im + return mpf_gamma(a, prec, rnd, type), fzero + + # Some kind of complex inf/nan + if (not aman and aexp) or (not bman and bexp): + return (fnan, fnan) + + # Initial working precision + wp = prec + 20 + + amag = aexp+abc + bmag = bexp+bbc + if aman: + mag = max(amag, bmag) + else: + mag = bmag + + # Close to 0 + if mag < -8: + if mag < -wp: + # 1/gamma(z) = z + euler*z^2 + O(z^3) + v = mpc_add(z, mpc_mul_mpf(mpc_mul(z,z,wp),mpf_euler(wp),wp), wp) + if type == 0: return mpc_reciprocal(v, prec, rnd) + if type == 1: return mpc_div(z, v, prec, rnd) + if type == 2: return mpc_pos(v, prec, rnd) + if type == 3: return mpc_log(mpc_reciprocal(v, prec), prec, rnd) + elif type != 1: + wp += (-mag) + + # Handle huge log-gamma values; must do this before converting to + # a fixed-point value. TODO: determine a precise cutoff of validity + # depending on amag and bmag + if type == 3 and mag > wp and ((not asign) or (bmag >= amag)): + return mpc_sub(mpc_mul(z, mpc_log(z, wp), wp), z, prec, rnd) + + # From now on, we assume having a gamma function + if type == 1: + return mpc_gamma((mpf_add(a, fone), b), prec, rnd, 0) + + an = abs(to_int(a)) + bn = abs(to_int(b)) + absn = max(an, bn) + gamma_size = absn*mag + if type == 3: + pass + else: + wp += bitcount(gamma_size) + + # Reflect to the right half-plane. Note that Stirling's expansion + # is valid in the left half-plane too, as long as we're not too close + # to the real axis, but in order to use this argument reduction + # in the negative direction must be implemented. + #need_reflection = asign and ((bmag < 0) or (amag-bmag > 4)) + need_reflection = asign + zorig = z + if need_reflection: + z = mpc_neg(z) + asign, aman, aexp, abc = a = z[0] + bsign, bman, bexp, bbc = b = z[1] + + # Imaginary part very small compared to real one? + yfinal = 0 + balance_prec = 0 + if bmag < -10: + # Check z ~= 1 and z ~= 2 for loggamma + if type == 3: + zsub1 = mpc_sub_mpf(z, fone) + if zsub1[0] == fzero: + cancel1 = -bmag + else: + cancel1 = -max(zsub1[0][2]+zsub1[0][3], bmag) + if cancel1 > wp: + pi = mpf_pi(wp) + x = mpc_mul_mpf(zsub1, pi, wp) + x = mpc_mul(x, x, wp) + x = mpc_div_mpf(x, from_int(12), wp) + y = mpc_mul_mpf(zsub1, mpf_neg(mpf_euler(wp)), wp) + yfinal = mpc_add(x, y, wp) + if not need_reflection: + return mpc_pos(yfinal, prec, rnd) + elif cancel1 > 0: + wp += cancel1 + zsub2 = mpc_sub_mpf(z, ftwo) + if zsub2[0] == fzero: + cancel2 = -bmag + else: + cancel2 = -max(zsub2[0][2]+zsub2[0][3], bmag) + if cancel2 > wp: + pi = mpf_pi(wp) + t = mpf_sub(mpf_mul(pi, pi), from_int(6)) + x = mpc_mul_mpf(mpc_mul(zsub2, zsub2, wp), t, wp) + x = mpc_div_mpf(x, from_int(12), wp) + y = mpc_mul_mpf(zsub2, mpf_sub(fone, mpf_euler(wp)), wp) + yfinal = mpc_add(x, y, wp) + if not need_reflection: + return mpc_pos(yfinal, prec, rnd) + elif cancel2 > 0: + wp += cancel2 + if bmag < -wp: + # Compute directly from the real gamma function. + pp = 2*(wp+10) + aabs = mpf_abs(a) + eps = mpf_shift(fone, amag-wp) + x1 = mpf_gamma(aabs, pp, type=type) + x2 = mpf_gamma(mpf_add(aabs, eps), pp, type=type) + xprime = mpf_div(mpf_sub(x2, x1, pp), eps, pp) + y = mpf_mul(b, xprime, prec, rnd) + yfinal = (x1, y) + # Note: we still need to use the reflection formula for + # near-poles, and the correct branch of the log-gamma function + if not need_reflection: + return mpc_pos(yfinal, prec, rnd) + else: + balance_prec += (-bmag) + + wp += balance_prec + n_for_stirling = int(GAMMA_STIRLING_BETA*wp) + need_reduction = absn < n_for_stirling + + afix = to_fixed(a, wp) + bfix = to_fixed(b, wp) + + r = 0 + if not yfinal: + zprered = z + # Argument reduction + if absn < n_for_stirling: + absn = complex(an, bn) + d = int((1 + n_for_stirling**2 - bn**2)**0.5 - an) + rre = one = MPZ_ONE << wp + rim = MPZ_ZERO + for k in xrange(d): + rre, rim = ((afix*rre-bfix*rim)>>wp), ((afix*rim + bfix*rre)>>wp) + afix += one + r = from_man_exp(rre, -wp), from_man_exp(rim, -wp) + a = from_man_exp(afix, -wp) + z = a, b + + yre, yim = complex_stirling_series(afix, bfix, wp) + # (z-1/2)*log(z) + S + lre, lim = mpc_log(z, wp) + lre = to_fixed(lre, wp) + lim = to_fixed(lim, wp) + yre = ((lre*afix - lim*bfix)>>wp) - (lre>>1) + yre + yim = ((lre*bfix + lim*afix)>>wp) - (lim>>1) + yim + y = from_man_exp(yre, -wp), from_man_exp(yim, -wp) + + if r and type == 3: + # If re(z) > 0 and abs(z) <= 4, the branches of loggamma(z) + # and log(gamma(z)) coincide. Otherwise, use the zeroth order + # Stirling expansion to compute the correct imaginary part. + y = mpc_sub(y, mpc_log(r, wp), wp) + zfa = to_float(zprered[0]) + zfb = to_float(zprered[1]) + zfabs = math.hypot(zfa,zfb) + #if not (zfa > 0.0 and zfabs <= 4): + yfb = to_float(y[1]) + u = math.atan2(zfb, zfa) + if zfabs <= 0.5: + gi = 0.577216*zfb - u + else: + gi = -zfb - 0.5*u + zfa*u + zfb*math.log(zfabs) + n = int(math.floor((gi-yfb)/(2*math.pi)+0.5)) + y = (y[0], mpf_add(y[1], mpf_mul_int(mpf_pi(wp), 2*n, wp), wp)) + + if need_reflection: + if type == 0 or type == 2: + A = mpc_mul(mpc_sin_pi(zorig, wp), zorig, wp) + B = (mpf_neg(mpf_pi(wp)), fzero) + if yfinal: + if type == 2: + A = mpc_div(A, yfinal, wp) + else: + A = mpc_mul(A, yfinal, wp) + else: + A = mpc_mul(A, mpc_exp(y, wp), wp) + if r: + B = mpc_mul(B, r, wp) + if type == 0: return mpc_div(B, A, prec, rnd) + if type == 2: return mpc_div(A, B, prec, rnd) + + # Reflection formula for the log-gamma function with correct branch + # http://functions.wolfram.com/GammaBetaErf/LogGamma/16/01/01/0006/ + # LogGamma[z] == -LogGamma[-z] - Log[-z] + + # Sign[Im[z]] Floor[Re[z]] Pi I + Log[Pi] - + # Log[Sin[Pi (z - Floor[Re[z]])]] - + # Pi I (1 - Abs[Sign[Im[z]]]) Abs[Floor[Re[z]]] + if type == 3: + if yfinal: + s1 = mpc_neg(yfinal) + else: + s1 = mpc_neg(y) + # s -= log(-z) + s1 = mpc_sub(s1, mpc_log(mpc_neg(zorig), wp), wp) + # floor(re(z)) + rezfloor = mpf_floor(zorig[0]) + imzsign = mpf_sign(zorig[1]) + pi = mpf_pi(wp) + t = mpf_mul(pi, rezfloor) + t = mpf_mul_int(t, imzsign, wp) + s1 = (s1[0], mpf_add(s1[1], t, wp)) + s1 = mpc_add_mpf(s1, mpf_log(pi, wp), wp) + t = mpc_sin_pi(mpc_sub_mpf(zorig, rezfloor), wp) + t = mpc_log(t, wp) + s1 = mpc_sub(s1, t, wp) + # Note: may actually be unused, because we fall back + # to the mpf_ function for real arguments + if not imzsign: + t = mpf_mul(pi, mpf_floor(rezfloor), wp) + s1 = (s1[0], mpf_sub(s1[1], t, wp)) + return mpc_pos(s1, prec, rnd) + else: + if type == 0: + if r: + return mpc_div(mpc_exp(y, wp), r, prec, rnd) + return mpc_exp(y, prec, rnd) + if type == 2: + if r: + return mpc_div(r, mpc_exp(y, wp), prec, rnd) + return mpc_exp(mpc_neg(y), prec, rnd) + if type == 3: + return mpc_pos(y, prec, rnd) + +def mpf_factorial(x, prec, rnd='d'): + return mpf_gamma(x, prec, rnd, 1) + +def mpc_factorial(x, prec, rnd='d'): + return mpc_gamma(x, prec, rnd, 1) + +def mpf_rgamma(x, prec, rnd='d'): + return mpf_gamma(x, prec, rnd, 2) + +def mpc_rgamma(x, prec, rnd='d'): + return mpc_gamma(x, prec, rnd, 2) + +def mpf_loggamma(x, prec, rnd='d'): + sign, man, exp, bc = x + if sign: + raise ComplexResult + return mpf_gamma(x, prec, rnd, 3) + +def mpc_loggamma(z, prec, rnd='d'): + a, b = z + asign, aman, aexp, abc = a + bsign, bman, bexp, bbc = b + if b == fzero and asign: + re = mpf_gamma(a, prec, rnd, 3) + n = (-aman) >> (-aexp) + im = mpf_mul_int(mpf_pi(prec+10), n, prec, rnd) + return re, im + return mpc_gamma(z, prec, rnd, 3) + +def mpf_gamma_int(n, prec, rnd=round_fast): + if n < SMALL_FACTORIAL_CACHE_SIZE: + return mpf_pos(small_factorial_cache[n-1], prec, rnd) + return mpf_gamma(from_int(n), prec, rnd) diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/libelefun.py b/venv/lib/python3.10/site-packages/mpmath/libmp/libelefun.py new file mode 100644 index 0000000000000000000000000000000000000000..3de2e5aaef02296ed03dec3df3021b56823f3728 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/libmp/libelefun.py @@ -0,0 +1,1428 @@ +""" +This module implements computation of elementary transcendental +functions (powers, logarithms, trigonometric and hyperbolic +functions, inverse trigonometric and hyperbolic) for real +floating-point numbers. + +For complex and interval implementations of the same functions, +see libmpc and libmpi. + +""" + +import math +from bisect import bisect + +from .backend import xrange +from .backend import MPZ, MPZ_ZERO, MPZ_ONE, MPZ_TWO, MPZ_FIVE, BACKEND + +from .libmpf import ( + round_floor, round_ceiling, round_down, round_up, + round_nearest, round_fast, + ComplexResult, + bitcount, bctable, lshift, rshift, giant_steps, sqrt_fixed, + from_int, to_int, from_man_exp, to_fixed, to_float, from_float, + from_rational, normalize, + fzero, fone, fnone, fhalf, finf, fninf, fnan, + mpf_cmp, mpf_sign, mpf_abs, + mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, mpf_div, mpf_shift, + mpf_rdiv_int, mpf_pow_int, mpf_sqrt, + reciprocal_rnd, negative_rnd, mpf_perturb, + isqrt_fast +) + +from .libintmath import ifib + + +#------------------------------------------------------------------------------- +# Tuning parameters +#------------------------------------------------------------------------------- + +# Cutoff for computing exp from cosh+sinh. This reduces the +# number of terms by half, but also requires a square root which +# is expensive with the pure-Python square root code. +if BACKEND == 'python': + EXP_COSH_CUTOFF = 600 +else: + EXP_COSH_CUTOFF = 400 +# Cutoff for using more than 2 series +EXP_SERIES_U_CUTOFF = 1500 + +# Also basically determined by sqrt +if BACKEND == 'python': + COS_SIN_CACHE_PREC = 400 +else: + COS_SIN_CACHE_PREC = 200 +COS_SIN_CACHE_STEP = 8 +cos_sin_cache = {} + +# Number of integer logarithms to cache (for zeta sums) +MAX_LOG_INT_CACHE = 2000 +log_int_cache = {} + +LOG_TAYLOR_PREC = 2500 # Use Taylor series with caching up to this prec +LOG_TAYLOR_SHIFT = 9 # Cache log values in steps of size 2^-N +log_taylor_cache = {} +# prec/size ratio of x for fastest convergence in AGM formula +LOG_AGM_MAG_PREC_RATIO = 20 + +ATAN_TAYLOR_PREC = 3000 # Same as for log +ATAN_TAYLOR_SHIFT = 7 # steps of size 2^-N +atan_taylor_cache = {} + + +# ~= next power of two + 20 +cache_prec_steps = [22,22] +for k in xrange(1, bitcount(LOG_TAYLOR_PREC)+1): + cache_prec_steps += [min(2**k,LOG_TAYLOR_PREC)+20] * 2**(k-1) + + +#----------------------------------------------------------------------------# +# # +# Elementary mathematical constants # +# # +#----------------------------------------------------------------------------# + +def constant_memo(f): + """ + Decorator for caching computed values of mathematical + constants. This decorator should be applied to a + function taking a single argument prec as input and + returning a fixed-point value with the given precision. + """ + f.memo_prec = -1 + f.memo_val = None + def g(prec, **kwargs): + memo_prec = f.memo_prec + if prec <= memo_prec: + return f.memo_val >> (memo_prec-prec) + newprec = int(prec*1.05+10) + f.memo_val = f(newprec, **kwargs) + f.memo_prec = newprec + return f.memo_val >> (newprec-prec) + g.__name__ = f.__name__ + g.__doc__ = f.__doc__ + return g + +def def_mpf_constant(fixed): + """ + Create a function that computes the mpf value for a mathematical + constant, given a function that computes the fixed-point value. + + Assumptions: the constant is positive and has magnitude ~= 1; + the fixed-point function rounds to floor. + """ + def f(prec, rnd=round_fast): + wp = prec + 20 + v = fixed(wp) + if rnd in (round_up, round_ceiling): + v += 1 + return normalize(0, v, -wp, bitcount(v), prec, rnd) + f.__doc__ = fixed.__doc__ + return f + +def bsp_acot(q, a, b, hyperbolic): + if b - a == 1: + a1 = MPZ(2*a + 3) + if hyperbolic or a&1: + return MPZ_ONE, a1 * q**2, a1 + else: + return -MPZ_ONE, a1 * q**2, a1 + m = (a+b)//2 + p1, q1, r1 = bsp_acot(q, a, m, hyperbolic) + p2, q2, r2 = bsp_acot(q, m, b, hyperbolic) + return q2*p1 + r1*p2, q1*q2, r1*r2 + +# the acoth(x) series converges like the geometric series for x^2 +# N = ceil(p*log(2)/(2*log(x))) +def acot_fixed(a, prec, hyperbolic): + """ + Compute acot(a) or acoth(a) for an integer a with binary splitting; see + http://numbers.computation.free.fr/Constants/Algorithms/splitting.html + """ + N = int(0.35 * prec/math.log(a) + 20) + p, q, r = bsp_acot(a, 0,N, hyperbolic) + return ((p+q)<> extraprec) + +# Logarithms of integers are needed for various computations involving +# logarithms, powers, radix conversion, etc + +@constant_memo +def ln2_fixed(prec): + """ + Computes ln(2). This is done with a hyperbolic Machin-type formula, + with binary splitting at high precision. + """ + return machin([(18, 26), (-2, 4801), (8, 8749)], prec, True) + +@constant_memo +def ln10_fixed(prec): + """ + Computes ln(10). This is done with a hyperbolic Machin-type formula. + """ + return machin([(46, 31), (34, 49), (20, 161)], prec, True) + + +r""" +For computation of pi, we use the Chudnovsky series: + + oo + ___ k + 1 \ (-1) (6 k)! (A + B k) + ----- = ) ----------------------- + 12 pi /___ 3 3k+3/2 + (3 k)! (k!) C + k = 0 + +where A, B, and C are certain integer constants. This series adds roughly +14 digits per term. Note that C^(3/2) can be extracted so that the +series contains only rational terms. This makes binary splitting very +efficient. + +The recurrence formulas for the binary splitting were taken from +ftp://ftp.gmplib.org/pub/src/gmp-chudnovsky.c + +Previously, Machin's formula was used at low precision and the AGM iteration +was used at high precision. However, the Chudnovsky series is essentially as +fast as the Machin formula at low precision and in practice about 3x faster +than the AGM at high precision (despite theoretically having a worse +asymptotic complexity), so there is no reason not to use it in all cases. + +""" + +# Constants in Chudnovsky's series +CHUD_A = MPZ(13591409) +CHUD_B = MPZ(545140134) +CHUD_C = MPZ(640320) +CHUD_D = MPZ(12) + +def bs_chudnovsky(a, b, level, verbose): + """ + Computes the sum from a to b of the series in the Chudnovsky + formula. Returns g, p, q where p/q is the sum as an exact + fraction and g is a temporary value used to save work + for recursive calls. + """ + if b-a == 1: + g = MPZ((6*b-5)*(2*b-1)*(6*b-1)) + p = b**3 * CHUD_C**3 // 24 + q = (-1)**b * g * (CHUD_A+CHUD_B*b) + else: + if verbose and level < 4: + print(" binary splitting", a, b) + mid = (a+b)//2 + g1, p1, q1 = bs_chudnovsky(a, mid, level+1, verbose) + g2, p2, q2 = bs_chudnovsky(mid, b, level+1, verbose) + p = p1*p2 + g = g1*g2 + q = q1*p2 + q2*g1 + return g, p, q + +@constant_memo +def pi_fixed(prec, verbose=False, verbose_base=None): + """ + Compute floor(pi * 2**prec) as a big integer. + + This is done using Chudnovsky's series (see comments in + libelefun.py for details). + """ + # The Chudnovsky series gives 14.18 digits per term + N = int(prec/3.3219280948/14.181647462 + 2) + if verbose: + print("binary splitting with N =", N) + g, p, q = bs_chudnovsky(0, N, 0, verbose) + sqrtC = isqrt_fast(CHUD_C<<(2*prec)) + v = p*CHUD_C*sqrtC//((q+CHUD_A*p)*CHUD_D) + return v + +def degree_fixed(prec): + return pi_fixed(prec)//180 + +def bspe(a, b): + """ + Sum series for exp(1)-1 between a, b, returning the result + as an exact fraction (p, q). + """ + if b-a == 1: + return MPZ_ONE, MPZ(b) + m = (a+b)//2 + p1, q1 = bspe(a, m) + p2, q2 = bspe(m, b) + return p1*q2+p2, q1*q2 + +@constant_memo +def e_fixed(prec): + """ + Computes exp(1). This is done using the ordinary Taylor series for + exp, with binary splitting. For a description of the algorithm, + see: + + http://numbers.computation.free.fr/Constants/ + Algorithms/splitting.html + """ + # Slight overestimate of N needed for 1/N! < 2**(-prec) + # This could be tightened for large N. + N = int(1.1*prec/math.log(prec) + 20) + p, q = bspe(0,N) + return ((p+q)<> 11 + +mpf_phi = def_mpf_constant(phi_fixed) +mpf_pi = def_mpf_constant(pi_fixed) +mpf_e = def_mpf_constant(e_fixed) +mpf_degree = def_mpf_constant(degree_fixed) +mpf_ln2 = def_mpf_constant(ln2_fixed) +mpf_ln10 = def_mpf_constant(ln10_fixed) + + +@constant_memo +def ln_sqrt2pi_fixed(prec): + wp = prec + 10 + # ln(sqrt(2*pi)) = ln(2*pi)/2 + return to_fixed(mpf_log(mpf_shift(mpf_pi(wp), 1), wp), prec-1) + +@constant_memo +def sqrtpi_fixed(prec): + return sqrt_fixed(pi_fixed(prec), prec) + +mpf_sqrtpi = def_mpf_constant(sqrtpi_fixed) +mpf_ln_sqrt2pi = def_mpf_constant(ln_sqrt2pi_fixed) + + +#----------------------------------------------------------------------------# +# # +# Powers # +# # +#----------------------------------------------------------------------------# + +def mpf_pow(s, t, prec, rnd=round_fast): + """ + Compute s**t. Raises ComplexResult if s is negative and t is + fractional. + """ + ssign, sman, sexp, sbc = s + tsign, tman, texp, tbc = t + if ssign and texp < 0: + raise ComplexResult("negative number raised to a fractional power") + if texp >= 0: + return mpf_pow_int(s, (-1)**tsign * (tman<> pbc)] + if pbc > workprec: + pm = pm >> (pbc-workprec) + pe += pbc - workprec + pbc = workprec + n -= 1 + if not n: + break + y = y*y + exp = exp+exp + bc = bc + bc - 2 + bc = bc + bctable[int(y >> bc)] + if bc > workprec: + y = y >> (bc-workprec) + exp += bc - workprec + bc = workprec + n = n // 2 + return pm, pe + +# froot(s, n, prec, rnd) computes the real n-th root of a +# positive mpf tuple s. +# To compute the root we start from a 50-bit estimate for r +# generated with ordinary floating-point arithmetic, and then refine +# the value to full accuracy using the iteration + +# 1 / y \ +# r = --- | (n-1) * r + ---------- | +# n+1 n \ n r_n**(n-1) / + +# which is simply Newton's method applied to the equation r**n = y. +# With giant_steps(start, prec+extra) = [p0,...,pm, prec+extra] +# and y = man * 2**-shift one has +# (man * 2**exp)**(1/n) = +# y**(1/n) * 2**(start-prec/n) * 2**(p0-start) * ... * 2**(prec+extra-pm) * +# 2**((exp+shift-(n-1)*prec)/n -extra)) +# The last factor is accounted for in the last line of froot. + +def nthroot_fixed(y, n, prec, exp1): + start = 50 + try: + y1 = rshift(y, prec - n*start) + r = MPZ(int(y1**(1.0/n))) + except OverflowError: + y1 = from_int(y1, start) + fn = from_int(n) + fn = mpf_rdiv_int(1, fn, start) + r = mpf_pow(y1, fn, start) + r = to_int(r) + extra = 10 + extra1 = n + prevp = start + for p in giant_steps(start, prec+extra): + pm, pe = int_pow_fixed(r, n-1, prevp) + r2 = rshift(pm, (n-1)*prevp - p - pe - extra1) + B = lshift(y, 2*p-prec+extra1)//r2 + r = (B + (n-1) * lshift(r, p-prevp))//n + prevp = p + return r + +def mpf_nthroot(s, n, prec, rnd=round_fast): + """nth-root of a positive number + + Use the Newton method when faster, otherwise use x**(1/n) + """ + sign, man, exp, bc = s + if sign: + raise ComplexResult("nth root of a negative number") + if not man: + if s == fnan: + return fnan + if s == fzero: + if n > 0: + return fzero + if n == 0: + return fone + return finf + # Infinity + if not n: + return fnan + if n < 0: + return fzero + return finf + flag_inverse = False + if n < 2: + if n == 0: + return fone + if n == 1: + return mpf_pos(s, prec, rnd) + if n == -1: + return mpf_div(fone, s, prec, rnd) + # n < 0 + rnd = reciprocal_rnd[rnd] + flag_inverse = True + extra_inverse = 5 + prec += extra_inverse + n = -n + if n > 20 and (n >= 20000 or prec < int(233 + 28.3 * n**0.62)): + prec2 = prec + 10 + fn = from_int(n) + nth = mpf_rdiv_int(1, fn, prec2) + r = mpf_pow(s, nth, prec2, rnd) + s = normalize(r[0], r[1], r[2], r[3], prec, rnd) + if flag_inverse: + return mpf_div(fone, s, prec-extra_inverse, rnd) + else: + return s + # Convert to a fixed-point number with prec2 bits. + prec2 = prec + 2*n - (prec%n) + # a few tests indicate that + # for 10 < n < 10**4 a bit more precision is needed + if n > 10: + prec2 += prec2//10 + prec2 = prec2 - prec2%n + # Mantissa may have more bits than we need. Trim it down. + shift = bc - prec2 + # Adjust exponents to make prec2 and exp+shift multiples of n. + sign1 = 0 + es = exp+shift + if es < 0: + sign1 = 1 + es = -es + if sign1: + shift += es%n + else: + shift -= es%n + man = rshift(man, shift) + extra = 10 + exp1 = ((exp+shift-(n-1)*prec2)//n) - extra + rnd_shift = 0 + if flag_inverse: + if rnd == 'u' or rnd == 'c': + rnd_shift = 1 + else: + if rnd == 'd' or rnd == 'f': + rnd_shift = 1 + man = nthroot_fixed(man+rnd_shift, n, prec2, exp1) + s = from_man_exp(man, exp1, prec, rnd) + if flag_inverse: + return mpf_div(fone, s, prec-extra_inverse, rnd) + else: + return s + +def mpf_cbrt(s, prec, rnd=round_fast): + """cubic root of a positive number""" + return mpf_nthroot(s, 3, prec, rnd) + +#----------------------------------------------------------------------------# +# # +# Logarithms # +# # +#----------------------------------------------------------------------------# + + +def log_int_fixed(n, prec, ln2=None): + """ + Fast computation of log(n), caching the value for small n, + intended for zeta sums. + """ + if n in log_int_cache: + value, vprec = log_int_cache[n] + if vprec >= prec: + return value >> (vprec - prec) + wp = prec + 10 + if wp <= LOG_TAYLOR_SHIFT: + if ln2 is None: + ln2 = ln2_fixed(wp) + r = bitcount(n) + x = n << (wp-r) + v = log_taylor_cached(x, wp) + r*ln2 + else: + v = to_fixed(mpf_log(from_int(n), wp+5), wp) + if n < MAX_LOG_INT_CACHE: + log_int_cache[n] = (v, wp) + return v >> (wp-prec) + +def agm_fixed(a, b, prec): + """ + Fixed-point computation of agm(a,b), assuming + a, b both close to unit magnitude. + """ + i = 0 + while 1: + anew = (a+b)>>1 + if i > 4 and abs(a-anew) < 8: + return a + b = isqrt_fast(a*b) + a = anew + i += 1 + return a + +def log_agm(x, prec): + """ + Fixed-point computation of -log(x) = log(1/x), suitable + for large precision. It is required that 0 < x < 1. The + algorithm used is the Sasaki-Kanada formula + + -log(x) = pi/agm(theta2(x)^2,theta3(x)^2). [1] + + For faster convergence in the theta functions, x should + be chosen closer to 0. + + Guard bits must be added by the caller. + + HYPOTHESIS: if x = 2^(-n), n bits need to be added to + account for the truncation to a fixed-point number, + and this is the only significant cancellation error. + + The number of bits lost to roundoff is small and can be + considered constant. + + [1] Richard P. Brent, "Fast Algorithms for High-Precision + Computation of Elementary Functions (extended abstract)", + http://wwwmaths.anu.edu.au/~brent/pd/RNC7-Brent.pdf + + """ + x2 = (x*x) >> prec + # Compute jtheta2(x)**2 + s = a = b = x2 + while a: + b = (b*x2) >> prec + a = (a*b) >> prec + s += a + s += (MPZ_ONE<>(prec-2) + s = (s*isqrt_fast(x<>prec + # Compute jtheta3(x)**2 + t = a = b = x + while a: + b = (b*x2) >> prec + a = (a*b) >> prec + t += a + t = (MPZ_ONE<>prec + # Final formula + p = agm_fixed(s, t, prec) + return (pi_fixed(prec) << prec) // p + +def log_taylor(x, prec, r=0): + """ + Fixed-point calculation of log(x). It is assumed that x is close + enough to 1 for the Taylor series to converge quickly. Convergence + can be improved by specifying r > 0 to compute + log(x^(1/2^r))*2^r, at the cost of performing r square roots. + + The caller must provide sufficient guard bits. + """ + for i in xrange(r): + x = isqrt_fast(x<> prec + v4 = (v2*v2) >> prec + s0 = v + s1 = v//3 + v = (v*v4) >> prec + k = 5 + while v: + s0 += v // k + k += 2 + s1 += v // k + v = (v*v4) >> prec + k += 2 + s1 = (s1*v2) >> prec + s = (s0+s1) << (1+r) + if sign: + return -s + return s + +def log_taylor_cached(x, prec): + """ + Fixed-point computation of log(x), assuming x in (0.5, 2) + and prec <= LOG_TAYLOR_PREC. + """ + n = x >> (prec-LOG_TAYLOR_SHIFT) + cached_prec = cache_prec_steps[prec] + dprec = cached_prec - prec + if (n, cached_prec) in log_taylor_cache: + a, log_a = log_taylor_cache[n, cached_prec] + else: + a = n << (cached_prec - LOG_TAYLOR_SHIFT) + log_a = log_taylor(a, cached_prec, 8) + log_taylor_cache[n, cached_prec] = (a, log_a) + a >>= dprec + log_a >>= dprec + u = ((x - a) << prec) // a + v = (u << prec) // ((MPZ_TWO << prec) + u) + v2 = (v*v) >> prec + v4 = (v2*v2) >> prec + s0 = v + s1 = v//3 + v = (v*v4) >> prec + k = 5 + while v: + s0 += v//k + k += 2 + s1 += v//k + v = (v*v4) >> prec + k += 2 + s1 = (s1*v2) >> prec + s = (s0+s1) << 1 + return log_a + s + +def mpf_log(x, prec, rnd=round_fast): + """ + Compute the natural logarithm of the mpf value x. If x is negative, + ComplexResult is raised. + """ + sign, man, exp, bc = x + #------------------------------------------------------------------ + # Handle special values + if not man: + if x == fzero: return fninf + if x == finf: return finf + if x == fnan: return fnan + if sign: + raise ComplexResult("logarithm of a negative number") + wp = prec + 20 + #------------------------------------------------------------------ + # Handle log(2^n) = log(n)*2. + # Here we catch the only possible exact value, log(1) = 0 + if man == 1: + if not exp: + return fzero + return from_man_exp(exp*ln2_fixed(wp), -wp, prec, rnd) + mag = exp+bc + abs_mag = abs(mag) + #------------------------------------------------------------------ + # Handle x = 1+eps, where log(x) ~ x. We need to check for + # cancellation when moving to fixed-point math and compensate + # by increasing the precision. Note that abs_mag in (0, 1) <=> + # 0.5 < x < 2 and x != 1 + if abs_mag <= 1: + # Calculate t = x-1 to measure distance from 1 in bits + tsign = 1-abs_mag + if tsign: + tman = (MPZ_ONE< wp: + t = normalize(tsign, tman, abs_mag-bc, tbc, tbc, 'n') + return mpf_perturb(t, tsign, prec, rnd) + else: + wp += cancellation + # TODO: if close enough to 1, we could use Taylor series + # even in the AGM precision range, since the Taylor series + # converges rapidly + #------------------------------------------------------------------ + # Another special case: + # n*log(2) is a good enough approximation + if abs_mag > 10000: + if bitcount(abs_mag) > wp: + return from_man_exp(exp*ln2_fixed(wp), -wp, prec, rnd) + #------------------------------------------------------------------ + # General case. + # Perform argument reduction using log(x) = log(x*2^n) - n*log(2): + # If we are in the Taylor precision range, choose magnitude 0 or 1. + # If we are in the AGM precision range, choose magnitude -m for + # some large m; benchmarking on one machine showed m = prec/20 to be + # optimal between 1000 and 100,000 digits. + if wp <= LOG_TAYLOR_PREC: + m = log_taylor_cached(lshift(man, wp-bc), wp) + if mag: + m += mag*ln2_fixed(wp) + else: + optimal_mag = -wp//LOG_AGM_MAG_PREC_RATIO + n = optimal_mag - mag + x = mpf_shift(x, n) + wp += (-optimal_mag) + m = -log_agm(to_fixed(x, wp), wp) + m -= n*ln2_fixed(wp) + return from_man_exp(m, -wp, prec, rnd) + +def mpf_log_hypot(a, b, prec, rnd): + """ + Computes log(sqrt(a^2+b^2)) accurately. + """ + # If either a or b is inf/nan/0, assume it to be a + if not b[1]: + a, b = b, a + # a is inf/nan/0 + if not a[1]: + # both are inf/nan/0 + if not b[1]: + if a == b == fzero: + return fninf + if fnan in (a, b): + return fnan + # at least one term is (+/- inf)^2 + return finf + # only a is inf/nan/0 + if a == fzero: + # log(sqrt(0+b^2)) = log(|b|) + return mpf_log(mpf_abs(b), prec, rnd) + if a == fnan: + return fnan + return finf + # Exact + a2 = mpf_mul(a,a) + b2 = mpf_mul(b,b) + extra = 20 + # Not exact + h2 = mpf_add(a2, b2, prec+extra) + cancelled = mpf_add(h2, fnone, 10) + mag_cancelled = cancelled[2]+cancelled[3] + # Just redo the sum exactly if necessary (could be smarter + # and avoid memory allocation when a or b is precisely 1 + # and the other is tiny...) + if cancelled == fzero or mag_cancelled < -extra//2: + h2 = mpf_add(a2, b2, prec+extra-min(a2[2],b2[2])) + return mpf_shift(mpf_log(h2, prec, rnd), -1) + + +#---------------------------------------------------------------------- +# Inverse tangent +# + +def atan_newton(x, prec): + if prec >= 100: + r = math.atan(int((x>>(prec-53)))/2.0**53) + else: + r = math.atan(int(x)/2.0**prec) + prevp = 50 + r = MPZ(int(r * 2.0**53) >> (53-prevp)) + extra_p = 50 + for wp in giant_steps(prevp, prec): + wp += extra_p + r = r << (wp-prevp) + cos, sin = cos_sin_fixed(r, wp) + tan = (sin << wp) // cos + a = ((tan-rshift(x, prec-wp)) << wp) // ((MPZ_ONE<>wp)) + r = r - a + prevp = wp + return rshift(r, prevp-prec) + +def atan_taylor_get_cached(n, prec): + # Taylor series with caching wins up to huge precisions + # To avoid unnecessary precomputation at low precision, we + # do it in steps + # Round to next power of 2 + prec2 = (1<<(bitcount(prec-1))) + 20 + dprec = prec2 - prec + if (n, prec2) in atan_taylor_cache: + a, atan_a = atan_taylor_cache[n, prec2] + else: + a = n << (prec2 - ATAN_TAYLOR_SHIFT) + atan_a = atan_newton(a, prec2) + atan_taylor_cache[n, prec2] = (a, atan_a) + return (a >> dprec), (atan_a >> dprec) + +def atan_taylor(x, prec): + n = (x >> (prec-ATAN_TAYLOR_SHIFT)) + a, atan_a = atan_taylor_get_cached(n, prec) + d = x - a + s0 = v = (d << prec) // ((a**2 >> prec) + (a*d >> prec) + (MPZ_ONE << prec)) + v2 = (v**2 >> prec) + v4 = (v2 * v2) >> prec + s1 = v//3 + v = (v * v4) >> prec + k = 5 + while v: + s0 += v // k + k += 2 + s1 += v // k + v = (v * v4) >> prec + k += 2 + s1 = (s1 * v2) >> prec + s = s0 - s1 + return atan_a + s + +def atan_inf(sign, prec, rnd): + if not sign: + return mpf_shift(mpf_pi(prec, rnd), -1) + return mpf_neg(mpf_shift(mpf_pi(prec, negative_rnd[rnd]), -1)) + +def mpf_atan(x, prec, rnd=round_fast): + sign, man, exp, bc = x + if not man: + if x == fzero: return fzero + if x == finf: return atan_inf(0, prec, rnd) + if x == fninf: return atan_inf(1, prec, rnd) + return fnan + mag = exp + bc + # Essentially infinity + if mag > prec+20: + return atan_inf(sign, prec, rnd) + # Essentially ~ x + if -mag > prec+20: + return mpf_perturb(x, 1-sign, prec, rnd) + wp = prec + 30 + abs(mag) + # For large x, use atan(x) = pi/2 - atan(1/x) + if mag >= 2: + x = mpf_rdiv_int(1, x, wp) + reciprocal = True + else: + reciprocal = False + t = to_fixed(x, wp) + if sign: + t = -t + if wp < ATAN_TAYLOR_PREC: + a = atan_taylor(t, wp) + else: + a = atan_newton(t, wp) + if reciprocal: + a = ((pi_fixed(wp)>>1)+1) - a + if sign: + a = -a + return from_man_exp(a, -wp, prec, rnd) + +# TODO: cleanup the special cases +def mpf_atan2(y, x, prec, rnd=round_fast): + xsign, xman, xexp, xbc = x + ysign, yman, yexp, ybc = y + if not yman: + if y == fzero and x != fnan: + if mpf_sign(x) >= 0: + return fzero + return mpf_pi(prec, rnd) + if y in (finf, fninf): + if x in (finf, fninf): + return fnan + # pi/2 + if y == finf: + return mpf_shift(mpf_pi(prec, rnd), -1) + # -pi/2 + return mpf_neg(mpf_shift(mpf_pi(prec, negative_rnd[rnd]), -1)) + return fnan + if ysign: + return mpf_neg(mpf_atan2(mpf_neg(y), x, prec, negative_rnd[rnd])) + if not xman: + if x == fnan: + return fnan + if x == finf: + return fzero + if x == fninf: + return mpf_pi(prec, rnd) + if y == fzero: + return fzero + return mpf_shift(mpf_pi(prec, rnd), -1) + tquo = mpf_atan(mpf_div(y, x, prec+4), prec+4) + if xsign: + return mpf_add(mpf_pi(prec+4), tquo, prec, rnd) + else: + return mpf_pos(tquo, prec, rnd) + +def mpf_asin(x, prec, rnd=round_fast): + sign, man, exp, bc = x + if bc+exp > 0 and x not in (fone, fnone): + raise ComplexResult("asin(x) is real only for -1 <= x <= 1") + # asin(x) = 2*atan(x/(1+sqrt(1-x**2))) + wp = prec + 15 + a = mpf_mul(x, x) + b = mpf_add(fone, mpf_sqrt(mpf_sub(fone, a, wp), wp), wp) + c = mpf_div(x, b, wp) + return mpf_shift(mpf_atan(c, prec, rnd), 1) + +def mpf_acos(x, prec, rnd=round_fast): + # acos(x) = 2*atan(sqrt(1-x**2)/(1+x)) + sign, man, exp, bc = x + if bc + exp > 0: + if x not in (fone, fnone): + raise ComplexResult("acos(x) is real only for -1 <= x <= 1") + if x == fnone: + return mpf_pi(prec, rnd) + wp = prec + 15 + a = mpf_mul(x, x) + b = mpf_sqrt(mpf_sub(fone, a, wp), wp) + c = mpf_div(b, mpf_add(fone, x, wp), wp) + return mpf_shift(mpf_atan(c, prec, rnd), 1) + +def mpf_asinh(x, prec, rnd=round_fast): + wp = prec + 20 + sign, man, exp, bc = x + mag = exp+bc + if mag < -8: + if mag < -wp: + return mpf_perturb(x, 1-sign, prec, rnd) + wp += (-mag) + # asinh(x) = log(x+sqrt(x**2+1)) + # use reflection symmetry to avoid cancellation + q = mpf_sqrt(mpf_add(mpf_mul(x, x), fone, wp), wp) + q = mpf_add(mpf_abs(x), q, wp) + if sign: + return mpf_neg(mpf_log(q, prec, negative_rnd[rnd])) + else: + return mpf_log(q, prec, rnd) + +def mpf_acosh(x, prec, rnd=round_fast): + # acosh(x) = log(x+sqrt(x**2-1)) + wp = prec + 15 + if mpf_cmp(x, fone) == -1: + raise ComplexResult("acosh(x) is real only for x >= 1") + q = mpf_sqrt(mpf_add(mpf_mul(x,x), fnone, wp), wp) + return mpf_log(mpf_add(x, q, wp), prec, rnd) + +def mpf_atanh(x, prec, rnd=round_fast): + # atanh(x) = log((1+x)/(1-x))/2 + sign, man, exp, bc = x + if (not man) and exp: + if x in (fzero, fnan): + return x + raise ComplexResult("atanh(x) is real only for -1 <= x <= 1") + mag = bc + exp + if mag > 0: + if mag == 1 and man == 1: + return [finf, fninf][sign] + raise ComplexResult("atanh(x) is real only for -1 <= x <= 1") + wp = prec + 15 + if mag < -8: + if mag < -wp: + return mpf_perturb(x, sign, prec, rnd) + wp += (-mag) + a = mpf_add(x, fone, wp) + b = mpf_sub(fone, x, wp) + return mpf_shift(mpf_log(mpf_div(a, b, wp), prec, rnd), -1) + +def mpf_fibonacci(x, prec, rnd=round_fast): + sign, man, exp, bc = x + if not man: + if x == fninf: + return fnan + return x + # F(2^n) ~= 2^(2^n) + size = abs(exp+bc) + if exp >= 0: + # Exact + if size < 10 or size <= bitcount(prec): + return from_int(ifib(to_int(x)), prec, rnd) + # Use the modified Binet formula + wp = prec + size + 20 + a = mpf_phi(wp) + b = mpf_add(mpf_shift(a, 1), fnone, wp) + u = mpf_pow(a, x, wp) + v = mpf_cos_pi(x, wp) + v = mpf_div(v, u, wp) + u = mpf_sub(u, v, wp) + u = mpf_div(u, b, prec, rnd) + return u + + +#------------------------------------------------------------------------------- +# Exponential-type functions +#------------------------------------------------------------------------------- + +def exponential_series(x, prec, type=0): + """ + Taylor series for cosh/sinh or cos/sin. + + type = 0 -- returns exp(x) (slightly faster than cosh+sinh) + type = 1 -- returns (cosh(x), sinh(x)) + type = 2 -- returns (cos(x), sin(x)) + """ + if x < 0: + x = -x + sign = 1 + else: + sign = 0 + r = int(0.5*prec**0.5) + xmag = bitcount(x) - prec + r = max(0, xmag + r) + extra = 10 + 2*max(r,-xmag) + wp = prec + extra + x <<= (extra - r) + one = MPZ_ONE << wp + alt = (type == 2) + if prec < EXP_SERIES_U_CUTOFF: + x2 = a = (x*x) >> wp + x4 = (x2*x2) >> wp + s0 = s1 = MPZ_ZERO + k = 2 + while a: + a //= (k-1)*k; s0 += a; k += 2 + a //= (k-1)*k; s1 += a; k += 2 + a = (a*x4) >> wp + s1 = (x2*s1) >> wp + if alt: + c = s1 - s0 + one + else: + c = s1 + s0 + one + else: + u = int(0.3*prec**0.35) + x2 = a = (x*x) >> wp + xpowers = [one, x2] + for i in xrange(1, u): + xpowers.append((xpowers[-1]*x2)>>wp) + sums = [MPZ_ZERO] * u + k = 2 + while a: + for i in xrange(u): + a //= (k-1)*k + if alt and k & 2: sums[i] -= a + else: sums[i] += a + k += 2 + a = (a*xpowers[-1]) >> wp + for i in xrange(1, u): + sums[i] = (sums[i]*xpowers[i]) >> wp + c = sum(sums) + one + if type == 0: + s = isqrt_fast(c*c - (one<> wp + return v >> extra + else: + # Repeatedly apply the double-angle formula + # cosh(2*x) = 2*cosh(x)^2 - 1 + # cos(2*x) = 2*cos(x)^2 - 1 + pshift = wp-1 + for i in xrange(r): + c = ((c*c) >> pshift) - one + # With the abs, this is the same for sinh and sin + s = isqrt_fast(abs((one<>extra), (s>>extra) + +def exp_basecase(x, prec): + """ + Compute exp(x) as a fixed-point number. Works for any x, + but for speed should have |x| < 1. For an arbitrary number, + use exp(x) = exp(x-m*log(2)) * 2^m where m = floor(x/log(2)). + """ + if prec > EXP_COSH_CUTOFF: + return exponential_series(x, prec, 0) + r = int(prec**0.5) + prec += r + s0 = s1 = (MPZ_ONE << prec) + k = 2 + a = x2 = (x*x) >> prec + while a: + a //= k; s0 += a; k += 1 + a //= k; s1 += a; k += 1 + a = (a*x2) >> prec + s1 = (s1*x) >> prec + s = s0 + s1 + u = r + while r: + s = (s*s) >> prec + r -= 1 + return s >> u + +def exp_expneg_basecase(x, prec): + """ + Computation of exp(x), exp(-x) + """ + if prec > EXP_COSH_CUTOFF: + cosh, sinh = exponential_series(x, prec, 1) + return cosh+sinh, cosh-sinh + a = exp_basecase(x, prec) + b = (MPZ_ONE << (prec+prec)) // a + return a, b + +def cos_sin_basecase(x, prec): + """ + Compute cos(x), sin(x) as fixed-point numbers, assuming x + in [0, pi/2). For an arbitrary number, use x' = x - m*(pi/2) + where m = floor(x/(pi/2)) along with quarter-period symmetries. + """ + if prec > COS_SIN_CACHE_PREC: + return exponential_series(x, prec, 2) + precs = prec - COS_SIN_CACHE_STEP + t = x >> precs + n = int(t) + if n not in cos_sin_cache: + w = t<<(10+COS_SIN_CACHE_PREC-COS_SIN_CACHE_STEP) + cos_t, sin_t = exponential_series(w, 10+COS_SIN_CACHE_PREC, 2) + cos_sin_cache[n] = (cos_t>>10), (sin_t>>10) + cos_t, sin_t = cos_sin_cache[n] + offset = COS_SIN_CACHE_PREC - prec + cos_t >>= offset + sin_t >>= offset + x -= t << precs + cos = MPZ_ONE << prec + sin = x + k = 2 + a = -((x*x) >> prec) + while a: + a //= k; cos += a; k += 1; a = (a*x) >> prec + a //= k; sin += a; k += 1; a = -((a*x) >> prec) + return ((cos*cos_t-sin*sin_t) >> prec), ((sin*cos_t+cos*sin_t) >> prec) + +def mpf_exp(x, prec, rnd=round_fast): + sign, man, exp, bc = x + if man: + mag = bc + exp + wp = prec + 14 + if sign: + man = -man + # TODO: the best cutoff depends on both x and the precision. + if prec > 600 and exp >= 0: + # Need about log2(exp(n)) ~= 1.45*mag extra precision + e = mpf_e(wp+int(1.45*mag)) + return mpf_pow_int(e, man<= 2 + if mag > 1: + # For large arguments: exp(2^mag*(1+eps)) = + # exp(2^mag)*exp(2^mag*eps) = exp(2^mag)*(1 + 2^mag*eps + ...) + # so about mag extra bits is required. + wpmod = wp + mag + offset = exp + wpmod + if offset >= 0: + t = man << offset + else: + t = man >> (-offset) + lg2 = ln2_fixed(wpmod) + n, t = divmod(t, lg2) + n = int(n) + t >>= mag + else: + offset = exp + wp + if offset >= 0: + t = man << offset + else: + t = man >> (-offset) + n = 0 + man = exp_basecase(t, wp) + return from_man_exp(man, n-wp, prec, rnd) + if not exp: + return fone + if x == fninf: + return fzero + return x + + +def mpf_cosh_sinh(x, prec, rnd=round_fast, tanh=0): + """Simultaneously compute (cosh(x), sinh(x)) for real x""" + sign, man, exp, bc = x + if (not man) and exp: + if tanh: + if x == finf: return fone + if x == fninf: return fnone + return fnan + if x == finf: return (finf, finf) + if x == fninf: return (finf, fninf) + return fnan, fnan + mag = exp+bc + wp = prec+14 + if mag < -4: + # Extremely close to 0, sinh(x) ~= x and cosh(x) ~= 1 + if mag < -wp: + if tanh: + return mpf_perturb(x, 1-sign, prec, rnd) + cosh = mpf_perturb(fone, 0, prec, rnd) + sinh = mpf_perturb(x, sign, prec, rnd) + return cosh, sinh + # Fix for cancellation when computing sinh + wp += (-mag) + # Does exp(-2*x) vanish? + if mag > 10: + if 3*(1<<(mag-1)) > wp: + # XXX: rounding + if tanh: + return mpf_perturb([fone,fnone][sign], 1-sign, prec, rnd) + c = s = mpf_shift(mpf_exp(mpf_abs(x), prec, rnd), -1) + if sign: + s = mpf_neg(s) + return c, s + # |x| > 1 + if mag > 1: + wpmod = wp + mag + offset = exp + wpmod + if offset >= 0: + t = man << offset + else: + t = man >> (-offset) + lg2 = ln2_fixed(wpmod) + n, t = divmod(t, lg2) + n = int(n) + t >>= mag + else: + offset = exp + wp + if offset >= 0: + t = man << offset + else: + t = man >> (-offset) + n = 0 + a, b = exp_expneg_basecase(t, wp) + # TODO: optimize division precision + cosh = a + (b>>(2*n)) + sinh = a - (b>>(2*n)) + if sign: + sinh = -sinh + if tanh: + man = (sinh << wp) // cosh + return from_man_exp(man, -wp, prec, rnd) + else: + cosh = from_man_exp(cosh, n-wp-1, prec, rnd) + sinh = from_man_exp(sinh, n-wp-1, prec, rnd) + return cosh, sinh + + +def mod_pi2(man, exp, mag, wp): + # Reduce to standard interval + if mag > 0: + i = 0 + while 1: + cancellation_prec = 20 << i + wpmod = wp + mag + cancellation_prec + pi2 = pi_fixed(wpmod-1) + pi4 = pi2 >> 1 + offset = wpmod + exp + if offset >= 0: + t = man << offset + else: + t = man >> (-offset) + n, y = divmod(t, pi2) + if y > pi4: + small = pi2 - y + else: + small = y + if small >> (wp+mag-10): + n = int(n) + t = y >> mag + wp = wpmod - mag + break + i += 1 + else: + wp += (-mag) + offset = exp + wp + if offset >= 0: + t = man << offset + else: + t = man >> (-offset) + n = 0 + return t, n, wp + + +def mpf_cos_sin(x, prec, rnd=round_fast, which=0, pi=False): + """ + which: + 0 -- return cos(x), sin(x) + 1 -- return cos(x) + 2 -- return sin(x) + 3 -- return tan(x) + + if pi=True, compute for pi*x + """ + sign, man, exp, bc = x + if not man: + if exp: + c, s = fnan, fnan + else: + c, s = fone, fzero + if which == 0: return c, s + if which == 1: return c + if which == 2: return s + if which == 3: return s + + mag = bc + exp + wp = prec + 10 + + # Extremely small? + if mag < 0: + if mag < -wp: + if pi: + x = mpf_mul(x, mpf_pi(wp)) + c = mpf_perturb(fone, 1, prec, rnd) + s = mpf_perturb(x, 1-sign, prec, rnd) + if which == 0: return c, s + if which == 1: return c + if which == 2: return s + if which == 3: return mpf_perturb(x, sign, prec, rnd) + if pi: + if exp >= -1: + if exp == -1: + c = fzero + s = (fone, fnone)[bool(man & 2) ^ sign] + elif exp == 0: + c, s = (fnone, fzero) + else: + c, s = (fone, fzero) + if which == 0: return c, s + if which == 1: return c + if which == 2: return s + if which == 3: return mpf_div(s, c, prec, rnd) + # Subtract nearest half-integer (= mod by pi/2) + n = ((man >> (-exp-2)) + 1) >> 1 + man = man - (n << (-exp-1)) + mag2 = bitcount(man) + exp + wp = prec + 10 - mag2 + offset = exp + wp + if offset >= 0: + t = man << offset + else: + t = man >> (-offset) + t = (t*pi_fixed(wp)) >> wp + else: + t, n, wp = mod_pi2(man, exp, mag, wp) + c, s = cos_sin_basecase(t, wp) + m = n & 3 + if m == 1: c, s = -s, c + elif m == 2: c, s = -c, -s + elif m == 3: c, s = s, -c + if sign: + s = -s + if which == 0: + c = from_man_exp(c, -wp, prec, rnd) + s = from_man_exp(s, -wp, prec, rnd) + return c, s + if which == 1: + return from_man_exp(c, -wp, prec, rnd) + if which == 2: + return from_man_exp(s, -wp, prec, rnd) + if which == 3: + return from_rational(s, c, prec, rnd) + +def mpf_cos(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 1) +def mpf_sin(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 2) +def mpf_tan(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 3) +def mpf_cos_sin_pi(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 0, 1) +def mpf_cos_pi(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 1, 1) +def mpf_sin_pi(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 2, 1) +def mpf_cosh(x, prec, rnd=round_fast): return mpf_cosh_sinh(x, prec, rnd)[0] +def mpf_sinh(x, prec, rnd=round_fast): return mpf_cosh_sinh(x, prec, rnd)[1] +def mpf_tanh(x, prec, rnd=round_fast): return mpf_cosh_sinh(x, prec, rnd, tanh=1) + + +# Low-overhead fixed-point versions + +def cos_sin_fixed(x, prec, pi2=None): + if pi2 is None: + pi2 = pi_fixed(prec-1) + n, t = divmod(x, pi2) + n = int(n) + c, s = cos_sin_basecase(t, prec) + m = n & 3 + if m == 0: return c, s + if m == 1: return -s, c + if m == 2: return -c, -s + if m == 3: return s, -c + +def exp_fixed(x, prec, ln2=None): + if ln2 is None: + ln2 = ln2_fixed(prec) + n, t = divmod(x, ln2) + n = int(n) + v = exp_basecase(t, prec) + if n >= 0: + return v << n + else: + return v >> (-n) + + +if BACKEND == 'sage': + try: + import sage.libs.mpmath.ext_libmp as _lbmp + mpf_sqrt = _lbmp.mpf_sqrt + mpf_exp = _lbmp.mpf_exp + mpf_log = _lbmp.mpf_log + mpf_cos = _lbmp.mpf_cos + mpf_sin = _lbmp.mpf_sin + mpf_pow = _lbmp.mpf_pow + exp_fixed = _lbmp.exp_fixed + cos_sin_fixed = _lbmp.cos_sin_fixed + log_int_fixed = _lbmp.log_int_fixed + except (ImportError, AttributeError): + print("Warning: Sage imports in libelefun failed") diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/libhyper.py b/venv/lib/python3.10/site-packages/mpmath/libmp/libhyper.py new file mode 100644 index 0000000000000000000000000000000000000000..04f52d59710be77819066aea5c1cf4b0883f72d7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/libmp/libhyper.py @@ -0,0 +1,1150 @@ +""" +This module implements computation of hypergeometric and related +functions. In particular, it provides code for generic summation +of hypergeometric series. Optimized versions for various special +cases are also provided. +""" + +import operator +import math + +from .backend import MPZ_ZERO, MPZ_ONE, BACKEND, xrange, exec_ + +from .libintmath import gcd + +from .libmpf import (\ + ComplexResult, round_fast, round_nearest, + negative_rnd, bitcount, to_fixed, from_man_exp, from_int, to_int, + from_rational, + fzero, fone, fnone, ftwo, finf, fninf, fnan, + mpf_sign, mpf_add, mpf_abs, mpf_pos, + mpf_cmp, mpf_lt, mpf_le, mpf_gt, mpf_min_max, + mpf_perturb, mpf_neg, mpf_shift, mpf_sub, mpf_mul, mpf_div, + sqrt_fixed, mpf_sqrt, mpf_rdiv_int, mpf_pow_int, + to_rational, +) + +from .libelefun import (\ + mpf_pi, mpf_exp, mpf_log, pi_fixed, mpf_cos_sin, mpf_cos, mpf_sin, + mpf_sqrt, agm_fixed, +) + +from .libmpc import (\ + mpc_one, mpc_sub, mpc_mul_mpf, mpc_mul, mpc_neg, complex_int_pow, + mpc_div, mpc_add_mpf, mpc_sub_mpf, + mpc_log, mpc_add, mpc_pos, mpc_shift, + mpc_is_infnan, mpc_zero, mpc_sqrt, mpc_abs, + mpc_mpf_div, mpc_square, mpc_exp +) + +from .libintmath import ifac +from .gammazeta import mpf_gamma_int, mpf_euler, euler_fixed + +class NoConvergence(Exception): + pass + + +#-----------------------------------------------------------------------# +# # +# Generic hypergeometric series # +# # +#-----------------------------------------------------------------------# + +""" +TODO: + +1. proper mpq parsing +2. imaginary z special-cased (also: rational, integer?) +3. more clever handling of series that don't converge because of stupid + upwards rounding +4. checking for cancellation + +""" + +def make_hyp_summator(key): + """ + Returns a function that sums a generalized hypergeometric series, + for given parameter types (integer, rational, real, complex). + + """ + p, q, param_types, ztype = key + + pstring = "".join(param_types) + fname = "hypsum_%i_%i_%s_%s_%s" % (p, q, pstring[:p], pstring[p:], ztype) + #print "generating hypsum", fname + + have_complex_param = 'C' in param_types + have_complex_arg = ztype == 'C' + have_complex = have_complex_param or have_complex_arg + + source = [] + add = source.append + + aint = [] + arat = [] + bint = [] + brat = [] + areal = [] + breal = [] + acomplex = [] + bcomplex = [] + + #add("wp = prec + 40") + add("MAX = kwargs.get('maxterms', wp*100)") + add("HIGH = MPZ_ONE<= 0:") + add(" ZRE = xm << offset") + add("else:") + add(" ZRE = xm >> (-offset)") + if have_complex_arg: + add("offset = ye + wp") + add("if offset >= 0:") + add(" ZIM = ym << offset") + add("else:") + add(" ZIM = ym >> (-offset)") + + for i, flag in enumerate(param_types): + W = ["A", "B"][i >= p] + if flag == 'Z': + ([aint,bint][i >= p]).append(i) + add("%sINT_%i = coeffs[%i]" % (W, i, i)) + elif flag == 'Q': + ([arat,brat][i >= p]).append(i) + add("%sP_%i, %sQ_%i = coeffs[%i]._mpq_" % (W, i, W, i, i)) + elif flag == 'R': + ([areal,breal][i >= p]).append(i) + add("xsign, xm, xe, xbc = coeffs[%i]._mpf_" % i) + add("if xsign: xm = -xm") + add("offset = xe + wp") + add("if offset >= 0:") + add(" %sREAL_%i = xm << offset" % (W, i)) + add("else:") + add(" %sREAL_%i = xm >> (-offset)" % (W, i)) + elif flag == 'C': + ([acomplex,bcomplex][i >= p]).append(i) + add("__re, __im = coeffs[%i]._mpc_" % i) + add("xsign, xm, xe, xbc = __re") + add("if xsign: xm = -xm") + add("ysign, ym, ye, ybc = __im") + add("if ysign: ym = -ym") + + add("offset = xe + wp") + add("if offset >= 0:") + add(" %sCRE_%i = xm << offset" % (W, i)) + add("else:") + add(" %sCRE_%i = xm >> (-offset)" % (W, i)) + add("offset = ye + wp") + add("if offset >= 0:") + add(" %sCIM_%i = ym << offset" % (W, i)) + add("else:") + add(" %sCIM_%i = ym >> (-offset)" % (W, i)) + else: + raise ValueError + + l_areal = len(areal) + l_breal = len(breal) + cancellable_real = min(l_areal, l_breal) + noncancellable_real_num = areal[cancellable_real:] + noncancellable_real_den = breal[cancellable_real:] + + # LOOP + add("for n in xrange(1,10**8):") + + add(" if n in magnitude_check:") + add(" p_mag = bitcount(abs(PRE))") + if have_complex: + add(" p_mag = max(p_mag, bitcount(abs(PIM)))") + add(" magnitude_check[n] = wp-p_mag") + + # Real factors + multiplier = " * ".join(["AINT_#".replace("#", str(i)) for i in aint] + \ + ["AP_#".replace("#", str(i)) for i in arat] + \ + ["BQ_#".replace("#", str(i)) for i in brat]) + + divisor = " * ".join(["BINT_#".replace("#", str(i)) for i in bint] + \ + ["BP_#".replace("#", str(i)) for i in brat] + \ + ["AQ_#".replace("#", str(i)) for i in arat] + ["n"]) + + if multiplier: + add(" mul = " + multiplier) + add(" div = " + divisor) + + # Check for singular terms + add(" if not div:") + if multiplier: + add(" if not mul:") + add(" break") + add(" raise ZeroDivisionError") + + # Update product + if have_complex: + + # TODO: when there are several real parameters and just a few complex + # (maybe just the complex argument), we only need to do about + # half as many ops if we accumulate the real factor in a single real variable + for k in range(cancellable_real): add(" PRE = PRE * AREAL_%i // BREAL_%i" % (areal[k], breal[k])) + for i in noncancellable_real_num: add(" PRE = (PRE * AREAL_#) >> wp".replace("#", str(i))) + for i in noncancellable_real_den: add(" PRE = (PRE << wp) // BREAL_#".replace("#", str(i))) + for k in range(cancellable_real): add(" PIM = PIM * AREAL_%i // BREAL_%i" % (areal[k], breal[k])) + for i in noncancellable_real_num: add(" PIM = (PIM * AREAL_#) >> wp".replace("#", str(i))) + for i in noncancellable_real_den: add(" PIM = (PIM << wp) // BREAL_#".replace("#", str(i))) + + if multiplier: + if have_complex_arg: + add(" PRE, PIM = (mul*(PRE*ZRE-PIM*ZIM))//div, (mul*(PIM*ZRE+PRE*ZIM))//div") + add(" PRE >>= wp") + add(" PIM >>= wp") + else: + add(" PRE = ((mul * PRE * ZRE) >> wp) // div") + add(" PIM = ((mul * PIM * ZRE) >> wp) // div") + else: + if have_complex_arg: + add(" PRE, PIM = (PRE*ZRE-PIM*ZIM)//div, (PIM*ZRE+PRE*ZIM)//div") + add(" PRE >>= wp") + add(" PIM >>= wp") + else: + add(" PRE = ((PRE * ZRE) >> wp) // div") + add(" PIM = ((PIM * ZRE) >> wp) // div") + + for i in acomplex: + add(" PRE, PIM = PRE*ACRE_#-PIM*ACIM_#, PIM*ACRE_#+PRE*ACIM_#".replace("#", str(i))) + add(" PRE >>= wp") + add(" PIM >>= wp") + + for i in bcomplex: + add(" mag = BCRE_#*BCRE_#+BCIM_#*BCIM_#".replace("#", str(i))) + add(" re = PRE*BCRE_# + PIM*BCIM_#".replace("#", str(i))) + add(" im = PIM*BCRE_# - PRE*BCIM_#".replace("#", str(i))) + add(" PRE = (re << wp) // mag".replace("#", str(i))) + add(" PIM = (im << wp) // mag".replace("#", str(i))) + + else: + for k in range(cancellable_real): add(" PRE = PRE * AREAL_%i // BREAL_%i" % (areal[k], breal[k])) + for i in noncancellable_real_num: add(" PRE = (PRE * AREAL_#) >> wp".replace("#", str(i))) + for i in noncancellable_real_den: add(" PRE = (PRE << wp) // BREAL_#".replace("#", str(i))) + if multiplier: + add(" PRE = ((PRE * mul * ZRE) >> wp) // div") + else: + add(" PRE = ((PRE * ZRE) >> wp) // div") + + # Add product to sum + if have_complex: + add(" SRE += PRE") + add(" SIM += PIM") + add(" if (HIGH > PRE > LOW) and (HIGH > PIM > LOW):") + add(" break") + else: + add(" SRE += PRE") + add(" if HIGH > PRE > LOW:") + add(" break") + + #add(" from mpmath import nprint, log, ldexp") + #add(" nprint([n, log(abs(PRE),2), ldexp(PRE,-wp)])") + + add(" if n > MAX:") + add(" raise NoConvergence('Hypergeometric series converges too slowly. Try increasing maxterms.')") + + # +1 all parameters for next loop + for i in aint: add(" AINT_# += 1".replace("#", str(i))) + for i in bint: add(" BINT_# += 1".replace("#", str(i))) + for i in arat: add(" AP_# += AQ_#".replace("#", str(i))) + for i in brat: add(" BP_# += BQ_#".replace("#", str(i))) + for i in areal: add(" AREAL_# += one".replace("#", str(i))) + for i in breal: add(" BREAL_# += one".replace("#", str(i))) + for i in acomplex: add(" ACRE_# += one".replace("#", str(i))) + for i in bcomplex: add(" BCRE_# += one".replace("#", str(i))) + + if have_complex: + add("a = from_man_exp(SRE, -wp, prec, 'n')") + add("b = from_man_exp(SIM, -wp, prec, 'n')") + + add("if SRE:") + add(" if SIM:") + add(" magn = max(a[2]+a[3], b[2]+b[3])") + add(" else:") + add(" magn = a[2]+a[3]") + add("elif SIM:") + add(" magn = b[2]+b[3]") + add("else:") + add(" magn = -wp+1") + + add("return (a, b), True, magn") + else: + add("a = from_man_exp(SRE, -wp, prec, 'n')") + + add("if SRE:") + add(" magn = a[2]+a[3]") + add("else:") + add(" magn = -wp+1") + + add("return a, False, magn") + + source = "\n".join((" " + line) for line in source) + source = ("def %s(coeffs, z, prec, wp, epsshift, magnitude_check, **kwargs):\n" % fname) + source + + namespace = {} + + exec_(source, globals(), namespace) + + #print source + return source, namespace[fname] + + +if BACKEND == 'sage': + + def make_hyp_summator(key): + """ + Returns a function that sums a generalized hypergeometric series, + for given parameter types (integer, rational, real, complex). + """ + from sage.libs.mpmath.ext_main import hypsum_internal + p, q, param_types, ztype = key + def _hypsum(coeffs, z, prec, wp, epsshift, magnitude_check, **kwargs): + return hypsum_internal(p, q, param_types, ztype, coeffs, z, + prec, wp, epsshift, magnitude_check, kwargs) + + return "(none)", _hypsum + + +#-----------------------------------------------------------------------# +# # +# Error functions # +# # +#-----------------------------------------------------------------------# + +# TODO: mpf_erf should call mpf_erfc when appropriate (currently +# only the converse delegation is implemented) + +def mpf_erf(x, prec, rnd=round_fast): + sign, man, exp, bc = x + if not man: + if x == fzero: return fzero + if x == finf: return fone + if x== fninf: return fnone + return fnan + size = exp + bc + lg = math.log + # The approximation erf(x) = 1 is accurate to > x^2 * log(e,2) bits + if size > 3 and 2*(size-1) + 0.528766 > lg(prec,2): + if sign: + return mpf_perturb(fnone, 0, prec, rnd) + else: + return mpf_perturb(fone, 1, prec, rnd) + # erf(x) ~ 2*x/sqrt(pi) close to 0 + if size < -prec: + # 2*x + x = mpf_shift(x,1) + c = mpf_sqrt(mpf_pi(prec+20), prec+20) + # TODO: interval rounding + return mpf_div(x, c, prec, rnd) + wp = prec + abs(size) + 25 + # Taylor series for erf, fixed-point summation + t = abs(to_fixed(x, wp)) + t2 = (t*t) >> wp + s, term, k = t, 12345, 1 + while term: + t = ((t * t2) >> wp) // k + term = t // (2*k+1) + if k & 1: + s -= term + else: + s += term + k += 1 + s = (s << (wp+1)) // sqrt_fixed(pi_fixed(wp), wp) + if sign: + s = -s + return from_man_exp(s, -wp, prec, rnd) + +# If possible, we use the asymptotic series for erfc. +# This is an alternating divergent asymptotic series, so +# the error is at most equal to the first omitted term. +# Here we check if the smallest term is small enough +# for a given x and precision +def erfc_check_series(x, prec): + n = to_int(x) + if n**2 * 1.44 > prec: + return True + return False + +def mpf_erfc(x, prec, rnd=round_fast): + sign, man, exp, bc = x + if not man: + if x == fzero: return fone + if x == finf: return fzero + if x == fninf: return ftwo + return fnan + wp = prec + 20 + mag = bc+exp + # Preserve full accuracy when exponent grows huge + wp += max(0, 2*mag) + regular_erf = sign or mag < 2 + if regular_erf or not erfc_check_series(x, wp): + if regular_erf: + return mpf_sub(fone, mpf_erf(x, prec+10, negative_rnd[rnd]), prec, rnd) + # 1-erf(x) ~ exp(-x^2), increase prec to deal with cancellation + n = to_int(x)+1 + return mpf_sub(fone, mpf_erf(x, prec + int(n**2*1.44) + 10), prec, rnd) + s = term = MPZ_ONE << wp + term_prev = 0 + t = (2 * to_fixed(x, wp) ** 2) >> wp + k = 1 + while 1: + term = ((term * (2*k - 1)) << wp) // t + if k > 4 and term > term_prev or not term: + break + if k & 1: + s -= term + else: + s += term + term_prev = term + #print k, to_str(from_man_exp(term, -wp, 50), 10) + k += 1 + s = (s << wp) // sqrt_fixed(pi_fixed(wp), wp) + s = from_man_exp(s, -wp, wp) + z = mpf_exp(mpf_neg(mpf_mul(x,x,wp),wp),wp) + y = mpf_div(mpf_mul(z, s, wp), x, prec, rnd) + return y + + +#-----------------------------------------------------------------------# +# # +# Exponential integrals # +# # +#-----------------------------------------------------------------------# + +def ei_taylor(x, prec): + s = t = x + k = 2 + while t: + t = ((t*x) >> prec) // k + s += t // k + k += 1 + return s + +def complex_ei_taylor(zre, zim, prec): + _abs = abs + sre = tre = zre + sim = tim = zim + k = 2 + while _abs(tre) + _abs(tim) > 5: + tre, tim = ((tre*zre-tim*zim)//k)>>prec, ((tre*zim+tim*zre)//k)>>prec + sre += tre // k + sim += tim // k + k += 1 + return sre, sim + +def ei_asymptotic(x, prec): + one = MPZ_ONE << prec + x = t = ((one << prec) // x) + s = one + x + k = 2 + while t: + t = (k*t*x) >> prec + s += t + k += 1 + return s + +def complex_ei_asymptotic(zre, zim, prec): + _abs = abs + one = MPZ_ONE << prec + M = (zim*zim + zre*zre) >> prec + # 1 / z + xre = tre = (zre << prec) // M + xim = tim = ((-zim) << prec) // M + sre = one + xre + sim = xim + k = 2 + while _abs(tre) + _abs(tim) > 1000: + #print tre, tim + tre, tim = ((tre*xre-tim*xim)*k)>>prec, ((tre*xim+tim*xre)*k)>>prec + sre += tre + sim += tim + k += 1 + if k > prec: + raise NoConvergence + return sre, sim + +def mpf_ei(x, prec, rnd=round_fast, e1=False): + if e1: + x = mpf_neg(x) + sign, man, exp, bc = x + if e1 and not sign: + if x == fzero: + return finf + raise ComplexResult("E1(x) for x < 0") + if man: + xabs = 0, man, exp, bc + xmag = exp+bc + wp = prec + 20 + can_use_asymp = xmag > wp + if not can_use_asymp: + if exp >= 0: + xabsint = man << exp + else: + xabsint = man >> (-exp) + can_use_asymp = xabsint > int(wp*0.693) + 10 + if can_use_asymp: + if xmag > wp: + v = fone + else: + v = from_man_exp(ei_asymptotic(to_fixed(x, wp), wp), -wp) + v = mpf_mul(v, mpf_exp(x, wp), wp) + v = mpf_div(v, x, prec, rnd) + else: + wp += 2*int(to_int(xabs)) + u = to_fixed(x, wp) + v = ei_taylor(u, wp) + euler_fixed(wp) + t1 = from_man_exp(v,-wp) + t2 = mpf_log(xabs,wp) + v = mpf_add(t1, t2, prec, rnd) + else: + if x == fzero: v = fninf + elif x == finf: v = finf + elif x == fninf: v = fzero + else: v = fnan + if e1: + v = mpf_neg(v) + return v + +def mpc_ei(z, prec, rnd=round_fast, e1=False): + if e1: + z = mpc_neg(z) + a, b = z + asign, aman, aexp, abc = a + bsign, bman, bexp, bbc = b + if b == fzero: + if e1: + x = mpf_neg(mpf_ei(a, prec, rnd)) + if not asign: + y = mpf_neg(mpf_pi(prec, rnd)) + else: + y = fzero + return x, y + else: + return mpf_ei(a, prec, rnd), fzero + if a != fzero: + if not aman or not bman: + return (fnan, fnan) + wp = prec + 40 + amag = aexp+abc + bmag = bexp+bbc + zmag = max(amag, bmag) + can_use_asymp = zmag > wp + if not can_use_asymp: + zabsint = abs(to_int(a)) + abs(to_int(b)) + can_use_asymp = zabsint > int(wp*0.693) + 20 + try: + if can_use_asymp: + if zmag > wp: + v = fone, fzero + else: + zre = to_fixed(a, wp) + zim = to_fixed(b, wp) + vre, vim = complex_ei_asymptotic(zre, zim, wp) + v = from_man_exp(vre, -wp), from_man_exp(vim, -wp) + v = mpc_mul(v, mpc_exp(z, wp), wp) + v = mpc_div(v, z, wp) + if e1: + v = mpc_neg(v, prec, rnd) + else: + x, y = v + if bsign: + v = mpf_pos(x, prec, rnd), mpf_sub(y, mpf_pi(wp), prec, rnd) + else: + v = mpf_pos(x, prec, rnd), mpf_add(y, mpf_pi(wp), prec, rnd) + return v + except NoConvergence: + pass + #wp += 2*max(0,zmag) + wp += 2*int(to_int(mpc_abs(z, 5))) + zre = to_fixed(a, wp) + zim = to_fixed(b, wp) + vre, vim = complex_ei_taylor(zre, zim, wp) + vre += euler_fixed(wp) + v = from_man_exp(vre,-wp), from_man_exp(vim,-wp) + if e1: + u = mpc_log(mpc_neg(z),wp) + else: + u = mpc_log(z,wp) + v = mpc_add(v, u, prec, rnd) + if e1: + v = mpc_neg(v) + return v + +def mpf_e1(x, prec, rnd=round_fast): + return mpf_ei(x, prec, rnd, True) + +def mpc_e1(x, prec, rnd=round_fast): + return mpc_ei(x, prec, rnd, True) + +def mpf_expint(n, x, prec, rnd=round_fast, gamma=False): + """ + E_n(x), n an integer, x real + + With gamma=True, computes Gamma(n,x) (upper incomplete gamma function) + + Returns (real, None) if real, otherwise (real, imag) + The imaginary part is an optional branch cut term + + """ + sign, man, exp, bc = x + if not man: + if gamma: + if x == fzero: + # Actually gamma function pole + if n <= 0: + return finf, None + return mpf_gamma_int(n, prec, rnd), None + if x == finf: + return fzero, None + # TODO: could return finite imaginary value at -inf + return fnan, fnan + else: + if x == fzero: + if n > 1: + return from_rational(1, n-1, prec, rnd), None + else: + return finf, None + if x == finf: + return fzero, None + return fnan, fnan + n_orig = n + if gamma: + n = 1-n + wp = prec + 20 + xmag = exp + bc + # Beware of near-poles + if xmag < -10: + raise NotImplementedError + nmag = bitcount(abs(n)) + have_imag = n > 0 and sign + negx = mpf_neg(x) + # Skip series if direct convergence + if n == 0 or 2*nmag - xmag < -wp: + if gamma: + v = mpf_exp(negx, wp) + re = mpf_mul(v, mpf_pow_int(x, n_orig-1, wp), prec, rnd) + else: + v = mpf_exp(negx, wp) + re = mpf_div(v, x, prec, rnd) + else: + # Finite number of terms, or... + can_use_asymptotic_series = -3*wp < n <= 0 + # ...large enough? + if not can_use_asymptotic_series: + xi = abs(to_int(x)) + m = min(max(1, xi-n), 2*wp) + siz = -n*nmag + (m+n)*bitcount(abs(m+n)) - m*xmag - (144*m//100) + tol = -wp-10 + can_use_asymptotic_series = siz < tol + if can_use_asymptotic_series: + r = ((-MPZ_ONE) << (wp+wp)) // to_fixed(x, wp) + m = n + t = r*m + s = MPZ_ONE << wp + while m and t: + s += t + m += 1 + t = (m*r*t) >> wp + v = mpf_exp(negx, wp) + if gamma: + # ~ exp(-x) * x^(n-1) * (1 + ...) + v = mpf_mul(v, mpf_pow_int(x, n_orig-1, wp), wp) + else: + # ~ exp(-x)/x * (1 + ...) + v = mpf_div(v, x, wp) + re = mpf_mul(v, from_man_exp(s, -wp), prec, rnd) + elif n == 1: + re = mpf_neg(mpf_ei(negx, prec, rnd)) + elif n > 0 and n < 3*wp: + T1 = mpf_neg(mpf_ei(negx, wp)) + if gamma: + if n_orig & 1: + T1 = mpf_neg(T1) + else: + T1 = mpf_mul(T1, mpf_pow_int(negx, n-1, wp), wp) + r = t = to_fixed(x, wp) + facs = [1] * (n-1) + for k in range(1,n-1): + facs[k] = facs[k-1] * k + facs = facs[::-1] + s = facs[0] << wp + for k in range(1, n-1): + if k & 1: + s -= facs[k] * t + else: + s += facs[k] * t + t = (t*r) >> wp + T2 = from_man_exp(s, -wp, wp) + T2 = mpf_mul(T2, mpf_exp(negx, wp)) + if gamma: + T2 = mpf_mul(T2, mpf_pow_int(x, n_orig, wp), wp) + R = mpf_add(T1, T2) + re = mpf_div(R, from_int(ifac(n-1)), prec, rnd) + else: + raise NotImplementedError + if have_imag: + M = from_int(-ifac(n-1)) + if gamma: + im = mpf_div(mpf_pi(wp), M, prec, rnd) + if n_orig & 1: + im = mpf_neg(im) + else: + im = mpf_div(mpf_mul(mpf_pi(wp), mpf_pow_int(negx, n_orig-1, wp), wp), M, prec, rnd) + return re, im + else: + return re, None + +def mpf_ci_si_taylor(x, wp, which=0): + """ + 0 - Ci(x) - (euler+log(x)) + 1 - Si(x) + """ + x = to_fixed(x, wp) + x2 = -(x*x) >> wp + if which == 0: + s, t, k = 0, (MPZ_ONE<>wp + s += t//k + k += 2 + return from_man_exp(s, -wp) + +def mpc_ci_si_taylor(re, im, wp, which=0): + # The following code is only designed for small arguments, + # and not too small arguments (for relative accuracy) + if re[1]: + mag = re[2]+re[3] + elif im[1]: + mag = im[2]+im[3] + if im[1]: + mag = max(mag, im[2]+im[3]) + if mag > 2 or mag < -wp: + raise NotImplementedError + wp += (2-mag) + zre = to_fixed(re, wp) + zim = to_fixed(im, wp) + z2re = (zim*zim-zre*zre)>>wp + z2im = (-2*zre*zim)>>wp + tre = zre + tim = zim + one = MPZ_ONE< 2: + f = k*(k-1) + tre, tim = ((tre*z2re-tim*z2im)//f)>>wp, ((tre*z2im+tim*z2re)//f)>>wp + sre += tre//k + sim += tim//k + k += 2 + return from_man_exp(sre, -wp), from_man_exp(sim, -wp) + +def mpf_ci_si(x, prec, rnd=round_fast, which=2): + """ + Calculation of Ci(x), Si(x) for real x. + + which = 0 -- returns (Ci(x), -) + which = 1 -- returns (Si(x), -) + which = 2 -- returns (Ci(x), Si(x)) + + Note: if x < 0, Ci(x) needs an additional imaginary term, pi*i. + """ + wp = prec + 20 + sign, man, exp, bc = x + ci, si = None, None + if not man: + if x == fzero: + return (fninf, fzero) + if x == fnan: + return (x, x) + ci = fzero + if which != 0: + if x == finf: + si = mpf_shift(mpf_pi(prec, rnd), -1) + if x == fninf: + si = mpf_neg(mpf_shift(mpf_pi(prec, negative_rnd[rnd]), -1)) + return (ci, si) + # For small x: Ci(x) ~ euler + log(x), Si(x) ~ x + mag = exp+bc + if mag < -wp: + if which != 0: + si = mpf_perturb(x, 1-sign, prec, rnd) + if which != 1: + y = mpf_euler(wp) + xabs = mpf_abs(x) + ci = mpf_add(y, mpf_log(xabs, wp), prec, rnd) + return ci, si + # For huge x: Ci(x) ~ sin(x)/x, Si(x) ~ pi/2 + elif mag > wp: + if which != 0: + if sign: + si = mpf_neg(mpf_pi(prec, negative_rnd[rnd])) + else: + si = mpf_pi(prec, rnd) + si = mpf_shift(si, -1) + if which != 1: + ci = mpf_div(mpf_sin(x, wp), x, prec, rnd) + return ci, si + else: + wp += abs(mag) + # Use an asymptotic series? The smallest value of n!/x^n + # occurs for n ~ x, where the magnitude is ~ exp(-x). + asymptotic = mag-1 > math.log(wp, 2) + # Case 1: convergent series near 0 + if not asymptotic: + if which != 0: + si = mpf_pos(mpf_ci_si_taylor(x, wp, 1), prec, rnd) + if which != 1: + ci = mpf_ci_si_taylor(x, wp, 0) + ci = mpf_add(ci, mpf_euler(wp), wp) + ci = mpf_add(ci, mpf_log(mpf_abs(x), wp), prec, rnd) + return ci, si + x = mpf_abs(x) + # Case 2: asymptotic series for x >> 1 + xf = to_fixed(x, wp) + xr = (MPZ_ONE<<(2*wp)) // xf # 1/x + s1 = (MPZ_ONE << wp) + s2 = xr + t = xr + k = 2 + while t: + t = -t + t = (t*xr*k)>>wp + k += 1 + s1 += t + t = (t*xr*k)>>wp + k += 1 + s2 += t + s1 = from_man_exp(s1, -wp) + s2 = from_man_exp(s2, -wp) + s1 = mpf_div(s1, x, wp) + s2 = mpf_div(s2, x, wp) + cos, sin = mpf_cos_sin(x, wp) + # Ci(x) = sin(x)*s1-cos(x)*s2 + # Si(x) = pi/2-cos(x)*s1-sin(x)*s2 + if which != 0: + si = mpf_add(mpf_mul(cos, s1), mpf_mul(sin, s2), wp) + si = mpf_sub(mpf_shift(mpf_pi(wp), -1), si, wp) + if sign: + si = mpf_neg(si) + si = mpf_pos(si, prec, rnd) + if which != 1: + ci = mpf_sub(mpf_mul(sin, s1), mpf_mul(cos, s2), prec, rnd) + return ci, si + +def mpf_ci(x, prec, rnd=round_fast): + if mpf_sign(x) < 0: + raise ComplexResult + return mpf_ci_si(x, prec, rnd, 0)[0] + +def mpf_si(x, prec, rnd=round_fast): + return mpf_ci_si(x, prec, rnd, 1)[1] + +def mpc_ci(z, prec, rnd=round_fast): + re, im = z + if im == fzero: + ci = mpf_ci_si(re, prec, rnd, 0)[0] + if mpf_sign(re) < 0: + return (ci, mpf_pi(prec, rnd)) + return (ci, fzero) + wp = prec + 20 + cre, cim = mpc_ci_si_taylor(re, im, wp, 0) + cre = mpf_add(cre, mpf_euler(wp), wp) + ci = mpc_add((cre, cim), mpc_log(z, wp), prec, rnd) + return ci + +def mpc_si(z, prec, rnd=round_fast): + re, im = z + if im == fzero: + return (mpf_ci_si(re, prec, rnd, 1)[1], fzero) + wp = prec + 20 + z = mpc_ci_si_taylor(re, im, wp, 1) + return mpc_pos(z, prec, rnd) + + +#-----------------------------------------------------------------------# +# # +# Bessel functions # +# # +#-----------------------------------------------------------------------# + +# A Bessel function of the first kind of integer order, J_n(x), is +# given by the power series + +# oo +# ___ k 2 k + n +# \ (-1) / x \ +# J_n(x) = ) ----------- | - | +# /___ k! (k + n)! \ 2 / +# k = 0 + +# Simplifying the quotient between two successive terms gives the +# ratio x^2 / (-4*k*(k+n)). Hence, we only need one full-precision +# multiplication and one division by a small integer per term. +# The complex version is very similar, the only difference being +# that the multiplication is actually 4 multiplies. + +# In the general case, we have +# J_v(x) = (x/2)**v / v! * 0F1(v+1, (-1/4)*z**2) + +# TODO: for extremely large x, we could use an asymptotic +# trigonometric approximation. + +# TODO: recompute at higher precision if the fixed-point mantissa +# is very small + +def mpf_besseljn(n, x, prec, rounding=round_fast): + prec += 50 + negate = n < 0 and n & 1 + mag = x[2]+x[3] + n = abs(n) + wp = prec + 20 + n*bitcount(n) + if mag < 0: + wp -= n * mag + x = to_fixed(x, wp) + x2 = (x**2) >> wp + if not n: + s = t = MPZ_ONE << wp + else: + s = t = (x**n // ifac(n)) >> ((n-1)*wp + n) + k = 1 + while t: + t = ((t * x2) // (-4*k*(k+n))) >> wp + s += t + k += 1 + if negate: + s = -s + return from_man_exp(s, -wp, prec, rounding) + +def mpc_besseljn(n, z, prec, rounding=round_fast): + negate = n < 0 and n & 1 + n = abs(n) + origprec = prec + zre, zim = z + mag = max(zre[2]+zre[3], zim[2]+zim[3]) + prec += 20 + n*bitcount(n) + abs(mag) + if mag < 0: + prec -= n * mag + zre = to_fixed(zre, prec) + zim = to_fixed(zim, prec) + z2re = (zre**2 - zim**2) >> prec + z2im = (zre*zim) >> (prec-1) + if not n: + sre = tre = MPZ_ONE << prec + sim = tim = MPZ_ZERO + else: + re, im = complex_int_pow(zre, zim, n) + sre = tre = (re // ifac(n)) >> ((n-1)*prec + n) + sim = tim = (im // ifac(n)) >> ((n-1)*prec + n) + k = 1 + while abs(tre) + abs(tim) > 3: + p = -4*k*(k+n) + tre, tim = tre*z2re - tim*z2im, tim*z2re + tre*z2im + tre = (tre // p) >> prec + tim = (tim // p) >> prec + sre += tre + sim += tim + k += 1 + if negate: + sre = -sre + sim = -sim + re = from_man_exp(sre, -prec, origprec, rounding) + im = from_man_exp(sim, -prec, origprec, rounding) + return (re, im) + +def mpf_agm(a, b, prec, rnd=round_fast): + """ + Computes the arithmetic-geometric mean agm(a,b) for + nonnegative mpf values a, b. + """ + asign, aman, aexp, abc = a + bsign, bman, bexp, bbc = b + if asign or bsign: + raise ComplexResult("agm of a negative number") + # Handle inf, nan or zero in either operand + if not (aman and bman): + if a == fnan or b == fnan: + return fnan + if a == finf: + if b == fzero: + return fnan + return finf + if b == finf: + if a == fzero: + return fnan + return finf + # agm(0,x) = agm(x,0) = 0 + return fzero + wp = prec + 20 + amag = aexp+abc + bmag = bexp+bbc + mag_delta = amag - bmag + # Reduce to roughly the same magnitude using floating-point AGM + abs_mag_delta = abs(mag_delta) + if abs_mag_delta > 10: + while abs_mag_delta > 10: + a, b = mpf_shift(mpf_add(a,b,wp),-1), \ + mpf_sqrt(mpf_mul(a,b,wp),wp) + abs_mag_delta //= 2 + asign, aman, aexp, abc = a + bsign, bman, bexp, bbc = b + amag = aexp+abc + bmag = bexp+bbc + mag_delta = amag - bmag + #print to_float(a), to_float(b) + # Use agm(a,b) = agm(x*a,x*b)/x to obtain a, b ~= 1 + min_mag = min(amag,bmag) + max_mag = max(amag,bmag) + n = 0 + # If too small, we lose precision when going to fixed-point + if min_mag < -8: + n = -min_mag + # If too large, we waste time using fixed-point with large numbers + elif max_mag > 20: + n = -max_mag + if n: + a = mpf_shift(a, n) + b = mpf_shift(b, n) + #print to_float(a), to_float(b) + af = to_fixed(a, wp) + bf = to_fixed(b, wp) + g = agm_fixed(af, bf, wp) + return from_man_exp(g, -wp-n, prec, rnd) + +def mpf_agm1(a, prec, rnd=round_fast): + """ + Computes the arithmetic-geometric mean agm(1,a) for a nonnegative + mpf value a. + """ + return mpf_agm(fone, a, prec, rnd) + +def mpc_agm(a, b, prec, rnd=round_fast): + """ + Complex AGM. + + TODO: + * check that convergence works as intended + * optimize + * select a nonarbitrary branch + """ + if mpc_is_infnan(a) or mpc_is_infnan(b): + return fnan, fnan + if mpc_zero in (a, b): + return fzero, fzero + if mpc_neg(a) == b: + return fzero, fzero + wp = prec+20 + eps = mpf_shift(fone, -wp+10) + while 1: + a1 = mpc_shift(mpc_add(a, b, wp), -1) + b1 = mpc_sqrt(mpc_mul(a, b, wp), wp) + a, b = a1, b1 + size = mpf_min_max([mpc_abs(a,10), mpc_abs(b,10)])[1] + err = mpc_abs(mpc_sub(a, b, 10), 10) + if size == fzero or mpf_lt(err, mpf_mul(eps, size)): + return a + +def mpc_agm1(a, prec, rnd=round_fast): + return mpc_agm(mpc_one, a, prec, rnd) + +def mpf_ellipk(x, prec, rnd=round_fast): + if not x[1]: + if x == fzero: + return mpf_shift(mpf_pi(prec, rnd), -1) + if x == fninf: + return fzero + if x == fnan: + return x + if x == fone: + return finf + # TODO: for |x| << 1/2, one could use fall back to + # pi/2 * hyp2f1_rat((1,2),(1,2),(1,1), x) + wp = prec + 15 + # Use K(x) = pi/2/agm(1,a) where a = sqrt(1-x) + # The sqrt raises ComplexResult if x > 0 + a = mpf_sqrt(mpf_sub(fone, x, wp), wp) + v = mpf_agm1(a, wp) + r = mpf_div(mpf_pi(wp), v, prec, rnd) + return mpf_shift(r, -1) + +def mpc_ellipk(z, prec, rnd=round_fast): + re, im = z + if im == fzero: + if re == finf: + return mpc_zero + if mpf_le(re, fone): + return mpf_ellipk(re, prec, rnd), fzero + wp = prec + 15 + a = mpc_sqrt(mpc_sub(mpc_one, z, wp), wp) + v = mpc_agm1(a, wp) + r = mpc_mpf_div(mpf_pi(wp), v, prec, rnd) + return mpc_shift(r, -1) + +def mpf_ellipe(x, prec, rnd=round_fast): + # http://functions.wolfram.com/EllipticIntegrals/ + # EllipticK/20/01/0001/ + # E = (1-m)*(K'(m)*2*m + K(m)) + sign, man, exp, bc = x + if not man: + if x == fzero: + return mpf_shift(mpf_pi(prec, rnd), -1) + if x == fninf: + return finf + if x == fnan: + return x + if x == finf: + raise ComplexResult + if x == fone: + return fone + wp = prec+20 + mag = exp+bc + if mag < -wp: + return mpf_shift(mpf_pi(prec, rnd), -1) + # Compute a finite difference for K' + p = max(mag, 0) - wp + h = mpf_shift(fone, p) + K = mpf_ellipk(x, 2*wp) + Kh = mpf_ellipk(mpf_sub(x, h), 2*wp) + Kdiff = mpf_shift(mpf_sub(K, Kh), -p) + t = mpf_sub(fone, x) + b = mpf_mul(Kdiff, mpf_shift(x,1), wp) + return mpf_mul(t, mpf_add(K, b), prec, rnd) + +def mpc_ellipe(z, prec, rnd=round_fast): + re, im = z + if im == fzero: + if re == finf: + return (fzero, finf) + if mpf_le(re, fone): + return mpf_ellipe(re, prec, rnd), fzero + wp = prec + 15 + mag = mpc_abs(z, 1) + p = max(mag[2]+mag[3], 0) - wp + h = mpf_shift(fone, p) + K = mpc_ellipk(z, 2*wp) + Kh = mpc_ellipk(mpc_add_mpf(z, h, 2*wp), 2*wp) + Kdiff = mpc_shift(mpc_sub(Kh, K, wp), -p) + t = mpc_sub(mpc_one, z, wp) + b = mpc_mul(Kdiff, mpc_shift(z,1), wp) + return mpc_mul(t, mpc_add(K, b, wp), prec, rnd) diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/libintmath.py b/venv/lib/python3.10/site-packages/mpmath/libmp/libintmath.py new file mode 100644 index 0000000000000000000000000000000000000000..7880546e135639208d136488408b102ad41682a2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/libmp/libintmath.py @@ -0,0 +1,584 @@ +""" +Utility functions for integer math. + +TODO: rename, cleanup, perhaps move the gmpy wrapper code +here from settings.py + +""" + +import math +from bisect import bisect + +from .backend import xrange +from .backend import BACKEND, gmpy, sage, sage_utils, MPZ, MPZ_ONE, MPZ_ZERO + +small_trailing = [0] * 256 +for j in range(1,8): + small_trailing[1<>> giant_steps(50,1000) + [66, 128, 253, 502, 1000] + >>> giant_steps(50,1000,4) + [65, 252, 1000] + + """ + L = [target] + while L[-1] > start*n: + L = L + [L[-1]//n + 2] + return L[::-1] + +def rshift(x, n): + """For an integer x, calculate x >> n with the fastest (floor) + rounding. Unlike the plain Python expression (x >> n), n is + allowed to be negative, in which case a left shift is performed.""" + if n >= 0: return x >> n + else: return x << (-n) + +def lshift(x, n): + """For an integer x, calculate x << n. Unlike the plain Python + expression (x << n), n is allowed to be negative, in which case a + right shift with default (floor) rounding is performed.""" + if n >= 0: return x << n + else: return x >> (-n) + +if BACKEND == 'sage': + import operator + rshift = operator.rshift + lshift = operator.lshift + +def python_trailing(n): + """Count the number of trailing zero bits in abs(n).""" + if not n: + return 0 + low_byte = n & 0xff + if low_byte: + return small_trailing[low_byte] + t = 8 + n >>= 8 + while not n & 0xff: + n >>= 8 + t += 8 + return t + small_trailing[n & 0xff] + +if BACKEND == 'gmpy': + if gmpy.version() >= '2': + def gmpy_trailing(n): + """Count the number of trailing zero bits in abs(n) using gmpy.""" + if n: return MPZ(n).bit_scan1() + else: return 0 + else: + def gmpy_trailing(n): + """Count the number of trailing zero bits in abs(n) using gmpy.""" + if n: return MPZ(n).scan1() + else: return 0 + +# Small powers of 2 +powers = [1<<_ for _ in range(300)] + +def python_bitcount(n): + """Calculate bit size of the nonnegative integer n.""" + bc = bisect(powers, n) + if bc != 300: + return bc + bc = int(math.log(n, 2)) - 4 + return bc + bctable[n>>bc] + +def gmpy_bitcount(n): + """Calculate bit size of the nonnegative integer n.""" + if n: return MPZ(n).numdigits(2) + else: return 0 + +#def sage_bitcount(n): +# if n: return MPZ(n).nbits() +# else: return 0 + +def sage_trailing(n): + return MPZ(n).trailing_zero_bits() + +if BACKEND == 'gmpy': + bitcount = gmpy_bitcount + trailing = gmpy_trailing +elif BACKEND == 'sage': + sage_bitcount = sage_utils.bitcount + bitcount = sage_bitcount + trailing = sage_trailing +else: + bitcount = python_bitcount + trailing = python_trailing + +if BACKEND == 'gmpy' and 'bit_length' in dir(gmpy): + bitcount = gmpy.bit_length + +# Used to avoid slow function calls as far as possible +trailtable = [trailing(n) for n in range(256)] +bctable = [bitcount(n) for n in range(1024)] + +# TODO: speed up for bases 2, 4, 8, 16, ... + +def bin_to_radix(x, xbits, base, bdigits): + """Changes radix of a fixed-point number; i.e., converts + x * 2**xbits to floor(x * 10**bdigits).""" + return x * (MPZ(base)**bdigits) >> xbits + +stddigits = '0123456789abcdefghijklmnopqrstuvwxyz' + +def small_numeral(n, base=10, digits=stddigits): + """Return the string numeral of a positive integer in an arbitrary + base. Most efficient for small input.""" + if base == 10: + return str(n) + digs = [] + while n: + n, digit = divmod(n, base) + digs.append(digits[digit]) + return "".join(digs[::-1]) + +def numeral_python(n, base=10, size=0, digits=stddigits): + """Represent the integer n as a string of digits in the given base. + Recursive division is used to make this function about 3x faster + than Python's str() for converting integers to decimal strings. + + The 'size' parameters specifies the number of digits in n; this + number is only used to determine splitting points and need not be + exact.""" + if n <= 0: + if not n: + return "0" + return "-" + numeral(-n, base, size, digits) + # Fast enough to do directly + if size < 250: + return small_numeral(n, base, digits) + # Divide in half + half = (size // 2) + (size & 1) + A, B = divmod(n, base**half) + ad = numeral(A, base, half, digits) + bd = numeral(B, base, half, digits).rjust(half, "0") + return ad + bd + +def numeral_gmpy(n, base=10, size=0, digits=stddigits): + """Represent the integer n as a string of digits in the given base. + Recursive division is used to make this function about 3x faster + than Python's str() for converting integers to decimal strings. + + The 'size' parameters specifies the number of digits in n; this + number is only used to determine splitting points and need not be + exact.""" + if n < 0: + return "-" + numeral(-n, base, size, digits) + # gmpy.digits() may cause a segmentation fault when trying to convert + # extremely large values to a string. The size limit may need to be + # adjusted on some platforms, but 1500000 works on Windows and Linux. + if size < 1500000: + return gmpy.digits(n, base) + # Divide in half + half = (size // 2) + (size & 1) + A, B = divmod(n, MPZ(base)**half) + ad = numeral(A, base, half, digits) + bd = numeral(B, base, half, digits).rjust(half, "0") + return ad + bd + +if BACKEND == "gmpy": + numeral = numeral_gmpy +else: + numeral = numeral_python + +_1_800 = 1<<800 +_1_600 = 1<<600 +_1_400 = 1<<400 +_1_200 = 1<<200 +_1_100 = 1<<100 +_1_50 = 1<<50 + +def isqrt_small_python(x): + """ + Correctly (floor) rounded integer square root, using + division. Fast up to ~200 digits. + """ + if not x: + return x + if x < _1_800: + # Exact with IEEE double precision arithmetic + if x < _1_50: + return int(x**0.5) + # Initial estimate can be any integer >= the true root; round up + r = int(x**0.5 * 1.00000000000001) + 1 + else: + bc = bitcount(x) + n = bc//2 + r = int((x>>(2*n-100))**0.5+2)<<(n-50) # +2 is to round up + # The following iteration now precisely computes floor(sqrt(x)) + # See e.g. Crandall & Pomerance, "Prime Numbers: A Computational + # Perspective" + while 1: + y = (r+x//r)>>1 + if y >= r: + return r + r = y + +def isqrt_fast_python(x): + """ + Fast approximate integer square root, computed using division-free + Newton iteration for large x. For random integers the result is almost + always correct (floor(sqrt(x))), but is 1 ulp too small with a roughly + 0.1% probability. If x is very close to an exact square, the answer is + 1 ulp wrong with high probability. + + With 0 guard bits, the largest error over a set of 10^5 random + inputs of size 1-10^5 bits was 3 ulp. The use of 10 guard bits + almost certainly guarantees a max 1 ulp error. + """ + # Use direct division-based iteration if sqrt(x) < 2^400 + # Assume floating-point square root accurate to within 1 ulp, then: + # 0 Newton iterations good to 52 bits + # 1 Newton iterations good to 104 bits + # 2 Newton iterations good to 208 bits + # 3 Newton iterations good to 416 bits + if x < _1_800: + y = int(x**0.5) + if x >= _1_100: + y = (y + x//y) >> 1 + if x >= _1_200: + y = (y + x//y) >> 1 + if x >= _1_400: + y = (y + x//y) >> 1 + return y + bc = bitcount(x) + guard_bits = 10 + x <<= 2*guard_bits + bc += 2*guard_bits + bc += (bc&1) + hbc = bc//2 + startprec = min(50, hbc) + # Newton iteration for 1/sqrt(x), with floating-point starting value + r = int(2.0**(2*startprec) * (x >> (bc-2*startprec)) ** -0.5) + pp = startprec + for p in giant_steps(startprec, hbc): + # r**2, scaled from real size 2**(-bc) to 2**p + r2 = (r*r) >> (2*pp - p) + # x*r**2, scaled from real size ~1.0 to 2**p + xr2 = ((x >> (bc-p)) * r2) >> p + # New value of r, scaled from real size 2**(-bc/2) to 2**p + r = (r * ((3<> (pp+1) + pp = p + # (1/sqrt(x))*x = sqrt(x) + return (r*(x>>hbc)) >> (p+guard_bits) + +def sqrtrem_python(x): + """Correctly rounded integer (floor) square root with remainder.""" + # to check cutoff: + # plot(lambda x: timing(isqrt, 2**int(x)), [0,2000]) + if x < _1_600: + y = isqrt_small_python(x) + return y, x - y*y + y = isqrt_fast_python(x) + 1 + rem = x - y*y + # Correct remainder + while rem < 0: + y -= 1 + rem += (1+2*y) + else: + if rem: + while rem > 2*(1+y): + y += 1 + rem -= (1+2*y) + return y, rem + +def isqrt_python(x): + """Integer square root with correct (floor) rounding.""" + return sqrtrem_python(x)[0] + +def sqrt_fixed(x, prec): + return isqrt_fast(x<= '2': + isqrt_small = isqrt_fast = isqrt = gmpy.isqrt + sqrtrem = gmpy.isqrt_rem + else: + isqrt_small = isqrt_fast = isqrt = gmpy.sqrt + sqrtrem = gmpy.sqrtrem +elif BACKEND == 'sage': + isqrt_small = isqrt_fast = isqrt = \ + getattr(sage_utils, "isqrt", lambda n: MPZ(n).isqrt()) + sqrtrem = lambda n: MPZ(n).sqrtrem() +else: + isqrt_small = isqrt_small_python + isqrt_fast = isqrt_fast_python + isqrt = isqrt_python + sqrtrem = sqrtrem_python + + +def ifib(n, _cache={}): + """Computes the nth Fibonacci number as an integer, for + integer n.""" + if n < 0: + return (-1)**(-n+1) * ifib(-n) + if n in _cache: + return _cache[n] + m = n + # Use Dijkstra's logarithmic algorithm + # The following implementation is basically equivalent to + # http://en.literateprograms.org/Fibonacci_numbers_(Scheme) + a, b, p, q = MPZ_ONE, MPZ_ZERO, MPZ_ZERO, MPZ_ONE + while n: + if n & 1: + aq = a*q + a, b = b*q+aq+a*p, b*p+aq + n -= 1 + else: + qq = q*q + p, q = p*p+qq, qq+2*p*q + n >>= 1 + if m < 250: + _cache[m] = b + return b + +MAX_FACTORIAL_CACHE = 1000 + +def ifac(n, memo={0:1, 1:1}): + """Return n factorial (for integers n >= 0 only).""" + f = memo.get(n) + if f: + return f + k = len(memo) + p = memo[k-1] + MAX = MAX_FACTORIAL_CACHE + while k <= n: + p *= k + if k <= MAX: + memo[k] = p + k += 1 + return p + +def ifac2(n, memo_pair=[{0:1}, {1:1}]): + """Return n!! (double factorial), integers n >= 0 only.""" + memo = memo_pair[n&1] + f = memo.get(n) + if f: + return f + k = max(memo) + p = memo[k] + MAX = MAX_FACTORIAL_CACHE + while k < n: + k += 2 + p *= k + if k <= MAX: + memo[k] = p + return p + +if BACKEND == 'gmpy': + ifac = gmpy.fac +elif BACKEND == 'sage': + ifac = lambda n: int(sage.factorial(n)) + ifib = sage.fibonacci + +def list_primes(n): + n = n + 1 + sieve = list(xrange(n)) + sieve[:2] = [0, 0] + for i in xrange(2, int(n**0.5)+1): + if sieve[i]: + for j in xrange(i**2, n, i): + sieve[j] = 0 + return [p for p in sieve if p] + +if BACKEND == 'sage': + # Note: it is *VERY* important for performance that we convert + # the list to Python ints. + def list_primes(n): + return [int(_) for _ in sage.primes(n+1)] + +small_odd_primes = (3,5,7,11,13,17,19,23,29,31,37,41,43,47) +small_odd_primes_set = set(small_odd_primes) + +def isprime(n): + """ + Determines whether n is a prime number. A probabilistic test is + performed if n is very large. No special trick is used for detecting + perfect powers. + + >>> sum(list_primes(100000)) + 454396537 + >>> sum(n*isprime(n) for n in range(100000)) + 454396537 + + """ + n = int(n) + if not n & 1: + return n == 2 + if n < 50: + return n in small_odd_primes_set + for p in small_odd_primes: + if not n % p: + return False + m = n-1 + s = trailing(m) + d = m >> s + def test(a): + x = pow(a,d,n) + if x == 1 or x == m: + return True + for r in xrange(1,s): + x = x**2 % n + if x == m: + return True + return False + # See http://primes.utm.edu/prove/prove2_3.html + if n < 1373653: + witnesses = [2,3] + elif n < 341550071728321: + witnesses = [2,3,5,7,11,13,17] + else: + witnesses = small_odd_primes + for a in witnesses: + if not test(a): + return False + return True + +def moebius(n): + """ + Evaluates the Moebius function which is `mu(n) = (-1)^k` if `n` + is a product of `k` distinct primes and `mu(n) = 0` otherwise. + + TODO: speed up using factorization + """ + n = abs(int(n)) + if n < 2: + return n + factors = [] + for p in xrange(2, n+1): + if not (n % p): + if not (n % p**2): + return 0 + if not sum(p % f for f in factors): + factors.append(p) + return (-1)**len(factors) + +def gcd(*args): + a = 0 + for b in args: + if a: + while b: + a, b = b, a % b + else: + a = b + return a + + +# Comment by Juan Arias de Reyna: +# +# I learn this method to compute EulerE[2n] from van de Lune. +# +# We apply the formula EulerE[2n] = (-1)^n 2**(-2n) sum_{j=0}^n a(2n,2j+1) +# +# where the numbers a(n,j) vanish for j > n+1 or j <= -1 and satisfies +# +# a(0,-1) = a(0,0) = 0; a(0,1)= 1; a(0,2) = a(0,3) = 0 +# +# a(n,j) = a(n-1,j) when n+j is even +# a(n,j) = (j-1) a(n-1,j-1) + (j+1) a(n-1,j+1) when n+j is odd +# +# +# But we can use only one array unidimensional a(j) since to compute +# a(n,j) we only need to know a(n-1,k) where k and j are of different parity +# and we have not to conserve the used values. +# +# We cached up the values of Euler numbers to sufficiently high order. +# +# Important Observation: If we pretend to use the numbers +# EulerE[1], EulerE[2], ... , EulerE[n] +# it is convenient to compute first EulerE[n], since the algorithm +# computes first all +# the previous ones, and keeps them in the CACHE + +MAX_EULER_CACHE = 500 + +def eulernum(m, _cache={0:MPZ_ONE}): + r""" + Computes the Euler numbers `E(n)`, which can be defined as + coefficients of the Taylor expansion of `1/cosh x`: + + .. math :: + + \frac{1}{\cosh x} = \sum_{n=0}^\infty \frac{E_n}{n!} x^n + + Example:: + + >>> [int(eulernum(n)) for n in range(11)] + [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0, -50521] + >>> [int(eulernum(n)) for n in range(11)] # test cache + [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0, -50521] + + """ + # for odd m > 1, the Euler numbers are zero + if m & 1: + return MPZ_ZERO + f = _cache.get(m) + if f: + return f + MAX = MAX_EULER_CACHE + n = m + a = [MPZ(_) for _ in [0,0,1,0,0,0]] + for n in range(1, m+1): + for j in range(n+1, -1, -2): + a[j+1] = (j-1)*a[j] + (j+1)*a[j+2] + a.append(0) + suma = 0 + for k in range(n+1, -1, -2): + suma += a[k+1] + if n <= MAX: + _cache[n] = ((-1)**(n//2))*(suma // 2**n) + if n == m: + return ((-1)**(n//2))*suma // 2**n + +def stirling1(n, k): + """ + Stirling number of the first kind. + """ + if n < 0 or k < 0: + raise ValueError + if k >= n: + return MPZ(n == k) + if k < 1: + return MPZ_ZERO + L = [MPZ_ZERO] * (k+1) + L[1] = MPZ_ONE + for m in xrange(2, n+1): + for j in xrange(min(k, m), 0, -1): + L[j] = (m-1) * L[j] + L[j-1] + return (-1)**(n+k) * L[k] + +def stirling2(n, k): + """ + Stirling number of the second kind. + """ + if n < 0 or k < 0: + raise ValueError + if k >= n: + return MPZ(n == k) + if k <= 1: + return MPZ(k == 1) + s = MPZ_ZERO + t = MPZ_ONE + for j in xrange(k+1): + if (k + j) & 1: + s -= t * MPZ(j)**n + else: + s += t * MPZ(j)**n + t = t * (k - j) // (j + 1) + return s // ifac(k) diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/libmpc.py b/venv/lib/python3.10/site-packages/mpmath/libmp/libmpc.py new file mode 100644 index 0000000000000000000000000000000000000000..cc22d0e73674676c8a9249ebc2d48da7f3be8b0d --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/libmp/libmpc.py @@ -0,0 +1,835 @@ +""" +Low-level functions for complex arithmetic. +""" + +import sys + +from .backend import MPZ, MPZ_ZERO, MPZ_ONE, MPZ_TWO, BACKEND + +from .libmpf import (\ + round_floor, round_ceiling, round_down, round_up, + round_nearest, round_fast, bitcount, + bctable, normalize, normalize1, reciprocal_rnd, rshift, lshift, giant_steps, + negative_rnd, + to_str, to_fixed, from_man_exp, from_float, to_float, from_int, to_int, + fzero, fone, ftwo, fhalf, finf, fninf, fnan, fnone, + mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, + mpf_div, mpf_mul_int, mpf_shift, mpf_sqrt, mpf_hypot, + mpf_rdiv_int, mpf_floor, mpf_ceil, mpf_nint, mpf_frac, + mpf_sign, mpf_hash, + ComplexResult +) + +from .libelefun import (\ + mpf_pi, mpf_exp, mpf_log, mpf_cos_sin, mpf_cosh_sinh, mpf_tan, mpf_pow_int, + mpf_log_hypot, + mpf_cos_sin_pi, mpf_phi, + mpf_cos, mpf_sin, mpf_cos_pi, mpf_sin_pi, + mpf_atan, mpf_atan2, mpf_cosh, mpf_sinh, mpf_tanh, + mpf_asin, mpf_acos, mpf_acosh, mpf_nthroot, mpf_fibonacci +) + +# An mpc value is a (real, imag) tuple +mpc_one = fone, fzero +mpc_zero = fzero, fzero +mpc_two = ftwo, fzero +mpc_half = (fhalf, fzero) + +_infs = (finf, fninf) +_infs_nan = (finf, fninf, fnan) + +def mpc_is_inf(z): + """Check if either real or imaginary part is infinite""" + re, im = z + if re in _infs: return True + if im in _infs: return True + return False + +def mpc_is_infnan(z): + """Check if either real or imaginary part is infinite or nan""" + re, im = z + if re in _infs_nan: return True + if im in _infs_nan: return True + return False + +def mpc_to_str(z, dps, **kwargs): + re, im = z + rs = to_str(re, dps) + if im[0]: + return rs + " - " + to_str(mpf_neg(im), dps, **kwargs) + "j" + else: + return rs + " + " + to_str(im, dps, **kwargs) + "j" + +def mpc_to_complex(z, strict=False, rnd=round_fast): + re, im = z + return complex(to_float(re, strict, rnd), to_float(im, strict, rnd)) + +def mpc_hash(z): + if sys.version_info >= (3, 2): + re, im = z + h = mpf_hash(re) + sys.hash_info.imag * mpf_hash(im) + # Need to reduce either module 2^32 or 2^64 + h = h % (2**sys.hash_info.width) + return int(h) + else: + try: + return hash(mpc_to_complex(z, strict=True)) + except OverflowError: + return hash(z) + +def mpc_conjugate(z, prec, rnd=round_fast): + re, im = z + return re, mpf_neg(im, prec, rnd) + +def mpc_is_nonzero(z): + return z != mpc_zero + +def mpc_add(z, w, prec, rnd=round_fast): + a, b = z + c, d = w + return mpf_add(a, c, prec, rnd), mpf_add(b, d, prec, rnd) + +def mpc_add_mpf(z, x, prec, rnd=round_fast): + a, b = z + return mpf_add(a, x, prec, rnd), b + +def mpc_sub(z, w, prec=0, rnd=round_fast): + a, b = z + c, d = w + return mpf_sub(a, c, prec, rnd), mpf_sub(b, d, prec, rnd) + +def mpc_sub_mpf(z, p, prec=0, rnd=round_fast): + a, b = z + return mpf_sub(a, p, prec, rnd), b + +def mpc_pos(z, prec, rnd=round_fast): + a, b = z + return mpf_pos(a, prec, rnd), mpf_pos(b, prec, rnd) + +def mpc_neg(z, prec=None, rnd=round_fast): + a, b = z + return mpf_neg(a, prec, rnd), mpf_neg(b, prec, rnd) + +def mpc_shift(z, n): + a, b = z + return mpf_shift(a, n), mpf_shift(b, n) + +def mpc_abs(z, prec, rnd=round_fast): + """Absolute value of a complex number, |a+bi|. + Returns an mpf value.""" + a, b = z + return mpf_hypot(a, b, prec, rnd) + +def mpc_arg(z, prec, rnd=round_fast): + """Argument of a complex number. Returns an mpf value.""" + a, b = z + return mpf_atan2(b, a, prec, rnd) + +def mpc_floor(z, prec, rnd=round_fast): + a, b = z + return mpf_floor(a, prec, rnd), mpf_floor(b, prec, rnd) + +def mpc_ceil(z, prec, rnd=round_fast): + a, b = z + return mpf_ceil(a, prec, rnd), mpf_ceil(b, prec, rnd) + +def mpc_nint(z, prec, rnd=round_fast): + a, b = z + return mpf_nint(a, prec, rnd), mpf_nint(b, prec, rnd) + +def mpc_frac(z, prec, rnd=round_fast): + a, b = z + return mpf_frac(a, prec, rnd), mpf_frac(b, prec, rnd) + + +def mpc_mul(z, w, prec, rnd=round_fast): + """ + Complex multiplication. + + Returns the real and imaginary part of (a+bi)*(c+di), rounded to + the specified precision. The rounding mode applies to the real and + imaginary parts separately. + """ + a, b = z + c, d = w + p = mpf_mul(a, c) + q = mpf_mul(b, d) + r = mpf_mul(a, d) + s = mpf_mul(b, c) + re = mpf_sub(p, q, prec, rnd) + im = mpf_add(r, s, prec, rnd) + return re, im + +def mpc_square(z, prec, rnd=round_fast): + # (a+b*I)**2 == a**2 - b**2 + 2*I*a*b + a, b = z + p = mpf_mul(a,a) + q = mpf_mul(b,b) + r = mpf_mul(a,b, prec, rnd) + re = mpf_sub(p, q, prec, rnd) + im = mpf_shift(r, 1) + return re, im + +def mpc_mul_mpf(z, p, prec, rnd=round_fast): + a, b = z + re = mpf_mul(a, p, prec, rnd) + im = mpf_mul(b, p, prec, rnd) + return re, im + +def mpc_mul_imag_mpf(z, x, prec, rnd=round_fast): + """ + Multiply the mpc value z by I*x where x is an mpf value. + """ + a, b = z + re = mpf_neg(mpf_mul(b, x, prec, rnd)) + im = mpf_mul(a, x, prec, rnd) + return re, im + +def mpc_mul_int(z, n, prec, rnd=round_fast): + a, b = z + re = mpf_mul_int(a, n, prec, rnd) + im = mpf_mul_int(b, n, prec, rnd) + return re, im + +def mpc_div(z, w, prec, rnd=round_fast): + a, b = z + c, d = w + wp = prec + 10 + # mag = c*c + d*d + mag = mpf_add(mpf_mul(c, c), mpf_mul(d, d), wp) + # (a*c+b*d)/mag, (b*c-a*d)/mag + t = mpf_add(mpf_mul(a,c), mpf_mul(b,d), wp) + u = mpf_sub(mpf_mul(b,c), mpf_mul(a,d), wp) + return mpf_div(t,mag,prec,rnd), mpf_div(u,mag,prec,rnd) + +def mpc_div_mpf(z, p, prec, rnd=round_fast): + """Calculate z/p where p is real""" + a, b = z + re = mpf_div(a, p, prec, rnd) + im = mpf_div(b, p, prec, rnd) + return re, im + +def mpc_reciprocal(z, prec, rnd=round_fast): + """Calculate 1/z efficiently""" + a, b = z + m = mpf_add(mpf_mul(a,a),mpf_mul(b,b),prec+10) + re = mpf_div(a, m, prec, rnd) + im = mpf_neg(mpf_div(b, m, prec, rnd)) + return re, im + +def mpc_mpf_div(p, z, prec, rnd=round_fast): + """Calculate p/z where p is real efficiently""" + a, b = z + m = mpf_add(mpf_mul(a,a),mpf_mul(b,b), prec+10) + re = mpf_div(mpf_mul(a,p), m, prec, rnd) + im = mpf_div(mpf_neg(mpf_mul(b,p)), m, prec, rnd) + return re, im + +def complex_int_pow(a, b, n): + """Complex integer power: computes (a+b*I)**n exactly for + nonnegative n (a and b must be Python ints).""" + wre = 1 + wim = 0 + while n: + if n & 1: + wre, wim = wre*a - wim*b, wim*a + wre*b + n -= 1 + a, b = a*a - b*b, 2*a*b + n //= 2 + return wre, wim + +def mpc_pow(z, w, prec, rnd=round_fast): + if w[1] == fzero: + return mpc_pow_mpf(z, w[0], prec, rnd) + return mpc_exp(mpc_mul(mpc_log(z, prec+10), w, prec+10), prec, rnd) + +def mpc_pow_mpf(z, p, prec, rnd=round_fast): + psign, pman, pexp, pbc = p + if pexp >= 0: + return mpc_pow_int(z, (-1)**psign * (pman< 0: + aman <<= de + aexp = bexp + else: + bman <<= (-de) + bexp = aexp + re, im = complex_int_pow(aman, bman, n) + re = from_man_exp(re, int(n*aexp), prec, rnd) + im = from_man_exp(im, int(n*bexp), prec, rnd) + return re, im + return mpc_exp(mpc_mul_int(mpc_log(z, prec+10), n, prec+10), prec, rnd) + +def mpc_sqrt(z, prec, rnd=round_fast): + """Complex square root (principal branch). + + We have sqrt(a+bi) = sqrt((r+a)/2) + b/sqrt(2*(r+a))*i where + r = abs(a+bi), when a+bi is not a negative real number.""" + a, b = z + if b == fzero: + if a == fzero: + return (a, b) + # When a+bi is a negative real number, we get a real sqrt times i + if a[0]: + im = mpf_sqrt(mpf_neg(a), prec, rnd) + return (fzero, im) + else: + re = mpf_sqrt(a, prec, rnd) + return (re, fzero) + wp = prec+20 + if not a[0]: # case a positive + t = mpf_add(mpc_abs((a, b), wp), a, wp) # t = abs(a+bi) + a + u = mpf_shift(t, -1) # u = t/2 + re = mpf_sqrt(u, prec, rnd) # re = sqrt(u) + v = mpf_shift(t, 1) # v = 2*t + w = mpf_sqrt(v, wp) # w = sqrt(v) + im = mpf_div(b, w, prec, rnd) # im = b / w + else: # case a negative + t = mpf_sub(mpc_abs((a, b), wp), a, wp) # t = abs(a+bi) - a + u = mpf_shift(t, -1) # u = t/2 + im = mpf_sqrt(u, prec, rnd) # im = sqrt(u) + v = mpf_shift(t, 1) # v = 2*t + w = mpf_sqrt(v, wp) # w = sqrt(v) + re = mpf_div(b, w, prec, rnd) # re = b/w + if b[0]: + re = mpf_neg(re) + im = mpf_neg(im) + return re, im + +def mpc_nthroot_fixed(a, b, n, prec): + # a, b signed integers at fixed precision prec + start = 50 + a1 = int(rshift(a, prec - n*start)) + b1 = int(rshift(b, prec - n*start)) + try: + r = (a1 + 1j * b1)**(1.0/n) + re = r.real + im = r.imag + re = MPZ(int(re)) + im = MPZ(int(im)) + except OverflowError: + a1 = from_int(a1, start) + b1 = from_int(b1, start) + fn = from_int(n) + nth = mpf_rdiv_int(1, fn, start) + re, im = mpc_pow((a1, b1), (nth, fzero), start) + re = to_int(re) + im = to_int(im) + extra = 10 + prevp = start + extra1 = n + for p in giant_steps(start, prec+extra): + # this is slow for large n, unlike int_pow_fixed + re2, im2 = complex_int_pow(re, im, n-1) + re2 = rshift(re2, (n-1)*prevp - p - extra1) + im2 = rshift(im2, (n-1)*prevp - p - extra1) + r4 = (re2*re2 + im2*im2) >> (p + extra1) + ap = rshift(a, prec - p) + bp = rshift(b, prec - p) + rec = (ap * re2 + bp * im2) >> p + imc = (-ap * im2 + bp * re2) >> p + reb = (rec << p) // r4 + imb = (imc << p) // r4 + re = (reb + (n-1)*lshift(re, p-prevp))//n + im = (imb + (n-1)*lshift(im, p-prevp))//n + prevp = p + return re, im + +def mpc_nthroot(z, n, prec, rnd=round_fast): + """ + Complex n-th root. + + Use Newton method as in the real case when it is faster, + otherwise use z**(1/n) + """ + a, b = z + if a[0] == 0 and b == fzero: + re = mpf_nthroot(a, n, prec, rnd) + return (re, fzero) + if n < 2: + if n == 0: + return mpc_one + if n == 1: + return mpc_pos((a, b), prec, rnd) + if n == -1: + return mpc_div(mpc_one, (a, b), prec, rnd) + inverse = mpc_nthroot((a, b), -n, prec+5, reciprocal_rnd[rnd]) + return mpc_div(mpc_one, inverse, prec, rnd) + if n <= 20: + prec2 = int(1.2 * (prec + 10)) + asign, aman, aexp, abc = a + bsign, bman, bexp, bbc = b + pf = mpc_abs((a,b), prec) + if pf[-2] + pf[-1] > -10 and pf[-2] + pf[-1] < prec: + af = to_fixed(a, prec2) + bf = to_fixed(b, prec2) + re, im = mpc_nthroot_fixed(af, bf, n, prec2) + extra = 10 + re = from_man_exp(re, -prec2-extra, prec2, rnd) + im = from_man_exp(im, -prec2-extra, prec2, rnd) + return re, im + fn = from_int(n) + prec2 = prec+10 + 10 + nth = mpf_rdiv_int(1, fn, prec2) + re, im = mpc_pow((a, b), (nth, fzero), prec2, rnd) + re = normalize(re[0], re[1], re[2], re[3], prec, rnd) + im = normalize(im[0], im[1], im[2], im[3], prec, rnd) + return re, im + +def mpc_cbrt(z, prec, rnd=round_fast): + """ + Complex cubic root. + """ + return mpc_nthroot(z, 3, prec, rnd) + +def mpc_exp(z, prec, rnd=round_fast): + """ + Complex exponential function. + + We use the direct formula exp(a+bi) = exp(a) * (cos(b) + sin(b)*i) + for the computation. This formula is very nice because it is + pefectly stable; since we just do real multiplications, the only + numerical errors that can creep in are single-ulp rounding errors. + + The formula is efficient since mpmath's real exp is quite fast and + since we can compute cos and sin simultaneously. + + It is no problem if a and b are large; if the implementations of + exp/cos/sin are accurate and efficient for all real numbers, then + so is this function for all complex numbers. + """ + a, b = z + if a == fzero: + return mpf_cos_sin(b, prec, rnd) + if b == fzero: + return mpf_exp(a, prec, rnd), fzero + mag = mpf_exp(a, prec+4, rnd) + c, s = mpf_cos_sin(b, prec+4, rnd) + re = mpf_mul(mag, c, prec, rnd) + im = mpf_mul(mag, s, prec, rnd) + return re, im + +def mpc_log(z, prec, rnd=round_fast): + re = mpf_log_hypot(z[0], z[1], prec, rnd) + im = mpc_arg(z, prec, rnd) + return re, im + +def mpc_cos(z, prec, rnd=round_fast): + """Complex cosine. The formula used is cos(a+bi) = cos(a)*cosh(b) - + sin(a)*sinh(b)*i. + + The same comments apply as for the complex exp: only real + multiplications are pewrormed, so no cancellation errors are + possible. The formula is also efficient since we can compute both + pairs (cos, sin) and (cosh, sinh) in single stwps.""" + a, b = z + if b == fzero: + return mpf_cos(a, prec, rnd), fzero + if a == fzero: + return mpf_cosh(b, prec, rnd), fzero + wp = prec + 6 + c, s = mpf_cos_sin(a, wp) + ch, sh = mpf_cosh_sinh(b, wp) + re = mpf_mul(c, ch, prec, rnd) + im = mpf_mul(s, sh, prec, rnd) + return re, mpf_neg(im) + +def mpc_sin(z, prec, rnd=round_fast): + """Complex sine. We have sin(a+bi) = sin(a)*cosh(b) + + cos(a)*sinh(b)*i. See the docstring for mpc_cos for additional + comments.""" + a, b = z + if b == fzero: + return mpf_sin(a, prec, rnd), fzero + if a == fzero: + return fzero, mpf_sinh(b, prec, rnd) + wp = prec + 6 + c, s = mpf_cos_sin(a, wp) + ch, sh = mpf_cosh_sinh(b, wp) + re = mpf_mul(s, ch, prec, rnd) + im = mpf_mul(c, sh, prec, rnd) + return re, im + +def mpc_tan(z, prec, rnd=round_fast): + """Complex tangent. Computed as tan(a+bi) = sin(2a)/M + sinh(2b)/M*i + where M = cos(2a) + cosh(2b).""" + a, b = z + asign, aman, aexp, abc = a + bsign, bman, bexp, bbc = b + if b == fzero: return mpf_tan(a, prec, rnd), fzero + if a == fzero: return fzero, mpf_tanh(b, prec, rnd) + wp = prec + 15 + a = mpf_shift(a, 1) + b = mpf_shift(b, 1) + c, s = mpf_cos_sin(a, wp) + ch, sh = mpf_cosh_sinh(b, wp) + # TODO: handle cancellation when c ~= -1 and ch ~= 1 + mag = mpf_add(c, ch, wp) + re = mpf_div(s, mag, prec, rnd) + im = mpf_div(sh, mag, prec, rnd) + return re, im + +def mpc_cos_pi(z, prec, rnd=round_fast): + a, b = z + if b == fzero: + return mpf_cos_pi(a, prec, rnd), fzero + b = mpf_mul(b, mpf_pi(prec+5), prec+5) + if a == fzero: + return mpf_cosh(b, prec, rnd), fzero + wp = prec + 6 + c, s = mpf_cos_sin_pi(a, wp) + ch, sh = mpf_cosh_sinh(b, wp) + re = mpf_mul(c, ch, prec, rnd) + im = mpf_mul(s, sh, prec, rnd) + return re, mpf_neg(im) + +def mpc_sin_pi(z, prec, rnd=round_fast): + a, b = z + if b == fzero: + return mpf_sin_pi(a, prec, rnd), fzero + b = mpf_mul(b, mpf_pi(prec+5), prec+5) + if a == fzero: + return fzero, mpf_sinh(b, prec, rnd) + wp = prec + 6 + c, s = mpf_cos_sin_pi(a, wp) + ch, sh = mpf_cosh_sinh(b, wp) + re = mpf_mul(s, ch, prec, rnd) + im = mpf_mul(c, sh, prec, rnd) + return re, im + +def mpc_cos_sin(z, prec, rnd=round_fast): + a, b = z + if a == fzero: + ch, sh = mpf_cosh_sinh(b, prec, rnd) + return (ch, fzero), (fzero, sh) + if b == fzero: + c, s = mpf_cos_sin(a, prec, rnd) + return (c, fzero), (s, fzero) + wp = prec + 6 + c, s = mpf_cos_sin(a, wp) + ch, sh = mpf_cosh_sinh(b, wp) + cre = mpf_mul(c, ch, prec, rnd) + cim = mpf_mul(s, sh, prec, rnd) + sre = mpf_mul(s, ch, prec, rnd) + sim = mpf_mul(c, sh, prec, rnd) + return (cre, mpf_neg(cim)), (sre, sim) + +def mpc_cos_sin_pi(z, prec, rnd=round_fast): + a, b = z + if b == fzero: + c, s = mpf_cos_sin_pi(a, prec, rnd) + return (c, fzero), (s, fzero) + b = mpf_mul(b, mpf_pi(prec+5), prec+5) + if a == fzero: + ch, sh = mpf_cosh_sinh(b, prec, rnd) + return (ch, fzero), (fzero, sh) + wp = prec + 6 + c, s = mpf_cos_sin_pi(a, wp) + ch, sh = mpf_cosh_sinh(b, wp) + cre = mpf_mul(c, ch, prec, rnd) + cim = mpf_mul(s, sh, prec, rnd) + sre = mpf_mul(s, ch, prec, rnd) + sim = mpf_mul(c, sh, prec, rnd) + return (cre, mpf_neg(cim)), (sre, sim) + +def mpc_cosh(z, prec, rnd=round_fast): + """Complex hyperbolic cosine. Computed as cosh(z) = cos(z*i).""" + a, b = z + return mpc_cos((b, mpf_neg(a)), prec, rnd) + +def mpc_sinh(z, prec, rnd=round_fast): + """Complex hyperbolic sine. Computed as sinh(z) = -i*sin(z*i).""" + a, b = z + b, a = mpc_sin((b, a), prec, rnd) + return a, b + +def mpc_tanh(z, prec, rnd=round_fast): + """Complex hyperbolic tangent. Computed as tanh(z) = -i*tan(z*i).""" + a, b = z + b, a = mpc_tan((b, a), prec, rnd) + return a, b + +# TODO: avoid loss of accuracy +def mpc_atan(z, prec, rnd=round_fast): + a, b = z + # atan(z) = (I/2)*(log(1-I*z) - log(1+I*z)) + # x = 1-I*z = 1 + b - I*a + # y = 1+I*z = 1 - b + I*a + wp = prec + 15 + x = mpf_add(fone, b, wp), mpf_neg(a) + y = mpf_sub(fone, b, wp), a + l1 = mpc_log(x, wp) + l2 = mpc_log(y, wp) + a, b = mpc_sub(l1, l2, prec, rnd) + # (I/2) * (a+b*I) = (-b/2 + a/2*I) + v = mpf_neg(mpf_shift(b,-1)), mpf_shift(a,-1) + # Subtraction at infinity gives correct real part but + # wrong imaginary part (should be zero) + if v[1] == fnan and mpc_is_inf(z): + v = (v[0], fzero) + return v + +beta_crossover = from_float(0.6417) +alpha_crossover = from_float(1.5) + +def acos_asin(z, prec, rnd, n): + """ complex acos for n = 0, asin for n = 1 + The algorithm is described in + T.E. Hull, T.F. Fairgrieve and P.T.P. Tang + 'Implementing the Complex Arcsine and Arcosine Functions + using Exception Handling', + ACM Trans. on Math. Software Vol. 23 (1997), p299 + The complex acos and asin can be defined as + acos(z) = acos(beta) - I*sign(a)* log(alpha + sqrt(alpha**2 -1)) + asin(z) = asin(beta) + I*sign(a)* log(alpha + sqrt(alpha**2 -1)) + where z = a + I*b + alpha = (1/2)*(r + s); beta = (1/2)*(r - s) = a/alpha + r = sqrt((a+1)**2 + y**2); s = sqrt((a-1)**2 + y**2) + These expressions are rewritten in different ways in different + regions, delimited by two crossovers alpha_crossover and beta_crossover, + and by abs(a) <= 1, in order to improve the numerical accuracy. + """ + a, b = z + wp = prec + 10 + # special cases with real argument + if b == fzero: + am = mpf_sub(fone, mpf_abs(a), wp) + # case abs(a) <= 1 + if not am[0]: + if n == 0: + return mpf_acos(a, prec, rnd), fzero + else: + return mpf_asin(a, prec, rnd), fzero + # cases abs(a) > 1 + else: + # case a < -1 + if a[0]: + pi = mpf_pi(prec, rnd) + c = mpf_acosh(mpf_neg(a), prec, rnd) + if n == 0: + return pi, mpf_neg(c) + else: + return mpf_neg(mpf_shift(pi, -1)), c + # case a > 1 + else: + c = mpf_acosh(a, prec, rnd) + if n == 0: + return fzero, c + else: + pi = mpf_pi(prec, rnd) + return mpf_shift(pi, -1), mpf_neg(c) + asign = bsign = 0 + if a[0]: + a = mpf_neg(a) + asign = 1 + if b[0]: + b = mpf_neg(b) + bsign = 1 + am = mpf_sub(fone, a, wp) + ap = mpf_add(fone, a, wp) + r = mpf_hypot(ap, b, wp) + s = mpf_hypot(am, b, wp) + alpha = mpf_shift(mpf_add(r, s, wp), -1) + beta = mpf_div(a, alpha, wp) + b2 = mpf_mul(b,b, wp) + # case beta <= beta_crossover + if not mpf_sub(beta_crossover, beta, wp)[0]: + if n == 0: + re = mpf_acos(beta, wp) + else: + re = mpf_asin(beta, wp) + else: + # to compute the real part in this region use the identity + # asin(beta) = atan(beta/sqrt(1-beta**2)) + # beta/sqrt(1-beta**2) = (alpha + a) * (alpha - a) + # alpha + a is numerically accurate; alpha - a can have + # cancellations leading to numerical inaccuracies, so rewrite + # it in differente ways according to the region + Ax = mpf_add(alpha, a, wp) + # case a <= 1 + if not am[0]: + # c = b*b/(r + (a+1)); d = (s + (1-a)) + # alpha - a = (1/2)*(c + d) + # case n=0: re = atan(sqrt((1/2) * Ax * (c + d))/a) + # case n=1: re = atan(a/sqrt((1/2) * Ax * (c + d))) + c = mpf_div(b2, mpf_add(r, ap, wp), wp) + d = mpf_add(s, am, wp) + re = mpf_shift(mpf_mul(Ax, mpf_add(c, d, wp), wp), -1) + if n == 0: + re = mpf_atan(mpf_div(mpf_sqrt(re, wp), a, wp), wp) + else: + re = mpf_atan(mpf_div(a, mpf_sqrt(re, wp), wp), wp) + else: + # c = Ax/(r + (a+1)); d = Ax/(s - (1-a)) + # alpha - a = (1/2)*(c + d) + # case n = 0: re = atan(b*sqrt(c + d)/2/a) + # case n = 1: re = atan(a/(b*sqrt(c + d)/2) + c = mpf_div(Ax, mpf_add(r, ap, wp), wp) + d = mpf_div(Ax, mpf_sub(s, am, wp), wp) + re = mpf_shift(mpf_add(c, d, wp), -1) + re = mpf_mul(b, mpf_sqrt(re, wp), wp) + if n == 0: + re = mpf_atan(mpf_div(re, a, wp), wp) + else: + re = mpf_atan(mpf_div(a, re, wp), wp) + # to compute alpha + sqrt(alpha**2 - 1), if alpha <= alpha_crossover + # replace it with 1 + Am1 + sqrt(Am1*(alpha+1))) + # where Am1 = alpha -1 + # if alpha <= alpha_crossover: + if not mpf_sub(alpha_crossover, alpha, wp)[0]: + c1 = mpf_div(b2, mpf_add(r, ap, wp), wp) + # case a < 1 + if mpf_neg(am)[0]: + # Am1 = (1/2) * (b*b/(r + (a+1)) + b*b/(s + (1-a)) + c2 = mpf_add(s, am, wp) + c2 = mpf_div(b2, c2, wp) + Am1 = mpf_shift(mpf_add(c1, c2, wp), -1) + else: + # Am1 = (1/2) * (b*b/(r + (a+1)) + (s - (1-a))) + c2 = mpf_sub(s, am, wp) + Am1 = mpf_shift(mpf_add(c1, c2, wp), -1) + # im = log(1 + Am1 + sqrt(Am1*(alpha+1))) + im = mpf_mul(Am1, mpf_add(alpha, fone, wp), wp) + im = mpf_log(mpf_add(fone, mpf_add(Am1, mpf_sqrt(im, wp), wp), wp), wp) + else: + # im = log(alpha + sqrt(alpha*alpha - 1)) + im = mpf_sqrt(mpf_sub(mpf_mul(alpha, alpha, wp), fone, wp), wp) + im = mpf_log(mpf_add(alpha, im, wp), wp) + if asign: + if n == 0: + re = mpf_sub(mpf_pi(wp), re, wp) + else: + re = mpf_neg(re) + if not bsign and n == 0: + im = mpf_neg(im) + if bsign and n == 1: + im = mpf_neg(im) + re = normalize(re[0], re[1], re[2], re[3], prec, rnd) + im = normalize(im[0], im[1], im[2], im[3], prec, rnd) + return re, im + +def mpc_acos(z, prec, rnd=round_fast): + return acos_asin(z, prec, rnd, 0) + +def mpc_asin(z, prec, rnd=round_fast): + return acos_asin(z, prec, rnd, 1) + +def mpc_asinh(z, prec, rnd=round_fast): + # asinh(z) = I * asin(-I z) + a, b = z + a, b = mpc_asin((b, mpf_neg(a)), prec, rnd) + return mpf_neg(b), a + +def mpc_acosh(z, prec, rnd=round_fast): + # acosh(z) = -I * acos(z) for Im(acos(z)) <= 0 + # +I * acos(z) otherwise + a, b = mpc_acos(z, prec, rnd) + if b[0] or b == fzero: + return mpf_neg(b), a + else: + return b, mpf_neg(a) + +def mpc_atanh(z, prec, rnd=round_fast): + # atanh(z) = (log(1+z)-log(1-z))/2 + wp = prec + 15 + a = mpc_add(z, mpc_one, wp) + b = mpc_sub(mpc_one, z, wp) + a = mpc_log(a, wp) + b = mpc_log(b, wp) + v = mpc_shift(mpc_sub(a, b, wp), -1) + # Subtraction at infinity gives correct imaginary part but + # wrong real part (should be zero) + if v[0] == fnan and mpc_is_inf(z): + v = (fzero, v[1]) + return v + +def mpc_fibonacci(z, prec, rnd=round_fast): + re, im = z + if im == fzero: + return (mpf_fibonacci(re, prec, rnd), fzero) + size = max(abs(re[2]+re[3]), abs(re[2]+re[3])) + wp = prec + size + 20 + a = mpf_phi(wp) + b = mpf_add(mpf_shift(a, 1), fnone, wp) + u = mpc_pow((a, fzero), z, wp) + v = mpc_cos_pi(z, wp) + v = mpc_div(v, u, wp) + u = mpc_sub(u, v, wp) + u = mpc_div_mpf(u, b, prec, rnd) + return u + +def mpf_expj(x, prec, rnd='f'): + raise ComplexResult + +def mpc_expj(z, prec, rnd='f'): + re, im = z + if im == fzero: + return mpf_cos_sin(re, prec, rnd) + if re == fzero: + return mpf_exp(mpf_neg(im), prec, rnd), fzero + ey = mpf_exp(mpf_neg(im), prec+10) + c, s = mpf_cos_sin(re, prec+10) + re = mpf_mul(ey, c, prec, rnd) + im = mpf_mul(ey, s, prec, rnd) + return re, im + +def mpf_expjpi(x, prec, rnd='f'): + raise ComplexResult + +def mpc_expjpi(z, prec, rnd='f'): + re, im = z + if im == fzero: + return mpf_cos_sin_pi(re, prec, rnd) + sign, man, exp, bc = im + wp = prec+10 + if man: + wp += max(0, exp+bc) + im = mpf_neg(mpf_mul(mpf_pi(wp), im, wp)) + if re == fzero: + return mpf_exp(im, prec, rnd), fzero + ey = mpf_exp(im, prec+10) + c, s = mpf_cos_sin_pi(re, prec+10) + re = mpf_mul(ey, c, prec, rnd) + im = mpf_mul(ey, s, prec, rnd) + return re, im + + +if BACKEND == 'sage': + try: + import sage.libs.mpmath.ext_libmp as _lbmp + mpc_exp = _lbmp.mpc_exp + mpc_sqrt = _lbmp.mpc_sqrt + except (ImportError, AttributeError): + print("Warning: Sage imports in libmpc failed") diff --git a/venv/lib/python3.10/site-packages/mpmath/libmp/libmpf.py b/venv/lib/python3.10/site-packages/mpmath/libmp/libmpf.py new file mode 100644 index 0000000000000000000000000000000000000000..5c162e17d4f688c71dc3476b944e2d31c65faab7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/libmp/libmpf.py @@ -0,0 +1,1414 @@ +""" +Low-level functions for arbitrary-precision floating-point arithmetic. +""" + +__docformat__ = 'plaintext' + +import math + +from bisect import bisect + +import sys + +# Importing random is slow +#from random import getrandbits +getrandbits = None + +from .backend import (MPZ, MPZ_TYPE, MPZ_ZERO, MPZ_ONE, MPZ_TWO, MPZ_FIVE, + BACKEND, STRICT, HASH_MODULUS, HASH_BITS, gmpy, sage, sage_utils) + +from .libintmath import (giant_steps, + trailtable, bctable, lshift, rshift, bitcount, trailing, + sqrt_fixed, numeral, isqrt, isqrt_fast, sqrtrem, + bin_to_radix) + +# We don't pickle tuples directly for the following reasons: +# 1: pickle uses str() for ints, which is inefficient when they are large +# 2: pickle doesn't work for gmpy mpzs +# Both problems are solved by using hex() + +if BACKEND == 'sage': + def to_pickable(x): + sign, man, exp, bc = x + return sign, hex(man), exp, bc +else: + def to_pickable(x): + sign, man, exp, bc = x + return sign, hex(man)[2:], exp, bc + +def from_pickable(x): + sign, man, exp, bc = x + return (sign, MPZ(man, 16), exp, bc) + +class ComplexResult(ValueError): + pass + +try: + intern +except NameError: + intern = lambda x: x + +# All supported rounding modes +round_nearest = intern('n') +round_floor = intern('f') +round_ceiling = intern('c') +round_up = intern('u') +round_down = intern('d') +round_fast = round_down + +def prec_to_dps(n): + """Return number of accurate decimals that can be represented + with a precision of n bits.""" + return max(1, int(round(int(n)/3.3219280948873626)-1)) + +def dps_to_prec(n): + """Return the number of bits required to represent n decimals + accurately.""" + return max(1, int(round((int(n)+1)*3.3219280948873626))) + +def repr_dps(n): + """Return the number of decimal digits required to represent + a number with n-bit precision so that it can be uniquely + reconstructed from the representation.""" + dps = prec_to_dps(n) + if dps == 15: + return 17 + return dps + 3 + +#----------------------------------------------------------------------------# +# Some commonly needed float values # +#----------------------------------------------------------------------------# + +# Regular number format: +# (-1)**sign * mantissa * 2**exponent, plus bitcount of mantissa +fzero = (0, MPZ_ZERO, 0, 0) +fnzero = (1, MPZ_ZERO, 0, 0) +fone = (0, MPZ_ONE, 0, 1) +fnone = (1, MPZ_ONE, 0, 1) +ftwo = (0, MPZ_ONE, 1, 1) +ften = (0, MPZ_FIVE, 1, 3) +fhalf = (0, MPZ_ONE, -1, 1) + +# Arbitrary encoding for special numbers: zero mantissa, nonzero exponent +fnan = (0, MPZ_ZERO, -123, -1) +finf = (0, MPZ_ZERO, -456, -2) +fninf = (1, MPZ_ZERO, -789, -3) + +# Was 1e1000; this is broken in Python 2.4 +math_float_inf = 1e300 * 1e300 + + +#----------------------------------------------------------------------------# +# Rounding # +#----------------------------------------------------------------------------# + +# This function can be used to round a mantissa generally. However, +# we will try to do most rounding inline for efficiency. +def round_int(x, n, rnd): + if rnd == round_nearest: + if x >= 0: + t = x >> (n-1) + if t & 1 and ((t & 2) or (x & h_mask[n<300][n])): + return (t>>1)+1 + else: + return t>>1 + else: + return -round_int(-x, n, rnd) + if rnd == round_floor: + return x >> n + if rnd == round_ceiling: + return -((-x) >> n) + if rnd == round_down: + if x >= 0: + return x >> n + return -((-x) >> n) + if rnd == round_up: + if x >= 0: + return -((-x) >> n) + return x >> n + +# These masks are used to pick out segments of numbers to determine +# which direction to round when rounding to nearest. +class h_mask_big: + def __getitem__(self, n): + return (MPZ_ONE<<(n-1))-1 + +h_mask_small = [0]+[((MPZ_ONE<<(_-1))-1) for _ in range(1, 300)] +h_mask = [h_mask_big(), h_mask_small] + +# The >> operator rounds to floor. shifts_down[rnd][sign] +# tells whether this is the right direction to use, or if the +# number should be negated before shifting +shifts_down = {round_floor:(1,0), round_ceiling:(0,1), + round_down:(1,1), round_up:(0,0)} + + +#----------------------------------------------------------------------------# +# Normalization of raw mpfs # +#----------------------------------------------------------------------------# + +# This function is called almost every time an mpf is created. +# It has been optimized accordingly. + +def _normalize(sign, man, exp, bc, prec, rnd): + """ + Create a raw mpf tuple with value (-1)**sign * man * 2**exp and + normalized mantissa. The mantissa is rounded in the specified + direction if its size exceeds the precision. Trailing zero bits + are also stripped from the mantissa to ensure that the + representation is canonical. + + Conditions on the input: + * The input must represent a regular (finite) number + * The sign bit must be 0 or 1 + * The mantissa must be positive + * The exponent must be an integer + * The bitcount must be exact + + If these conditions are not met, use from_man_exp, mpf_pos, or any + of the conversion functions to create normalized raw mpf tuples. + """ + if not man: + return fzero + # Cut mantissa down to size if larger than target precision + n = bc - prec + if n > 0: + if rnd == round_nearest: + t = man >> (n-1) + if t & 1 and ((t & 2) or (man & h_mask[n<300][n])): + man = (t>>1)+1 + else: + man = t>>1 + elif shifts_down[rnd][sign]: + man >>= n + else: + man = -((-man)>>n) + exp += n + bc = prec + # Strip trailing bits + if not man & 1: + t = trailtable[int(man & 255)] + if not t: + while not man & 255: + man >>= 8 + exp += 8 + bc -= 8 + t = trailtable[int(man & 255)] + man >>= t + exp += t + bc -= t + # Bit count can be wrong if the input mantissa was 1 less than + # a power of 2 and got rounded up, thereby adding an extra bit. + # With trailing bits removed, all powers of two have mantissa 1, + # so this is easy to check for. + if man == 1: + bc = 1 + return sign, man, exp, bc + +def _normalize1(sign, man, exp, bc, prec, rnd): + """same as normalize, but with the added condition that + man is odd or zero + """ + if not man: + return fzero + if bc <= prec: + return sign, man, exp, bc + n = bc - prec + if rnd == round_nearest: + t = man >> (n-1) + if t & 1 and ((t & 2) or (man & h_mask[n<300][n])): + man = (t>>1)+1 + else: + man = t>>1 + elif shifts_down[rnd][sign]: + man >>= n + else: + man = -((-man)>>n) + exp += n + bc = prec + # Strip trailing bits + if not man & 1: + t = trailtable[int(man & 255)] + if not t: + while not man & 255: + man >>= 8 + exp += 8 + bc -= 8 + t = trailtable[int(man & 255)] + man >>= t + exp += t + bc -= t + # Bit count can be wrong if the input mantissa was 1 less than + # a power of 2 and got rounded up, thereby adding an extra bit. + # With trailing bits removed, all powers of two have mantissa 1, + # so this is easy to check for. + if man == 1: + bc = 1 + return sign, man, exp, bc + +try: + _exp_types = (int, long) +except NameError: + _exp_types = (int,) + +def strict_normalize(sign, man, exp, bc, prec, rnd): + """Additional checks on the components of an mpf. Enable tests by setting + the environment variable MPMATH_STRICT to Y.""" + assert type(man) == MPZ_TYPE + assert type(bc) in _exp_types + assert type(exp) in _exp_types + assert bc == bitcount(man) + return _normalize(sign, man, exp, bc, prec, rnd) + +def strict_normalize1(sign, man, exp, bc, prec, rnd): + """Additional checks on the components of an mpf. Enable tests by setting + the environment variable MPMATH_STRICT to Y.""" + assert type(man) == MPZ_TYPE + assert type(bc) in _exp_types + assert type(exp) in _exp_types + assert bc == bitcount(man) + assert (not man) or (man & 1) + return _normalize1(sign, man, exp, bc, prec, rnd) + +if BACKEND == 'gmpy' and '_mpmath_normalize' in dir(gmpy): + _normalize = gmpy._mpmath_normalize + _normalize1 = gmpy._mpmath_normalize + +if BACKEND == 'sage': + _normalize = _normalize1 = sage_utils.normalize + +if STRICT: + normalize = strict_normalize + normalize1 = strict_normalize1 +else: + normalize = _normalize + normalize1 = _normalize1 + +#----------------------------------------------------------------------------# +# Conversion functions # +#----------------------------------------------------------------------------# + +def from_man_exp(man, exp, prec=None, rnd=round_fast): + """Create raw mpf from (man, exp) pair. The mantissa may be signed. + If no precision is specified, the mantissa is stored exactly.""" + man = MPZ(man) + sign = 0 + if man < 0: + sign = 1 + man = -man + if man < 1024: + bc = bctable[int(man)] + else: + bc = bitcount(man) + if not prec: + if not man: + return fzero + if not man & 1: + if man & 2: + return (sign, man >> 1, exp + 1, bc - 1) + t = trailtable[int(man & 255)] + if not t: + while not man & 255: + man >>= 8 + exp += 8 + bc -= 8 + t = trailtable[int(man & 255)] + man >>= t + exp += t + bc -= t + return (sign, man, exp, bc) + return normalize(sign, man, exp, bc, prec, rnd) + +int_cache = dict((n, from_man_exp(n, 0)) for n in range(-10, 257)) + +if BACKEND == 'gmpy' and '_mpmath_create' in dir(gmpy): + from_man_exp = gmpy._mpmath_create + +if BACKEND == 'sage': + from_man_exp = sage_utils.from_man_exp + +def from_int(n, prec=0, rnd=round_fast): + """Create a raw mpf from an integer. If no precision is specified, + the mantissa is stored exactly.""" + if not prec: + if n in int_cache: + return int_cache[n] + return from_man_exp(n, 0, prec, rnd) + +def to_man_exp(s): + """Return (man, exp) of a raw mpf. Raise an error if inf/nan.""" + sign, man, exp, bc = s + if (not man) and exp: + raise ValueError("mantissa and exponent are undefined for %s" % man) + return man, exp + +def to_int(s, rnd=None): + """Convert a raw mpf to the nearest int. Rounding is done down by + default (same as int(float) in Python), but can be changed. If the + input is inf/nan, an exception is raised.""" + sign, man, exp, bc = s + if (not man) and exp: + raise ValueError("cannot convert inf or nan to int") + if exp >= 0: + if sign: + return (-man) << exp + return man << exp + # Make default rounding fast + if not rnd: + if sign: + return -(man >> (-exp)) + else: + return man >> (-exp) + if sign: + return round_int(-man, -exp, rnd) + else: + return round_int(man, -exp, rnd) + +def mpf_round_int(s, rnd): + sign, man, exp, bc = s + if (not man) and exp: + return s + if exp >= 0: + return s + mag = exp+bc + if mag < 1: + if rnd == round_ceiling: + if sign: return fzero + else: return fone + elif rnd == round_floor: + if sign: return fnone + else: return fzero + elif rnd == round_nearest: + if mag < 0 or man == MPZ_ONE: return fzero + elif sign: return fnone + else: return fone + else: + raise NotImplementedError + return mpf_pos(s, min(bc, mag), rnd) + +def mpf_floor(s, prec=0, rnd=round_fast): + v = mpf_round_int(s, round_floor) + if prec: + v = mpf_pos(v, prec, rnd) + return v + +def mpf_ceil(s, prec=0, rnd=round_fast): + v = mpf_round_int(s, round_ceiling) + if prec: + v = mpf_pos(v, prec, rnd) + return v + +def mpf_nint(s, prec=0, rnd=round_fast): + v = mpf_round_int(s, round_nearest) + if prec: + v = mpf_pos(v, prec, rnd) + return v + +def mpf_frac(s, prec=0, rnd=round_fast): + return mpf_sub(s, mpf_floor(s), prec, rnd) + +def from_float(x, prec=53, rnd=round_fast): + """Create a raw mpf from a Python float, rounding if necessary. + If prec >= 53, the result is guaranteed to represent exactly the + same number as the input. If prec is not specified, use prec=53.""" + # frexp only raises an exception for nan on some platforms + if x != x: + return fnan + # in Python2.5 math.frexp gives an exception for float infinity + # in Python2.6 it returns (float infinity, 0) + try: + m, e = math.frexp(x) + except: + if x == math_float_inf: return finf + if x == -math_float_inf: return fninf + return fnan + if x == math_float_inf: return finf + if x == -math_float_inf: return fninf + return from_man_exp(int(m*(1<<53)), e-53, prec, rnd) + +def from_npfloat(x, prec=113, rnd=round_fast): + """Create a raw mpf from a numpy float, rounding if necessary. + If prec >= 113, the result is guaranteed to represent exactly the + same number as the input. If prec is not specified, use prec=113.""" + y = float(x) + if x == y: # ldexp overflows for float16 + return from_float(y, prec, rnd) + import numpy as np + if np.isfinite(x): + m, e = np.frexp(x) + return from_man_exp(int(np.ldexp(m, 113)), int(e-113), prec, rnd) + if np.isposinf(x): return finf + if np.isneginf(x): return fninf + return fnan + +def from_Decimal(x, prec=None, rnd=round_fast): + """Create a raw mpf from a Decimal, rounding if necessary. + If prec is not specified, use the equivalent bit precision + of the number of significant digits in x.""" + if x.is_nan(): return fnan + if x.is_infinite(): return fninf if x.is_signed() else finf + if prec is None: + prec = int(len(x.as_tuple()[1])*3.3219280948873626) + return from_str(str(x), prec, rnd) + +def to_float(s, strict=False, rnd=round_fast): + """ + Convert a raw mpf to a Python float. The result is exact if the + bitcount of s is <= 53 and no underflow/overflow occurs. + + If the number is too large or too small to represent as a regular + float, it will be converted to inf or 0.0. Setting strict=True + forces an OverflowError to be raised instead. + + Warning: with a directed rounding mode, the correct nearest representable + floating-point number in the specified direction might not be computed + in case of overflow or (gradual) underflow. + """ + sign, man, exp, bc = s + if not man: + if s == fzero: return 0.0 + if s == finf: return math_float_inf + if s == fninf: return -math_float_inf + return math_float_inf/math_float_inf + if bc > 53: + sign, man, exp, bc = normalize1(sign, man, exp, bc, 53, rnd) + if sign: + man = -man + try: + return math.ldexp(man, exp) + except OverflowError: + if strict: + raise + # Overflow to infinity + if exp + bc > 0: + if sign: + return -math_float_inf + else: + return math_float_inf + # Underflow to zero + return 0.0 + +def from_rational(p, q, prec, rnd=round_fast): + """Create a raw mpf from a rational number p/q, round if + necessary.""" + return mpf_div(from_int(p), from_int(q), prec, rnd) + +def to_rational(s): + """Convert a raw mpf to a rational number. Return integers (p, q) + such that s = p/q exactly.""" + sign, man, exp, bc = s + if sign: + man = -man + if bc == -1: + raise ValueError("cannot convert %s to a rational number" % man) + if exp >= 0: + return man * (1<= 0: return (-man) << offset + else: return (-man) >> (-offset) + else: + if offset >= 0: return man << offset + else: return man >> (-offset) + + +############################################################################## +############################################################################## + +#----------------------------------------------------------------------------# +# Arithmetic operations, etc. # +#----------------------------------------------------------------------------# + +def mpf_rand(prec): + """Return a raw mpf chosen randomly from [0, 1), with prec bits + in the mantissa.""" + global getrandbits + if not getrandbits: + import random + getrandbits = random.getrandbits + return from_man_exp(getrandbits(prec), -prec, prec, round_floor) + +def mpf_eq(s, t): + """Test equality of two raw mpfs. This is simply tuple comparison + unless either number is nan, in which case the result is False.""" + if not s[1] or not t[1]: + if s == fnan or t == fnan: + return False + return s == t + +def mpf_hash(s): + # Duplicate the new hash algorithm introduces in Python 3.2. + if sys.version_info >= (3, 2): + ssign, sman, sexp, sbc = s + + # Handle special numbers + if not sman: + if s == fnan: return sys.hash_info.nan + if s == finf: return sys.hash_info.inf + if s == fninf: return -sys.hash_info.inf + h = sman % HASH_MODULUS + if sexp >= 0: + sexp = sexp % HASH_BITS + else: + sexp = HASH_BITS - 1 - ((-1 - sexp) % HASH_BITS) + h = (h << sexp) % HASH_MODULUS + if ssign: h = -h + if h == -1: h = -2 + return int(h) + else: + try: + # Try to be compatible with hash values for floats and ints + return hash(to_float(s, strict=1)) + except OverflowError: + # We must unfortunately sacrifice compatibility with ints here. + # We could do hash(man << exp) when the exponent is positive, but + # this would cause unreasonable inefficiency for large numbers. + return hash(s) + +def mpf_cmp(s, t): + """Compare the raw mpfs s and t. Return -1 if s < t, 0 if s == t, + and 1 if s > t. (Same convention as Python's cmp() function.)""" + + # In principle, a comparison amounts to determining the sign of s-t. + # A full subtraction is relatively slow, however, so we first try to + # look at the components. + ssign, sman, sexp, sbc = s + tsign, tman, texp, tbc = t + + # Handle zeros and special numbers + if not sman or not tman: + if s == fzero: return -mpf_sign(t) + if t == fzero: return mpf_sign(s) + if s == t: return 0 + # Follow same convention as Python's cmp for float nan + if t == fnan: return 1 + if s == finf: return 1 + if t == fninf: return 1 + return -1 + # Different sides of zero + if ssign != tsign: + if not ssign: return 1 + return -1 + # This reduces to direct integer comparison + if sexp == texp: + if sman == tman: + return 0 + if sman > tman: + if ssign: return -1 + else: return 1 + else: + if ssign: return 1 + else: return -1 + # Check position of the highest set bit in each number. If + # different, there is certainly an inequality. + a = sbc + sexp + b = tbc + texp + if ssign: + if a < b: return 1 + if a > b: return -1 + else: + if a < b: return -1 + if a > b: return 1 + + # Both numbers have the same highest bit. Subtract to find + # how the lower bits compare. + delta = mpf_sub(s, t, 5, round_floor) + if delta[0]: + return -1 + return 1 + +def mpf_lt(s, t): + if s == fnan or t == fnan: + return False + return mpf_cmp(s, t) < 0 + +def mpf_le(s, t): + if s == fnan or t == fnan: + return False + return mpf_cmp(s, t) <= 0 + +def mpf_gt(s, t): + if s == fnan or t == fnan: + return False + return mpf_cmp(s, t) > 0 + +def mpf_ge(s, t): + if s == fnan or t == fnan: + return False + return mpf_cmp(s, t) >= 0 + +def mpf_min_max(seq): + min = max = seq[0] + for x in seq[1:]: + if mpf_lt(x, min): min = x + if mpf_gt(x, max): max = x + return min, max + +def mpf_pos(s, prec=0, rnd=round_fast): + """Calculate 0+s for a raw mpf (i.e., just round s to the specified + precision).""" + if prec: + sign, man, exp, bc = s + if (not man) and exp: + return s + return normalize1(sign, man, exp, bc, prec, rnd) + return s + +def mpf_neg(s, prec=None, rnd=round_fast): + """Negate a raw mpf (return -s), rounding the result to the + specified precision. The prec argument can be omitted to do the + operation exactly.""" + sign, man, exp, bc = s + if not man: + if exp: + if s == finf: return fninf + if s == fninf: return finf + return s + if not prec: + return (1-sign, man, exp, bc) + return normalize1(1-sign, man, exp, bc, prec, rnd) + +def mpf_abs(s, prec=None, rnd=round_fast): + """Return abs(s) of the raw mpf s, rounded to the specified + precision. The prec argument can be omitted to generate an + exact result.""" + sign, man, exp, bc = s + if (not man) and exp: + if s == fninf: + return finf + return s + if not prec: + if sign: + return (0, man, exp, bc) + return s + return normalize1(0, man, exp, bc, prec, rnd) + +def mpf_sign(s): + """Return -1, 0, or 1 (as a Python int, not a raw mpf) depending on + whether s is negative, zero, or positive. (Nan is taken to give 0.)""" + sign, man, exp, bc = s + if not man: + if s == finf: return 1 + if s == fninf: return -1 + return 0 + return (-1) ** sign + +def mpf_add(s, t, prec=0, rnd=round_fast, _sub=0): + """ + Add the two raw mpf values s and t. + + With prec=0, no rounding is performed. Note that this can + produce a very large mantissa (potentially too large to fit + in memory) if exponents are far apart. + """ + ssign, sman, sexp, sbc = s + tsign, tman, texp, tbc = t + tsign ^= _sub + # Standard case: two nonzero, regular numbers + if sman and tman: + offset = sexp - texp + if offset: + if offset > 0: + # Outside precision range; only need to perturb + if offset > 100 and prec: + delta = sbc + sexp - tbc - texp + if delta > prec + 4: + offset = prec + 4 + sman <<= offset + if tsign == ssign: sman += 1 + else: sman -= 1 + return normalize1(ssign, sman, sexp-offset, + bitcount(sman), prec, rnd) + # Add + if ssign == tsign: + man = tman + (sman << offset) + # Subtract + else: + if ssign: man = tman - (sman << offset) + else: man = (sman << offset) - tman + if man >= 0: + ssign = 0 + else: + man = -man + ssign = 1 + bc = bitcount(man) + return normalize1(ssign, man, texp, bc, prec or bc, rnd) + elif offset < 0: + # Outside precision range; only need to perturb + if offset < -100 and prec: + delta = tbc + texp - sbc - sexp + if delta > prec + 4: + offset = prec + 4 + tman <<= offset + if ssign == tsign: tman += 1 + else: tman -= 1 + return normalize1(tsign, tman, texp-offset, + bitcount(tman), prec, rnd) + # Add + if ssign == tsign: + man = sman + (tman << -offset) + # Subtract + else: + if tsign: man = sman - (tman << -offset) + else: man = (tman << -offset) - sman + if man >= 0: + ssign = 0 + else: + man = -man + ssign = 1 + bc = bitcount(man) + return normalize1(ssign, man, sexp, bc, prec or bc, rnd) + # Equal exponents; no shifting necessary + if ssign == tsign: + man = tman + sman + else: + if ssign: man = tman - sman + else: man = sman - tman + if man >= 0: + ssign = 0 + else: + man = -man + ssign = 1 + bc = bitcount(man) + return normalize(ssign, man, texp, bc, prec or bc, rnd) + # Handle zeros and special numbers + if _sub: + t = mpf_neg(t) + if not sman: + if sexp: + if s == t or tman or not texp: + return s + return fnan + if tman: + return normalize1(tsign, tman, texp, tbc, prec or tbc, rnd) + return t + if texp: + return t + if sman: + return normalize1(ssign, sman, sexp, sbc, prec or sbc, rnd) + return s + +def mpf_sub(s, t, prec=0, rnd=round_fast): + """Return the difference of two raw mpfs, s-t. This function is + simply a wrapper of mpf_add that changes the sign of t.""" + return mpf_add(s, t, prec, rnd, 1) + +def mpf_sum(xs, prec=0, rnd=round_fast, absolute=False): + """ + Sum a list of mpf values efficiently and accurately + (typically no temporary roundoff occurs). If prec=0, + the final result will not be rounded either. + + There may be roundoff error or cancellation if extremely + large exponent differences occur. + + With absolute=True, sums the absolute values. + """ + man = 0 + exp = 0 + max_extra_prec = prec*2 or 1000000 # XXX + special = None + for x in xs: + xsign, xman, xexp, xbc = x + if xman: + if xsign and not absolute: + xman = -xman + delta = xexp - exp + if xexp >= exp: + # x much larger than existing sum? + # first: quick test + if (delta > max_extra_prec) and \ + ((not man) or delta-bitcount(abs(man)) > max_extra_prec): + man = xman + exp = xexp + else: + man += (xman << delta) + else: + delta = -delta + # x much smaller than existing sum? + if delta-xbc > max_extra_prec: + if not man: + man, exp = xman, xexp + else: + man = (man << delta) + xman + exp = xexp + elif xexp: + if absolute: + x = mpf_abs(x) + special = mpf_add(special or fzero, x, 1) + # Will be inf or nan + if special: + return special + return from_man_exp(man, exp, prec, rnd) + +def gmpy_mpf_mul(s, t, prec=0, rnd=round_fast): + """Multiply two raw mpfs""" + ssign, sman, sexp, sbc = s + tsign, tman, texp, tbc = t + sign = ssign ^ tsign + man = sman*tman + if man: + bc = bitcount(man) + if prec: + return normalize1(sign, man, sexp+texp, bc, prec, rnd) + else: + return (sign, man, sexp+texp, bc) + s_special = (not sman) and sexp + t_special = (not tman) and texp + if not s_special and not t_special: + return fzero + if fnan in (s, t): return fnan + if (not tman) and texp: s, t = t, s + if t == fzero: return fnan + return {1:finf, -1:fninf}[mpf_sign(s) * mpf_sign(t)] + +def gmpy_mpf_mul_int(s, n, prec, rnd=round_fast): + """Multiply by a Python integer.""" + sign, man, exp, bc = s + if not man: + return mpf_mul(s, from_int(n), prec, rnd) + if not n: + return fzero + if n < 0: + sign ^= 1 + n = -n + man *= n + return normalize(sign, man, exp, bitcount(man), prec, rnd) + +def python_mpf_mul(s, t, prec=0, rnd=round_fast): + """Multiply two raw mpfs""" + ssign, sman, sexp, sbc = s + tsign, tman, texp, tbc = t + sign = ssign ^ tsign + man = sman*tman + if man: + bc = sbc + tbc - 1 + bc += int(man>>bc) + if prec: + return normalize1(sign, man, sexp+texp, bc, prec, rnd) + else: + return (sign, man, sexp+texp, bc) + s_special = (not sman) and sexp + t_special = (not tman) and texp + if not s_special and not t_special: + return fzero + if fnan in (s, t): return fnan + if (not tman) and texp: s, t = t, s + if t == fzero: return fnan + return {1:finf, -1:fninf}[mpf_sign(s) * mpf_sign(t)] + +def python_mpf_mul_int(s, n, prec, rnd=round_fast): + """Multiply by a Python integer.""" + sign, man, exp, bc = s + if not man: + return mpf_mul(s, from_int(n), prec, rnd) + if not n: + return fzero + if n < 0: + sign ^= 1 + n = -n + man *= n + # Generally n will be small + if n < 1024: + bc += bctable[int(n)] - 1 + else: + bc += bitcount(n) - 1 + bc += int(man>>bc) + return normalize(sign, man, exp, bc, prec, rnd) + + +if BACKEND == 'gmpy': + mpf_mul = gmpy_mpf_mul + mpf_mul_int = gmpy_mpf_mul_int +else: + mpf_mul = python_mpf_mul + mpf_mul_int = python_mpf_mul_int + +def mpf_shift(s, n): + """Quickly multiply the raw mpf s by 2**n without rounding.""" + sign, man, exp, bc = s + if not man: + return s + return sign, man, exp+n, bc + +def mpf_frexp(x): + """Convert x = y*2**n to (y, n) with abs(y) in [0.5, 1) if nonzero""" + sign, man, exp, bc = x + if not man: + if x == fzero: + return (fzero, 0) + else: + raise ValueError + return mpf_shift(x, -bc-exp), bc+exp + +def mpf_div(s, t, prec, rnd=round_fast): + """Floating-point division""" + ssign, sman, sexp, sbc = s + tsign, tman, texp, tbc = t + if not sman or not tman: + if s == fzero: + if t == fzero: raise ZeroDivisionError + if t == fnan: return fnan + return fzero + if t == fzero: + raise ZeroDivisionError + s_special = (not sman) and sexp + t_special = (not tman) and texp + if s_special and t_special: + return fnan + if s == fnan or t == fnan: + return fnan + if not t_special: + if t == fzero: + return fnan + return {1:finf, -1:fninf}[mpf_sign(s) * mpf_sign(t)] + return fzero + sign = ssign ^ tsign + if tman == 1: + return normalize1(sign, sman, sexp-texp, sbc, prec, rnd) + # Same strategy as for addition: if there is a remainder, perturb + # the result a few bits outside the precision range before rounding + extra = prec - sbc + tbc + 5 + if extra < 5: + extra = 5 + quot, rem = divmod(sman< sexp+sbc: + return s + # Another important special case: this allows us to do e.g. x % 1.0 + # to find the fractional part of x, and it will work when x is huge. + if tman == 1 and sexp > texp+tbc: + return fzero + base = min(sexp, texp) + sman = (-1)**ssign * sman + tman = (-1)**tsign * tman + man = (sman << (sexp-base)) % (tman << (texp-base)) + if man >= 0: + sign = 0 + else: + man = -man + sign = 1 + return normalize(sign, man, base, bitcount(man), prec, rnd) + +reciprocal_rnd = { + round_down : round_up, + round_up : round_down, + round_floor : round_ceiling, + round_ceiling : round_floor, + round_nearest : round_nearest +} + +negative_rnd = { + round_down : round_down, + round_up : round_up, + round_floor : round_ceiling, + round_ceiling : round_floor, + round_nearest : round_nearest +} + +def mpf_pow_int(s, n, prec, rnd=round_fast): + """Compute s**n, where s is a raw mpf and n is a Python integer.""" + sign, man, exp, bc = s + + if (not man) and exp: + if s == finf: + if n > 0: return s + if n == 0: return fnan + return fzero + if s == fninf: + if n > 0: return [finf, fninf][n & 1] + if n == 0: return fnan + return fzero + return fnan + + n = int(n) + if n == 0: return fone + if n == 1: return mpf_pos(s, prec, rnd) + if n == 2: + _, man, exp, bc = s + if not man: + return fzero + man = man*man + if man == 1: + return (0, MPZ_ONE, exp+exp, 1) + bc = bc + bc - 2 + bc += bctable[int(man>>bc)] + return normalize1(0, man, exp+exp, bc, prec, rnd) + if n == -1: return mpf_div(fone, s, prec, rnd) + if n < 0: + inverse = mpf_pow_int(s, -n, prec+5, reciprocal_rnd[rnd]) + return mpf_div(fone, inverse, prec, rnd) + + result_sign = sign & n + + # Use exact integer power when the exact mantissa is small + if man == 1: + return (result_sign, MPZ_ONE, exp*n, 1) + if bc*n < 1000: + man **= n + return normalize1(result_sign, man, exp*n, bitcount(man), prec, rnd) + + # Use directed rounding all the way through to maintain rigorous + # bounds for interval arithmetic + rounds_down = (rnd == round_nearest) or \ + shifts_down[rnd][result_sign] + + # Now we perform binary exponentiation. Need to estimate precision + # to avoid rounding errors from temporary operations. Roughly log_2(n) + # operations are performed. + workprec = prec + 4*bitcount(n) + 4 + _, pm, pe, pbc = fone + while 1: + if n & 1: + pm = pm*man + pe = pe+exp + pbc += bc - 2 + pbc = pbc + bctable[int(pm >> pbc)] + if pbc > workprec: + if rounds_down: + pm = pm >> (pbc-workprec) + else: + pm = -((-pm) >> (pbc-workprec)) + pe += pbc - workprec + pbc = workprec + n -= 1 + if not n: + break + man = man*man + exp = exp+exp + bc = bc + bc - 2 + bc = bc + bctable[int(man >> bc)] + if bc > workprec: + if rounds_down: + man = man >> (bc-workprec) + else: + man = -((-man) >> (bc-workprec)) + exp += bc - workprec + bc = workprec + n = n // 2 + + return normalize(result_sign, pm, pe, pbc, prec, rnd) + + +def mpf_perturb(x, eps_sign, prec, rnd): + """ + For nonzero x, calculate x + eps with directed rounding, where + eps < prec relatively and eps has the given sign (0 for + positive, 1 for negative). + + With rounding to nearest, this is taken to simply normalize + x to the given precision. + """ + if rnd == round_nearest: + return mpf_pos(x, prec, rnd) + sign, man, exp, bc = x + eps = (eps_sign, MPZ_ONE, exp+bc-prec-1, 1) + if sign: + away = (rnd in (round_down, round_ceiling)) ^ eps_sign + else: + away = (rnd in (round_up, round_ceiling)) ^ eps_sign + if away: + return mpf_add(x, eps, prec, rnd) + else: + return mpf_pos(x, prec, rnd) + + +#----------------------------------------------------------------------------# +# Radix conversion # +#----------------------------------------------------------------------------# + +def to_digits_exp(s, dps): + """Helper function for representing the floating-point number s as + a decimal with dps digits. Returns (sign, string, exponent) where + sign is '' or '-', string is the digit string, and exponent is + the decimal exponent as an int. + + If inexact, the decimal representation is rounded toward zero.""" + + # Extract sign first so it doesn't mess up the string digit count + if s[0]: + sign = '-' + s = mpf_neg(s) + else: + sign = '' + _sign, man, exp, bc = s + + if not man: + return '', '0', 0 + + bitprec = int(dps * math.log(10,2)) + 10 + + # Cut down to size + # TODO: account for precision when doing this + exp_from_1 = exp + bc + if abs(exp_from_1) > 3500: + from .libelefun import mpf_ln2, mpf_ln10 + # Set b = int(exp * log(2)/log(10)) + # If exp is huge, we must use high-precision arithmetic to + # find the nearest power of ten + expprec = bitcount(abs(exp)) + 5 + tmp = from_int(exp) + tmp = mpf_mul(tmp, mpf_ln2(expprec)) + tmp = mpf_div(tmp, mpf_ln10(expprec), expprec) + b = to_int(tmp) + s = mpf_div(s, mpf_pow_int(ften, b, bitprec), bitprec) + _sign, man, exp, bc = s + exponent = b + else: + exponent = 0 + + # First, calculate mantissa digits by converting to a binary + # fixed-point number and then converting that number to + # a decimal fixed-point number. + fixprec = max(bitprec - exp - bc, 0) + fixdps = int(fixprec / math.log(10,2) + 0.5) + sf = to_fixed(s, fixprec) + sd = bin_to_radix(sf, fixprec, 10, fixdps) + digits = numeral(sd, base=10, size=dps) + + exponent += len(digits) - fixdps - 1 + return sign, digits, exponent + +def to_str(s, dps, strip_zeros=True, min_fixed=None, max_fixed=None, + show_zero_exponent=False): + """ + Convert a raw mpf to a decimal floating-point literal with at + most `dps` decimal digits in the mantissa (not counting extra zeros + that may be inserted for visual purposes). + + The number will be printed in fixed-point format if the position + of the leading digit is strictly between min_fixed + (default = min(-dps/3,-5)) and max_fixed (default = dps). + + To force fixed-point format always, set min_fixed = -inf, + max_fixed = +inf. To force floating-point format, set + min_fixed >= max_fixed. + + The literal is formatted so that it can be parsed back to a number + by to_str, float() or Decimal(). + """ + + # Special numbers + if not s[1]: + if s == fzero: + if dps: t = '0.0' + else: t = '.0' + if show_zero_exponent: + t += 'e+0' + return t + if s == finf: return '+inf' + if s == fninf: return '-inf' + if s == fnan: return 'nan' + raise ValueError + + if min_fixed is None: min_fixed = min(-(dps//3), -5) + if max_fixed is None: max_fixed = dps + + # to_digits_exp rounds to floor. + # This sometimes kills some instances of "...00001" + sign, digits, exponent = to_digits_exp(s, dps+3) + + # No digits: show only .0; round exponent to nearest + if not dps: + if digits[0] in '56789': + exponent += 1 + digits = ".0" + + else: + # Rounding up kills some instances of "...99999" + if len(digits) > dps and digits[dps] in '56789': + digits = digits[:dps] + i = dps - 1 + while i >= 0 and digits[i] == '9': + i -= 1 + if i >= 0: + digits = digits[:i] + str(int(digits[i]) + 1) + '0' * (dps - i - 1) + else: + digits = '1' + '0' * (dps - 1) + exponent += 1 + else: + digits = digits[:dps] + + # Prettify numbers close to unit magnitude + if min_fixed < exponent < max_fixed: + if exponent < 0: + digits = ("0"*int(-exponent)) + digits + split = 1 + else: + split = exponent + 1 + if split > dps: + digits += "0"*(split-dps) + exponent = 0 + else: + split = 1 + + digits = (digits[:split] + "." + digits[split:]) + + if strip_zeros: + # Clean up trailing zeros + digits = digits.rstrip('0') + if digits[-1] == ".": + digits += "0" + + if exponent == 0 and dps and not show_zero_exponent: return sign + digits + if exponent >= 0: return sign + digits + "e+" + str(exponent) + if exponent < 0: return sign + digits + "e" + str(exponent) + +def str_to_man_exp(x, base=10): + """Helper function for from_str.""" + x = x.lower().rstrip('l') + # Verify that the input is a valid float literal + float(x) + # Split into mantissa, exponent + parts = x.split('e') + if len(parts) == 1: + exp = 0 + else: # == 2 + x = parts[0] + exp = int(parts[1]) + # Look for radix point in mantissa + parts = x.split('.') + if len(parts) == 2: + a, b = parts[0], parts[1].rstrip('0') + exp -= len(b) + x = a + b + x = MPZ(int(x, base)) + return x, exp + +special_str = {'inf':finf, '+inf':finf, '-inf':fninf, 'nan':fnan} + +def from_str(x, prec, rnd=round_fast): + """Create a raw mpf from a decimal literal, rounding in the + specified direction if the input number cannot be represented + exactly as a binary floating-point number with the given number of + bits. The literal syntax accepted is the same as for Python + floats. + + TODO: the rounding does not work properly for large exponents. + """ + x = x.lower().strip() + if x in special_str: + return special_str[x] + + if '/' in x: + p, q = x.split('/') + p, q = p.rstrip('l'), q.rstrip('l') + return from_rational(int(p), int(q), prec, rnd) + + man, exp = str_to_man_exp(x, base=10) + + # XXX: appropriate cutoffs & track direction + # note no factors of 5 + if abs(exp) > 400: + s = from_int(man, prec+10) + s = mpf_mul(s, mpf_pow_int(ften, exp, prec+10), prec, rnd) + else: + if exp >= 0: + s = from_int(man * 10**exp, prec, rnd) + else: + s = from_rational(man, 10**-exp, prec, rnd) + return s + +# Binary string conversion. These are currently mainly used for debugging +# and could use some improvement in the future + +def from_bstr(x): + man, exp = str_to_man_exp(x, base=2) + man = MPZ(man) + sign = 0 + if man < 0: + man = -man + sign = 1 + bc = bitcount(man) + return normalize(sign, man, exp, bc, bc, round_floor) + +def to_bstr(x): + sign, man, exp, bc = x + return ['','-'][sign] + numeral(man, size=bitcount(man), base=2) + ("e%i" % exp) + + +#----------------------------------------------------------------------------# +# Square roots # +#----------------------------------------------------------------------------# + + +def mpf_sqrt(s, prec, rnd=round_fast): + """ + Compute the square root of a nonnegative mpf value. The + result is correctly rounded. + """ + sign, man, exp, bc = s + if sign: + raise ComplexResult("square root of a negative number") + if not man: + return s + if exp & 1: + exp -= 1 + man <<= 1 + bc += 1 + elif man == 1: + return normalize1(sign, man, exp//2, bc, prec, rnd) + shift = max(4, 2*prec-bc+4) + shift += shift & 1 + if rnd in 'fd': + man = isqrt(man<= 0: + a = mpf_pos(sa, prec, round_floor) + b = mpf_pos(sb, prec, round_ceiling) + # Upper point nonnegative? + elif sbs >= 0: + a = fzero + negsa = mpf_neg(sa) + if mpf_lt(negsa, sb): + b = mpf_pos(sb, prec, round_ceiling) + else: + b = mpf_pos(negsa, prec, round_ceiling) + # Both negative? + else: + a = mpf_neg(sb, prec, round_floor) + b = mpf_neg(sa, prec, round_ceiling) + return a, b + +# TODO: optimize +def mpi_mul_mpf(s, t, prec): + return mpi_mul(s, (t, t), prec) + +def mpi_div_mpf(s, t, prec): + return mpi_div(s, (t, t), prec) + +def mpi_mul(s, t, prec=0): + sa, sb = s + ta, tb = t + sas = mpf_sign(sa) + sbs = mpf_sign(sb) + tas = mpf_sign(ta) + tbs = mpf_sign(tb) + if sas == sbs == 0: + # Should maybe be undefined + if ta == fninf or tb == finf: + return fninf, finf + return fzero, fzero + if tas == tbs == 0: + # Should maybe be undefined + if sa == fninf or sb == finf: + return fninf, finf + return fzero, fzero + if sas >= 0: + # positive * positive + if tas >= 0: + a = mpf_mul(sa, ta, prec, round_floor) + b = mpf_mul(sb, tb, prec, round_ceiling) + if a == fnan: a = fzero + if b == fnan: b = finf + # positive * negative + elif tbs <= 0: + a = mpf_mul(sb, ta, prec, round_floor) + b = mpf_mul(sa, tb, prec, round_ceiling) + if a == fnan: a = fninf + if b == fnan: b = fzero + # positive * both signs + else: + a = mpf_mul(sb, ta, prec, round_floor) + b = mpf_mul(sb, tb, prec, round_ceiling) + if a == fnan: a = fninf + if b == fnan: b = finf + elif sbs <= 0: + # negative * positive + if tas >= 0: + a = mpf_mul(sa, tb, prec, round_floor) + b = mpf_mul(sb, ta, prec, round_ceiling) + if a == fnan: a = fninf + if b == fnan: b = fzero + # negative * negative + elif tbs <= 0: + a = mpf_mul(sb, tb, prec, round_floor) + b = mpf_mul(sa, ta, prec, round_ceiling) + if a == fnan: a = fzero + if b == fnan: b = finf + # negative * both signs + else: + a = mpf_mul(sa, tb, prec, round_floor) + b = mpf_mul(sa, ta, prec, round_ceiling) + if a == fnan: a = fninf + if b == fnan: b = finf + else: + # General case: perform all cross-multiplications and compare + # Since the multiplications can be done exactly, we need only + # do 4 (instead of 8: two for each rounding mode) + cases = [mpf_mul(sa, ta), mpf_mul(sa, tb), mpf_mul(sb, ta), mpf_mul(sb, tb)] + if fnan in cases: + a, b = (fninf, finf) + else: + a, b = mpf_min_max(cases) + a = mpf_pos(a, prec, round_floor) + b = mpf_pos(b, prec, round_ceiling) + return a, b + +def mpi_square(s, prec=0): + sa, sb = s + if mpf_ge(sa, fzero): + a = mpf_mul(sa, sa, prec, round_floor) + b = mpf_mul(sb, sb, prec, round_ceiling) + elif mpf_le(sb, fzero): + a = mpf_mul(sb, sb, prec, round_floor) + b = mpf_mul(sa, sa, prec, round_ceiling) + else: + sa = mpf_neg(sa) + sa, sb = mpf_min_max([sa, sb]) + a = fzero + b = mpf_mul(sb, sb, prec, round_ceiling) + return a, b + +def mpi_div(s, t, prec): + sa, sb = s + ta, tb = t + sas = mpf_sign(sa) + sbs = mpf_sign(sb) + tas = mpf_sign(ta) + tbs = mpf_sign(tb) + # 0 / X + if sas == sbs == 0: + # 0 / + if (tas < 0 and tbs > 0) or (tas == 0 or tbs == 0): + return fninf, finf + return fzero, fzero + # Denominator contains both negative and positive numbers; + # this should properly be a multi-interval, but the closest + # match is the entire (extended) real line + if tas < 0 and tbs > 0: + return fninf, finf + # Assume denominator to be nonnegative + if tas < 0: + return mpi_div(mpi_neg(s), mpi_neg(t), prec) + # Division by zero + # XXX: make sure all results make sense + if tas == 0: + # Numerator contains both signs? + if sas < 0 and sbs > 0: + return fninf, finf + if tas == tbs: + return fninf, finf + # Numerator positive? + if sas >= 0: + a = mpf_div(sa, tb, prec, round_floor) + b = finf + if sbs <= 0: + a = fninf + b = mpf_div(sb, tb, prec, round_ceiling) + # Division with positive denominator + # We still have to handle nans resulting from inf/0 or inf/inf + else: + # Nonnegative numerator + if sas >= 0: + a = mpf_div(sa, tb, prec, round_floor) + b = mpf_div(sb, ta, prec, round_ceiling) + if a == fnan: a = fzero + if b == fnan: b = finf + # Nonpositive numerator + elif sbs <= 0: + a = mpf_div(sa, ta, prec, round_floor) + b = mpf_div(sb, tb, prec, round_ceiling) + if a == fnan: a = fninf + if b == fnan: b = fzero + # Numerator contains both signs? + else: + a = mpf_div(sa, ta, prec, round_floor) + b = mpf_div(sb, ta, prec, round_ceiling) + if a == fnan: a = fninf + if b == fnan: b = finf + return a, b + +def mpi_pi(prec): + a = mpf_pi(prec, round_floor) + b = mpf_pi(prec, round_ceiling) + return a, b + +def mpi_exp(s, prec): + sa, sb = s + # exp is monotonic + a = mpf_exp(sa, prec, round_floor) + b = mpf_exp(sb, prec, round_ceiling) + return a, b + +def mpi_log(s, prec): + sa, sb = s + # log is monotonic + a = mpf_log(sa, prec, round_floor) + b = mpf_log(sb, prec, round_ceiling) + return a, b + +def mpi_sqrt(s, prec): + sa, sb = s + # sqrt is monotonic + a = mpf_sqrt(sa, prec, round_floor) + b = mpf_sqrt(sb, prec, round_ceiling) + return a, b + +def mpi_atan(s, prec): + sa, sb = s + a = mpf_atan(sa, prec, round_floor) + b = mpf_atan(sb, prec, round_ceiling) + return a, b + +def mpi_pow_int(s, n, prec): + sa, sb = s + if n < 0: + return mpi_div((fone, fone), mpi_pow_int(s, -n, prec+20), prec) + if n == 0: + return (fone, fone) + if n == 1: + return s + if n == 2: + return mpi_square(s, prec) + # Odd -- signs are preserved + if n & 1: + a = mpf_pow_int(sa, n, prec, round_floor) + b = mpf_pow_int(sb, n, prec, round_ceiling) + # Even -- important to ensure positivity + else: + sas = mpf_sign(sa) + sbs = mpf_sign(sb) + # Nonnegative? + if sas >= 0: + a = mpf_pow_int(sa, n, prec, round_floor) + b = mpf_pow_int(sb, n, prec, round_ceiling) + # Nonpositive? + elif sbs <= 0: + a = mpf_pow_int(sb, n, prec, round_floor) + b = mpf_pow_int(sa, n, prec, round_ceiling) + # Mixed signs? + else: + a = fzero + # max(-a,b)**n + sa = mpf_neg(sa) + if mpf_ge(sa, sb): + b = mpf_pow_int(sa, n, prec, round_ceiling) + else: + b = mpf_pow_int(sb, n, prec, round_ceiling) + return a, b + +def mpi_pow(s, t, prec): + ta, tb = t + if ta == tb and ta not in (finf, fninf): + if ta == from_int(to_int(ta)): + return mpi_pow_int(s, to_int(ta), prec) + if ta == fhalf: + return mpi_sqrt(s, prec) + u = mpi_log(s, prec + 20) + v = mpi_mul(u, t, prec + 20) + return mpi_exp(v, prec) + +def MIN(x, y): + if mpf_le(x, y): + return x + return y + +def MAX(x, y): + if mpf_ge(x, y): + return x + return y + +def cos_sin_quadrant(x, wp): + sign, man, exp, bc = x + if x == fzero: + return fone, fzero, 0 + # TODO: combine evaluation code to avoid duplicate modulo + c, s = mpf_cos_sin(x, wp) + t, n, wp_ = mod_pi2(man, exp, exp+bc, 15) + if sign: + n = -1-n + return c, s, n + +def mpi_cos_sin(x, prec): + a, b = x + if a == b == fzero: + return (fone, fone), (fzero, fzero) + # Guaranteed to contain both -1 and 1 + if (finf in x) or (fninf in x): + return (fnone, fone), (fnone, fone) + wp = prec + 20 + ca, sa, na = cos_sin_quadrant(a, wp) + cb, sb, nb = cos_sin_quadrant(b, wp) + ca, cb = mpf_min_max([ca, cb]) + sa, sb = mpf_min_max([sa, sb]) + # Both functions are monotonic within one quadrant + if na == nb: + pass + # Guaranteed to contain both -1 and 1 + elif nb - na >= 4: + return (fnone, fone), (fnone, fone) + else: + # cos has maximum between a and b + if na//4 != nb//4: + cb = fone + # cos has minimum + if (na-2)//4 != (nb-2)//4: + ca = fnone + # sin has maximum + if (na-1)//4 != (nb-1)//4: + sb = fone + # sin has minimum + if (na-3)//4 != (nb-3)//4: + sa = fnone + # Perturb to force interval rounding + more = from_man_exp((MPZ_ONE<= 1: + if sign: + return fnone + return fone + return v + ca = finalize(ca, round_floor) + cb = finalize(cb, round_ceiling) + sa = finalize(sa, round_floor) + sb = finalize(sb, round_ceiling) + return (ca,cb), (sa,sb) + +def mpi_cos(x, prec): + return mpi_cos_sin(x, prec)[0] + +def mpi_sin(x, prec): + return mpi_cos_sin(x, prec)[1] + +def mpi_tan(x, prec): + cos, sin = mpi_cos_sin(x, prec+20) + return mpi_div(sin, cos, prec) + +def mpi_cot(x, prec): + cos, sin = mpi_cos_sin(x, prec+20) + return mpi_div(cos, sin, prec) + +def mpi_from_str_a_b(x, y, percent, prec): + wp = prec + 20 + xa = from_str(x, wp, round_floor) + xb = from_str(x, wp, round_ceiling) + #ya = from_str(y, wp, round_floor) + y = from_str(y, wp, round_ceiling) + assert mpf_ge(y, fzero) + if percent: + y = mpf_mul(MAX(mpf_abs(xa), mpf_abs(xb)), y, wp, round_ceiling) + y = mpf_div(y, from_int(100), wp, round_ceiling) + a = mpf_sub(xa, y, prec, round_floor) + b = mpf_add(xb, y, prec, round_ceiling) + return a, b + +def mpi_from_str(s, prec): + """ + Parse an interval number given as a string. + + Allowed forms are + + "-1.23e-27" + Any single decimal floating-point literal. + "a +- b" or "a (b)" + a is the midpoint of the interval and b is the half-width + "a +- b%" or "a (b%)" + a is the midpoint of the interval and the half-width + is b percent of a (`a \times b / 100`). + "[a, b]" + The interval indicated directly. + "x[y,z]e" + x are shared digits, y and z are unequal digits, e is the exponent. + + """ + e = ValueError("Improperly formed interval number '%s'" % s) + s = s.replace(" ", "") + wp = prec + 20 + if "+-" in s: + x, y = s.split("+-") + return mpi_from_str_a_b(x, y, False, prec) + # case 2 + elif "(" in s: + # Don't confuse with a complex number (x,y) + if s[0] == "(" or ")" not in s: + raise e + s = s.replace(")", "") + percent = False + if "%" in s: + if s[-1] != "%": + raise e + percent = True + s = s.replace("%", "") + x, y = s.split("(") + return mpi_from_str_a_b(x, y, percent, prec) + elif "," in s: + if ('[' not in s) or (']' not in s): + raise e + if s[0] == '[': + # case 3 + s = s.replace("[", "") + s = s.replace("]", "") + a, b = s.split(",") + a = from_str(a, prec, round_floor) + b = from_str(b, prec, round_ceiling) + return a, b + else: + # case 4 + x, y = s.split('[') + y, z = y.split(',') + if 'e' in s: + z, e = z.split(']') + else: + z, e = z.rstrip(']'), '' + a = from_str(x+y+e, prec, round_floor) + b = from_str(x+z+e, prec, round_ceiling) + return a, b + else: + a = from_str(s, prec, round_floor) + b = from_str(s, prec, round_ceiling) + return a, b + +def mpi_to_str(x, dps, use_spaces=True, brackets='[]', mode='brackets', error_dps=4, **kwargs): + """ + Convert a mpi interval to a string. + + **Arguments** + + *dps* + decimal places to use for printing + *use_spaces* + use spaces for more readable output, defaults to true + *brackets* + pair of strings (or two-character string) giving left and right brackets + *mode* + mode of display: 'plusminus', 'percent', 'brackets' (default) or 'diff' + *error_dps* + limit the error to *error_dps* digits (mode 'plusminus and 'percent') + + Additional keyword arguments are forwarded to the mpf-to-string conversion + for the components of the output. + + **Examples** + + >>> from mpmath import mpi, mp + >>> mp.dps = 30 + >>> x = mpi(1, 2)._mpi_ + >>> mpi_to_str(x, 2, mode='plusminus') + '1.5 +- 0.5' + >>> mpi_to_str(x, 2, mode='percent') + '1.5 (33.33%)' + >>> mpi_to_str(x, 2, mode='brackets') + '[1.0, 2.0]' + >>> mpi_to_str(x, 2, mode='brackets' , brackets=('<', '>')) + '<1.0, 2.0>' + >>> x = mpi('5.2582327113062393041', '5.2582327113062749951')._mpi_ + >>> mpi_to_str(x, 15, mode='diff') + '5.2582327113062[4, 7]' + >>> mpi_to_str(mpi(0)._mpi_, 2, mode='percent') + '0.0 (0.0%)' + + """ + prec = dps_to_prec(dps) + wp = prec + 20 + a, b = x + mid = mpi_mid(x, prec) + delta = mpi_delta(x, prec) + a_str = to_str(a, dps, **kwargs) + b_str = to_str(b, dps, **kwargs) + mid_str = to_str(mid, dps, **kwargs) + sp = "" + if use_spaces: + sp = " " + br1, br2 = brackets + if mode == 'plusminus': + delta_str = to_str(mpf_shift(delta,-1), dps, **kwargs) + s = mid_str + sp + "+-" + sp + delta_str + elif mode == 'percent': + if mid == fzero: + p = fzero + else: + # p = 100 * delta(x) / (2*mid(x)) + p = mpf_mul(delta, from_int(100)) + p = mpf_div(p, mpf_mul(mid, from_int(2)), wp) + s = mid_str + sp + "(" + to_str(p, error_dps) + "%)" + elif mode == 'brackets': + s = br1 + a_str + "," + sp + b_str + br2 + elif mode == 'diff': + # use more digits if str(x.a) and str(x.b) are equal + if a_str == b_str: + a_str = to_str(a, dps+3, **kwargs) + b_str = to_str(b, dps+3, **kwargs) + # separate mantissa and exponent + a = a_str.split('e') + if len(a) == 1: + a.append('') + b = b_str.split('e') + if len(b) == 1: + b.append('') + if a[1] == b[1]: + if a[0] != b[0]: + for i in xrange(len(a[0]) + 1): + if a[0][i] != b[0][i]: + break + s = (a[0][:i] + br1 + a[0][i:] + ',' + sp + b[0][i:] + br2 + + 'e'*min(len(a[1]), 1) + a[1]) + else: # no difference + s = a[0] + br1 + br2 + 'e'*min(len(a[1]), 1) + a[1] + else: + s = br1 + 'e'.join(a) + ',' + sp + 'e'.join(b) + br2 + else: + raise ValueError("'%s' is unknown mode for printing mpi" % mode) + return s + +def mpci_add(x, y, prec): + a, b = x + c, d = y + return mpi_add(a, c, prec), mpi_add(b, d, prec) + +def mpci_sub(x, y, prec): + a, b = x + c, d = y + return mpi_sub(a, c, prec), mpi_sub(b, d, prec) + +def mpci_neg(x, prec=0): + a, b = x + return mpi_neg(a, prec), mpi_neg(b, prec) + +def mpci_pos(x, prec): + a, b = x + return mpi_pos(a, prec), mpi_pos(b, prec) + +def mpci_mul(x, y, prec): + # TODO: optimize for real/imag cases + a, b = x + c, d = y + r1 = mpi_mul(a,c) + r2 = mpi_mul(b,d) + re = mpi_sub(r1,r2,prec) + i1 = mpi_mul(a,d) + i2 = mpi_mul(b,c) + im = mpi_add(i1,i2,prec) + return re, im + +def mpci_div(x, y, prec): + # TODO: optimize for real/imag cases + a, b = x + c, d = y + wp = prec+20 + m1 = mpi_square(c) + m2 = mpi_square(d) + m = mpi_add(m1,m2,wp) + re = mpi_add(mpi_mul(a,c), mpi_mul(b,d), wp) + im = mpi_sub(mpi_mul(b,c), mpi_mul(a,d), wp) + re = mpi_div(re, m, prec) + im = mpi_div(im, m, prec) + return re, im + +def mpci_exp(x, prec): + a, b = x + wp = prec+20 + r = mpi_exp(a, wp) + c, s = mpi_cos_sin(b, wp) + a = mpi_mul(r, c, prec) + b = mpi_mul(r, s, prec) + return a, b + +def mpi_shift(x, n): + a, b = x + return mpf_shift(a,n), mpf_shift(b,n) + +def mpi_cosh_sinh(x, prec): + # TODO: accuracy for small x + wp = prec+20 + e1 = mpi_exp(x, wp) + e2 = mpi_div(mpi_one, e1, wp) + c = mpi_add(e1, e2, prec) + s = mpi_sub(e1, e2, prec) + c = mpi_shift(c, -1) + s = mpi_shift(s, -1) + return c, s + +def mpci_cos(x, prec): + a, b = x + wp = prec+10 + c, s = mpi_cos_sin(a, wp) + ch, sh = mpi_cosh_sinh(b, wp) + re = mpi_mul(c, ch, prec) + im = mpi_mul(s, sh, prec) + return re, mpi_neg(im) + +def mpci_sin(x, prec): + a, b = x + wp = prec+10 + c, s = mpi_cos_sin(a, wp) + ch, sh = mpi_cosh_sinh(b, wp) + re = mpi_mul(s, ch, prec) + im = mpi_mul(c, sh, prec) + return re, im + +def mpci_abs(x, prec): + a, b = x + if a == mpi_zero: + return mpi_abs(b) + if b == mpi_zero: + return mpi_abs(a) + # Important: nonnegative + a = mpi_square(a) + b = mpi_square(b) + t = mpi_add(a, b, prec+20) + return mpi_sqrt(t, prec) + +def mpi_atan2(y, x, prec): + ya, yb = y + xa, xb = x + # Constrained to the real line + if ya == yb == fzero: + if mpf_ge(xa, fzero): + return mpi_zero + return mpi_pi(prec) + # Right half-plane + if mpf_ge(xa, fzero): + if mpf_ge(ya, fzero): + a = mpf_atan2(ya, xb, prec, round_floor) + else: + a = mpf_atan2(ya, xa, prec, round_floor) + if mpf_ge(yb, fzero): + b = mpf_atan2(yb, xa, prec, round_ceiling) + else: + b = mpf_atan2(yb, xb, prec, round_ceiling) + # Upper half-plane + elif mpf_ge(ya, fzero): + b = mpf_atan2(ya, xa, prec, round_ceiling) + if mpf_le(xb, fzero): + a = mpf_atan2(yb, xb, prec, round_floor) + else: + a = mpf_atan2(ya, xb, prec, round_floor) + # Lower half-plane + elif mpf_le(yb, fzero): + a = mpf_atan2(yb, xa, prec, round_floor) + if mpf_le(xb, fzero): + b = mpf_atan2(ya, xb, prec, round_ceiling) + else: + b = mpf_atan2(yb, xb, prec, round_ceiling) + # Covering the origin + else: + b = mpf_pi(prec, round_ceiling) + a = mpf_neg(b) + return a, b + +def mpci_arg(z, prec): + x, y = z + return mpi_atan2(y, x, prec) + +def mpci_log(z, prec): + x, y = z + re = mpi_log(mpci_abs(z, prec+20), prec) + im = mpci_arg(z, prec) + return re, im + +def mpci_pow(x, y, prec): + # TODO: recognize/speed up real cases, integer y + yre, yim = y + if yim == mpi_zero: + ya, yb = yre + if ya == yb: + sign, man, exp, bc = yb + if man and exp >= 0: + return mpci_pow_int(x, (-1)**sign * int(man<>= 1 + return mpci_pos(result, prec) + +gamma_min_a = from_float(1.46163214496) +gamma_min_b = from_float(1.46163214497) +gamma_min = (gamma_min_a, gamma_min_b) +gamma_mono_imag_a = from_float(-1.1) +gamma_mono_imag_b = from_float(1.1) + +def mpi_overlap(x, y): + a, b = x + c, d = y + if mpf_lt(d, a): return False + if mpf_gt(c, b): return False + return True + +# type = 0 -- gamma +# type = 1 -- factorial +# type = 2 -- 1/gamma +# type = 3 -- log-gamma + +def mpi_gamma(z, prec, type=0): + a, b = z + wp = prec+20 + + if type == 1: + return mpi_gamma(mpi_add(z, mpi_one, wp), prec, 0) + + # increasing + if mpf_gt(a, gamma_min_b): + if type == 0: + c = mpf_gamma(a, prec, round_floor) + d = mpf_gamma(b, prec, round_ceiling) + elif type == 2: + c = mpf_rgamma(b, prec, round_floor) + d = mpf_rgamma(a, prec, round_ceiling) + elif type == 3: + c = mpf_loggamma(a, prec, round_floor) + d = mpf_loggamma(b, prec, round_ceiling) + # decreasing + elif mpf_gt(a, fzero) and mpf_lt(b, gamma_min_a): + if type == 0: + c = mpf_gamma(b, prec, round_floor) + d = mpf_gamma(a, prec, round_ceiling) + elif type == 2: + c = mpf_rgamma(a, prec, round_floor) + d = mpf_rgamma(b, prec, round_ceiling) + elif type == 3: + c = mpf_loggamma(b, prec, round_floor) + d = mpf_loggamma(a, prec, round_ceiling) + else: + # TODO: reflection formula + znew = mpi_add(z, mpi_one, wp) + if type == 0: return mpi_div(mpi_gamma(znew, prec+2, 0), z, prec) + if type == 2: return mpi_mul(mpi_gamma(znew, prec+2, 2), z, prec) + if type == 3: return mpi_sub(mpi_gamma(znew, prec+2, 3), mpi_log(z, prec+2), prec) + return c, d + +def mpci_gamma(z, prec, type=0): + (a1,a2), (b1,b2) = z + + # Real case + if b1 == b2 == fzero and (type != 3 or mpf_gt(a1,fzero)): + return mpi_gamma(z, prec, type), mpi_zero + + # Estimate precision + wp = prec+20 + if type != 3: + amag = a2[2]+a2[3] + bmag = b2[2]+b2[3] + if a2 != fzero: + mag = max(amag, bmag) + else: + mag = bmag + an = abs(to_int(a2)) + bn = abs(to_int(b2)) + absn = max(an, bn) + gamma_size = max(0,absn*mag) + wp += bitcount(gamma_size) + + # Assume type != 1 + if type == 1: + (a1,a2) = mpi_add((a1,a2), mpi_one, wp); z = (a1,a2), (b1,b2) + type = 0 + + # Avoid non-monotonic region near the negative real axis + if mpf_lt(a1, gamma_min_b): + if mpi_overlap((b1,b2), (gamma_mono_imag_a, gamma_mono_imag_b)): + # TODO: reflection formula + #if mpf_lt(a2, mpf_shift(fone,-1)): + # znew = mpci_sub((mpi_one,mpi_zero),z,wp) + # ... + # Recurrence: + # gamma(z) = gamma(z+1)/z + znew = mpi_add((a1,a2), mpi_one, wp), (b1,b2) + if type == 0: return mpci_div(mpci_gamma(znew, prec+2, 0), z, prec) + if type == 2: return mpci_mul(mpci_gamma(znew, prec+2, 2), z, prec) + if type == 3: return mpci_sub(mpci_gamma(znew, prec+2, 3), mpci_log(z,prec+2), prec) + + # Use monotonicity (except for a small region close to the + # origin and near poles) + # upper half-plane + if mpf_ge(b1, fzero): + minre = mpc_loggamma((a1,b2), wp, round_floor) + maxre = mpc_loggamma((a2,b1), wp, round_ceiling) + minim = mpc_loggamma((a1,b1), wp, round_floor) + maxim = mpc_loggamma((a2,b2), wp, round_ceiling) + # lower half-plane + elif mpf_le(b2, fzero): + minre = mpc_loggamma((a1,b1), wp, round_floor) + maxre = mpc_loggamma((a2,b2), wp, round_ceiling) + minim = mpc_loggamma((a2,b1), wp, round_floor) + maxim = mpc_loggamma((a1,b2), wp, round_ceiling) + # crosses real axis + else: + maxre = mpc_loggamma((a2,fzero), wp, round_ceiling) + # stretches more into the lower half-plane + if mpf_gt(mpf_neg(b1), b2): + minre = mpc_loggamma((a1,b1), wp, round_ceiling) + else: + minre = mpc_loggamma((a1,b2), wp, round_ceiling) + minim = mpc_loggamma((a2,b1), wp, round_floor) + maxim = mpc_loggamma((a2,b2), wp, round_floor) + + w = (minre[0], maxre[0]), (minim[1], maxim[1]) + if type == 3: + return mpi_pos(w[0], prec), mpi_pos(w[1], prec) + if type == 2: + w = mpci_neg(w) + return mpci_exp(w, prec) + +def mpi_loggamma(z, prec): return mpi_gamma(z, prec, type=3) +def mpci_loggamma(z, prec): return mpci_gamma(z, prec, type=3) + +def mpi_rgamma(z, prec): return mpi_gamma(z, prec, type=2) +def mpci_rgamma(z, prec): return mpci_gamma(z, prec, type=2) + +def mpi_factorial(z, prec): return mpi_gamma(z, prec, type=1) +def mpci_factorial(z, prec): return mpci_gamma(z, prec, type=1) diff --git a/venv/lib/python3.10/site-packages/mpmath/math2.py b/venv/lib/python3.10/site-packages/mpmath/math2.py new file mode 100644 index 0000000000000000000000000000000000000000..302e25f509c18b2c76a2b62611f2765db84ab13e --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/math2.py @@ -0,0 +1,672 @@ +""" +This module complements the math and cmath builtin modules by providing +fast machine precision versions of some additional functions (gamma, ...) +and wrapping math/cmath functions so that they can be called with either +real or complex arguments. +""" + +import operator +import math +import cmath + +# Irrational (?) constants +pi = 3.1415926535897932385 +e = 2.7182818284590452354 +sqrt2 = 1.4142135623730950488 +sqrt5 = 2.2360679774997896964 +phi = 1.6180339887498948482 +ln2 = 0.69314718055994530942 +ln10 = 2.302585092994045684 +euler = 0.57721566490153286061 +catalan = 0.91596559417721901505 +khinchin = 2.6854520010653064453 +apery = 1.2020569031595942854 + +logpi = 1.1447298858494001741 + +def _mathfun_real(f_real, f_complex): + def f(x, **kwargs): + if type(x) is float: + return f_real(x) + if type(x) is complex: + return f_complex(x) + try: + x = float(x) + return f_real(x) + except (TypeError, ValueError): + x = complex(x) + return f_complex(x) + f.__name__ = f_real.__name__ + return f + +def _mathfun(f_real, f_complex): + def f(x, **kwargs): + if type(x) is complex: + return f_complex(x) + try: + return f_real(float(x)) + except (TypeError, ValueError): + return f_complex(complex(x)) + f.__name__ = f_real.__name__ + return f + +def _mathfun_n(f_real, f_complex): + def f(*args, **kwargs): + try: + return f_real(*(float(x) for x in args)) + except (TypeError, ValueError): + return f_complex(*(complex(x) for x in args)) + f.__name__ = f_real.__name__ + return f + +# Workaround for non-raising log and sqrt in Python 2.5 and 2.4 +# on Unix system +try: + math.log(-2.0) + def math_log(x): + if x <= 0.0: + raise ValueError("math domain error") + return math.log(x) + def math_sqrt(x): + if x < 0.0: + raise ValueError("math domain error") + return math.sqrt(x) +except (ValueError, TypeError): + math_log = math.log + math_sqrt = math.sqrt + +pow = _mathfun_n(operator.pow, lambda x, y: complex(x)**y) +log = _mathfun_n(math_log, cmath.log) +sqrt = _mathfun(math_sqrt, cmath.sqrt) +exp = _mathfun_real(math.exp, cmath.exp) + +cos = _mathfun_real(math.cos, cmath.cos) +sin = _mathfun_real(math.sin, cmath.sin) +tan = _mathfun_real(math.tan, cmath.tan) + +acos = _mathfun(math.acos, cmath.acos) +asin = _mathfun(math.asin, cmath.asin) +atan = _mathfun_real(math.atan, cmath.atan) + +cosh = _mathfun_real(math.cosh, cmath.cosh) +sinh = _mathfun_real(math.sinh, cmath.sinh) +tanh = _mathfun_real(math.tanh, cmath.tanh) + +floor = _mathfun_real(math.floor, + lambda z: complex(math.floor(z.real), math.floor(z.imag))) +ceil = _mathfun_real(math.ceil, + lambda z: complex(math.ceil(z.real), math.ceil(z.imag))) + + +cos_sin = _mathfun_real(lambda x: (math.cos(x), math.sin(x)), + lambda z: (cmath.cos(z), cmath.sin(z))) + +cbrt = _mathfun(lambda x: x**(1./3), lambda z: z**(1./3)) + +def nthroot(x, n): + r = 1./n + try: + return float(x) ** r + except (ValueError, TypeError): + return complex(x) ** r + +def _sinpi_real(x): + if x < 0: + return -_sinpi_real(-x) + n, r = divmod(x, 0.5) + r *= pi + n %= 4 + if n == 0: return math.sin(r) + if n == 1: return math.cos(r) + if n == 2: return -math.sin(r) + if n == 3: return -math.cos(r) + +def _cospi_real(x): + if x < 0: + x = -x + n, r = divmod(x, 0.5) + r *= pi + n %= 4 + if n == 0: return math.cos(r) + if n == 1: return -math.sin(r) + if n == 2: return -math.cos(r) + if n == 3: return math.sin(r) + +def _sinpi_complex(z): + if z.real < 0: + return -_sinpi_complex(-z) + n, r = divmod(z.real, 0.5) + z = pi*complex(r, z.imag) + n %= 4 + if n == 0: return cmath.sin(z) + if n == 1: return cmath.cos(z) + if n == 2: return -cmath.sin(z) + if n == 3: return -cmath.cos(z) + +def _cospi_complex(z): + if z.real < 0: + z = -z + n, r = divmod(z.real, 0.5) + z = pi*complex(r, z.imag) + n %= 4 + if n == 0: return cmath.cos(z) + if n == 1: return -cmath.sin(z) + if n == 2: return -cmath.cos(z) + if n == 3: return cmath.sin(z) + +cospi = _mathfun_real(_cospi_real, _cospi_complex) +sinpi = _mathfun_real(_sinpi_real, _sinpi_complex) + +def tanpi(x): + try: + return sinpi(x) / cospi(x) + except OverflowError: + if complex(x).imag > 10: + return 1j + if complex(x).imag < 10: + return -1j + raise + +def cotpi(x): + try: + return cospi(x) / sinpi(x) + except OverflowError: + if complex(x).imag > 10: + return -1j + if complex(x).imag < 10: + return 1j + raise + +INF = 1e300*1e300 +NINF = -INF +NAN = INF-INF +EPS = 2.2204460492503131e-16 + +_exact_gamma = (INF, 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, + 362880.0, 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0, + 1307674368000.0, 20922789888000.0, 355687428096000.0, 6402373705728000.0, + 121645100408832000.0, 2432902008176640000.0) + +_max_exact_gamma = len(_exact_gamma)-1 + +# Lanczos coefficients used by the GNU Scientific Library +_lanczos_g = 7 +_lanczos_p = (0.99999999999980993, 676.5203681218851, -1259.1392167224028, + 771.32342877765313, -176.61502916214059, 12.507343278686905, + -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7) + +def _gamma_real(x): + _intx = int(x) + if _intx == x: + if _intx <= 0: + #return (-1)**_intx * INF + raise ZeroDivisionError("gamma function pole") + if _intx <= _max_exact_gamma: + return _exact_gamma[_intx] + if x < 0.5: + # TODO: sinpi + return pi / (_sinpi_real(x)*_gamma_real(1-x)) + else: + x -= 1.0 + r = _lanczos_p[0] + for i in range(1, _lanczos_g+2): + r += _lanczos_p[i]/(x+i) + t = x + _lanczos_g + 0.5 + return 2.506628274631000502417 * t**(x+0.5) * math.exp(-t) * r + +def _gamma_complex(x): + if not x.imag: + return complex(_gamma_real(x.real)) + if x.real < 0.5: + # TODO: sinpi + return pi / (_sinpi_complex(x)*_gamma_complex(1-x)) + else: + x -= 1.0 + r = _lanczos_p[0] + for i in range(1, _lanczos_g+2): + r += _lanczos_p[i]/(x+i) + t = x + _lanczos_g + 0.5 + return 2.506628274631000502417 * t**(x+0.5) * cmath.exp(-t) * r + +gamma = _mathfun_real(_gamma_real, _gamma_complex) + +def rgamma(x): + try: + return 1./gamma(x) + except ZeroDivisionError: + return x*0.0 + +def factorial(x): + return gamma(x+1.0) + +def arg(x): + if type(x) is float: + return math.atan2(0.0,x) + return math.atan2(x.imag,x.real) + +# XXX: broken for negatives +def loggamma(x): + if type(x) not in (float, complex): + try: + x = float(x) + except (ValueError, TypeError): + x = complex(x) + try: + xreal = x.real + ximag = x.imag + except AttributeError: # py2.5 + xreal = x + ximag = 0.0 + # Reflection formula + # http://functions.wolfram.com/GammaBetaErf/LogGamma/16/01/01/0003/ + if xreal < 0.0: + if abs(x) < 0.5: + v = log(gamma(x)) + if ximag == 0: + v = v.conjugate() + return v + z = 1-x + try: + re = z.real + im = z.imag + except AttributeError: # py2.5 + re = z + im = 0.0 + refloor = floor(re) + if im == 0.0: + imsign = 0 + elif im < 0.0: + imsign = -1 + else: + imsign = 1 + return (-pi*1j)*abs(refloor)*(1-abs(imsign)) + logpi - \ + log(sinpi(z-refloor)) - loggamma(z) + 1j*pi*refloor*imsign + if x == 1.0 or x == 2.0: + return x*0 + p = 0. + while abs(x) < 11: + p -= log(x) + x += 1.0 + s = 0.918938533204672742 + (x-0.5)*log(x) - x + r = 1./x + r2 = r*r + s += 0.083333333333333333333*r; r *= r2 + s += -0.0027777777777777777778*r; r *= r2 + s += 0.00079365079365079365079*r; r *= r2 + s += -0.0005952380952380952381*r; r *= r2 + s += 0.00084175084175084175084*r; r *= r2 + s += -0.0019175269175269175269*r; r *= r2 + s += 0.0064102564102564102564*r; r *= r2 + s += -0.02955065359477124183*r + return s + p + +_psi_coeff = [ +0.083333333333333333333, +-0.0083333333333333333333, +0.003968253968253968254, +-0.0041666666666666666667, +0.0075757575757575757576, +-0.021092796092796092796, +0.083333333333333333333, +-0.44325980392156862745, +3.0539543302701197438, +-26.456212121212121212] + +def _digamma_real(x): + _intx = int(x) + if _intx == x: + if _intx <= 0: + raise ZeroDivisionError("polygamma pole") + if x < 0.5: + x = 1.0-x + s = pi*cotpi(x) + else: + s = 0.0 + while x < 10.0: + s -= 1.0/x + x += 1.0 + x2 = x**-2 + t = x2 + for c in _psi_coeff: + s -= c*t + if t < 1e-20: + break + t *= x2 + return s + math_log(x) - 0.5/x + +def _digamma_complex(x): + if not x.imag: + return complex(_digamma_real(x.real)) + if x.real < 0.5: + x = 1.0-x + s = pi*cotpi(x) + else: + s = 0.0 + while abs(x) < 10.0: + s -= 1.0/x + x += 1.0 + x2 = x**-2 + t = x2 + for c in _psi_coeff: + s -= c*t + if abs(t) < 1e-20: + break + t *= x2 + return s + cmath.log(x) - 0.5/x + +digamma = _mathfun_real(_digamma_real, _digamma_complex) + +# TODO: could implement complex erf and erfc here. Need +# to find an accurate method (avoiding cancellation) +# for approx. 1 < abs(x) < 9. + +_erfc_coeff_P = [ + 1.0000000161203922312, + 2.1275306946297962644, + 2.2280433377390253297, + 1.4695509105618423961, + 0.66275911699770787537, + 0.20924776504163751585, + 0.045459713768411264339, + 0.0063065951710717791934, + 0.00044560259661560421715][::-1] + +_erfc_coeff_Q = [ + 1.0000000000000000000, + 3.2559100272784894318, + 4.9019435608903239131, + 4.4971472894498014205, + 2.7845640601891186528, + 1.2146026030046904138, + 0.37647108453729465912, + 0.080970149639040548613, + 0.011178148899483545902, + 0.00078981003831980423513][::-1] + +def _polyval(coeffs, x): + p = coeffs[0] + for c in coeffs[1:]: + p = c + x*p + return p + +def _erf_taylor(x): + # Taylor series assuming 0 <= x <= 1 + x2 = x*x + s = t = x + n = 1 + while abs(t) > 1e-17: + t *= x2/n + s -= t/(n+n+1) + n += 1 + t *= x2/n + s += t/(n+n+1) + n += 1 + return 1.1283791670955125739*s + +def _erfc_mid(x): + # Rational approximation assuming 0 <= x <= 9 + return exp(-x*x)*_polyval(_erfc_coeff_P,x)/_polyval(_erfc_coeff_Q,x) + +def _erfc_asymp(x): + # Asymptotic expansion assuming x >= 9 + x2 = x*x + v = exp(-x2)/x*0.56418958354775628695 + r = t = 0.5 / x2 + s = 1.0 + for n in range(1,22,4): + s -= t + t *= r * (n+2) + s += t + t *= r * (n+4) + if abs(t) < 1e-17: + break + return s * v + +def erf(x): + """ + erf of a real number. + """ + x = float(x) + if x != x: + return x + if x < 0.0: + return -erf(-x) + if x >= 1.0: + if x >= 6.0: + return 1.0 + return 1.0 - _erfc_mid(x) + return _erf_taylor(x) + +def erfc(x): + """ + erfc of a real number. + """ + x = float(x) + if x != x: + return x + if x < 0.0: + if x < -6.0: + return 2.0 + return 2.0-erfc(-x) + if x > 9.0: + return _erfc_asymp(x) + if x >= 1.0: + return _erfc_mid(x) + return 1.0 - _erf_taylor(x) + +gauss42 = [\ +(0.99839961899006235, 0.0041059986046490839), +(-0.99839961899006235, 0.0041059986046490839), +(0.9915772883408609, 0.009536220301748501), +(-0.9915772883408609,0.009536220301748501), +(0.97934250806374812, 0.014922443697357493), +(-0.97934250806374812, 0.014922443697357493), +(0.96175936533820439,0.020227869569052644), +(-0.96175936533820439, 0.020227869569052644), +(0.93892355735498811, 0.025422959526113047), +(-0.93892355735498811,0.025422959526113047), +(0.91095972490412735, 0.030479240699603467), +(-0.91095972490412735, 0.030479240699603467), +(0.87802056981217269,0.03536907109759211), +(-0.87802056981217269, 0.03536907109759211), +(0.8402859832618168, 0.040065735180692258), +(-0.8402859832618168,0.040065735180692258), +(0.7979620532554873, 0.044543577771965874), +(-0.7979620532554873, 0.044543577771965874), +(0.75127993568948048,0.048778140792803244), +(-0.75127993568948048, 0.048778140792803244), +(0.70049459055617114, 0.052746295699174064), +(-0.70049459055617114,0.052746295699174064), +(0.64588338886924779, 0.056426369358018376), +(-0.64588338886924779, 0.056426369358018376), +(0.58774459748510932, 0.059798262227586649), +(-0.58774459748510932, 0.059798262227586649), +(0.5263957499311922, 0.062843558045002565), +(-0.5263957499311922, 0.062843558045002565), +(0.46217191207042191, 0.065545624364908975), +(-0.46217191207042191, 0.065545624364908975), +(0.39542385204297503, 0.067889703376521934), +(-0.39542385204297503, 0.067889703376521934), +(0.32651612446541151, 0.069862992492594159), +(-0.32651612446541151, 0.069862992492594159), +(0.25582507934287907, 0.071454714265170971), +(-0.25582507934287907, 0.071454714265170971), +(0.18373680656485453, 0.072656175243804091), +(-0.18373680656485453, 0.072656175243804091), +(0.11064502720851986, 0.073460813453467527), +(-0.11064502720851986, 0.073460813453467527), +(0.036948943165351772, 0.073864234232172879), +(-0.036948943165351772, 0.073864234232172879)] + +EI_ASYMP_CONVERGENCE_RADIUS = 40.0 + +def ei_asymp(z, _e1=False): + r = 1./z + s = t = 1.0 + k = 1 + while 1: + t *= k*r + s += t + if abs(t) < 1e-16: + break + k += 1 + v = s*exp(z)/z + if _e1: + if type(z) is complex: + zreal = z.real + zimag = z.imag + else: + zreal = z + zimag = 0.0 + if zimag == 0.0 and zreal > 0.0: + v += pi*1j + else: + if type(z) is complex: + if z.imag > 0: + v += pi*1j + if z.imag < 0: + v -= pi*1j + return v + +def ei_taylor(z, _e1=False): + s = t = z + k = 2 + while 1: + t = t*z/k + term = t/k + if abs(term) < 1e-17: + break + s += term + k += 1 + s += euler + if _e1: + s += log(-z) + else: + if type(z) is float or z.imag == 0.0: + s += math_log(abs(z)) + else: + s += cmath.log(z) + return s + +def ei(z, _e1=False): + typez = type(z) + if typez not in (float, complex): + try: + z = float(z) + typez = float + except (TypeError, ValueError): + z = complex(z) + typez = complex + if not z: + return -INF + absz = abs(z) + if absz > EI_ASYMP_CONVERGENCE_RADIUS: + return ei_asymp(z, _e1) + elif absz <= 2.0 or (typez is float and z > 0.0): + return ei_taylor(z, _e1) + # Integrate, starting from whichever is smaller of a Taylor + # series value or an asymptotic series value + if typez is complex and z.real > 0.0: + zref = z / absz + ref = ei_taylor(zref, _e1) + else: + zref = EI_ASYMP_CONVERGENCE_RADIUS * z / absz + ref = ei_asymp(zref, _e1) + C = (zref-z)*0.5 + D = (zref+z)*0.5 + s = 0.0 + if type(z) is complex: + _exp = cmath.exp + else: + _exp = math.exp + for x,w in gauss42: + t = C*x+D + s += w*_exp(t)/t + ref -= C*s + return ref + +def e1(z): + # hack to get consistent signs if the imaginary part if 0 + # and signed + typez = type(z) + if type(z) not in (float, complex): + try: + z = float(z) + typez = float + except (TypeError, ValueError): + z = complex(z) + typez = complex + if typez is complex and not z.imag: + z = complex(z.real, 0.0) + # end hack + return -ei(-z, _e1=True) + +_zeta_int = [\ +-0.5, +0.0, +1.6449340668482264365,1.2020569031595942854,1.0823232337111381915, +1.0369277551433699263,1.0173430619844491397,1.0083492773819228268, +1.0040773561979443394,1.0020083928260822144,1.0009945751278180853, +1.0004941886041194646,1.0002460865533080483,1.0001227133475784891, +1.0000612481350587048,1.0000305882363070205,1.0000152822594086519, +1.0000076371976378998,1.0000038172932649998,1.0000019082127165539, +1.0000009539620338728,1.0000004769329867878,1.0000002384505027277, +1.0000001192199259653,1.0000000596081890513,1.0000000298035035147, +1.0000000149015548284] + +_zeta_P = [-3.50000000087575873, -0.701274355654678147, +-0.0672313458590012612, -0.00398731457954257841, +-0.000160948723019303141, -4.67633010038383371e-6, +-1.02078104417700585e-7, -1.68030037095896287e-9, +-1.85231868742346722e-11][::-1] + +_zeta_Q = [1.00000000000000000, -0.936552848762465319, +-0.0588835413263763741, -0.00441498861482948666, +-0.000143416758067432622, -5.10691659585090782e-6, +-9.58813053268913799e-8, -1.72963791443181972e-9, +-1.83527919681474132e-11][::-1] + +_zeta_1 = [3.03768838606128127e-10, -1.21924525236601262e-8, +2.01201845887608893e-7, -1.53917240683468381e-6, +-5.09890411005967954e-7, 0.000122464707271619326, +-0.000905721539353130232, -0.00239315326074843037, +0.084239750013159168, 0.418938517907442414, 0.500000001921884009] + +_zeta_0 = [-3.46092485016748794e-10, -6.42610089468292485e-9, +1.76409071536679773e-7, -1.47141263991560698e-6, -6.38880222546167613e-7, +0.000122641099800668209, -0.000905894913516772796, -0.00239303348507992713, +0.0842396947501199816, 0.418938533204660256, 0.500000000000000052] + +def zeta(s): + """ + Riemann zeta function, real argument + """ + if not isinstance(s, (float, int)): + try: + s = float(s) + except (ValueError, TypeError): + try: + s = complex(s) + if not s.imag: + return complex(zeta(s.real)) + except (ValueError, TypeError): + pass + raise NotImplementedError + if s == 1: + raise ValueError("zeta(1) pole") + if s >= 27: + return 1.0 + 2.0**(-s) + 3.0**(-s) + n = int(s) + if n == s: + if n >= 0: + return _zeta_int[n] + if not (n % 2): + return 0.0 + if s <= 0.0: + return 2.**s*pi**(s-1)*_sinpi_real(0.5*s)*_gamma_real(1-s)*zeta(1-s) + if s <= 2.0: + if s <= 1.0: + return _polyval(_zeta_0,s)/(s-1) + return _polyval(_zeta_1,s)/(s-1) + z = _polyval(_zeta_P,s) / _polyval(_zeta_Q,s) + return 1.0 + 2.0**(-s) + 3.0**(-s) + 4.0**(-s)*z diff --git a/venv/lib/python3.10/site-packages/mpmath/matrices/__init__.py b/venv/lib/python3.10/site-packages/mpmath/matrices/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..293697b9fcf8bd82d58ac4ff45acd73fadac82f9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/matrices/__init__.py @@ -0,0 +1,2 @@ +from . import eigen # to set methods +from . import eigen_symmetric # to set methods diff --git a/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cd030bf73cdc79cdee657a3d18932094582d54b Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/calculus.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/calculus.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26e09a07db54490ad1c6e9a078d930edae610307 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/calculus.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/eigen.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/eigen.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad6feddf771c2578360599377862e00b22c798d7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/eigen.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/eigen_symmetric.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/eigen_symmetric.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b3506e197d81b1b67f3bc96589c60796c9f6794 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/eigen_symmetric.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/linalg.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/linalg.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7df8e19b754ae43a08de3216d722bae04a5bffb Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/linalg.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/matrices.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/matrices.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1507b8ca50cecd2071f83a68451f84253c84eee Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/matrices/__pycache__/matrices.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/matrices/calculus.py b/venv/lib/python3.10/site-packages/mpmath/matrices/calculus.py new file mode 100644 index 0000000000000000000000000000000000000000..7fae2a7a9a29898241ed41810331b480ff70798f --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/matrices/calculus.py @@ -0,0 +1,531 @@ +from ..libmp.backend import xrange + +# TODO: should use diagonalization-based algorithms + +class MatrixCalculusMethods(object): + + def _exp_pade(ctx, a): + """ + Exponential of a matrix using Pade approximants. + + See G. H. Golub, C. F. van Loan 'Matrix Computations', + third Ed., page 572 + + TODO: + - find a good estimate for q + - reduce the number of matrix multiplications to improve + performance + """ + def eps_pade(p): + return ctx.mpf(2)**(3-2*p) * \ + ctx.factorial(p)**2/(ctx.factorial(2*p)**2 * (2*p + 1)) + q = 4 + extraq = 8 + while 1: + if eps_pade(q) < ctx.eps: + break + q += 1 + q += extraq + j = int(max(1, ctx.mag(ctx.mnorm(a,'inf')))) + extra = q + prec = ctx.prec + ctx.dps += extra + 3 + try: + a = a/2**j + na = a.rows + den = ctx.eye(na) + num = ctx.eye(na) + x = ctx.eye(na) + c = ctx.mpf(1) + for k in range(1, q+1): + c *= ctx.mpf(q - k + 1)/((2*q - k + 1) * k) + x = a*x + cx = c*x + num += cx + den += (-1)**k * cx + f = ctx.lu_solve_mat(den, num) + for k in range(j): + f = f*f + finally: + ctx.prec = prec + return f*1 + + def expm(ctx, A, method='taylor'): + r""" + Computes the matrix exponential of a square matrix `A`, which is defined + by the power series + + .. math :: + + \exp(A) = I + A + \frac{A^2}{2!} + \frac{A^3}{3!} + \ldots + + With method='taylor', the matrix exponential is computed + using the Taylor series. With method='pade', Pade approximants + are used instead. + + **Examples** + + Basic examples:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> expm(zeros(3)) + [1.0 0.0 0.0] + [0.0 1.0 0.0] + [0.0 0.0 1.0] + >>> expm(eye(3)) + [2.71828182845905 0.0 0.0] + [ 0.0 2.71828182845905 0.0] + [ 0.0 0.0 2.71828182845905] + >>> expm([[1,1,0],[1,0,1],[0,1,0]]) + [ 3.86814500615414 2.26812870852145 0.841130841230196] + [ 2.26812870852145 2.44114713886289 1.42699786729125] + [0.841130841230196 1.42699786729125 1.6000162976327] + >>> expm([[1,1,0],[1,0,1],[0,1,0]], method='pade') + [ 3.86814500615414 2.26812870852145 0.841130841230196] + [ 2.26812870852145 2.44114713886289 1.42699786729125] + [0.841130841230196 1.42699786729125 1.6000162976327] + >>> expm([[1+j, 0], [1+j,1]]) + [(1.46869393991589 + 2.28735528717884j) 0.0] + [ (1.03776739863568 + 3.536943175722j) (2.71828182845905 + 0.0j)] + + Matrices with large entries are allowed:: + + >>> expm(matrix([[1,2],[2,3]])**25) + [5.65024064048415e+2050488462815550 9.14228140091932e+2050488462815550] + [9.14228140091932e+2050488462815550 1.47925220414035e+2050488462815551] + + The identity `\exp(A+B) = \exp(A) \exp(B)` does not hold for + noncommuting matrices:: + + >>> A = hilbert(3) + >>> B = A + eye(3) + >>> chop(mnorm(A*B - B*A)) + 0.0 + >>> chop(mnorm(expm(A+B) - expm(A)*expm(B))) + 0.0 + >>> B = A + ones(3) + >>> mnorm(A*B - B*A) + 1.8 + >>> mnorm(expm(A+B) - expm(A)*expm(B)) + 42.0927851137247 + + """ + if method == 'pade': + prec = ctx.prec + try: + A = ctx.matrix(A) + ctx.prec += 2*A.rows + res = ctx._exp_pade(A) + finally: + ctx.prec = prec + return res + A = ctx.matrix(A) + prec = ctx.prec + j = int(max(1, ctx.mag(ctx.mnorm(A,'inf')))) + j += int(0.5*prec**0.5) + try: + ctx.prec += 10 + 2*j + tol = +ctx.eps + A = A/2**j + T = A + Y = A**0 + A + k = 2 + while 1: + T *= A * (1/ctx.mpf(k)) + if ctx.mnorm(T, 'inf') < tol: + break + Y += T + k += 1 + for k in xrange(j): + Y = Y*Y + finally: + ctx.prec = prec + Y *= 1 + return Y + + def cosm(ctx, A): + r""" + Gives the cosine of a square matrix `A`, defined in analogy + with the matrix exponential. + + Examples:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> X = eye(3) + >>> cosm(X) + [0.54030230586814 0.0 0.0] + [ 0.0 0.54030230586814 0.0] + [ 0.0 0.0 0.54030230586814] + >>> X = hilbert(3) + >>> cosm(X) + [ 0.424403834569555 -0.316643413047167 -0.221474945949293] + [-0.316643413047167 0.820646708837824 -0.127183694770039] + [-0.221474945949293 -0.127183694770039 0.909236687217541] + >>> X = matrix([[1+j,-2],[0,-j]]) + >>> cosm(X) + [(0.833730025131149 - 0.988897705762865j) (1.07485840848393 - 0.17192140544213j)] + [ 0.0 (1.54308063481524 + 0.0j)] + """ + B = 0.5 * (ctx.expm(A*ctx.j) + ctx.expm(A*(-ctx.j))) + if not sum(A.apply(ctx.im).apply(abs)): + B = B.apply(ctx.re) + return B + + def sinm(ctx, A): + r""" + Gives the sine of a square matrix `A`, defined in analogy + with the matrix exponential. + + Examples:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> X = eye(3) + >>> sinm(X) + [0.841470984807897 0.0 0.0] + [ 0.0 0.841470984807897 0.0] + [ 0.0 0.0 0.841470984807897] + >>> X = hilbert(3) + >>> sinm(X) + [0.711608512150994 0.339783913247439 0.220742837314741] + [0.339783913247439 0.244113865695532 0.187231271174372] + [0.220742837314741 0.187231271174372 0.155816730769635] + >>> X = matrix([[1+j,-2],[0,-j]]) + >>> sinm(X) + [(1.29845758141598 + 0.634963914784736j) (-1.96751511930922 + 0.314700021761367j)] + [ 0.0 (0.0 - 1.1752011936438j)] + """ + B = (-0.5j) * (ctx.expm(A*ctx.j) - ctx.expm(A*(-ctx.j))) + if not sum(A.apply(ctx.im).apply(abs)): + B = B.apply(ctx.re) + return B + + def _sqrtm_rot(ctx, A, _may_rotate): + # If the iteration fails to converge, cheat by performing + # a rotation by a complex number + u = ctx.j**0.3 + return ctx.sqrtm(u*A, _may_rotate) / ctx.sqrt(u) + + def sqrtm(ctx, A, _may_rotate=2): + r""" + Computes a square root of the square matrix `A`, i.e. returns + a matrix `B = A^{1/2}` such that `B^2 = A`. The square root + of a matrix, if it exists, is not unique. + + **Examples** + + Square roots of some simple matrices:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> sqrtm([[1,0], [0,1]]) + [1.0 0.0] + [0.0 1.0] + >>> sqrtm([[0,0], [0,0]]) + [0.0 0.0] + [0.0 0.0] + >>> sqrtm([[2,0],[0,1]]) + [1.4142135623731 0.0] + [ 0.0 1.0] + >>> sqrtm([[1,1],[1,0]]) + [ (0.920442065259926 - 0.21728689675164j) (0.568864481005783 + 0.351577584254143j)] + [(0.568864481005783 + 0.351577584254143j) (0.351577584254143 - 0.568864481005783j)] + >>> sqrtm([[1,0],[0,1]]) + [1.0 0.0] + [0.0 1.0] + >>> sqrtm([[-1,0],[0,1]]) + [(0.0 - 1.0j) 0.0] + [ 0.0 (1.0 + 0.0j)] + >>> sqrtm([[j,0],[0,j]]) + [(0.707106781186547 + 0.707106781186547j) 0.0] + [ 0.0 (0.707106781186547 + 0.707106781186547j)] + + A square root of a rotation matrix, giving the corresponding + half-angle rotation matrix:: + + >>> t1 = 0.75 + >>> t2 = t1 * 0.5 + >>> A1 = matrix([[cos(t1), -sin(t1)], [sin(t1), cos(t1)]]) + >>> A2 = matrix([[cos(t2), -sin(t2)], [sin(t2), cos(t2)]]) + >>> sqrtm(A1) + [0.930507621912314 -0.366272529086048] + [0.366272529086048 0.930507621912314] + >>> A2 + [0.930507621912314 -0.366272529086048] + [0.366272529086048 0.930507621912314] + + The identity `(A^2)^{1/2} = A` does not necessarily hold:: + + >>> A = matrix([[4,1,4],[7,8,9],[10,2,11]]) + >>> sqrtm(A**2) + [ 4.0 1.0 4.0] + [ 7.0 8.0 9.0] + [10.0 2.0 11.0] + >>> sqrtm(A)**2 + [ 4.0 1.0 4.0] + [ 7.0 8.0 9.0] + [10.0 2.0 11.0] + >>> A = matrix([[-4,1,4],[7,-8,9],[10,2,11]]) + >>> sqrtm(A**2) + [ 7.43715112194995 -0.324127569985474 1.8481718827526] + [-0.251549715716942 9.32699765900402 2.48221180985147] + [ 4.11609388833616 0.775751877098258 13.017955697342] + >>> chop(sqrtm(A)**2) + [-4.0 1.0 4.0] + [ 7.0 -8.0 9.0] + [10.0 2.0 11.0] + + For some matrices, a square root does not exist:: + + >>> sqrtm([[0,1], [0,0]]) + Traceback (most recent call last): + ... + ZeroDivisionError: matrix is numerically singular + + Two examples from the documentation for Matlab's ``sqrtm``:: + + >>> mp.dps = 15; mp.pretty = True + >>> sqrtm([[7,10],[15,22]]) + [1.56669890360128 1.74077655955698] + [2.61116483933547 4.17786374293675] + >>> + >>> X = matrix(\ + ... [[5,-4,1,0,0], + ... [-4,6,-4,1,0], + ... [1,-4,6,-4,1], + ... [0,1,-4,6,-4], + ... [0,0,1,-4,5]]) + >>> Y = matrix(\ + ... [[2,-1,-0,-0,-0], + ... [-1,2,-1,0,-0], + ... [0,-1,2,-1,0], + ... [-0,0,-1,2,-1], + ... [-0,-0,-0,-1,2]]) + >>> mnorm(sqrtm(X) - Y) + 4.53155328326114e-19 + + """ + A = ctx.matrix(A) + # Trivial + if A*0 == A: + return A + prec = ctx.prec + if _may_rotate: + d = ctx.det(A) + if abs(ctx.im(d)) < 16*ctx.eps and ctx.re(d) < 0: + return ctx._sqrtm_rot(A, _may_rotate-1) + try: + ctx.prec += 10 + tol = ctx.eps * 128 + Y = A + Z = I = A**0 + k = 0 + # Denman-Beavers iteration + while 1: + Yprev = Y + try: + Y, Z = 0.5*(Y+ctx.inverse(Z)), 0.5*(Z+ctx.inverse(Y)) + except ZeroDivisionError: + if _may_rotate: + Y = ctx._sqrtm_rot(A, _may_rotate-1) + break + else: + raise + mag1 = ctx.mnorm(Y-Yprev, 'inf') + mag2 = ctx.mnorm(Y, 'inf') + if mag1 <= mag2*tol: + break + if _may_rotate and k > 6 and not mag1 < mag2 * 0.001: + return ctx._sqrtm_rot(A, _may_rotate-1) + k += 1 + if k > ctx.prec: + raise ctx.NoConvergence + finally: + ctx.prec = prec + Y *= 1 + return Y + + def logm(ctx, A): + r""" + Computes a logarithm of the square matrix `A`, i.e. returns + a matrix `B = \log(A)` such that `\exp(B) = A`. The logarithm + of a matrix, if it exists, is not unique. + + **Examples** + + Logarithms of some simple matrices:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> X = eye(3) + >>> logm(X) + [0.0 0.0 0.0] + [0.0 0.0 0.0] + [0.0 0.0 0.0] + >>> logm(2*X) + [0.693147180559945 0.0 0.0] + [ 0.0 0.693147180559945 0.0] + [ 0.0 0.0 0.693147180559945] + >>> logm(expm(X)) + [1.0 0.0 0.0] + [0.0 1.0 0.0] + [0.0 0.0 1.0] + + A logarithm of a complex matrix:: + + >>> X = matrix([[2+j, 1, 3], [1-j, 1-2*j, 1], [-4, -5, j]]) + >>> B = logm(X) + >>> nprint(B) + [ (0.808757 + 0.107759j) (2.20752 + 0.202762j) (1.07376 - 0.773874j)] + [ (0.905709 - 0.107795j) (0.0287395 - 0.824993j) (0.111619 + 0.514272j)] + [(-0.930151 + 0.399512j) (-2.06266 - 0.674397j) (0.791552 + 0.519839j)] + >>> chop(expm(B)) + [(2.0 + 1.0j) 1.0 3.0] + [(1.0 - 1.0j) (1.0 - 2.0j) 1.0] + [ -4.0 -5.0 (0.0 + 1.0j)] + + A matrix `X` close to the identity matrix, for which + `\log(\exp(X)) = \exp(\log(X)) = X` holds:: + + >>> X = eye(3) + hilbert(3)/4 + >>> X + [ 1.25 0.125 0.0833333333333333] + [ 0.125 1.08333333333333 0.0625] + [0.0833333333333333 0.0625 1.05] + >>> logm(expm(X)) + [ 1.25 0.125 0.0833333333333333] + [ 0.125 1.08333333333333 0.0625] + [0.0833333333333333 0.0625 1.05] + >>> expm(logm(X)) + [ 1.25 0.125 0.0833333333333333] + [ 0.125 1.08333333333333 0.0625] + [0.0833333333333333 0.0625 1.05] + + A logarithm of a rotation matrix, giving back the angle of + the rotation:: + + >>> t = 3.7 + >>> A = matrix([[cos(t),sin(t)],[-sin(t),cos(t)]]) + >>> chop(logm(A)) + [ 0.0 -2.58318530717959] + [2.58318530717959 0.0] + >>> (2*pi-t) + 2.58318530717959 + + For some matrices, a logarithm does not exist:: + + >>> logm([[1,0], [0,0]]) + Traceback (most recent call last): + ... + ZeroDivisionError: matrix is numerically singular + + Logarithm of a matrix with large entries:: + + >>> logm(hilbert(3) * 10**20).apply(re) + [ 45.5597513593433 1.27721006042799 0.317662687717978] + [ 1.27721006042799 42.5222778973542 2.24003708791604] + [0.317662687717978 2.24003708791604 42.395212822267] + + """ + A = ctx.matrix(A) + prec = ctx.prec + try: + ctx.prec += 10 + tol = ctx.eps * 128 + I = A**0 + B = A + n = 0 + while 1: + B = ctx.sqrtm(B) + n += 1 + if ctx.mnorm(B-I, 'inf') < 0.125: + break + T = X = B-I + L = X*0 + k = 1 + while 1: + if k & 1: + L += T / k + else: + L -= T / k + T *= X + if ctx.mnorm(T, 'inf') < tol: + break + k += 1 + if k > ctx.prec: + raise ctx.NoConvergence + finally: + ctx.prec = prec + L *= 2**n + return L + + def powm(ctx, A, r): + r""" + Computes `A^r = \exp(A \log r)` for a matrix `A` and complex + number `r`. + + **Examples** + + Powers and inverse powers of a matrix:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = True + >>> A = matrix([[4,1,4],[7,8,9],[10,2,11]]) + >>> powm(A, 2) + [ 63.0 20.0 69.0] + [174.0 89.0 199.0] + [164.0 48.0 179.0] + >>> chop(powm(powm(A, 4), 1/4.)) + [ 4.0 1.0 4.0] + [ 7.0 8.0 9.0] + [10.0 2.0 11.0] + >>> powm(extraprec(20)(powm)(A, -4), -1/4.) + [ 4.0 1.0 4.0] + [ 7.0 8.0 9.0] + [10.0 2.0 11.0] + >>> chop(powm(powm(A, 1+0.5j), 1/(1+0.5j))) + [ 4.0 1.0 4.0] + [ 7.0 8.0 9.0] + [10.0 2.0 11.0] + >>> powm(extraprec(5)(powm)(A, -1.5), -1/(1.5)) + [ 4.0 1.0 4.0] + [ 7.0 8.0 9.0] + [10.0 2.0 11.0] + + A Fibonacci-generating matrix:: + + >>> powm([[1,1],[1,0]], 10) + [89.0 55.0] + [55.0 34.0] + >>> fib(10) + 55.0 + >>> powm([[1,1],[1,0]], 6.5) + [(16.5166626964253 - 0.0121089837381789j) (10.2078589271083 + 0.0195927472575932j)] + [(10.2078589271083 + 0.0195927472575932j) (6.30880376931698 - 0.0317017309957721j)] + >>> (phi**6.5 - (1-phi)**6.5)/sqrt(5) + (10.2078589271083 - 0.0195927472575932j) + >>> powm([[1,1],[1,0]], 6.2) + [ (14.3076953002666 - 0.008222855781077j) (8.81733464837593 + 0.0133048601383712j)] + [(8.81733464837593 + 0.0133048601383712j) (5.49036065189071 - 0.0215277159194482j)] + >>> (phi**6.2 - (1-phi)**6.2)/sqrt(5) + (8.81733464837593 - 0.0133048601383712j) + + """ + A = ctx.matrix(A) + r = ctx.convert(r) + prec = ctx.prec + try: + ctx.prec += 10 + if ctx.isint(r): + v = A ** int(r) + elif ctx.isint(r*2): + y = int(r*2) + v = ctx.sqrtm(A) ** y + else: + v = ctx.expm(r*ctx.logm(A)) + finally: + ctx.prec = prec + v *= 1 + return v diff --git a/venv/lib/python3.10/site-packages/mpmath/matrices/eigen.py b/venv/lib/python3.10/site-packages/mpmath/matrices/eigen.py new file mode 100644 index 0000000000000000000000000000000000000000..885d604203195b695183329acc637de91aeaf5ea --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/matrices/eigen.py @@ -0,0 +1,877 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +################################################################################################## +# module for the eigenvalue problem +# Copyright 2013 Timo Hartmann (thartmann15 at gmail.com) +# +# todo: +# - implement balancing +# - agressive early deflation +# +################################################################################################## + +""" +The eigenvalue problem +---------------------- + +This file contains routines for the eigenvalue problem. + +high level routines: + + hessenberg : reduction of a real or complex square matrix to upper Hessenberg form + schur : reduction of a real or complex square matrix to upper Schur form + eig : eigenvalues and eigenvectors of a real or complex square matrix + +low level routines: + + hessenberg_reduce_0 : reduction of a real or complex square matrix to upper Hessenberg form + hessenberg_reduce_1 : auxiliary routine to hessenberg_reduce_0 + qr_step : a single implicitly shifted QR step for an upper Hessenberg matrix + hessenberg_qr : Schur decomposition of an upper Hessenberg matrix + eig_tr_r : right eigenvectors of an upper triangular matrix + eig_tr_l : left eigenvectors of an upper triangular matrix +""" + +from ..libmp.backend import xrange + +class Eigen(object): + pass + +def defun(f): + setattr(Eigen, f.__name__, f) + return f + +def hessenberg_reduce_0(ctx, A, T): + """ + This routine computes the (upper) Hessenberg decomposition of a square matrix A. + Given A, an unitary matrix Q is calculated such that + + Q' A Q = H and Q' Q = Q Q' = 1 + + where H is an upper Hessenberg matrix, meaning that it only contains zeros + below the first subdiagonal. Here ' denotes the hermitian transpose (i.e. + transposition and conjugation). + + parameters: + A (input/output) On input, A contains the square matrix A of + dimension (n,n). On output, A contains a compressed representation + of Q and H. + T (output) An array of length n containing the first elements of + the Householder reflectors. + """ + + # internally we work with householder reflections from the right. + # let u be a row vector (i.e. u[i]=A[i,:i]). then + # Q is build up by reflectors of the type (1-v'v) where v is a suitable + # modification of u. these reflectors are applyed to A from the right. + # because we work with reflectors from the right we have to start with + # the bottom row of A and work then upwards (this corresponds to + # some kind of RQ decomposition). + # the first part of the vectors v (i.e. A[i,:(i-1)]) are stored as row vectors + # in the lower left part of A (excluding the diagonal and subdiagonal). + # the last entry of v is stored in T. + # the upper right part of A (including diagonal and subdiagonal) becomes H. + + + n = A.rows + if n <= 2: return + + for i in xrange(n-1, 1, -1): + + # scale the vector + + scale = 0 + for k in xrange(0, i): + scale += abs(ctx.re(A[i,k])) + abs(ctx.im(A[i,k])) + + scale_inv = 0 + if scale != 0: + scale_inv = 1 / scale + + if scale == 0 or ctx.isinf(scale_inv): + # sadly there are floating point numbers not equal to zero whose reciprocal is infinity + T[i] = 0 + A[i,i-1] = 0 + continue + + # calculate parameters for housholder transformation + + H = 0 + for k in xrange(0, i): + A[i,k] *= scale_inv + rr = ctx.re(A[i,k]) + ii = ctx.im(A[i,k]) + H += rr * rr + ii * ii + + F = A[i,i-1] + f = abs(F) + G = ctx.sqrt(H) + A[i,i-1] = - G * scale + + if f == 0: + T[i] = G + else: + ff = F / f + T[i] = F + G * ff + A[i,i-1] *= ff + + H += G * f + H = 1 / ctx.sqrt(H) + + T[i] *= H + for k in xrange(0, i - 1): + A[i,k] *= H + + for j in xrange(0, i): + # apply housholder transformation (from right) + + G = ctx.conj(T[i]) * A[j,i-1] + for k in xrange(0, i-1): + G += ctx.conj(A[i,k]) * A[j,k] + + A[j,i-1] -= G * T[i] + for k in xrange(0, i-1): + A[j,k] -= G * A[i,k] + + for j in xrange(0, n): + # apply housholder transformation (from left) + + G = T[i] * A[i-1,j] + for k in xrange(0, i-1): + G += A[i,k] * A[k,j] + + A[i-1,j] -= G * ctx.conj(T[i]) + for k in xrange(0, i-1): + A[k,j] -= G * ctx.conj(A[i,k]) + + + +def hessenberg_reduce_1(ctx, A, T): + """ + This routine forms the unitary matrix Q described in hessenberg_reduce_0. + + parameters: + A (input/output) On input, A is the same matrix as delivered by + hessenberg_reduce_0. On output, A is set to Q. + + T (input) On input, T is the same array as delivered by hessenberg_reduce_0. + """ + + n = A.rows + + if n == 1: + A[0,0] = 1 + return + + A[0,0] = A[1,1] = 1 + A[0,1] = A[1,0] = 0 + + for i in xrange(2, n): + if T[i] != 0: + + for j in xrange(0, i): + G = T[i] * A[i-1,j] + for k in xrange(0, i-1): + G += A[i,k] * A[k,j] + + A[i-1,j] -= G * ctx.conj(T[i]) + for k in xrange(0, i-1): + A[k,j] -= G * ctx.conj(A[i,k]) + + A[i,i] = 1 + for j in xrange(0, i): + A[j,i] = A[i,j] = 0 + + + +@defun +def hessenberg(ctx, A, overwrite_a = False): + """ + This routine computes the Hessenberg decomposition of a square matrix A. + Given A, an unitary matrix Q is determined such that + + Q' A Q = H and Q' Q = Q Q' = 1 + + where H is an upper right Hessenberg matrix. Here ' denotes the hermitian + transpose (i.e. transposition and conjugation). + + input: + A : a real or complex square matrix + overwrite_a : if true, allows modification of A which may improve + performance. if false, A is not modified. + + output: + Q : an unitary matrix + H : an upper right Hessenberg matrix + + example: + >>> from mpmath import mp + >>> A = mp.matrix([[3, -1, 2], [2, 5, -5], [-2, -3, 7]]) + >>> Q, H = mp.hessenberg(A) + >>> mp.nprint(H, 3) # doctest:+SKIP + [ 3.15 2.23 4.44] + [-0.769 4.85 3.05] + [ 0.0 3.61 7.0] + >>> print(mp.chop(A - Q * H * Q.transpose_conj())) + [0.0 0.0 0.0] + [0.0 0.0 0.0] + [0.0 0.0 0.0] + + return value: (Q, H) + """ + + n = A.rows + + if n == 1: + return (ctx.matrix([[1]]), A) + + if not overwrite_a: + A = A.copy() + + T = ctx.matrix(n, 1) + + hessenberg_reduce_0(ctx, A, T) + Q = A.copy() + hessenberg_reduce_1(ctx, Q, T) + + for x in xrange(n): + for y in xrange(x+2, n): + A[y,x] = 0 + + return Q, A + + +########################################################################### + + +def qr_step(ctx, n0, n1, A, Q, shift): + """ + This subroutine executes a single implicitly shifted QR step applied to an + upper Hessenberg matrix A. Given A and shift as input, first an QR + decomposition is calculated: + + Q R = A - shift * 1 . + + The output is then following matrix: + + R Q + shift * 1 + + parameters: + n0, n1 (input) Two integers which specify the submatrix A[n0:n1,n0:n1] + on which this subroutine operators. The subdiagonal elements + to the left and below this submatrix must be deflated (i.e. zero). + following restriction is imposed: n1>=n0+2 + A (input/output) On input, A is an upper Hessenberg matrix. + On output, A is replaced by "R Q + shift * 1" + Q (input/output) The parameter Q is multiplied by the unitary matrix + Q arising from the QR decomposition. Q can also be false, in which + case the unitary matrix Q is not computated. + shift (input) a complex number specifying the shift. idealy close to an + eigenvalue of the bottemmost part of the submatrix A[n0:n1,n0:n1]. + + references: + Stoer, Bulirsch - Introduction to Numerical Analysis. + Kresser : Numerical Methods for General and Structured Eigenvalue Problems + """ + + # implicitly shifted and bulge chasing is explained at p.398/399 in "Stoer, Bulirsch - Introduction to Numerical Analysis" + # for bulge chasing see also "Watkins - The Matrix Eigenvalue Problem" sec.4.5,p.173 + + # the Givens rotation we used is determined as follows: let c,s be two complex + # numbers. then we have following relation: + # + # v = sqrt(|c|^2 + |s|^2) + # + # 1/v [ c~ s~] [c] = [v] + # [-s c ] [s] [0] + # + # the matrix on the left is our Givens rotation. + + n = A.rows + + # first step + + # calculate givens rotation + c = A[n0 ,n0] - shift + s = A[n0+1,n0] + + v = ctx.hypot(ctx.hypot(ctx.re(c), ctx.im(c)), ctx.hypot(ctx.re(s), ctx.im(s))) + + if v == 0: + v = 1 + c = 1 + s = 0 + else: + c /= v + s /= v + + cc = ctx.conj(c) + cs = ctx.conj(s) + + for k in xrange(n0, n): + # apply givens rotation from the left + x = A[n0 ,k] + y = A[n0+1,k] + A[n0 ,k] = cc * x + cs * y + A[n0+1,k] = c * y - s * x + + for k in xrange(min(n1, n0+3)): + # apply givens rotation from the right + x = A[k,n0 ] + y = A[k,n0+1] + A[k,n0 ] = c * x + s * y + A[k,n0+1] = cc * y - cs * x + + if not isinstance(Q, bool): + for k in xrange(n): + # eigenvectors + x = Q[k,n0 ] + y = Q[k,n0+1] + Q[k,n0 ] = c * x + s * y + Q[k,n0+1] = cc * y - cs * x + + # chase the bulge + + for j in xrange(n0, n1 - 2): + # calculate givens rotation + + c = A[j+1,j] + s = A[j+2,j] + + v = ctx.hypot(ctx.hypot(ctx.re(c), ctx.im(c)), ctx.hypot(ctx.re(s), ctx.im(s))) + + if v == 0: + A[j+1,j] = 0 + v = 1 + c = 1 + s = 0 + else: + A[j+1,j] = v + c /= v + s /= v + + A[j+2,j] = 0 + + cc = ctx.conj(c) + cs = ctx.conj(s) + + for k in xrange(j+1, n): + # apply givens rotation from the left + x = A[j+1,k] + y = A[j+2,k] + A[j+1,k] = cc * x + cs * y + A[j+2,k] = c * y - s * x + + for k in xrange(0, min(n1, j+4)): + # apply givens rotation from the right + x = A[k,j+1] + y = A[k,j+2] + A[k,j+1] = c * x + s * y + A[k,j+2] = cc * y - cs * x + + if not isinstance(Q, bool): + for k in xrange(0, n): + # eigenvectors + x = Q[k,j+1] + y = Q[k,j+2] + Q[k,j+1] = c * x + s * y + Q[k,j+2] = cc * y - cs * x + + + +def hessenberg_qr(ctx, A, Q): + """ + This routine computes the Schur decomposition of an upper Hessenberg matrix A. + Given A, an unitary matrix Q is determined such that + + Q' A Q = R and Q' Q = Q Q' = 1 + + where R is an upper right triangular matrix. Here ' denotes the hermitian + transpose (i.e. transposition and conjugation). + + parameters: + A (input/output) On input, A contains an upper Hessenberg matrix. + On output, A is replace by the upper right triangluar matrix R. + + Q (input/output) The parameter Q is multiplied by the unitary + matrix Q arising from the Schur decomposition. Q can also be + false, in which case the unitary matrix Q is not computated. + """ + + n = A.rows + + norm = 0 + for x in xrange(n): + for y in xrange(min(x+2, n)): + norm += ctx.re(A[y,x]) ** 2 + ctx.im(A[y,x]) ** 2 + norm = ctx.sqrt(norm) / n + + if norm == 0: + return + + n0 = 0 + n1 = n + + eps = ctx.eps / (100 * n) + maxits = ctx.dps * 4 + + its = totalits = 0 + + while 1: + # kressner p.32 algo 3 + # the active submatrix is A[n0:n1,n0:n1] + + k = n0 + + while k + 1 < n1: + s = abs(ctx.re(A[k,k])) + abs(ctx.im(A[k,k])) + abs(ctx.re(A[k+1,k+1])) + abs(ctx.im(A[k+1,k+1])) + if s < eps * norm: + s = norm + if abs(A[k+1,k]) < eps * s: + break + k += 1 + + if k + 1 < n1: + # deflation found at position (k+1, k) + + A[k+1,k] = 0 + n0 = k + 1 + + its = 0 + + if n0 + 1 >= n1: + # block of size at most two has converged + n0 = 0 + n1 = k + 1 + if n1 < 2: + # QR algorithm has converged + return + else: + if (its % 30) == 10: + # exceptional shift + shift = A[n1-1,n1-2] + elif (its % 30) == 20: + # exceptional shift + shift = abs(A[n1-1,n1-2]) + elif (its % 30) == 29: + # exceptional shift + shift = norm + else: + # A = [ a b ] det(x-A)=x*x-x*tr(A)+det(A) + # [ c d ] + # + # eigenvalues bad: (tr(A)+sqrt((tr(A))**2-4*det(A)))/2 + # bad because of cancellation if |c| is small and |a-d| is small, too. + # + # eigenvalues good: (a+d+sqrt((a-d)**2+4*b*c))/2 + + t = A[n1-2,n1-2] + A[n1-1,n1-1] + s = (A[n1-1,n1-1] - A[n1-2,n1-2]) ** 2 + 4 * A[n1-1,n1-2] * A[n1-2,n1-1] + if ctx.re(s) > 0: + s = ctx.sqrt(s) + else: + s = ctx.sqrt(-s) * 1j + a = (t + s) / 2 + b = (t - s) / 2 + if abs(A[n1-1,n1-1] - a) > abs(A[n1-1,n1-1] - b): + shift = b + else: + shift = a + + its += 1 + totalits += 1 + + qr_step(ctx, n0, n1, A, Q, shift) + + if its > maxits: + raise RuntimeError("qr: failed to converge after %d steps" % its) + + +@defun +def schur(ctx, A, overwrite_a = False): + """ + This routine computes the Schur decomposition of a square matrix A. + Given A, an unitary matrix Q is determined such that + + Q' A Q = R and Q' Q = Q Q' = 1 + + where R is an upper right triangular matrix. Here ' denotes the + hermitian transpose (i.e. transposition and conjugation). + + input: + A : a real or complex square matrix + overwrite_a : if true, allows modification of A which may improve + performance. if false, A is not modified. + + output: + Q : an unitary matrix + R : an upper right triangular matrix + + return value: (Q, R) + + example: + >>> from mpmath import mp + >>> A = mp.matrix([[3, -1, 2], [2, 5, -5], [-2, -3, 7]]) + >>> Q, R = mp.schur(A) + >>> mp.nprint(R, 3) # doctest:+SKIP + [2.0 0.417 -2.53] + [0.0 4.0 -4.74] + [0.0 0.0 9.0] + >>> print(mp.chop(A - Q * R * Q.transpose_conj())) + [0.0 0.0 0.0] + [0.0 0.0 0.0] + [0.0 0.0 0.0] + + warning: The Schur decomposition is not unique. + """ + + n = A.rows + + if n == 1: + return (ctx.matrix([[1]]), A) + + if not overwrite_a: + A = A.copy() + + T = ctx.matrix(n, 1) + + hessenberg_reduce_0(ctx, A, T) + Q = A.copy() + hessenberg_reduce_1(ctx, Q, T) + + for x in xrange(n): + for y in xrange(x + 2, n): + A[y,x] = 0 + + hessenberg_qr(ctx, A, Q) + + return Q, A + + +def eig_tr_r(ctx, A): + """ + This routine calculates the right eigenvectors of an upper right triangular matrix. + + input: + A an upper right triangular matrix + + output: + ER a matrix whose columns form the right eigenvectors of A + + return value: ER + """ + + # this subroutine is inspired by the lapack routines ctrevc.f,clatrs.f + + n = A.rows + + ER = ctx.eye(n) + + eps = ctx.eps + + unfl = ctx.ldexp(ctx.one, -ctx.prec * 30) + # since mpmath effectively has no limits on the exponent, we simply scale doubles up + # original double has prec*20 + + smlnum = unfl * (n / eps) + simin = 1 / ctx.sqrt(eps) + + rmax = 1 + + for i in xrange(1, n): + s = A[i,i] + + smin = max(eps * abs(s), smlnum) + + for j in xrange(i - 1, -1, -1): + + r = 0 + for k in xrange(j + 1, i + 1): + r += A[j,k] * ER[k,i] + + t = A[j,j] - s + if abs(t) < smin: + t = smin + + r = -r / t + ER[j,i] = r + + rmax = max(rmax, abs(r)) + if rmax > simin: + for k in xrange(j, i+1): + ER[k,i] /= rmax + rmax = 1 + + if rmax != 1: + for k in xrange(0, i + 1): + ER[k,i] /= rmax + + return ER + +def eig_tr_l(ctx, A): + """ + This routine calculates the left eigenvectors of an upper right triangular matrix. + + input: + A an upper right triangular matrix + + output: + EL a matrix whose rows form the left eigenvectors of A + + return value: EL + """ + + n = A.rows + + EL = ctx.eye(n) + + eps = ctx.eps + + unfl = ctx.ldexp(ctx.one, -ctx.prec * 30) + # since mpmath effectively has no limits on the exponent, we simply scale doubles up + # original double has prec*20 + + smlnum = unfl * (n / eps) + simin = 1 / ctx.sqrt(eps) + + rmax = 1 + + for i in xrange(0, n - 1): + s = A[i,i] + + smin = max(eps * abs(s), smlnum) + + for j in xrange(i + 1, n): + + r = 0 + for k in xrange(i, j): + r += EL[i,k] * A[k,j] + + t = A[j,j] - s + if abs(t) < smin: + t = smin + + r = -r / t + EL[i,j] = r + + rmax = max(rmax, abs(r)) + if rmax > simin: + for k in xrange(i, j + 1): + EL[i,k] /= rmax + rmax = 1 + + if rmax != 1: + for k in xrange(i, n): + EL[i,k] /= rmax + + return EL + +@defun +def eig(ctx, A, left = False, right = True, overwrite_a = False): + """ + This routine computes the eigenvalues and optionally the left and right + eigenvectors of a square matrix A. Given A, a vector E and matrices ER + and EL are calculated such that + + A ER[:,i] = E[i] ER[:,i] + EL[i,:] A = EL[i,:] E[i] + + E contains the eigenvalues of A. The columns of ER contain the right eigenvectors + of A whereas the rows of EL contain the left eigenvectors. + + + input: + A : a real or complex square matrix of shape (n, n) + left : if true, the left eigenvectors are calculated. + right : if true, the right eigenvectors are calculated. + overwrite_a : if true, allows modification of A which may improve + performance. if false, A is not modified. + + output: + E : a list of length n containing the eigenvalues of A. + ER : a matrix whose columns contain the right eigenvectors of A. + EL : a matrix whose rows contain the left eigenvectors of A. + + return values: + E if left and right are both false. + (E, ER) if right is true and left is false. + (E, EL) if left is true and right is false. + (E, EL, ER) if left and right are true. + + + examples: + >>> from mpmath import mp + >>> A = mp.matrix([[3, -1, 2], [2, 5, -5], [-2, -3, 7]]) + >>> E, ER = mp.eig(A) + >>> print(mp.chop(A * ER[:,0] - E[0] * ER[:,0])) + [0.0] + [0.0] + [0.0] + + >>> E, EL, ER = mp.eig(A,left = True, right = True) + >>> E, EL, ER = mp.eig_sort(E, EL, ER) + >>> mp.nprint(E) + [2.0, 4.0, 9.0] + >>> print(mp.chop(A * ER[:,0] - E[0] * ER[:,0])) + [0.0] + [0.0] + [0.0] + >>> print(mp.chop( EL[0,:] * A - EL[0,:] * E[0])) + [0.0 0.0 0.0] + + warning: + - If there are multiple eigenvalues, the eigenvectors do not necessarily + span the whole vectorspace, i.e. ER and EL may have not full rank. + Furthermore in that case the eigenvectors are numerical ill-conditioned. + - In the general case the eigenvalues have no natural order. + + see also: + - eigh (or eigsy, eighe) for the symmetric eigenvalue problem. + - eig_sort for sorting of eigenvalues and eigenvectors + """ + + n = A.rows + + if n == 1: + if left and (not right): + return ([A[0]], ctx.matrix([[1]])) + + if right and (not left): + return ([A[0]], ctx.matrix([[1]])) + + return ([A[0]], ctx.matrix([[1]]), ctx.matrix([[1]])) + + if not overwrite_a: + A = A.copy() + + T = ctx.zeros(n, 1) + + hessenberg_reduce_0(ctx, A, T) + + if left or right: + Q = A.copy() + hessenberg_reduce_1(ctx, Q, T) + else: + Q = False + + for x in xrange(n): + for y in xrange(x + 2, n): + A[y,x] = 0 + + hessenberg_qr(ctx, A, Q) + + E = [0 for i in xrange(n)] + for i in xrange(n): + E[i] = A[i,i] + + if not (left or right): + return E + + if left: + EL = eig_tr_l(ctx, A) + EL = EL * Q.transpose_conj() + + if right: + ER = eig_tr_r(ctx, A) + ER = Q * ER + + if left and (not right): + return (E, EL) + + if right and (not left): + return (E, ER) + + return (E, EL, ER) + +@defun +def eig_sort(ctx, E, EL = False, ER = False, f = "real"): + """ + This routine sorts the eigenvalues and eigenvectors delivered by ``eig``. + + parameters: + E : the eigenvalues as delivered by eig + EL : the left eigenvectors as delivered by eig, or false + ER : the right eigenvectors as delivered by eig, or false + f : either a string ("real" sort by increasing real part, "imag" sort by + increasing imag part, "abs" sort by absolute value) or a function + mapping complexs to the reals, i.e. ``f = lambda x: -mp.re(x) `` + would sort the eigenvalues by decreasing real part. + + return values: + E if EL and ER are both false. + (E, ER) if ER is not false and left is false. + (E, EL) if EL is not false and right is false. + (E, EL, ER) if EL and ER are not false. + + example: + >>> from mpmath import mp + >>> A = mp.matrix([[3, -1, 2], [2, 5, -5], [-2, -3, 7]]) + >>> E, EL, ER = mp.eig(A,left = True, right = True) + >>> E, EL, ER = mp.eig_sort(E, EL, ER) + >>> mp.nprint(E) + [2.0, 4.0, 9.0] + >>> E, EL, ER = mp.eig_sort(E, EL, ER,f = lambda x: -mp.re(x)) + >>> mp.nprint(E) + [9.0, 4.0, 2.0] + >>> print(mp.chop(A * ER[:,0] - E[0] * ER[:,0])) + [0.0] + [0.0] + [0.0] + >>> print(mp.chop( EL[0,:] * A - EL[0,:] * E[0])) + [0.0 0.0 0.0] + """ + + if isinstance(f, str): + if f == "real": + f = ctx.re + elif f == "imag": + f = ctx.im + elif f == "abs": + f = abs + else: + raise RuntimeError("unknown function %s" % f) + + n = len(E) + + # Sort eigenvalues (bubble-sort) + + for i in xrange(n): + imax = i + s = f(E[i]) # s is the current maximal element + + for j in xrange(i + 1, n): + c = f(E[j]) + if c < s: + s = c + imax = j + + if imax != i: + # swap eigenvalues + + z = E[i] + E[i] = E[imax] + E[imax] = z + + if not isinstance(EL, bool): + for j in xrange(n): + z = EL[i,j] + EL[i,j] = EL[imax,j] + EL[imax,j] = z + + if not isinstance(ER, bool): + for j in xrange(n): + z = ER[j,i] + ER[j,i] = ER[j,imax] + ER[j,imax] = z + + if isinstance(EL, bool) and isinstance(ER, bool): + return E + + if isinstance(EL, bool) and not(isinstance(ER, bool)): + return (E, ER) + + if isinstance(ER, bool) and not(isinstance(EL, bool)): + return (E, EL) + + return (E, EL, ER) diff --git a/venv/lib/python3.10/site-packages/mpmath/matrices/eigen_symmetric.py b/venv/lib/python3.10/site-packages/mpmath/matrices/eigen_symmetric.py new file mode 100644 index 0000000000000000000000000000000000000000..c82c0bb061d22c37a89f82a0b9bdab3e9ba7ddde --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/matrices/eigen_symmetric.py @@ -0,0 +1,1807 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +################################################################################################## +# module for the symmetric eigenvalue problem +# Copyright 2013 Timo Hartmann (thartmann15 at gmail.com) +# +# todo: +# - implement balancing +# +################################################################################################## + +""" +The symmetric eigenvalue problem. +--------------------------------- + +This file contains routines for the symmetric eigenvalue problem. + +high level routines: + + eigsy : real symmetric (ordinary) eigenvalue problem + eighe : complex hermitian (ordinary) eigenvalue problem + eigh : unified interface for eigsy and eighe + svd_r : singular value decomposition for real matrices + svd_c : singular value decomposition for complex matrices + svd : unified interface for svd_r and svd_c + + +low level routines: + + r_sy_tridiag : reduction of real symmetric matrix to real symmetric tridiagonal matrix + c_he_tridiag_0 : reduction of complex hermitian matrix to real symmetric tridiagonal matrix + c_he_tridiag_1 : auxiliary routine to c_he_tridiag_0 + c_he_tridiag_2 : auxiliary routine to c_he_tridiag_0 + tridiag_eigen : solves the real symmetric tridiagonal matrix eigenvalue problem + svd_r_raw : raw singular value decomposition for real matrices + svd_c_raw : raw singular value decomposition for complex matrices +""" + +from ..libmp.backend import xrange +from .eigen import defun + + +def r_sy_tridiag(ctx, A, D, E, calc_ev = True): + """ + This routine transforms a real symmetric matrix A to a real symmetric + tridiagonal matrix T using an orthogonal similarity transformation: + Q' * A * Q = T (here ' denotes the matrix transpose). + The orthogonal matrix Q is build up from Householder reflectors. + + parameters: + A (input/output) On input, A contains the real symmetric matrix of + dimension (n,n). On output, if calc_ev is true, A contains the + orthogonal matrix Q, otherwise A is destroyed. + + D (output) real array of length n, contains the diagonal elements + of the tridiagonal matrix + + E (output) real array of length n, contains the offdiagonal elements + of the tridiagonal matrix in E[0:(n-1)] where is the dimension of + the matrix A. E[n-1] is undefined. + + calc_ev (input) If calc_ev is true, this routine explicitly calculates the + orthogonal matrix Q which is then returned in A. If calc_ev is + false, Q is not explicitly calculated resulting in a shorter run time. + + This routine is a python translation of the fortran routine tred2.f in the + software library EISPACK (see netlib.org) which itself is based on the algol + procedure tred2 described in: + - Num. Math. 11, p.181-195 (1968) by Martin, Reinsch and Wilkonson + - Handbook for auto. comp., Vol II, Linear Algebra, p.212-226 (1971) + + For a good introduction to Householder reflections, see also + Stoer, Bulirsch - Introduction to Numerical Analysis. + """ + + # note : the vector v of the i-th houshoulder reflector is stored in a[(i+1):,i] + # whereas v/ is stored in a[i,(i+1):] + + n = A.rows + for i in xrange(n - 1, 0, -1): + # scale the vector + + scale = 0 + for k in xrange(0, i): + scale += abs(A[k,i]) + + scale_inv = 0 + if scale != 0: + scale_inv = 1/scale + + # sadly there are floating point numbers not equal to zero whose reciprocal is infinity + + if i == 1 or scale == 0 or ctx.isinf(scale_inv): + E[i] = A[i-1,i] # nothing to do + D[i] = 0 + continue + + # calculate parameters for housholder transformation + + H = 0 + for k in xrange(0, i): + A[k,i] *= scale_inv + H += A[k,i] * A[k,i] + + F = A[i-1,i] + G = ctx.sqrt(H) + if F > 0: + G = -G + E[i] = scale * G + H -= F * G + A[i-1,i] = F - G + F = 0 + + # apply housholder transformation + + for j in xrange(0, i): + if calc_ev: + A[i,j] = A[j,i] / H + + G = 0 # calculate A*U + for k in xrange(0, j + 1): + G += A[k,j] * A[k,i] + for k in xrange(j + 1, i): + G += A[j,k] * A[k,i] + + E[j] = G / H # calculate P + F += E[j] * A[j,i] + + HH = F / (2 * H) + + for j in xrange(0, i): # calculate reduced A + F = A[j,i] + G = E[j] - HH * F # calculate Q + E[j] = G + + for k in xrange(0, j + 1): + A[k,j] -= F * E[k] + G * A[k,i] + + D[i] = H + + for i in xrange(1, n): # better for compatibility + E[i-1] = E[i] + E[n-1] = 0 + + if calc_ev: + D[0] = 0 + for i in xrange(0, n): + if D[i] != 0: + for j in xrange(0, i): # accumulate transformation matrices + G = 0 + for k in xrange(0, i): + G += A[i,k] * A[k,j] + for k in xrange(0, i): + A[k,j] -= G * A[k,i] + + D[i] = A[i,i] + A[i,i] = 1 + + for j in xrange(0, i): + A[j,i] = A[i,j] = 0 + else: + for i in xrange(0, n): + D[i] = A[i,i] + + + + + +def c_he_tridiag_0(ctx, A, D, E, T): + """ + This routine transforms a complex hermitian matrix A to a real symmetric + tridiagonal matrix T using an unitary similarity transformation: + Q' * A * Q = T (here ' denotes the hermitian matrix transpose, + i.e. transposition und conjugation). + The unitary matrix Q is build up from Householder reflectors and + an unitary diagonal matrix. + + parameters: + A (input/output) On input, A contains the complex hermitian matrix + of dimension (n,n). On output, A contains the unitary matrix Q + in compressed form. + + D (output) real array of length n, contains the diagonal elements + of the tridiagonal matrix. + + E (output) real array of length n, contains the offdiagonal elements + of the tridiagonal matrix in E[0:(n-1)] where is the dimension of + the matrix A. E[n-1] is undefined. + + T (output) complex array of length n, contains a unitary diagonal + matrix. + + This routine is a python translation (in slightly modified form) of the fortran + routine htridi.f in the software library EISPACK (see netlib.org) which itself + is a complex version of the algol procedure tred1 described in: + - Num. Math. 11, p.181-195 (1968) by Martin, Reinsch and Wilkonson + - Handbook for auto. comp., Vol II, Linear Algebra, p.212-226 (1971) + + For a good introduction to Householder reflections, see also + Stoer, Bulirsch - Introduction to Numerical Analysis. + """ + + n = A.rows + T[n-1] = 1 + for i in xrange(n - 1, 0, -1): + + # scale the vector + + scale = 0 + for k in xrange(0, i): + scale += abs(ctx.re(A[k,i])) + abs(ctx.im(A[k,i])) + + scale_inv = 0 + if scale != 0: + scale_inv = 1 / scale + + # sadly there are floating point numbers not equal to zero whose reciprocal is infinity + + if scale == 0 or ctx.isinf(scale_inv): + E[i] = 0 + D[i] = 0 + T[i-1] = 1 + continue + + if i == 1: + F = A[i-1,i] + f = abs(F) + E[i] = f + D[i] = 0 + if f != 0: + T[i-1] = T[i] * F / f + else: + T[i-1] = T[i] + continue + + # calculate parameters for housholder transformation + + H = 0 + for k in xrange(0, i): + A[k,i] *= scale_inv + rr = ctx.re(A[k,i]) + ii = ctx.im(A[k,i]) + H += rr * rr + ii * ii + + F = A[i-1,i] + f = abs(F) + G = ctx.sqrt(H) + H += G * f + E[i] = scale * G + if f != 0: + F = F / f + TZ = - T[i] * F # T[i-1]=-T[i]*F, but we need T[i-1] as temporary storage + G *= F + else: + TZ = -T[i] # T[i-1]=-T[i] + A[i-1,i] += G + F = 0 + + # apply housholder transformation + + for j in xrange(0, i): + A[i,j] = A[j,i] / H + + G = 0 # calculate A*U + for k in xrange(0, j + 1): + G += ctx.conj(A[k,j]) * A[k,i] + for k in xrange(j + 1, i): + G += A[j,k] * A[k,i] + + T[j] = G / H # calculate P + F += ctx.conj(T[j]) * A[j,i] + + HH = F / (2 * H) + + for j in xrange(0, i): # calculate reduced A + F = A[j,i] + G = T[j] - HH * F # calculate Q + T[j] = G + + for k in xrange(0, j + 1): + A[k,j] -= ctx.conj(F) * T[k] + ctx.conj(G) * A[k,i] + # as we use the lower left part for storage + # we have to use the transpose of the normal formula + + T[i-1] = TZ + D[i] = H + + for i in xrange(1, n): # better for compatibility + E[i-1] = E[i] + E[n-1] = 0 + + D[0] = 0 + for i in xrange(0, n): + zw = D[i] + D[i] = ctx.re(A[i,i]) + A[i,i] = zw + + + + + + + +def c_he_tridiag_1(ctx, A, T): + """ + This routine forms the unitary matrix Q described in c_he_tridiag_0. + + parameters: + A (input/output) On input, A is the same matrix as delivered by + c_he_tridiag_0. On output, A is set to Q. + + T (input) On input, T is the same array as delivered by c_he_tridiag_0. + + """ + + n = A.rows + + for i in xrange(0, n): + if A[i,i] != 0: + for j in xrange(0, i): + G = 0 + for k in xrange(0, i): + G += ctx.conj(A[i,k]) * A[k,j] + for k in xrange(0, i): + A[k,j] -= G * A[k,i] + + A[i,i] = 1 + + for j in xrange(0, i): + A[j,i] = A[i,j] = 0 + + for i in xrange(0, n): + for k in xrange(0, n): + A[i,k] *= T[k] + + + + +def c_he_tridiag_2(ctx, A, T, B): + """ + This routine applied the unitary matrix Q described in c_he_tridiag_0 + onto the the matrix B, i.e. it forms Q*B. + + parameters: + A (input) On input, A is the same matrix as delivered by c_he_tridiag_0. + + T (input) On input, T is the same array as delivered by c_he_tridiag_0. + + B (input/output) On input, B is a complex matrix. On output B is replaced + by Q*B. + + This routine is a python translation of the fortran routine htribk.f in the + software library EISPACK (see netlib.org). See c_he_tridiag_0 for more + references. + """ + + n = A.rows + + for i in xrange(0, n): + for k in xrange(0, n): + B[k,i] *= T[k] + + for i in xrange(0, n): + if A[i,i] != 0: + for j in xrange(0, n): + G = 0 + for k in xrange(0, i): + G += ctx.conj(A[i,k]) * B[k,j] + for k in xrange(0, i): + B[k,j] -= G * A[k,i] + + + + + +def tridiag_eigen(ctx, d, e, z = False): + """ + This subroutine find the eigenvalues and the first components of the + eigenvectors of a real symmetric tridiagonal matrix using the implicit + QL method. + + parameters: + + d (input/output) real array of length n. on input, d contains the diagonal + elements of the input matrix. on output, d contains the eigenvalues in + ascending order. + + e (input) real array of length n. on input, e contains the offdiagonal + elements of the input matrix in e[0:(n-1)]. On output, e has been + destroyed. + + z (input/output) If z is equal to False, no eigenvectors will be computed. + Otherwise on input z should have the format z[0:m,0:n] (i.e. a real or + complex matrix of dimension (m,n) ). On output this matrix will be + multiplied by the matrix of the eigenvectors (i.e. the columns of this + matrix are the eigenvectors): z --> z*EV + That means if z[i,j]={1 if j==j; 0 otherwise} on input, then on output + z will contain the first m components of the eigenvectors. That means + if m is equal to n, the i-th eigenvector will be z[:,i]. + + This routine is a python translation (in slightly modified form) of the + fortran routine imtql2.f in the software library EISPACK (see netlib.org) + which itself is based on the algol procudure imtql2 desribed in: + - num. math. 12, p. 377-383(1968) by matrin and wilkinson + - modified in num. math. 15, p. 450(1970) by dubrulle + - handbook for auto. comp., vol. II-linear algebra, p. 241-248 (1971) + See also the routine gaussq.f in netlog.org or acm algorithm 726. + """ + + n = len(d) + e[n-1] = 0 + iterlim = 2 * ctx.dps + + for l in xrange(n): + j = 0 + while 1: + m = l + while 1: + # look for a small subdiagonal element + if m + 1 == n: + break + if abs(e[m]) <= ctx.eps * (abs(d[m]) + abs(d[m + 1])): + break + m = m + 1 + if m == l: + break + + if j >= iterlim: + raise RuntimeError("tridiag_eigen: no convergence to an eigenvalue after %d iterations" % iterlim) + + j += 1 + + # form shift + + p = d[l] + g = (d[l + 1] - p) / (2 * e[l]) + r = ctx.hypot(g, 1) + + if g < 0: + s = g - r + else: + s = g + r + + g = d[m] - p + e[l] / s + + s, c, p = 1, 1, 0 + + for i in xrange(m - 1, l - 1, -1): + f = s * e[i] + b = c * e[i] + if abs(f) > abs(g): # this here is a slight improvement also used in gaussq.f or acm algorithm 726. + c = g / f + r = ctx.hypot(c, 1) + e[i + 1] = f * r + s = 1 / r + c = c * s + else: + s = f / g + r = ctx.hypot(s, 1) + e[i + 1] = g * r + c = 1 / r + s = s * c + g = d[i + 1] - p + r = (d[i] - g) * s + 2 * c * b + p = s * r + d[i + 1] = g + p + g = c * r - b + + if not isinstance(z, bool): + # calculate eigenvectors + for w in xrange(z.rows): + f = z[w,i+1] + z[w,i+1] = s * z[w,i] + c * f + z[w,i ] = c * z[w,i] - s * f + + d[l] = d[l] - p + e[l] = g + e[m] = 0 + + for ii in xrange(1, n): + # sort eigenvalues and eigenvectors (bubble-sort) + i = ii - 1 + k = i + p = d[i] + for j in xrange(ii, n): + if d[j] >= p: + continue + k = j + p = d[k] + if k == i: + continue + d[k] = d[i] + d[i] = p + + if not isinstance(z, bool): + for w in xrange(z.rows): + p = z[w,i] + z[w,i] = z[w,k] + z[w,k] = p + +######################################################################################## + +@defun +def eigsy(ctx, A, eigvals_only = False, overwrite_a = False): + """ + This routine solves the (ordinary) eigenvalue problem for a real symmetric + square matrix A. Given A, an orthogonal matrix Q is calculated which + diagonalizes A: + + Q' A Q = diag(E) and Q Q' = Q' Q = 1 + + Here diag(E) is a diagonal matrix whose diagonal is E. + ' denotes the transpose. + + The columns of Q are the eigenvectors of A and E contains the eigenvalues: + + A Q[:,i] = E[i] Q[:,i] + + + input: + + A: real matrix of format (n,n) which is symmetric + (i.e. A=A' or A[i,j]=A[j,i]) + + eigvals_only: if true, calculates only the eigenvalues E. + if false, calculates both eigenvectors and eigenvalues. + + overwrite_a: if true, allows modification of A which may improve + performance. if false, A is not modified. + + output: + + E: vector of format (n). contains the eigenvalues of A in ascending order. + + Q: orthogonal matrix of format (n,n). contains the eigenvectors + of A as columns. + + return value: + + E if eigvals_only is true + (E, Q) if eigvals_only is false + + example: + >>> from mpmath import mp + >>> A = mp.matrix([[3, 2], [2, 0]]) + >>> E = mp.eigsy(A, eigvals_only = True) + >>> print(E) + [-1.0] + [ 4.0] + + >>> A = mp.matrix([[1, 2], [2, 3]]) + >>> E, Q = mp.eigsy(A) + >>> print(mp.chop(A * Q[:,0] - E[0] * Q[:,0])) + [0.0] + [0.0] + + see also: eighe, eigh, eig + """ + + if not overwrite_a: + A = A.copy() + + d = ctx.zeros(A.rows, 1) + e = ctx.zeros(A.rows, 1) + + if eigvals_only: + r_sy_tridiag(ctx, A, d, e, calc_ev = False) + tridiag_eigen(ctx, d, e, False) + return d + else: + r_sy_tridiag(ctx, A, d, e, calc_ev = True) + tridiag_eigen(ctx, d, e, A) + return (d, A) + + +@defun +def eighe(ctx, A, eigvals_only = False, overwrite_a = False): + """ + This routine solves the (ordinary) eigenvalue problem for a complex + hermitian square matrix A. Given A, an unitary matrix Q is calculated which + diagonalizes A: + + Q' A Q = diag(E) and Q Q' = Q' Q = 1 + + Here diag(E) a is diagonal matrix whose diagonal is E. + ' denotes the hermitian transpose (i.e. ordinary transposition and + complex conjugation). + + The columns of Q are the eigenvectors of A and E contains the eigenvalues: + + A Q[:,i] = E[i] Q[:,i] + + + input: + + A: complex matrix of format (n,n) which is hermitian + (i.e. A=A' or A[i,j]=conj(A[j,i])) + + eigvals_only: if true, calculates only the eigenvalues E. + if false, calculates both eigenvectors and eigenvalues. + + overwrite_a: if true, allows modification of A which may improve + performance. if false, A is not modified. + + output: + + E: vector of format (n). contains the eigenvalues of A in ascending order. + + Q: unitary matrix of format (n,n). contains the eigenvectors + of A as columns. + + return value: + + E if eigvals_only is true + (E, Q) if eigvals_only is false + + example: + >>> from mpmath import mp + >>> A = mp.matrix([[1, -3 - 1j], [-3 + 1j, -2]]) + >>> E = mp.eighe(A, eigvals_only = True) + >>> print(E) + [-4.0] + [ 3.0] + + >>> A = mp.matrix([[1, 2 + 5j], [2 - 5j, 3]]) + >>> E, Q = mp.eighe(A) + >>> print(mp.chop(A * Q[:,0] - E[0] * Q[:,0])) + [0.0] + [0.0] + + see also: eigsy, eigh, eig + """ + + if not overwrite_a: + A = A.copy() + + d = ctx.zeros(A.rows, 1) + e = ctx.zeros(A.rows, 1) + t = ctx.zeros(A.rows, 1) + + if eigvals_only: + c_he_tridiag_0(ctx, A, d, e, t) + tridiag_eigen(ctx, d, e, False) + return d + else: + c_he_tridiag_0(ctx, A, d, e, t) + B = ctx.eye(A.rows) + tridiag_eigen(ctx, d, e, B) + c_he_tridiag_2(ctx, A, t, B) + return (d, B) + +@defun +def eigh(ctx, A, eigvals_only = False, overwrite_a = False): + """ + "eigh" is a unified interface for "eigsy" and "eighe". Depending on + whether A is real or complex the appropriate function is called. + + This routine solves the (ordinary) eigenvalue problem for a real symmetric + or complex hermitian square matrix A. Given A, an orthogonal (A real) or + unitary (A complex) matrix Q is calculated which diagonalizes A: + + Q' A Q = diag(E) and Q Q' = Q' Q = 1 + + Here diag(E) a is diagonal matrix whose diagonal is E. + ' denotes the hermitian transpose (i.e. ordinary transposition and + complex conjugation). + + The columns of Q are the eigenvectors of A and E contains the eigenvalues: + + A Q[:,i] = E[i] Q[:,i] + + input: + + A: a real or complex square matrix of format (n,n) which is symmetric + (i.e. A[i,j]=A[j,i]) or hermitian (i.e. A[i,j]=conj(A[j,i])). + + eigvals_only: if true, calculates only the eigenvalues E. + if false, calculates both eigenvectors and eigenvalues. + + overwrite_a: if true, allows modification of A which may improve + performance. if false, A is not modified. + + output: + + E: vector of format (n). contains the eigenvalues of A in ascending order. + + Q: an orthogonal or unitary matrix of format (n,n). contains the + eigenvectors of A as columns. + + return value: + + E if eigvals_only is true + (E, Q) if eigvals_only is false + + example: + >>> from mpmath import mp + >>> A = mp.matrix([[3, 2], [2, 0]]) + >>> E = mp.eigh(A, eigvals_only = True) + >>> print(E) + [-1.0] + [ 4.0] + + >>> A = mp.matrix([[1, 2], [2, 3]]) + >>> E, Q = mp.eigh(A) + >>> print(mp.chop(A * Q[:,0] - E[0] * Q[:,0])) + [0.0] + [0.0] + + >>> A = mp.matrix([[1, 2 + 5j], [2 - 5j, 3]]) + >>> E, Q = mp.eigh(A) + >>> print(mp.chop(A * Q[:,0] - E[0] * Q[:,0])) + [0.0] + [0.0] + + see also: eigsy, eighe, eig + """ + + iscomplex = any(type(x) is ctx.mpc for x in A) + + if iscomplex: + return ctx.eighe(A, eigvals_only = eigvals_only, overwrite_a = overwrite_a) + else: + return ctx.eigsy(A, eigvals_only = eigvals_only, overwrite_a = overwrite_a) + + +@defun +def gauss_quadrature(ctx, n, qtype = "legendre", alpha = 0, beta = 0): + """ + This routine calulates gaussian quadrature rules for different + families of orthogonal polynomials. Let (a, b) be an interval, + W(x) a positive weight function and n a positive integer. + Then the purpose of this routine is to calculate pairs (x_k, w_k) + for k=0, 1, 2, ... (n-1) which give + + int(W(x) * F(x), x = a..b) = sum(w_k * F(x_k),k = 0..(n-1)) + + exact for all polynomials F(x) of degree (strictly) less than 2*n. For all + integrable functions F(x) the sum is a (more or less) good approximation to + the integral. The x_k are called nodes (which are the zeros of the + related orthogonal polynomials) and the w_k are called the weights. + + parameters + n (input) The degree of the quadrature rule, i.e. its number of + nodes. + + qtype (input) The family of orthogonal polynmomials for which to + compute the quadrature rule. See the list below. + + alpha (input) real number, used as parameter for some orthogonal + polynomials + + beta (input) real number, used as parameter for some orthogonal + polynomials. + + return value + + (X, W) a pair of two real arrays where x_k = X[k] and w_k = W[k]. + + + orthogonal polynomials: + + qtype polynomial + ----- ---------- + + "legendre" Legendre polynomials, W(x)=1 on the interval (-1, +1) + "legendre01" shifted Legendre polynomials, W(x)=1 on the interval (0, +1) + "hermite" Hermite polynomials, W(x)=exp(-x*x) on (-infinity,+infinity) + "laguerre" Laguerre polynomials, W(x)=exp(-x) on (0,+infinity) + "glaguerre" generalized Laguerre polynomials, W(x)=exp(-x)*x**alpha + on (0, +infinity) + "chebyshev1" Chebyshev polynomials of the first kind, W(x)=1/sqrt(1-x*x) + on (-1, +1) + "chebyshev2" Chebyshev polynomials of the second kind, W(x)=sqrt(1-x*x) + on (-1, +1) + "jacobi" Jacobi polynomials, W(x)=(1-x)**alpha * (1+x)**beta on (-1, +1) + with alpha>-1 and beta>-1 + + examples: + >>> from mpmath import mp + >>> f = lambda x: x**8 + 2 * x**6 - 3 * x**4 + 5 * x**2 - 7 + >>> X, W = mp.gauss_quadrature(5, "hermite") + >>> A = mp.fdot([(f(x), w) for x, w in zip(X, W)]) + >>> B = mp.sqrt(mp.pi) * 57 / 16 + >>> C = mp.quad(lambda x: mp.exp(- x * x) * f(x), [-mp.inf, +mp.inf]) + >>> mp.nprint((mp.chop(A-B, tol = 1e-10), mp.chop(A-C, tol = 1e-10))) + (0.0, 0.0) + + >>> f = lambda x: x**5 - 2 * x**4 + 3 * x**3 - 5 * x**2 + 7 * x - 11 + >>> X, W = mp.gauss_quadrature(3, "laguerre") + >>> A = mp.fdot([(f(x), w) for x, w in zip(X, W)]) + >>> B = 76 + >>> C = mp.quad(lambda x: mp.exp(-x) * f(x), [0, +mp.inf]) + >>> mp.nprint(mp.chop(A-B, tol = 1e-10), mp.chop(A-C, tol = 1e-10)) + .0 + + # orthogonality of the chebyshev polynomials: + >>> f = lambda x: mp.chebyt(3, x) * mp.chebyt(2, x) + >>> X, W = mp.gauss_quadrature(3, "chebyshev1") + >>> A = mp.fdot([(f(x), w) for x, w in zip(X, W)]) + >>> print(mp.chop(A, tol = 1e-10)) + 0.0 + + references: + - golub and welsch, "calculations of gaussian quadrature rules", mathematics of + computation 23, p. 221-230 (1969) + - golub, "some modified matrix eigenvalue problems", siam review 15, p. 318-334 (1973) + - stroud and secrest, "gaussian quadrature formulas", prentice-hall (1966) + + See also the routine gaussq.f in netlog.org or ACM Transactions on + Mathematical Software algorithm 726. + """ + + d = ctx.zeros(n, 1) + e = ctx.zeros(n, 1) + z = ctx.zeros(1, n) + + z[0,0] = 1 + + if qtype == "legendre": + # legendre on the range -1 +1 , abramowitz, table 25.4, p.916 + w = 2 + for i in xrange(n): + j = i + 1 + e[i] = ctx.sqrt(j * j / (4 * j * j - ctx.mpf(1))) + elif qtype == "legendre01": + # legendre shifted to 0 1 , abramowitz, table 25.8, p.921 + w = 1 + for i in xrange(n): + d[i] = 1 / ctx.mpf(2) + j = i + 1 + e[i] = ctx.sqrt(j * j / (16 * j * j - ctx.mpf(4))) + elif qtype == "hermite": + # hermite on the range -inf +inf , abramowitz, table 25.10,p.924 + w = ctx.sqrt(ctx.pi) + for i in xrange(n): + j = i + 1 + e[i] = ctx.sqrt(j / ctx.mpf(2)) + elif qtype == "laguerre": + # laguerre on the range 0 +inf , abramowitz, table 25.9, p. 923 + w = 1 + for i in xrange(n): + j = i + 1 + d[i] = 2 * j - 1 + e[i] = j + elif qtype=="chebyshev1": + # chebyshev polynimials of the first kind + w = ctx.pi + for i in xrange(n): + e[i] = 1 / ctx.mpf(2) + e[0] = ctx.sqrt(1 / ctx.mpf(2)) + elif qtype == "chebyshev2": + # chebyshev polynimials of the second kind + w = ctx.pi / 2 + for i in xrange(n): + e[i] = 1 / ctx.mpf(2) + elif qtype == "glaguerre": + # generalized laguerre on the range 0 +inf + w = ctx.gamma(1 + alpha) + for i in xrange(n): + j = i + 1 + d[i] = 2 * j - 1 + alpha + e[i] = ctx.sqrt(j * (j + alpha)) + elif qtype == "jacobi": + # jacobi polynomials + alpha = ctx.mpf(alpha) + beta = ctx.mpf(beta) + ab = alpha + beta + abi = ab + 2 + w = (2**(ab+1)) * ctx.gamma(alpha + 1) * ctx.gamma(beta + 1) / ctx.gamma(abi) + d[0] = (beta - alpha) / abi + e[0] = ctx.sqrt(4 * (1 + alpha) * (1 + beta) / ((abi + 1) * (abi * abi))) + a2b2 = beta * beta - alpha * alpha + for i in xrange(1, n): + j = i + 1 + abi = 2 * j + ab + d[i] = a2b2 / ((abi - 2) * abi) + e[i] = ctx.sqrt(4 * j * (j + alpha) * (j + beta) * (j + ab) / ((abi * abi - 1) * abi * abi)) + elif isinstance(qtype, str): + raise ValueError("unknown quadrature rule \"%s\"" % qtype) + elif not isinstance(qtype, str): + w = qtype(d, e) + else: + assert 0 + + tridiag_eigen(ctx, d, e, z) + + for i in xrange(len(z)): + z[i] *= z[i] + + z = z.transpose() + return (d, w * z) + +################################################################################################## +################################################################################################## +################################################################################################## + +def svd_r_raw(ctx, A, V = False, calc_u = False): + """ + This routine computes the singular value decomposition of a matrix A. + Given A, two orthogonal matrices U and V are calculated such that + + A = U S V + + where S is a suitable shaped matrix whose off-diagonal elements are zero. + The diagonal elements of S are the singular values of A, i.e. the + squareroots of the eigenvalues of A' A or A A'. Here ' denotes the transpose. + Householder bidiagonalization and a variant of the QR algorithm is used. + + overview of the matrices : + + A : m*n A gets replaced by U + U : m*n U replaces A. If n>m then only the first m*m block of U is + non-zero. column-orthogonal: U' U = B + here B is a n*n matrix whose first min(m,n) diagonal + elements are 1 and all other elements are zero. + S : n*n diagonal matrix, only the diagonal elements are stored in + the array S. only the first min(m,n) diagonal elements are non-zero. + V : n*n orthogonal: V V' = V' V = 1 + + parameters: + A (input/output) On input, A contains a real matrix of shape m*n. + On output, if calc_u is true A contains the column-orthogonal + matrix U; otherwise A is simply used as workspace and thus destroyed. + + V (input/output) if false, the matrix V is not calculated. otherwise + V must be a matrix of shape n*n. + + calc_u (input) If true, the matrix U is calculated and replaces A. + if false, U is not calculated and A is simply destroyed + + return value: + S an array of length n containing the singular values of A sorted by + decreasing magnitude. only the first min(m,n) elements are non-zero. + + This routine is a python translation of the fortran routine svd.f in the + software library EISPACK (see netlib.org) which itself is based on the + algol procedure svd described in: + - num. math. 14, 403-420(1970) by golub and reinsch. + - wilkinson/reinsch: handbook for auto. comp., vol ii-linear algebra, 134-151(1971). + + """ + + m, n = A.rows, A.cols + + S = ctx.zeros(n, 1) + + # work is a temporary array of size n + work = ctx.zeros(n, 1) + + g = scale = anorm = 0 + maxits = 3 * ctx.dps + + for i in xrange(n): # householder reduction to bidiagonal form + work[i] = scale*g + g = s = scale = 0 + if i < m: + for k in xrange(i, m): + scale += ctx.fabs(A[k,i]) + if scale != 0: + for k in xrange(i, m): + A[k,i] /= scale + s += A[k,i] * A[k,i] + f = A[i,i] + g = -ctx.sqrt(s) + if f < 0: + g = -g + h = f * g - s + A[i,i] = f - g + for j in xrange(i+1, n): + s = 0 + for k in xrange(i, m): + s += A[k,i] * A[k,j] + f = s / h + for k in xrange(i, m): + A[k,j] += f * A[k,i] + for k in xrange(i,m): + A[k,i] *= scale + + S[i] = scale * g + g = s = scale = 0 + + if i < m and i != n - 1: + for k in xrange(i+1, n): + scale += ctx.fabs(A[i,k]) + if scale: + for k in xrange(i+1, n): + A[i,k] /= scale + s += A[i,k] * A[i,k] + f = A[i,i+1] + g = -ctx.sqrt(s) + if f < 0: + g = -g + h = f * g - s + A[i,i+1] = f - g + + for k in xrange(i+1, n): + work[k] = A[i,k] / h + + for j in xrange(i+1, m): + s = 0 + for k in xrange(i+1, n): + s += A[j,k] * A[i,k] + for k in xrange(i+1, n): + A[j,k] += s * work[k] + + for k in xrange(i+1, n): + A[i,k] *= scale + + anorm = max(anorm, ctx.fabs(S[i]) + ctx.fabs(work[i])) + + if not isinstance(V, bool): + for i in xrange(n-2, -1, -1): # accumulation of right hand transformations + V[i+1,i+1] = 1 + + if work[i+1] != 0: + for j in xrange(i+1, n): + V[i,j] = (A[i,j] / A[i,i+1]) / work[i+1] + for j in xrange(i+1, n): + s = 0 + for k in xrange(i+1, n): + s += A[i,k] * V[j,k] + for k in xrange(i+1, n): + V[j,k] += s * V[i,k] + + for j in xrange(i+1, n): + V[j,i] = V[i,j] = 0 + + V[0,0] = 1 + + if m= maxits: + raise RuntimeError("svd: no convergence to an eigenvalue after %d iterations" % its) + + x = S[l] # shift from bottom 2 by 2 minor + nm = k-1 + y = S[nm] + g = work[nm] + h = work[k] + f = ((y - z) * (y + z) + (g - h) * (g + h))/(2 * h * y) + g = ctx.hypot(f, 1) + if f >= 0: f = ((x - z) * (x + z) + h * ((y / (f + g)) - h)) / x + else: f = ((x - z) * (x + z) + h * ((y / (f - g)) - h)) / x + + c = s = 1 # next qt transformation + + for j in xrange(l, nm + 1): + g = work[j+1] + y = S[j+1] + h = s * g + g = c * g + z = ctx.hypot(f, h) + work[j] = z + c = f / z + s = h / z + f = x * c + g * s + g = g * c - x * s + h = y * s + y *= c + if not isinstance(V, bool): + for jj in xrange(n): + x = V[j ,jj] + z = V[j+1,jj] + V[j ,jj]= x * c + z * s + V[j+1 ,jj]= z * c - x * s + z = ctx.hypot(f, h) + S[j] = z + if z != 0: # rotation can be arbitray if z=0 + z = 1 / z + c = f * z + s = h * z + f = c * g + s * y + x = c * y - s * g + + if calc_u: + for jj in xrange(m): + y = A[jj,j ] + z = A[jj,j+1] + A[jj,j ] = y * c + z * s + A[jj,j+1 ] = z * c - y * s + + work[l] = 0 + work[k] = f + S[k] = x + + ########################## + + # Sort singular values into decreasing order (bubble-sort) + + for i in xrange(n): + imax = i + s = ctx.fabs(S[i]) # s is the current maximal element + + for j in xrange(i + 1, n): + c = ctx.fabs(S[j]) + if c > s: + s = c + imax = j + + if imax != i: + # swap singular values + + z = S[i] + S[i] = S[imax] + S[imax] = z + + if calc_u: + for j in xrange(m): + z = A[j,i] + A[j,i] = A[j,imax] + A[j,imax] = z + + if not isinstance(V, bool): + for j in xrange(n): + z = V[i,j] + V[i,j] = V[imax,j] + V[imax,j] = z + + return S + +####################### + +def svd_c_raw(ctx, A, V = False, calc_u = False): + """ + This routine computes the singular value decomposition of a matrix A. + Given A, two unitary matrices U and V are calculated such that + + A = U S V + + where S is a suitable shaped matrix whose off-diagonal elements are zero. + The diagonal elements of S are the singular values of A, i.e. the + squareroots of the eigenvalues of A' A or A A'. Here ' denotes the hermitian + transpose (i.e. transposition and conjugation). Householder bidiagonalization + and a variant of the QR algorithm is used. + + overview of the matrices : + + A : m*n A gets replaced by U + U : m*n U replaces A. If n>m then only the first m*m block of U is + non-zero. column-unitary: U' U = B + here B is a n*n matrix whose first min(m,n) diagonal + elements are 1 and all other elements are zero. + S : n*n diagonal matrix, only the diagonal elements are stored in + the array S. only the first min(m,n) diagonal elements are non-zero. + V : n*n unitary: V V' = V' V = 1 + + parameters: + A (input/output) On input, A contains a complex matrix of shape m*n. + On output, if calc_u is true A contains the column-unitary + matrix U; otherwise A is simply used as workspace and thus destroyed. + + V (input/output) if false, the matrix V is not calculated. otherwise + V must be a matrix of shape n*n. + + calc_u (input) If true, the matrix U is calculated and replaces A. + if false, U is not calculated and A is simply destroyed + + return value: + S an array of length n containing the singular values of A sorted by + decreasing magnitude. only the first min(m,n) elements are non-zero. + + This routine is a python translation of the fortran routine svd.f in the + software library EISPACK (see netlib.org) which itself is based on the + algol procedure svd described in: + - num. math. 14, 403-420(1970) by golub and reinsch. + - wilkinson/reinsch: handbook for auto. comp., vol ii-linear algebra, 134-151(1971). + + """ + + m, n = A.rows, A.cols + + S = ctx.zeros(n, 1) + + # work is a temporary array of size n + work = ctx.zeros(n, 1) + lbeta = ctx.zeros(n, 1) + rbeta = ctx.zeros(n, 1) + dwork = ctx.zeros(n, 1) + + g = scale = anorm = 0 + maxits = 3 * ctx.dps + + for i in xrange(n): # householder reduction to bidiagonal form + dwork[i] = scale * g # dwork are the side-diagonal elements + g = s = scale = 0 + if i < m: + for k in xrange(i, m): + scale += ctx.fabs(ctx.re(A[k,i])) + ctx.fabs(ctx.im(A[k,i])) + if scale != 0: + for k in xrange(i, m): + A[k,i] /= scale + ar = ctx.re(A[k,i]) + ai = ctx.im(A[k,i]) + s += ar * ar + ai * ai + f = A[i,i] + g = -ctx.sqrt(s) + if ctx.re(f) < 0: + beta = -g - ctx.conj(f) + g = -g + else: + beta = -g + ctx.conj(f) + beta /= ctx.conj(beta) + beta += 1 + h = 2 * (ctx.re(f) * g - s) + A[i,i] = f - g + beta /= h + lbeta[i] = (beta / scale) / scale + for j in xrange(i+1, n): + s = 0 + for k in xrange(i, m): + s += ctx.conj(A[k,i]) * A[k,j] + f = beta * s + for k in xrange(i, m): + A[k,j] += f * A[k,i] + for k in xrange(i, m): + A[k,i] *= scale + + S[i] = scale * g # S are the diagonal elements + g = s = scale = 0 + + if i < m and i != n - 1: + for k in xrange(i+1, n): + scale += ctx.fabs(ctx.re(A[i,k])) + ctx.fabs(ctx.im(A[i,k])) + if scale: + for k in xrange(i+1, n): + A[i,k] /= scale + ar = ctx.re(A[i,k]) + ai = ctx.im(A[i,k]) + s += ar * ar + ai * ai + f = A[i,i+1] + g = -ctx.sqrt(s) + if ctx.re(f) < 0: + beta = -g - ctx.conj(f) + g = -g + else: + beta = -g + ctx.conj(f) + + beta /= ctx.conj(beta) + beta += 1 + + h = 2 * (ctx.re(f) * g - s) + A[i,i+1] = f - g + + beta /= h + rbeta[i] = (beta / scale) / scale + + for k in xrange(i+1, n): + work[k] = A[i, k] + + for j in xrange(i+1, m): + s = 0 + for k in xrange(i+1, n): + s += ctx.conj(A[i,k]) * A[j,k] + f = s * beta + for k in xrange(i+1,n): + A[j,k] += f * work[k] + + for k in xrange(i+1, n): + A[i,k] *= scale + + anorm = max(anorm,ctx.fabs(S[i]) + ctx.fabs(dwork[i])) + + if not isinstance(V, bool): + for i in xrange(n-2, -1, -1): # accumulation of right hand transformations + V[i+1,i+1] = 1 + + if dwork[i+1] != 0: + f = ctx.conj(rbeta[i]) + for j in xrange(i+1, n): + V[i,j] = A[i,j] * f + for j in xrange(i+1, n): + s = 0 + for k in xrange(i+1, n): + s += ctx.conj(A[i,k]) * V[j,k] + for k in xrange(i+1, n): + V[j,k] += s * V[i,k] + + for j in xrange(i+1,n): + V[j,i] = V[i,j] = 0 + + V[0,0] = 1 + + if m < n : minnm = m + else : minnm = n + + if calc_u: + for i in xrange(minnm-1, -1, -1): # accumulation of left hand transformations + g = S[i] + for j in xrange(i+1, n): + A[i,j] = 0 + if g != 0: + g = 1 / g + for j in xrange(i+1, n): + s = 0 + for k in xrange(i+1, m): + s += ctx.conj(A[k,i]) * A[k,j] + f = s * ctx.conj(lbeta[i]) + for k in xrange(i, m): + A[k,j] += f * A[k,i] + for j in xrange(i, m): + A[j,i] *= g + else: + for j in xrange(i, m): + A[j,i] = 0 + A[i,i] += 1 + + for k in xrange(n-1, -1, -1): + # diagonalization of the bidiagonal form: + # loop over singular values, and over allowed itations + + its = 0 + while 1: + its += 1 + flag = True + + for l in xrange(k, -1, -1): + nm = l - 1 + + if ctx.fabs(dwork[l]) + anorm == anorm: + flag = False + break + + if ctx.fabs(S[nm]) + anorm == anorm: + break + + if flag: + c = 0 + s = 1 + for i in xrange(l, k+1): + f = s * dwork[i] + dwork[i] *= c + if ctx.fabs(f) + anorm == anorm: + break + g = S[i] + h = ctx.hypot(f, g) + S[i] = h + h = 1 / h + c = g * h + s = -f * h + + if calc_u: + for j in xrange(m): + y = A[j,nm] + z = A[j,i] + A[j,nm]= y * c + z * s + A[j,i] = z * c - y * s + + z = S[k] + + if l == k: # convergence + if z < 0: # singular value is made nonnegative + S[k] = -z + if not isinstance(V, bool): + for j in xrange(n): + V[k,j] = -V[k,j] + break + + if its >= maxits: + raise RuntimeError("svd: no convergence to an eigenvalue after %d iterations" % its) + + x = S[l] # shift from bottom 2 by 2 minor + nm = k-1 + y = S[nm] + g = dwork[nm] + h = dwork[k] + f = ((y - z) * (y + z) + (g - h) * (g + h)) / (2 * h * y) + g = ctx.hypot(f, 1) + if f >=0: f = (( x - z) *( x + z) + h *((y / (f + g)) - h)) / x + else: f = (( x - z) *( x + z) + h *((y / (f - g)) - h)) / x + + c = s = 1 # next qt transformation + + for j in xrange(l, nm + 1): + g = dwork[j+1] + y = S[j+1] + h = s * g + g = c * g + z = ctx.hypot(f, h) + dwork[j] = z + c = f / z + s = h / z + f = x * c + g * s + g = g * c - x * s + h = y * s + y *= c + if not isinstance(V, bool): + for jj in xrange(n): + x = V[j ,jj] + z = V[j+1,jj] + V[j ,jj]= x * c + z * s + V[j+1,jj ]= z * c - x * s + z = ctx.hypot(f, h) + S[j] = z + if z != 0: # rotation can be arbitray if z=0 + z = 1 / z + c = f * z + s = h * z + f = c * g + s * y + x = c * y - s * g + if calc_u: + for jj in xrange(m): + y = A[jj,j ] + z = A[jj,j+1] + A[jj,j ]= y * c + z * s + A[jj,j+1 ]= z * c - y * s + + dwork[l] = 0 + dwork[k] = f + S[k] = x + + ########################## + + # Sort singular values into decreasing order (bubble-sort) + + for i in xrange(n): + imax = i + s = ctx.fabs(S[i]) # s is the current maximal element + + for j in xrange(i + 1, n): + c = ctx.fabs(S[j]) + if c > s: + s = c + imax = j + + if imax != i: + # swap singular values + + z = S[i] + S[i] = S[imax] + S[imax] = z + + if calc_u: + for j in xrange(m): + z = A[j,i] + A[j,i] = A[j,imax] + A[j,imax] = z + + if not isinstance(V, bool): + for j in xrange(n): + z = V[i,j] + V[i,j] = V[imax,j] + V[imax,j] = z + + return S + +################################################################################################## + +@defun +def svd_r(ctx, A, full_matrices = False, compute_uv = True, overwrite_a = False): + """ + This routine computes the singular value decomposition of a matrix A. + Given A, two orthogonal matrices U and V are calculated such that + + A = U S V and U' U = 1 and V V' = 1 + + where S is a suitable shaped matrix whose off-diagonal elements are zero. + Here ' denotes the transpose. The diagonal elements of S are the singular + values of A, i.e. the squareroots of the eigenvalues of A' A or A A'. + + input: + A : a real matrix of shape (m, n) + full_matrices : if true, U and V are of shape (m, m) and (n, n). + if false, U and V are of shape (m, min(m, n)) and (min(m, n), n). + compute_uv : if true, U and V are calculated. if false, only S is calculated. + overwrite_a : if true, allows modification of A which may improve + performance. if false, A is not modified. + + output: + U : an orthogonal matrix: U' U = 1. if full_matrices is true, U is of + shape (m, m). ortherwise it is of shape (m, min(m, n)). + + S : an array of length min(m, n) containing the singular values of A sorted by + decreasing magnitude. + + V : an orthogonal matrix: V V' = 1. if full_matrices is true, V is of + shape (n, n). ortherwise it is of shape (min(m, n), n). + + return value: + + S if compute_uv is false + (U, S, V) if compute_uv is true + + overview of the matrices: + + full_matrices true: + A : m*n + U : m*m U' U = 1 + S as matrix : m*n + V : n*n V V' = 1 + + full_matrices false: + A : m*n + U : m*min(n,m) U' U = 1 + S as matrix : min(m,n)*min(m,n) + V : min(m,n)*n V V' = 1 + + examples: + + >>> from mpmath import mp + >>> A = mp.matrix([[2, -2, -1], [3, 4, -2], [-2, -2, 0]]) + >>> S = mp.svd_r(A, compute_uv = False) + >>> print(S) + [6.0] + [3.0] + [1.0] + + >>> U, S, V = mp.svd_r(A) + >>> print(mp.chop(A - U * mp.diag(S) * V)) + [0.0 0.0 0.0] + [0.0 0.0 0.0] + [0.0 0.0 0.0] + + + see also: svd, svd_c + """ + + m, n = A.rows, A.cols + + if not compute_uv: + if not overwrite_a: + A = A.copy() + S = svd_r_raw(ctx, A, V = False, calc_u = False) + S = S[:min(m,n)] + return S + + if full_matrices and n < m: + V = ctx.zeros(m, m) + A0 = ctx.zeros(m, m) + A0[:,:n] = A + S = svd_r_raw(ctx, A0, V, calc_u = True) + + S = S[:n] + V = V[:n,:n] + + return (A0, S, V) + else: + if not overwrite_a: + A = A.copy() + V = ctx.zeros(n, n) + S = svd_r_raw(ctx, A, V, calc_u = True) + + if n > m: + if full_matrices == False: + V = V[:m,:] + + S = S[:m] + A = A[:,:m] + + return (A, S, V) + +############################## + +@defun +def svd_c(ctx, A, full_matrices = False, compute_uv = True, overwrite_a = False): + """ + This routine computes the singular value decomposition of a matrix A. + Given A, two unitary matrices U and V are calculated such that + + A = U S V and U' U = 1 and V V' = 1 + + where S is a suitable shaped matrix whose off-diagonal elements are zero. + Here ' denotes the hermitian transpose (i.e. transposition and complex + conjugation). The diagonal elements of S are the singular values of A, + i.e. the squareroots of the eigenvalues of A' A or A A'. + + input: + A : a complex matrix of shape (m, n) + full_matrices : if true, U and V are of shape (m, m) and (n, n). + if false, U and V are of shape (m, min(m, n)) and (min(m, n), n). + compute_uv : if true, U and V are calculated. if false, only S is calculated. + overwrite_a : if true, allows modification of A which may improve + performance. if false, A is not modified. + + output: + U : an unitary matrix: U' U = 1. if full_matrices is true, U is of + shape (m, m). ortherwise it is of shape (m, min(m, n)). + + S : an array of length min(m, n) containing the singular values of A sorted by + decreasing magnitude. + + V : an unitary matrix: V V' = 1. if full_matrices is true, V is of + shape (n, n). ortherwise it is of shape (min(m, n), n). + + return value: + + S if compute_uv is false + (U, S, V) if compute_uv is true + + overview of the matrices: + + full_matrices true: + A : m*n + U : m*m U' U = 1 + S as matrix : m*n + V : n*n V V' = 1 + + full_matrices false: + A : m*n + U : m*min(n,m) U' U = 1 + S as matrix : min(m,n)*min(m,n) + V : min(m,n)*n V V' = 1 + + example: + >>> from mpmath import mp + >>> A = mp.matrix([[-2j, -1-3j, -2+2j], [2-2j, -1-3j, 1], [-3+1j,-2j,0]]) + >>> S = mp.svd_c(A, compute_uv = False) + >>> print(mp.chop(S - mp.matrix([mp.sqrt(34), mp.sqrt(15), mp.sqrt(6)]))) + [0.0] + [0.0] + [0.0] + + >>> U, S, V = mp.svd_c(A) + >>> print(mp.chop(A - U * mp.diag(S) * V)) + [0.0 0.0 0.0] + [0.0 0.0 0.0] + [0.0 0.0 0.0] + + see also: svd, svd_r + """ + + m, n = A.rows, A.cols + + if not compute_uv: + if not overwrite_a: + A = A.copy() + S = svd_c_raw(ctx, A, V = False, calc_u = False) + S = S[:min(m,n)] + return S + + if full_matrices and n < m: + V = ctx.zeros(m, m) + A0 = ctx.zeros(m, m) + A0[:,:n] = A + S = svd_c_raw(ctx, A0, V, calc_u = True) + + S = S[:n] + V = V[:n,:n] + + return (A0, S, V) + else: + if not overwrite_a: + A = A.copy() + V = ctx.zeros(n, n) + S = svd_c_raw(ctx, A, V, calc_u = True) + + if n > m: + if full_matrices == False: + V = V[:m,:] + + S = S[:m] + A = A[:,:m] + + return (A, S, V) + +@defun +def svd(ctx, A, full_matrices = False, compute_uv = True, overwrite_a = False): + """ + "svd" is a unified interface for "svd_r" and "svd_c". Depending on + whether A is real or complex the appropriate function is called. + + This routine computes the singular value decomposition of a matrix A. + Given A, two orthogonal (A real) or unitary (A complex) matrices U and V + are calculated such that + + A = U S V and U' U = 1 and V V' = 1 + + where S is a suitable shaped matrix whose off-diagonal elements are zero. + Here ' denotes the hermitian transpose (i.e. transposition and complex + conjugation). The diagonal elements of S are the singular values of A, + i.e. the squareroots of the eigenvalues of A' A or A A'. + + input: + A : a real or complex matrix of shape (m, n) + full_matrices : if true, U and V are of shape (m, m) and (n, n). + if false, U and V are of shape (m, min(m, n)) and (min(m, n), n). + compute_uv : if true, U and V are calculated. if false, only S is calculated. + overwrite_a : if true, allows modification of A which may improve + performance. if false, A is not modified. + + output: + U : an orthogonal or unitary matrix: U' U = 1. if full_matrices is true, U is of + shape (m, m). ortherwise it is of shape (m, min(m, n)). + + S : an array of length min(m, n) containing the singular values of A sorted by + decreasing magnitude. + + V : an orthogonal or unitary matrix: V V' = 1. if full_matrices is true, V is of + shape (n, n). ortherwise it is of shape (min(m, n), n). + + return value: + + S if compute_uv is false + (U, S, V) if compute_uv is true + + overview of the matrices: + + full_matrices true: + A : m*n + U : m*m U' U = 1 + S as matrix : m*n + V : n*n V V' = 1 + + full_matrices false: + A : m*n + U : m*min(n,m) U' U = 1 + S as matrix : min(m,n)*min(m,n) + V : min(m,n)*n V V' = 1 + + examples: + + >>> from mpmath import mp + >>> A = mp.matrix([[2, -2, -1], [3, 4, -2], [-2, -2, 0]]) + >>> S = mp.svd(A, compute_uv = False) + >>> print(S) + [6.0] + [3.0] + [1.0] + + >>> U, S, V = mp.svd(A) + >>> print(mp.chop(A - U * mp.diag(S) * V)) + [0.0 0.0 0.0] + [0.0 0.0 0.0] + [0.0 0.0 0.0] + + see also: svd_r, svd_c + """ + + iscomplex = any(type(x) is ctx.mpc for x in A) + + if iscomplex: + return ctx.svd_c(A, full_matrices = full_matrices, compute_uv = compute_uv, overwrite_a = overwrite_a) + else: + return ctx.svd_r(A, full_matrices = full_matrices, compute_uv = compute_uv, overwrite_a = overwrite_a) diff --git a/venv/lib/python3.10/site-packages/mpmath/matrices/linalg.py b/venv/lib/python3.10/site-packages/mpmath/matrices/linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..e2fe643e809822e3d05a52b73c965edb622f9af9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/matrices/linalg.py @@ -0,0 +1,790 @@ +""" +Linear algebra +-------------- + +Linear equations +................ + +Basic linear algebra is implemented; you can for example solve the linear +equation system:: + + x + 2*y = -10 + 3*x + 4*y = 10 + +using ``lu_solve``:: + + >>> from mpmath import * + >>> mp.pretty = False + >>> A = matrix([[1, 2], [3, 4]]) + >>> b = matrix([-10, 10]) + >>> x = lu_solve(A, b) + >>> x + matrix( + [['30.0'], + ['-20.0']]) + +If you don't trust the result, use ``residual`` to calculate the residual ||A*x-b||:: + + >>> residual(A, x, b) + matrix( + [['3.46944695195361e-18'], + ['3.46944695195361e-18']]) + >>> str(eps) + '2.22044604925031e-16' + +As you can see, the solution is quite accurate. The error is caused by the +inaccuracy of the internal floating point arithmetic. Though, it's even smaller +than the current machine epsilon, which basically means you can trust the +result. + +If you need more speed, use NumPy, or ``fp.lu_solve`` for a floating-point computation. + + >>> fp.lu_solve(A, b) # doctest: +ELLIPSIS + matrix(...) + +``lu_solve`` accepts overdetermined systems. It is usually not possible to solve +such systems, so the residual is minimized instead. Internally this is done +using Cholesky decomposition to compute a least squares approximation. This means +that that ``lu_solve`` will square the errors. If you can't afford this, use +``qr_solve`` instead. It is twice as slow but more accurate, and it calculates +the residual automatically. + + +Matrix factorization +.................... + +The function ``lu`` computes an explicit LU factorization of a matrix:: + + >>> P, L, U = lu(matrix([[0,2,3],[4,5,6],[7,8,9]])) + >>> print(P) + [0.0 0.0 1.0] + [1.0 0.0 0.0] + [0.0 1.0 0.0] + >>> print(L) + [ 1.0 0.0 0.0] + [ 0.0 1.0 0.0] + [0.571428571428571 0.214285714285714 1.0] + >>> print(U) + [7.0 8.0 9.0] + [0.0 2.0 3.0] + [0.0 0.0 0.214285714285714] + >>> print(P.T*L*U) + [0.0 2.0 3.0] + [4.0 5.0 6.0] + [7.0 8.0 9.0] + +Interval matrices +----------------- + +Matrices may contain interval elements. This allows one to perform +basic linear algebra operations such as matrix multiplication +and equation solving with rigorous error bounds:: + + >>> a = iv.matrix([['0.1','0.3','1.0'], + ... ['7.1','5.5','4.8'], + ... ['3.2','4.4','5.6']]) + >>> + >>> b = iv.matrix(['4','0.6','0.5']) + >>> c = iv.lu_solve(a, b) + >>> print(c) + [ [5.2582327113062568605927528666, 5.25823271130625686059275702219]] + [[-13.1550493962678375411635581388, -13.1550493962678375411635540152]] + [ [7.42069154774972557628979076189, 7.42069154774972557628979190734]] + >>> print(a*c) + [ [3.99999999999999999999999844904, 4.00000000000000000000000155096]] + [[0.599999999999999999999968898009, 0.600000000000000000000031763736]] + [[0.499999999999999999999979320485, 0.500000000000000000000020679515]] +""" + +# TODO: +# *implement high-level qr() +# *test unitvector +# *iterative solving + +from copy import copy + +from ..libmp.backend import xrange + +class LinearAlgebraMethods(object): + + def LU_decomp(ctx, A, overwrite=False, use_cache=True): + """ + LU-factorization of a n*n matrix using the Gauss algorithm. + Returns L and U in one matrix and the pivot indices. + + Use overwrite to specify whether A will be overwritten with L and U. + """ + if not A.rows == A.cols: + raise ValueError('need n*n matrix') + # get from cache if possible + if use_cache and isinstance(A, ctx.matrix) and A._LU: + return A._LU + if not overwrite: + orig = A + A = A.copy() + tol = ctx.absmin(ctx.mnorm(A,1) * ctx.eps) # each pivot element has to be bigger + n = A.rows + p = [None]*(n - 1) + for j in xrange(n - 1): + # pivoting, choose max(abs(reciprocal row sum)*abs(pivot element)) + biggest = 0 + for k in xrange(j, n): + s = ctx.fsum([ctx.absmin(A[k,l]) for l in xrange(j, n)]) + if ctx.absmin(s) <= tol: + raise ZeroDivisionError('matrix is numerically singular') + current = 1/s * ctx.absmin(A[k,j]) + if current > biggest: # TODO: what if equal? + biggest = current + p[j] = k + # swap rows according to p + ctx.swap_row(A, j, p[j]) + if ctx.absmin(A[j,j]) <= tol: + raise ZeroDivisionError('matrix is numerically singular') + # calculate elimination factors and add rows + for i in xrange(j + 1, n): + A[i,j] /= A[j,j] + for k in xrange(j + 1, n): + A[i,k] -= A[i,j]*A[j,k] + if ctx.absmin(A[n - 1,n - 1]) <= tol: + raise ZeroDivisionError('matrix is numerically singular') + # cache decomposition + if not overwrite and isinstance(orig, ctx.matrix): + orig._LU = (A, p) + return A, p + + def L_solve(ctx, L, b, p=None): + """ + Solve the lower part of a LU factorized matrix for y. + """ + if L.rows != L.cols: + raise RuntimeError("need n*n matrix") + n = L.rows + if len(b) != n: + raise ValueError("Value should be equal to n") + b = copy(b) + if p: # swap b according to p + for k in xrange(0, len(p)): + ctx.swap_row(b, k, p[k]) + # solve + for i in xrange(1, n): + for j in xrange(i): + b[i] -= L[i,j] * b[j] + return b + + def U_solve(ctx, U, y): + """ + Solve the upper part of a LU factorized matrix for x. + """ + if U.rows != U.cols: + raise RuntimeError("need n*n matrix") + n = U.rows + if len(y) != n: + raise ValueError("Value should be equal to n") + x = copy(y) + for i in xrange(n - 1, -1, -1): + for j in xrange(i + 1, n): + x[i] -= U[i,j] * x[j] + x[i] /= U[i,i] + return x + + def lu_solve(ctx, A, b, **kwargs): + """ + Ax = b => x + + Solve a determined or overdetermined linear equations system. + Fast LU decomposition is used, which is less accurate than QR decomposition + (especially for overdetermined systems), but it's twice as efficient. + Use qr_solve if you want more precision or have to solve a very ill- + conditioned system. + + If you specify real=True, it does not check for overdeterminded complex + systems. + """ + prec = ctx.prec + try: + ctx.prec += 10 + # do not overwrite A nor b + A, b = ctx.matrix(A, **kwargs).copy(), ctx.matrix(b, **kwargs).copy() + if A.rows < A.cols: + raise ValueError('cannot solve underdetermined system') + if A.rows > A.cols: + # use least-squares method if overdetermined + # (this increases errors) + AH = A.H + A = AH * A + b = AH * b + if (kwargs.get('real', False) or + not sum(type(i) is ctx.mpc for i in A)): + # TODO: necessary to check also b? + x = ctx.cholesky_solve(A, b) + else: + x = ctx.lu_solve(A, b) + else: + # LU factorization + A, p = ctx.LU_decomp(A) + b = ctx.L_solve(A, b, p) + x = ctx.U_solve(A, b) + finally: + ctx.prec = prec + return x + + def improve_solution(ctx, A, x, b, maxsteps=1): + """ + Improve a solution to a linear equation system iteratively. + + This re-uses the LU decomposition and is thus cheap. + Usually 3 up to 4 iterations are giving the maximal improvement. + """ + if A.rows != A.cols: + raise RuntimeError("need n*n matrix") # TODO: really? + for _ in xrange(maxsteps): + r = ctx.residual(A, x, b) + if ctx.norm(r, 2) < 10*ctx.eps: + break + # this uses cached LU decomposition and is thus cheap + dx = ctx.lu_solve(A, -r) + x += dx + return x + + def lu(ctx, A): + """ + A -> P, L, U + + LU factorisation of a square matrix A. L is the lower, U the upper part. + P is the permutation matrix indicating the row swaps. + + P*A = L*U + + If you need efficiency, use the low-level method LU_decomp instead, it's + much more memory efficient. + """ + # get factorization + A, p = ctx.LU_decomp(A) + n = A.rows + L = ctx.matrix(n) + U = ctx.matrix(n) + for i in xrange(n): + for j in xrange(n): + if i > j: + L[i,j] = A[i,j] + elif i == j: + L[i,j] = 1 + U[i,j] = A[i,j] + else: + U[i,j] = A[i,j] + # calculate permutation matrix + P = ctx.eye(n) + for k in xrange(len(p)): + ctx.swap_row(P, k, p[k]) + return P, L, U + + def unitvector(ctx, n, i): + """ + Return the i-th n-dimensional unit vector. + """ + assert 0 < i <= n, 'this unit vector does not exist' + return [ctx.zero]*(i-1) + [ctx.one] + [ctx.zero]*(n-i) + + def inverse(ctx, A, **kwargs): + """ + Calculate the inverse of a matrix. + + If you want to solve an equation system Ax = b, it's recommended to use + solve(A, b) instead, it's about 3 times more efficient. + """ + prec = ctx.prec + try: + ctx.prec += 10 + # do not overwrite A + A = ctx.matrix(A, **kwargs).copy() + n = A.rows + # get LU factorisation + A, p = ctx.LU_decomp(A) + cols = [] + # calculate unit vectors and solve corresponding system to get columns + for i in xrange(1, n + 1): + e = ctx.unitvector(n, i) + y = ctx.L_solve(A, e, p) + cols.append(ctx.U_solve(A, y)) + # convert columns to matrix + inv = [] + for i in xrange(n): + row = [] + for j in xrange(n): + row.append(cols[j][i]) + inv.append(row) + result = ctx.matrix(inv, **kwargs) + finally: + ctx.prec = prec + return result + + def householder(ctx, A): + """ + (A|b) -> H, p, x, res + + (A|b) is the coefficient matrix with left hand side of an optionally + overdetermined linear equation system. + H and p contain all information about the transformation matrices. + x is the solution, res the residual. + """ + if not isinstance(A, ctx.matrix): + raise TypeError("A should be a type of ctx.matrix") + m = A.rows + n = A.cols + if m < n - 1: + raise RuntimeError("Columns should not be less than rows") + # calculate Householder matrix + p = [] + for j in xrange(0, n - 1): + s = ctx.fsum(abs(A[i,j])**2 for i in xrange(j, m)) + if not abs(s) > ctx.eps: + raise ValueError('matrix is numerically singular') + p.append(-ctx.sign(ctx.re(A[j,j])) * ctx.sqrt(s)) + kappa = ctx.one / (s - p[j] * A[j,j]) + A[j,j] -= p[j] + for k in xrange(j+1, n): + y = ctx.fsum(ctx.conj(A[i,j]) * A[i,k] for i in xrange(j, m)) * kappa + for i in xrange(j, m): + A[i,k] -= A[i,j] * y + # solve Rx = c1 + x = [A[i,n - 1] for i in xrange(n - 1)] + for i in xrange(n - 2, -1, -1): + x[i] -= ctx.fsum(A[i,j] * x[j] for j in xrange(i + 1, n - 1)) + x[i] /= p[i] + # calculate residual + if not m == n - 1: + r = [A[m-1-i, n-1] for i in xrange(m - n + 1)] + else: + # determined system, residual should be 0 + r = [0]*m # maybe a bad idea, changing r[i] will change all elements + return A, p, x, r + + #def qr(ctx, A): + # """ + # A -> Q, R + # + # QR factorisation of a square matrix A using Householder decomposition. + # Q is orthogonal, this leads to very few numerical errors. + # + # A = Q*R + # """ + # H, p, x, res = householder(A) + # TODO: implement this + + def residual(ctx, A, x, b, **kwargs): + """ + Calculate the residual of a solution to a linear equation system. + + r = A*x - b for A*x = b + """ + oldprec = ctx.prec + try: + ctx.prec *= 2 + A, x, b = ctx.matrix(A, **kwargs), ctx.matrix(x, **kwargs), ctx.matrix(b, **kwargs) + return A*x - b + finally: + ctx.prec = oldprec + + def qr_solve(ctx, A, b, norm=None, **kwargs): + """ + Ax = b => x, ||Ax - b|| + + Solve a determined or overdetermined linear equations system and + calculate the norm of the residual (error). + QR decomposition using Householder factorization is applied, which gives very + accurate results even for ill-conditioned matrices. qr_solve is twice as + efficient. + """ + if norm is None: + norm = ctx.norm + prec = ctx.prec + try: + ctx.prec += 10 + # do not overwrite A nor b + A, b = ctx.matrix(A, **kwargs).copy(), ctx.matrix(b, **kwargs).copy() + if A.rows < A.cols: + raise ValueError('cannot solve underdetermined system') + H, p, x, r = ctx.householder(ctx.extend(A, b)) + res = ctx.norm(r) + # calculate residual "manually" for determined systems + if res == 0: + res = ctx.norm(ctx.residual(A, x, b)) + return ctx.matrix(x, **kwargs), res + finally: + ctx.prec = prec + + def cholesky(ctx, A, tol=None): + r""" + Cholesky decomposition of a symmetric positive-definite matrix `A`. + Returns a lower triangular matrix `L` such that `A = L \times L^T`. + More generally, for a complex Hermitian positive-definite matrix, + a Cholesky decomposition satisfying `A = L \times L^H` is returned. + + The Cholesky decomposition can be used to solve linear equation + systems twice as efficiently as LU decomposition, or to + test whether `A` is positive-definite. + + The optional parameter ``tol`` determines the tolerance for + verifying positive-definiteness. + + **Examples** + + Cholesky decomposition of a positive-definite symmetric matrix:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> A = eye(3) + hilbert(3) + >>> nprint(A) + [ 2.0 0.5 0.333333] + [ 0.5 1.33333 0.25] + [0.333333 0.25 1.2] + >>> L = cholesky(A) + >>> nprint(L) + [ 1.41421 0.0 0.0] + [0.353553 1.09924 0.0] + [0.235702 0.15162 1.05899] + >>> chop(A - L*L.T) + [0.0 0.0 0.0] + [0.0 0.0 0.0] + [0.0 0.0 0.0] + + Cholesky decomposition of a Hermitian matrix:: + + >>> A = eye(3) + matrix([[0,0.25j,-0.5j],[-0.25j,0,0],[0.5j,0,0]]) + >>> L = cholesky(A) + >>> nprint(L) + [ 1.0 0.0 0.0] + [(0.0 - 0.25j) (0.968246 + 0.0j) 0.0] + [ (0.0 + 0.5j) (0.129099 + 0.0j) (0.856349 + 0.0j)] + >>> chop(A - L*L.H) + [0.0 0.0 0.0] + [0.0 0.0 0.0] + [0.0 0.0 0.0] + + Attempted Cholesky decomposition of a matrix that is not positive + definite:: + + >>> A = -eye(3) + hilbert(3) + >>> L = cholesky(A) + Traceback (most recent call last): + ... + ValueError: matrix is not positive-definite + + **References** + + 1. [Wikipedia]_ http://en.wikipedia.org/wiki/Cholesky_decomposition + + """ + if not isinstance(A, ctx.matrix): + raise RuntimeError("A should be a type of ctx.matrix") + if not A.rows == A.cols: + raise ValueError('need n*n matrix') + if tol is None: + tol = +ctx.eps + n = A.rows + L = ctx.matrix(n) + for j in xrange(n): + c = ctx.re(A[j,j]) + if abs(c-A[j,j]) > tol: + raise ValueError('matrix is not Hermitian') + s = c - ctx.fsum((L[j,k] for k in xrange(j)), + absolute=True, squared=True) + if s < tol: + raise ValueError('matrix is not positive-definite') + L[j,j] = ctx.sqrt(s) + for i in xrange(j, n): + it1 = (L[i,k] for k in xrange(j)) + it2 = (L[j,k] for k in xrange(j)) + t = ctx.fdot(it1, it2, conjugate=True) + L[i,j] = (A[i,j] - t) / L[j,j] + return L + + def cholesky_solve(ctx, A, b, **kwargs): + """ + Ax = b => x + + Solve a symmetric positive-definite linear equation system. + This is twice as efficient as lu_solve. + + Typical use cases: + * A.T*A + * Hessian matrix + * differential equations + """ + prec = ctx.prec + try: + ctx.prec += 10 + # do not overwrite A nor b + A, b = ctx.matrix(A, **kwargs).copy(), ctx.matrix(b, **kwargs).copy() + if A.rows != A.cols: + raise ValueError('can only solve determined system') + # Cholesky factorization + L = ctx.cholesky(A) + # solve + n = L.rows + if len(b) != n: + raise ValueError("Value should be equal to n") + for i in xrange(n): + b[i] -= ctx.fsum(L[i,j] * b[j] for j in xrange(i)) + b[i] /= L[i,i] + x = ctx.U_solve(L.T, b) + return x + finally: + ctx.prec = prec + + def det(ctx, A): + """ + Calculate the determinant of a matrix. + """ + prec = ctx.prec + try: + # do not overwrite A + A = ctx.matrix(A).copy() + # use LU factorization to calculate determinant + try: + R, p = ctx.LU_decomp(A) + except ZeroDivisionError: + return 0 + z = 1 + for i, e in enumerate(p): + if i != e: + z *= -1 + for i in xrange(A.rows): + z *= R[i,i] + return z + finally: + ctx.prec = prec + + def cond(ctx, A, norm=None): + """ + Calculate the condition number of a matrix using a specified matrix norm. + + The condition number estimates the sensitivity of a matrix to errors. + Example: small input errors for ill-conditioned coefficient matrices + alter the solution of the system dramatically. + + For ill-conditioned matrices it's recommended to use qr_solve() instead + of lu_solve(). This does not help with input errors however, it just avoids + to add additional errors. + + Definition: cond(A) = ||A|| * ||A**-1|| + """ + if norm is None: + norm = lambda x: ctx.mnorm(x,1) + return norm(A) * norm(ctx.inverse(A)) + + def lu_solve_mat(ctx, a, b): + """Solve a * x = b where a and b are matrices.""" + r = ctx.matrix(a.rows, b.cols) + for i in range(b.cols): + c = ctx.lu_solve(a, b.column(i)) + for j in range(len(c)): + r[j, i] = c[j] + return r + + def qr(ctx, A, mode = 'full', edps = 10): + """ + Compute a QR factorization $A = QR$ where + A is an m x n matrix of real or complex numbers where m >= n + + mode has following meanings: + (1) mode = 'raw' returns two matrixes (A, tau) in the + internal format used by LAPACK + (2) mode = 'skinny' returns the leading n columns of Q + and n rows of R + (3) Any other value returns the leading m columns of Q + and m rows of R + + edps is the increase in mp precision used for calculations + + **Examples** + + >>> from mpmath import * + >>> mp.dps = 15 + >>> mp.pretty = True + >>> A = matrix([[1, 2], [3, 4], [1, 1]]) + >>> Q, R = qr(A) + >>> Q + [-0.301511344577764 0.861640436855329 0.408248290463863] + [-0.904534033733291 -0.123091490979333 -0.408248290463863] + [-0.301511344577764 -0.492365963917331 0.816496580927726] + >>> R + [-3.3166247903554 -4.52267016866645] + [ 0.0 0.738548945875996] + [ 0.0 0.0] + >>> Q * R + [1.0 2.0] + [3.0 4.0] + [1.0 1.0] + >>> chop(Q.T * Q) + [1.0 0.0 0.0] + [0.0 1.0 0.0] + [0.0 0.0 1.0] + >>> B = matrix([[1+0j, 2-3j], [3+j, 4+5j]]) + >>> Q, R = qr(B) + >>> nprint(Q) + [ (-0.301511 + 0.0j) (0.0695795 - 0.95092j)] + [(-0.904534 - 0.301511j) (-0.115966 + 0.278318j)] + >>> nprint(R) + [(-3.31662 + 0.0j) (-5.72872 - 2.41209j)] + [ 0.0 (3.91965 + 0.0j)] + >>> Q * R + [(1.0 + 0.0j) (2.0 - 3.0j)] + [(3.0 + 1.0j) (4.0 + 5.0j)] + >>> chop(Q.T * Q.conjugate()) + [1.0 0.0] + [0.0 1.0] + + """ + + # check values before continuing + assert isinstance(A, ctx.matrix) + m = A.rows + n = A.cols + assert n >= 0 + assert m >= n + assert edps >= 0 + + # check for complex data type + cmplx = any(type(x) is ctx.mpc for x in A) + + # temporarily increase the precision and initialize + with ctx.extradps(edps): + tau = ctx.matrix(n,1) + A = A.copy() + + # --------------- + # FACTOR MATRIX A + # --------------- + if cmplx: + one = ctx.mpc('1.0', '0.0') + zero = ctx.mpc('0.0', '0.0') + rzero = ctx.mpf('0.0') + + # main loop to factor A (complex) + for j in xrange(0, n): + alpha = A[j,j] + alphr = ctx.re(alpha) + alphi = ctx.im(alpha) + + if (m-j) >= 2: + xnorm = ctx.fsum( A[i,j]*ctx.conj(A[i,j]) for i in xrange(j+1, m) ) + xnorm = ctx.re( ctx.sqrt(xnorm) ) + else: + xnorm = rzero + + if (xnorm == rzero) and (alphi == rzero): + tau[j] = zero + continue + + if alphr < rzero: + beta = ctx.sqrt(alphr**2 + alphi**2 + xnorm**2) + else: + beta = -ctx.sqrt(alphr**2 + alphi**2 + xnorm**2) + + tau[j] = ctx.mpc( (beta - alphr) / beta, -alphi / beta ) + t = -ctx.conj(tau[j]) + za = one / (alpha - beta) + + for i in xrange(j+1, m): + A[i,j] *= za + + A[j,j] = one + for k in xrange(j+1, n): + y = ctx.fsum(A[i,j] * ctx.conj(A[i,k]) for i in xrange(j, m)) + temp = t * ctx.conj(y) + for i in xrange(j, m): + A[i,k] += A[i,j] * temp + + A[j,j] = ctx.mpc(beta, '0.0') + else: + one = ctx.mpf('1.0') + zero = ctx.mpf('0.0') + + # main loop to factor A (real) + for j in xrange(0, n): + alpha = A[j,j] + + if (m-j) > 2: + xnorm = ctx.fsum( (A[i,j])**2 for i in xrange(j+1, m) ) + xnorm = ctx.sqrt(xnorm) + elif (m-j) == 2: + xnorm = abs( A[m-1,j] ) + else: + xnorm = zero + + if xnorm == zero: + tau[j] = zero + continue + + if alpha < zero: + beta = ctx.sqrt(alpha**2 + xnorm**2) + else: + beta = -ctx.sqrt(alpha**2 + xnorm**2) + + tau[j] = (beta - alpha) / beta + t = -tau[j] + da = one / (alpha - beta) + + for i in xrange(j+1, m): + A[i,j] *= da + + A[j,j] = one + for k in xrange(j+1, n): + y = ctx.fsum( A[i,j] * A[i,k] for i in xrange(j, m) ) + temp = t * y + for i in xrange(j,m): + A[i,k] += A[i,j] * temp + + A[j,j] = beta + + # return factorization in same internal format as LAPACK + if (mode == 'raw') or (mode == 'RAW'): + return A, tau + + # ---------------------------------- + # FORM Q USING BACKWARD ACCUMULATION + # ---------------------------------- + + # form R before the values are overwritten + R = A.copy() + for j in xrange(0, n): + for i in xrange(j+1, m): + R[i,j] = zero + + # set the value of p (number of columns of Q to return) + p = m + if (mode == 'skinny') or (mode == 'SKINNY'): + p = n + + # add columns to A if needed and initialize + A.cols += (p-n) + for j in xrange(0, p): + A[j,j] = one + for i in xrange(0, j): + A[i,j] = zero + + # main loop to form Q + for j in xrange(n-1, -1, -1): + t = -tau[j] + A[j,j] += t + + for k in xrange(j+1, p): + if cmplx: + y = ctx.fsum(A[i,j] * ctx.conj(A[i,k]) for i in xrange(j+1, m)) + temp = t * ctx.conj(y) + else: + y = ctx.fsum(A[i,j] * A[i,k] for i in xrange(j+1, m)) + temp = t * y + A[j,k] = temp + for i in xrange(j+1, m): + A[i,k] += A[i,j] * temp + + for i in xrange(j+1, m): + A[i, j] *= t + + return A, R[0:p,0:n] + + # ------------------ + # END OF FUNCTION QR + # ------------------ diff --git a/venv/lib/python3.10/site-packages/mpmath/matrices/matrices.py b/venv/lib/python3.10/site-packages/mpmath/matrices/matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..a97d5a9ca7e173195386dc7cb60860a826ab6a97 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/matrices/matrices.py @@ -0,0 +1,1005 @@ +from ..libmp.backend import xrange +import warnings + +# TODO: interpret list as vectors (for multiplication) + +rowsep = '\n' +colsep = ' ' + +class _matrix(object): + """ + Numerical matrix. + + Specify the dimensions or the data as a nested list. + Elements default to zero. + Use a flat list to create a column vector easily. + + The datatype of the context (mpf for mp, mpi for iv, and float for fp) is used to store the data. + + Creating matrices + ----------------- + + Matrices in mpmath are implemented using dictionaries. Only non-zero values + are stored, so it is cheap to represent sparse matrices. + + The most basic way to create one is to use the ``matrix`` class directly. + You can create an empty matrix specifying the dimensions: + + >>> from mpmath import * + >>> mp.dps = 15 + >>> matrix(2) + matrix( + [['0.0', '0.0'], + ['0.0', '0.0']]) + >>> matrix(2, 3) + matrix( + [['0.0', '0.0', '0.0'], + ['0.0', '0.0', '0.0']]) + + Calling ``matrix`` with one dimension will create a square matrix. + + To access the dimensions of a matrix, use the ``rows`` or ``cols`` keyword: + + >>> A = matrix(3, 2) + >>> A + matrix( + [['0.0', '0.0'], + ['0.0', '0.0'], + ['0.0', '0.0']]) + >>> A.rows + 3 + >>> A.cols + 2 + + You can also change the dimension of an existing matrix. This will set the + new elements to 0. If the new dimension is smaller than before, the + concerning elements are discarded: + + >>> A.rows = 2 + >>> A + matrix( + [['0.0', '0.0'], + ['0.0', '0.0']]) + + Internally ``mpmathify`` is used every time an element is set. This + is done using the syntax A[row,column], counting from 0: + + >>> A = matrix(2) + >>> A[1,1] = 1 + 1j + >>> A + matrix( + [['0.0', '0.0'], + ['0.0', mpc(real='1.0', imag='1.0')]]) + + A more comfortable way to create a matrix lets you use nested lists: + + >>> matrix([[1, 2], [3, 4]]) + matrix( + [['1.0', '2.0'], + ['3.0', '4.0']]) + + Convenient advanced functions are available for creating various standard + matrices, see ``zeros``, ``ones``, ``diag``, ``eye``, ``randmatrix`` and + ``hilbert``. + + Vectors + ....... + + Vectors may also be represented by the ``matrix`` class (with rows = 1 or cols = 1). + For vectors there are some things which make life easier. A column vector can + be created using a flat list, a row vectors using an almost flat nested list:: + + >>> matrix([1, 2, 3]) + matrix( + [['1.0'], + ['2.0'], + ['3.0']]) + >>> matrix([[1, 2, 3]]) + matrix( + [['1.0', '2.0', '3.0']]) + + Optionally vectors can be accessed like lists, using only a single index:: + + >>> x = matrix([1, 2, 3]) + >>> x[1] + mpf('2.0') + >>> x[1,0] + mpf('2.0') + + Other + ..... + + Like you probably expected, matrices can be printed:: + + >>> print randmatrix(3) # doctest:+SKIP + [ 0.782963853573023 0.802057689719883 0.427895717335467] + [0.0541876859348597 0.708243266653103 0.615134039977379] + [ 0.856151514955773 0.544759264818486 0.686210904770947] + + Use ``nstr`` or ``nprint`` to specify the number of digits to print:: + + >>> nprint(randmatrix(5), 3) # doctest:+SKIP + [2.07e-1 1.66e-1 5.06e-1 1.89e-1 8.29e-1] + [6.62e-1 6.55e-1 4.47e-1 4.82e-1 2.06e-2] + [4.33e-1 7.75e-1 6.93e-2 2.86e-1 5.71e-1] + [1.01e-1 2.53e-1 6.13e-1 3.32e-1 2.59e-1] + [1.56e-1 7.27e-2 6.05e-1 6.67e-2 2.79e-1] + + As matrices are mutable, you will need to copy them sometimes:: + + >>> A = matrix(2) + >>> A + matrix( + [['0.0', '0.0'], + ['0.0', '0.0']]) + >>> B = A.copy() + >>> B[0,0] = 1 + >>> B + matrix( + [['1.0', '0.0'], + ['0.0', '0.0']]) + >>> A + matrix( + [['0.0', '0.0'], + ['0.0', '0.0']]) + + Finally, it is possible to convert a matrix to a nested list. This is very useful, + as most Python libraries involving matrices or arrays (namely NumPy or SymPy) + support this format:: + + >>> B.tolist() + [[mpf('1.0'), mpf('0.0')], [mpf('0.0'), mpf('0.0')]] + + + Matrix operations + ----------------- + + You can add and subtract matrices of compatible dimensions:: + + >>> A = matrix([[1, 2], [3, 4]]) + >>> B = matrix([[-2, 4], [5, 9]]) + >>> A + B + matrix( + [['-1.0', '6.0'], + ['8.0', '13.0']]) + >>> A - B + matrix( + [['3.0', '-2.0'], + ['-2.0', '-5.0']]) + >>> A + ones(3) # doctest:+ELLIPSIS + Traceback (most recent call last): + ... + ValueError: incompatible dimensions for addition + + It is possible to multiply or add matrices and scalars. In the latter case the + operation will be done element-wise:: + + >>> A * 2 + matrix( + [['2.0', '4.0'], + ['6.0', '8.0']]) + >>> A / 4 + matrix( + [['0.25', '0.5'], + ['0.75', '1.0']]) + >>> A - 1 + matrix( + [['0.0', '1.0'], + ['2.0', '3.0']]) + + Of course you can perform matrix multiplication, if the dimensions are + compatible, using ``@`` (for Python >= 3.5) or ``*``. For clarity, ``@`` is + recommended (`PEP 465 `), because + the meaning of ``*`` is different in many other Python libraries such as NumPy. + + >>> A @ B # doctest:+SKIP + matrix( + [['8.0', '22.0'], + ['14.0', '48.0']]) + >>> A * B # same as A @ B + matrix( + [['8.0', '22.0'], + ['14.0', '48.0']]) + >>> matrix([[1, 2, 3]]) * matrix([[-6], [7], [-2]]) + matrix( + [['2.0']]) + + .. + COMMENT: TODO: the above "doctest:+SKIP" may be removed as soon as we + have dropped support for Python 3.5 and below. + + You can raise powers of square matrices:: + + >>> A**2 + matrix( + [['7.0', '10.0'], + ['15.0', '22.0']]) + + Negative powers will calculate the inverse:: + + >>> A**-1 + matrix( + [['-2.0', '1.0'], + ['1.5', '-0.5']]) + >>> A * A**-1 + matrix( + [['1.0', '1.0842021724855e-19'], + ['-2.16840434497101e-19', '1.0']]) + + + + Matrix transposition is straightforward:: + + >>> A = ones(2, 3) + >>> A + matrix( + [['1.0', '1.0', '1.0'], + ['1.0', '1.0', '1.0']]) + >>> A.T + matrix( + [['1.0', '1.0'], + ['1.0', '1.0'], + ['1.0', '1.0']]) + + Norms + ..... + + Sometimes you need to know how "large" a matrix or vector is. Due to their + multidimensional nature it's not possible to compare them, but there are + several functions to map a matrix or a vector to a positive real number, the + so called norms. + + For vectors the p-norm is intended, usually the 1-, the 2- and the oo-norm are + used. + + >>> x = matrix([-10, 2, 100]) + >>> norm(x, 1) + mpf('112.0') + >>> norm(x, 2) + mpf('100.5186549850325') + >>> norm(x, inf) + mpf('100.0') + + Please note that the 2-norm is the most used one, though it is more expensive + to calculate than the 1- or oo-norm. + + It is possible to generalize some vector norms to matrix norm:: + + >>> A = matrix([[1, -1000], [100, 50]]) + >>> mnorm(A, 1) + mpf('1050.0') + >>> mnorm(A, inf) + mpf('1001.0') + >>> mnorm(A, 'F') + mpf('1006.2310867787777') + + The last norm (the "Frobenius-norm") is an approximation for the 2-norm, which + is hard to calculate and not available. The Frobenius-norm lacks some + mathematical properties you might expect from a norm. + """ + + def __init__(self, *args, **kwargs): + self.__data = {} + # LU decompostion cache, this is useful when solving the same system + # multiple times, when calculating the inverse and when calculating the + # determinant + self._LU = None + if "force_type" in kwargs: + warnings.warn("The force_type argument was removed, it did not work" + " properly anyway. If you want to force floating-point or" + " interval computations, use the respective methods from `fp`" + " or `mp` instead, e.g., `fp.matrix()` or `iv.matrix()`." + " If you want to truncate values to integer, use .apply(int) instead.") + if isinstance(args[0], (list, tuple)): + if isinstance(args[0][0], (list, tuple)): + # interpret nested list as matrix + A = args[0] + self.__rows = len(A) + self.__cols = len(A[0]) + for i, row in enumerate(A): + for j, a in enumerate(row): + # note: this will call __setitem__ which will call self.ctx.convert() to convert the datatype. + self[i, j] = a + else: + # interpret list as row vector + v = args[0] + self.__rows = len(v) + self.__cols = 1 + for i, e in enumerate(v): + self[i, 0] = e + elif isinstance(args[0], int): + # create empty matrix of given dimensions + if len(args) == 1: + self.__rows = self.__cols = args[0] + else: + if not isinstance(args[1], int): + raise TypeError("expected int") + self.__rows = args[0] + self.__cols = args[1] + elif isinstance(args[0], _matrix): + A = args[0] + self.__rows = A._matrix__rows + self.__cols = A._matrix__cols + for i in xrange(A.__rows): + for j in xrange(A.__cols): + self[i, j] = A[i, j] + elif hasattr(args[0], 'tolist'): + A = self.ctx.matrix(args[0].tolist()) + self.__data = A._matrix__data + self.__rows = A._matrix__rows + self.__cols = A._matrix__cols + else: + raise TypeError('could not interpret given arguments') + + def apply(self, f): + """ + Return a copy of self with the function `f` applied elementwise. + """ + new = self.ctx.matrix(self.__rows, self.__cols) + for i in xrange(self.__rows): + for j in xrange(self.__cols): + new[i,j] = f(self[i,j]) + return new + + def __nstr__(self, n=None, **kwargs): + # 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): + if n: + string = self.ctx.nstr(self[i,j], n, **kwargs) + else: + string = str(self[i,j]) + res[-1].append(string) + maxlen[j] = max(len(string), maxlen[j]) + # Patch strings together + for i, row in enumerate(res): + for j, elem in enumerate(row): + # Pad each element up to maxlen so the columns line up + row[j] = elem.rjust(maxlen[j]) + res[i] = "[" + colsep.join(row) + "]" + return rowsep.join(res) + + def __str__(self): + return self.__nstr__() + + def _toliststr(self, avoid_type=False): + """ + Create a list string from a matrix. + + If avoid_type: avoid multiple 'mpf's. + """ + # XXX: should be something like self.ctx._types + typ = self.ctx.mpf + s = '[' + for i in xrange(self.__rows): + s += '[' + for j in xrange(self.__cols): + if not avoid_type or not isinstance(self[i,j], typ): + a = repr(self[i,j]) + else: + a = "'" + str(self[i,j]) + "'" + s += a + ', ' + s = s[:-2] + s += '],\n ' + s = s[:-3] + s += ']' + return s + + def tolist(self): + """ + Convert the matrix to a nested list. + """ + return [[self[i,j] for j in range(self.__cols)] for i in range(self.__rows)] + + def __repr__(self): + if self.ctx.pretty: + return self.__str__() + s = 'matrix(\n' + s += self._toliststr(avoid_type=True) + ')' + return s + + def __get_element(self, key): + ''' + Fast extraction of the i,j element from the matrix + This function is for private use only because is unsafe: + 1. Does not check on the value of key it expects key to be a integer tuple (i,j) + 2. Does not check bounds + ''' + if key in self.__data: + return self.__data[key] + else: + return self.ctx.zero + + def __set_element(self, key, value): + ''' + Fast assignment of the i,j element in the matrix + This function is unsafe: + 1. Does not check on the value of key it expects key to be a integer tuple (i,j) + 2. Does not check bounds + 3. Does not check the value type + 4. Does not reset the LU cache + ''' + if value: # only store non-zeros + self.__data[key] = value + elif key in self.__data: + del self.__data[key] + + + def __getitem__(self, key): + ''' + Getitem function for mp matrix class with slice index enabled + it allows the following assingments + scalar to a slice of the matrix + B = A[:,2:6] + ''' + # Convert vector to matrix indexing + if isinstance(key, int) or isinstance(key,slice): + # only sufficent for vectors + if self.__rows == 1: + key = (0, key) + elif self.__cols == 1: + key = (key, 0) + else: + raise IndexError('insufficient indices for matrix') + + if isinstance(key[0],slice) or isinstance(key[1],slice): + + #Rows + if isinstance(key[0],slice): + #Check bounds + if (key[0].start is None or key[0].start >= 0) and \ + (key[0].stop is None or key[0].stop <= self.__rows+1): + # Generate indices + rows = xrange(*key[0].indices(self.__rows)) + else: + raise IndexError('Row index out of bounds') + else: + # Single row + rows = [key[0]] + + # Columns + if isinstance(key[1],slice): + # Check bounds + if (key[1].start is None or key[1].start >= 0) and \ + (key[1].stop is None or key[1].stop <= self.__cols+1): + # Generate indices + columns = xrange(*key[1].indices(self.__cols)) + else: + raise IndexError('Column index out of bounds') + + else: + # Single column + columns = [key[1]] + + # Create matrix slice + m = self.ctx.matrix(len(rows),len(columns)) + + # Assign elements to the output matrix + for i,x in enumerate(rows): + for j,y in enumerate(columns): + m.__set_element((i,j),self.__get_element((x,y))) + + return m + + else: + # single element extraction + if key[0] >= self.__rows or key[1] >= self.__cols: + raise IndexError('matrix index out of range') + if key in self.__data: + return self.__data[key] + else: + return self.ctx.zero + + def __setitem__(self, key, value): + # setitem function for mp matrix class with slice index enabled + # it allows the following assingments + # scalar to a slice of the matrix + # A[:,2:6] = 2.5 + # submatrix to matrix (the value matrix should be the same size as the slice size) + # A[3,:] = B where A is n x m and B is n x 1 + # Convert vector to matrix indexing + if isinstance(key, int) or isinstance(key,slice): + # only sufficent for vectors + if self.__rows == 1: + key = (0, key) + elif self.__cols == 1: + key = (key, 0) + else: + raise IndexError('insufficient indices for matrix') + # Slice indexing + if isinstance(key[0],slice) or isinstance(key[1],slice): + # Rows + if isinstance(key[0],slice): + # Check bounds + if (key[0].start is None or key[0].start >= 0) and \ + (key[0].stop is None or key[0].stop <= self.__rows+1): + # generate row indices + rows = xrange(*key[0].indices(self.__rows)) + else: + raise IndexError('Row index out of bounds') + else: + # Single row + rows = [key[0]] + # Columns + if isinstance(key[1],slice): + # Check bounds + if (key[1].start is None or key[1].start >= 0) and \ + (key[1].stop is None or key[1].stop <= self.__cols+1): + # Generate column indices + columns = xrange(*key[1].indices(self.__cols)) + else: + raise IndexError('Column index out of bounds') + else: + # Single column + columns = [key[1]] + # Assign slice with a scalar + if isinstance(value,self.ctx.matrix): + # Assign elements to matrix if input and output dimensions match + if len(rows) == value.rows and len(columns) == value.cols: + for i,x in enumerate(rows): + for j,y in enumerate(columns): + self.__set_element((x,y), value.__get_element((i,j))) + else: + raise ValueError('Dimensions do not match') + else: + # Assign slice with scalars + value = self.ctx.convert(value) + for i in rows: + for j in columns: + self.__set_element((i,j), value) + else: + # Single element assingment + # Check bounds + if key[0] >= self.__rows or key[1] >= self.__cols: + raise IndexError('matrix index out of range') + # Convert and store value + value = self.ctx.convert(value) + if value: # only store non-zeros + self.__data[key] = value + elif key in self.__data: + del self.__data[key] + + if self._LU: + self._LU = None + return + + def __iter__(self): + for i in xrange(self.__rows): + for j in xrange(self.__cols): + yield self[i,j] + + def __mul__(self, other): + if isinstance(other, self.ctx.matrix): + # dot multiplication + if self.__cols != other.__rows: + raise ValueError('dimensions not compatible for multiplication') + new = self.ctx.matrix(self.__rows, other.__cols) + self_zero = self.ctx.zero + self_get = self.__data.get + other_zero = other.ctx.zero + other_get = other.__data.get + for i in xrange(self.__rows): + for j in xrange(other.__cols): + new[i, j] = self.ctx.fdot((self_get((i,k), self_zero), other_get((k,j), other_zero)) + for k in xrange(other.__rows)) + return new + else: + # try scalar multiplication + new = self.ctx.matrix(self.__rows, self.__cols) + for i in xrange(self.__rows): + for j in xrange(self.__cols): + new[i, j] = other * self[i, j] + return new + + def __matmul__(self, other): + return self.__mul__(other) + + def __rmul__(self, other): + # assume other is scalar and thus commutative + if isinstance(other, self.ctx.matrix): + raise TypeError("other should not be type of ctx.matrix") + return self.__mul__(other) + + def __pow__(self, other): + # avoid cyclic import problems + #from linalg import inverse + if not isinstance(other, int): + raise ValueError('only integer exponents are supported') + if not self.__rows == self.__cols: + raise ValueError('only powers of square matrices are defined') + n = other + if n == 0: + return self.ctx.eye(self.__rows) + if n < 0: + n = -n + neg = True + else: + neg = False + i = n + y = 1 + z = self.copy() + while i != 0: + if i % 2 == 1: + y = y * z + z = z*z + i = i // 2 + if neg: + y = self.ctx.inverse(y) + return y + + def __div__(self, other): + # assume other is scalar and do element-wise divison + assert not isinstance(other, self.ctx.matrix) + new = self.ctx.matrix(self.__rows, self.__cols) + for i in xrange(self.__rows): + for j in xrange(self.__cols): + new[i,j] = self[i,j] / other + return new + + __truediv__ = __div__ + + def __add__(self, other): + if isinstance(other, self.ctx.matrix): + if not (self.__rows == other.__rows and self.__cols == other.__cols): + raise ValueError('incompatible dimensions for addition') + new = self.ctx.matrix(self.__rows, self.__cols) + for i in xrange(self.__rows): + for j in xrange(self.__cols): + new[i,j] = self[i,j] + other[i,j] + return new + else: + # assume other is scalar and add element-wise + new = self.ctx.matrix(self.__rows, self.__cols) + for i in xrange(self.__rows): + for j in xrange(self.__cols): + new[i,j] += self[i,j] + other + return new + + def __radd__(self, other): + return self.__add__(other) + + def __sub__(self, other): + if isinstance(other, self.ctx.matrix) and not (self.__rows == other.__rows + and self.__cols == other.__cols): + raise ValueError('incompatible dimensions for subtraction') + return self.__add__(other * (-1)) + + def __pos__(self): + """ + +M returns a copy of M, rounded to current working precision. + """ + return (+1) * self + + def __neg__(self): + return (-1) * self + + def __rsub__(self, other): + return -self + other + + def __eq__(self, other): + return self.__rows == other.__rows and self.__cols == other.__cols \ + and self.__data == other.__data + + def __len__(self): + if self.rows == 1: + return self.cols + elif self.cols == 1: + return self.rows + else: + return self.rows # do it like numpy + + def __getrows(self): + return self.__rows + + def __setrows(self, value): + for key in self.__data.copy(): + if key[0] >= value: + del self.__data[key] + self.__rows = value + + rows = property(__getrows, __setrows, doc='number of rows') + + def __getcols(self): + return self.__cols + + def __setcols(self, value): + for key in self.__data.copy(): + if key[1] >= value: + del self.__data[key] + self.__cols = value + + cols = property(__getcols, __setcols, doc='number of columns') + + def transpose(self): + new = self.ctx.matrix(self.__cols, self.__rows) + for i in xrange(self.__rows): + for j in xrange(self.__cols): + new[j,i] = self[i,j] + return new + + T = property(transpose) + + def conjugate(self): + return self.apply(self.ctx.conj) + + def transpose_conj(self): + return self.conjugate().transpose() + + H = property(transpose_conj) + + def copy(self): + new = self.ctx.matrix(self.__rows, self.__cols) + new.__data = self.__data.copy() + return new + + __copy__ = copy + + def column(self, n): + m = self.ctx.matrix(self.rows, 1) + for i in range(self.rows): + m[i] = self[i,n] + return m + +class MatrixMethods(object): + + def __init__(ctx): + # XXX: subclass + ctx.matrix = type('matrix', (_matrix,), {}) + ctx.matrix.ctx = ctx + ctx.matrix.convert = ctx.convert + + def eye(ctx, n, **kwargs): + """ + Create square identity matrix n x n. + """ + A = ctx.matrix(n, **kwargs) + for i in xrange(n): + A[i,i] = 1 + return A + + def diag(ctx, diagonal, **kwargs): + """ + Create square diagonal matrix using given list. + + Example: + >>> from mpmath import diag, mp + >>> mp.pretty = False + >>> diag([1, 2, 3]) + matrix( + [['1.0', '0.0', '0.0'], + ['0.0', '2.0', '0.0'], + ['0.0', '0.0', '3.0']]) + """ + A = ctx.matrix(len(diagonal), **kwargs) + for i in xrange(len(diagonal)): + A[i,i] = diagonal[i] + return A + + def zeros(ctx, *args, **kwargs): + """ + Create matrix m x n filled with zeros. + One given dimension will create square matrix n x n. + + Example: + >>> from mpmath import zeros, mp + >>> mp.pretty = False + >>> zeros(2) + matrix( + [['0.0', '0.0'], + ['0.0', '0.0']]) + """ + if len(args) == 1: + m = n = args[0] + elif len(args) == 2: + m = args[0] + n = args[1] + else: + raise TypeError('zeros expected at most 2 arguments, got %i' % len(args)) + A = ctx.matrix(m, n, **kwargs) + for i in xrange(m): + for j in xrange(n): + A[i,j] = 0 + return A + + def ones(ctx, *args, **kwargs): + """ + Create matrix m x n filled with ones. + One given dimension will create square matrix n x n. + + Example: + >>> from mpmath import ones, mp + >>> mp.pretty = False + >>> ones(2) + matrix( + [['1.0', '1.0'], + ['1.0', '1.0']]) + """ + if len(args) == 1: + m = n = args[0] + elif len(args) == 2: + m = args[0] + n = args[1] + else: + raise TypeError('ones expected at most 2 arguments, got %i' % len(args)) + A = ctx.matrix(m, n, **kwargs) + for i in xrange(m): + for j in xrange(n): + A[i,j] = 1 + return A + + def hilbert(ctx, m, n=None): + """ + Create (pseudo) hilbert matrix m x n. + One given dimension will create hilbert matrix n x n. + + The matrix is very ill-conditioned and symmetric, positive definite if + square. + """ + if n is None: + n = m + A = ctx.matrix(m, n) + for i in xrange(m): + for j in xrange(n): + A[i,j] = ctx.one / (i + j + 1) + return A + + def randmatrix(ctx, m, n=None, min=0, max=1, **kwargs): + """ + Create a random m x n matrix. + + All values are >= min and >> from mpmath import randmatrix + >>> randmatrix(2) # doctest:+SKIP + matrix( + [['0.53491598236191806', '0.57195669543302752'], + ['0.85589992269513615', '0.82444367501382143']]) + """ + if not n: + n = m + A = ctx.matrix(m, n, **kwargs) + for i in xrange(m): + for j in xrange(n): + A[i,j] = ctx.rand() * (max - min) + min + return A + + def swap_row(ctx, A, i, j): + """ + Swap row i with row j. + """ + if i == j: + return + if isinstance(A, ctx.matrix): + for k in xrange(A.cols): + A[i,k], A[j,k] = A[j,k], A[i,k] + elif isinstance(A, list): + A[i], A[j] = A[j], A[i] + else: + raise TypeError('could not interpret type') + + def extend(ctx, A, b): + """ + Extend matrix A with column b and return result. + """ + if not isinstance(A, ctx.matrix): + raise TypeError("A should be a type of ctx.matrix") + if A.rows != len(b): + raise ValueError("Value should be equal to len(b)") + A = A.copy() + A.cols += 1 + for i in xrange(A.rows): + A[i, A.cols-1] = b[i] + return A + + def norm(ctx, x, p=2): + r""" + Gives the entrywise `p`-norm of an iterable *x*, i.e. the vector norm + `\left(\sum_k |x_k|^p\right)^{1/p}`, for any given `1 \le p \le \infty`. + + Special cases: + + If *x* is not iterable, this just returns ``absmax(x)``. + + ``p=1`` gives the sum of absolute values. + + ``p=2`` is the standard Euclidean vector norm. + + ``p=inf`` gives the magnitude of the largest element. + + For *x* a matrix, ``p=2`` is the Frobenius norm. + For operator matrix norms, use :func:`~mpmath.mnorm` instead. + + You can use the string 'inf' as well as float('inf') or mpf('inf') + to specify the infinity norm. + + **Examples** + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> x = matrix([-10, 2, 100]) + >>> norm(x, 1) + mpf('112.0') + >>> norm(x, 2) + mpf('100.5186549850325') + >>> norm(x, inf) + mpf('100.0') + + """ + try: + iter(x) + except TypeError: + return ctx.absmax(x) + if type(p) is not int: + p = ctx.convert(p) + if p == ctx.inf: + return max(ctx.absmax(i) for i in x) + elif p == 1: + return ctx.fsum(x, absolute=1) + elif p == 2: + return ctx.sqrt(ctx.fsum(x, absolute=1, squared=1)) + elif p > 1: + return ctx.nthroot(ctx.fsum(abs(i)**p for i in x), p) + else: + raise ValueError('p has to be >= 1') + + def mnorm(ctx, A, p=1): + r""" + Gives the matrix (operator) `p`-norm of A. Currently ``p=1`` and ``p=inf`` + are supported: + + ``p=1`` gives the 1-norm (maximal column sum) + + ``p=inf`` gives the `\infty`-norm (maximal row sum). + You can use the string 'inf' as well as float('inf') or mpf('inf') + + ``p=2`` (not implemented) for a square matrix is the usual spectral + matrix norm, i.e. the largest singular value. + + ``p='f'`` (or 'F', 'fro', 'Frobenius, 'frobenius') gives the + Frobenius norm, which is the elementwise 2-norm. The Frobenius norm is an + approximation of the spectral norm and satisfies + + .. math :: + + \frac{1}{\sqrt{\mathrm{rank}(A)}} \|A\|_F \le \|A\|_2 \le \|A\|_F + + The Frobenius norm lacks some mathematical properties that might + be expected of a norm. + + For general elementwise `p`-norms, use :func:`~mpmath.norm` instead. + + **Examples** + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> A = matrix([[1, -1000], [100, 50]]) + >>> mnorm(A, 1) + mpf('1050.0') + >>> mnorm(A, inf) + mpf('1001.0') + >>> mnorm(A, 'F') + mpf('1006.2310867787777') + + """ + A = ctx.matrix(A) + if type(p) is not int: + if type(p) is str and 'frobenius'.startswith(p.lower()): + return ctx.norm(A, 2) + p = ctx.convert(p) + m, n = A.rows, A.cols + if p == 1: + return max(ctx.fsum((A[i,j] for i in xrange(m)), absolute=1) for j in xrange(n)) + elif p == ctx.inf: + return max(ctx.fsum((A[i,j] for j in xrange(n)), absolute=1) for i in xrange(m)) + else: + raise NotImplementedError("matrix p-norm for arbitrary p") + +if __name__ == '__main__': + import doctest + doctest.testmod() diff --git a/venv/lib/python3.10/site-packages/mpmath/rational.py b/venv/lib/python3.10/site-packages/mpmath/rational.py new file mode 100644 index 0000000000000000000000000000000000000000..58745205319ac3548ad5feb49371d2d154b2d3c8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/rational.py @@ -0,0 +1,240 @@ +import operator +import sys +from .libmp import int_types, mpf_hash, bitcount, from_man_exp, HASH_MODULUS + +new = object.__new__ + +def create_reduced(p, q, _cache={}): + key = p, q + if key in _cache: + return _cache[key] + x, y = p, q + while y: + x, y = y, x % y + if x != 1: + p //= x + q //= x + v = new(mpq) + v._mpq_ = p, q + # Speedup integers, half-integers and other small fractions + if q <= 4 and abs(key[0]) < 100: + _cache[key] = v + return v + +class mpq(object): + """ + Exact rational type, currently only intended for internal use. + """ + + __slots__ = ["_mpq_"] + + def __new__(cls, p, q=1): + if type(p) is tuple: + p, q = p + elif hasattr(p, '_mpq_'): + p, q = p._mpq_ + return create_reduced(p, q) + + def __repr__(s): + return "mpq(%s,%s)" % s._mpq_ + + def __str__(s): + return "(%s/%s)" % s._mpq_ + + def __int__(s): + a, b = s._mpq_ + return a // b + + def __nonzero__(s): + return bool(s._mpq_[0]) + + __bool__ = __nonzero__ + + def __hash__(s): + a, b = s._mpq_ + if sys.version_info >= (3, 2): + inverse = pow(b, HASH_MODULUS-2, HASH_MODULUS) + if not inverse: + h = sys.hash_info.inf + else: + h = (abs(a) * inverse) % HASH_MODULUS + if a < 0: h = -h + if h == -1: h = -2 + return h + else: + if b == 1: + return hash(a) + # Power of two: mpf compatible hash + if not (b & (b-1)): + return mpf_hash(from_man_exp(a, 1-bitcount(b))) + return hash((a,b)) + + def __eq__(s, t): + ttype = type(t) + if ttype is mpq: + return s._mpq_ == t._mpq_ + if ttype in int_types: + a, b = s._mpq_ + if b != 1: + return False + return a == t + return NotImplemented + + def __ne__(s, t): + ttype = type(t) + if ttype is mpq: + return s._mpq_ != t._mpq_ + if ttype in int_types: + a, b = s._mpq_ + if b != 1: + return True + return a != t + return NotImplemented + + def _cmp(s, t, op): + ttype = type(t) + if ttype in int_types: + a, b = s._mpq_ + return op(a, t*b) + if ttype is mpq: + a, b = s._mpq_ + c, d = t._mpq_ + return op(a*d, b*c) + return NotImplementedError + + def __lt__(s, t): return s._cmp(t, operator.lt) + def __le__(s, t): return s._cmp(t, operator.le) + def __gt__(s, t): return s._cmp(t, operator.gt) + def __ge__(s, t): return s._cmp(t, operator.ge) + + def __abs__(s): + a, b = s._mpq_ + if a >= 0: + return s + v = new(mpq) + v._mpq_ = -a, b + return v + + def __neg__(s): + a, b = s._mpq_ + v = new(mpq) + v._mpq_ = -a, b + return v + + def __pos__(s): + return s + + def __add__(s, t): + ttype = type(t) + if ttype is mpq: + a, b = s._mpq_ + c, d = t._mpq_ + return create_reduced(a*d+b*c, b*d) + if ttype in int_types: + a, b = s._mpq_ + v = new(mpq) + v._mpq_ = a+b*t, b + return v + return NotImplemented + + __radd__ = __add__ + + def __sub__(s, t): + ttype = type(t) + if ttype is mpq: + a, b = s._mpq_ + c, d = t._mpq_ + return create_reduced(a*d-b*c, b*d) + if ttype in int_types: + a, b = s._mpq_ + v = new(mpq) + v._mpq_ = a-b*t, b + return v + return NotImplemented + + def __rsub__(s, t): + ttype = type(t) + if ttype is mpq: + a, b = s._mpq_ + c, d = t._mpq_ + return create_reduced(b*c-a*d, b*d) + if ttype in int_types: + a, b = s._mpq_ + v = new(mpq) + v._mpq_ = b*t-a, b + return v + return NotImplemented + + def __mul__(s, t): + ttype = type(t) + if ttype is mpq: + a, b = s._mpq_ + c, d = t._mpq_ + return create_reduced(a*c, b*d) + if ttype in int_types: + a, b = s._mpq_ + return create_reduced(a*t, b) + return NotImplemented + + __rmul__ = __mul__ + + def __div__(s, t): + ttype = type(t) + if ttype is mpq: + a, b = s._mpq_ + c, d = t._mpq_ + return create_reduced(a*d, b*c) + if ttype in int_types: + a, b = s._mpq_ + return create_reduced(a, b*t) + return NotImplemented + + def __rdiv__(s, t): + ttype = type(t) + if ttype is mpq: + a, b = s._mpq_ + c, d = t._mpq_ + return create_reduced(b*c, a*d) + if ttype in int_types: + a, b = s._mpq_ + return create_reduced(b*t, a) + return NotImplemented + + def __pow__(s, t): + ttype = type(t) + if ttype in int_types: + a, b = s._mpq_ + if t: + if t < 0: + a, b, t = b, a, -t + v = new(mpq) + v._mpq_ = a**t, b**t + return v + raise ZeroDivisionError + return NotImplemented + + +mpq_1 = mpq((1,1)) +mpq_0 = mpq((0,1)) +mpq_1_2 = mpq((1,2)) +mpq_3_2 = mpq((3,2)) +mpq_1_4 = mpq((1,4)) +mpq_1_16 = mpq((1,16)) +mpq_3_16 = mpq((3,16)) +mpq_5_2 = mpq((5,2)) +mpq_3_4 = mpq((3,4)) +mpq_7_4 = mpq((7,4)) +mpq_5_4 = mpq((5,4)) + + +# Register with "numbers" ABC +# We do not subclass, hence we do not use the @abstractmethod checks. While +# this is less invasive it may turn out that we do not actually support +# parts of the expected interfaces. See +# http://docs.python.org/2/library/numbers.html for list of abstract +# methods. +try: + import numbers + numbers.Rational.register(mpq) +except ImportError: + pass diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__init__.py b/venv/lib/python3.10/site-packages/mpmath/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13cca458c50ac9a60d91bdd1e3bfd71873c068cb Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/extratest_gamma.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/extratest_gamma.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcb6504d67ab245ba5ce5028983d8780f34650ee Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/extratest_gamma.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/extratest_zeta.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/extratest_zeta.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6469c6a30fcc4336c4b2681f65e4bd350f463f9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/extratest_zeta.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/runtests.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/runtests.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cf86c02b850a55b32d80bbae5bb73e4045aad44 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/runtests.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_basic_ops.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_basic_ops.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0696d8b4837298f7042fccf2fb60904d31a20bf1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_basic_ops.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_bitwise.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_bitwise.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c9732183b69e5f54d2a2574c1e87e01aadc9413 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_bitwise.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_calculus.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_calculus.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89f11cd70822080b5805436423f47edf5dc236c1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_calculus.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_compatibility.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_compatibility.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24fb7acdc3784c5b7bd470b584692ddc1e1c24e3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_compatibility.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_convert.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_convert.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec3c2c9dc345c165ff12e13ac794e0f14a2863b2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_convert.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_diff.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_diff.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f595119e99cc50242124248f12151c5abd302ff3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_diff.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_division.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_division.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d3b05bd4531ed9f372777545e0b2963b26fc179 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_division.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_eigen.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_eigen.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e26b94037b2e0d92853d4f8672c89f5190fddedc Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_eigen.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_eigen_symmetric.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_eigen_symmetric.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bff166a53d45cad4be38b60673726d4e4d21488 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_eigen_symmetric.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_elliptic.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_elliptic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c86da4f82e327929fb6870c06dca2b9bd9c324e9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_elliptic.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_fp.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_fp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1da9627bbe32fad73e0217c649193fa862d92b61 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_fp.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_functions.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_functions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..405c57b76442defdbe0132125dce490f1e678d07 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_functions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_functions2.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_functions2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef64d32e264af740a111fbdaee3753bc24288996 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_functions2.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_gammazeta.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_gammazeta.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dd13e9565aeaad0f599b53b62e59aad97e91bf1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_gammazeta.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_hp.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_hp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86d8f2946d516c9c5983faf40cffeaa5f291c3d7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_hp.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_identify.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_identify.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbc020768100e2e42e73c6159ee5bfbed1a483d8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_identify.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_interval.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_interval.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2241210e691e5787bbad120d51b59d22ae4f7eb Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_interval.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_levin.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_levin.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44a8d09083edca2ce299dff6e6cc3091884c0c03 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_levin.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_linalg.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_linalg.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e9f28af4cb3521a25378f4b2e64485013c0e4ce Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_linalg.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_matrices.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_matrices.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..decb2676cb4f7f1aea8910085240977343b0cbd1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_matrices.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_mpmath.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_mpmath.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58a3b61eac916fd251de7c4ae0214e4ccd729646 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_mpmath.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_ode.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_ode.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12d85267903c6c875f306d466027238050f08cc7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_ode.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_pickle.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_pickle.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3241426356efae60b6e22795ea2a5f88bafc1e16 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_pickle.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_power.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_power.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..200fdbe89b011954ef6eb2c7d6f580afc165ca66 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_power.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_quad.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_quad.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ad2a96142ec9fce52f3ff6eafa05c344264adf0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_quad.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_rootfinding.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_rootfinding.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..896787620c8177f277f002ba7deb285d799456d7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_rootfinding.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_special.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_special.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4091a92d272ee648885280e1fb2ad7c174de6fa Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_special.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_str.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_str.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ea3fe1bce8e4eaf15129bb8449422e5adffa636 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_str.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_summation.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_summation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06991bb195adc9690bf80f735e91013dd2b2d0b0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_summation.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_trig.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_trig.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4694cc9b4c8dc984f7a3dfe110c58d6821d959e3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_trig.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_visualization.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_visualization.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4c95b152849877a2ea9417b3b85f600d114a019 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_visualization.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/torture.cpython-310.pyc b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/torture.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..614053d46d699f5d4d97ed7648d1cabde9262da0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mpmath/tests/__pycache__/torture.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/extratest_gamma.py b/venv/lib/python3.10/site-packages/mpmath/tests/extratest_gamma.py new file mode 100644 index 0000000000000000000000000000000000000000..5a27b61b19aba0abf6bdb8adc16fc1ec7689b67a --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/extratest_gamma.py @@ -0,0 +1,215 @@ +from mpmath import * +from mpmath.libmp import ifac + +import sys +if "-dps" in sys.argv: + maxdps = int(sys.argv[sys.argv.index("-dps")+1]) +else: + maxdps = 1000 + +raise_ = "-raise" in sys.argv + +errcount = 0 + +def check(name, func, z, y): + global errcount + try: + x = func(z) + except: + errcount += 1 + if raise_: + raise + print() + print(name) + print("EXCEPTION") + import traceback + traceback.print_tb(sys.exc_info()[2]) + print() + return + xre = x.real + xim = x.imag + yre = y.real + yim = y.imag + tol = eps*8 + err = 0 + if abs(xre-yre) > abs(yre)*tol: + err = 1 + print() + print("Error! %s (re = %s, wanted %s, err=%s)" % (name, nstr(xre,10), nstr(yre,10), nstr(abs(xre-yre)))) + errcount += 1 + if raise_: + raise SystemExit + if abs(xim-yim) > abs(yim)*tol: + err = 1 + print() + print("Error! %s (im = %s, wanted %s, err=%s)" % (name, nstr(xim,10), nstr(yim,10), nstr(abs(xim-yim)))) + errcount += 1 + if raise_: + raise SystemExit + if not err: + sys.stdout.write("%s ok; " % name) + +def testcase(case): + z, result = case + print("Testing z =", z) + mp.dps = 1010 + z = eval(z) + mp.dps = maxdps + 50 + if result is None: + gamma_val = gamma(z) + loggamma_val = loggamma(z) + factorial_val = factorial(z) + rgamma_val = rgamma(z) + else: + loggamma_val = eval(result) + gamma_val = exp(loggamma_val) + factorial_val = z * gamma_val + rgamma_val = 1/gamma_val + for dps in [5, 10, 15, 25, 40, 60, 90, 120, 250, 600, 1000, 1800, 3600]: + if dps > maxdps: + break + mp.dps = dps + print("dps = %s" % dps) + check("gamma", gamma, z, gamma_val) + check("rgamma", rgamma, z, rgamma_val) + check("loggamma", loggamma, z, loggamma_val) + check("factorial", factorial, z, factorial_val) + print() + mp.dps = 15 + +testcases = [] + +# Basic values +for n in list(range(1,200)) + list(range(201,2000,17)): + testcases.append(["%s" % n, None]) +for n in range(-200,200): + testcases.append(["%s+0.5" % n, None]) + testcases.append(["%s+0.37" % n, None]) + +testcases += [\ +["(0.1+1j)", None], +["(-0.1+1j)", None], +["(0.1-1j)", None], +["(-0.1-1j)", None], +["10j", None], +["-10j", None], +["100j", None], +["10000j", None], +["-10000000j", None], +["(10**100)*j", None], +["125+(10**100)*j", None], +["-125+(10**100)*j", None], +["(10**10)*(1+j)", None], +["(10**10)*(-1+j)", None], +["(10**100)*(1+j)", None], +["(10**100)*(-1+j)", None], +["(1.5-1j)", None], +["(6+4j)", None], +["(4+1j)", None], +["(3.5+2j)", None], +["(1.5-1j)", None], +["(-6-4j)", None], +["(-2-3j)", None], +["(-2.5-2j)", None], +["(4+1j)", None], +["(3+3j)", None], +["(2-2j)", None], +["1", "0"], +["2", "0"], +["3", "log(2)"], +["4", "log(6)"], +["5", "log(24)"], +["0.5", "log(pi)/2"], +["1.5", "log(sqrt(pi)/2)"], +["2.5", "log(3*sqrt(pi)/4)"], +["mpf('0.37')", None], +["0.25", "log(sqrt(2*sqrt(2*pi**3)/agm(1,sqrt(2))))"], +["-0.4", None], +["mpf('-1.9')", None], +["mpf('12.8')", None], +["mpf('33.7')", None], +["mpf('95.2')", None], +["mpf('160.3')", None], +["mpf('2057.8')", None], +["25", "log(ifac(24))"], +["80", "log(ifac(79))"], +["500", "log(ifac(500-1))"], +["8000", "log(ifac(8000-1))"], +["8000.5", None], +["mpf('8000.1')", None], +["mpf('1.37e10')", None], +["mpf('1.37e10')*(1+j)", None], +["mpf('1.37e10')*(-1+j)", None], +["mpf('1.37e10')*(-1-j)", None], +["mpf('1.37e10')*(-1+j)", None], +["mpf('1.37e100')", None], +["mpf('1.37e100')*(1+j)", None], +["mpf('1.37e100')*(-1+j)", None], +["mpf('1.37e100')*(-1-j)", None], +["mpf('1.37e100')*(-1+j)", None], +["3+4j", +"mpc('" +"-1.7566267846037841105306041816232757851567066070613445016197619371316057169" +"4723618263960834804618463052988607348289672535780644470689771115236512106002" +"5970873471563240537307638968509556191696167970488390423963867031934333890838" +"8009531786948197210025029725361069435208930363494971027388382086721660805397" +"9163230643216054580167976201709951509519218635460317367338612500626714783631" +"7498317478048447525674016344322545858832610325861086336204591943822302971823" +"5161814175530618223688296232894588415495615809337292518431903058265147109853" +"1710568942184987827643886816200452860853873815413367529829631430146227470517" +"6579967222200868632179482214312673161276976117132204633283806161971389519137" +"1243359764435612951384238091232760634271570950240717650166551484551654327989" +"9360285030081716934130446150245110557038117075172576825490035434069388648124" +"6678152254554001586736120762641422590778766100376515737713938521275749049949" +"1284143906816424244705094759339932733567910991920631339597278805393743140853" +"391550313363278558195609260225928','" +"4.74266443803465792819488940755002274088830335171164611359052405215840070271" +"5906813009373171139767051863542508136875688550817670379002790304870822775498" +"2809996675877564504192565392367259119610438951593128982646945990372179860613" +"4294436498090428077839141927485901735557543641049637962003652638924845391650" +"9546290137755550107224907606529385248390667634297183361902055842228798984200" +"9591180450211798341715874477629099687609819466457990642030707080894518168924" +"6805549314043258530272479246115112769957368212585759640878745385160943755234" +"9398036774908108204370323896757543121853650025529763655312360354244898913463" +"7115955702828838923393113618205074162812089732064414530813087483533203244056" +"0546577484241423134079056537777170351934430586103623577814746004431994179990" +"5318522939077992613855205801498201930221975721246498720895122345420698451980" +"0051215797310305885845964334761831751370672996984756815410977750799748813563" +"8784405288158432214886648743541773208808731479748217023665577802702269468013" +"673719173759245720489020315779001')"], +] + +for z in [4, 14, 34, 64]: + testcases.append(["(2+j)*%s/3" % z, None]) + testcases.append(["(-2+j)*%s/3" % z, None]) + testcases.append(["(1+2*j)*%s/3" % z, None]) + testcases.append(["(2-j)*%s/3" % z, None]) + testcases.append(["(20+j)*%s/3" % z, None]) + testcases.append(["(-20+j)*%s/3" % z, None]) + testcases.append(["(1+20*j)*%s/3" % z, None]) + testcases.append(["(20-j)*%s/3" % z, None]) + testcases.append(["(200+j)*%s/3" % z, None]) + testcases.append(["(-200+j)*%s/3" % z, None]) + testcases.append(["(1+200*j)*%s/3" % z, None]) + testcases.append(["(200-j)*%s/3" % z, None]) + +# Poles +for n in [0,1,2,3,4,25,-1,-2,-3,-4,-20,-21,-50,-51,-200,-201,-20000,-20001]: + for t in ['1e-5', '1e-20', '1e-100', '1e-10000']: + testcases.append(["fadd(%s,'%s',exact=True)" % (n, t), None]) + testcases.append(["fsub(%s,'%s',exact=True)" % (n, t), None]) + testcases.append(["fadd(%s,'%sj',exact=True)" % (n, t), None]) + testcases.append(["fsub(%s,'%sj',exact=True)" % (n, t), None]) + +if __name__ == "__main__": + from timeit import default_timer as clock + tot_time = 0.0 + for case in testcases: + t1 = clock() + testcase(case) + t2 = clock() + print("Test time:", t2-t1) + print() + tot_time += (t2-t1) + print("Total time:", tot_time) + print("Errors:", errcount) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/extratest_zeta.py b/venv/lib/python3.10/site-packages/mpmath/tests/extratest_zeta.py new file mode 100644 index 0000000000000000000000000000000000000000..582b3d9cbd956b9cdf94309e0e718371fe716101 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/extratest_zeta.py @@ -0,0 +1,30 @@ +from mpmath import zetazero +from timeit import default_timer as clock + +def test_zetazero(): + cases = [\ + (399999999, 156762524.6750591511), + (241389216, 97490234.2276711795), + (526196239, 202950727.691229534), + (542964976, 209039046.578535272), + (1048449112, 388858885.231056486), + (1048449113, 388858885.384337406), + (1048449114, 388858886.002285122), + (1048449115, 388858886.00239369), + (1048449116, 388858886.690745053) + ] + for n, v in cases: + print(n, v) + t1 = clock() + ok = zetazero(n).ae(complex(0.5,v)) + t2 = clock() + print("ok =", ok, ("(time = %s)" % round(t2-t1,3))) + print("Now computing two huge zeros (this may take hours)") + print("Computing zetazero(8637740722917)") + ok = zetazero(8637740722917).ae(complex(0.5,2124447368584.39296466152)) + print("ok =", ok) + ok = zetazero(8637740722918).ae(complex(0.5,2124447368584.39298170604)) + print("ok =", ok) + +if __name__ == "__main__": + test_zetazero() diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/runtests.py b/venv/lib/python3.10/site-packages/mpmath/tests/runtests.py new file mode 100644 index 0000000000000000000000000000000000000000..70fde272fdc0e05e3d8951edddca380bd36139ab --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/runtests.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python + +""" +python runtests.py -py + Use py.test to run tests (more useful for debugging) + +python runtests.py -coverage + Generate test coverage report. Statistics are written to /tmp + +python runtests.py -profile + Generate profile stats (this is much slower) + +python runtests.py -nogmpy + Run tests without using GMPY even if it exists + +python runtests.py -strict + Enforce extra tests in normalize() + +python runtests.py -local + Insert '../..' at the beginning of sys.path to use local mpmath + +python runtests.py -skip ... + Skip tests from the listed modules + +Additional arguments are used to filter the tests to run. Only files that have +one of the arguments in their name are executed. + +""" + +import sys, os, traceback + +profile = False +if "-profile" in sys.argv: + sys.argv.remove('-profile') + profile = True + +coverage = False +if "-coverage" in sys.argv: + sys.argv.remove('-coverage') + coverage = True + +if "-nogmpy" in sys.argv: + sys.argv.remove('-nogmpy') + os.environ['MPMATH_NOGMPY'] = 'Y' + +if "-strict" in sys.argv: + sys.argv.remove('-strict') + os.environ['MPMATH_STRICT'] = 'Y' + +if "-local" in sys.argv: + sys.argv.remove('-local') + importdir = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), + '../..')) +else: + importdir = '' + +# TODO: add a flag for this +testdir = '' + +def testit(importdir='', testdir='', exit_on_fail=False): + """Run all tests in testdir while importing from importdir.""" + if importdir: + sys.path.insert(1, importdir) + if testdir: + sys.path.insert(1, testdir) + import os.path + import mpmath + print("mpmath imported from %s" % os.path.dirname(mpmath.__file__)) + print("mpmath backend: %s" % mpmath.libmp.backend.BACKEND) + print("mpmath mp class: %s" % repr(mpmath.mp)) + print("mpmath version: %s" % mpmath.__version__) + print("Python version: %s" % sys.version) + print("") + if "-py" in sys.argv: + sys.argv.remove('-py') + import py + py.test.cmdline.main() + else: + import glob + from timeit import default_timer as clock + modules = [] + args = sys.argv[1:] + excluded = [] + if '-skip' in args: + excluded = args[args.index('-skip')+1:] + args = args[:args.index('-skip')] + # search for tests in directory of this file if not otherwise specified + if not testdir: + pattern = os.path.dirname(sys.argv[0]) + else: + pattern = testdir + if pattern: + pattern += '/' + pattern += 'test*.py' + # look for tests (respecting specified filter) + for f in glob.glob(pattern): + name = os.path.splitext(os.path.basename(f))[0] + # If run as a script, only run tests given as args, if any are given + if args and __name__ == "__main__": + ok = False + for arg in args: + if arg in name: + ok = True + break + if not ok: + continue + elif name in excluded: + continue + module = __import__(name) + priority = module.__dict__.get('priority', 100) + if priority == 666: + modules = [[priority, name, module]] + break + modules.append([priority, name, module]) + # execute tests + modules.sort() + tstart = clock() + for priority, name, module in modules: + print(name) + for f in sorted(module.__dict__.keys()): + if f.startswith('test_'): + if coverage and ('numpy' in f): + continue + sys.stdout.write(" " + f[5:].ljust(25) + " ") + t1 = clock() + try: + module.__dict__[f]() + except: + etype, evalue, trb = sys.exc_info() + if etype in (KeyboardInterrupt, SystemExit): + raise + print("") + print("TEST FAILED!") + print("") + traceback.print_exc() + if exit_on_fail: + return + t2 = clock() + print("ok " + " " + ("%.7f" % (t2-t1)) + " s") + tend = clock() + print("") + print("finished tests in " + ("%.2f" % (tend-tstart)) + " seconds") + # clean sys.path + if importdir: + sys.path.remove(importdir) + if testdir: + sys.path.remove(testdir) + +if __name__ == '__main__': + if profile: + import cProfile + cProfile.run("testit('%s', '%s')" % (importdir, testdir), sort=1) + elif coverage: + import trace + tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix], + trace=0, count=1) + tracer.run('testit(importdir, testdir)') + r = tracer.results() + r.write_results(show_missing=True, summary=True, coverdir="/tmp") + else: + testit(importdir, testdir) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_basic_ops.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_basic_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..f577c7fa9f9734876b6767f6cc21144df305d82f --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_basic_ops.py @@ -0,0 +1,451 @@ +import mpmath +from mpmath import * +from mpmath.libmp import * +import random +import sys + +try: + long = long +except NameError: + long = int + +def test_type_compare(): + assert mpf(2) == mpc(2,0) + assert mpf(0) == mpc(0) + assert mpf(2) != mpc(2, 0.00001) + assert mpf(2) == 2.0 + assert mpf(2) != 3.0 + assert mpf(2) == 2 + assert mpf(2) != '2.0' + assert mpc(2) != '2.0' + +def test_add(): + assert mpf(2.5) + mpf(3) == 5.5 + assert mpf(2.5) + 3 == 5.5 + assert mpf(2.5) + 3.0 == 5.5 + assert 3 + mpf(2.5) == 5.5 + assert 3.0 + mpf(2.5) == 5.5 + assert (3+0j) + mpf(2.5) == 5.5 + assert mpc(2.5) + mpf(3) == 5.5 + assert mpc(2.5) + 3 == 5.5 + assert mpc(2.5) + 3.0 == 5.5 + assert mpc(2.5) + (3+0j) == 5.5 + assert 3 + mpc(2.5) == 5.5 + assert 3.0 + mpc(2.5) == 5.5 + assert (3+0j) + mpc(2.5) == 5.5 + +def test_sub(): + assert mpf(2.5) - mpf(3) == -0.5 + assert mpf(2.5) - 3 == -0.5 + assert mpf(2.5) - 3.0 == -0.5 + assert 3 - mpf(2.5) == 0.5 + assert 3.0 - mpf(2.5) == 0.5 + assert (3+0j) - mpf(2.5) == 0.5 + assert mpc(2.5) - mpf(3) == -0.5 + assert mpc(2.5) - 3 == -0.5 + assert mpc(2.5) - 3.0 == -0.5 + assert mpc(2.5) - (3+0j) == -0.5 + assert 3 - mpc(2.5) == 0.5 + assert 3.0 - mpc(2.5) == 0.5 + assert (3+0j) - mpc(2.5) == 0.5 + +def test_mul(): + assert mpf(2.5) * mpf(3) == 7.5 + assert mpf(2.5) * 3 == 7.5 + assert mpf(2.5) * 3.0 == 7.5 + assert 3 * mpf(2.5) == 7.5 + assert 3.0 * mpf(2.5) == 7.5 + assert (3+0j) * mpf(2.5) == 7.5 + assert mpc(2.5) * mpf(3) == 7.5 + assert mpc(2.5) * 3 == 7.5 + assert mpc(2.5) * 3.0 == 7.5 + assert mpc(2.5) * (3+0j) == 7.5 + assert 3 * mpc(2.5) == 7.5 + assert 3.0 * mpc(2.5) == 7.5 + assert (3+0j) * mpc(2.5) == 7.5 + +def test_div(): + assert mpf(6) / mpf(3) == 2.0 + assert mpf(6) / 3 == 2.0 + assert mpf(6) / 3.0 == 2.0 + assert 6 / mpf(3) == 2.0 + assert 6.0 / mpf(3) == 2.0 + assert (6+0j) / mpf(3.0) == 2.0 + assert mpc(6) / mpf(3) == 2.0 + assert mpc(6) / 3 == 2.0 + assert mpc(6) / 3.0 == 2.0 + assert mpc(6) / (3+0j) == 2.0 + assert 6 / mpc(3) == 2.0 + assert 6.0 / mpc(3) == 2.0 + assert (6+0j) / mpc(3) == 2.0 + +def test_pow(): + assert mpf(6) ** mpf(3) == 216.0 + assert mpf(6) ** 3 == 216.0 + assert mpf(6) ** 3.0 == 216.0 + assert 6 ** mpf(3) == 216.0 + assert 6.0 ** mpf(3) == 216.0 + assert (6+0j) ** mpf(3.0) == 216.0 + assert mpc(6) ** mpf(3) == 216.0 + assert mpc(6) ** 3 == 216.0 + assert mpc(6) ** 3.0 == 216.0 + assert mpc(6) ** (3+0j) == 216.0 + assert 6 ** mpc(3) == 216.0 + assert 6.0 ** mpc(3) == 216.0 + assert (6+0j) ** mpc(3) == 216.0 + +def test_mixed_misc(): + assert 1 + mpf(3) == mpf(3) + 1 == 4 + assert 1 - mpf(3) == -(mpf(3) - 1) == -2 + assert 3 * mpf(2) == mpf(2) * 3 == 6 + assert 6 / mpf(2) == mpf(6) / 2 == 3 + assert 1.0 + mpf(3) == mpf(3) + 1.0 == 4 + assert 1.0 - mpf(3) == -(mpf(3) - 1.0) == -2 + assert 3.0 * mpf(2) == mpf(2) * 3.0 == 6 + assert 6.0 / mpf(2) == mpf(6) / 2.0 == 3 + +def test_add_misc(): + mp.dps = 15 + assert mpf(4) + mpf(-70) == -66 + assert mpf(1) + mpf(1.1)/80 == 1 + 1.1/80 + assert mpf((1, 10000000000)) + mpf(3) == mpf((1, 10000000000)) + assert mpf(3) + mpf((1, 10000000000)) == mpf((1, 10000000000)) + assert mpf((1, -10000000000)) + mpf(3) == mpf(3) + assert mpf(3) + mpf((1, -10000000000)) == mpf(3) + assert mpf(1) + 1e-15 != 1 + assert mpf(1) + 1e-20 == 1 + assert mpf(1.07e-22) + 0 == mpf(1.07e-22) + assert mpf(0) + mpf(1.07e-22) == mpf(1.07e-22) + +def test_complex_misc(): + # many more tests needed + assert 1 + mpc(2) == 3 + assert not mpc(2).ae(2 + 1e-13) + assert mpc(2+1e-15j).ae(2) + +def test_complex_zeros(): + for a in [0,2]: + for b in [0,3]: + for c in [0,4]: + for d in [0,5]: + assert mpc(a,b)*mpc(c,d) == complex(a,b)*complex(c,d) + +def test_hash(): + for i in range(-256, 256): + assert hash(mpf(i)) == hash(i) + assert hash(mpf(0.5)) == hash(0.5) + assert hash(mpc(2,3)) == hash(2+3j) + # Check that this doesn't fail + assert hash(inf) + # Check that overflow doesn't assign equal hashes to large numbers + assert hash(mpf('1e1000')) != hash('1e10000') + assert hash(mpc(100,'1e1000')) != hash(mpc(200,'1e1000')) + from mpmath.rational import mpq + assert hash(mp.mpq(1,3)) + assert hash(mp.mpq(0,1)) == 0 + assert hash(mp.mpq(-1,1)) == hash(-1) + assert hash(mp.mpq(1,1)) == hash(1) + assert hash(mp.mpq(5,1)) == hash(5) + assert hash(mp.mpq(1,2)) == hash(0.5) + if sys.version_info >= (3, 2): + assert hash(mpf(1)*2**2000) == hash(2**2000) + assert hash(mpf(1)/2**2000) == hash(mpq(1,2**2000)) + +# Advanced rounding test +def test_add_rounding(): + mp.dps = 15 + a = from_float(1e-50) + assert mpf_sub(mpf_add(fone, a, 53, round_up), fone, 53, round_up) == from_float(2.2204460492503131e-16) + assert mpf_sub(fone, a, 53, round_up) == fone + assert mpf_sub(fone, mpf_sub(fone, a, 53, round_down), 53, round_down) == from_float(1.1102230246251565e-16) + assert mpf_add(fone, a, 53, round_down) == fone + +def test_almost_equal(): + assert mpf(1.2).ae(mpf(1.20000001), 1e-7) + assert not mpf(1.2).ae(mpf(1.20000001), 1e-9) + assert not mpf(-0.7818314824680298).ae(mpf(-0.774695868667929)) + +def test_arithmetic_functions(): + import operator + ops = [(operator.add, fadd), (operator.sub, fsub), (operator.mul, fmul), + (operator.truediv, fdiv)] + a = mpf(0.27) + b = mpf(1.13) + c = mpc(0.51+2.16j) + d = mpc(1.08-0.99j) + for x in [a,b,c,d]: + for y in [a,b,c,d]: + for op, fop in ops: + if fop is not fdiv: + mp.prec = 200 + z0 = op(x,y) + mp.prec = 60 + z1 = op(x,y) + mp.prec = 53 + z2 = op(x,y) + assert fop(x, y, prec=60) == z1 + assert fop(x, y) == z2 + if fop is not fdiv: + assert fop(x, y, prec=inf) == z0 + assert fop(x, y, dps=inf) == z0 + assert fop(x, y, exact=True) == z0 + assert fneg(fneg(z1, exact=True), prec=inf) == z1 + assert fneg(z1) == -(+z1) + mp.dps = 15 + +def test_exact_integer_arithmetic(): + # XXX: re-fix this so that all operations are tested with all rounding modes + random.seed(0) + for prec in [6, 10, 25, 40, 100, 250, 725]: + for rounding in ['d', 'u', 'f', 'c', 'n']: + mp.dps = prec + M = 10**(prec-2) + M2 = 10**(prec//2-2) + for i in range(10): + a = random.randint(-M, M) + b = random.randint(-M, M) + assert mpf(a, rounding=rounding) == a + assert int(mpf(a, rounding=rounding)) == a + assert int(mpf(str(a), rounding=rounding)) == a + assert mpf(a) + mpf(b) == a + b + assert mpf(a) - mpf(b) == a - b + assert -mpf(a) == -a + a = random.randint(-M2, M2) + b = random.randint(-M2, M2) + assert mpf(a) * mpf(b) == a*b + assert mpf_mul(from_int(a), from_int(b), mp.prec, rounding) == from_int(a*b) + mp.dps = 15 + +def test_odd_int_bug(): + assert to_int(from_int(3), round_nearest) == 3 + +def test_str_1000_digits(): + mp.dps = 1001 + # last digit may be wrong + assert str(mpf(2)**0.5)[-10:-1] == '9518488472'[:9] + assert str(pi)[-10:-1] == '2164201989'[:9] + mp.dps = 15 + +def test_str_10000_digits(): + mp.dps = 10001 + # last digit may be wrong + assert str(mpf(2)**0.5)[-10:-1] == '5873258351'[:9] + assert str(pi)[-10:-1] == '5256375678'[:9] + mp.dps = 15 + +def test_monitor(): + f = lambda x: x**2 + a = [] + b = [] + g = monitor(f, a.append, b.append) + assert g(3) == 9 + assert g(4) == 16 + assert a[0] == ((3,), {}) + assert b[0] == 9 + +def test_nint_distance(): + assert nint_distance(mpf(-3)) == (-3, -inf) + assert nint_distance(mpc(-3)) == (-3, -inf) + assert nint_distance(mpf(-3.1)) == (-3, -3) + assert nint_distance(mpf(-3.01)) == (-3, -6) + assert nint_distance(mpf(-3.001)) == (-3, -9) + assert nint_distance(mpf(-3.0001)) == (-3, -13) + assert nint_distance(mpf(-2.9)) == (-3, -3) + assert nint_distance(mpf(-2.99)) == (-3, -6) + assert nint_distance(mpf(-2.999)) == (-3, -9) + assert nint_distance(mpf(-2.9999)) == (-3, -13) + assert nint_distance(mpc(-3+0.1j)) == (-3, -3) + assert nint_distance(mpc(-3+0.01j)) == (-3, -6) + assert nint_distance(mpc(-3.1+0.1j)) == (-3, -3) + assert nint_distance(mpc(-3.01+0.01j)) == (-3, -6) + assert nint_distance(mpc(-3.001+0.001j)) == (-3, -9) + assert nint_distance(mpf(0)) == (0, -inf) + assert nint_distance(mpf(0.01)) == (0, -6) + assert nint_distance(mpf('1e-100')) == (0, -332) + +def test_floor_ceil_nint_frac(): + mp.dps = 15 + for n in range(-10,10): + assert floor(n) == n + assert floor(n+0.5) == n + assert ceil(n) == n + assert ceil(n+0.5) == n+1 + assert nint(n) == n + # nint rounds to even + if n % 2 == 1: + assert nint(n+0.5) == n+1 + else: + assert nint(n+0.5) == n + assert floor(inf) == inf + assert floor(ninf) == ninf + assert isnan(floor(nan)) + assert ceil(inf) == inf + assert ceil(ninf) == ninf + assert isnan(ceil(nan)) + assert nint(inf) == inf + assert nint(ninf) == ninf + assert isnan(nint(nan)) + assert floor(0.1) == 0 + assert floor(0.9) == 0 + assert floor(-0.1) == -1 + assert floor(-0.9) == -1 + assert floor(10000000000.1) == 10000000000 + assert floor(10000000000.9) == 10000000000 + assert floor(-10000000000.1) == -10000000000-1 + assert floor(-10000000000.9) == -10000000000-1 + assert floor(1e-100) == 0 + assert floor(-1e-100) == -1 + assert floor(1e100) == 1e100 + assert floor(-1e100) == -1e100 + assert ceil(0.1) == 1 + assert ceil(0.9) == 1 + assert ceil(-0.1) == 0 + assert ceil(-0.9) == 0 + assert ceil(10000000000.1) == 10000000000+1 + assert ceil(10000000000.9) == 10000000000+1 + assert ceil(-10000000000.1) == -10000000000 + assert ceil(-10000000000.9) == -10000000000 + assert ceil(1e-100) == 1 + assert ceil(-1e-100) == 0 + assert ceil(1e100) == 1e100 + assert ceil(-1e100) == -1e100 + assert nint(0.1) == 0 + assert nint(0.9) == 1 + assert nint(-0.1) == 0 + assert nint(-0.9) == -1 + assert nint(10000000000.1) == 10000000000 + assert nint(10000000000.9) == 10000000000+1 + assert nint(-10000000000.1) == -10000000000 + assert nint(-10000000000.9) == -10000000000-1 + assert nint(1e-100) == 0 + assert nint(-1e-100) == 0 + assert nint(1e100) == 1e100 + assert nint(-1e100) == -1e100 + assert floor(3.2+4.6j) == 3+4j + assert ceil(3.2+4.6j) == 4+5j + assert nint(3.2+4.6j) == 3+5j + for n in range(-10,10): + assert frac(n) == 0 + assert frac(0.25) == 0.25 + assert frac(1.25) == 0.25 + assert frac(2.25) == 0.25 + assert frac(-0.25) == 0.75 + assert frac(-1.25) == 0.75 + assert frac(-2.25) == 0.75 + assert frac('1e100000000000000') == 0 + u = mpf('1e-100000000000000') + assert frac(u) == u + assert frac(-u) == 1 # rounding! + u = mpf('1e-400') + assert frac(-u, prec=0) == fsub(1, u, exact=True) + assert frac(3.25+4.75j) == 0.25+0.75j + +def test_isnan_etc(): + from mpmath.rational import mpq + assert isnan(nan) == True + assert isnan(3) == False + assert isnan(mpf(3)) == False + assert isnan(inf) == False + assert isnan(mpc(2,nan)) == True + assert isnan(mpc(2,nan)) == True + assert isnan(mpc(nan,nan)) == True + assert isnan(mpc(2,2)) == False + assert isnan(mpc(nan,inf)) == True + assert isnan(mpc(inf,inf)) == False + assert isnan(mpq((3,2))) == False + assert isnan(mpq((0,1))) == False + assert isinf(inf) == True + assert isinf(-inf) == True + assert isinf(3) == False + assert isinf(nan) == False + assert isinf(3+4j) == False + assert isinf(mpc(inf)) == True + assert isinf(mpc(3,inf)) == True + assert isinf(mpc(inf,3)) == True + assert isinf(mpc(inf,inf)) == True + assert isinf(mpc(nan,inf)) == True + assert isinf(mpc(inf,nan)) == True + assert isinf(mpc(nan,nan)) == False + assert isinf(mpq((3,2))) == False + assert isinf(mpq((0,1))) == False + assert isnormal(3) == True + assert isnormal(3.5) == True + assert isnormal(mpf(3.5)) == True + assert isnormal(0) == False + assert isnormal(mpf(0)) == False + assert isnormal(0.0) == False + assert isnormal(inf) == False + assert isnormal(-inf) == False + assert isnormal(nan) == False + assert isnormal(float(inf)) == False + assert isnormal(mpc(0,0)) == False + assert isnormal(mpc(3,0)) == True + assert isnormal(mpc(0,3)) == True + assert isnormal(mpc(3,3)) == True + assert isnormal(mpc(0,nan)) == False + assert isnormal(mpc(0,inf)) == False + assert isnormal(mpc(3,nan)) == False + assert isnormal(mpc(3,inf)) == False + assert isnormal(mpc(3,-inf)) == False + assert isnormal(mpc(nan,0)) == False + assert isnormal(mpc(inf,0)) == False + assert isnormal(mpc(nan,3)) == False + assert isnormal(mpc(inf,3)) == False + assert isnormal(mpc(inf,nan)) == False + assert isnormal(mpc(nan,inf)) == False + assert isnormal(mpc(nan,nan)) == False + assert isnormal(mpc(inf,inf)) == False + assert isnormal(mpq((3,2))) == True + assert isnormal(mpq((0,1))) == False + assert isint(3) == True + assert isint(0) == True + assert isint(long(3)) == True + assert isint(long(0)) == True + assert isint(mpf(3)) == True + assert isint(mpf(0)) == True + assert isint(mpf(-3)) == True + assert isint(mpf(3.2)) == False + assert isint(3.2) == False + assert isint(nan) == False + assert isint(inf) == False + assert isint(-inf) == False + assert isint(mpc(0)) == True + assert isint(mpc(3)) == True + assert isint(mpc(3.2)) == False + assert isint(mpc(3,inf)) == False + assert isint(mpc(inf)) == False + assert isint(mpc(3,2)) == False + assert isint(mpc(0,2)) == False + assert isint(mpc(3,2),gaussian=True) == True + assert isint(mpc(3,0),gaussian=True) == True + assert isint(mpc(0,3),gaussian=True) == True + assert isint(3+4j) == False + assert isint(3+4j, gaussian=True) == True + assert isint(3+0j) == True + assert isint(mpq((3,2))) == False + assert isint(mpq((3,9))) == False + assert isint(mpq((9,3))) == True + assert isint(mpq((0,4))) == True + assert isint(mpq((1,1))) == True + assert isint(mpq((-1,1))) == True + assert mp.isnpint(0) == True + assert mp.isnpint(1) == False + assert mp.isnpint(-1) == True + assert mp.isnpint(-1.1) == False + assert mp.isnpint(-1.0) == True + assert mp.isnpint(mp.mpq(1,2)) == False + assert mp.isnpint(mp.mpq(-1,2)) == False + assert mp.isnpint(mp.mpq(-3,1)) == True + assert mp.isnpint(mp.mpq(0,1)) == True + assert mp.isnpint(mp.mpq(1,1)) == False + assert mp.isnpint(0+0j) == True + assert mp.isnpint(-1+0j) == True + assert mp.isnpint(-1.1+0j) == False + assert mp.isnpint(-1+0.1j) == False + assert mp.isnpint(0+0.1j) == False + + +def test_issue_438(): + assert mpf(finf) == mpf('inf') + assert mpf(fninf) == mpf('-inf') + assert mpf(fnan)._mpf_ == mpf('nan')._mpf_ diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_bitwise.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_bitwise.py new file mode 100644 index 0000000000000000000000000000000000000000..4f61b69fc8819cf275abaedd98847c58c3b5924a --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_bitwise.py @@ -0,0 +1,188 @@ +""" +Test bit-level integer and mpf operations +""" + +from mpmath import * +from mpmath.libmp import * + +def test_bitcount(): + assert bitcount(0) == 0 + assert bitcount(1) == 1 + assert bitcount(7) == 3 + assert bitcount(8) == 4 + assert bitcount(2**100) == 101 + assert bitcount(2**100-1) == 100 + +def test_trailing(): + assert trailing(0) == 0 + assert trailing(1) == 0 + assert trailing(2) == 1 + assert trailing(7) == 0 + assert trailing(8) == 3 + assert trailing(2**100) == 100 + assert trailing(2**100-1) == 0 + +def test_round_down(): + assert from_man_exp(0, -4, 4, round_down)[:3] == (0, 0, 0) + assert from_man_exp(0xf0, -4, 4, round_down)[:3] == (0, 15, 0) + assert from_man_exp(0xf1, -4, 4, round_down)[:3] == (0, 15, 0) + assert from_man_exp(0xff, -4, 4, round_down)[:3] == (0, 15, 0) + assert from_man_exp(-0xf0, -4, 4, round_down)[:3] == (1, 15, 0) + assert from_man_exp(-0xf1, -4, 4, round_down)[:3] == (1, 15, 0) + assert from_man_exp(-0xff, -4, 4, round_down)[:3] == (1, 15, 0) + +def test_round_up(): + assert from_man_exp(0, -4, 4, round_up)[:3] == (0, 0, 0) + assert from_man_exp(0xf0, -4, 4, round_up)[:3] == (0, 15, 0) + assert from_man_exp(0xf1, -4, 4, round_up)[:3] == (0, 1, 4) + assert from_man_exp(0xff, -4, 4, round_up)[:3] == (0, 1, 4) + assert from_man_exp(-0xf0, -4, 4, round_up)[:3] == (1, 15, 0) + assert from_man_exp(-0xf1, -4, 4, round_up)[:3] == (1, 1, 4) + assert from_man_exp(-0xff, -4, 4, round_up)[:3] == (1, 1, 4) + +def test_round_floor(): + assert from_man_exp(0, -4, 4, round_floor)[:3] == (0, 0, 0) + assert from_man_exp(0xf0, -4, 4, round_floor)[:3] == (0, 15, 0) + assert from_man_exp(0xf1, -4, 4, round_floor)[:3] == (0, 15, 0) + assert from_man_exp(0xff, -4, 4, round_floor)[:3] == (0, 15, 0) + assert from_man_exp(-0xf0, -4, 4, round_floor)[:3] == (1, 15, 0) + assert from_man_exp(-0xf1, -4, 4, round_floor)[:3] == (1, 1, 4) + assert from_man_exp(-0xff, -4, 4, round_floor)[:3] == (1, 1, 4) + +def test_round_ceiling(): + assert from_man_exp(0, -4, 4, round_ceiling)[:3] == (0, 0, 0) + assert from_man_exp(0xf0, -4, 4, round_ceiling)[:3] == (0, 15, 0) + assert from_man_exp(0xf1, -4, 4, round_ceiling)[:3] == (0, 1, 4) + assert from_man_exp(0xff, -4, 4, round_ceiling)[:3] == (0, 1, 4) + assert from_man_exp(-0xf0, -4, 4, round_ceiling)[:3] == (1, 15, 0) + assert from_man_exp(-0xf1, -4, 4, round_ceiling)[:3] == (1, 15, 0) + assert from_man_exp(-0xff, -4, 4, round_ceiling)[:3] == (1, 15, 0) + +def test_round_nearest(): + assert from_man_exp(0, -4, 4, round_nearest)[:3] == (0, 0, 0) + assert from_man_exp(0xf0, -4, 4, round_nearest)[:3] == (0, 15, 0) + assert from_man_exp(0xf7, -4, 4, round_nearest)[:3] == (0, 15, 0) + assert from_man_exp(0xf8, -4, 4, round_nearest)[:3] == (0, 1, 4) # 1111.1000 -> 10000.0 + assert from_man_exp(0xf9, -4, 4, round_nearest)[:3] == (0, 1, 4) # 1111.1001 -> 10000.0 + assert from_man_exp(0xe8, -4, 4, round_nearest)[:3] == (0, 7, 1) # 1110.1000 -> 1110.0 + assert from_man_exp(0xe9, -4, 4, round_nearest)[:3] == (0, 15, 0) # 1110.1001 -> 1111.0 + assert from_man_exp(-0xf0, -4, 4, round_nearest)[:3] == (1, 15, 0) + assert from_man_exp(-0xf7, -4, 4, round_nearest)[:3] == (1, 15, 0) + assert from_man_exp(-0xf8, -4, 4, round_nearest)[:3] == (1, 1, 4) + assert from_man_exp(-0xf9, -4, 4, round_nearest)[:3] == (1, 1, 4) + assert from_man_exp(-0xe8, -4, 4, round_nearest)[:3] == (1, 7, 1) + assert from_man_exp(-0xe9, -4, 4, round_nearest)[:3] == (1, 15, 0) + +def test_rounding_bugs(): + # 1 less than power-of-two cases + assert from_man_exp(72057594037927935, -56, 53, round_up) == (0, 1, 0, 1) + assert from_man_exp(73786976294838205979, -65, 53, round_nearest) == (0, 1, 1, 1) + assert from_man_exp(31, 0, 4, round_up) == (0, 1, 5, 1) + assert from_man_exp(-31, 0, 4, round_floor) == (1, 1, 5, 1) + assert from_man_exp(255, 0, 7, round_up) == (0, 1, 8, 1) + assert from_man_exp(-255, 0, 7, round_floor) == (1, 1, 8, 1) + +def test_rounding_issue_200(): + a = from_man_exp(9867,-100) + b = from_man_exp(9867,-200) + c = from_man_exp(-1,0) + z = (1, 1023, -10, 10) + assert mpf_add(a, c, 10, 'd') == z + assert mpf_add(b, c, 10, 'd') == z + assert mpf_add(c, a, 10, 'd') == z + assert mpf_add(c, b, 10, 'd') == z + +def test_perturb(): + a = fone + b = from_float(0.99999999999999989) + c = from_float(1.0000000000000002) + assert mpf_perturb(a, 0, 53, round_nearest) == a + assert mpf_perturb(a, 1, 53, round_nearest) == a + assert mpf_perturb(a, 0, 53, round_up) == c + assert mpf_perturb(a, 0, 53, round_ceiling) == c + assert mpf_perturb(a, 0, 53, round_down) == a + assert mpf_perturb(a, 0, 53, round_floor) == a + assert mpf_perturb(a, 1, 53, round_up) == a + assert mpf_perturb(a, 1, 53, round_ceiling) == a + assert mpf_perturb(a, 1, 53, round_down) == b + assert mpf_perturb(a, 1, 53, round_floor) == b + a = mpf_neg(a) + b = mpf_neg(b) + c = mpf_neg(c) + assert mpf_perturb(a, 0, 53, round_nearest) == a + assert mpf_perturb(a, 1, 53, round_nearest) == a + assert mpf_perturb(a, 0, 53, round_up) == a + assert mpf_perturb(a, 0, 53, round_floor) == a + assert mpf_perturb(a, 0, 53, round_down) == b + assert mpf_perturb(a, 0, 53, round_ceiling) == b + assert mpf_perturb(a, 1, 53, round_up) == c + assert mpf_perturb(a, 1, 53, round_floor) == c + assert mpf_perturb(a, 1, 53, round_down) == a + assert mpf_perturb(a, 1, 53, round_ceiling) == a + +def test_add_exact(): + ff = from_float + assert mpf_add(ff(3.0), ff(2.5)) == ff(5.5) + assert mpf_add(ff(3.0), ff(-2.5)) == ff(0.5) + assert mpf_add(ff(-3.0), ff(2.5)) == ff(-0.5) + assert mpf_add(ff(-3.0), ff(-2.5)) == ff(-5.5) + assert mpf_sub(mpf_add(fone, ff(1e-100)), fone) == ff(1e-100) + assert mpf_sub(mpf_add(ff(1e-100), fone), fone) == ff(1e-100) + assert mpf_sub(mpf_add(fone, ff(-1e-100)), fone) == ff(-1e-100) + assert mpf_sub(mpf_add(ff(-1e-100), fone), fone) == ff(-1e-100) + assert mpf_add(fone, fzero) == fone + assert mpf_add(fzero, fone) == fone + assert mpf_add(fzero, fzero) == fzero + +def test_long_exponent_shifts(): + mp.dps = 15 + # Check for possible bugs due to exponent arithmetic overflow + # in a C implementation + x = mpf(1) + for p in [32, 64]: + a = ldexp(1,2**(p-1)) + b = ldexp(1,2**p) + c = ldexp(1,2**(p+1)) + d = ldexp(1,-2**(p-1)) + e = ldexp(1,-2**p) + f = ldexp(1,-2**(p+1)) + assert (x+a) == a + assert (x+b) == b + assert (x+c) == c + assert (x+d) == x + assert (x+e) == x + assert (x+f) == x + assert (a+x) == a + assert (b+x) == b + assert (c+x) == c + assert (d+x) == x + assert (e+x) == x + assert (f+x) == x + assert (x-a) == -a + assert (x-b) == -b + assert (x-c) == -c + assert (x-d) == x + assert (x-e) == x + assert (x-f) == x + assert (a-x) == a + assert (b-x) == b + assert (c-x) == c + assert (d-x) == -x + assert (e-x) == -x + assert (f-x) == -x + +def test_float_rounding(): + mp.prec = 64 + for x in [mpf(1), mpf(1)+eps, mpf(1)-eps, -mpf(1)+eps, -mpf(1)-eps]: + fa = float(x) + fb = float(fadd(x,0,prec=53,rounding='n')) + assert fa == fb + z = mpc(x,x) + ca = complex(z) + cb = complex(fadd(z,0,prec=53,rounding='n')) + assert ca == cb + for rnd in ['n', 'd', 'u', 'f', 'c']: + fa = to_float(x._mpf_, rnd=rnd) + fb = to_float(fadd(x,0,prec=53,rounding=rnd)._mpf_, rnd=rnd) + assert fa == fb + mp.prec = 53 diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_calculus.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_calculus.py new file mode 100644 index 0000000000000000000000000000000000000000..f0a59773d672f0db20bb5072773472a5a3cc1d1f --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_calculus.py @@ -0,0 +1,216 @@ +import pytest +from mpmath import * + +def test_approximation(): + mp.dps = 15 + f = lambda x: cos(2-2*x)/x + p, err = chebyfit(f, [2, 4], 8, error=True) + assert err < 1e-5 + for i in range(10): + x = 2 + i/5. + assert abs(polyval(p, x) - f(x)) < err + +def test_limits(): + mp.dps = 15 + assert limit(lambda x: (x-sin(x))/x**3, 0).ae(mpf(1)/6) + assert limit(lambda n: (1+1/n)**n, inf).ae(e) + +def test_polyval(): + assert polyval([], 3) == 0 + assert polyval([0], 3) == 0 + assert polyval([5], 3) == 5 + # 4x^3 - 2x + 5 + p = [4, 0, -2, 5] + assert polyval(p,4) == 253 + assert polyval(p,4,derivative=True) == (253, 190) + +def test_polyroots(): + p = polyroots([1,-4]) + assert p[0].ae(4) + p, q = polyroots([1,2,3]) + assert p.ae(-1 - sqrt(2)*j) + assert q.ae(-1 + sqrt(2)*j) + #this is not a real test, it only tests a specific case + assert polyroots([1]) == [] + pytest.raises(ValueError, lambda: polyroots([0])) + +def test_polyroots_legendre(): + n = 64 + coeffs = [11975573020964041433067793888190275875, 0, + -190100434726484311252477736051902332000, 0, + 1437919688271127330313741595496589239248, 0, + -6897338342113537600691931230430793911840, 0, + 23556405536185284408974715545252277554280, 0, + -60969520211303089058522793175947071316960, 0, + 124284021969194758465450309166353645376880, 0, + -204721258548015217049921875719981284186016, 0, + 277415422258095841688223780704620656114900, 0, + -313237834141273382807123548182995095192800, 0, + 297432255354328395601259515935229287637200, 0, + -239057700565161140389797367947941296605600, 0, + 163356095386193445933028201431093219347160, 0, + -95158890516229191805647495979277603503200, 0, + 47310254620162038075933656063247634556400, 0, + -20071017111583894941305187420771723751200, 0, + 7255051932731034189479516844750603752850, 0, + -2228176940331017311443863996901733412640, 0, + 579006552594977616773047095969088431600, 0, + -126584428502545713788439446082310831200, 0, + 23112325428835593809686977515028663000, 0, + -3491517141958743235617737161547844000, 0, + 431305058712550634988073414073557200, 0, + -42927166660756742088912492757452000, 0, + 3378527005707706553294038781836500, 0, + -205277590220215081719131470288800, 0, + 9330799555464321896324157740400, 0, + -304114948474392713657972548576, 0, + 6695289961520387531608984680, 0, + -91048139350447232095702560, 0, + 659769125727878493447120, 0, + -1905929106580294155360, 0, + 916312070471295267] + + with mp.workdps(3): + with pytest.raises(mp.NoConvergence): + polyroots(coeffs, maxsteps=5, cleanup=True, error=False, + extraprec=n*10) + + roots = polyroots(coeffs, maxsteps=50, cleanup=True, error=False, + extraprec=n*10) + roots = [str(r) for r in roots] + assert roots == \ + ['-0.999', '-0.996', '-0.991', '-0.983', '-0.973', '-0.961', + '-0.946', '-0.93', '-0.911', '-0.889', '-0.866', '-0.841', + '-0.813', '-0.784', '-0.753', '-0.72', '-0.685', '-0.649', + '-0.611', '-0.572', '-0.531', '-0.489', '-0.446', '-0.402', + '-0.357', '-0.311', '-0.265', '-0.217', '-0.17', '-0.121', + '-0.073', '-0.0243', '0.0243', '0.073', '0.121', '0.17', '0.217', + '0.265', '0.311', '0.357', '0.402', '0.446', '0.489', '0.531', + '0.572', '0.611', '0.649', '0.685', '0.72', '0.753', '0.784', + '0.813', '0.841', '0.866', '0.889', '0.911', '0.93', '0.946', + '0.961', '0.973', '0.983', '0.991', '0.996', '0.999'] + +def test_polyroots_legendre_init(): + extra_prec = 100 + coeffs = [11975573020964041433067793888190275875, 0, + -190100434726484311252477736051902332000, 0, + 1437919688271127330313741595496589239248, 0, + -6897338342113537600691931230430793911840, 0, + 23556405536185284408974715545252277554280, 0, + -60969520211303089058522793175947071316960, 0, + 124284021969194758465450309166353645376880, 0, + -204721258548015217049921875719981284186016, 0, + 277415422258095841688223780704620656114900, 0, + -313237834141273382807123548182995095192800, 0, + 297432255354328395601259515935229287637200, 0, + -239057700565161140389797367947941296605600, 0, + 163356095386193445933028201431093219347160, 0, + -95158890516229191805647495979277603503200, 0, + 47310254620162038075933656063247634556400, 0, + -20071017111583894941305187420771723751200, 0, + 7255051932731034189479516844750603752850, 0, + -2228176940331017311443863996901733412640, 0, + 579006552594977616773047095969088431600, 0, + -126584428502545713788439446082310831200, 0, + 23112325428835593809686977515028663000, 0, + -3491517141958743235617737161547844000, 0, + 431305058712550634988073414073557200, 0, + -42927166660756742088912492757452000, 0, + 3378527005707706553294038781836500, 0, + -205277590220215081719131470288800, 0, + 9330799555464321896324157740400, 0, + -304114948474392713657972548576, 0, + 6695289961520387531608984680, 0, + -91048139350447232095702560, 0, + 659769125727878493447120, 0, + -1905929106580294155360, 0, + 916312070471295267] + + roots_init = matrix(['-0.999', '-0.996', '-0.991', '-0.983', '-0.973', + '-0.961', '-0.946', '-0.93', '-0.911', '-0.889', + '-0.866', '-0.841', '-0.813', '-0.784', '-0.753', + '-0.72', '-0.685', '-0.649', '-0.611', '-0.572', + '-0.531', '-0.489', '-0.446', '-0.402', '-0.357', + '-0.311', '-0.265', '-0.217', '-0.17', '-0.121', + '-0.073', '-0.0243', '0.0243', '0.073', '0.121', + '0.17', '0.217', '0.265', ' 0.311', '0.357', + '0.402', '0.446', '0.489', '0.531', '0.572', + '0.611', '0.649', '0.685', '0.72', '0.753', + '0.784', '0.813', '0.841', '0.866', '0.889', + '0.911', '0.93', '0.946', '0.961', '0.973', + '0.983', '0.991', '0.996', '0.999', '1.0']) + with mp.workdps(2*mp.dps): + roots_exact = polyroots(coeffs, maxsteps=50, cleanup=True, error=False, + extraprec=2*extra_prec) + with pytest.raises(mp.NoConvergence): + polyroots(coeffs, maxsteps=5, cleanup=True, error=False, + extraprec=extra_prec) + roots,err = polyroots(coeffs, maxsteps=5, cleanup=True, error=True, + extraprec=extra_prec,roots_init=roots_init) + assert max(matrix(roots_exact)-matrix(roots).apply(abs)) < err + roots1,err1 = polyroots(coeffs, maxsteps=25, cleanup=True, error=True, + extraprec=extra_prec,roots_init=roots_init[:60]) + assert max(matrix(roots_exact)-matrix(roots1).apply(abs)) < err1 + +def test_pade(): + one = mpf(1) + mp.dps = 20 + N = 10 + a = [one] + k = 1 + for i in range(1, N+1): + k *= i + a.append(one/k) + p, q = pade(a, N//2, N//2) + for x in arange(0, 1, 0.1): + r = polyval(p[::-1], x)/polyval(q[::-1], x) + assert(r.ae(exp(x), 1.0e-10)) + mp.dps = 15 + +def test_fourier(): + mp.dps = 15 + c, s = fourier(lambda x: x+1, [-1, 2], 2) + #plot([lambda x: x+1, lambda x: fourierval((c, s), [-1, 2], x)], [-1, 2]) + assert c[0].ae(1.5) + assert c[1].ae(-3*sqrt(3)/(2*pi)) + assert c[2].ae(3*sqrt(3)/(4*pi)) + assert s[0] == 0 + assert s[1].ae(3/(2*pi)) + assert s[2].ae(3/(4*pi)) + assert fourierval((c, s), [-1, 2], 1).ae(1.9134966715663442) + +def test_differint(): + mp.dps = 15 + assert differint(lambda t: t, 2, -0.5).ae(8*sqrt(2/pi)/3) + +def test_invlap(): + mp.dps = 15 + t = 0.01 + fp = lambda p: 1/(p+1)**2 + ft = lambda t: t*exp(-t) + ftt = ft(t) + assert invertlaplace(fp,t,method='talbot').ae(ftt) + assert invertlaplace(fp,t,method='stehfest').ae(ftt) + assert invertlaplace(fp,t,method='dehoog').ae(ftt) + assert invertlaplace(fp,t,method='cohen').ae(ftt) + t = 1.0 + ftt = ft(t) + assert invertlaplace(fp,t,method='talbot').ae(ftt) + assert invertlaplace(fp,t,method='stehfest').ae(ftt) + assert invertlaplace(fp,t,method='dehoog').ae(ftt) + assert invertlaplace(fp,t,method='cohen').ae(ftt) + + t = 0.01 + fp = lambda p: log(p)/p + ft = lambda t: -euler-log(t) + ftt = ft(t) + assert invertlaplace(fp,t,method='talbot').ae(ftt) + assert invertlaplace(fp,t,method='stehfest').ae(ftt) + assert invertlaplace(fp,t,method='dehoog').ae(ftt) + assert invertlaplace(fp,t,method='cohen').ae(ftt) + t = 1.0 + ftt = ft(t) + assert invertlaplace(fp,t,method='talbot').ae(ftt) + assert invertlaplace(fp,t,method='stehfest').ae(ftt) + assert invertlaplace(fp,t,method='dehoog').ae(ftt) + assert invertlaplace(fp,t,method='cohen').ae(ftt) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_compatibility.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_compatibility.py new file mode 100644 index 0000000000000000000000000000000000000000..f26d6044b521306b6d1eaeadc5c7839be226dc54 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_compatibility.py @@ -0,0 +1,77 @@ +from mpmath import * +from random import seed, randint, random +import math + +# Test compatibility with Python floats, which are +# IEEE doubles (53-bit) + +N = 5000 +seed(1) + +# Choosing exponents between roughly -140, 140 ensures that +# the Python floats don't overflow or underflow +xs = [(random()-1) * 10**randint(-140, 140) for x in range(N)] +ys = [(random()-1) * 10**randint(-140, 140) for x in range(N)] + +# include some equal values +ys[int(N*0.8):] = xs[int(N*0.8):] + +# Detect whether Python is compiled to use 80-bit floating-point +# instructions, in which case the double compatibility test breaks +uses_x87 = -4.1974624032366689e+117 / -8.4657370748010221e-47 \ + == 4.9581771393902231e+163 + +def test_double_compatibility(): + mp.prec = 53 + for x, y in zip(xs, ys): + mpx = mpf(x) + mpy = mpf(y) + assert mpf(x) == x + assert (mpx < mpy) == (x < y) + assert (mpx > mpy) == (x > y) + assert (mpx == mpy) == (x == y) + assert (mpx != mpy) == (x != y) + assert (mpx <= mpy) == (x <= y) + assert (mpx >= mpy) == (x >= y) + assert mpx == mpx + if uses_x87: + mp.prec = 64 + a = mpx + mpy + b = mpx * mpy + c = mpx / mpy + d = mpx % mpy + mp.prec = 53 + assert +a == x + y + assert +b == x * y + assert +c == x / y + assert +d == x % y + else: + assert mpx + mpy == x + y + assert mpx * mpy == x * y + assert mpx / mpy == x / y + assert mpx % mpy == x % y + assert abs(mpx) == abs(x) + assert mpf(repr(x)) == x + assert ceil(mpx) == math.ceil(x) + assert floor(mpx) == math.floor(x) + +def test_sqrt(): + # this fails quite often. it appers to be float + # that rounds the wrong way, not mpf + fail = 0 + mp.prec = 53 + for x in xs: + x = abs(x) + mp.prec = 100 + mp_high = mpf(x)**0.5 + mp.prec = 53 + mp_low = mpf(x)**0.5 + fp = x**0.5 + assert abs(mp_low-mp_high) <= abs(fp-mp_high) + fail += mp_low != fp + assert fail < N/10 + +def test_bugs(): + # particular bugs + assert mpf(4.4408920985006262E-16) < mpf(1.7763568394002505E-15) + assert mpf(-4.4408920985006262E-16) > mpf(-1.7763568394002505E-15) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_convert.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1db5b55c89e980e08fc3fa43cc9715ad68cac9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_convert.py @@ -0,0 +1,233 @@ +import random +from mpmath import * +from mpmath.libmp import * + + +def test_basic_string(): + """ + Test basic string conversion + """ + mp.dps = 15 + assert mpf('3') == mpf('3.0') == mpf('0003.') == mpf('0.03e2') == mpf(3.0) + assert mpf('30') == mpf('30.0') == mpf('00030.') == mpf(30.0) + for i in range(10): + for j in range(10): + assert mpf('%ie%i' % (i,j)) == i * 10**j + assert str(mpf('25000.0')) == '25000.0' + assert str(mpf('2500.0')) == '2500.0' + assert str(mpf('250.0')) == '250.0' + assert str(mpf('25.0')) == '25.0' + assert str(mpf('2.5')) == '2.5' + assert str(mpf('0.25')) == '0.25' + assert str(mpf('0.025')) == '0.025' + assert str(mpf('0.0025')) == '0.0025' + assert str(mpf('0.00025')) == '0.00025' + assert str(mpf('0.000025')) == '2.5e-5' + assert str(mpf(0)) == '0.0' + assert str(mpf('2.5e1000000000000000000000')) == '2.5e+1000000000000000000000' + assert str(mpf('2.6e-1000000000000000000000')) == '2.6e-1000000000000000000000' + assert str(mpf(1.23402834e-15)) == '1.23402834e-15' + assert str(mpf(-1.23402834e-15)) == '-1.23402834e-15' + assert str(mpf(-1.2344e-15)) == '-1.2344e-15' + assert repr(mpf(-1.2344e-15)) == "mpf('-1.2343999999999999e-15')" + assert str(mpf("2163048125L")) == '2163048125.0' + assert str(mpf("-2163048125l")) == '-2163048125.0' + assert str(mpf("-2163048125L/1088391168")) == '-1.98738118113799' + assert str(mpf("2163048125/1088391168l")) == '1.98738118113799' + +def test_pretty(): + mp.pretty = True + assert repr(mpf(2.5)) == '2.5' + assert repr(mpc(2.5,3.5)) == '(2.5 + 3.5j)' + mp.pretty = False + iv.pretty = True + assert repr(mpi(2.5,3.5)) == '[2.5, 3.5]' + iv.pretty = False + +def test_str_whitespace(): + assert mpf('1.26 ') == 1.26 + +def test_unicode(): + mp.dps = 15 + try: + unicode = unicode + except NameError: + unicode = str + assert mpf(unicode('2.76')) == 2.76 + assert mpf(unicode('inf')) == inf + +def test_str_format(): + assert to_str(from_float(0.1),15,strip_zeros=False) == '0.100000000000000' + assert to_str(from_float(0.0),15,show_zero_exponent=True) == '0.0e+0' + assert to_str(from_float(0.0),0,show_zero_exponent=True) == '.0e+0' + assert to_str(from_float(0.0),0,show_zero_exponent=False) == '.0' + assert to_str(from_float(0.0),1,show_zero_exponent=True) == '0.0e+0' + assert to_str(from_float(0.0),1,show_zero_exponent=False) == '0.0' + assert to_str(from_float(1.23),3,show_zero_exponent=True) == '1.23e+0' + assert to_str(from_float(1.23456789000000e-2),15,strip_zeros=False,min_fixed=0,max_fixed=0) == '1.23456789000000e-2' + assert to_str(from_float(1.23456789000000e+2),15,strip_zeros=False,min_fixed=0,max_fixed=0) == '1.23456789000000e+2' + assert to_str(from_float(2.1287e14), 15, max_fixed=1000) == '212870000000000.0' + assert to_str(from_float(2.1287e15), 15, max_fixed=1000) == '2128700000000000.0' + assert to_str(from_float(2.1287e16), 15, max_fixed=1000) == '21287000000000000.0' + assert to_str(from_float(2.1287e30), 15, max_fixed=1000) == '2128700000000000000000000000000.0' + +def test_tight_string_conversion(): + mp.dps = 15 + # In an old version, '0.5' wasn't recognized as representing + # an exact binary number and was erroneously rounded up or down + assert from_str('0.5', 10, round_floor) == fhalf + assert from_str('0.5', 10, round_ceiling) == fhalf + +def test_eval_repr_invariant(): + """Test that eval(repr(x)) == x""" + random.seed(123) + for dps in [10, 15, 20, 50, 100]: + mp.dps = dps + for i in range(1000): + a = mpf(random.random())**0.5 * 10**random.randint(-100, 100) + assert eval(repr(a)) == a + mp.dps = 15 + +def test_str_bugs(): + mp.dps = 15 + # Decimal rounding used to give the wrong exponent in some cases + assert str(mpf('1e600')) == '1.0e+600' + assert str(mpf('1e10000')) == '1.0e+10000' + +def test_str_prec0(): + assert to_str(from_float(1.234), 0) == '.0e+0' + assert to_str(from_float(1e-15), 0) == '.0e-15' + assert to_str(from_float(1e+15), 0) == '.0e+15' + assert to_str(from_float(-1e-15), 0) == '-.0e-15' + assert to_str(from_float(-1e+15), 0) == '-.0e+15' + +def test_convert_rational(): + mp.dps = 15 + assert from_rational(30, 5, 53, round_nearest) == (0, 3, 1, 2) + assert from_rational(-7, 4, 53, round_nearest) == (1, 7, -2, 3) + assert to_rational((0, 1, -1, 1)) == (1, 2) + +def test_custom_class(): + class mympf: + @property + def _mpf_(self): + return mpf(3.5)._mpf_ + class mympc: + @property + def _mpc_(self): + return mpf(3.5)._mpf_, mpf(2.5)._mpf_ + assert mpf(2) + mympf() == 5.5 + assert mympf() + mpf(2) == 5.5 + assert mpf(mympf()) == 3.5 + assert mympc() + mpc(2) == mpc(5.5, 2.5) + assert mpc(2) + mympc() == mpc(5.5, 2.5) + assert mpc(mympc()) == (3.5+2.5j) + +def test_conversion_methods(): + class SomethingRandom: + pass + class SomethingReal: + def _mpmath_(self, prec, rounding): + return mp.make_mpf(from_str('1.3', prec, rounding)) + class SomethingComplex: + def _mpmath_(self, prec, rounding): + return mp.make_mpc((from_str('1.3', prec, rounding), \ + from_str('1.7', prec, rounding))) + x = mpf(3) + z = mpc(3) + a = SomethingRandom() + y = SomethingReal() + w = SomethingComplex() + for d in [15, 45]: + mp.dps = d + assert (x+y).ae(mpf('4.3')) + assert (y+x).ae(mpf('4.3')) + assert (x+w).ae(mpc('4.3', '1.7')) + assert (w+x).ae(mpc('4.3', '1.7')) + assert (z+y).ae(mpc('4.3')) + assert (y+z).ae(mpc('4.3')) + assert (z+w).ae(mpc('4.3', '1.7')) + assert (w+z).ae(mpc('4.3', '1.7')) + x-y; y-x; x-w; w-x; z-y; y-z; z-w; w-z + x*y; y*x; x*w; w*x; z*y; y*z; z*w; w*z + x/y; y/x; x/w; w/x; z/y; y/z; z/w; w/z + x**y; y**x; x**w; w**x; z**y; y**z; z**w; w**z + x==y; y==x; x==w; w==x; z==y; y==z; z==w; w==z + mp.dps = 15 + assert x.__add__(a) is NotImplemented + assert x.__radd__(a) is NotImplemented + assert x.__lt__(a) is NotImplemented + assert x.__gt__(a) is NotImplemented + assert x.__le__(a) is NotImplemented + assert x.__ge__(a) is NotImplemented + assert x.__eq__(a) is NotImplemented + assert x.__ne__(a) is NotImplemented + # implementation detail + if hasattr(x, "__cmp__"): + assert x.__cmp__(a) is NotImplemented + assert x.__sub__(a) is NotImplemented + assert x.__rsub__(a) is NotImplemented + assert x.__mul__(a) is NotImplemented + assert x.__rmul__(a) is NotImplemented + assert x.__div__(a) is NotImplemented + assert x.__rdiv__(a) is NotImplemented + assert x.__mod__(a) is NotImplemented + assert x.__rmod__(a) is NotImplemented + assert x.__pow__(a) is NotImplemented + assert x.__rpow__(a) is NotImplemented + assert z.__add__(a) is NotImplemented + assert z.__radd__(a) is NotImplemented + assert z.__eq__(a) is NotImplemented + assert z.__ne__(a) is NotImplemented + assert z.__sub__(a) is NotImplemented + assert z.__rsub__(a) is NotImplemented + assert z.__mul__(a) is NotImplemented + assert z.__rmul__(a) is NotImplemented + assert z.__div__(a) is NotImplemented + assert z.__rdiv__(a) is NotImplemented + assert z.__pow__(a) is NotImplemented + assert z.__rpow__(a) is NotImplemented + +def test_mpmathify(): + assert mpmathify('1/2') == 0.5 + assert mpmathify('(1.0+1.0j)') == mpc(1, 1) + assert mpmathify('(1.2e-10 - 3.4e5j)') == mpc('1.2e-10', '-3.4e5') + assert mpmathify('1j') == mpc(1j) + +def test_issue548(): + try: + # This expression is invalid, but may trigger the ReDOS vulnerability + # in the regular expression for parsing complex numbers. + mpmathify('(' + '1' * 5000 + '!j') + except: + return + # The expression is invalid and should raise an exception. + assert False + +def test_compatibility(): + try: + import numpy as np + from fractions import Fraction + from decimal import Decimal + import decimal + except ImportError: + return + # numpy types + for nptype in np.core.numerictypes.typeDict.values(): + if issubclass(nptype, np.complexfloating): + x = nptype(complex(0.5, -0.5)) + elif issubclass(nptype, np.floating): + x = nptype(0.5) + elif issubclass(nptype, np.integer): + x = nptype(2) + # Handle the weird types + try: diff = np.abs(type(np.sqrt(x))(sqrt(x)) - np.sqrt(x)) + except: continue + assert diff < 2.0**-53 + #Fraction and Decimal + oldprec = mp.prec + mp.prec = 1000 + decimal.getcontext().prec = mp.dps + assert sqrt(Fraction(2, 3)).ae(sqrt(mpf('2/3'))) + assert sqrt(Decimal(2)/Decimal(3)).ae(sqrt(mpf('2/3'))) + mp.prec = oldprec diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_diff.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..f5711609da38862eb4fd62c88d35f1704c9425a4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_diff.py @@ -0,0 +1,61 @@ +from mpmath import * + +def test_diff(): + mp.dps = 15 + assert diff(log, 2.0, n=0).ae(log(2)) + assert diff(cos, 1.0).ae(-sin(1)) + assert diff(abs, 0.0) == 0 + assert diff(abs, 0.0, direction=1) == 1 + assert diff(abs, 0.0, direction=-1) == -1 + assert diff(exp, 1.0).ae(e) + assert diff(exp, 1.0, n=5).ae(e) + assert diff(exp, 2.0, n=5, direction=3*j).ae(e**2) + assert diff(lambda x: x**2, 3.0, method='quad').ae(6) + assert diff(lambda x: 3+x**5, 3.0, n=2, method='quad').ae(540) + assert diff(lambda x: 3+x**5, 3.0, n=2, method='step').ae(540) + assert diffun(sin)(2).ae(cos(2)) + assert diffun(sin, n=2)(2).ae(-sin(2)) + +def test_diffs(): + mp.dps = 15 + assert [chop(d) for d in diffs(sin, 0, 1)] == [0, 1] + assert [chop(d) for d in diffs(sin, 0, 1, method='quad')] == [0, 1] + assert [chop(d) for d in diffs(sin, 0, 2)] == [0, 1, 0] + assert [chop(d) for d in diffs(sin, 0, 2, method='quad')] == [0, 1, 0] + +def test_taylor(): + mp.dps = 15 + # Easy to test since the coefficients are exact in floating-point + assert taylor(sqrt, 1, 4) == [1, 0.5, -0.125, 0.0625, -0.0390625] + +def test_diff_partial(): + mp.dps = 15 + x,y,z = xyz = 2,3,7 + f = lambda x,y,z: 3*x**2 * (y+2)**3 * z**5 + assert diff(f, xyz, (0,0,0)).ae(25210500) + assert diff(f, xyz, (0,0,1)).ae(18007500) + assert diff(f, xyz, (0,0,2)).ae(10290000) + assert diff(f, xyz, (0,1,0)).ae(15126300) + assert diff(f, xyz, (0,1,1)).ae(10804500) + assert diff(f, xyz, (0,1,2)).ae(6174000) + assert diff(f, xyz, (0,2,0)).ae(6050520) + assert diff(f, xyz, (0,2,1)).ae(4321800) + assert diff(f, xyz, (0,2,2)).ae(2469600) + assert diff(f, xyz, (1,0,0)).ae(25210500) + assert diff(f, xyz, (1,0,1)).ae(18007500) + assert diff(f, xyz, (1,0,2)).ae(10290000) + assert diff(f, xyz, (1,1,0)).ae(15126300) + assert diff(f, xyz, (1,1,1)).ae(10804500) + assert diff(f, xyz, (1,1,2)).ae(6174000) + assert diff(f, xyz, (1,2,0)).ae(6050520) + assert diff(f, xyz, (1,2,1)).ae(4321800) + assert diff(f, xyz, (1,2,2)).ae(2469600) + assert diff(f, xyz, (2,0,0)).ae(12605250) + assert diff(f, xyz, (2,0,1)).ae(9003750) + assert diff(f, xyz, (2,0,2)).ae(5145000) + assert diff(f, xyz, (2,1,0)).ae(7563150) + assert diff(f, xyz, (2,1,1)).ae(5402250) + assert diff(f, xyz, (2,1,2)).ae(3087000) + assert diff(f, xyz, (2,2,0)).ae(3025260) + assert diff(f, xyz, (2,2,1)).ae(2160900) + assert diff(f, xyz, (2,2,2)).ae(1234800) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_division.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_division.py new file mode 100644 index 0000000000000000000000000000000000000000..c704cadeb953793ac0a887aa09c4278cf68a2824 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_division.py @@ -0,0 +1,143 @@ +from mpmath.libmp import * +from mpmath import mpf, mp + +from random import randint, choice, seed + +all_modes = [round_floor, round_ceiling, round_down, round_up, round_nearest] + +fb = from_bstr +fi = from_int +ff = from_float + + +def test_div_1_3(): + a = fi(1) + b = fi(3) + c = fi(-1) + + # floor rounds down, ceiling rounds up + assert mpf_div(a, b, 7, round_floor) == fb('0.01010101') + assert mpf_div(a, b, 7, round_ceiling) == fb('0.01010110') + assert mpf_div(a, b, 7, round_down) == fb('0.01010101') + assert mpf_div(a, b, 7, round_up) == fb('0.01010110') + assert mpf_div(a, b, 7, round_nearest) == fb('0.01010101') + + # floor rounds up, ceiling rounds down + assert mpf_div(c, b, 7, round_floor) == fb('-0.01010110') + assert mpf_div(c, b, 7, round_ceiling) == fb('-0.01010101') + assert mpf_div(c, b, 7, round_down) == fb('-0.01010101') + assert mpf_div(c, b, 7, round_up) == fb('-0.01010110') + assert mpf_div(c, b, 7, round_nearest) == fb('-0.01010101') + +def test_mpf_divi_1_3(): + a = 1 + b = fi(3) + c = -1 + assert mpf_rdiv_int(a, b, 7, round_floor) == fb('0.01010101') + assert mpf_rdiv_int(a, b, 7, round_ceiling) == fb('0.01010110') + assert mpf_rdiv_int(a, b, 7, round_down) == fb('0.01010101') + assert mpf_rdiv_int(a, b, 7, round_up) == fb('0.01010110') + assert mpf_rdiv_int(a, b, 7, round_nearest) == fb('0.01010101') + assert mpf_rdiv_int(c, b, 7, round_floor) == fb('-0.01010110') + assert mpf_rdiv_int(c, b, 7, round_ceiling) == fb('-0.01010101') + assert mpf_rdiv_int(c, b, 7, round_down) == fb('-0.01010101') + assert mpf_rdiv_int(c, b, 7, round_up) == fb('-0.01010110') + assert mpf_rdiv_int(c, b, 7, round_nearest) == fb('-0.01010101') + + +def test_div_300(): + + q = fi(1000000) + a = fi(300499999) # a/q is a little less than a half-integer + b = fi(300500000) # b/q exactly a half-integer + c = fi(300500001) # c/q is a little more than a half-integer + + # Check nearest integer rounding (prec=9 as 2**8 < 300 < 2**9) + + assert mpf_div(a, q, 9, round_down) == fi(300) + assert mpf_div(b, q, 9, round_down) == fi(300) + assert mpf_div(c, q, 9, round_down) == fi(300) + assert mpf_div(a, q, 9, round_up) == fi(301) + assert mpf_div(b, q, 9, round_up) == fi(301) + assert mpf_div(c, q, 9, round_up) == fi(301) + + # Nearest even integer is down + assert mpf_div(a, q, 9, round_nearest) == fi(300) + assert mpf_div(b, q, 9, round_nearest) == fi(300) + assert mpf_div(c, q, 9, round_nearest) == fi(301) + + # Nearest even integer is up + a = fi(301499999) + b = fi(301500000) + c = fi(301500001) + assert mpf_div(a, q, 9, round_nearest) == fi(301) + assert mpf_div(b, q, 9, round_nearest) == fi(302) + assert mpf_div(c, q, 9, round_nearest) == fi(302) + + +def test_tight_integer_division(): + # Test that integer division at tightest possible precision is exact + N = 100 + seed(1) + for i in range(N): + a = choice([1, -1]) * randint(1, 1< 1: + print("original matrix (hessenberg):\n", A) + + n = A.rows + + Q, H = mp.hessenberg(A) + + if verbose > 1: + print("Q:\n",Q) + print("H:\n",H) + + B = Q * H * Q.transpose_conj() + + eps = mp.exp(0.8 * mp.log(mp.eps)) + + err0 = 0 + for x in xrange(n): + for y in xrange(n): + err0 += abs(A[y,x] - B[y,x]) + err0 /= n * n + + err1 = 0 + for x in xrange(n): + for y in xrange(x + 2, n): + err1 += abs(H[y,x]) + + if verbose > 0: + print("difference (H):", err0, err1) + + if verbose > 1: + print("B:\n", B) + + assert err0 < eps + assert err1 == 0 + + +def run_schur(A, verbose = 0): + if verbose > 1: + print("original matrix (schur):\n", A) + + n = A.rows + + Q, R = mp.schur(A) + + if verbose > 1: + print("Q:\n", Q) + print("R:\n", R) + + B = Q * R * Q.transpose_conj() + C = Q * Q.transpose_conj() + + eps = mp.exp(0.8 * mp.log(mp.eps)) + + err0 = 0 + for x in xrange(n): + for y in xrange(n): + err0 += abs(A[y,x] - B[y,x]) + err0 /= n * n + + err1 = 0 + for x in xrange(n): + for y in xrange(n): + if x == y: + C[y,x] -= 1 + err1 += abs(C[y,x]) + err1 /= n * n + + err2 = 0 + for x in xrange(n): + for y in xrange(x + 1, n): + err2 += abs(R[y,x]) + + if verbose > 0: + print("difference (S):", err0, err1, err2) + + if verbose > 1: + print("B:\n", B) + + assert err0 < eps + assert err1 < eps + assert err2 == 0 + +def run_eig(A, verbose = 0): + if verbose > 1: + print("original matrix (eig):\n", A) + + n = A.rows + + E, EL, ER = mp.eig(A, left = True, right = True) + + if verbose > 1: + print("E:\n", E) + print("EL:\n", EL) + print("ER:\n", ER) + + eps = mp.exp(0.8 * mp.log(mp.eps)) + + err0 = 0 + for i in xrange(n): + B = A * ER[:,i] - E[i] * ER[:,i] + err0 = max(err0, mp.mnorm(B)) + + B = EL[i,:] * A - EL[i,:] * E[i] + err0 = max(err0, mp.mnorm(B)) + + err0 /= n * n + + if verbose > 0: + print("difference (E):", err0) + + assert err0 < eps + +##################### + +def test_eig_dyn(): + v = 0 + for i in xrange(5): + n = 1 + int(mp.rand() * 5) + if mp.rand() > 0.5: + # real + A = 2 * mp.randmatrix(n, n) - 1 + if mp.rand() > 0.5: + A *= 10 + for x in xrange(n): + for y in xrange(n): + A[x,y] = int(A[x,y]) + else: + A = (2 * mp.randmatrix(n, n) - 1) + 1j * (2 * mp.randmatrix(n, n) - 1) + if mp.rand() > 0.5: + A *= 10 + for x in xrange(n): + for y in xrange(n): + A[x,y] = int(mp.re(A[x,y])) + 1j * int(mp.im(A[x,y])) + + run_hessenberg(A, verbose = v) + run_schur(A, verbose = v) + run_eig(A, verbose = v) + +def test_eig(): + v = 0 + AS = [] + + A = mp.matrix([[2, 1, 0], # jordan block of size 3 + [0, 2, 1], + [0, 0, 2]]) + AS.append(A) + AS.append(A.transpose()) + + A = mp.matrix([[2, 0, 0], # jordan block of size 2 + [0, 2, 1], + [0, 0, 2]]) + AS.append(A) + AS.append(A.transpose()) + + A = mp.matrix([[2, 0, 1], # jordan block of size 2 + [0, 2, 0], + [0, 0, 2]]) + AS.append(A) + AS.append(A.transpose()) + + A= mp.matrix([[0, 0, 1], # cyclic + [1, 0, 0], + [0, 1, 0]]) + AS.append(A) + AS.append(A.transpose()) + + for A in AS: + run_hessenberg(A, verbose = v) + run_schur(A, verbose = v) + run_eig(A, verbose = v) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_eigen_symmetric.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_eigen_symmetric.py new file mode 100644 index 0000000000000000000000000000000000000000..aab3d8ea3142aada6e14ad6d3ea25a7e8293554d --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_eigen_symmetric.py @@ -0,0 +1,357 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +from mpmath import mp +from mpmath import libmp + +xrange = libmp.backend.xrange + +def run_eigsy(A, verbose = False): + if verbose: + print("original matrix:\n", str(A)) + + D, Q = mp.eigsy(A) + B = Q * mp.diag(D) * Q.transpose() + C = A - B + E = Q * Q.transpose() - mp.eye(A.rows) + + if verbose: + print("eigenvalues:\n", D) + print("eigenvectors:\n", Q) + + NC = mp.mnorm(C) + NE = mp.mnorm(E) + + if verbose: + print("difference:", NC, "\n", C, "\n") + print("difference:", NE, "\n", E, "\n") + + eps = mp.exp( 0.8 * mp.log(mp.eps)) + + assert NC < eps + assert NE < eps + + return NC + +def run_eighe(A, verbose = False): + if verbose: + print("original matrix:\n", str(A)) + + D, Q = mp.eighe(A) + B = Q * mp.diag(D) * Q.transpose_conj() + C = A - B + E = Q * Q.transpose_conj() - mp.eye(A.rows) + + if verbose: + print("eigenvalues:\n", D) + print("eigenvectors:\n", Q) + + NC = mp.mnorm(C) + NE = mp.mnorm(E) + + if verbose: + print("difference:", NC, "\n", C, "\n") + print("difference:", NE, "\n", E, "\n") + + eps = mp.exp( 0.8 * mp.log(mp.eps)) + + assert NC < eps + assert NE < eps + + return NC + +def run_svd_r(A, full_matrices = False, verbose = True): + + m, n = A.rows, A.cols + + eps = mp.exp(0.8 * mp.log(mp.eps)) + + if verbose: + print("original matrix:\n", str(A)) + print("full", full_matrices) + + U, S0, V = mp.svd_r(A, full_matrices = full_matrices) + + S = mp.zeros(U.cols, V.rows) + for j in xrange(min(m, n)): + S[j,j] = S0[j] + + if verbose: + print("U:\n", str(U)) + print("S:\n", str(S0)) + print("V:\n", str(V)) + + C = U * S * V - A + err = mp.mnorm(C) + if verbose: + print("C\n", str(C), "\n", err) + assert err < eps + + D = V * V.transpose() - mp.eye(V.rows) + err = mp.mnorm(D) + if verbose: + print("D:\n", str(D), "\n", err) + assert err < eps + + E = U.transpose() * U - mp.eye(U.cols) + err = mp.mnorm(E) + if verbose: + print("E:\n", str(E), "\n", err) + assert err < eps + +def run_svd_c(A, full_matrices = False, verbose = True): + + m, n = A.rows, A.cols + + eps = mp.exp(0.8 * mp.log(mp.eps)) + + if verbose: + print("original matrix:\n", str(A)) + print("full", full_matrices) + + U, S0, V = mp.svd_c(A, full_matrices = full_matrices) + + S = mp.zeros(U.cols, V.rows) + for j in xrange(min(m, n)): + S[j,j] = S0[j] + + if verbose: + print("U:\n", str(U)) + print("S:\n", str(S0)) + print("V:\n", str(V)) + + C = U * S * V - A + err = mp.mnorm(C) + if verbose: + print("C\n", str(C), "\n", err) + assert err < eps + + D = V * V.transpose_conj() - mp.eye(V.rows) + err = mp.mnorm(D) + if verbose: + print("D:\n", str(D), "\n", err) + assert err < eps + + E = U.transpose_conj() * U - mp.eye(U.cols) + err = mp.mnorm(E) + if verbose: + print("E:\n", str(E), "\n", err) + assert err < eps + +def run_gauss(qtype, a, b): + eps = 1e-5 + + d, e = mp.gauss_quadrature(len(a), qtype) + d -= mp.matrix(a) + e -= mp.matrix(b) + + assert mp.mnorm(d) < eps + assert mp.mnorm(e) < eps + +def irandmatrix(n, range = 10): + """ + random matrix with integer entries + """ + A = mp.matrix(n, n) + for i in xrange(n): + for j in xrange(n): + A[i,j]=int( (2 * mp.rand() - 1) * range) + return A + +####################### + +def test_eighe_fixed_matrix(): + A = mp.matrix([[2, 3], [3, 5]]) + run_eigsy(A) + run_eighe(A) + + A = mp.matrix([[7, -11], [-11, 13]]) + run_eigsy(A) + run_eighe(A) + + A = mp.matrix([[2, 11, 7], [11, 3, 13], [7, 13, 5]]) + run_eigsy(A) + run_eighe(A) + + A = mp.matrix([[2, 0, 7], [0, 3, 1], [7, 1, 5]]) + run_eigsy(A) + run_eighe(A) + + # + + A = mp.matrix([[2, 3+7j], [3-7j, 5]]) + run_eighe(A) + + A = mp.matrix([[2, -11j, 0], [+11j, 3, 29j], [0, -29j, 5]]) + run_eighe(A) + + A = mp.matrix([[2, 11 + 17j, 7 + 19j], [11 - 17j, 3, -13 + 23j], [7 - 19j, -13 - 23j, 5]]) + run_eighe(A) + +def test_eigsy_randmatrix(): + N = 5 + + for a in xrange(10): + A = 2 * mp.randmatrix(N, N) - 1 + + for i in xrange(0, N): + for j in xrange(i + 1, N): + A[j,i] = A[i,j] + + run_eigsy(A) + +def test_eighe_randmatrix(): + N = 5 + + for a in xrange(10): + A = (2 * mp.randmatrix(N, N) - 1) + 1j * (2 * mp.randmatrix(N, N) - 1) + + for i in xrange(0, N): + A[i,i] = mp.re(A[i,i]) + for j in xrange(i + 1, N): + A[j,i] = mp.conj(A[i,j]) + + run_eighe(A) + +def test_eigsy_irandmatrix(): + N = 4 + R = 4 + + for a in xrange(10): + A=irandmatrix(N, R) + + for i in xrange(0, N): + for j in xrange(i + 1, N): + A[j,i] = A[i,j] + + run_eigsy(A) + +def test_eighe_irandmatrix(): + N = 4 + R = 4 + + for a in xrange(10): + A=irandmatrix(N, R) + 1j * irandmatrix(N, R) + + for i in xrange(0, N): + A[i,i] = mp.re(A[i,i]) + for j in xrange(i + 1, N): + A[j,i] = mp.conj(A[i,j]) + + run_eighe(A) + +def test_svd_r_rand(): + for i in xrange(5): + full = mp.rand() > 0.5 + m = 1 + int(mp.rand() * 10) + n = 1 + int(mp.rand() * 10) + A = 2 * mp.randmatrix(m, n) - 1 + if mp.rand() > 0.5: + A *= 10 + for x in xrange(m): + for y in xrange(n): + A[x,y]=int(A[x,y]) + + run_svd_r(A, full_matrices = full, verbose = False) + +def test_svd_c_rand(): + for i in xrange(5): + full = mp.rand() > 0.5 + m = 1 + int(mp.rand() * 10) + n = 1 + int(mp.rand() * 10) + A = (2 * mp.randmatrix(m, n) - 1) + 1j * (2 * mp.randmatrix(m, n) - 1) + if mp.rand() > 0.5: + A *= 10 + for x in xrange(m): + for y in xrange(n): + A[x,y]=int(mp.re(A[x,y])) + 1j * int(mp.im(A[x,y])) + + run_svd_c(A, full_matrices=full, verbose=False) + +def test_svd_test_case(): + # a test case from Golub and Reinsch + # (see wilkinson/reinsch: handbook for auto. comp., vol ii-linear algebra, 134-151(1971).) + + eps = mp.exp(0.8 * mp.log(mp.eps)) + + a = [[22, 10, 2, 3, 7], + [14, 7, 10, 0, 8], + [-1, 13, -1, -11, 3], + [-3, -2, 13, -2, 4], + [ 9, 8, 1, -2, 4], + [ 9, 1, -7, 5, -1], + [ 2, -6, 6, 5, 1], + [ 4, 5, 0, -2, 2]] + + a = mp.matrix(a) + b = mp.matrix([mp.sqrt(1248), 20, mp.sqrt(384), 0, 0]) + + S = mp.svd_r(a, compute_uv = False) + S -= b + assert mp.mnorm(S) < eps + + S = mp.svd_c(a, compute_uv = False) + S -= b + assert mp.mnorm(S) < eps + + +def test_gauss_quadrature_static(): + a = [-0.57735027, 0.57735027] + b = [ 1, 1] + run_gauss("legendre", a , b) + + a = [ -0.906179846, -0.538469310, 0, 0.538469310, 0.906179846] + b = [ 0.23692689, 0.47862867, 0.56888889, 0.47862867, 0.23692689] + run_gauss("legendre", a , b) + + a = [ 0.06943184, 0.33000948, 0.66999052, 0.93056816] + b = [ 0.17392742, 0.32607258, 0.32607258, 0.17392742] + run_gauss("legendre01", a , b) + + a = [-0.70710678, 0.70710678] + b = [ 0.88622693, 0.88622693] + run_gauss("hermite", a , b) + + a = [ -2.02018287, -0.958572465, 0, 0.958572465, 2.02018287] + b = [ 0.01995324, 0.39361932, 0.94530872, 0.39361932, 0.01995324] + run_gauss("hermite", a , b) + + a = [ 0.41577456, 2.29428036, 6.28994508] + b = [ 0.71109301, 0.27851773, 0.01038926] + run_gauss("laguerre", a , b) + +def test_gauss_quadrature_dynamic(verbose = False): + n = 5 + + A = mp.randmatrix(2 * n, 1) + + def F(x): + r = 0 + for i in xrange(len(A) - 1, -1, -1): + r = r * x + A[i] + return r + + def run(qtype, FW, R, alpha = 0, beta = 0): + X, W = mp.gauss_quadrature(n, qtype, alpha = alpha, beta = beta) + + a = 0 + for i in xrange(len(X)): + a += W[i] * F(X[i]) + + b = mp.quad(lambda x: FW(x) * F(x), R) + + c = mp.fabs(a - b) + + if verbose: + print(qtype, c, a, b) + + assert c < 1e-5 + + run("legendre", lambda x: 1, [-1, 1]) + run("legendre01", lambda x: 1, [0, 1]) + run("hermite", lambda x: mp.exp(-x*x), [-mp.inf, mp.inf]) + run("laguerre", lambda x: mp.exp(-x), [0, mp.inf]) + run("glaguerre", lambda x: mp.sqrt(x)*mp.exp(-x), [0, mp.inf], alpha = 1 / mp.mpf(2)) + run("chebyshev1", lambda x: 1/mp.sqrt(1-x*x), [-1, 1]) + run("chebyshev2", lambda x: mp.sqrt(1-x*x), [-1, 1]) + run("jacobi", lambda x: (1-x)**(1/mp.mpf(3)) * (1+x)**(1/mp.mpf(5)), [-1, 1], alpha = 1 / mp.mpf(3), beta = 1 / mp.mpf(5) ) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_elliptic.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_elliptic.py new file mode 100644 index 0000000000000000000000000000000000000000..4dddc2df34b8d2fa7f2028b3501e5b7f140d8912 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_elliptic.py @@ -0,0 +1,670 @@ +""" +Limited tests of the elliptic functions module. A full suite of +extensive testing can be found in elliptic_torture_tests.py + +Author of the first version: M.T. Taschuk + +References: + +[1] Abramowitz & Stegun. 'Handbook of Mathematical Functions, 9th Ed.', + (Dover duplicate of 1972 edition) +[2] Whittaker 'A Course of Modern Analysis, 4th Ed.', 1946, + Cambridge University Press + +""" + +import mpmath +import random +import pytest + +from mpmath import * + +def mpc_ae(a, b, eps=eps): + res = True + res = res and a.real.ae(b.real, eps) + res = res and a.imag.ae(b.imag, eps) + return res + +zero = mpf(0) +one = mpf(1) + +jsn = ellipfun('sn') +jcn = ellipfun('cn') +jdn = ellipfun('dn') + +calculate_nome = lambda k: qfrom(k=k) + +def test_ellipfun(): + mp.dps = 15 + assert ellipfun('ss', 0, 0) == 1 + assert ellipfun('cc', 0, 0) == 1 + assert ellipfun('dd', 0, 0) == 1 + assert ellipfun('nn', 0, 0) == 1 + assert ellipfun('sn', 0.25, 0).ae(sin(0.25)) + assert ellipfun('cn', 0.25, 0).ae(cos(0.25)) + assert ellipfun('dn', 0.25, 0).ae(1) + assert ellipfun('ns', 0.25, 0).ae(csc(0.25)) + assert ellipfun('nc', 0.25, 0).ae(sec(0.25)) + assert ellipfun('nd', 0.25, 0).ae(1) + assert ellipfun('sc', 0.25, 0).ae(tan(0.25)) + assert ellipfun('sd', 0.25, 0).ae(sin(0.25)) + assert ellipfun('cd', 0.25, 0).ae(cos(0.25)) + assert ellipfun('cs', 0.25, 0).ae(cot(0.25)) + assert ellipfun('dc', 0.25, 0).ae(sec(0.25)) + assert ellipfun('ds', 0.25, 0).ae(csc(0.25)) + assert ellipfun('sn', 0.25, 1).ae(tanh(0.25)) + assert ellipfun('cn', 0.25, 1).ae(sech(0.25)) + assert ellipfun('dn', 0.25, 1).ae(sech(0.25)) + assert ellipfun('ns', 0.25, 1).ae(coth(0.25)) + assert ellipfun('nc', 0.25, 1).ae(cosh(0.25)) + assert ellipfun('nd', 0.25, 1).ae(cosh(0.25)) + assert ellipfun('sc', 0.25, 1).ae(sinh(0.25)) + assert ellipfun('sd', 0.25, 1).ae(sinh(0.25)) + assert ellipfun('cd', 0.25, 1).ae(1) + assert ellipfun('cs', 0.25, 1).ae(csch(0.25)) + assert ellipfun('dc', 0.25, 1).ae(1) + assert ellipfun('ds', 0.25, 1).ae(csch(0.25)) + assert ellipfun('sn', 0.25, 0.5).ae(0.24615967096986145833) + assert ellipfun('cn', 0.25, 0.5).ae(0.96922928989378439337) + assert ellipfun('dn', 0.25, 0.5).ae(0.98473484156599474563) + assert ellipfun('ns', 0.25, 0.5).ae(4.0624038700573130369) + assert ellipfun('nc', 0.25, 0.5).ae(1.0317476065024692949) + assert ellipfun('nd', 0.25, 0.5).ae(1.0155017958029488665) + assert ellipfun('sc', 0.25, 0.5).ae(0.25397465134058993408) + assert ellipfun('sd', 0.25, 0.5).ae(0.24997558792415733063) + assert ellipfun('cd', 0.25, 0.5).ae(0.98425408443195497052) + assert ellipfun('cs', 0.25, 0.5).ae(3.9374008182374110826) + assert ellipfun('dc', 0.25, 0.5).ae(1.0159978158253033913) + assert ellipfun('ds', 0.25, 0.5).ae(4.0003906313579720593) + + + + +def test_calculate_nome(): + mp.dps = 100 + + q = calculate_nome(zero) + assert(q == zero) + + mp.dps = 25 + # used Mathematica's EllipticNomeQ[m] + math1 = [(mpf(1)/10, mpf('0.006584651553858370274473060')), + (mpf(2)/10, mpf('0.01394285727531826872146409')), + (mpf(3)/10, mpf('0.02227743615715350822901627')), + (mpf(4)/10, mpf('0.03188334731336317755064299')), + (mpf(5)/10, mpf('0.04321391826377224977441774')), + (mpf(6)/10, mpf('0.05702025781460967637754953')), + (mpf(7)/10, mpf('0.07468994353717944761143751')), + (mpf(8)/10, mpf('0.09927369733882489703607378')), + (mpf(9)/10, mpf('0.1401731269542615524091055')), + (mpf(9)/10, mpf('0.1401731269542615524091055'))] + + for i in math1: + m = i[0] + q = calculate_nome(sqrt(m)) + assert q.ae(i[1]) + + mp.dps = 15 + +def test_jtheta(): + mp.dps = 25 + + z = q = zero + for n in range(1,5): + value = jtheta(n, z, q) + assert(value == (n-1)//2) + + for q in [one, mpf(2)]: + for n in range(1,5): + pytest.raises(ValueError, lambda: jtheta(n, z, q)) + + z = one/10 + q = one/11 + + # Mathematical N[EllipticTheta[1, 1/10, 1/11], 25] + res = mpf('0.1069552990104042681962096') + result = jtheta(1, z, q) + assert(result.ae(res)) + + # Mathematica N[EllipticTheta[2, 1/10, 1/11], 25] + res = mpf('1.101385760258855791140606') + result = jtheta(2, z, q) + assert(result.ae(res)) + + # Mathematica N[EllipticTheta[3, 1/10, 1/11], 25] + res = mpf('1.178319743354331061795905') + result = jtheta(3, z, q) + assert(result.ae(res)) + + # Mathematica N[EllipticTheta[4, 1/10, 1/11], 25] + res = mpf('0.8219318954665153577314573') + result = jtheta(4, z, q) + assert(result.ae(res)) + + # test for sin zeros for jtheta(1, z, q) + # test for cos zeros for jtheta(2, z, q) + z1 = pi + z2 = pi/2 + for i in range(10): + qstring = str(random.random()) + q = mpf(qstring) + result = jtheta(1, z1, q) + assert(result.ae(0)) + result = jtheta(2, z2, q) + assert(result.ae(0)) + mp.dps = 15 + + +def test_jtheta_issue_79(): + # near the circle of covergence |q| = 1 the convergence slows + # down; for |q| > Q_LIM the theta functions raise ValueError + mp.dps = 30 + mp.dps += 30 + q = mpf(6)/10 - one/10**6 - mpf(8)/10 * j + mp.dps -= 30 + # Mathematica run first + # N[EllipticTheta[3, 1, 6/10 - 10^-6 - 8/10*I], 2000] + # then it works: + # N[EllipticTheta[3, 1, 6/10 - 10^-6 - 8/10*I], 30] + res = mpf('32.0031009628901652627099524264') + \ + mpf('16.6153027998236087899308935624') * j + result = jtheta(3, 1, q) + # check that for abs(q) > Q_LIM a ValueError exception is raised + mp.dps += 30 + q = mpf(6)/10 - one/10**7 - mpf(8)/10 * j + mp.dps -= 30 + pytest.raises(ValueError, lambda: jtheta(3, 1, q)) + + # bug reported in issue 79 + mp.dps = 100 + z = (1+j)/3 + q = mpf(368983957219251)/10**15 + mpf(636363636363636)/10**15 * j + # Mathematica N[EllipticTheta[1, z, q], 35] + res = mpf('2.4439389177990737589761828991467471') + \ + mpf('0.5446453005688226915290954851851490') *j + mp.dps = 30 + result = jtheta(1, z, q) + assert(result.ae(res)) + mp.dps = 80 + z = 3 + 4*j + q = 0.5 + 0.5*j + r1 = jtheta(1, z, q) + mp.dps = 15 + r2 = jtheta(1, z, q) + assert r1.ae(r2) + mp.dps = 80 + z = 3 + j + q1 = exp(j*3) + # longer test + # for n in range(1, 6) + for n in range(1, 2): + mp.dps = 80 + q = q1*(1 - mpf(1)/10**n) + r1 = jtheta(1, z, q) + mp.dps = 15 + r2 = jtheta(1, z, q) + assert r1.ae(r2) + mp.dps = 15 + # issue 79 about high derivatives + assert jtheta(3, 4.5, 0.25, 9).ae(1359.04892680683) + assert jtheta(3, 4.5, 0.25, 50).ae(-6.14832772630905e+33) + mp.dps = 50 + r = jtheta(3, 4.5, 0.25, 9) + assert r.ae('1359.048926806828939547859396600218966947753213803') + r = jtheta(3, 4.5, 0.25, 50) + assert r.ae('-6148327726309051673317975084654262.4119215720343656') + +def test_jtheta_identities(): + """ + Tests the some of the jacobi identidies found in Abramowitz, + Sec. 16.28, Pg. 576. The identities are tested to 1 part in 10^98. + """ + mp.dps = 110 + eps1 = ldexp(eps, 30) + + for i in range(10): + qstring = str(random.random()) + q = mpf(qstring) + + zstring = str(10*random.random()) + z = mpf(zstring) + # Abramowitz 16.28.1 + # v_1(z, q)**2 * v_4(0, q)**2 = v_3(z, q)**2 * v_2(0, q)**2 + # - v_2(z, q)**2 * v_3(0, q)**2 + term1 = (jtheta(1, z, q)**2) * (jtheta(4, zero, q)**2) + term2 = (jtheta(3, z, q)**2) * (jtheta(2, zero, q)**2) + term3 = (jtheta(2, z, q)**2) * (jtheta(3, zero, q)**2) + equality = term1 - term2 + term3 + assert(equality.ae(0, eps1)) + + zstring = str(100*random.random()) + z = mpf(zstring) + # Abramowitz 16.28.2 + # v_2(z, q)**2 * v_4(0, q)**2 = v_4(z, q)**2 * v_2(0, q)**2 + # - v_1(z, q)**2 * v_3(0, q)**2 + term1 = (jtheta(2, z, q)**2) * (jtheta(4, zero, q)**2) + term2 = (jtheta(4, z, q)**2) * (jtheta(2, zero, q)**2) + term3 = (jtheta(1, z, q)**2) * (jtheta(3, zero, q)**2) + equality = term1 - term2 + term3 + assert(equality.ae(0, eps1)) + + # Abramowitz 16.28.3 + # v_3(z, q)**2 * v_4(0, q)**2 = v_4(z, q)**2 * v_3(0, q)**2 + # - v_1(z, q)**2 * v_2(0, q)**2 + term1 = (jtheta(3, z, q)**2) * (jtheta(4, zero, q)**2) + term2 = (jtheta(4, z, q)**2) * (jtheta(3, zero, q)**2) + term3 = (jtheta(1, z, q)**2) * (jtheta(2, zero, q)**2) + equality = term1 - term2 + term3 + assert(equality.ae(0, eps1)) + + # Abramowitz 16.28.4 + # v_4(z, q)**2 * v_4(0, q)**2 = v_3(z, q)**2 * v_3(0, q)**2 + # - v_2(z, q)**2 * v_2(0, q)**2 + term1 = (jtheta(4, z, q)**2) * (jtheta(4, zero, q)**2) + term2 = (jtheta(3, z, q)**2) * (jtheta(3, zero, q)**2) + term3 = (jtheta(2, z, q)**2) * (jtheta(2, zero, q)**2) + equality = term1 - term2 + term3 + assert(equality.ae(0, eps1)) + + # Abramowitz 16.28.5 + # v_2(0, q)**4 + v_4(0, q)**4 == v_3(0, q)**4 + term1 = (jtheta(2, zero, q))**4 + term2 = (jtheta(4, zero, q))**4 + term3 = (jtheta(3, zero, q))**4 + equality = term1 + term2 - term3 + assert(equality.ae(0, eps1)) + mp.dps = 15 + +def test_jtheta_complex(): + mp.dps = 30 + z = mpf(1)/4 + j/8 + q = mpf(1)/3 + j/7 + # Mathematica N[EllipticTheta[1, 1/4 + I/8, 1/3 + I/7], 35] + res = mpf('0.31618034835986160705729105731678285') + \ + mpf('0.07542013825835103435142515194358975') * j + r = jtheta(1, z, q) + assert(mpc_ae(r, res)) + + # Mathematica N[EllipticTheta[2, 1/4 + I/8, 1/3 + I/7], 35] + res = mpf('1.6530986428239765928634711417951828') + \ + mpf('0.2015344864707197230526742145361455') * j + r = jtheta(2, z, q) + assert(mpc_ae(r, res)) + + # Mathematica N[EllipticTheta[3, 1/4 + I/8, 1/3 + I/7], 35] + res = mpf('1.6520564411784228184326012700348340') + \ + mpf('0.1998129119671271328684690067401823') * j + r = jtheta(3, z, q) + assert(mpc_ae(r, res)) + + # Mathematica N[EllipticTheta[4, 1/4 + I/8, 1/3 + I/7], 35] + res = mpf('0.37619082382228348252047624089973824') - \ + mpf('0.15623022130983652972686227200681074') * j + r = jtheta(4, z, q) + assert(mpc_ae(r, res)) + + # check some theta function identities + mp.dos = 100 + z = mpf(1)/4 + j/8 + q = mpf(1)/3 + j/7 + mp.dps += 10 + a = [0,0, jtheta(2, 0, q), jtheta(3, 0, q), jtheta(4, 0, q)] + t = [0, jtheta(1, z, q), jtheta(2, z, q), jtheta(3, z, q), jtheta(4, z, q)] + r = [(t[2]*a[4])**2 - (t[4]*a[2])**2 + (t[1] *a[3])**2, + (t[3]*a[4])**2 - (t[4]*a[3])**2 + (t[1] *a[2])**2, + (t[1]*a[4])**2 - (t[3]*a[2])**2 + (t[2] *a[3])**2, + (t[4]*a[4])**2 - (t[3]*a[3])**2 + (t[2] *a[2])**2, + a[2]**4 + a[4]**4 - a[3]**4] + mp.dps -= 10 + for x in r: + assert(mpc_ae(x, mpc(0))) + mp.dps = 15 + +def test_djtheta(): + mp.dps = 30 + + z = one/7 + j/3 + q = one/8 + j/5 + # Mathematica N[EllipticThetaPrime[1, 1/7 + I/3, 1/8 + I/5], 35] + res = mpf('1.5555195883277196036090928995803201') - \ + mpf('0.02439761276895463494054149673076275') * j + result = jtheta(1, z, q, 1) + assert(mpc_ae(result, res)) + + # Mathematica N[EllipticThetaPrime[2, 1/7 + I/3, 1/8 + I/5], 35] + res = mpf('0.19825296689470982332701283509685662') - \ + mpf('0.46038135182282106983251742935250009') * j + result = jtheta(2, z, q, 1) + assert(mpc_ae(result, res)) + + # Mathematica N[EllipticThetaPrime[3, 1/7 + I/3, 1/8 + I/5], 35] + res = mpf('0.36492498415476212680896699407390026') - \ + mpf('0.57743812698666990209897034525640369') * j + result = jtheta(3, z, q, 1) + assert(mpc_ae(result, res)) + + # Mathematica N[EllipticThetaPrime[4, 1/7 + I/3, 1/8 + I/5], 35] + res = mpf('-0.38936892528126996010818803742007352') + \ + mpf('0.66549886179739128256269617407313625') * j + result = jtheta(4, z, q, 1) + assert(mpc_ae(result, res)) + + for i in range(10): + q = (one*random.random() + j*random.random())/2 + # identity in Wittaker, Watson &21.41 + a = jtheta(1, 0, q, 1) + b = jtheta(2, 0, q)*jtheta(3, 0, q)*jtheta(4, 0, q) + assert(a.ae(b)) + + # test higher derivatives + mp.dps = 20 + for q,z in [(one/3, one/5), (one/3 + j/8, one/5), + (one/3, one/5 + j/8), (one/3 + j/7, one/5 + j/8)]: + for n in [1, 2, 3, 4]: + r = jtheta(n, z, q, 2) + r1 = diff(lambda zz: jtheta(n, zz, q), z, n=2) + assert r.ae(r1) + r = jtheta(n, z, q, 3) + r1 = diff(lambda zz: jtheta(n, zz, q), z, n=3) + assert r.ae(r1) + + # identity in Wittaker, Watson &21.41 + q = one/3 + z = zero + a = [0]*5 + a[1] = jtheta(1, z, q, 3)/jtheta(1, z, q, 1) + for n in [2,3,4]: + a[n] = jtheta(n, z, q, 2)/jtheta(n, z, q) + equality = a[2] + a[3] + a[4] - a[1] + assert(equality.ae(0)) + mp.dps = 15 + +def test_jsn(): + """ + Test some special cases of the sn(z, q) function. + """ + mp.dps = 100 + + # trival case + result = jsn(zero, zero) + assert(result == zero) + + # Abramowitz Table 16.5 + # + # sn(0, m) = 0 + + for i in range(10): + qstring = str(random.random()) + q = mpf(qstring) + + equality = jsn(zero, q) + assert(equality.ae(0)) + + # Abramowitz Table 16.6.1 + # + # sn(z, 0) = sin(z), m == 0 + # + # sn(z, 1) = tanh(z), m == 1 + # + # It would be nice to test these, but I find that they run + # in to numerical trouble. I'm currently treating as a boundary + # case for sn function. + + mp.dps = 25 + arg = one/10 + #N[JacobiSN[1/10, 2^-100], 25] + res = mpf('0.09983341664682815230681420') + m = ldexp(one, -100) + result = jsn(arg, m) + assert(result.ae(res)) + + # N[JacobiSN[1/10, 1/10], 25] + res = mpf('0.09981686718599080096451168') + result = jsn(arg, arg) + assert(result.ae(res)) + mp.dps = 15 + +def test_jcn(): + """ + Test some special cases of the cn(z, q) function. + """ + mp.dps = 100 + + # Abramowitz Table 16.5 + # cn(0, q) = 1 + qstring = str(random.random()) + q = mpf(qstring) + cn = jcn(zero, q) + assert(cn.ae(one)) + + # Abramowitz Table 16.6.2 + # + # cn(u, 0) = cos(u), m == 0 + # + # cn(u, 1) = sech(z), m == 1 + # + # It would be nice to test these, but I find that they run + # in to numerical trouble. I'm currently treating as a boundary + # case for cn function. + + mp.dps = 25 + arg = one/10 + m = ldexp(one, -100) + #N[JacobiCN[1/10, 2^-100], 25] + res = mpf('0.9950041652780257660955620') + result = jcn(arg, m) + assert(result.ae(res)) + + # N[JacobiCN[1/10, 1/10], 25] + res = mpf('0.9950058256237368748520459') + result = jcn(arg, arg) + assert(result.ae(res)) + mp.dps = 15 + +def test_jdn(): + """ + Test some special cases of the dn(z, q) function. + """ + mp.dps = 100 + + # Abramowitz Table 16.5 + # dn(0, q) = 1 + mstring = str(random.random()) + m = mpf(mstring) + + dn = jdn(zero, m) + assert(dn.ae(one)) + + mp.dps = 25 + # N[JacobiDN[1/10, 1/10], 25] + res = mpf('0.9995017055025556219713297') + arg = one/10 + result = jdn(arg, arg) + assert(result.ae(res)) + mp.dps = 15 + + +def test_sn_cn_dn_identities(): + """ + Tests the some of the jacobi elliptic function identities found + on Mathworld. Haven't found in Abramowitz. + """ + mp.dps = 100 + N = 5 + for i in range(N): + qstring = str(random.random()) + q = mpf(qstring) + zstring = str(100*random.random()) + z = mpf(zstring) + + # MathWorld + # sn(z, q)**2 + cn(z, q)**2 == 1 + term1 = jsn(z, q)**2 + term2 = jcn(z, q)**2 + equality = one - term1 - term2 + assert(equality.ae(0)) + + # MathWorld + # k**2 * sn(z, m)**2 + dn(z, m)**2 == 1 + for i in range(N): + mstring = str(random.random()) + m = mpf(qstring) + k = m.sqrt() + zstring = str(10*random.random()) + z = mpf(zstring) + term1 = k**2 * jsn(z, m)**2 + term2 = jdn(z, m)**2 + equality = one - term1 - term2 + assert(equality.ae(0)) + + + for i in range(N): + mstring = str(random.random()) + m = mpf(mstring) + k = m.sqrt() + zstring = str(random.random()) + z = mpf(zstring) + + # MathWorld + # k**2 * cn(z, m)**2 + (1 - k**2) = dn(z, m)**2 + term1 = k**2 * jcn(z, m)**2 + term2 = 1 - k**2 + term3 = jdn(z, m)**2 + equality = term3 - term1 - term2 + assert(equality.ae(0)) + + K = ellipk(k**2) + # Abramowitz Table 16.5 + # sn(K, m) = 1; K is K(k), first complete elliptic integral + r = jsn(K, m) + assert(r.ae(one)) + + # Abramowitz Table 16.5 + # cn(K, q) = 0; K is K(k), first complete elliptic integral + equality = jcn(K, m) + assert(equality.ae(0)) + + # Abramowitz Table 16.6.3 + # dn(z, 0) = 1, m == 0 + z = m + value = jdn(z, zero) + assert(value.ae(one)) + + mp.dps = 15 + +def test_sn_cn_dn_complex(): + mp.dps = 30 + # N[JacobiSN[1/4 + I/8, 1/3 + I/7], 35] in Mathematica + res = mpf('0.2495674401066275492326652143537') + \ + mpf('0.12017344422863833381301051702823') * j + u = mpf(1)/4 + j/8 + m = mpf(1)/3 + j/7 + r = jsn(u, m) + assert(mpc_ae(r, res)) + + #N[JacobiCN[1/4 + I/8, 1/3 + I/7], 35] + res = mpf('0.9762691700944007312693721148331') - \ + mpf('0.0307203994181623243583169154824')*j + r = jcn(u, m) + #assert r.real.ae(res.real) + #assert r.imag.ae(res.imag) + assert(mpc_ae(r, res)) + + #N[JacobiDN[1/4 + I/8, 1/3 + I/7], 35] + res = mpf('0.99639490163039577560547478589753039') - \ + mpf('0.01346296520008176393432491077244994')*j + r = jdn(u, m) + assert(mpc_ae(r, res)) + mp.dps = 15 + +def test_elliptic_integrals(): + # Test cases from Carlson's paper + mp.dps = 15 + assert elliprd(0,2,1).ae(1.7972103521033883112) + assert elliprd(2,3,4).ae(0.16510527294261053349) + assert elliprd(j,-j,2).ae(0.65933854154219768919) + assert elliprd(0,j,-j).ae(1.2708196271909686299 + 2.7811120159520578777j) + assert elliprd(0,j-1,j).ae(-1.8577235439239060056 - 0.96193450888838559989j) + assert elliprd(-2-j,-j,-1+j).ae(1.8249027393703805305 - 1.2218475784827035855j) + # extra test cases + assert elliprg(0,0,0) == 0 + assert elliprg(0,0,16).ae(2) + assert elliprg(0,16,0).ae(2) + assert elliprg(16,0,0).ae(2) + assert elliprg(1,4,0).ae(1.2110560275684595248036) + assert elliprg(1,0,4).ae(1.2110560275684595248036) + assert elliprg(0,4,1).ae(1.2110560275684595248036) + # should be symmetric -- fixes a bug present in the paper + x,y,z = 1,1j,-1+1j + assert elliprg(x,y,z).ae(0.64139146875812627545 + 0.58085463774808290907j) + assert elliprg(x,z,y).ae(0.64139146875812627545 + 0.58085463774808290907j) + assert elliprg(y,x,z).ae(0.64139146875812627545 + 0.58085463774808290907j) + assert elliprg(y,z,x).ae(0.64139146875812627545 + 0.58085463774808290907j) + assert elliprg(z,x,y).ae(0.64139146875812627545 + 0.58085463774808290907j) + assert elliprg(z,y,x).ae(0.64139146875812627545 + 0.58085463774808290907j) + + for n in [5, 15, 30, 60, 100]: + mp.dps = n + assert elliprf(1,2,0).ae('1.3110287771460599052324197949455597068413774757158115814084108519003952935352071251151477664807145467230678763') + assert elliprf(0.5,1,0).ae('1.854074677301371918433850347195260046217598823521766905585928045056021776838119978357271861650371897277771871') + assert elliprf(j,-j,0).ae('1.854074677301371918433850347195260046217598823521766905585928045056021776838119978357271861650371897277771871') + assert elliprf(j-1,j,0).ae(mpc('0.79612586584233913293056938229563057846592264089185680214929401744498956943287031832657642790719940442165621412', + '-1.2138566698364959864300942567386038975419875860741507618279563735753073152507112254567291141460317931258599889')) + assert elliprf(2,3,4).ae('0.58408284167715170669284916892566789240351359699303216166309375305508295130412919665541330837704050454472379308') + assert elliprf(j,-j,2).ae('1.0441445654064360931078658361850779139591660747973017593275012615517220315993723776182276555339288363064476126') + assert elliprf(j-1,j,1-j).ae(mpc('0.93912050218619371196624617169781141161485651998254431830645241993282941057500174238125105410055253623847335313', + '-0.53296252018635269264859303449447908970360344322834582313172115220559316331271520508208025270300138589669326136')) + assert elliprc(0,0.25).ae(+pi) + assert elliprc(2.25,2).ae(+ln2) + assert elliprc(0,j).ae(mpc('1.1107207345395915617539702475151734246536554223439225557713489017391086982748684776438317336911913093408525532', + '-1.1107207345395915617539702475151734246536554223439225557713489017391086982748684776438317336911913093408525532')) + assert elliprc(-j,j).ae(mpc('1.2260849569072198222319655083097718755633725139745941606203839524036426936825652935738621522906572884239069297', + '-0.34471136988767679699935618332997956653521218571295874986708834375026550946053920574015526038040124556716711353')) + assert elliprc(0.25,-2).ae(ln2/3) + assert elliprc(j,-1).ae(mpc('0.77778596920447389875196055840799837589537035343923012237628610795937014001905822029050288316217145443865649819', + '0.1983248499342877364755170948292130095921681309577950696116251029742793455964385947473103628983664877025779304')) + assert elliprj(0,1,2,3).ae('0.77688623778582332014190282640545501102298064276022952731669118325952563819813258230708177398475643634103990878') + assert elliprj(2,3,4,5).ae('0.14297579667156753833233879421985774801466647854232626336218889885463800128817976132826443904216546421431528308') + assert elliprj(2,3,4,-1+j).ae(mpc('0.13613945827770535203521374457913768360237593025944342652613569368333226052158214183059386307242563164036672709', + '-0.38207561624427164249600936454845112611060375760094156571007648297226090050927156176977091273224510621553615189')) + assert elliprj(j,-j,0,2).ae('1.6490011662710884518243257224860232300246792717163891216346170272567376981346412066066050103935109581019055806') + assert elliprj(-1+j,-1-j,1,2).ae('0.94148358841220238083044612133767270187474673547917988681610772381758628963408843935027667916713866133196845063') + assert elliprj(j,-j,0,1-j).ae(mpc('1.8260115229009316249372594065790946657011067182850435297162034335356430755397401849070610280860044610878657501', + '1.2290661908643471500163617732957042849283739403009556715926326841959667290840290081010472716420690899886276961')) + assert elliprj(-1+j,-1-j,1,-3+j).ae(mpc('-0.61127970812028172123588152373622636829986597243716610650831553882054127570542477508023027578037045504958619422', + '-1.0684038390006807880182112972232562745485871763154040245065581157751693730095703406209466903752930797510491155')) + assert elliprj(-1+j,-2-j,-j,-1+j).ae(mpc('1.8249027393703805304622013339009022294368078659619988943515764258335975852685224202567854526307030593012768954', + '-1.2218475784827035854568450371590419833166777535029296025352291308244564398645467465067845461070602841312456831')) + + assert elliprg(0,16,16).ae(+pi) + assert elliprg(2,3,4).ae('1.7255030280692277601061148835701141842692457170470456590515892070736643637303053506944907685301315299153040991') + assert elliprg(0,j,-j).ae('0.42360654239698954330324956174109581824072295516347109253028968632986700241706737986160014699730561497106114281') + assert elliprg(j-1,j,0).ae(mpc('0.44660591677018372656731970402124510811555212083508861036067729944477855594654762496407405328607219895053798354', + '0.70768352357515390073102719507612395221369717586839400605901402910893345301718731499237159587077682267374159282')) + assert elliprg(-j,j-1,j).ae(mpc('0.36023392184473309033675652092928695596803358846377334894215349632203382573844427952830064383286995172598964266', + '0.40348623401722113740956336997761033878615232917480045914551915169013722542827052849476969199578321834819903921')) + assert elliprg(0, mpf('0.0796'), 4).ae('1.0284758090288040009838871385180217366569777284430590125081211090574701293154645750017813190805144572673802094') + mp.dps = 15 + + # more test cases for the branch of ellippi / elliprj + assert elliprj(-1-0.5j, -10-6j, -10-3j, -5+10j).ae(0.128470516743927699 + 0.102175950778504625j, abs_eps=1e-8) + assert elliprj(1.987, 4.463 - 1.614j, 0, -3.965).ae(-0.341575118513811305 - 0.394703757004268486j, abs_eps=1e-8) + assert elliprj(0.3068, -4.037+0.632j, 1.654, -0.9609).ae(-1.14735199581485639 - 0.134450158867472264j, abs_eps=1e-8) + assert elliprj(0.3068, -4.037-0.632j, 1.654, -0.9609).ae(1.758765901861727 - 0.161002343366626892j, abs_eps=1e-5) + assert elliprj(0.3068, -4.037+0.0632j, 1.654, -0.9609).ae(-1.17157627949475577 - 0.069182614173988811j, abs_eps=1e-8) + assert elliprj(0.3068, -4.037+0.00632j, 1.654, -0.9609).ae(-1.17337595670549633 - 0.0623069224526925j, abs_eps=1e-8) + + # these require accurate integration + assert elliprj(0.3068, -4.037-0.0632j, 1.654, -0.9609).ae(1.77940452391261626 + 0.0388711305592447234j) + assert elliprj(0.3068, -4.037-0.00632j, 1.654, -0.9609).ae(1.77806722756403055 + 0.0592749824572262329j) + # issue #571 + assert ellippi(2.1 + 0.94j, 2.3 + 0.98j, 2.5 + 0.01j).ae(-0.40652414240811963438 + 2.1547659461404749309j) + + assert ellippi(2.0-1.0j, 2.0+1.0j).ae(1.8578723151271115 - 1.18642180609983531j) + assert ellippi(2.0-0.5j, 0.5+1.0j).ae(0.936761970766645807 - 1.61876787838890786j) + assert ellippi(2.0, 1.0+1.0j).ae(0.999881420735506708 - 2.4139272867045391j) + assert ellippi(2.0+1.0j, 2.0-1.0j).ae(1.8578723151271115 + 1.18642180609983531j) + assert ellippi(2.0+1.0j, 2.0).ae(2.78474654927885845 + 2.02204728966993314j) + +def test_issue_238(): + assert isnan(qfrom(m=nan)) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_fp.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_fp.py new file mode 100644 index 0000000000000000000000000000000000000000..99f3759c3071c4d55e0481472f3d16c1f5df1fef --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_fp.py @@ -0,0 +1,1671 @@ +""" +Easy-to-use test-generating code: + +cases = ''' +exp 2.25 +log 2.25 +''' + +from mpmath import * +mp.dps = 20 +for test in cases.splitlines(): + if not test: + continue + words = test.split() + fname = words[0] + args = words[1:] + argstr = ", ".join(args) + testline = "%s(%s)" % (fname, argstr) + ans = str(eval(testline)) + print " assert ae(fp.%s, %s)" % (testline, ans) + +""" + +from mpmath import fp + +def ae(x, y, tol=1e-12): + if x == y: + return True + return abs(x-y) <= tol*abs(y) + +def test_conj(): + assert fp.conj(4) == 4 + assert fp.conj(3+4j) == 3-4j + assert fp.fdot([1,2],[3,2+1j], conjugate=True) == 7-2j + +def test_fp_number_parts(): + assert ae(fp.arg(3), 0.0) + assert ae(fp.arg(-3), 3.1415926535897932385) + assert ae(fp.arg(3j), 1.5707963267948966192) + assert ae(fp.arg(-3j), -1.5707963267948966192) + assert ae(fp.arg(2+3j), 0.98279372324732906799) + assert ae(fp.arg(-1-1j), -2.3561944901923449288) + assert ae(fp.re(2.5), 2.5) + assert ae(fp.re(2.5+3j), 2.5) + assert ae(fp.im(2.5), 0.0) + assert ae(fp.im(2.5+3j), 3.0) + assert ae(fp.floor(2.5), 2.0) + assert ae(fp.floor(2), 2.0) + assert ae(fp.floor(2.0+0j), (2.0 + 0.0j)) + assert ae(fp.floor(-1.5-0.5j), (-2.0 - 1.0j)) + assert ae(fp.ceil(2.5), 3.0) + assert ae(fp.ceil(2), 2.0) + assert ae(fp.ceil(2.0+0j), (2.0 + 0.0j)) + assert ae(fp.ceil(-1.5-0.5j), (-1.0 + 0.0j)) + +def test_fp_cospi_sinpi(): + assert ae(fp.sinpi(0), 0.0) + assert ae(fp.sinpi(0.25), 0.7071067811865475244) + assert ae(fp.sinpi(0.5), 1.0) + assert ae(fp.sinpi(0.75), 0.7071067811865475244) + assert ae(fp.sinpi(1), 0.0) + assert ae(fp.sinpi(1.25), -0.7071067811865475244) + assert ae(fp.sinpi(1.5), -1.0) + assert ae(fp.sinpi(1.75), -0.7071067811865475244) + assert ae(fp.sinpi(2), 0.0) + assert ae(fp.sinpi(2.25), 0.7071067811865475244) + assert ae(fp.sinpi(0+3j), (0.0 + 6195.8238636085899556j)) + assert ae(fp.sinpi(0.25+3j), (4381.1091260582448033 + 4381.1090689950686908j)) + assert ae(fp.sinpi(0.5+3j), (6195.8239443081075259 + 0.0j)) + assert ae(fp.sinpi(0.75+3j), (4381.1091260582448033 - 4381.1090689950686908j)) + assert ae(fp.sinpi(1+3j), (0.0 - 6195.8238636085899556j)) + assert ae(fp.sinpi(1.25+3j), (-4381.1091260582448033 - 4381.1090689950686908j)) + assert ae(fp.sinpi(1.5+3j), (-6195.8239443081075259 + 0.0j)) + assert ae(fp.sinpi(1.75+3j), (-4381.1091260582448033 + 4381.1090689950686908j)) + assert ae(fp.sinpi(2+3j), (0.0 + 6195.8238636085899556j)) + assert ae(fp.sinpi(2.25+3j), (4381.1091260582448033 + 4381.1090689950686908j)) + assert ae(fp.sinpi(-0.75), -0.7071067811865475244) + assert ae(fp.sinpi(-1e-10), -3.1415926535897933529e-10) + assert ae(fp.sinpi(1e-10), 3.1415926535897933529e-10) + assert ae(fp.sinpi(1e-10+1e-10j), (3.141592653589793353e-10 + 3.1415926535897933528e-10j)) + assert ae(fp.sinpi(1e-10-1e-10j), (3.141592653589793353e-10 - 3.1415926535897933528e-10j)) + assert ae(fp.sinpi(-1e-10+1e-10j), (-3.141592653589793353e-10 + 3.1415926535897933528e-10j)) + assert ae(fp.sinpi(-1e-10-1e-10j), (-3.141592653589793353e-10 - 3.1415926535897933528e-10j)) + assert ae(fp.cospi(0), 1.0) + assert ae(fp.cospi(0.25), 0.7071067811865475244) + assert ae(fp.cospi(0.5), 0.0) + assert ae(fp.cospi(0.75), -0.7071067811865475244) + assert ae(fp.cospi(1), -1.0) + assert ae(fp.cospi(1.25), -0.7071067811865475244) + assert ae(fp.cospi(1.5), 0.0) + assert ae(fp.cospi(1.75), 0.7071067811865475244) + assert ae(fp.cospi(2), 1.0) + assert ae(fp.cospi(2.25), 0.7071067811865475244) + assert ae(fp.cospi(0+3j), (6195.8239443081075259 + 0.0j)) + assert ae(fp.cospi(0.25+3j), (4381.1091260582448033 - 4381.1090689950686908j)) + assert ae(fp.cospi(0.5+3j), (0.0 - 6195.8238636085899556j)) + assert ae(fp.cospi(0.75+3j), (-4381.1091260582448033 - 4381.1090689950686908j)) + assert ae(fp.cospi(1+3j), (-6195.8239443081075259 + 0.0j)) + assert ae(fp.cospi(1.25+3j), (-4381.1091260582448033 + 4381.1090689950686908j)) + assert ae(fp.cospi(1.5+3j), (0.0 + 6195.8238636085899556j)) + assert ae(fp.cospi(1.75+3j), (4381.1091260582448033 + 4381.1090689950686908j)) + assert ae(fp.cospi(2+3j), (6195.8239443081075259 + 0.0j)) + assert ae(fp.cospi(2.25+3j), (4381.1091260582448033 - 4381.1090689950686908j)) + assert ae(fp.cospi(-0.75), -0.7071067811865475244) + assert ae(fp.sinpi(-0.7), -0.80901699437494750611) + assert ae(fp.cospi(-0.7), -0.5877852522924730163) + assert ae(fp.cospi(-3+2j), (-267.74676148374822225 + 0.0j)) + assert ae(fp.sinpi(-3+2j), (0.0 - 267.74489404101651426j)) + assert ae(fp.sinpi(-0.7+2j), (-216.6116802292079471 - 157.37650009392034693j)) + assert ae(fp.cospi(-0.7+2j), (-157.37759774921754565 + 216.61016943630197336j)) + +def test_fp_expj(): + assert ae(fp.expj(0), (1.0 + 0.0j)) + assert ae(fp.expj(1), (0.5403023058681397174 + 0.84147098480789650665j)) + assert ae(fp.expj(2), (-0.416146836547142387 + 0.9092974268256816954j)) + assert ae(fp.expj(0.75), (0.73168886887382088631 + 0.68163876002333416673j)) + assert ae(fp.expj(2+3j), (-0.020718731002242879378 + 0.045271253156092975488j)) + assert ae(fp.expjpi(0), (1.0 + 0.0j)) + assert ae(fp.expjpi(1), (-1.0 + 0.0j)) + assert ae(fp.expjpi(2), (1.0 + 0.0j)) + assert ae(fp.expjpi(0.75), (-0.7071067811865475244 + 0.7071067811865475244j)) + assert ae(fp.expjpi(2+3j), (0.000080699517570304599239 + 0.0j)) + +def test_fp_bernoulli(): + assert ae(fp.bernoulli(0), 1.0) + assert ae(fp.bernoulli(1), -0.5) + assert ae(fp.bernoulli(2), 0.16666666666666666667) + assert ae(fp.bernoulli(10), 0.075757575757575757576) + assert ae(fp.bernoulli(11), 0.0) + +def test_fp_gamma(): + assert ae(fp.gamma(1), 1.0) + assert ae(fp.gamma(1.5), 0.88622692545275801365) + assert ae(fp.gamma(10), 362880.0) + assert ae(fp.gamma(-0.5), -3.5449077018110320546) + assert ae(fp.gamma(-7.1), 0.0016478244570263333622) + assert ae(fp.gamma(12.3), 83385367.899970000963) + assert ae(fp.gamma(2+0j), (1.0 + 0.0j)) + assert ae(fp.gamma(-2.5+0j), (-0.94530872048294188123 + 0.0j)) + assert ae(fp.gamma(3+4j), (0.0052255384713692141947 - 0.17254707929430018772j)) + assert ae(fp.gamma(-3-4j), (0.00001460997305874775607 - 0.000020760733311509070396j)) + assert ae(fp.fac(0), 1.0) + assert ae(fp.fac(1), 1.0) + assert ae(fp.fac(20), 2432902008176640000.0) + assert ae(fp.fac(-3.5), -0.94530872048294188123) + assert ae(fp.fac(2+3j), (-0.44011340763700171113 - 0.06363724312631702183j)) + assert ae(fp.loggamma(1.0), 0.0) + assert ae(fp.loggamma(2.0), 0.0) + assert ae(fp.loggamma(3.0), 0.69314718055994530942) + assert ae(fp.loggamma(7.25), 7.0521854507385394449) + assert ae(fp.loggamma(1000.0), 5905.2204232091812118) + assert ae(fp.loggamma(1e50), 1.1412925464970229298e+52) + assert ae(fp.loggamma(1e25+1e25j), (5.6125802751733671621e+26 + 5.7696599078528568383e+26j)) + assert ae(fp.loggamma(3+4j), (-1.7566267846037841105 + 4.7426644380346579282j)) + assert ae(fp.loggamma(-0.5), (1.2655121234846453965 - 3.1415926535897932385j)) + assert ae(fp.loggamma(-1.25), (1.3664317612369762346 - 6.2831853071795864769j)) + assert ae(fp.loggamma(-2.75), (0.0044878975359557733115 - 9.4247779607693797154j)) + assert ae(fp.loggamma(-3.5), (-1.3090066849930420464 - 12.566370614359172954j)) + assert ae(fp.loggamma(-4.5), (-2.8130840817693161197 - 15.707963267948966192j)) + assert ae(fp.loggamma(-2+3j), (-6.776523813485657093 - 4.568791367260286402j)) + assert ae(fp.loggamma(-1000.3), (-5912.8440347785205041 - 3144.7342462433830317j)) + assert ae(fp.loggamma(-100-100j), (-632.35117666833135562 - 158.37641469650352462j)) + assert ae(fp.loggamma(1e-10), 23.025850929882735237) + assert ae(fp.loggamma(-1e-10), (23.02585092999817837 - 3.1415926535897932385j)) + assert ae(fp.loggamma(1e-10j), (23.025850929940456804 - 1.5707963268526181857j)) + assert ae(fp.loggamma(1e-10j-1e-10), (22.679277339718205716 - 2.3561944902500664954j)) + +def test_fp_psi(): + assert ae(fp.psi(0, 3.7), 1.1671535393615114409) + assert ae(fp.psi(0, 0.5), -1.9635100260214234794) + assert ae(fp.psi(0, 1), -0.57721566490153286061) + assert ae(fp.psi(0, -2.5), 1.1031566406452431872) + assert ae(fp.psi(0, 12.9), 2.5179671503279156347) + assert ae(fp.psi(0, 100), 4.6001618527380874002) + assert ae(fp.psi(0, 2500.3), 7.8239660143238547877) + assert ae(fp.psi(0, 1e40), 92.103403719761827391) + assert ae(fp.psi(0, 1e200), 460.51701859880913677) + assert ae(fp.psi(0, 3.7+0j), (1.1671535393615114409 + 0.0j)) + assert ae(fp.psi(1, 3), 0.39493406684822643647) + assert ae(fp.psi(3, 2+3j), (-0.05383196209159972116 + 0.0076890935247364805218j)) + assert ae(fp.psi(4, -0.5+1j), (1.2719531355492328195 - 18.211833410936276774j)) + assert ae(fp.harmonic(0), 0.0) + assert ae(fp.harmonic(1), 1.0) + assert ae(fp.harmonic(2), 1.5) + assert ae(fp.harmonic(100), 5.1873775176396202608) + assert ae(fp.harmonic(-2.5), 1.2803723055467760478) + assert ae(fp.harmonic(2+3j), (1.9390425294578375875 + 0.87336044981834544043j)) + assert ae(fp.harmonic(-5-4j), (2.3725754822349437733 - 2.4160904444801621j)) + +def test_fp_zeta(): + assert ae(fp.zeta(1e100), 1.0) + assert ae(fp.zeta(3), 1.2020569031595942854) + assert ae(fp.zeta(2+0j), (1.6449340668482264365 + 0.0j)) + assert ae(fp.zeta(0.93), -13.713619351638164784) + assert ae(fp.zeta(1.74), 1.9796863545771774095) + assert ae(fp.zeta(0.0), -0.5) + assert ae(fp.zeta(-1.0), -0.083333333333333333333) + assert ae(fp.zeta(-2.0), 0.0) + assert ae(fp.zeta(-3.0), 0.0083333333333333333333) + assert ae(fp.zeta(-500.0), 0.0) + assert ae(fp.zeta(-7.4), 0.0036537321227995882447) + assert ae(fp.zeta(2.1), 1.5602165335033620158) + assert ae(fp.zeta(26.9), 1.0000000079854809935) + assert ae(fp.zeta(26), 1.0000000149015548284) + assert ae(fp.zeta(27), 1.0000000074507117898) + assert ae(fp.zeta(28), 1.0000000037253340248) + assert ae(fp.zeta(27.1), 1.000000006951755045) + assert ae(fp.zeta(32.7), 1.0000000001433243232) + assert ae(fp.zeta(100), 1.0) + assert ae(fp.altzeta(3.5), 0.92755357777394803511) + assert ae(fp.altzeta(1), 0.69314718055994530942) + assert ae(fp.altzeta(2), 0.82246703342411321824) + assert ae(fp.altzeta(0), 0.5) + assert ae(fp.zeta(-2+3j, 1), (0.13297115587929864827 + 0.12305330040458776494j)) + assert ae(fp.zeta(-2+3j, 5), (18.384866151867576927 - 11.377015110597711009j)) + assert ae(fp.zeta(1.0000000001), 9999999173.1735741337) + assert ae(fp.zeta(0.9999999999), -9999999172.0191428039) + assert ae(fp.zeta(1+0.000000001j), (0.57721566490153286061 - 999999999.99999993765j)) + assert ae(fp.primezeta(2.5+4j), (-0.16922458243438033385 - 0.010847965298387727811j)) + assert ae(fp.primezeta(4), 0.076993139764246844943) + assert ae(fp.riemannr(3.7), 2.3034079839110855717) + assert ae(fp.riemannr(8), 3.9011860449341499474) + assert ae(fp.riemannr(3+4j), (2.2369653314259991796 + 1.6339943856990281694j)) + +def test_fp_hyp2f1(): + assert ae(fp.hyp2f1(1, (3,2), 3.25, 5.0), (-0.46600275923108143059 - 0.74393667908854842325j)) + assert ae(fp.hyp2f1(1+1j, (3,2), 3.25, 5.0), (-5.9208875603806515987 - 2.3813557707889590686j)) + assert ae(fp.hyp2f1(1+1j, (3,2), 3.25, 2+3j), (0.17174552030925080445 + 0.19589781970539389999j)) + +def test_fp_erf(): + assert fp.erf(2) == fp.erf(2.0) == fp.erf(2.0+0.0j) + assert fp.erf(fp.inf) == 1.0 + assert fp.erf(fp.ninf) == -1.0 + assert ae(fp.erf(0), 0.0) + assert ae(fp.erf(-0), -0.0) + assert ae(fp.erf(0.3), 0.32862675945912741619) + assert ae(fp.erf(-0.3), -0.32862675945912741619) + assert ae(fp.erf(0.9), 0.79690821242283213966) + assert ae(fp.erf(-0.9), -0.79690821242283213966) + assert ae(fp.erf(1.0), 0.84270079294971486934) + assert ae(fp.erf(-1.0), -0.84270079294971486934) + assert ae(fp.erf(1.1), 0.88020506957408172966) + assert ae(fp.erf(-1.1), -0.88020506957408172966) + assert ae(fp.erf(8.5), 1.0) + assert ae(fp.erf(-8.5), -1.0) + assert ae(fp.erf(9.1), 1.0) + assert ae(fp.erf(-9.1), -1.0) + assert ae(fp.erf(20.0), 1.0) + assert ae(fp.erf(-20.0), -1.0) + assert ae(fp.erf(10000.0), 1.0) + assert ae(fp.erf(-10000.0), -1.0) + assert ae(fp.erf(1e+50), 1.0) + assert ae(fp.erf(-1e+50), -1.0) + assert ae(fp.erf(1j), 1.650425758797542876j) + assert ae(fp.erf(-1j), -1.650425758797542876j) + assert ae(fp.erf((2+3j)), (-20.829461427614568389 + 8.6873182714701631444j)) + assert ae(fp.erf(-(2+3j)), -(-20.829461427614568389 + 8.6873182714701631444j)) + assert ae(fp.erf((8+9j)), (-1072004.2525062051158 + 364149.91954310255423j)) + assert ae(fp.erf(-(8+9j)), -(-1072004.2525062051158 + 364149.91954310255423j)) + assert fp.erfc(fp.inf) == 0.0 + assert fp.erfc(fp.ninf) == 2.0 + assert fp.erfc(0) == 1 + assert fp.erfc(-0.0) == 1 + assert fp.erfc(0+0j) == 1 + assert ae(fp.erfc(0.3), 0.67137324054087258381) + assert ae(fp.erfc(-0.3), 1.3286267594591274162) + assert ae(fp.erfc(0.9), 0.20309178757716786034) + assert ae(fp.erfc(-0.9), 1.7969082124228321397) + assert ae(fp.erfc(1.0), 0.15729920705028513066) + assert ae(fp.erfc(-1.0), 1.8427007929497148693) + assert ae(fp.erfc(1.1), 0.11979493042591827034) + assert ae(fp.erfc(-1.1), 1.8802050695740817297) + assert ae(fp.erfc(8.5), 2.7623240713337714461e-33) + assert ae(fp.erfc(-8.5), 2.0) + assert ae(fp.erfc(9.1), 6.6969004279886077452e-38) + assert ae(fp.erfc(-9.1), 2.0) + assert ae(fp.erfc(20.0), 5.3958656116079009289e-176) + assert ae(fp.erfc(-20.0), 2.0) + assert ae(fp.erfc(10000.0), 0.0) + assert ae(fp.erfc(-10000.0), 2.0) + assert ae(fp.erfc(1e+50), 0.0) + assert ae(fp.erfc(-1e+50), 2.0) + assert ae(fp.erfc(1j), (1.0 - 1.650425758797542876j)) + assert ae(fp.erfc(-1j), (1.0 + 1.650425758797542876j)) + assert ae(fp.erfc((2+3j)), (21.829461427614568389 - 8.6873182714701631444j), 1e-13) + assert ae(fp.erfc(-(2+3j)), (-19.829461427614568389 + 8.6873182714701631444j), 1e-13) + assert ae(fp.erfc((8+9j)), (1072005.2525062051158 - 364149.91954310255423j)) + assert ae(fp.erfc(-(8+9j)), (-1072003.2525062051158 + 364149.91954310255423j)) + assert ae(fp.erfc(20+0j), (5.3958656116079009289e-176 + 0.0j)) + +def test_fp_lambertw(): + assert ae(fp.lambertw(0.0), 0.0) + assert ae(fp.lambertw(1.0), 0.567143290409783873) + assert ae(fp.lambertw(7.5), 1.5662309537823875394) + assert ae(fp.lambertw(-0.25), -0.35740295618138890307) + assert ae(fp.lambertw(-10.0), (1.3699809685212708156 + 2.140194527074713196j)) + assert ae(fp.lambertw(0+0j), (0.0 + 0.0j)) + assert ae(fp.lambertw(4+0j), (1.2021678731970429392 + 0.0j)) + assert ae(fp.lambertw(1000.5), 5.2500227450408980127) + assert ae(fp.lambertw(1e100), 224.84310644511850156) + assert ae(fp.lambertw(-1000.0), (5.1501630246362515223 + 2.6641981432905204596j)) + assert ae(fp.lambertw(1e-10), 9.9999999990000003645e-11) + assert ae(fp.lambertw(1e-10j), (1.0000000000000000728e-20 + 1.0000000000000000364e-10j)) + assert ae(fp.lambertw(3+4j), (1.2815618061237758782 + 0.53309522202097107131j)) + assert ae(fp.lambertw(-3-4j), (1.0750730665692549276 - 1.3251023817343588823j)) + assert ae(fp.lambertw(10000+1000j), (7.2361526563371602186 + 0.087567810943839352034j)) + assert ae(fp.lambertw(0.0, -1), -fp.inf) + assert ae(fp.lambertw(1.0, -1), (-1.5339133197935745079 - 4.3751851530618983855j)) + assert ae(fp.lambertw(7.5, -1), (0.44125668415098614999 - 4.8039842008452390179j)) + assert ae(fp.lambertw(-0.25, -1), -2.1532923641103496492) + assert ae(fp.lambertw(-10.0, -1), (1.3699809685212708156 - 2.140194527074713196j)) + assert ae(fp.lambertw(0+0j, -1), -fp.inf) + assert ae(fp.lambertw(4+0j, -1), (-0.15730793189620765317 - 4.6787800704666656212j)) + assert ae(fp.lambertw(1000.5, -1), (4.9153765415404024736 - 5.4465682700815159569j)) + assert ae(fp.lambertw(1e100, -1), (224.84272130101601052 - 6.2553713838167244141j)) + assert ae(fp.lambertw(-1000.0, -1), (5.1501630246362515223 - 2.6641981432905204596j)) + assert ae(fp.lambertw(1e-10, -1), (-26.303186778379041521 - 3.2650939117038283975j)) + assert ae(fp.lambertw(1e-10j, -1), (-26.297238779529035028 - 1.6328071613455765135j)) + assert ae(fp.lambertw(3+4j, -1), (0.25856740686699741676 - 3.8521166861614355895j)) + assert ae(fp.lambertw(-3-4j, -1), (-0.32028750204310768396 - 6.8801677192091972343j)) + assert ae(fp.lambertw(10000+1000j, -1), (7.0255308742285435567 - 5.5177506835734067601j)) + assert ae(fp.lambertw(0.0, 2), -fp.inf) + assert ae(fp.lambertw(1.0, 2), (-2.4015851048680028842 + 10.776299516115070898j)) + assert ae(fp.lambertw(7.5, 2), (-0.38003357962843791529 + 10.960916473368746184j)) + assert ae(fp.lambertw(-0.25, 2), (-4.0558735269061511898 + 13.852334658567271386j)) + assert ae(fp.lambertw(-10.0, 2), (-0.34479123764318858696 + 14.112740596763592363j)) + assert ae(fp.lambertw(0+0j, 2), -fp.inf) + assert ae(fp.lambertw(4+0j, 2), (-1.0070343323804262788 + 10.903476551861683082j)) + assert ae(fp.lambertw(1000.5, 2), (4.4076185165459395295 + 11.365524591091402177j)) + assert ae(fp.lambertw(1e100, 2), (224.84156762724875878 + 12.510785262632255672j)) + assert ae(fp.lambertw(-1000.0, 2), (4.1984245610246530756 + 14.420478573754313845j)) + assert ae(fp.lambertw(1e-10, 2), (-26.362258095445866488 + 9.7800247407031482519j)) + assert ae(fp.lambertw(1e-10j, 2), (-26.384250801683084252 + 11.403535950607739763j)) + assert ae(fp.lambertw(3+4j, 2), (-0.86554679943333993562 + 11.849956798331992027j)) + assert ae(fp.lambertw(-3-4j, 2), (-0.55792273874679112639 + 8.7173627024159324811j)) + assert ae(fp.lambertw(10000+1000j, 2), (6.6223802254585662734 + 11.61348646825020766j)) + +def test_fp_stress_ei_e1(): + # Can be tightened on recent Pythons with more accurate math/cmath + ATOL = 1e-13 + PTOL = 1e-12 + v = fp.e1(1.1641532182693481445e-10) + assert ae(v, 22.296641293693077672, tol=ATOL) + assert type(v) is float + v = fp.e1(0.25) + assert ae(v, 1.0442826344437381945, tol=ATOL) + assert type(v) is float + v = fp.e1(1.0) + assert ae(v, 0.21938393439552027368, tol=ATOL) + assert type(v) is float + v = fp.e1(2.0) + assert ae(v, 0.048900510708061119567, tol=ATOL) + assert type(v) is float + v = fp.e1(5.0) + assert ae(v, 0.0011482955912753257973, tol=ATOL) + assert type(v) is float + v = fp.e1(20.0) + assert ae(v, 9.8355252906498816904e-11, tol=ATOL) + assert type(v) is float + v = fp.e1(30.0) + assert ae(v, 3.0215520106888125448e-15, tol=ATOL) + assert type(v) is float + v = fp.e1(40.0) + assert ae(v, 1.0367732614516569722e-19, tol=ATOL) + assert type(v) is float + v = fp.e1(50.0) + assert ae(v, 3.7832640295504590187e-24, tol=ATOL) + assert type(v) is float + v = fp.e1(80.0) + assert ae(v, 2.2285432586884729112e-37, tol=ATOL) + assert type(v) is float + v = fp.e1((1.1641532182693481445e-10 + 0.0j)) + assert ae(v, (22.296641293693077672 + 0.0j), tol=ATOL) + assert ae(v.real, 22.296641293693077672, tol=PTOL) + assert v.imag == 0 + v = fp.e1((0.25 + 0.0j)) + assert ae(v, (1.0442826344437381945 + 0.0j), tol=ATOL) + assert ae(v.real, 1.0442826344437381945, tol=PTOL) + assert v.imag == 0 + v = fp.e1((1.0 + 0.0j)) + assert ae(v, (0.21938393439552027368 + 0.0j), tol=ATOL) + assert ae(v.real, 0.21938393439552027368, tol=PTOL) + assert v.imag == 0 + v = fp.e1((2.0 + 0.0j)) + assert ae(v, (0.048900510708061119567 + 0.0j), tol=ATOL) + assert ae(v.real, 0.048900510708061119567, tol=PTOL) + assert v.imag == 0 + v = fp.e1((5.0 + 0.0j)) + assert ae(v, (0.0011482955912753257973 + 0.0j), tol=ATOL) + assert ae(v.real, 0.0011482955912753257973, tol=PTOL) + assert v.imag == 0 + v = fp.e1((20.0 + 0.0j)) + assert ae(v, (9.8355252906498816904e-11 + 0.0j), tol=ATOL) + assert ae(v.real, 9.8355252906498816904e-11, tol=PTOL) + assert v.imag == 0 + v = fp.e1((30.0 + 0.0j)) + assert ae(v, (3.0215520106888125448e-15 + 0.0j), tol=ATOL) + assert ae(v.real, 3.0215520106888125448e-15, tol=PTOL) + assert v.imag == 0 + v = fp.e1((40.0 + 0.0j)) + assert ae(v, (1.0367732614516569722e-19 + 0.0j), tol=ATOL) + assert ae(v.real, 1.0367732614516569722e-19, tol=PTOL) + assert v.imag == 0 + v = fp.e1((50.0 + 0.0j)) + assert ae(v, (3.7832640295504590187e-24 + 0.0j), tol=ATOL) + assert ae(v.real, 3.7832640295504590187e-24, tol=PTOL) + assert v.imag == 0 + v = fp.e1((80.0 + 0.0j)) + assert ae(v, (2.2285432586884729112e-37 + 0.0j), tol=ATOL) + assert ae(v.real, 2.2285432586884729112e-37, tol=PTOL) + assert v.imag == 0 + v = fp.e1((4.6566128730773925781e-10 + 1.1641532182693481445e-10j)) + assert ae(v, (20.880034622014215597 - 0.24497866301044883237j), tol=ATOL) + assert ae(v.real, 20.880034622014215597, tol=PTOL) + assert ae(v.imag, -0.24497866301044883237, tol=PTOL) + v = fp.e1((1.0 + 0.25j)) + assert ae(v, (0.19731063945004229095 - 0.087366045774299963672j), tol=ATOL) + assert ae(v.real, 0.19731063945004229095, tol=PTOL) + assert ae(v.imag, -0.087366045774299963672, tol=PTOL) + v = fp.e1((4.0 + 1.0j)) + assert ae(v, (0.0013106173980145506944 - 0.0034542480199350626699j), tol=ATOL) + assert ae(v.real, 0.0013106173980145506944, tol=PTOL) + assert ae(v.imag, -0.0034542480199350626699, tol=PTOL) + v = fp.e1((8.0 + 2.0j)) + assert ae(v, (-0.000022278049065270225945 - 0.000029191940456521555288j), tol=ATOL) + assert ae(v.real, -0.000022278049065270225945, tol=PTOL) + assert ae(v.imag, -0.000029191940456521555288, tol=PTOL) + v = fp.e1((20.0 + 5.0j)) + assert ae(v, (4.7711374515765346894e-11 + 8.2902652405126947359e-11j), tol=ATOL) + assert ae(v.real, 4.7711374515765346894e-11, tol=PTOL) + assert ae(v.imag, 8.2902652405126947359e-11, tol=PTOL) + v = fp.e1((80.0 + 20.0j)) + assert ae(v, (3.8353473865788235787e-38 - 2.129247592349605139e-37j), tol=ATOL) + assert ae(v.real, 3.8353473865788235787e-38, tol=PTOL) + assert ae(v.imag, -2.129247592349605139e-37, tol=PTOL) + v = fp.e1((120.0 + 30.0j)) + assert ae(v, (2.3836002337480334716e-55 + 5.6704043587126198306e-55j), tol=ATOL) + assert ae(v.real, 2.3836002337480334716e-55, tol=PTOL) + assert ae(v.imag, 5.6704043587126198306e-55, tol=PTOL) + v = fp.e1((160.0 + 40.0j)) + assert ae(v, (-1.6238022898654510661e-72 - 1.104172355572287367e-72j), tol=ATOL) + assert ae(v.real, -1.6238022898654510661e-72, tol=PTOL) + assert ae(v.imag, -1.104172355572287367e-72, tol=PTOL) + v = fp.e1((200.0 + 50.0j)) + assert ae(v, (6.6800061461666228487e-90 + 1.4473816083541016115e-91j), tol=ATOL) + assert ae(v.real, 6.6800061461666228487e-90, tol=PTOL) + assert ae(v.imag, 1.4473816083541016115e-91, tol=PTOL) + v = fp.e1((320.0 + 80.0j)) + assert ae(v, (4.2737871527778786157e-143 + 3.1789935525785660314e-142j), tol=ATOL) + assert ae(v.real, 4.2737871527778786157e-143, tol=PTOL) + assert ae(v.imag, 3.1789935525785660314e-142, tol=PTOL) + v = fp.e1((1.1641532182693481445e-10 + 1.1641532182693481445e-10j)) + assert ae(v, (21.950067703413105017 - 0.7853981632810329878j), tol=ATOL) + assert ae(v.real, 21.950067703413105017, tol=PTOL) + assert ae(v.imag, -0.7853981632810329878, tol=PTOL) + v = fp.e1((0.25 + 0.25j)) + assert ae(v, (0.71092525792923287894 - 0.56491812441304194711j), tol=ATOL) + assert ae(v.real, 0.71092525792923287894, tol=PTOL) + assert ae(v.imag, -0.56491812441304194711, tol=PTOL) + v = fp.e1((1.0 + 1.0j)) + assert ae(v, (0.00028162445198141832551 - 0.17932453503935894015j), tol=ATOL) + assert ae(v.real, 0.00028162445198141832551, tol=PTOL) + assert ae(v.imag, -0.17932453503935894015, tol=PTOL) + v = fp.e1((2.0 + 2.0j)) + assert ae(v, (-0.033767089606562004246 - 0.018599414169750541925j), tol=ATOL) + assert ae(v.real, -0.033767089606562004246, tol=PTOL) + assert ae(v.imag, -0.018599414169750541925, tol=PTOL) + v = fp.e1((5.0 + 5.0j)) + assert ae(v, (0.0007266506660356393891 + 0.00047102780163522245054j), tol=ATOL) + assert ae(v.real, 0.0007266506660356393891, tol=PTOL) + assert ae(v.imag, 0.00047102780163522245054, tol=PTOL) + v = fp.e1((20.0 + 20.0j)) + assert ae(v, (-2.3824537449367396579e-11 - 6.6969873156525615158e-11j), tol=ATOL) + assert ae(v.real, -2.3824537449367396579e-11, tol=PTOL) + assert ae(v.imag, -6.6969873156525615158e-11, tol=PTOL) + v = fp.e1((30.0 + 30.0j)) + assert ae(v, (1.7316045841744061617e-15 + 1.3065678019487308689e-15j), tol=ATOL) + assert ae(v.real, 1.7316045841744061617e-15, tol=PTOL) + assert ae(v.imag, 1.3065678019487308689e-15, tol=PTOL) + v = fp.e1((40.0 + 40.0j)) + assert ae(v, (-7.4001043002899232182e-20 - 4.991847855336816304e-21j), tol=ATOL) + assert ae(v.real, -7.4001043002899232182e-20, tol=PTOL) + assert ae(v.imag, -4.991847855336816304e-21, tol=PTOL) + v = fp.e1((50.0 + 50.0j)) + assert ae(v, (2.3566128324644641219e-24 - 1.3188326726201614778e-24j), tol=ATOL) + assert ae(v.real, 2.3566128324644641219e-24, tol=PTOL) + assert ae(v.imag, -1.3188326726201614778e-24, tol=PTOL) + v = fp.e1((80.0 + 80.0j)) + assert ae(v, (9.8279750572186526673e-38 + 1.243952841288868831e-37j), tol=ATOL) + assert ae(v.real, 9.8279750572186526673e-38, tol=PTOL) + assert ae(v.imag, 1.243952841288868831e-37, tol=PTOL) + v = fp.e1((1.1641532182693481445e-10 + 4.6566128730773925781e-10j)) + assert ae(v, (20.880034621664969632 - 1.3258176632023711778j), tol=ATOL) + assert ae(v.real, 20.880034621664969632, tol=PTOL) + assert ae(v.imag, -1.3258176632023711778, tol=PTOL) + v = fp.e1((0.25 + 1.0j)) + assert ae(v, (-0.16868306393667788761 - 0.4858011885947426971j), tol=ATOL) + assert ae(v.real, -0.16868306393667788761, tol=PTOL) + assert ae(v.imag, -0.4858011885947426971, tol=PTOL) + v = fp.e1((1.0 + 4.0j)) + assert ae(v, (0.03373591813926547318 + 0.073523452241083821877j), tol=ATOL) + assert ae(v.real, 0.03373591813926547318, tol=PTOL) + assert ae(v.imag, 0.073523452241083821877, tol=PTOL) + v = fp.e1((2.0 + 8.0j)) + assert ae(v, (-0.015392833434733785143 - 0.0031747121557605415914j), tol=ATOL) + assert ae(v.real, -0.015392833434733785143, tol=PTOL) + assert ae(v.imag, -0.0031747121557605415914, tol=PTOL) + v = fp.e1((5.0 + 20.0j)) + assert ae(v, (-0.00024419662286542966525 - 0.00021008322966152755674j), tol=ATOL) + assert ae(v.real, -0.00024419662286542966525, tol=PTOL) + assert ae(v.imag, -0.00021008322966152755674, tol=PTOL) + v = fp.e1((20.0 + 80.0j)) + assert ae(v, (2.3255552781051330088e-11 + 8.9463918891349438007e-12j), tol=ATOL) + assert ae(v.real, 2.3255552781051330088e-11, tol=PTOL) + assert ae(v.imag, 8.9463918891349438007e-12, tol=PTOL) + v = fp.e1((30.0 + 120.0j)) + assert ae(v, (-2.7068919097124652332e-16 - 7.0477762411705130239e-16j), tol=ATOL) + assert ae(v.real, -2.7068919097124652332e-16, tol=PTOL) + assert ae(v.imag, -7.0477762411705130239e-16, tol=PTOL) + v = fp.e1((40.0 + 160.0j)) + assert ae(v, (-1.1695597827678024687e-20 + 2.2907401455645736661e-20j), tol=ATOL) + assert ae(v.real, -1.1695597827678024687e-20, tol=PTOL) + assert ae(v.imag, 2.2907401455645736661e-20, tol=PTOL) + v = fp.e1((50.0 + 200.0j)) + assert ae(v, (9.0323746914410162531e-25 - 2.3950601790033530935e-25j), tol=ATOL) + assert ae(v.real, 9.0323746914410162531e-25, tol=PTOL) + assert ae(v.imag, -2.3950601790033530935e-25, tol=PTOL) + v = fp.e1((80.0 + 320.0j)) + assert ae(v, (3.4819106748728063576e-38 - 4.215653005615772724e-38j), tol=ATOL) + assert ae(v.real, 3.4819106748728063576e-38, tol=PTOL) + assert ae(v.imag, -4.215653005615772724e-38, tol=PTOL) + v = fp.e1((0.0 + 1.1641532182693481445e-10j)) + assert ae(v, (22.29664129357666235 - 1.5707963266784812974j), tol=ATOL) + assert ae(v.real, 22.29664129357666235, tol=PTOL) + assert ae(v.imag, -1.5707963266784812974, tol=PTOL) + v = fp.e1((0.0 + 0.25j)) + assert ae(v, (0.82466306258094565309 - 1.3216627564751394551j), tol=ATOL) + assert ae(v.real, 0.82466306258094565309, tol=PTOL) + assert ae(v.imag, -1.3216627564751394551, tol=PTOL) + v = fp.e1((0.0 + 1.0j)) + assert ae(v, (-0.33740392290096813466 - 0.62471325642771360429j), tol=ATOL) + assert ae(v.real, -0.33740392290096813466, tol=PTOL) + assert ae(v.imag, -0.62471325642771360429, tol=PTOL) + v = fp.e1((0.0 + 2.0j)) + assert ae(v, (-0.4229808287748649957 + 0.034616650007798229345j), tol=ATOL) + assert ae(v.real, -0.4229808287748649957, tol=PTOL) + assert ae(v.imag, 0.034616650007798229345, tol=PTOL) + v = fp.e1((0.0 + 5.0j)) + assert ae(v, (0.19002974965664387862 - 0.020865081850222481957j), tol=ATOL) + assert ae(v.real, 0.19002974965664387862, tol=PTOL) + assert ae(v.imag, -0.020865081850222481957, tol=PTOL) + v = fp.e1((0.0 + 20.0j)) + assert ae(v, (-0.04441982084535331654 - 0.022554625751456779068j), tol=ATOL) + assert ae(v.real, -0.04441982084535331654, tol=PTOL) + assert ae(v.imag, -0.022554625751456779068, tol=PTOL) + v = fp.e1((0.0 + 30.0j)) + assert ae(v, (0.033032417282071143779 - 0.0040397867645455082476j), tol=ATOL) + assert ae(v.real, 0.033032417282071143779, tol=PTOL) + assert ae(v.imag, -0.0040397867645455082476, tol=PTOL) + v = fp.e1((0.0 + 40.0j)) + assert ae(v, (-0.019020007896208766962 + 0.016188792559887887544j), tol=ATOL) + assert ae(v.real, -0.019020007896208766962, tol=PTOL) + assert ae(v.imag, 0.016188792559887887544, tol=PTOL) + v = fp.e1((0.0 + 50.0j)) + assert ae(v, (0.0056283863241163054402 - 0.019179254308960724503j), tol=ATOL) + assert ae(v.real, 0.0056283863241163054402, tol=PTOL) + assert ae(v.imag, -0.019179254308960724503, tol=PTOL) + v = fp.e1((0.0 + 80.0j)) + assert ae(v, (0.012402501155070958192 + 0.0015345601175906961199j), tol=ATOL) + assert ae(v.real, 0.012402501155070958192, tol=PTOL) + assert ae(v.imag, 0.0015345601175906961199, tol=PTOL) + v = fp.e1((-1.1641532182693481445e-10 + 4.6566128730773925781e-10j)) + assert ae(v, (20.880034621432138988 - 1.8157749894560994861j), tol=ATOL) + assert ae(v.real, 20.880034621432138988, tol=PTOL) + assert ae(v.imag, -1.8157749894560994861, tol=PTOL) + v = fp.e1((-0.25 + 1.0j)) + assert ae(v, (-0.59066621214766308594 - 0.74474454765205036972j), tol=ATOL) + assert ae(v.real, -0.59066621214766308594, tol=PTOL) + assert ae(v.imag, -0.74474454765205036972, tol=PTOL) + v = fp.e1((-1.0 + 4.0j)) + assert ae(v, (0.49739047283060471093 + 0.41543605404038863174j), tol=ATOL) + assert ae(v.real, 0.49739047283060471093, tol=PTOL) + assert ae(v.imag, 0.41543605404038863174, tol=PTOL) + v = fp.e1((-2.0 + 8.0j)) + assert ae(v, (-0.8705211147733730969 + 0.24099328498605539667j), tol=ATOL) + assert ae(v.real, -0.8705211147733730969, tol=PTOL) + assert ae(v.imag, 0.24099328498605539667, tol=PTOL) + v = fp.e1((-5.0 + 20.0j)) + assert ae(v, (-7.0789514293925893007 - 1.6102177171960790536j), tol=ATOL) + assert ae(v.real, -7.0789514293925893007, tol=PTOL) + assert ae(v.imag, -1.6102177171960790536, tol=PTOL) + v = fp.e1((-20.0 + 80.0j)) + assert ae(v, (5855431.4907298084434 - 720920.93315409165707j), tol=ATOL) + assert ae(v.real, 5855431.4907298084434, tol=PTOL) + assert ae(v.imag, -720920.93315409165707, tol=PTOL) + v = fp.e1((-30.0 + 120.0j)) + assert ae(v, (-65402491644.703470747 - 56697658399.657460294j), tol=ATOL) + assert ae(v.real, -65402491644.703470747, tol=PTOL) + assert ae(v.imag, -56697658399.657460294, tol=PTOL) + v = fp.e1((-40.0 + 160.0j)) + assert ae(v, (25504929379604.776769 + 1429035198630573.2463j), tol=ATOL) + assert ae(v.real, 25504929379604.776769, tol=PTOL) + assert ae(v.imag, 1429035198630573.2463, tol=PTOL) + v = fp.e1((-50.0 + 200.0j)) + assert ae(v, (18437746526988116954.0 - 17146362239046152345.0j), tol=ATOL) + assert ae(v.real, 18437746526988116954.0, tol=PTOL) + assert ae(v.imag, -17146362239046152345.0, tol=PTOL) + v = fp.e1((-80.0 + 320.0j)) + assert ae(v, (3.3464697299634526706e+31 - 1.6473152633843023919e+32j), tol=ATOL) + assert ae(v.real, 3.3464697299634526706e+31, tol=PTOL) + assert ae(v.imag, -1.6473152633843023919e+32, tol=PTOL) + v = fp.e1((-4.6566128730773925781e-10 + 1.1641532182693481445e-10j)) + assert ae(v, (20.880034621082893023 - 2.8966139903465137624j), tol=ATOL) + assert ae(v.real, 20.880034621082893023, tol=PTOL) + assert ae(v.imag, -2.8966139903465137624, tol=PTOL) + v = fp.e1((-1.0 + 0.25j)) + assert ae(v, (-1.8942716983721074932 - 2.4689102827070540799j), tol=ATOL) + assert ae(v.real, -1.8942716983721074932, tol=PTOL) + assert ae(v.imag, -2.4689102827070540799, tol=PTOL) + v = fp.e1((-4.0 + 1.0j)) + assert ae(v, (-14.806699492675420438 + 9.1384225230837893776j), tol=ATOL) + assert ae(v.real, -14.806699492675420438, tol=PTOL) + assert ae(v.imag, 9.1384225230837893776, tol=PTOL) + v = fp.e1((-8.0 + 2.0j)) + assert ae(v, (54.633252667426386294 + 413.20318163814670688j), tol=ATOL) + assert ae(v.real, 54.633252667426386294, tol=PTOL) + assert ae(v.imag, 413.20318163814670688, tol=PTOL) + v = fp.e1((-20.0 + 5.0j)) + assert ae(v, (-711836.97165402624643 - 24745250.939695900956j), tol=ATOL) + assert ae(v.real, -711836.97165402624643, tol=PTOL) + assert ae(v.imag, -24745250.939695900956, tol=PTOL) + v = fp.e1((-80.0 + 20.0j)) + assert ae(v, (-4.2139911108612653091e+32 + 5.3367124741918251637e+32j), tol=ATOL) + assert ae(v.real, -4.2139911108612653091e+32, tol=PTOL) + assert ae(v.imag, 5.3367124741918251637e+32, tol=PTOL) + v = fp.e1((-120.0 + 30.0j)) + assert ae(v, (9.7760616203707508892e+48 - 1.058257682317195792e+50j), tol=ATOL) + assert ae(v.real, 9.7760616203707508892e+48, tol=PTOL) + assert ae(v.imag, -1.058257682317195792e+50, tol=PTOL) + v = fp.e1((-160.0 + 40.0j)) + assert ae(v, (8.7065541466623638861e+66 + 1.6577106725141739889e+67j), tol=ATOL) + assert ae(v.real, 8.7065541466623638861e+66, tol=PTOL) + assert ae(v.imag, 1.6577106725141739889e+67, tol=PTOL) + v = fp.e1((-200.0 + 50.0j)) + assert ae(v, (-3.070744996327018106e+84 - 1.7243244846769415903e+84j), tol=ATOL) + assert ae(v.real, -3.070744996327018106e+84, tol=PTOL) + assert ae(v.imag, -1.7243244846769415903e+84, tol=PTOL) + v = fp.e1((-320.0 + 80.0j)) + assert ae(v, (9.9960598637998647276e+135 - 2.6855081527595608863e+136j), tol=ATOL) + assert ae(v.real, 9.9960598637998647276e+135, tol=PTOL) + assert ae(v.imag, -2.6855081527595608863e+136, tol=PTOL) + v = fp.e1(-1.1641532182693481445e-10) + assert ae(v, (22.296641293460247028 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 22.296641293460247028, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-0.25) + assert ae(v, (0.54254326466191372953 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 0.54254326466191372953, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-1.0) + assert ae(v, (-1.8951178163559367555 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -1.8951178163559367555, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-2.0) + assert ae(v, (-4.9542343560018901634 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -4.9542343560018901634, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-5.0) + assert ae(v, (-40.185275355803177455 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -40.185275355803177455, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-20.0) + assert ae(v, (-25615652.66405658882 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -25615652.66405658882, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-30.0) + assert ae(v, (-368973209407.27419706 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -368973209407.27419706, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-40.0) + assert ae(v, (-6039718263611241.5784 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -6039718263611241.5784, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-50.0) + assert ae(v, (-1.0585636897131690963e+20 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -1.0585636897131690963e+20, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1(-80.0) + assert ae(v, (-7.0146000049047999696e+32 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -7.0146000049047999696e+32, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-1.1641532182693481445e-10 + 0.0j)) + assert ae(v, (22.296641293460247028 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 22.296641293460247028, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-0.25 + 0.0j)) + assert ae(v, (0.54254326466191372953 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 0.54254326466191372953, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-1.0 + 0.0j)) + assert ae(v, (-1.8951178163559367555 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -1.8951178163559367555, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-2.0 + 0.0j)) + assert ae(v, (-4.9542343560018901634 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -4.9542343560018901634, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-5.0 + 0.0j)) + assert ae(v, (-40.185275355803177455 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -40.185275355803177455, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-20.0 + 0.0j)) + assert ae(v, (-25615652.66405658882 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -25615652.66405658882, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-30.0 + 0.0j)) + assert ae(v, (-368973209407.27419706 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -368973209407.27419706, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-40.0 + 0.0j)) + assert ae(v, (-6039718263611241.5784 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -6039718263611241.5784, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-50.0 + 0.0j)) + assert ae(v, (-1.0585636897131690963e+20 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -1.0585636897131690963e+20, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-80.0 + 0.0j)) + assert ae(v, (-7.0146000049047999696e+32 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -7.0146000049047999696e+32, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.e1((-4.6566128730773925781e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (20.880034621082893023 + 2.8966139903465137624j), tol=ATOL) + assert ae(v.real, 20.880034621082893023, tol=PTOL) + assert ae(v.imag, 2.8966139903465137624, tol=PTOL) + v = fp.e1((-1.0 - 0.25j)) + assert ae(v, (-1.8942716983721074932 + 2.4689102827070540799j), tol=ATOL) + assert ae(v.real, -1.8942716983721074932, tol=PTOL) + assert ae(v.imag, 2.4689102827070540799, tol=PTOL) + v = fp.e1((-4.0 - 1.0j)) + assert ae(v, (-14.806699492675420438 - 9.1384225230837893776j), tol=ATOL) + assert ae(v.real, -14.806699492675420438, tol=PTOL) + assert ae(v.imag, -9.1384225230837893776, tol=PTOL) + v = fp.e1((-8.0 - 2.0j)) + assert ae(v, (54.633252667426386294 - 413.20318163814670688j), tol=ATOL) + assert ae(v.real, 54.633252667426386294, tol=PTOL) + assert ae(v.imag, -413.20318163814670688, tol=PTOL) + v = fp.e1((-20.0 - 5.0j)) + assert ae(v, (-711836.97165402624643 + 24745250.939695900956j), tol=ATOL) + assert ae(v.real, -711836.97165402624643, tol=PTOL) + assert ae(v.imag, 24745250.939695900956, tol=PTOL) + v = fp.e1((-80.0 - 20.0j)) + assert ae(v, (-4.2139911108612653091e+32 - 5.3367124741918251637e+32j), tol=ATOL) + assert ae(v.real, -4.2139911108612653091e+32, tol=PTOL) + assert ae(v.imag, -5.3367124741918251637e+32, tol=PTOL) + v = fp.e1((-120.0 - 30.0j)) + assert ae(v, (9.7760616203707508892e+48 + 1.058257682317195792e+50j), tol=ATOL) + assert ae(v.real, 9.7760616203707508892e+48, tol=PTOL) + assert ae(v.imag, 1.058257682317195792e+50, tol=PTOL) + v = fp.e1((-160.0 - 40.0j)) + assert ae(v, (8.7065541466623638861e+66 - 1.6577106725141739889e+67j), tol=ATOL) + assert ae(v.real, 8.7065541466623638861e+66, tol=PTOL) + assert ae(v.imag, -1.6577106725141739889e+67, tol=PTOL) + v = fp.e1((-200.0 - 50.0j)) + assert ae(v, (-3.070744996327018106e+84 + 1.7243244846769415903e+84j), tol=ATOL) + assert ae(v.real, -3.070744996327018106e+84, tol=PTOL) + assert ae(v.imag, 1.7243244846769415903e+84, tol=PTOL) + v = fp.e1((-320.0 - 80.0j)) + assert ae(v, (9.9960598637998647276e+135 + 2.6855081527595608863e+136j), tol=ATOL) + assert ae(v.real, 9.9960598637998647276e+135, tol=PTOL) + assert ae(v.imag, 2.6855081527595608863e+136, tol=PTOL) + v = fp.e1((-1.1641532182693481445e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (21.950067703180274374 + 2.356194490075929607j), tol=ATOL) + assert ae(v.real, 21.950067703180274374, tol=PTOL) + assert ae(v.imag, 2.356194490075929607, tol=PTOL) + v = fp.e1((-0.25 - 0.25j)) + assert ae(v, (0.21441047326710323254 + 2.0732153554307936389j), tol=ATOL) + assert ae(v.real, 0.21441047326710323254, tol=PTOL) + assert ae(v.imag, 2.0732153554307936389, tol=PTOL) + v = fp.e1((-1.0 - 1.0j)) + assert ae(v, (-1.7646259855638540684 + 0.7538228020792708192j), tol=ATOL) + assert ae(v.real, -1.7646259855638540684, tol=PTOL) + assert ae(v.imag, 0.7538228020792708192, tol=PTOL) + v = fp.e1((-2.0 - 2.0j)) + assert ae(v, (-1.8920781621855474089 - 2.1753697842428647236j), tol=ATOL) + assert ae(v.real, -1.8920781621855474089, tol=PTOL) + assert ae(v.imag, -2.1753697842428647236, tol=PTOL) + v = fp.e1((-5.0 - 5.0j)) + assert ae(v, (13.470936071475245856 + 18.464085049321024206j), tol=ATOL) + assert ae(v.real, 13.470936071475245856, tol=PTOL) + assert ae(v.imag, 18.464085049321024206, tol=PTOL) + v = fp.e1((-20.0 - 20.0j)) + assert ae(v, (-16589317.398788971896 - 5831702.3296441771206j), tol=ATOL) + assert ae(v.real, -16589317.398788971896, tol=PTOL) + assert ae(v.imag, -5831702.3296441771206, tol=PTOL) + v = fp.e1((-30.0 - 30.0j)) + assert ae(v, (154596484273.69322527 + 204179357837.41389696j), tol=ATOL) + assert ae(v.real, 154596484273.69322527, tol=PTOL) + assert ae(v.imag, 204179357837.41389696, tol=PTOL) + v = fp.e1((-40.0 - 40.0j)) + assert ae(v, (-287512180321448.45408 - 4203502407932314.974j), tol=ATOL) + assert ae(v.real, -287512180321448.45408, tol=PTOL) + assert ae(v.imag, -4203502407932314.974, tol=PTOL) + v = fp.e1((-50.0 - 50.0j)) + assert ae(v, (-36128528616649268826.0 + 64648801861338741963.0j), tol=ATOL) + assert ae(v.real, -36128528616649268826.0, tol=PTOL) + assert ae(v.imag, 64648801861338741963.0, tol=PTOL) + v = fp.e1((-80.0 - 80.0j)) + assert ae(v, (3.8674816337930010217e+32 + 3.0540709639658071041e+32j), tol=ATOL) + assert ae(v.real, 3.8674816337930010217e+32, tol=PTOL) + assert ae(v.imag, 3.0540709639658071041e+32, tol=PTOL) + v = fp.e1((-1.1641532182693481445e-10 - 4.6566128730773925781e-10j)) + assert ae(v, (20.880034621432138988 + 1.8157749894560994861j), tol=ATOL) + assert ae(v.real, 20.880034621432138988, tol=PTOL) + assert ae(v.imag, 1.8157749894560994861, tol=PTOL) + v = fp.e1((-0.25 - 1.0j)) + assert ae(v, (-0.59066621214766308594 + 0.74474454765205036972j), tol=ATOL) + assert ae(v.real, -0.59066621214766308594, tol=PTOL) + assert ae(v.imag, 0.74474454765205036972, tol=PTOL) + v = fp.e1((-1.0 - 4.0j)) + assert ae(v, (0.49739047283060471093 - 0.41543605404038863174j), tol=ATOL) + assert ae(v.real, 0.49739047283060471093, tol=PTOL) + assert ae(v.imag, -0.41543605404038863174, tol=PTOL) + v = fp.e1((-2.0 - 8.0j)) + assert ae(v, (-0.8705211147733730969 - 0.24099328498605539667j), tol=ATOL) + assert ae(v.real, -0.8705211147733730969, tol=PTOL) + assert ae(v.imag, -0.24099328498605539667, tol=PTOL) + v = fp.e1((-5.0 - 20.0j)) + assert ae(v, (-7.0789514293925893007 + 1.6102177171960790536j), tol=ATOL) + assert ae(v.real, -7.0789514293925893007, tol=PTOL) + assert ae(v.imag, 1.6102177171960790536, tol=PTOL) + v = fp.e1((-20.0 - 80.0j)) + assert ae(v, (5855431.4907298084434 + 720920.93315409165707j), tol=ATOL) + assert ae(v.real, 5855431.4907298084434, tol=PTOL) + assert ae(v.imag, 720920.93315409165707, tol=PTOL) + v = fp.e1((-30.0 - 120.0j)) + assert ae(v, (-65402491644.703470747 + 56697658399.657460294j), tol=ATOL) + assert ae(v.real, -65402491644.703470747, tol=PTOL) + assert ae(v.imag, 56697658399.657460294, tol=PTOL) + v = fp.e1((-40.0 - 160.0j)) + assert ae(v, (25504929379604.776769 - 1429035198630573.2463j), tol=ATOL) + assert ae(v.real, 25504929379604.776769, tol=PTOL) + assert ae(v.imag, -1429035198630573.2463, tol=PTOL) + v = fp.e1((-50.0 - 200.0j)) + assert ae(v, (18437746526988116954.0 + 17146362239046152345.0j), tol=ATOL) + assert ae(v.real, 18437746526988116954.0, tol=PTOL) + assert ae(v.imag, 17146362239046152345.0, tol=PTOL) + v = fp.e1((-80.0 - 320.0j)) + assert ae(v, (3.3464697299634526706e+31 + 1.6473152633843023919e+32j), tol=ATOL) + assert ae(v.real, 3.3464697299634526706e+31, tol=PTOL) + assert ae(v.imag, 1.6473152633843023919e+32, tol=PTOL) + v = fp.e1((0.0 - 1.1641532182693481445e-10j)) + assert ae(v, (22.29664129357666235 + 1.5707963266784812974j), tol=ATOL) + assert ae(v.real, 22.29664129357666235, tol=PTOL) + assert ae(v.imag, 1.5707963266784812974, tol=PTOL) + v = fp.e1((0.0 - 0.25j)) + assert ae(v, (0.82466306258094565309 + 1.3216627564751394551j), tol=ATOL) + assert ae(v.real, 0.82466306258094565309, tol=PTOL) + assert ae(v.imag, 1.3216627564751394551, tol=PTOL) + v = fp.e1((0.0 - 1.0j)) + assert ae(v, (-0.33740392290096813466 + 0.62471325642771360429j), tol=ATOL) + assert ae(v.real, -0.33740392290096813466, tol=PTOL) + assert ae(v.imag, 0.62471325642771360429, tol=PTOL) + v = fp.e1((0.0 - 2.0j)) + assert ae(v, (-0.4229808287748649957 - 0.034616650007798229345j), tol=ATOL) + assert ae(v.real, -0.4229808287748649957, tol=PTOL) + assert ae(v.imag, -0.034616650007798229345, tol=PTOL) + v = fp.e1((0.0 - 5.0j)) + assert ae(v, (0.19002974965664387862 + 0.020865081850222481957j), tol=ATOL) + assert ae(v.real, 0.19002974965664387862, tol=PTOL) + assert ae(v.imag, 0.020865081850222481957, tol=PTOL) + v = fp.e1((0.0 - 20.0j)) + assert ae(v, (-0.04441982084535331654 + 0.022554625751456779068j), tol=ATOL) + assert ae(v.real, -0.04441982084535331654, tol=PTOL) + assert ae(v.imag, 0.022554625751456779068, tol=PTOL) + v = fp.e1((0.0 - 30.0j)) + assert ae(v, (0.033032417282071143779 + 0.0040397867645455082476j), tol=ATOL) + assert ae(v.real, 0.033032417282071143779, tol=PTOL) + assert ae(v.imag, 0.0040397867645455082476, tol=PTOL) + v = fp.e1((0.0 - 40.0j)) + assert ae(v, (-0.019020007896208766962 - 0.016188792559887887544j), tol=ATOL) + assert ae(v.real, -0.019020007896208766962, tol=PTOL) + assert ae(v.imag, -0.016188792559887887544, tol=PTOL) + v = fp.e1((0.0 - 50.0j)) + assert ae(v, (0.0056283863241163054402 + 0.019179254308960724503j), tol=ATOL) + assert ae(v.real, 0.0056283863241163054402, tol=PTOL) + assert ae(v.imag, 0.019179254308960724503, tol=PTOL) + v = fp.e1((0.0 - 80.0j)) + assert ae(v, (0.012402501155070958192 - 0.0015345601175906961199j), tol=ATOL) + assert ae(v.real, 0.012402501155070958192, tol=PTOL) + assert ae(v.imag, -0.0015345601175906961199, tol=PTOL) + v = fp.e1((1.1641532182693481445e-10 - 4.6566128730773925781e-10j)) + assert ae(v, (20.880034621664969632 + 1.3258176632023711778j), tol=ATOL) + assert ae(v.real, 20.880034621664969632, tol=PTOL) + assert ae(v.imag, 1.3258176632023711778, tol=PTOL) + v = fp.e1((0.25 - 1.0j)) + assert ae(v, (-0.16868306393667788761 + 0.4858011885947426971j), tol=ATOL) + assert ae(v.real, -0.16868306393667788761, tol=PTOL) + assert ae(v.imag, 0.4858011885947426971, tol=PTOL) + v = fp.e1((1.0 - 4.0j)) + assert ae(v, (0.03373591813926547318 - 0.073523452241083821877j), tol=ATOL) + assert ae(v.real, 0.03373591813926547318, tol=PTOL) + assert ae(v.imag, -0.073523452241083821877, tol=PTOL) + v = fp.e1((2.0 - 8.0j)) + assert ae(v, (-0.015392833434733785143 + 0.0031747121557605415914j), tol=ATOL) + assert ae(v.real, -0.015392833434733785143, tol=PTOL) + assert ae(v.imag, 0.0031747121557605415914, tol=PTOL) + v = fp.e1((5.0 - 20.0j)) + assert ae(v, (-0.00024419662286542966525 + 0.00021008322966152755674j), tol=ATOL) + assert ae(v.real, -0.00024419662286542966525, tol=PTOL) + assert ae(v.imag, 0.00021008322966152755674, tol=PTOL) + v = fp.e1((20.0 - 80.0j)) + assert ae(v, (2.3255552781051330088e-11 - 8.9463918891349438007e-12j), tol=ATOL) + assert ae(v.real, 2.3255552781051330088e-11, tol=PTOL) + assert ae(v.imag, -8.9463918891349438007e-12, tol=PTOL) + v = fp.e1((30.0 - 120.0j)) + assert ae(v, (-2.7068919097124652332e-16 + 7.0477762411705130239e-16j), tol=ATOL) + assert ae(v.real, -2.7068919097124652332e-16, tol=PTOL) + assert ae(v.imag, 7.0477762411705130239e-16, tol=PTOL) + v = fp.e1((40.0 - 160.0j)) + assert ae(v, (-1.1695597827678024687e-20 - 2.2907401455645736661e-20j), tol=ATOL) + assert ae(v.real, -1.1695597827678024687e-20, tol=PTOL) + assert ae(v.imag, -2.2907401455645736661e-20, tol=PTOL) + v = fp.e1((50.0 - 200.0j)) + assert ae(v, (9.0323746914410162531e-25 + 2.3950601790033530935e-25j), tol=ATOL) + assert ae(v.real, 9.0323746914410162531e-25, tol=PTOL) + assert ae(v.imag, 2.3950601790033530935e-25, tol=PTOL) + v = fp.e1((80.0 - 320.0j)) + assert ae(v, (3.4819106748728063576e-38 + 4.215653005615772724e-38j), tol=ATOL) + assert ae(v.real, 3.4819106748728063576e-38, tol=PTOL) + assert ae(v.imag, 4.215653005615772724e-38, tol=PTOL) + v = fp.e1((1.1641532182693481445e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (21.950067703413105017 + 0.7853981632810329878j), tol=ATOL) + assert ae(v.real, 21.950067703413105017, tol=PTOL) + assert ae(v.imag, 0.7853981632810329878, tol=PTOL) + v = fp.e1((0.25 - 0.25j)) + assert ae(v, (0.71092525792923287894 + 0.56491812441304194711j), tol=ATOL) + assert ae(v.real, 0.71092525792923287894, tol=PTOL) + assert ae(v.imag, 0.56491812441304194711, tol=PTOL) + v = fp.e1((1.0 - 1.0j)) + assert ae(v, (0.00028162445198141832551 + 0.17932453503935894015j), tol=ATOL) + assert ae(v.real, 0.00028162445198141832551, tol=PTOL) + assert ae(v.imag, 0.17932453503935894015, tol=PTOL) + v = fp.e1((2.0 - 2.0j)) + assert ae(v, (-0.033767089606562004246 + 0.018599414169750541925j), tol=ATOL) + assert ae(v.real, -0.033767089606562004246, tol=PTOL) + assert ae(v.imag, 0.018599414169750541925, tol=PTOL) + v = fp.e1((5.0 - 5.0j)) + assert ae(v, (0.0007266506660356393891 - 0.00047102780163522245054j), tol=ATOL) + assert ae(v.real, 0.0007266506660356393891, tol=PTOL) + assert ae(v.imag, -0.00047102780163522245054, tol=PTOL) + v = fp.e1((20.0 - 20.0j)) + assert ae(v, (-2.3824537449367396579e-11 + 6.6969873156525615158e-11j), tol=ATOL) + assert ae(v.real, -2.3824537449367396579e-11, tol=PTOL) + assert ae(v.imag, 6.6969873156525615158e-11, tol=PTOL) + v = fp.e1((30.0 - 30.0j)) + assert ae(v, (1.7316045841744061617e-15 - 1.3065678019487308689e-15j), tol=ATOL) + assert ae(v.real, 1.7316045841744061617e-15, tol=PTOL) + assert ae(v.imag, -1.3065678019487308689e-15, tol=PTOL) + v = fp.e1((40.0 - 40.0j)) + assert ae(v, (-7.4001043002899232182e-20 + 4.991847855336816304e-21j), tol=ATOL) + assert ae(v.real, -7.4001043002899232182e-20, tol=PTOL) + assert ae(v.imag, 4.991847855336816304e-21, tol=PTOL) + v = fp.e1((50.0 - 50.0j)) + assert ae(v, (2.3566128324644641219e-24 + 1.3188326726201614778e-24j), tol=ATOL) + assert ae(v.real, 2.3566128324644641219e-24, tol=PTOL) + assert ae(v.imag, 1.3188326726201614778e-24, tol=PTOL) + v = fp.e1((80.0 - 80.0j)) + assert ae(v, (9.8279750572186526673e-38 - 1.243952841288868831e-37j), tol=ATOL) + assert ae(v.real, 9.8279750572186526673e-38, tol=PTOL) + assert ae(v.imag, -1.243952841288868831e-37, tol=PTOL) + v = fp.e1((4.6566128730773925781e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (20.880034622014215597 + 0.24497866301044883237j), tol=ATOL) + assert ae(v.real, 20.880034622014215597, tol=PTOL) + assert ae(v.imag, 0.24497866301044883237, tol=PTOL) + v = fp.e1((1.0 - 0.25j)) + assert ae(v, (0.19731063945004229095 + 0.087366045774299963672j), tol=ATOL) + assert ae(v.real, 0.19731063945004229095, tol=PTOL) + assert ae(v.imag, 0.087366045774299963672, tol=PTOL) + v = fp.e1((4.0 - 1.0j)) + assert ae(v, (0.0013106173980145506944 + 0.0034542480199350626699j), tol=ATOL) + assert ae(v.real, 0.0013106173980145506944, tol=PTOL) + assert ae(v.imag, 0.0034542480199350626699, tol=PTOL) + v = fp.e1((8.0 - 2.0j)) + assert ae(v, (-0.000022278049065270225945 + 0.000029191940456521555288j), tol=ATOL) + assert ae(v.real, -0.000022278049065270225945, tol=PTOL) + assert ae(v.imag, 0.000029191940456521555288, tol=PTOL) + v = fp.e1((20.0 - 5.0j)) + assert ae(v, (4.7711374515765346894e-11 - 8.2902652405126947359e-11j), tol=ATOL) + assert ae(v.real, 4.7711374515765346894e-11, tol=PTOL) + assert ae(v.imag, -8.2902652405126947359e-11, tol=PTOL) + v = fp.e1((80.0 - 20.0j)) + assert ae(v, (3.8353473865788235787e-38 + 2.129247592349605139e-37j), tol=ATOL) + assert ae(v.real, 3.8353473865788235787e-38, tol=PTOL) + assert ae(v.imag, 2.129247592349605139e-37, tol=PTOL) + v = fp.e1((120.0 - 30.0j)) + assert ae(v, (2.3836002337480334716e-55 - 5.6704043587126198306e-55j), tol=ATOL) + assert ae(v.real, 2.3836002337480334716e-55, tol=PTOL) + assert ae(v.imag, -5.6704043587126198306e-55, tol=PTOL) + v = fp.e1((160.0 - 40.0j)) + assert ae(v, (-1.6238022898654510661e-72 + 1.104172355572287367e-72j), tol=ATOL) + assert ae(v.real, -1.6238022898654510661e-72, tol=PTOL) + assert ae(v.imag, 1.104172355572287367e-72, tol=PTOL) + v = fp.e1((200.0 - 50.0j)) + assert ae(v, (6.6800061461666228487e-90 - 1.4473816083541016115e-91j), tol=ATOL) + assert ae(v.real, 6.6800061461666228487e-90, tol=PTOL) + assert ae(v.imag, -1.4473816083541016115e-91, tol=PTOL) + v = fp.e1((320.0 - 80.0j)) + assert ae(v, (4.2737871527778786157e-143 - 3.1789935525785660314e-142j), tol=ATOL) + assert ae(v.real, 4.2737871527778786157e-143, tol=PTOL) + assert ae(v.imag, -3.1789935525785660314e-142, tol=PTOL) + v = fp.ei(1.1641532182693481445e-10) + assert ae(v, -22.296641293460247028, tol=ATOL) + assert type(v) is float + v = fp.ei(0.25) + assert ae(v, -0.54254326466191372953, tol=ATOL) + assert type(v) is float + v = fp.ei(1.0) + assert ae(v, 1.8951178163559367555, tol=ATOL) + assert type(v) is float + v = fp.ei(2.0) + assert ae(v, 4.9542343560018901634, tol=ATOL) + assert type(v) is float + v = fp.ei(5.0) + assert ae(v, 40.185275355803177455, tol=ATOL) + assert type(v) is float + v = fp.ei(20.0) + assert ae(v, 25615652.66405658882, tol=ATOL) + assert type(v) is float + v = fp.ei(30.0) + assert ae(v, 368973209407.27419706, tol=ATOL) + assert type(v) is float + v = fp.ei(40.0) + assert ae(v, 6039718263611241.5784, tol=ATOL) + assert type(v) is float + v = fp.ei(50.0) + assert ae(v, 1.0585636897131690963e+20, tol=ATOL) + assert type(v) is float + v = fp.ei(80.0) + assert ae(v, 7.0146000049047999696e+32, tol=ATOL) + assert type(v) is float + v = fp.ei((1.1641532182693481445e-10 + 0.0j)) + assert ae(v, (-22.296641293460247028 + 0.0j), tol=ATOL) + assert ae(v.real, -22.296641293460247028, tol=PTOL) + assert v.imag == 0 + v = fp.ei((0.25 + 0.0j)) + assert ae(v, (-0.54254326466191372953 + 0.0j), tol=ATOL) + assert ae(v.real, -0.54254326466191372953, tol=PTOL) + assert v.imag == 0 + v = fp.ei((1.0 + 0.0j)) + assert ae(v, (1.8951178163559367555 + 0.0j), tol=ATOL) + assert ae(v.real, 1.8951178163559367555, tol=PTOL) + assert v.imag == 0 + v = fp.ei((2.0 + 0.0j)) + assert ae(v, (4.9542343560018901634 + 0.0j), tol=ATOL) + assert ae(v.real, 4.9542343560018901634, tol=PTOL) + assert v.imag == 0 + v = fp.ei((5.0 + 0.0j)) + assert ae(v, (40.185275355803177455 + 0.0j), tol=ATOL) + assert ae(v.real, 40.185275355803177455, tol=PTOL) + assert v.imag == 0 + v = fp.ei((20.0 + 0.0j)) + assert ae(v, (25615652.66405658882 + 0.0j), tol=ATOL) + assert ae(v.real, 25615652.66405658882, tol=PTOL) + assert v.imag == 0 + v = fp.ei((30.0 + 0.0j)) + assert ae(v, (368973209407.27419706 + 0.0j), tol=ATOL) + assert ae(v.real, 368973209407.27419706, tol=PTOL) + assert v.imag == 0 + v = fp.ei((40.0 + 0.0j)) + assert ae(v, (6039718263611241.5784 + 0.0j), tol=ATOL) + assert ae(v.real, 6039718263611241.5784, tol=PTOL) + assert v.imag == 0 + v = fp.ei((50.0 + 0.0j)) + assert ae(v, (1.0585636897131690963e+20 + 0.0j), tol=ATOL) + assert ae(v.real, 1.0585636897131690963e+20, tol=PTOL) + assert v.imag == 0 + v = fp.ei((80.0 + 0.0j)) + assert ae(v, (7.0146000049047999696e+32 + 0.0j), tol=ATOL) + assert ae(v.real, 7.0146000049047999696e+32, tol=PTOL) + assert v.imag == 0 + v = fp.ei((4.6566128730773925781e-10 + 1.1641532182693481445e-10j)) + assert ae(v, (-20.880034621082893023 + 0.24497866324327947603j), tol=ATOL) + assert ae(v.real, -20.880034621082893023, tol=PTOL) + assert ae(v.imag, 0.24497866324327947603, tol=PTOL) + v = fp.ei((1.0 + 0.25j)) + assert ae(v, (1.8942716983721074932 + 0.67268237088273915854j), tol=ATOL) + assert ae(v.real, 1.8942716983721074932, tol=PTOL) + assert ae(v.imag, 0.67268237088273915854, tol=PTOL) + v = fp.ei((4.0 + 1.0j)) + assert ae(v, (14.806699492675420438 + 12.280015176673582616j), tol=ATOL) + assert ae(v.real, 14.806699492675420438, tol=PTOL) + assert ae(v.imag, 12.280015176673582616, tol=PTOL) + v = fp.ei((8.0 + 2.0j)) + assert ae(v, (-54.633252667426386294 + 416.34477429173650012j), tol=ATOL) + assert ae(v.real, -54.633252667426386294, tol=PTOL) + assert ae(v.imag, 416.34477429173650012, tol=PTOL) + v = fp.ei((20.0 + 5.0j)) + assert ae(v, (711836.97165402624643 - 24745247.798103247366j), tol=ATOL) + assert ae(v.real, 711836.97165402624643, tol=PTOL) + assert ae(v.imag, -24745247.798103247366, tol=PTOL) + v = fp.ei((80.0 + 20.0j)) + assert ae(v, (4.2139911108612653091e+32 + 5.3367124741918251637e+32j), tol=ATOL) + assert ae(v.real, 4.2139911108612653091e+32, tol=PTOL) + assert ae(v.imag, 5.3367124741918251637e+32, tol=PTOL) + v = fp.ei((120.0 + 30.0j)) + assert ae(v, (-9.7760616203707508892e+48 - 1.058257682317195792e+50j), tol=ATOL) + assert ae(v.real, -9.7760616203707508892e+48, tol=PTOL) + assert ae(v.imag, -1.058257682317195792e+50, tol=PTOL) + v = fp.ei((160.0 + 40.0j)) + assert ae(v, (-8.7065541466623638861e+66 + 1.6577106725141739889e+67j), tol=ATOL) + assert ae(v.real, -8.7065541466623638861e+66, tol=PTOL) + assert ae(v.imag, 1.6577106725141739889e+67, tol=PTOL) + v = fp.ei((200.0 + 50.0j)) + assert ae(v, (3.070744996327018106e+84 - 1.7243244846769415903e+84j), tol=ATOL) + assert ae(v.real, 3.070744996327018106e+84, tol=PTOL) + assert ae(v.imag, -1.7243244846769415903e+84, tol=PTOL) + v = fp.ei((320.0 + 80.0j)) + assert ae(v, (-9.9960598637998647276e+135 - 2.6855081527595608863e+136j), tol=ATOL) + assert ae(v.real, -9.9960598637998647276e+135, tol=PTOL) + assert ae(v.imag, -2.6855081527595608863e+136, tol=PTOL) + v = fp.ei((1.1641532182693481445e-10 + 1.1641532182693481445e-10j)) + assert ae(v, (-21.950067703180274374 + 0.78539816351386363145j), tol=ATOL) + assert ae(v.real, -21.950067703180274374, tol=PTOL) + assert ae(v.imag, 0.78539816351386363145, tol=PTOL) + v = fp.ei((0.25 + 0.25j)) + assert ae(v, (-0.21441047326710323254 + 1.0683772981589995996j), tol=ATOL) + assert ae(v.real, -0.21441047326710323254, tol=PTOL) + assert ae(v.imag, 1.0683772981589995996, tol=PTOL) + v = fp.ei((1.0 + 1.0j)) + assert ae(v, (1.7646259855638540684 + 2.3877698515105224193j), tol=ATOL) + assert ae(v.real, 1.7646259855638540684, tol=PTOL) + assert ae(v.imag, 2.3877698515105224193, tol=PTOL) + v = fp.ei((2.0 + 2.0j)) + assert ae(v, (1.8920781621855474089 + 5.3169624378326579621j), tol=ATOL) + assert ae(v.real, 1.8920781621855474089, tol=PTOL) + assert ae(v.imag, 5.3169624378326579621, tol=PTOL) + v = fp.ei((5.0 + 5.0j)) + assert ae(v, (-13.470936071475245856 - 15.322492395731230968j), tol=ATOL) + assert ae(v.real, -13.470936071475245856, tol=PTOL) + assert ae(v.imag, -15.322492395731230968, tol=PTOL) + v = fp.ei((20.0 + 20.0j)) + assert ae(v, (16589317.398788971896 + 5831705.4712368307104j), tol=ATOL) + assert ae(v.real, 16589317.398788971896, tol=PTOL) + assert ae(v.imag, 5831705.4712368307104, tol=PTOL) + v = fp.ei((30.0 + 30.0j)) + assert ae(v, (-154596484273.69322527 - 204179357834.2723043j), tol=ATOL) + assert ae(v.real, -154596484273.69322527, tol=PTOL) + assert ae(v.imag, -204179357834.2723043, tol=PTOL) + v = fp.ei((40.0 + 40.0j)) + assert ae(v, (287512180321448.45408 + 4203502407932318.1156j), tol=ATOL) + assert ae(v.real, 287512180321448.45408, tol=PTOL) + assert ae(v.imag, 4203502407932318.1156, tol=PTOL) + v = fp.ei((50.0 + 50.0j)) + assert ae(v, (36128528616649268826.0 - 64648801861338741960.0j), tol=ATOL) + assert ae(v.real, 36128528616649268826.0, tol=PTOL) + assert ae(v.imag, -64648801861338741960.0, tol=PTOL) + v = fp.ei((80.0 + 80.0j)) + assert ae(v, (-3.8674816337930010217e+32 - 3.0540709639658071041e+32j), tol=ATOL) + assert ae(v.real, -3.8674816337930010217e+32, tol=PTOL) + assert ae(v.imag, -3.0540709639658071041e+32, tol=PTOL) + v = fp.ei((1.1641532182693481445e-10 + 4.6566128730773925781e-10j)) + assert ae(v, (-20.880034621432138988 + 1.3258176641336937524j), tol=ATOL) + assert ae(v.real, -20.880034621432138988, tol=PTOL) + assert ae(v.imag, 1.3258176641336937524, tol=PTOL) + v = fp.ei((0.25 + 1.0j)) + assert ae(v, (0.59066621214766308594 + 2.3968481059377428687j), tol=ATOL) + assert ae(v.real, 0.59066621214766308594, tol=PTOL) + assert ae(v.imag, 2.3968481059377428687, tol=PTOL) + v = fp.ei((1.0 + 4.0j)) + assert ae(v, (-0.49739047283060471093 + 3.5570287076301818702j), tol=ATOL) + assert ae(v.real, -0.49739047283060471093, tol=PTOL) + assert ae(v.imag, 3.5570287076301818702, tol=PTOL) + v = fp.ei((2.0 + 8.0j)) + assert ae(v, (0.8705211147733730969 + 3.3825859385758486351j), tol=ATOL) + assert ae(v.real, 0.8705211147733730969, tol=PTOL) + assert ae(v.imag, 3.3825859385758486351, tol=PTOL) + v = fp.ei((5.0 + 20.0j)) + assert ae(v, (7.0789514293925893007 + 1.5313749363937141849j), tol=ATOL) + assert ae(v.real, 7.0789514293925893007, tol=PTOL) + assert ae(v.imag, 1.5313749363937141849, tol=PTOL) + v = fp.ei((20.0 + 80.0j)) + assert ae(v, (-5855431.4907298084434 - 720917.79156143806727j), tol=ATOL) + assert ae(v.real, -5855431.4907298084434, tol=PTOL) + assert ae(v.imag, -720917.79156143806727, tol=PTOL) + v = fp.ei((30.0 + 120.0j)) + assert ae(v, (65402491644.703470747 - 56697658396.51586764j), tol=ATOL) + assert ae(v.real, 65402491644.703470747, tol=PTOL) + assert ae(v.imag, -56697658396.51586764, tol=PTOL) + v = fp.ei((40.0 + 160.0j)) + assert ae(v, (-25504929379604.776769 + 1429035198630576.3879j), tol=ATOL) + assert ae(v.real, -25504929379604.776769, tol=PTOL) + assert ae(v.imag, 1429035198630576.3879, tol=PTOL) + v = fp.ei((50.0 + 200.0j)) + assert ae(v, (-18437746526988116954.0 - 17146362239046152342.0j), tol=ATOL) + assert ae(v.real, -18437746526988116954.0, tol=PTOL) + assert ae(v.imag, -17146362239046152342.0, tol=PTOL) + v = fp.ei((80.0 + 320.0j)) + assert ae(v, (-3.3464697299634526706e+31 - 1.6473152633843023919e+32j), tol=ATOL) + assert ae(v.real, -3.3464697299634526706e+31, tol=PTOL) + assert ae(v.imag, -1.6473152633843023919e+32, tol=PTOL) + v = fp.ei((0.0 + 1.1641532182693481445e-10j)) + assert ae(v, (-22.29664129357666235 + 1.5707963269113119411j), tol=ATOL) + assert ae(v.real, -22.29664129357666235, tol=PTOL) + assert ae(v.imag, 1.5707963269113119411, tol=PTOL) + v = fp.ei((0.0 + 0.25j)) + assert ae(v, (-0.82466306258094565309 + 1.8199298971146537833j), tol=ATOL) + assert ae(v.real, -0.82466306258094565309, tol=PTOL) + assert ae(v.imag, 1.8199298971146537833, tol=PTOL) + v = fp.ei((0.0 + 1.0j)) + assert ae(v, (0.33740392290096813466 + 2.5168793971620796342j), tol=ATOL) + assert ae(v.real, 0.33740392290096813466, tol=PTOL) + assert ae(v.imag, 2.5168793971620796342, tol=PTOL) + v = fp.ei((0.0 + 2.0j)) + assert ae(v, (0.4229808287748649957 + 3.1762093035975914678j), tol=ATOL) + assert ae(v.real, 0.4229808287748649957, tol=PTOL) + assert ae(v.imag, 3.1762093035975914678, tol=PTOL) + v = fp.ei((0.0 + 5.0j)) + assert ae(v, (-0.19002974965664387862 + 3.1207275717395707565j), tol=ATOL) + assert ae(v.real, -0.19002974965664387862, tol=PTOL) + assert ae(v.imag, 3.1207275717395707565, tol=PTOL) + v = fp.ei((0.0 + 20.0j)) + assert ae(v, (0.04441982084535331654 + 3.1190380278383364594j), tol=ATOL) + assert ae(v.real, 0.04441982084535331654, tol=PTOL) + assert ae(v.imag, 3.1190380278383364594, tol=PTOL) + v = fp.ei((0.0 + 30.0j)) + assert ae(v, (-0.033032417282071143779 + 3.1375528668252477302j), tol=ATOL) + assert ae(v.real, -0.033032417282071143779, tol=PTOL) + assert ae(v.imag, 3.1375528668252477302, tol=PTOL) + v = fp.ei((0.0 + 40.0j)) + assert ae(v, (0.019020007896208766962 + 3.157781446149681126j), tol=ATOL) + assert ae(v.real, 0.019020007896208766962, tol=PTOL) + assert ae(v.imag, 3.157781446149681126, tol=PTOL) + v = fp.ei((0.0 + 50.0j)) + assert ae(v, (-0.0056283863241163054402 + 3.122413399280832514j), tol=ATOL) + assert ae(v.real, -0.0056283863241163054402, tol=PTOL) + assert ae(v.imag, 3.122413399280832514, tol=PTOL) + v = fp.ei((0.0 + 80.0j)) + assert ae(v, (-0.012402501155070958192 + 3.1431272137073839346j), tol=ATOL) + assert ae(v.real, -0.012402501155070958192, tol=PTOL) + assert ae(v.imag, 3.1431272137073839346, tol=PTOL) + v = fp.ei((-1.1641532182693481445e-10 + 4.6566128730773925781e-10j)) + assert ae(v, (-20.880034621664969632 + 1.8157749903874220607j), tol=ATOL) + assert ae(v.real, -20.880034621664969632, tol=PTOL) + assert ae(v.imag, 1.8157749903874220607, tol=PTOL) + v = fp.ei((-0.25 + 1.0j)) + assert ae(v, (0.16868306393667788761 + 2.6557914649950505414j), tol=ATOL) + assert ae(v.real, 0.16868306393667788761, tol=PTOL) + assert ae(v.imag, 2.6557914649950505414, tol=PTOL) + v = fp.ei((-1.0 + 4.0j)) + assert ae(v, (-0.03373591813926547318 + 3.2151161058308770603j), tol=ATOL) + assert ae(v.real, -0.03373591813926547318, tol=PTOL) + assert ae(v.imag, 3.2151161058308770603, tol=PTOL) + v = fp.ei((-2.0 + 8.0j)) + assert ae(v, (0.015392833434733785143 + 3.1384179414340326969j), tol=ATOL) + assert ae(v.real, 0.015392833434733785143, tol=PTOL) + assert ae(v.imag, 3.1384179414340326969, tol=PTOL) + v = fp.ei((-5.0 + 20.0j)) + assert ae(v, (0.00024419662286542966525 + 3.1413825703601317109j), tol=ATOL) + assert ae(v.real, 0.00024419662286542966525, tol=PTOL) + assert ae(v.imag, 3.1413825703601317109, tol=PTOL) + v = fp.ei((-20.0 + 80.0j)) + assert ae(v, (-2.3255552781051330088e-11 + 3.1415926535987396304j), tol=ATOL) + assert ae(v.real, -2.3255552781051330088e-11, tol=PTOL) + assert ae(v.imag, 3.1415926535987396304, tol=PTOL) + v = fp.ei((-30.0 + 120.0j)) + assert ae(v, (2.7068919097124652332e-16 + 3.1415926535897925337j), tol=ATOL) + assert ae(v.real, 2.7068919097124652332e-16, tol=PTOL) + assert ae(v.imag, 3.1415926535897925337, tol=PTOL) + v = fp.ei((-40.0 + 160.0j)) + assert ae(v, (1.1695597827678024687e-20 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 1.1695597827678024687e-20, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei((-50.0 + 200.0j)) + assert ae(v, (-9.0323746914410162531e-25 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -9.0323746914410162531e-25, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei((-80.0 + 320.0j)) + assert ae(v, (-3.4819106748728063576e-38 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -3.4819106748728063576e-38, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei((-4.6566128730773925781e-10 + 1.1641532182693481445e-10j)) + assert ae(v, (-20.880034622014215597 + 2.8966139905793444061j), tol=ATOL) + assert ae(v.real, -20.880034622014215597, tol=PTOL) + assert ae(v.imag, 2.8966139905793444061, tol=PTOL) + v = fp.ei((-1.0 + 0.25j)) + assert ae(v, (-0.19731063945004229095 + 3.0542266078154932748j), tol=ATOL) + assert ae(v.real, -0.19731063945004229095, tol=PTOL) + assert ae(v.imag, 3.0542266078154932748, tol=PTOL) + v = fp.ei((-4.0 + 1.0j)) + assert ae(v, (-0.0013106173980145506944 + 3.1381384055698581758j), tol=ATOL) + assert ae(v.real, -0.0013106173980145506944, tol=PTOL) + assert ae(v.imag, 3.1381384055698581758, tol=PTOL) + v = fp.ei((-8.0 + 2.0j)) + assert ae(v, (0.000022278049065270225945 + 3.1415634616493367169j), tol=ATOL) + assert ae(v.real, 0.000022278049065270225945, tol=PTOL) + assert ae(v.imag, 3.1415634616493367169, tol=PTOL) + v = fp.ei((-20.0 + 5.0j)) + assert ae(v, (-4.7711374515765346894e-11 + 3.1415926536726958909j), tol=ATOL) + assert ae(v.real, -4.7711374515765346894e-11, tol=PTOL) + assert ae(v.imag, 3.1415926536726958909, tol=PTOL) + v = fp.ei((-80.0 + 20.0j)) + assert ae(v, (-3.8353473865788235787e-38 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -3.8353473865788235787e-38, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei((-120.0 + 30.0j)) + assert ae(v, (-2.3836002337480334716e-55 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -2.3836002337480334716e-55, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei((-160.0 + 40.0j)) + assert ae(v, (1.6238022898654510661e-72 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 1.6238022898654510661e-72, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei((-200.0 + 50.0j)) + assert ae(v, (-6.6800061461666228487e-90 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -6.6800061461666228487e-90, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei((-320.0 + 80.0j)) + assert ae(v, (-4.2737871527778786157e-143 + 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -4.2737871527778786157e-143, tol=PTOL) + assert ae(v.imag, 3.1415926535897932385, tol=PTOL) + v = fp.ei(-1.1641532182693481445e-10) + assert ae(v, -22.296641293693077672, tol=ATOL) + assert type(v) is float + v = fp.ei(-0.25) + assert ae(v, -1.0442826344437381945, tol=ATOL) + assert type(v) is float + v = fp.ei(-1.0) + assert ae(v, -0.21938393439552027368, tol=ATOL) + assert type(v) is float + v = fp.ei(-2.0) + assert ae(v, -0.048900510708061119567, tol=ATOL) + assert type(v) is float + v = fp.ei(-5.0) + assert ae(v, -0.0011482955912753257973, tol=ATOL) + assert type(v) is float + v = fp.ei(-20.0) + assert ae(v, -9.8355252906498816904e-11, tol=ATOL) + assert type(v) is float + v = fp.ei(-30.0) + assert ae(v, -3.0215520106888125448e-15, tol=ATOL) + assert type(v) is float + v = fp.ei(-40.0) + assert ae(v, -1.0367732614516569722e-19, tol=ATOL) + assert type(v) is float + v = fp.ei(-50.0) + assert ae(v, -3.7832640295504590187e-24, tol=ATOL) + assert type(v) is float + v = fp.ei(-80.0) + assert ae(v, -2.2285432586884729112e-37, tol=ATOL) + assert type(v) is float + v = fp.ei((-1.1641532182693481445e-10 + 0.0j)) + assert ae(v, (-22.296641293693077672 + 0.0j), tol=ATOL) + assert ae(v.real, -22.296641293693077672, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-0.25 + 0.0j)) + assert ae(v, (-1.0442826344437381945 + 0.0j), tol=ATOL) + assert ae(v.real, -1.0442826344437381945, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-1.0 + 0.0j)) + assert ae(v, (-0.21938393439552027368 + 0.0j), tol=ATOL) + assert ae(v.real, -0.21938393439552027368, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-2.0 + 0.0j)) + assert ae(v, (-0.048900510708061119567 + 0.0j), tol=ATOL) + assert ae(v.real, -0.048900510708061119567, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-5.0 + 0.0j)) + assert ae(v, (-0.0011482955912753257973 + 0.0j), tol=ATOL) + assert ae(v.real, -0.0011482955912753257973, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-20.0 + 0.0j)) + assert ae(v, (-9.8355252906498816904e-11 + 0.0j), tol=ATOL) + assert ae(v.real, -9.8355252906498816904e-11, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-30.0 + 0.0j)) + assert ae(v, (-3.0215520106888125448e-15 + 0.0j), tol=ATOL) + assert ae(v.real, -3.0215520106888125448e-15, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-40.0 + 0.0j)) + assert ae(v, (-1.0367732614516569722e-19 + 0.0j), tol=ATOL) + assert ae(v.real, -1.0367732614516569722e-19, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-50.0 + 0.0j)) + assert ae(v, (-3.7832640295504590187e-24 + 0.0j), tol=ATOL) + assert ae(v.real, -3.7832640295504590187e-24, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-80.0 + 0.0j)) + assert ae(v, (-2.2285432586884729112e-37 + 0.0j), tol=ATOL) + assert ae(v.real, -2.2285432586884729112e-37, tol=PTOL) + assert v.imag == 0 + v = fp.ei((-4.6566128730773925781e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (-20.880034622014215597 - 2.8966139905793444061j), tol=ATOL) + assert ae(v.real, -20.880034622014215597, tol=PTOL) + assert ae(v.imag, -2.8966139905793444061, tol=PTOL) + v = fp.ei((-1.0 - 0.25j)) + assert ae(v, (-0.19731063945004229095 - 3.0542266078154932748j), tol=ATOL) + assert ae(v.real, -0.19731063945004229095, tol=PTOL) + assert ae(v.imag, -3.0542266078154932748, tol=PTOL) + v = fp.ei((-4.0 - 1.0j)) + assert ae(v, (-0.0013106173980145506944 - 3.1381384055698581758j), tol=ATOL) + assert ae(v.real, -0.0013106173980145506944, tol=PTOL) + assert ae(v.imag, -3.1381384055698581758, tol=PTOL) + v = fp.ei((-8.0 - 2.0j)) + assert ae(v, (0.000022278049065270225945 - 3.1415634616493367169j), tol=ATOL) + assert ae(v.real, 0.000022278049065270225945, tol=PTOL) + assert ae(v.imag, -3.1415634616493367169, tol=PTOL) + v = fp.ei((-20.0 - 5.0j)) + assert ae(v, (-4.7711374515765346894e-11 - 3.1415926536726958909j), tol=ATOL) + assert ae(v.real, -4.7711374515765346894e-11, tol=PTOL) + assert ae(v.imag, -3.1415926536726958909, tol=PTOL) + v = fp.ei((-80.0 - 20.0j)) + assert ae(v, (-3.8353473865788235787e-38 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -3.8353473865788235787e-38, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-120.0 - 30.0j)) + assert ae(v, (-2.3836002337480334716e-55 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -2.3836002337480334716e-55, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-160.0 - 40.0j)) + assert ae(v, (1.6238022898654510661e-72 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 1.6238022898654510661e-72, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-200.0 - 50.0j)) + assert ae(v, (-6.6800061461666228487e-90 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -6.6800061461666228487e-90, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-320.0 - 80.0j)) + assert ae(v, (-4.2737871527778786157e-143 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -4.2737871527778786157e-143, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-1.1641532182693481445e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (-21.950067703413105017 - 2.3561944903087602507j), tol=ATOL) + assert ae(v.real, -21.950067703413105017, tol=PTOL) + assert ae(v.imag, -2.3561944903087602507, tol=PTOL) + v = fp.ei((-0.25 - 0.25j)) + assert ae(v, (-0.71092525792923287894 - 2.5766745291767512913j), tol=ATOL) + assert ae(v.real, -0.71092525792923287894, tol=PTOL) + assert ae(v.imag, -2.5766745291767512913, tol=PTOL) + v = fp.ei((-1.0 - 1.0j)) + assert ae(v, (-0.00028162445198141832551 - 2.9622681185504342983j), tol=ATOL) + assert ae(v.real, -0.00028162445198141832551, tol=PTOL) + assert ae(v.imag, -2.9622681185504342983, tol=PTOL) + v = fp.ei((-2.0 - 2.0j)) + assert ae(v, (0.033767089606562004246 - 3.1229932394200426965j), tol=ATOL) + assert ae(v.real, 0.033767089606562004246, tol=PTOL) + assert ae(v.imag, -3.1229932394200426965, tol=PTOL) + v = fp.ei((-5.0 - 5.0j)) + assert ae(v, (-0.0007266506660356393891 - 3.1420636813914284609j), tol=ATOL) + assert ae(v.real, -0.0007266506660356393891, tol=PTOL) + assert ae(v.imag, -3.1420636813914284609, tol=PTOL) + v = fp.ei((-20.0 - 20.0j)) + assert ae(v, (2.3824537449367396579e-11 - 3.1415926535228233653j), tol=ATOL) + assert ae(v.real, 2.3824537449367396579e-11, tol=PTOL) + assert ae(v.imag, -3.1415926535228233653, tol=PTOL) + v = fp.ei((-30.0 - 30.0j)) + assert ae(v, (-1.7316045841744061617e-15 - 3.141592653589794545j), tol=ATOL) + assert ae(v.real, -1.7316045841744061617e-15, tol=PTOL) + assert ae(v.imag, -3.141592653589794545, tol=PTOL) + v = fp.ei((-40.0 - 40.0j)) + assert ae(v, (7.4001043002899232182e-20 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 7.4001043002899232182e-20, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-50.0 - 50.0j)) + assert ae(v, (-2.3566128324644641219e-24 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -2.3566128324644641219e-24, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-80.0 - 80.0j)) + assert ae(v, (-9.8279750572186526673e-38 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -9.8279750572186526673e-38, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-1.1641532182693481445e-10 - 4.6566128730773925781e-10j)) + assert ae(v, (-20.880034621664969632 - 1.8157749903874220607j), tol=ATOL) + assert ae(v.real, -20.880034621664969632, tol=PTOL) + assert ae(v.imag, -1.8157749903874220607, tol=PTOL) + v = fp.ei((-0.25 - 1.0j)) + assert ae(v, (0.16868306393667788761 - 2.6557914649950505414j), tol=ATOL) + assert ae(v.real, 0.16868306393667788761, tol=PTOL) + assert ae(v.imag, -2.6557914649950505414, tol=PTOL) + v = fp.ei((-1.0 - 4.0j)) + assert ae(v, (-0.03373591813926547318 - 3.2151161058308770603j), tol=ATOL) + assert ae(v.real, -0.03373591813926547318, tol=PTOL) + assert ae(v.imag, -3.2151161058308770603, tol=PTOL) + v = fp.ei((-2.0 - 8.0j)) + assert ae(v, (0.015392833434733785143 - 3.1384179414340326969j), tol=ATOL) + assert ae(v.real, 0.015392833434733785143, tol=PTOL) + assert ae(v.imag, -3.1384179414340326969, tol=PTOL) + v = fp.ei((-5.0 - 20.0j)) + assert ae(v, (0.00024419662286542966525 - 3.1413825703601317109j), tol=ATOL) + assert ae(v.real, 0.00024419662286542966525, tol=PTOL) + assert ae(v.imag, -3.1413825703601317109, tol=PTOL) + v = fp.ei((-20.0 - 80.0j)) + assert ae(v, (-2.3255552781051330088e-11 - 3.1415926535987396304j), tol=ATOL) + assert ae(v.real, -2.3255552781051330088e-11, tol=PTOL) + assert ae(v.imag, -3.1415926535987396304, tol=PTOL) + v = fp.ei((-30.0 - 120.0j)) + assert ae(v, (2.7068919097124652332e-16 - 3.1415926535897925337j), tol=ATOL) + assert ae(v.real, 2.7068919097124652332e-16, tol=PTOL) + assert ae(v.imag, -3.1415926535897925337, tol=PTOL) + v = fp.ei((-40.0 - 160.0j)) + assert ae(v, (1.1695597827678024687e-20 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, 1.1695597827678024687e-20, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-50.0 - 200.0j)) + assert ae(v, (-9.0323746914410162531e-25 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -9.0323746914410162531e-25, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((-80.0 - 320.0j)) + assert ae(v, (-3.4819106748728063576e-38 - 3.1415926535897932385j), tol=ATOL) + assert ae(v.real, -3.4819106748728063576e-38, tol=PTOL) + assert ae(v.imag, -3.1415926535897932385, tol=PTOL) + v = fp.ei((0.0 - 1.1641532182693481445e-10j)) + assert ae(v, (-22.29664129357666235 - 1.5707963269113119411j), tol=ATOL) + assert ae(v.real, -22.29664129357666235, tol=PTOL) + assert ae(v.imag, -1.5707963269113119411, tol=PTOL) + v = fp.ei((0.0 - 0.25j)) + assert ae(v, (-0.82466306258094565309 - 1.8199298971146537833j), tol=ATOL) + assert ae(v.real, -0.82466306258094565309, tol=PTOL) + assert ae(v.imag, -1.8199298971146537833, tol=PTOL) + v = fp.ei((0.0 - 1.0j)) + assert ae(v, (0.33740392290096813466 - 2.5168793971620796342j), tol=ATOL) + assert ae(v.real, 0.33740392290096813466, tol=PTOL) + assert ae(v.imag, -2.5168793971620796342, tol=PTOL) + v = fp.ei((0.0 - 2.0j)) + assert ae(v, (0.4229808287748649957 - 3.1762093035975914678j), tol=ATOL) + assert ae(v.real, 0.4229808287748649957, tol=PTOL) + assert ae(v.imag, -3.1762093035975914678, tol=PTOL) + v = fp.ei((0.0 - 5.0j)) + assert ae(v, (-0.19002974965664387862 - 3.1207275717395707565j), tol=ATOL) + assert ae(v.real, -0.19002974965664387862, tol=PTOL) + assert ae(v.imag, -3.1207275717395707565, tol=PTOL) + v = fp.ei((0.0 - 20.0j)) + assert ae(v, (0.04441982084535331654 - 3.1190380278383364594j), tol=ATOL) + assert ae(v.real, 0.04441982084535331654, tol=PTOL) + assert ae(v.imag, -3.1190380278383364594, tol=PTOL) + v = fp.ei((0.0 - 30.0j)) + assert ae(v, (-0.033032417282071143779 - 3.1375528668252477302j), tol=ATOL) + assert ae(v.real, -0.033032417282071143779, tol=PTOL) + assert ae(v.imag, -3.1375528668252477302, tol=PTOL) + v = fp.ei((0.0 - 40.0j)) + assert ae(v, (0.019020007896208766962 - 3.157781446149681126j), tol=ATOL) + assert ae(v.real, 0.019020007896208766962, tol=PTOL) + assert ae(v.imag, -3.157781446149681126, tol=PTOL) + v = fp.ei((0.0 - 50.0j)) + assert ae(v, (-0.0056283863241163054402 - 3.122413399280832514j), tol=ATOL) + assert ae(v.real, -0.0056283863241163054402, tol=PTOL) + assert ae(v.imag, -3.122413399280832514, tol=PTOL) + v = fp.ei((0.0 - 80.0j)) + assert ae(v, (-0.012402501155070958192 - 3.1431272137073839346j), tol=ATOL) + assert ae(v.real, -0.012402501155070958192, tol=PTOL) + assert ae(v.imag, -3.1431272137073839346, tol=PTOL) + v = fp.ei((1.1641532182693481445e-10 - 4.6566128730773925781e-10j)) + assert ae(v, (-20.880034621432138988 - 1.3258176641336937524j), tol=ATOL) + assert ae(v.real, -20.880034621432138988, tol=PTOL) + assert ae(v.imag, -1.3258176641336937524, tol=PTOL) + v = fp.ei((0.25 - 1.0j)) + assert ae(v, (0.59066621214766308594 - 2.3968481059377428687j), tol=ATOL) + assert ae(v.real, 0.59066621214766308594, tol=PTOL) + assert ae(v.imag, -2.3968481059377428687, tol=PTOL) + v = fp.ei((1.0 - 4.0j)) + assert ae(v, (-0.49739047283060471093 - 3.5570287076301818702j), tol=ATOL) + assert ae(v.real, -0.49739047283060471093, tol=PTOL) + assert ae(v.imag, -3.5570287076301818702, tol=PTOL) + v = fp.ei((2.0 - 8.0j)) + assert ae(v, (0.8705211147733730969 - 3.3825859385758486351j), tol=ATOL) + assert ae(v.real, 0.8705211147733730969, tol=PTOL) + assert ae(v.imag, -3.3825859385758486351, tol=PTOL) + v = fp.ei((5.0 - 20.0j)) + assert ae(v, (7.0789514293925893007 - 1.5313749363937141849j), tol=ATOL) + assert ae(v.real, 7.0789514293925893007, tol=PTOL) + assert ae(v.imag, -1.5313749363937141849, tol=PTOL) + v = fp.ei((20.0 - 80.0j)) + assert ae(v, (-5855431.4907298084434 + 720917.79156143806727j), tol=ATOL) + assert ae(v.real, -5855431.4907298084434, tol=PTOL) + assert ae(v.imag, 720917.79156143806727, tol=PTOL) + v = fp.ei((30.0 - 120.0j)) + assert ae(v, (65402491644.703470747 + 56697658396.51586764j), tol=ATOL) + assert ae(v.real, 65402491644.703470747, tol=PTOL) + assert ae(v.imag, 56697658396.51586764, tol=PTOL) + v = fp.ei((40.0 - 160.0j)) + assert ae(v, (-25504929379604.776769 - 1429035198630576.3879j), tol=ATOL) + assert ae(v.real, -25504929379604.776769, tol=PTOL) + assert ae(v.imag, -1429035198630576.3879, tol=PTOL) + v = fp.ei((50.0 - 200.0j)) + assert ae(v, (-18437746526988116954.0 + 17146362239046152342.0j), tol=ATOL) + assert ae(v.real, -18437746526988116954.0, tol=PTOL) + assert ae(v.imag, 17146362239046152342.0, tol=PTOL) + v = fp.ei((80.0 - 320.0j)) + assert ae(v, (-3.3464697299634526706e+31 + 1.6473152633843023919e+32j), tol=ATOL) + assert ae(v.real, -3.3464697299634526706e+31, tol=PTOL) + assert ae(v.imag, 1.6473152633843023919e+32, tol=PTOL) + v = fp.ei((1.1641532182693481445e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (-21.950067703180274374 - 0.78539816351386363145j), tol=ATOL) + assert ae(v.real, -21.950067703180274374, tol=PTOL) + assert ae(v.imag, -0.78539816351386363145, tol=PTOL) + v = fp.ei((0.25 - 0.25j)) + assert ae(v, (-0.21441047326710323254 - 1.0683772981589995996j), tol=ATOL) + assert ae(v.real, -0.21441047326710323254, tol=PTOL) + assert ae(v.imag, -1.0683772981589995996, tol=PTOL) + v = fp.ei((1.0 - 1.0j)) + assert ae(v, (1.7646259855638540684 - 2.3877698515105224193j), tol=ATOL) + assert ae(v.real, 1.7646259855638540684, tol=PTOL) + assert ae(v.imag, -2.3877698515105224193, tol=PTOL) + v = fp.ei((2.0 - 2.0j)) + assert ae(v, (1.8920781621855474089 - 5.3169624378326579621j), tol=ATOL) + assert ae(v.real, 1.8920781621855474089, tol=PTOL) + assert ae(v.imag, -5.3169624378326579621, tol=PTOL) + v = fp.ei((5.0 - 5.0j)) + assert ae(v, (-13.470936071475245856 + 15.322492395731230968j), tol=ATOL) + assert ae(v.real, -13.470936071475245856, tol=PTOL) + assert ae(v.imag, 15.322492395731230968, tol=PTOL) + v = fp.ei((20.0 - 20.0j)) + assert ae(v, (16589317.398788971896 - 5831705.4712368307104j), tol=ATOL) + assert ae(v.real, 16589317.398788971896, tol=PTOL) + assert ae(v.imag, -5831705.4712368307104, tol=PTOL) + v = fp.ei((30.0 - 30.0j)) + assert ae(v, (-154596484273.69322527 + 204179357834.2723043j), tol=ATOL) + assert ae(v.real, -154596484273.69322527, tol=PTOL) + assert ae(v.imag, 204179357834.2723043, tol=PTOL) + v = fp.ei((40.0 - 40.0j)) + assert ae(v, (287512180321448.45408 - 4203502407932318.1156j), tol=ATOL) + assert ae(v.real, 287512180321448.45408, tol=PTOL) + assert ae(v.imag, -4203502407932318.1156, tol=PTOL) + v = fp.ei((50.0 - 50.0j)) + assert ae(v, (36128528616649268826.0 + 64648801861338741960.0j), tol=ATOL) + assert ae(v.real, 36128528616649268826.0, tol=PTOL) + assert ae(v.imag, 64648801861338741960.0, tol=PTOL) + v = fp.ei((80.0 - 80.0j)) + assert ae(v, (-3.8674816337930010217e+32 + 3.0540709639658071041e+32j), tol=ATOL) + assert ae(v.real, -3.8674816337930010217e+32, tol=PTOL) + assert ae(v.imag, 3.0540709639658071041e+32, tol=PTOL) + v = fp.ei((4.6566128730773925781e-10 - 1.1641532182693481445e-10j)) + assert ae(v, (-20.880034621082893023 - 0.24497866324327947603j), tol=ATOL) + assert ae(v.real, -20.880034621082893023, tol=PTOL) + assert ae(v.imag, -0.24497866324327947603, tol=PTOL) + v = fp.ei((1.0 - 0.25j)) + assert ae(v, (1.8942716983721074932 - 0.67268237088273915854j), tol=ATOL) + assert ae(v.real, 1.8942716983721074932, tol=PTOL) + assert ae(v.imag, -0.67268237088273915854, tol=PTOL) + v = fp.ei((4.0 - 1.0j)) + assert ae(v, (14.806699492675420438 - 12.280015176673582616j), tol=ATOL) + assert ae(v.real, 14.806699492675420438, tol=PTOL) + assert ae(v.imag, -12.280015176673582616, tol=PTOL) + v = fp.ei((8.0 - 2.0j)) + assert ae(v, (-54.633252667426386294 - 416.34477429173650012j), tol=ATOL) + assert ae(v.real, -54.633252667426386294, tol=PTOL) + assert ae(v.imag, -416.34477429173650012, tol=PTOL) + v = fp.ei((20.0 - 5.0j)) + assert ae(v, (711836.97165402624643 + 24745247.798103247366j), tol=ATOL) + assert ae(v.real, 711836.97165402624643, tol=PTOL) + assert ae(v.imag, 24745247.798103247366, tol=PTOL) + v = fp.ei((80.0 - 20.0j)) + assert ae(v, (4.2139911108612653091e+32 - 5.3367124741918251637e+32j), tol=ATOL) + assert ae(v.real, 4.2139911108612653091e+32, tol=PTOL) + assert ae(v.imag, -5.3367124741918251637e+32, tol=PTOL) + v = fp.ei((120.0 - 30.0j)) + assert ae(v, (-9.7760616203707508892e+48 + 1.058257682317195792e+50j), tol=ATOL) + assert ae(v.real, -9.7760616203707508892e+48, tol=PTOL) + assert ae(v.imag, 1.058257682317195792e+50, tol=PTOL) + v = fp.ei((160.0 - 40.0j)) + assert ae(v, (-8.7065541466623638861e+66 - 1.6577106725141739889e+67j), tol=ATOL) + assert ae(v.real, -8.7065541466623638861e+66, tol=PTOL) + assert ae(v.imag, -1.6577106725141739889e+67, tol=PTOL) + v = fp.ei((200.0 - 50.0j)) + assert ae(v, (3.070744996327018106e+84 + 1.7243244846769415903e+84j), tol=ATOL) + assert ae(v.real, 3.070744996327018106e+84, tol=PTOL) + assert ae(v.imag, 1.7243244846769415903e+84, tol=PTOL) + v = fp.ei((320.0 - 80.0j)) + assert ae(v, (-9.9960598637998647276e+135 + 2.6855081527595608863e+136j), tol=ATOL) + assert ae(v.real, -9.9960598637998647276e+135, tol=PTOL) + assert ae(v.imag, 2.6855081527595608863e+136, tol=PTOL) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_functions.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfe852f008173eb636c147abc83d71dbdd4d23a --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_functions.py @@ -0,0 +1,920 @@ +from mpmath.libmp import * +from mpmath import * +import random +import time +import math +import cmath + +def mpc_ae(a, b, eps=eps): + res = True + res = res and a.real.ae(b.real, eps) + res = res and a.imag.ae(b.imag, eps) + return res + +#---------------------------------------------------------------------------- +# Constants and functions +# + +tpi = "3.1415926535897932384626433832795028841971693993751058209749445923078\ +1640628620899862803482534211706798" +te = "2.71828182845904523536028747135266249775724709369995957496696762772407\ +663035354759457138217852516642743" +tdegree = "0.017453292519943295769236907684886127134428718885417254560971914\ +4017100911460344944368224156963450948221" +teuler = "0.5772156649015328606065120900824024310421593359399235988057672348\ +84867726777664670936947063291746749516" +tln2 = "0.693147180559945309417232121458176568075500134360255254120680009493\ +393621969694715605863326996418687542" +tln10 = "2.30258509299404568401799145468436420760110148862877297603332790096\ +757260967735248023599720508959829834" +tcatalan = "0.91596559417721901505460351493238411077414937428167213426649811\ +9621763019776254769479356512926115106249" +tkhinchin = "2.6854520010653064453097148354817956938203822939944629530511523\ +4555721885953715200280114117493184769800" +tglaisher = "1.2824271291006226368753425688697917277676889273250011920637400\ +2174040630885882646112973649195820237439420646" +tapery = "1.2020569031595942853997381615114499907649862923404988817922715553\ +4183820578631309018645587360933525815" +tphi = "1.618033988749894848204586834365638117720309179805762862135448622705\ +26046281890244970720720418939113748475" +tmertens = "0.26149721284764278375542683860869585905156664826119920619206421\ +3924924510897368209714142631434246651052" +ttwinprime = "0.660161815846869573927812110014555778432623360284733413319448\ +423335405642304495277143760031413839867912" + +def test_constants(): + for prec in [3, 7, 10, 15, 20, 37, 80, 100, 29]: + mp.dps = prec + assert pi == mpf(tpi) + assert e == mpf(te) + assert degree == mpf(tdegree) + assert euler == mpf(teuler) + assert ln2 == mpf(tln2) + assert ln10 == mpf(tln10) + assert catalan == mpf(tcatalan) + assert khinchin == mpf(tkhinchin) + assert glaisher == mpf(tglaisher) + assert phi == mpf(tphi) + if prec < 50: + assert mertens == mpf(tmertens) + assert twinprime == mpf(ttwinprime) + mp.dps = 15 + assert pi >= -1 + assert pi > 2 + assert pi > 3 + assert pi < 4 + +def test_exact_sqrts(): + for i in range(20000): + assert sqrt(mpf(i*i)) == i + random.seed(1) + for prec in [100, 300, 1000, 10000]: + mp.dps = prec + for i in range(20): + A = random.randint(10**(prec//2-2), 10**(prec//2-1)) + assert sqrt(mpf(A*A)) == A + mp.dps = 15 + for i in range(100): + for a in [1, 8, 25, 112307]: + assert sqrt(mpf((a*a, 2*i))) == mpf((a, i)) + assert sqrt(mpf((a*a, -2*i))) == mpf((a, -i)) + +def test_sqrt_rounding(): + for i in [2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15]: + i = from_int(i) + for dps in [7, 15, 83, 106, 2000]: + mp.dps = dps + a = mpf_pow_int(mpf_sqrt(i, mp.prec, round_down), 2, mp.prec, round_down) + b = mpf_pow_int(mpf_sqrt(i, mp.prec, round_up), 2, mp.prec, round_up) + assert mpf_lt(a, i) + assert mpf_gt(b, i) + random.seed(1234) + prec = 100 + for rnd in [round_down, round_nearest, round_ceiling]: + for i in range(100): + a = mpf_rand(prec) + b = mpf_mul(a, a) + assert mpf_sqrt(b, prec, rnd) == a + # Test some extreme cases + mp.dps = 100 + a = mpf(9) + 1e-90 + b = mpf(9) - 1e-90 + mp.dps = 15 + assert sqrt(a, rounding='d') == 3 + assert sqrt(a, rounding='n') == 3 + assert sqrt(a, rounding='u') > 3 + assert sqrt(b, rounding='d') < 3 + assert sqrt(b, rounding='n') == 3 + assert sqrt(b, rounding='u') == 3 + # A worst case, from the MPFR test suite + assert sqrt(mpf('7.0503726185518891')) == mpf('2.655253776675949') + +def test_float_sqrt(): + mp.dps = 15 + # These should round identically + for x in [0, 1e-7, 0.1, 0.5, 1, 2, 3, 4, 5, 0.333, 76.19]: + assert sqrt(mpf(x)) == float(x)**0.5 + assert sqrt(-1) == 1j + assert sqrt(-2).ae(cmath.sqrt(-2)) + assert sqrt(-3).ae(cmath.sqrt(-3)) + assert sqrt(-100).ae(cmath.sqrt(-100)) + assert sqrt(1j).ae(cmath.sqrt(1j)) + assert sqrt(-1j).ae(cmath.sqrt(-1j)) + assert sqrt(math.pi + math.e*1j).ae(cmath.sqrt(math.pi + math.e*1j)) + assert sqrt(math.pi - math.e*1j).ae(cmath.sqrt(math.pi - math.e*1j)) + +def test_hypot(): + assert hypot(0, 0) == 0 + assert hypot(0, 0.33) == mpf(0.33) + assert hypot(0.33, 0) == mpf(0.33) + assert hypot(-0.33, 0) == mpf(0.33) + assert hypot(3, 4) == mpf(5) + +def test_exact_cbrt(): + for i in range(0, 20000, 200): + assert cbrt(mpf(i*i*i)) == i + random.seed(1) + for prec in [100, 300, 1000, 10000]: + mp.dps = prec + A = random.randint(10**(prec//2-2), 10**(prec//2-1)) + assert cbrt(mpf(A*A*A)) == A + mp.dps = 15 + +def test_exp(): + assert exp(0) == 1 + assert exp(10000).ae(mpf('8.8068182256629215873e4342')) + assert exp(-10000).ae(mpf('1.1354838653147360985e-4343')) + a = exp(mpf((1, 8198646019315405, -53, 53))) + assert(a.bc == bitcount(a.man)) + mp.prec = 67 + a = exp(mpf((1, 1781864658064754565, -60, 61))) + assert(a.bc == bitcount(a.man)) + mp.prec = 53 + assert exp(ln2 * 10).ae(1024) + assert exp(2+2j).ae(cmath.exp(2+2j)) + +def test_issue_73(): + mp.dps = 512 + a = exp(-1) + b = exp(1) + mp.dps = 15 + assert (+a).ae(0.36787944117144233) + assert (+b).ae(2.7182818284590451) + +def test_log(): + mp.dps = 15 + assert log(1) == 0 + for x in [0.5, 1.5, 2.0, 3.0, 100, 10**50, 1e-50]: + assert log(x).ae(math.log(x)) + assert log(x, x) == 1 + assert log(1024, 2) == 10 + assert log(10**1234, 10) == 1234 + assert log(2+2j).ae(cmath.log(2+2j)) + # Accuracy near 1 + assert (log(0.6+0.8j).real*10**17).ae(2.2204460492503131) + assert (log(0.6-0.8j).real*10**17).ae(2.2204460492503131) + assert (log(0.8-0.6j).real*10**17).ae(2.2204460492503131) + assert (log(1+1e-8j).real*10**16).ae(0.5) + assert (log(1-1e-8j).real*10**16).ae(0.5) + assert (log(-1+1e-8j).real*10**16).ae(0.5) + assert (log(-1-1e-8j).real*10**16).ae(0.5) + assert (log(1j+1e-8).real*10**16).ae(0.5) + assert (log(1j-1e-8).real*10**16).ae(0.5) + assert (log(-1j+1e-8).real*10**16).ae(0.5) + assert (log(-1j-1e-8).real*10**16).ae(0.5) + assert (log(1+1e-40j).real*10**80).ae(0.5) + assert (log(1j+1e-40).real*10**80).ae(0.5) + # Huge + assert log(ldexp(1.234,10**20)).ae(log(2)*1e20) + assert log(ldexp(1.234,10**200)).ae(log(2)*1e200) + # Some special values + assert log(mpc(0,0)) == mpc(-inf,0) + assert isnan(log(mpc(nan,0)).real) + assert isnan(log(mpc(nan,0)).imag) + assert isnan(log(mpc(0,nan)).real) + assert isnan(log(mpc(0,nan)).imag) + assert isnan(log(mpc(nan,1)).real) + assert isnan(log(mpc(nan,1)).imag) + assert isnan(log(mpc(1,nan)).real) + assert isnan(log(mpc(1,nan)).imag) + +def test_trig_hyperb_basic(): + for x in (list(range(100)) + list(range(-100,0))): + t = x / 4.1 + assert cos(mpf(t)).ae(math.cos(t)) + assert sin(mpf(t)).ae(math.sin(t)) + assert tan(mpf(t)).ae(math.tan(t)) + assert cosh(mpf(t)).ae(math.cosh(t)) + assert sinh(mpf(t)).ae(math.sinh(t)) + assert tanh(mpf(t)).ae(math.tanh(t)) + assert sin(1+1j).ae(cmath.sin(1+1j)) + assert sin(-4-3.6j).ae(cmath.sin(-4-3.6j)) + assert cos(1+1j).ae(cmath.cos(1+1j)) + assert cos(-4-3.6j).ae(cmath.cos(-4-3.6j)) + +def test_degrees(): + assert cos(0*degree) == 1 + assert cos(90*degree).ae(0) + assert cos(180*degree).ae(-1) + assert cos(270*degree).ae(0) + assert cos(360*degree).ae(1) + assert sin(0*degree) == 0 + assert sin(90*degree).ae(1) + assert sin(180*degree).ae(0) + assert sin(270*degree).ae(-1) + assert sin(360*degree).ae(0) + +def random_complexes(N): + random.seed(1) + a = [] + for i in range(N): + x1 = random.uniform(-10, 10) + y1 = random.uniform(-10, 10) + x2 = random.uniform(-10, 10) + y2 = random.uniform(-10, 10) + z1 = complex(x1, y1) + z2 = complex(x2, y2) + a.append((z1, z2)) + return a + +def test_complex_powers(): + for dps in [15, 30, 100]: + # Check accuracy for complex square root + mp.dps = dps + a = mpc(1j)**0.5 + assert a.real == a.imag == mpf(2)**0.5 / 2 + mp.dps = 15 + random.seed(1) + for (z1, z2) in random_complexes(100): + assert (mpc(z1)**mpc(z2)).ae(z1**z2, 1e-12) + assert (e**(-pi*1j)).ae(-1) + mp.dps = 50 + assert (e**(-pi*1j)).ae(-1) + mp.dps = 15 + +def test_complex_sqrt_accuracy(): + def test_mpc_sqrt(lst): + for a, b in lst: + z = mpc(a + j*b) + assert mpc_ae(sqrt(z*z), z) + z = mpc(-a + j*b) + assert mpc_ae(sqrt(z*z), -z) + z = mpc(a - j*b) + assert mpc_ae(sqrt(z*z), z) + z = mpc(-a - j*b) + assert mpc_ae(sqrt(z*z), -z) + random.seed(2) + N = 10 + mp.dps = 30 + dps = mp.dps + test_mpc_sqrt([(random.uniform(0, 10),random.uniform(0, 10)) for i in range(N)]) + test_mpc_sqrt([(i + 0.1, (i + 0.2)*10**i) for i in range(N)]) + mp.dps = 15 + +def test_atan(): + mp.dps = 15 + assert atan(-2.3).ae(math.atan(-2.3)) + assert atan(1e-50) == 1e-50 + assert atan(1e50).ae(pi/2) + assert atan(-1e-50) == -1e-50 + assert atan(-1e50).ae(-pi/2) + assert atan(10**1000).ae(pi/2) + for dps in [25, 70, 100, 300, 1000]: + mp.dps = dps + assert (4*atan(1)).ae(pi) + mp.dps = 15 + pi2 = pi/2 + assert atan(mpc(inf,-1)).ae(pi2) + assert atan(mpc(inf,0)).ae(pi2) + assert atan(mpc(inf,1)).ae(pi2) + assert atan(mpc(1,inf)).ae(pi2) + assert atan(mpc(0,inf)).ae(pi2) + assert atan(mpc(-1,inf)).ae(-pi2) + assert atan(mpc(-inf,1)).ae(-pi2) + assert atan(mpc(-inf,0)).ae(-pi2) + assert atan(mpc(-inf,-1)).ae(-pi2) + assert atan(mpc(-1,-inf)).ae(-pi2) + assert atan(mpc(0,-inf)).ae(-pi2) + assert atan(mpc(1,-inf)).ae(pi2) + +def test_atan2(): + mp.dps = 15 + assert atan2(1,1).ae(pi/4) + assert atan2(1,-1).ae(3*pi/4) + assert atan2(-1,-1).ae(-3*pi/4) + assert atan2(-1,1).ae(-pi/4) + assert atan2(-1,0).ae(-pi/2) + assert atan2(1,0).ae(pi/2) + assert atan2(0,0) == 0 + assert atan2(inf,0).ae(pi/2) + assert atan2(-inf,0).ae(-pi/2) + assert isnan(atan2(inf,inf)) + assert isnan(atan2(-inf,inf)) + assert isnan(atan2(inf,-inf)) + assert isnan(atan2(3,nan)) + assert isnan(atan2(nan,3)) + assert isnan(atan2(0,nan)) + assert isnan(atan2(nan,0)) + assert atan2(0,inf) == 0 + assert atan2(0,-inf).ae(pi) + assert atan2(10,inf) == 0 + assert atan2(-10,inf) == 0 + assert atan2(-10,-inf).ae(-pi) + assert atan2(10,-inf).ae(pi) + assert atan2(inf,10).ae(pi/2) + assert atan2(inf,-10).ae(pi/2) + assert atan2(-inf,10).ae(-pi/2) + assert atan2(-inf,-10).ae(-pi/2) + +def test_areal_inverses(): + assert asin(mpf(0)) == 0 + assert asinh(mpf(0)) == 0 + assert acosh(mpf(1)) == 0 + assert isinstance(asin(mpf(0.5)), mpf) + assert isinstance(asin(mpf(2.0)), mpc) + assert isinstance(acos(mpf(0.5)), mpf) + assert isinstance(acos(mpf(2.0)), mpc) + assert isinstance(atanh(mpf(0.1)), mpf) + assert isinstance(atanh(mpf(1.1)), mpc) + + random.seed(1) + for i in range(50): + x = random.uniform(0, 1) + assert asin(mpf(x)).ae(math.asin(x)) + assert acos(mpf(x)).ae(math.acos(x)) + + x = random.uniform(-10, 10) + assert asinh(mpf(x)).ae(cmath.asinh(x).real) + assert isinstance(asinh(mpf(x)), mpf) + x = random.uniform(1, 10) + assert acosh(mpf(x)).ae(cmath.acosh(x).real) + assert isinstance(acosh(mpf(x)), mpf) + x = random.uniform(-10, 0.999) + assert isinstance(acosh(mpf(x)), mpc) + + x = random.uniform(-1, 1) + assert atanh(mpf(x)).ae(cmath.atanh(x).real) + assert isinstance(atanh(mpf(x)), mpf) + + dps = mp.dps + mp.dps = 300 + assert isinstance(asin(0.5), mpf) + mp.dps = 1000 + assert asin(1).ae(pi/2) + assert asin(-1).ae(-pi/2) + mp.dps = dps + +def test_invhyperb_inaccuracy(): + mp.dps = 15 + assert (asinh(1e-5)*10**5).ae(0.99999999998333333) + assert (asinh(1e-10)*10**10).ae(1) + assert (asinh(1e-50)*10**50).ae(1) + assert (asinh(-1e-5)*10**5).ae(-0.99999999998333333) + assert (asinh(-1e-10)*10**10).ae(-1) + assert (asinh(-1e-50)*10**50).ae(-1) + assert asinh(10**20).ae(46.744849040440862) + assert asinh(-10**20).ae(-46.744849040440862) + assert (tanh(1e-10)*10**10).ae(1) + assert (tanh(-1e-10)*10**10).ae(-1) + assert (atanh(1e-10)*10**10).ae(1) + assert (atanh(-1e-10)*10**10).ae(-1) + +def test_complex_functions(): + for x in (list(range(10)) + list(range(-10,0))): + for y in (list(range(10)) + list(range(-10,0))): + z = complex(x, y)/4.3 + 0.01j + assert exp(mpc(z)).ae(cmath.exp(z)) + assert log(mpc(z)).ae(cmath.log(z)) + assert cos(mpc(z)).ae(cmath.cos(z)) + assert sin(mpc(z)).ae(cmath.sin(z)) + assert tan(mpc(z)).ae(cmath.tan(z)) + assert sinh(mpc(z)).ae(cmath.sinh(z)) + assert cosh(mpc(z)).ae(cmath.cosh(z)) + assert tanh(mpc(z)).ae(cmath.tanh(z)) + +def test_complex_inverse_functions(): + mp.dps = 15 + iv.dps = 15 + for (z1, z2) in random_complexes(30): + # apparently cmath uses a different branch, so we + # can't use it for comparison + assert sinh(asinh(z1)).ae(z1) + # + assert acosh(z1).ae(cmath.acosh(z1)) + assert atanh(z1).ae(cmath.atanh(z1)) + assert atan(z1).ae(cmath.atan(z1)) + # the reason we set a big eps here is that the cmath + # functions are inaccurate + assert asin(z1).ae(cmath.asin(z1), rel_eps=1e-12) + assert acos(z1).ae(cmath.acos(z1), rel_eps=1e-12) + one = mpf(1) + for i in range(-9, 10, 3): + for k in range(-9, 10, 3): + a = 0.9*j*10**k + 0.8*one*10**i + b = cos(acos(a)) + assert b.ae(a) + b = sin(asin(a)) + assert b.ae(a) + one = mpf(1) + err = 2*10**-15 + for i in range(-9, 9, 3): + for k in range(-9, 9, 3): + a = -0.9*10**k + j*0.8*one*10**i + b = cosh(acosh(a)) + assert b.ae(a, err) + b = sinh(asinh(a)) + assert b.ae(a, err) + +def test_reciprocal_functions(): + assert sec(3).ae(-1.01010866590799375) + assert csc(3).ae(7.08616739573718592) + assert cot(3).ae(-7.01525255143453347) + assert sech(3).ae(0.0993279274194332078) + assert csch(3).ae(0.0998215696688227329) + assert coth(3).ae(1.00496982331368917) + assert asec(3).ae(1.23095941734077468) + assert acsc(3).ae(0.339836909454121937) + assert acot(3).ae(0.321750554396642193) + assert asech(0.5).ae(1.31695789692481671) + assert acsch(3).ae(0.327450150237258443) + assert acoth(3).ae(0.346573590279972655) + assert acot(0).ae(1.5707963267948966192) + assert acoth(0).ae(1.5707963267948966192j) + +def test_ldexp(): + mp.dps = 15 + assert ldexp(mpf(2.5), 0) == 2.5 + assert ldexp(mpf(2.5), -1) == 1.25 + assert ldexp(mpf(2.5), 2) == 10 + assert ldexp(mpf('inf'), 3) == mpf('inf') + +def test_frexp(): + mp.dps = 15 + assert frexp(0) == (0.0, 0) + assert frexp(9) == (0.5625, 4) + assert frexp(1) == (0.5, 1) + assert frexp(0.2) == (0.8, -2) + assert frexp(1000) == (0.9765625, 10) + +def test_aliases(): + assert ln(7) == log(7) + assert log10(3.75) == log(3.75,10) + assert degrees(5.6) == 5.6 / degree + assert radians(5.6) == 5.6 * degree + assert power(-1,0.5) == j + assert fmod(25,7) == 4.0 and isinstance(fmod(25,7), mpf) + +def test_arg_sign(): + assert arg(3) == 0 + assert arg(-3).ae(pi) + assert arg(j).ae(pi/2) + assert arg(-j).ae(-pi/2) + assert arg(0) == 0 + assert isnan(atan2(3,nan)) + assert isnan(atan2(nan,3)) + assert isnan(atan2(0,nan)) + assert isnan(atan2(nan,0)) + assert isnan(atan2(nan,nan)) + assert arg(inf) == 0 + assert arg(-inf).ae(pi) + assert isnan(arg(nan)) + #assert arg(inf*j).ae(pi/2) + assert sign(0) == 0 + assert sign(3) == 1 + assert sign(-3) == -1 + assert sign(inf) == 1 + assert sign(-inf) == -1 + assert isnan(sign(nan)) + assert sign(j) == j + assert sign(-3*j) == -j + assert sign(1+j).ae((1+j)/sqrt(2)) + +def test_misc_bugs(): + # test that this doesn't raise an exception + mp.dps = 1000 + log(1302) + mp.dps = 15 + +def test_arange(): + assert arange(10) == [mpf('0.0'), mpf('1.0'), mpf('2.0'), mpf('3.0'), + mpf('4.0'), mpf('5.0'), mpf('6.0'), mpf('7.0'), + mpf('8.0'), mpf('9.0')] + assert arange(-5, 5) == [mpf('-5.0'), mpf('-4.0'), mpf('-3.0'), + mpf('-2.0'), mpf('-1.0'), mpf('0.0'), + mpf('1.0'), mpf('2.0'), mpf('3.0'), mpf('4.0')] + assert arange(0, 1, 0.1) == [mpf('0.0'), mpf('0.10000000000000001'), + mpf('0.20000000000000001'), + mpf('0.30000000000000004'), + mpf('0.40000000000000002'), + mpf('0.5'), mpf('0.60000000000000009'), + mpf('0.70000000000000007'), + mpf('0.80000000000000004'), + mpf('0.90000000000000002')] + assert arange(17, -9, -3) == [mpf('17.0'), mpf('14.0'), mpf('11.0'), + mpf('8.0'), mpf('5.0'), mpf('2.0'), + mpf('-1.0'), mpf('-4.0'), mpf('-7.0')] + assert arange(0.2, 0.1, -0.1) == [mpf('0.20000000000000001')] + assert arange(0) == [] + assert arange(1000, -1) == [] + assert arange(-1.23, 3.21, -0.0000001) == [] + +def test_linspace(): + assert linspace(2, 9, 7) == [mpf('2.0'), mpf('3.166666666666667'), + mpf('4.3333333333333339'), mpf('5.5'), mpf('6.666666666666667'), + mpf('7.8333333333333339'), mpf('9.0')] + assert linspace(2, 9, 7, endpoint=0) == [mpf('2.0'), mpf('3.0'), mpf('4.0'), + mpf('5.0'), mpf('6.0'), mpf('7.0'), mpf('8.0')] + assert linspace(2, 7, 1) == [mpf(2)] + +def test_float_cbrt(): + mp.dps = 30 + for a in arange(0,10,0.1): + assert cbrt(a*a*a).ae(a, eps) + assert cbrt(-1).ae(0.5 + j*sqrt(3)/2) + one_third = mpf(1)/3 + for a in arange(0,10,2.7) + [0.1 + 10**5]: + a = mpc(a + 1.1j) + r1 = cbrt(a) + mp.dps += 10 + r2 = pow(a, one_third) + mp.dps -= 10 + assert r1.ae(r2, eps) + mp.dps = 100 + for n in range(100, 301, 100): + w = 10**n + j*10**-3 + z = w*w*w + r = cbrt(z) + assert mpc_ae(r, w, eps) + mp.dps = 15 + +def test_root(): + mp.dps = 30 + random.seed(1) + a = random.randint(0, 10000) + p = a*a*a + r = nthroot(mpf(p), 3) + assert r == a + for n in range(4, 10): + p = p*a + assert nthroot(mpf(p), n) == a + mp.dps = 40 + for n in range(10, 5000, 100): + for a in [random.random()*10000, random.random()*10**100]: + r = nthroot(a, n) + r1 = pow(a, mpf(1)/n) + assert r.ae(r1) + r = nthroot(a, -n) + r1 = pow(a, -mpf(1)/n) + assert r.ae(r1) + # XXX: this is broken right now + # tests for nthroot rounding + for rnd in ['nearest', 'up', 'down']: + mp.rounding = rnd + for n in [-5, -3, 3, 5]: + prec = 50 + for i in range(10): + mp.prec = prec + a = rand() + mp.prec = 2*prec + b = a**n + mp.prec = prec + r = nthroot(b, n) + assert r == a + mp.dps = 30 + for n in range(3, 21): + a = (random.random() + j*random.random()) + assert nthroot(a, n).ae(pow(a, mpf(1)/n)) + assert mpc_ae(nthroot(a, n), pow(a, mpf(1)/n)) + a = (random.random()*10**100 + j*random.random()) + r = nthroot(a, n) + mp.dps += 4 + r1 = pow(a, mpf(1)/n) + mp.dps -= 4 + assert r.ae(r1) + assert mpc_ae(r, r1, eps) + r = nthroot(a, -n) + mp.dps += 4 + r1 = pow(a, -mpf(1)/n) + mp.dps -= 4 + assert r.ae(r1) + assert mpc_ae(r, r1, eps) + mp.dps = 15 + assert nthroot(4, 1) == 4 + assert nthroot(4, 0) == 1 + assert nthroot(4, -1) == 0.25 + assert nthroot(inf, 1) == inf + assert nthroot(inf, 2) == inf + assert nthroot(inf, 3) == inf + assert nthroot(inf, -1) == 0 + assert nthroot(inf, -2) == 0 + assert nthroot(inf, -3) == 0 + assert nthroot(j, 1) == j + assert nthroot(j, 0) == 1 + assert nthroot(j, -1) == -j + assert isnan(nthroot(nan, 1)) + assert isnan(nthroot(nan, 0)) + assert isnan(nthroot(nan, -1)) + assert isnan(nthroot(inf, 0)) + assert root(2,3) == nthroot(2,3) + assert root(16,4,0) == 2 + assert root(16,4,1) == 2j + assert root(16,4,2) == -2 + assert root(16,4,3) == -2j + assert root(16,4,4) == 2 + assert root(-125,3,1) == -5 + +def test_issue_136(): + for dps in [20, 80]: + mp.dps = dps + r = nthroot(mpf('-1e-20'), 4) + assert r.ae(mpf(10)**(-5) * (1 + j) * mpf(2)**(-0.5)) + mp.dps = 80 + assert nthroot('-1e-3', 4).ae(mpf(10)**(-3./4) * (1 + j)/sqrt(2)) + assert nthroot('-1e-6', 4).ae((1 + j)/(10 * sqrt(20))) + # Check that this doesn't take eternity to compute + mp.dps = 20 + assert nthroot('-1e100000000', 4).ae((1+j)*mpf('1e25000000')/sqrt(2)) + mp.dps = 15 + +def test_mpcfun_real_imag(): + mp.dps = 15 + x = mpf(0.3) + y = mpf(0.4) + assert exp(mpc(x,0)) == exp(x) + assert exp(mpc(0,y)) == mpc(cos(y),sin(y)) + assert cos(mpc(x,0)) == cos(x) + assert sin(mpc(x,0)) == sin(x) + assert cos(mpc(0,y)) == cosh(y) + assert sin(mpc(0,y)) == mpc(0,sinh(y)) + assert cospi(mpc(x,0)) == cospi(x) + assert sinpi(mpc(x,0)) == sinpi(x) + assert cospi(mpc(0,y)).ae(cosh(pi*y)) + assert sinpi(mpc(0,y)).ae(mpc(0,sinh(pi*y))) + c, s = cospi_sinpi(mpc(x,0)) + assert c == cospi(x) + assert s == sinpi(x) + c, s = cospi_sinpi(mpc(0,y)) + assert c.ae(cosh(pi*y)) + assert s.ae(mpc(0,sinh(pi*y))) + c, s = cos_sin(mpc(x,0)) + assert c == cos(x) + assert s == sin(x) + c, s = cos_sin(mpc(0,y)) + assert c == cosh(y) + assert s == mpc(0,sinh(y)) + +def test_perturbation_rounding(): + mp.dps = 100 + a = pi/10**50 + b = -pi/10**50 + c = 1 + a + d = 1 + b + mp.dps = 15 + assert exp(a) == 1 + assert exp(a, rounding='c') > 1 + assert exp(b, rounding='c') == 1 + assert exp(a, rounding='f') == 1 + assert exp(b, rounding='f') < 1 + assert cos(a) == 1 + assert cos(a, rounding='c') == 1 + assert cos(b, rounding='c') == 1 + assert cos(a, rounding='f') < 1 + assert cos(b, rounding='f') < 1 + for f in [sin, atan, asinh, tanh]: + assert f(a) == +a + assert f(a, rounding='c') > a + assert f(a, rounding='f') < a + assert f(b) == +b + assert f(b, rounding='c') > b + assert f(b, rounding='f') < b + for f in [asin, tan, sinh, atanh]: + assert f(a) == +a + assert f(b) == +b + assert f(a, rounding='c') > a + assert f(b, rounding='c') > b + assert f(a, rounding='f') < a + assert f(b, rounding='f') < b + assert ln(c) == +a + assert ln(d) == +b + assert ln(c, rounding='c') > a + assert ln(c, rounding='f') < a + assert ln(d, rounding='c') > b + assert ln(d, rounding='f') < b + assert cosh(a) == 1 + assert cosh(b) == 1 + assert cosh(a, rounding='c') > 1 + assert cosh(b, rounding='c') > 1 + assert cosh(a, rounding='f') == 1 + assert cosh(b, rounding='f') == 1 + +def test_integer_parts(): + assert floor(3.2) == 3 + assert ceil(3.2) == 4 + assert floor(3.2+5j) == 3+5j + assert ceil(3.2+5j) == 4+5j + +def test_complex_parts(): + assert fabs('3') == 3 + assert fabs(3+4j) == 5 + assert re(3) == 3 + assert re(1+4j) == 1 + assert im(3) == 0 + assert im(1+4j) == 4 + assert conj(3) == 3 + assert conj(3+4j) == 3-4j + assert mpf(3).conjugate() == 3 + +def test_cospi_sinpi(): + assert sinpi(0) == 0 + assert sinpi(0.5) == 1 + assert sinpi(1) == 0 + assert sinpi(1.5) == -1 + assert sinpi(2) == 0 + assert sinpi(2.5) == 1 + assert sinpi(-0.5) == -1 + assert cospi(0) == 1 + assert cospi(0.5) == 0 + assert cospi(1) == -1 + assert cospi(1.5) == 0 + assert cospi(2) == 1 + assert cospi(2.5) == 0 + assert cospi(-0.5) == 0 + assert cospi(100000000000.25).ae(sqrt(2)/2) + a = cospi(2+3j) + assert a.real.ae(cos((2+3j)*pi).real) + assert a.imag == 0 + b = sinpi(2+3j) + assert b.imag.ae(sin((2+3j)*pi).imag) + assert b.real == 0 + mp.dps = 35 + x1 = mpf(10000) - mpf('1e-15') + x2 = mpf(10000) + mpf('1e-15') + x3 = mpf(10000.5) - mpf('1e-15') + x4 = mpf(10000.5) + mpf('1e-15') + x5 = mpf(10001) - mpf('1e-15') + x6 = mpf(10001) + mpf('1e-15') + x7 = mpf(10001.5) - mpf('1e-15') + x8 = mpf(10001.5) + mpf('1e-15') + mp.dps = 15 + M = 10**15 + assert (sinpi(x1)*M).ae(-pi) + assert (sinpi(x2)*M).ae(pi) + assert (cospi(x3)*M).ae(pi) + assert (cospi(x4)*M).ae(-pi) + assert (sinpi(x5)*M).ae(pi) + assert (sinpi(x6)*M).ae(-pi) + assert (cospi(x7)*M).ae(-pi) + assert (cospi(x8)*M).ae(pi) + assert 0.999 < cospi(x1, rounding='d') < 1 + assert 0.999 < cospi(x2, rounding='d') < 1 + assert 0.999 < sinpi(x3, rounding='d') < 1 + assert 0.999 < sinpi(x4, rounding='d') < 1 + assert -1 < cospi(x5, rounding='d') < -0.999 + assert -1 < cospi(x6, rounding='d') < -0.999 + assert -1 < sinpi(x7, rounding='d') < -0.999 + assert -1 < sinpi(x8, rounding='d') < -0.999 + assert (sinpi(1e-15)*M).ae(pi) + assert (sinpi(-1e-15)*M).ae(-pi) + assert cospi(1e-15) == 1 + assert cospi(1e-15, rounding='d') < 1 + +def test_expj(): + assert expj(0) == 1 + assert expj(1).ae(exp(j)) + assert expj(j).ae(exp(-1)) + assert expj(1+j).ae(exp(j*(1+j))) + assert expjpi(0) == 1 + assert expjpi(1).ae(exp(j*pi)) + assert expjpi(j).ae(exp(-pi)) + assert expjpi(1+j).ae(exp(j*pi*(1+j))) + assert expjpi(-10**15 * j).ae('2.22579818340535731e+1364376353841841') + +def test_sinc(): + assert sinc(0) == sincpi(0) == 1 + assert sinc(inf) == sincpi(inf) == 0 + assert sinc(-inf) == sincpi(-inf) == 0 + assert sinc(2).ae(0.45464871341284084770) + assert sinc(2+3j).ae(0.4463290318402435457-2.7539470277436474940j) + assert sincpi(2) == 0 + assert sincpi(1.5).ae(-0.212206590789193781) + +def test_fibonacci(): + mp.dps = 15 + assert [fibonacci(n) for n in range(-5, 10)] == \ + [5, -3, 2, -1, 1, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34] + assert fib(2.5).ae(1.4893065462657091) + assert fib(3+4j).ae(-5248.51130728372 - 14195.962288353j) + assert fib(1000).ae(4.3466557686937455e+208) + assert str(fib(10**100)) == '6.24499112864607e+2089876402499787337692720892375554168224592399182109535392875613974104853496745963277658556235103534' + mp.dps = 2100 + a = fib(10000) + assert a % 10**10 == 9947366875 + mp.dps = 15 + assert fibonacci(inf) == inf + assert fib(3+0j) == 2 + +def test_call_with_dps(): + mp.dps = 15 + assert abs(exp(1, dps=30)-e(dps=35)) < 1e-29 + +def test_tanh(): + mp.dps = 15 + assert tanh(0) == 0 + assert tanh(inf) == 1 + assert tanh(-inf) == -1 + assert isnan(tanh(nan)) + assert tanh(mpc('inf', '0')) == 1 + +def test_atanh(): + mp.dps = 15 + assert atanh(0) == 0 + assert atanh(0.5).ae(0.54930614433405484570) + assert atanh(-0.5).ae(-0.54930614433405484570) + assert atanh(1) == inf + assert atanh(-1) == -inf + assert isnan(atanh(nan)) + assert isinstance(atanh(1), mpf) + assert isinstance(atanh(-1), mpf) + # Limits at infinity + jpi2 = j*pi/2 + assert atanh(inf).ae(-jpi2) + assert atanh(-inf).ae(jpi2) + assert atanh(mpc(inf,-1)).ae(-jpi2) + assert atanh(mpc(inf,0)).ae(-jpi2) + assert atanh(mpc(inf,1)).ae(jpi2) + assert atanh(mpc(1,inf)).ae(jpi2) + assert atanh(mpc(0,inf)).ae(jpi2) + assert atanh(mpc(-1,inf)).ae(jpi2) + assert atanh(mpc(-inf,1)).ae(jpi2) + assert atanh(mpc(-inf,0)).ae(jpi2) + assert atanh(mpc(-inf,-1)).ae(-jpi2) + assert atanh(mpc(-1,-inf)).ae(-jpi2) + assert atanh(mpc(0,-inf)).ae(-jpi2) + assert atanh(mpc(1,-inf)).ae(-jpi2) + +def test_expm1(): + mp.dps = 15 + assert expm1(0) == 0 + assert expm1(3).ae(exp(3)-1) + assert expm1(inf) == inf + assert expm1(1e-50).ae(1e-50) + assert (expm1(1e-10)*1e10).ae(1.00000000005) + +def test_log1p(): + mp.dps = 15 + assert log1p(0) == 0 + assert log1p(3).ae(log(1+3)) + assert log1p(inf) == inf + assert log1p(1e-50).ae(1e-50) + assert (log1p(1e-10)*1e10).ae(0.99999999995) + +def test_powm1(): + mp.dps = 15 + assert powm1(2,3) == 7 + assert powm1(-1,2) == 0 + assert powm1(-1,0) == 0 + assert powm1(-2,0) == 0 + assert powm1(3+4j,0) == 0 + assert powm1(0,1) == -1 + assert powm1(0,0) == 0 + assert powm1(1,0) == 0 + assert powm1(1,2) == 0 + assert powm1(1,3+4j) == 0 + assert powm1(1,5) == 0 + assert powm1(j,4) == 0 + assert powm1(-j,4) == 0 + assert (powm1(2,1e-100)*1e100).ae(ln2) + assert powm1(2,'1e-100000000000') != 0 + assert (powm1(fadd(1,1e-100,exact=True), 5)*1e100).ae(5) + +def test_unitroots(): + assert unitroots(1) == [1] + assert unitroots(2) == [1, -1] + a, b, c = unitroots(3) + assert a == 1 + assert b.ae(-0.5 + 0.86602540378443864676j) + assert c.ae(-0.5 - 0.86602540378443864676j) + assert unitroots(1, primitive=True) == [1] + assert unitroots(2, primitive=True) == [-1] + assert unitroots(3, primitive=True) == unitroots(3)[1:] + assert unitroots(4, primitive=True) == [j, -j] + assert len(unitroots(17, primitive=True)) == 16 + assert len(unitroots(16, primitive=True)) == 8 + +def test_cyclotomic(): + mp.dps = 15 + assert [cyclotomic(n,1) for n in range(31)] == [1,0,2,3,2,5,1,7,2,3,1,11,1,13,1,1,2,17,1,19,1,1,1,23,1,5,1,3,1,29,1] + assert [cyclotomic(n,-1) for n in range(31)] == [1,-2,0,1,2,1,3,1,2,1,5,1,1,1,7,1,2,1,3,1,1,1,11,1,1,1,13,1,1,1,1] + assert [cyclotomic(n,j) for n in range(21)] == [1,-1+j,1+j,j,0,1,-j,j,2,-j,1,j,3,1,-j,1,2,1,j,j,5] + assert [cyclotomic(n,-j) for n in range(21)] == [1,-1-j,1-j,-j,0,1,j,-j,2,j,1,-j,3,1,j,1,2,1,-j,-j,5] + assert cyclotomic(1624,j) == 1 + assert cyclotomic(33600,j) == 1 + u = sqrt(j, prec=500) + assert cyclotomic(8, u).ae(0) + assert cyclotomic(30, u).ae(5.8284271247461900976) + assert cyclotomic(2040, u).ae(1) + assert cyclotomic(0,2.5) == 1 + assert cyclotomic(1,2.5) == 2.5-1 + assert cyclotomic(2,2.5) == 2.5+1 + assert cyclotomic(3,2.5) == 2.5**2 + 2.5 + 1 + assert cyclotomic(7,2.5) == 406.234375 diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_functions2.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_functions2.py new file mode 100644 index 0000000000000000000000000000000000000000..2b2d57fcec9be0db4d921b013f24fd6a5e0e9930 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_functions2.py @@ -0,0 +1,2384 @@ +import math +import pytest +from mpmath import * + +def test_bessel(): + mp.dps = 15 + assert j0(1).ae(0.765197686557966551) + assert j0(pi).ae(-0.304242177644093864) + assert j0(1000).ae(0.0247866861524201746) + assert j0(-25).ae(0.0962667832759581162) + assert j1(1).ae(0.440050585744933516) + assert j1(pi).ae(0.284615343179752757) + assert j1(1000).ae(0.00472831190708952392) + assert j1(-25).ae(0.125350249580289905) + assert besselj(5,1).ae(0.000249757730211234431) + assert besselj(5+0j,1).ae(0.000249757730211234431) + assert besselj(5,pi).ae(0.0521411843671184747) + assert besselj(5,1000).ae(0.00502540694523318607) + assert besselj(5,-25).ae(0.0660079953984229934) + assert besselj(-3,2).ae(-0.128943249474402051) + assert besselj(-4,2).ae(0.0339957198075684341) + assert besselj(3,3+2j).ae(0.424718794929639595942 + 0.625665327745785804812j) + assert besselj(0.25,4).ae(-0.374760630804249715) + assert besselj(1+2j,3+4j).ae(0.319247428741872131 - 0.669557748880365678j) + assert (besselj(3, 10**10) * 10**5).ae(0.76765081748139204023) + assert bessely(-0.5, 0) == 0 + assert bessely(0.5, 0) == -inf + assert bessely(1.5, 0) == -inf + assert bessely(0,0) == -inf + assert bessely(-0.4, 0) == -inf + assert bessely(-0.6, 0) == inf + assert bessely(-1, 0) == inf + assert bessely(-1.4, 0) == inf + assert bessely(-1.6, 0) == -inf + assert bessely(-1, 0) == inf + assert bessely(-2, 0) == -inf + assert bessely(-3, 0) == inf + assert bessely(0.5, 0) == -inf + assert bessely(1, 0) == -inf + assert bessely(1.5, 0) == -inf + assert bessely(2, 0) == -inf + assert bessely(2.5, 0) == -inf + assert bessely(3, 0) == -inf + assert bessely(0,0.5).ae(-0.44451873350670655715) + assert bessely(1,0.5).ae(-1.4714723926702430692) + assert bessely(-1,0.5).ae(1.4714723926702430692) + assert bessely(3.5,0.5).ae(-138.86400867242488443) + assert bessely(0,3+4j).ae(4.6047596915010138655-8.8110771408232264208j) + assert bessely(0,j).ae(-0.26803248203398854876+1.26606587775200833560j) + assert (bessely(3, 10**10) * 10**5).ae(0.21755917537013204058) + assert besseli(0,0) == 1 + assert besseli(1,0) == 0 + assert besseli(2,0) == 0 + assert besseli(-1,0) == 0 + assert besseli(-2,0) == 0 + assert besseli(0,0.5).ae(1.0634833707413235193) + assert besseli(1,0.5).ae(0.25789430539089631636) + assert besseli(-1,0.5).ae(0.25789430539089631636) + assert besseli(3.5,0.5).ae(0.00068103597085793815863) + assert besseli(0,3+4j).ae(-3.3924877882755196097-1.3239458916287264815j) + assert besseli(0,j).ae(besselj(0,1)) + assert (besseli(3, 10**10) * mpf(10)**(-4342944813)).ae(4.2996028505491271875) + assert besselk(0,0) == inf + assert besselk(1,0) == inf + assert besselk(2,0) == inf + assert besselk(-1,0) == inf + assert besselk(-2,0) == inf + assert besselk(0,0.5).ae(0.92441907122766586178) + assert besselk(1,0.5).ae(1.6564411200033008937) + assert besselk(-1,0.5).ae(1.6564411200033008937) + assert besselk(3.5,0.5).ae(207.48418747548460607) + assert besselk(0,3+4j).ae(-0.007239051213570155013+0.026510418350267677215j) + assert besselk(0,j).ae(-0.13863371520405399968-1.20196971531720649914j) + assert (besselk(3, 10**10) * mpf(10)**4342944824).ae(1.1628981033356187851) + # test for issue 331, bug reported by Michael Hartmann + for n in range(10,100,10): + mp.dps = n + assert besseli(91.5,24.7708).ae("4.00830632138673963619656140653537080438462342928377020695738635559218797348548092636896796324190271316137982810144874264e-41") + +def test_bessel_zeros(): + mp.dps = 15 + assert besseljzero(0,1).ae(2.40482555769577276869) + assert besseljzero(2,1).ae(5.1356223018406825563) + assert besseljzero(1,50).ae(157.86265540193029781) + assert besseljzero(10,1).ae(14.475500686554541220) + assert besseljzero(0.5,3).ae(9.4247779607693797153) + assert besseljzero(2,1,1).ae(3.0542369282271403228) + assert besselyzero(0,1).ae(0.89357696627916752158) + assert besselyzero(2,1).ae(3.3842417671495934727) + assert besselyzero(1,50).ae(156.29183520147840108) + assert besselyzero(10,1).ae(12.128927704415439387) + assert besselyzero(0.5,3).ae(7.8539816339744830962) + assert besselyzero(2,1,1).ae(5.0025829314460639452) + +def test_hankel(): + mp.dps = 15 + assert hankel1(0,0.5).ae(0.93846980724081290423-0.44451873350670655715j) + assert hankel1(1,0.5).ae(0.2422684576748738864-1.4714723926702430692j) + assert hankel1(-1,0.5).ae(-0.2422684576748738864+1.4714723926702430692j) + assert hankel1(1.5,0.5).ae(0.0917016996256513026-2.5214655504213378514j) + assert hankel1(1.5,3+4j).ae(0.0066806866476728165382-0.0036684231610839127106j) + assert hankel2(0,0.5).ae(0.93846980724081290423+0.44451873350670655715j) + assert hankel2(1,0.5).ae(0.2422684576748738864+1.4714723926702430692j) + assert hankel2(-1,0.5).ae(-0.2422684576748738864-1.4714723926702430692j) + assert hankel2(1.5,0.5).ae(0.0917016996256513026+2.5214655504213378514j) + assert hankel2(1.5,3+4j).ae(14.783528526098567526-7.397390270853446512j) + +def test_struve(): + mp.dps = 15 + assert struveh(2,3).ae(0.74238666967748318564) + assert struveh(-2.5,3).ae(0.41271003220971599344) + assert struvel(2,3).ae(1.7476573277362782744) + assert struvel(-2.5,3).ae(1.5153394466819651377) + +def test_whittaker(): + mp.dps = 15 + assert whitm(2,3,4).ae(49.753745589025246591) + assert whitw(2,3,4).ae(14.111656223052932215) + +def test_kelvin(): + mp.dps = 15 + assert ber(2,3).ae(0.80836846563726819091) + assert ber(3,4).ae(-0.28262680167242600233) + assert ber(-3,2).ae(-0.085611448496796363669) + assert bei(2,3).ae(-0.89102236377977331571) + assert bei(-3,2).ae(-0.14420994155731828415) + assert ker(2,3).ae(0.12839126695733458928) + assert ker(-3,2).ae(-0.29802153400559142783) + assert ker(0.5,3).ae(-0.085662378535217097524) + assert kei(2,3).ae(0.036804426134164634000) + assert kei(-3,2).ae(0.88682069845786731114) + assert kei(0.5,3).ae(0.013633041571314302948) + +def test_hyper_misc(): + mp.dps = 15 + assert hyp0f1(1,0) == 1 + assert hyp1f1(1,2,0) == 1 + assert hyp1f2(1,2,3,0) == 1 + assert hyp2f1(1,2,3,0) == 1 + assert hyp2f2(1,2,3,4,0) == 1 + assert hyp2f3(1,2,3,4,5,0) == 1 + # Degenerate case: 0F0 + assert hyper([],[],0) == 1 + assert hyper([],[],-2).ae(exp(-2)) + # Degenerate case: 1F0 + assert hyper([2],[],1.5) == 4 + # + assert hyp2f1((1,3),(2,3),(5,6),mpf(27)/32).ae(1.6) + assert hyp2f1((1,4),(1,2),(3,4),mpf(80)/81).ae(1.8) + assert hyp2f1((2,3),(1,1),(3,2),(2+j)/3).ae(1.327531603558679093+0.439585080092769253j) + mp.dps = 25 + v = mpc('1.2282306665029814734863026', '-0.1225033830118305184672133') + assert hyper([(3,4),2+j,1],[1,5,j/3],mpf(1)/5+j/8).ae(v) + mp.dps = 15 + +def test_elliptic_integrals(): + mp.dps = 15 + assert ellipk(0).ae(pi/2) + assert ellipk(0.5).ae(gamma(0.25)**2/(4*sqrt(pi))) + assert ellipk(1) == inf + assert ellipk(1+0j) == inf + assert ellipk(-1).ae('1.3110287771460599052') + assert ellipk(-2).ae('1.1714200841467698589') + assert isinstance(ellipk(-2), mpf) + assert isinstance(ellipe(-2), mpf) + assert ellipk(-50).ae('0.47103424540873331679') + mp.dps = 30 + n1 = +fraction(99999,100000) + n2 = +fraction(100001,100000) + mp.dps = 15 + assert ellipk(n1).ae('7.1427724505817781901') + assert ellipk(n2).ae(mpc('7.1427417367963090109', '-1.5707923998261688019')) + assert ellipe(n1).ae('1.0000332138990829170') + v = ellipe(n2) + assert v.real.ae('0.999966786328145474069137') + assert (v.imag*10**6).ae('7.853952181727432') + assert ellipk(2).ae(mpc('1.3110287771460599052', '-1.3110287771460599052')) + assert ellipk(50).ae(mpc('0.22326753950210985451', '-0.47434723226254522087')) + assert ellipk(3+4j).ae(mpc('0.91119556380496500866', '0.63133428324134524388')) + assert ellipk(3-4j).ae(mpc('0.91119556380496500866', '-0.63133428324134524388')) + assert ellipk(-3+4j).ae(mpc('0.95357894880405122483', '0.23093044503746114444')) + assert ellipk(-3-4j).ae(mpc('0.95357894880405122483', '-0.23093044503746114444')) + assert isnan(ellipk(nan)) + assert isnan(ellipe(nan)) + assert ellipk(inf) == 0 + assert isinstance(ellipk(inf), mpc) + assert ellipk(-inf) == 0 + assert ellipk(1+0j) == inf + assert ellipe(0).ae(pi/2) + assert ellipe(0.5).ae(pi**(mpf(3)/2)/gamma(0.25)**2 +gamma(0.25)**2/(8*sqrt(pi))) + assert ellipe(1) == 1 + assert ellipe(1+0j) == 1 + assert ellipe(inf) == mpc(0,inf) + assert ellipe(-inf) == inf + assert ellipe(3+4j).ae(1.4995535209333469543-1.5778790079127582745j) + assert ellipe(3-4j).ae(1.4995535209333469543+1.5778790079127582745j) + assert ellipe(-3+4j).ae(2.5804237855343377803-0.8306096791000413778j) + assert ellipe(-3-4j).ae(2.5804237855343377803+0.8306096791000413778j) + assert ellipe(2).ae(0.59907011736779610372+0.59907011736779610372j) + assert ellipe('1e-1000000000').ae(pi/2) + assert ellipk('1e-1000000000').ae(pi/2) + assert ellipe(-pi).ae(2.4535865983838923) + mp.dps = 50 + assert ellipk(1/pi).ae('1.724756270009501831744438120951614673874904182624739673') + assert ellipe(1/pi).ae('1.437129808135123030101542922290970050337425479058225712') + assert ellipk(-10*pi).ae('0.5519067523886233967683646782286965823151896970015484512') + assert ellipe(-10*pi).ae('5.926192483740483797854383268707108012328213431657645509') + v = ellipk(pi) + assert v.real.ae('0.973089521698042334840454592642137667227167622330325225') + assert v.imag.ae('-1.156151296372835303836814390793087600271609993858798016') + v = ellipe(pi) + assert v.real.ae('0.4632848917264710404078033487934663562998345622611263332') + assert v.imag.ae('1.0637961621753130852473300451583414489944099504180510966') + mp.dps = 15 + +def test_exp_integrals(): + mp.dps = 15 + x = +e + z = e + sqrt(3)*j + assert ei(x).ae(8.21168165538361560) + assert li(x).ae(1.89511781635593676) + assert si(x).ae(1.82104026914756705) + assert ci(x).ae(0.213958001340379779) + assert shi(x).ae(4.11520706247846193) + assert chi(x).ae(4.09647459290515367) + assert fresnels(x).ae(0.437189718149787643) + assert fresnelc(x).ae(0.401777759590243012) + assert airyai(x).ae(0.0108502401568586681) + assert airybi(x).ae(8.98245748585468627) + assert ei(z).ae(3.72597969491314951 + 7.34213212314224421j) + assert li(z).ae(2.28662658112562502 + 1.50427225297269364j) + assert si(z).ae(2.48122029237669054 + 0.12684703275254834j) + assert ci(z).ae(0.169255590269456633 - 0.892020751420780353j) + assert shi(z).ae(1.85810366559344468 + 3.66435842914920263j) + assert chi(z).ae(1.86787602931970484 + 3.67777369399304159j) + assert fresnels(z/3).ae(0.034534397197008182 + 0.754859844188218737j) + assert fresnelc(z/3).ae(1.261581645990027372 + 0.417949198775061893j) + assert airyai(z).ae(-0.0162552579839056062 - 0.0018045715700210556j) + assert airybi(z).ae(-4.98856113282883371 + 2.08558537872180623j) + assert li(0) == 0.0 + assert li(1) == -inf + assert li(inf) == inf + assert isinstance(li(0.7), mpf) + assert si(inf).ae(pi/2) + assert si(-inf).ae(-pi/2) + assert ci(inf) == 0 + assert ci(0) == -inf + assert isinstance(ei(-0.7), mpf) + assert airyai(inf) == 0 + assert airybi(inf) == inf + assert airyai(-inf) == 0 + assert airybi(-inf) == 0 + assert fresnels(inf) == 0.5 + assert fresnelc(inf) == 0.5 + assert fresnels(-inf) == -0.5 + assert fresnelc(-inf) == -0.5 + assert shi(0) == 0 + assert shi(inf) == inf + assert shi(-inf) == -inf + assert chi(0) == -inf + assert chi(inf) == inf + +def test_ei(): + mp.dps = 15 + assert ei(0) == -inf + assert ei(inf) == inf + assert ei(-inf) == -0.0 + assert ei(20+70j).ae(6.1041351911152984397e6 - 2.7324109310519928872e6j) + # tests for the asymptotic expansion + # values checked with Mathematica ExpIntegralEi + mp.dps = 50 + r = ei(20000) + s = '3.8781962825045010930273870085501819470698476975019e+8681' + assert str(r) == s + r = ei(-200) + s = '-6.8852261063076355977108174824557929738368086933303e-90' + assert str(r) == s + r =ei(20000 + 10*j) + sre = '-3.255138234032069402493850638874410725961401274106e+8681' + sim = '-2.1081929993474403520785942429469187647767369645423e+8681' + assert str(r.real) == sre and str(r.imag) == sim + mp.dps = 15 + # More asymptotic expansions + assert chi(-10**6+100j).ae('1.3077239389562548386e+434288 + 7.6808956999707408158e+434287j') + assert shi(-10**6+100j).ae('-1.3077239389562548386e+434288 - 7.6808956999707408158e+434287j') + mp.dps = 15 + assert ei(10j).ae(-0.0454564330044553726+3.2291439210137706686j) + assert ei(100j).ae(-0.0051488251426104921+3.1330217936839529126j) + u = ei(fmul(10**20, j, exact=True)) + assert u.real.ae(-6.4525128526578084421345e-21, abs_eps=0, rel_eps=8*eps) + assert u.imag.ae(pi) + assert ei(-10j).ae(-0.0454564330044553726-3.2291439210137706686j) + assert ei(-100j).ae(-0.0051488251426104921-3.1330217936839529126j) + u = ei(fmul(-10**20, j, exact=True)) + assert u.real.ae(-6.4525128526578084421345e-21, abs_eps=0, rel_eps=8*eps) + assert u.imag.ae(-pi) + assert ei(10+10j).ae(-1576.1504265768517448+436.9192317011328140j) + u = ei(-10+10j) + assert u.real.ae(7.6698978415553488362543e-7, abs_eps=0, rel_eps=8*eps) + assert u.imag.ae(3.141595611735621062025) + +def test_e1(): + mp.dps = 15 + assert e1(0) == inf + assert e1(inf) == 0 + assert e1(-inf) == mpc(-inf, -pi) + assert e1(10j).ae(0.045456433004455372635 + 0.087551267423977430100j) + assert e1(100j).ae(0.0051488251426104921444 - 0.0085708599058403258790j) + assert e1(fmul(10**20, j, exact=True)).ae(6.4525128526578084421e-21 - 7.6397040444172830039e-21j, abs_eps=0, rel_eps=8*eps) + assert e1(-10j).ae(0.045456433004455372635 - 0.087551267423977430100j) + assert e1(-100j).ae(0.0051488251426104921444 + 0.0085708599058403258790j) + assert e1(fmul(-10**20, j, exact=True)).ae(6.4525128526578084421e-21 + 7.6397040444172830039e-21j, abs_eps=0, rel_eps=8*eps) + +def test_expint(): + mp.dps = 15 + assert expint(0,0) == inf + assert expint(0,1).ae(1/e) + assert expint(0,1.5).ae(2/exp(1.5)/3) + assert expint(1,1).ae(-ei(-1)) + assert expint(2,0).ae(1) + assert expint(3,0).ae(1/2.) + assert expint(4,0).ae(1/3.) + assert expint(-2, 0.5).ae(26/sqrt(e)) + assert expint(-1,-1) == 0 + assert expint(-2,-1).ae(-e) + assert expint(5.5, 0).ae(2/9.) + assert expint(2.00000001,0).ae(100000000./100000001) + assert expint(2+3j,4-j).ae(0.0023461179581675065414+0.0020395540604713669262j) + assert expint('1.01', '1e-1000').ae(99.9999999899412802) + assert expint('1.000000000001', 3.5).ae(0.00697013985754701819446) + assert expint(2,3).ae(3*ei(-3)+exp(-3)) + assert (expint(10,20)*10**10).ae(0.694439055541231353) + assert expint(3,inf) == 0 + assert expint(3.2,inf) == 0 + assert expint(3.2+2j,inf) == 0 + assert expint(1,3j).ae(-0.11962978600800032763 + 0.27785620120457163717j) + assert expint(1,3).ae(0.013048381094197037413) + assert expint(1,-3).ae(-ei(3)-pi*j) + #assert expint(3) == expint(1,3) + assert expint(1,-20).ae(-25615652.66405658882 - 3.1415926535897932385j) + assert expint(1000000,0).ae(1./999999) + assert expint(0,2+3j).ae(-0.025019798357114678171 + 0.027980439405104419040j) + assert expint(-1,2+3j).ae(-0.022411973626262070419 + 0.038058922011377716932j) + assert expint(-1.5,0) == inf + +def test_trig_integrals(): + mp.dps = 30 + assert si(mpf(1)/1000000).ae('0.000000999999999999944444444444446111') + assert ci(mpf(1)/1000000).ae('-13.2382948930629912435014366276') + assert si(10**10).ae('1.5707963267075846569685111517747537') + assert ci(10**10).ae('-4.87506025174822653785729773959e-11') + assert si(10**100).ae(pi/2) + assert (ci(10**100)*10**100).ae('-0.372376123661276688262086695553') + assert si(-3) == -si(3) + assert ci(-3).ae(ci(3) + pi*j) + # Test complex structure + mp.dps = 15 + assert mp.ci(50).ae(-0.0056283863241163054402) + assert mp.ci(50+2j).ae(-0.018378282946133067149+0.070352808023688336193j) + assert mp.ci(20j).ae(1.28078263320282943611e7+1.5707963267949j) + assert mp.ci(-2+20j).ae(-4.050116856873293505e6+1.207476188206989909e7j) + assert mp.ci(-50+2j).ae(-0.0183782829461330671+3.0712398455661049023j) + assert mp.ci(-50).ae(-0.0056283863241163054+3.1415926535897932385j) + assert mp.ci(-50-2j).ae(-0.0183782829461330671-3.0712398455661049023j) + assert mp.ci(-2-20j).ae(-4.050116856873293505e6-1.207476188206989909e7j) + assert mp.ci(-20j).ae(1.28078263320282943611e7-1.5707963267949j) + assert mp.ci(50-2j).ae(-0.018378282946133067149-0.070352808023688336193j) + assert mp.si(50).ae(1.5516170724859358947) + assert mp.si(50+2j).ae(1.497884414277228461-0.017515007378437448j) + assert mp.si(20j).ae(1.2807826332028294459e7j) + assert mp.si(-2+20j).ae(-1.20747603112735722103e7-4.050116856873293554e6j) + assert mp.si(-50+2j).ae(-1.497884414277228461-0.017515007378437448j) + assert mp.si(-50).ae(-1.5516170724859358947) + assert mp.si(-50-2j).ae(-1.497884414277228461+0.017515007378437448j) + assert mp.si(-2-20j).ae(-1.20747603112735722103e7+4.050116856873293554e6j) + assert mp.si(-20j).ae(-1.2807826332028294459e7j) + assert mp.si(50-2j).ae(1.497884414277228461+0.017515007378437448j) + assert mp.chi(50j).ae(-0.0056283863241163054+1.5707963267948966192j) + assert mp.chi(-2+50j).ae(-0.0183782829461330671+1.6411491348185849554j) + assert mp.chi(-20).ae(1.28078263320282943611e7+3.1415926535898j) + assert mp.chi(-20-2j).ae(-4.050116856873293505e6+1.20747571696809187053e7j) + assert mp.chi(-2-50j).ae(-0.0183782829461330671-1.6411491348185849554j) + assert mp.chi(-50j).ae(-0.0056283863241163054-1.5707963267948966192j) + assert mp.chi(2-50j).ae(-0.0183782829461330671-1.500443518771208283j) + assert mp.chi(20-2j).ae(-4.050116856873293505e6-1.20747603112735722951e7j) + assert mp.chi(20).ae(1.2807826332028294361e7) + assert mp.chi(2+50j).ae(-0.0183782829461330671+1.500443518771208283j) + assert mp.shi(50j).ae(1.5516170724859358947j) + assert mp.shi(-2+50j).ae(0.017515007378437448+1.497884414277228461j) + assert mp.shi(-20).ae(-1.2807826332028294459e7) + assert mp.shi(-20-2j).ae(4.050116856873293554e6-1.20747603112735722103e7j) + assert mp.shi(-2-50j).ae(0.017515007378437448-1.497884414277228461j) + assert mp.shi(-50j).ae(-1.5516170724859358947j) + assert mp.shi(2-50j).ae(-0.017515007378437448-1.497884414277228461j) + assert mp.shi(20-2j).ae(-4.050116856873293554e6-1.20747603112735722103e7j) + assert mp.shi(20).ae(1.2807826332028294459e7) + assert mp.shi(2+50j).ae(-0.017515007378437448+1.497884414277228461j) + def ae(x,y,tol=1e-12): + return abs(x-y) <= abs(y)*tol + assert fp.ci(fp.inf) == 0 + assert ae(fp.ci(fp.ninf), fp.pi*1j) + assert ae(fp.si(fp.inf), fp.pi/2) + assert ae(fp.si(fp.ninf), -fp.pi/2) + assert fp.si(0) == 0 + assert ae(fp.ci(50), -0.0056283863241163054402) + assert ae(fp.ci(50+2j), -0.018378282946133067149+0.070352808023688336193j) + assert ae(fp.ci(20j), 1.28078263320282943611e7+1.5707963267949j) + assert ae(fp.ci(-2+20j), -4.050116856873293505e6+1.207476188206989909e7j) + assert ae(fp.ci(-50+2j), -0.0183782829461330671+3.0712398455661049023j) + assert ae(fp.ci(-50), -0.0056283863241163054+3.1415926535897932385j) + assert ae(fp.ci(-50-2j), -0.0183782829461330671-3.0712398455661049023j) + assert ae(fp.ci(-2-20j), -4.050116856873293505e6-1.207476188206989909e7j) + assert ae(fp.ci(-20j), 1.28078263320282943611e7-1.5707963267949j) + assert ae(fp.ci(50-2j), -0.018378282946133067149-0.070352808023688336193j) + assert ae(fp.si(50), 1.5516170724859358947) + assert ae(fp.si(50+2j), 1.497884414277228461-0.017515007378437448j) + assert ae(fp.si(20j), 1.2807826332028294459e7j) + assert ae(fp.si(-2+20j), -1.20747603112735722103e7-4.050116856873293554e6j) + assert ae(fp.si(-50+2j), -1.497884414277228461-0.017515007378437448j) + assert ae(fp.si(-50), -1.5516170724859358947) + assert ae(fp.si(-50-2j), -1.497884414277228461+0.017515007378437448j) + assert ae(fp.si(-2-20j), -1.20747603112735722103e7+4.050116856873293554e6j) + assert ae(fp.si(-20j), -1.2807826332028294459e7j) + assert ae(fp.si(50-2j), 1.497884414277228461+0.017515007378437448j) + assert ae(fp.chi(50j), -0.0056283863241163054+1.5707963267948966192j) + assert ae(fp.chi(-2+50j), -0.0183782829461330671+1.6411491348185849554j) + assert ae(fp.chi(-20), 1.28078263320282943611e7+3.1415926535898j) + assert ae(fp.chi(-20-2j), -4.050116856873293505e6+1.20747571696809187053e7j) + assert ae(fp.chi(-2-50j), -0.0183782829461330671-1.6411491348185849554j) + assert ae(fp.chi(-50j), -0.0056283863241163054-1.5707963267948966192j) + assert ae(fp.chi(2-50j), -0.0183782829461330671-1.500443518771208283j) + assert ae(fp.chi(20-2j), -4.050116856873293505e6-1.20747603112735722951e7j) + assert ae(fp.chi(20), 1.2807826332028294361e7) + assert ae(fp.chi(2+50j), -0.0183782829461330671+1.500443518771208283j) + assert ae(fp.shi(50j), 1.5516170724859358947j) + assert ae(fp.shi(-2+50j), 0.017515007378437448+1.497884414277228461j) + assert ae(fp.shi(-20), -1.2807826332028294459e7) + assert ae(fp.shi(-20-2j), 4.050116856873293554e6-1.20747603112735722103e7j) + assert ae(fp.shi(-2-50j), 0.017515007378437448-1.497884414277228461j) + assert ae(fp.shi(-50j), -1.5516170724859358947j) + assert ae(fp.shi(2-50j), -0.017515007378437448-1.497884414277228461j) + assert ae(fp.shi(20-2j), -4.050116856873293554e6-1.20747603112735722103e7j) + assert ae(fp.shi(20), 1.2807826332028294459e7) + assert ae(fp.shi(2+50j), -0.017515007378437448+1.497884414277228461j) + +def test_airy(): + mp.dps = 15 + assert (airyai(10)*10**10).ae(1.1047532552898687) + assert (airybi(10)/10**9).ae(0.45564115354822515) + assert (airyai(1000)*10**9158).ae(9.306933063179556004) + assert (airybi(1000)/10**9154).ae(5.4077118391949465477) + assert airyai(-1000).ae(0.055971895773019918842) + assert airybi(-1000).ae(-0.083264574117080633012) + assert (airyai(100+100j)*10**188).ae(2.9099582462207032076 + 2.353013591706178756j) + assert (airybi(100+100j)/10**185).ae(1.7086751714463652039 - 3.1416590020830804578j) + +def test_hyper_0f1(): + mp.dps = 15 + v = 8.63911136507950465 + assert hyper([],[(1,3)],1.5).ae(v) + assert hyper([],[1/3.],1.5).ae(v) + assert hyp0f1(1/3.,1.5).ae(v) + assert hyp0f1((1,3),1.5).ae(v) + # Asymptotic expansion + assert hyp0f1(3,1e9).ae('4.9679055380347771271e+27455') + assert hyp0f1(3,1e9j).ae('-2.1222788784457702157e+19410 + 5.0840597555401854116e+19410j') + +def test_hyper_1f1(): + mp.dps = 15 + v = 1.2917526488617656673 + assert hyper([(1,2)],[(3,2)],0.7).ae(v) + assert hyper([(1,2)],[(3,2)],0.7+0j).ae(v) + assert hyper([0.5],[(3,2)],0.7).ae(v) + assert hyper([0.5],[1.5],0.7).ae(v) + assert hyper([0.5],[(3,2)],0.7+0j).ae(v) + assert hyper([0.5],[1.5],0.7+0j).ae(v) + assert hyper([(1,2)],[1.5+0j],0.7).ae(v) + assert hyper([0.5+0j],[1.5],0.7).ae(v) + assert hyper([0.5+0j],[1.5+0j],0.7+0j).ae(v) + assert hyp1f1(0.5,1.5,0.7).ae(v) + assert hyp1f1((1,2),1.5,0.7).ae(v) + # Asymptotic expansion + assert hyp1f1(2,3,1e10).ae('2.1555012157015796988e+4342944809') + assert (hyp1f1(2,3,1e10j)*10**10).ae(-0.97501205020039745852 - 1.7462392454512132074j) + # Shouldn't use asymptotic expansion + assert hyp1f1(-2, 1, 10000).ae(49980001) + # Bug + assert hyp1f1(1j,fraction(1,3),0.415-69.739j).ae(25.857588206024346592 + 15.738060264515292063j) + +def test_hyper_2f1(): + mp.dps = 15 + v = 1.0652207633823291032 + assert hyper([(1,2), (3,4)], [2], 0.3).ae(v) + assert hyper([(1,2), 0.75], [2], 0.3).ae(v) + assert hyper([0.5, 0.75], [2.0], 0.3).ae(v) + assert hyper([0.5, 0.75], [2.0], 0.3+0j).ae(v) + assert hyper([0.5+0j, (3,4)], [2.0], 0.3+0j).ae(v) + assert hyper([0.5+0j, (3,4)], [2.0], 0.3).ae(v) + assert hyper([0.5, (3,4)], [2.0+0j], 0.3).ae(v) + assert hyper([0.5+0j, 0.75+0j], [2.0+0j], 0.3+0j).ae(v) + v = 1.09234681096223231717 + 0.18104859169479360380j + assert hyper([(1,2),0.75+j], [2], 0.5).ae(v) + assert hyper([0.5,0.75+j], [2.0], 0.5).ae(v) + assert hyper([0.5,0.75+j], [2.0], 0.5+0j).ae(v) + assert hyper([0.5,0.75+j], [2.0+0j], 0.5+0j).ae(v) + v = 0.9625 - 0.125j + assert hyper([(3,2),-1],[4], 0.1+j/3).ae(v) + assert hyper([1.5,-1.0],[4], 0.1+j/3).ae(v) + assert hyper([1.5,-1.0],[4+0j], 0.1+j/3).ae(v) + assert hyper([1.5+0j,-1.0+0j],[4+0j], 0.1+j/3).ae(v) + v = 1.02111069501693445001 - 0.50402252613466859521j + assert hyper([(2,10),(3,10)],[(4,10)],1.5).ae(v) + assert hyper([0.2,(3,10)],[0.4+0j],1.5).ae(v) + assert hyper([0.2,(3,10)],[0.4+0j],1.5+0j).ae(v) + v = 0.76922501362865848528 + 0.32640579593235886194j + assert hyper([(2,10),(3,10)],[(4,10)],4+2j).ae(v) + assert hyper([0.2,(3,10)],[0.4+0j],4+2j).ae(v) + assert hyper([0.2,(3,10)],[(4,10)],4+2j).ae(v) + +def test_hyper_2f1_hard(): + mp.dps = 15 + # Singular cases + assert hyp2f1(2,-1,-1,3).ae(7) + assert hyp2f1(2,-1,-1,3,eliminate_all=True).ae(0.25) + assert hyp2f1(2,-2,-2,3).ae(34) + assert hyp2f1(2,-2,-2,3,eliminate_all=True).ae(0.25) + assert hyp2f1(2,-2,-3,3) == 14 + assert hyp2f1(2,-3,-2,3) == inf + assert hyp2f1(2,-1.5,-1.5,3) == 0.25 + assert hyp2f1(1,2,3,0) == 1 + assert hyp2f1(0,1,0,0) == 1 + assert hyp2f1(0,0,0,0) == 1 + assert isnan(hyp2f1(1,1,0,0)) + assert hyp2f1(2,-1,-5, 0.25+0.25j).ae(1.1+0.1j) + assert hyp2f1(2,-5,-5, 0.25+0.25j, eliminate=False).ae(163./128 + 125./128*j) + assert hyp2f1(0.7235, -1, -5, 0.3).ae(1.04341) + assert hyp2f1(0.7235, -5, -5, 0.3, eliminate=False).ae(1.2939225017815903812) + assert hyp2f1(-1,-2,4,1) == 1.5 + assert hyp2f1(1,2,-3,1) == inf + assert hyp2f1(-2,-2,1,1) == 6 + assert hyp2f1(1,-2,-4,1).ae(5./3) + assert hyp2f1(0,-6,-4,1) == 1 + assert hyp2f1(0,-3,-4,1) == 1 + assert hyp2f1(0,0,0,1) == 1 + assert hyp2f1(1,0,0,1,eliminate=False) == 1 + assert hyp2f1(1,1,0,1) == inf + assert hyp2f1(1,-6,-4,1) == inf + assert hyp2f1(-7.2,-0.5,-4.5,1) == 0 + assert hyp2f1(-7.2,-1,-2,1).ae(-2.6) + assert hyp2f1(1,-0.5,-4.5, 1) == inf + assert hyp2f1(1,0.5,-4.5, 1) == -inf + # Check evaluation on / close to unit circle + z = exp(j*pi/3) + w = (nthroot(2,3)+1)*exp(j*pi/12)/nthroot(3,4)**3 + assert hyp2f1('1/2','1/6','1/3', z).ae(w) + assert hyp2f1('1/2','1/6','1/3', z.conjugate()).ae(w.conjugate()) + assert hyp2f1(0.25, (1,3), 2, '0.999').ae(1.06826449496030635) + assert hyp2f1(0.25, (1,3), 2, '1.001').ae(1.06867299254830309446-0.00001446586793975874j) + assert hyp2f1(0.25, (1,3), 2, -1).ae(0.96656584492524351673) + assert hyp2f1(0.25, (1,3), 2, j).ae(0.99041766248982072266+0.03777135604180735522j) + assert hyp2f1(2,3,5,'0.99').ae(27.699347904322690602) + assert hyp2f1((3,2),-0.5,3,'0.99').ae(0.68403036843911661388) + assert hyp2f1(2,3,5,1j).ae(0.37290667145974386127+0.59210004902748285917j) + assert fsum([hyp2f1((7,10),(2,3),(-1,2), 0.95*exp(j*k)) for k in range(1,15)]).ae(52.851400204289452922+6.244285013912953225j) + assert fsum([hyp2f1((7,10),(2,3),(-1,2), 1.05*exp(j*k)) for k in range(1,15)]).ae(54.506013786220655330-3.000118813413217097j) + assert fsum([hyp2f1((7,10),(2,3),(-1,2), exp(j*k)) for k in range(1,15)]).ae(55.792077935955314887+1.731986485778500241j) + assert hyp2f1(2,2.5,-3.25,0.999).ae(218373932801217082543180041.33) + # Branches + assert hyp2f1(1,1,2,1.01).ae(4.5595744415723676911-3.1104877758314784539j) + assert hyp2f1(1,1,2,1.01+0.1j).ae(2.4149427480552782484+1.4148224796836938829j) + assert hyp2f1(1,1,2,3+4j).ae(0.14576709331407297807+0.48379185417980360773j) + assert hyp2f1(1,1,2,4).ae(-0.27465307216702742285 - 0.78539816339744830962j) + assert hyp2f1(1,1,2,-4).ae(0.40235947810852509365) + # Other: + # Cancellation with a large parameter involved (bug reported on sage-devel) + assert hyp2f1(112, (51,10), (-9,10), -0.99999).ae(-1.6241361047970862961e-24, abs_eps=0, rel_eps=eps*16) + +def test_hyper_3f2_etc(): + assert hyper([1,2,3],[1.5,8],-1).ae(0.67108992351533333030) + assert hyper([1,2,3,4],[5,6,7], -1).ae(0.90232988035425506008) + assert hyper([1,2,3],[1.25,5], 1).ae(28.924181329701905701) + assert hyper([1,2,3,4],[5,6,7],5).ae(1.5192307344006649499-1.1529845225075537461j) + assert hyper([1,2,3,4,5],[6,7,8,9],-1).ae(0.96288759462882357253) + assert hyper([1,2,3,4,5],[6,7,8,9],1).ae(1.0428697385885855841) + assert hyper([1,2,3,4,5],[6,7,8,9],5).ae(1.33980653631074769423-0.07143405251029226699j) + assert hyper([1,2.79,3.08,4.37],[5.2,6.1,7.3],5).ae(1.0996321464692607231-1.7748052293979985001j) + assert hyper([1,1,1],[1,2],1) == inf + assert hyper([1,1,1],[2,(101,100)],1).ae(100.01621213528313220) + # slow -- covered by doctests + #assert hyper([1,1,1],[2,3],0.9999).ae(1.2897972005319693905) + +def test_hyper_u(): + mp.dps = 15 + assert hyperu(2,-3,0).ae(0.05) + assert hyperu(2,-3.5,0).ae(4./99) + assert hyperu(2,0,0) == 0.5 + assert hyperu(-5,1,0) == -120 + assert hyperu(-5,2,0) == inf + assert hyperu(-5,-2,0) == 0 + assert hyperu(7,7,3).ae(0.00014681269365593503986) #exp(3)*gammainc(-6,3) + assert hyperu(2,-3,4).ae(0.011836478100271995559) + assert hyperu(3,4,5).ae(1./125) + assert hyperu(2,3,0.0625) == 256 + assert hyperu(-1,2,0.25+0.5j) == -1.75+0.5j + assert hyperu(0.5,1.5,7.25).ae(2/sqrt(29)) + assert hyperu(2,6,pi).ae(0.55804439825913399130) + assert (hyperu((3,2),8,100+201j)*10**4).ae(-0.3797318333856738798 - 2.9974928453561707782j) + assert (hyperu((5,2),(-1,2),-5000)*10**10).ae(-5.6681877926881664678j) + # XXX: fails because of undetected cancellation in low level series code + # Alternatively: could use asymptotic series here, if convergence test + # tweaked back to recognize this one + #assert (hyperu((5,2),(-1,2),-500)*10**7).ae(-1.82526906001593252847j) + +def test_hyper_2f0(): + mp.dps = 15 + assert hyper([1,2],[],3) == hyp2f0(1,2,3) + assert hyp2f0(2,3,7).ae(0.0116108068639728714668 - 0.0073727413865865802130j) + assert hyp2f0(2,3,0) == 1 + assert hyp2f0(0,0,0) == 1 + assert hyp2f0(-1,-1,1).ae(2) + assert hyp2f0(-4,1,1.5).ae(62.5) + assert hyp2f0(-4,1,50).ae(147029801) + assert hyp2f0(-4,1,0.0001).ae(0.99960011997600240000) + assert hyp2f0(0.5,0.25,0.001).ae(1.0001251174078538115) + assert hyp2f0(0.5,0.25,3+4j).ae(0.85548875824755163518 + 0.21636041283392292973j) + # Important: cancellation check + assert hyp2f0((1,6),(5,6),-0.02371708245126284498).ae(0.996785723120804309) + # Should be exact; polynomial case + assert hyp2f0(-2,1,0.5+0.5j,zeroprec=200) == 0 + assert hyp2f0(1,-2,0.5+0.5j,zeroprec=200) == 0 + # There used to be a bug in thresholds that made one of the following hang + for d in [15, 50, 80]: + mp.dps = d + assert hyp2f0(1.5, 0.5, 0.009).ae('1.006867007239309717945323585695344927904000945829843527398772456281301440034218290443367270629519483 + 1.238277162240704919639384945859073461954721356062919829456053965502443570466701567100438048602352623e-46j') + +def test_hyper_1f2(): + mp.dps = 15 + assert hyper([1],[2,3],4) == hyp1f2(1,2,3,4) + a1,b1,b2 = (1,10),(2,3),1./16 + assert hyp1f2(a1,b1,b2,10).ae(298.7482725554557568) + assert hyp1f2(a1,b1,b2,100).ae(224128961.48602947604) + assert hyp1f2(a1,b1,b2,1000).ae(1.1669528298622675109e+27) + assert hyp1f2(a1,b1,b2,10000).ae(2.4780514622487212192e+86) + assert hyp1f2(a1,b1,b2,100000).ae(1.3885391458871523997e+274) + assert hyp1f2(a1,b1,b2,1000000).ae('9.8851796978960318255e+867') + assert hyp1f2(a1,b1,b2,10**7).ae('1.1505659189516303646e+2746') + assert hyp1f2(a1,b1,b2,10**8).ae('1.4672005404314334081e+8685') + assert hyp1f2(a1,b1,b2,10**20).ae('3.6888217332150976493e+8685889636') + assert hyp1f2(a1,b1,b2,10*j).ae(-16.163252524618572878 - 44.321567896480184312j) + assert hyp1f2(a1,b1,b2,100*j).ae(61938.155294517848171 + 637349.45215942348739j) + assert hyp1f2(a1,b1,b2,1000*j).ae(8455057657257695958.7 + 6261969266997571510.6j) + assert hyp1f2(a1,b1,b2,10000*j).ae(-8.9771211184008593089e+60 + 4.6550528111731631456e+59j) + assert hyp1f2(a1,b1,b2,100000*j).ae(2.6398091437239324225e+193 + 4.1658080666870618332e+193j) + assert hyp1f2(a1,b1,b2,1000000*j).ae('3.5999042951925965458e+613 + 1.5026014707128947992e+613j') + assert hyp1f2(a1,b1,b2,10**7*j).ae('-8.3208715051623234801e+1939 - 3.6752883490851869429e+1941j') + assert hyp1f2(a1,b1,b2,10**8*j).ae('2.0724195707891484454e+6140 - 1.3276619482724266387e+6141j') + assert hyp1f2(a1,b1,b2,10**20*j).ae('-1.1734497974795488504e+6141851462 + 1.1498106965385471542e+6141851462j') + +def test_hyper_2f3(): + mp.dps = 15 + assert hyper([1,2],[3,4,5],6) == hyp2f3(1,2,3,4,5,6) + a1,a2,b1,b2,b3 = (1,10),(2,3),(3,10), 2, 1./16 + # Check asymptotic expansion + assert hyp2f3(a1,a2,b1,b2,b3,10).ae(128.98207160698659976) + assert hyp2f3(a1,a2,b1,b2,b3,1000).ae(6.6309632883131273141e25) + assert hyp2f3(a1,a2,b1,b2,b3,10000).ae(4.6863639362713340539e84) + assert hyp2f3(a1,a2,b1,b2,b3,100000).ae(8.6632451236103084119e271) + assert hyp2f3(a1,a2,b1,b2,b3,10**6).ae('2.0291718386574980641e865') + assert hyp2f3(a1,a2,b1,b2,b3,10**7).ae('7.7639836665710030977e2742') + assert hyp2f3(a1,a2,b1,b2,b3,10**8).ae('3.2537462584071268759e8681') + assert hyp2f3(a1,a2,b1,b2,b3,10**20).ae('1.2966030542911614163e+8685889627') + assert hyp2f3(a1,a2,b1,b2,b3,10*j).ae(-18.551602185587547854 - 13.348031097874113552j) + assert hyp2f3(a1,a2,b1,b2,b3,100*j).ae(78634.359124504488695 + 74459.535945281973996j) + assert hyp2f3(a1,a2,b1,b2,b3,1000*j).ae(597682550276527901.59 - 65136194809352613.078j) + assert hyp2f3(a1,a2,b1,b2,b3,10000*j).ae(-1.1779696326238582496e+59 + 1.2297607505213133872e+59j) + assert hyp2f3(a1,a2,b1,b2,b3,100000*j).ae(2.9844228969804380301e+191 + 7.5587163231490273296e+190j) + assert hyp2f3(a1,a2,b1,b2,b3,1000000*j).ae('7.4859161049322370311e+610 - 2.8467477015940090189e+610j') + assert hyp2f3(a1,a2,b1,b2,b3,10**7*j).ae('-1.7477645579418800826e+1938 - 1.7606522995808116405e+1938j') + assert hyp2f3(a1,a2,b1,b2,b3,10**8*j).ae('-1.6932731942958401784e+6137 - 2.4521909113114629368e+6137j') + assert hyp2f3(a1,a2,b1,b2,b3,10**20*j).ae('-2.0988815677627225449e+6141851451 + 5.7708223542739208681e+6141851452j') + +def test_hyper_2f2(): + mp.dps = 15 + assert hyper([1,2],[3,4],5) == hyp2f2(1,2,3,4,5) + a1,a2,b1,b2 = (3,10),4,(1,2),1./16 + assert hyp2f2(a1,a2,b1,b2,10).ae(448225936.3377556696) + assert hyp2f2(a1,a2,b1,b2,10000).ae('1.2012553712966636711e+4358') + assert hyp2f2(a1,a2,b1,b2,-20000).ae(-0.04182343755661214626) + assert hyp2f2(a1,a2,b1,b2,10**20).ae('1.1148680024303263661e+43429448190325182840') + +def test_orthpoly(): + mp.dps = 15 + assert jacobi(-4,2,3,0.7).ae(22800./4913) + assert jacobi(3,2,4,5.5) == 4133.125 + assert jacobi(1.5,5/6.,4,0).ae(-1.0851951434075508417) + assert jacobi(-2, 1, 2, 4).ae(-0.16) + assert jacobi(2, -1, 2.5, 4).ae(34.59375) + #assert jacobi(2, -1, 2, 4) == 28.5 + assert legendre(5, 7) == 129367 + assert legendre(0.5,0).ae(0.53935260118837935667) + assert legendre(-1,-1) == 1 + assert legendre(0,-1) == 1 + assert legendre(0, 1) == 1 + assert legendre(1, -1) == -1 + assert legendre(7, 1) == 1 + assert legendre(7, -1) == -1 + assert legendre(8,1.5).ae(15457523./32768) + assert legendre(j,-j).ae(2.4448182735671431011 + 0.6928881737669934843j) + assert chebyu(5,1) == 6 + assert chebyt(3,2) == 26 + assert legendre(3.5,-1) == inf + assert legendre(4.5,-1) == -inf + assert legendre(3.5+1j,-1) == mpc(inf,inf) + assert legendre(4.5+1j,-1) == mpc(-inf,-inf) + assert laguerre(4, -2, 3).ae(-1.125) + assert laguerre(3, 1+j, 0.5).ae(0.2291666666666666667 + 2.5416666666666666667j) + +def test_hermite(): + mp.dps = 15 + assert hermite(-2, 0).ae(0.5) + assert hermite(-1, 0).ae(0.88622692545275801365) + assert hermite(0, 0).ae(1) + assert hermite(1, 0) == 0 + assert hermite(2, 0).ae(-2) + assert hermite(0, 2).ae(1) + assert hermite(1, 2).ae(4) + assert hermite(1, -2).ae(-4) + assert hermite(2, -2).ae(14) + assert hermite(0.5, 0).ae(0.69136733903629335053) + assert hermite(9, 0) == 0 + assert hermite(4,4).ae(3340) + assert hermite(3,4).ae(464) + assert hermite(-4,4).ae(0.00018623860287512396181) + assert hermite(-3,4).ae(0.0016540169879668766270) + assert hermite(9, 2.5j).ae(13638725j) + assert hermite(9, -2.5j).ae(-13638725j) + assert hermite(9, 100).ae(511078883759363024000) + assert hermite(9, -100).ae(-511078883759363024000) + assert hermite(9, 100j).ae(512922083920643024000j) + assert hermite(9, -100j).ae(-512922083920643024000j) + assert hermite(-9.5, 2.5j).ae(-2.9004951258126778174e-6 + 1.7601372934039951100e-6j) + assert hermite(-9.5, -2.5j).ae(-2.9004951258126778174e-6 - 1.7601372934039951100e-6j) + assert hermite(-9.5, 100).ae(1.3776300722767084162e-22, abs_eps=0, rel_eps=eps) + assert hermite(-9.5, -100).ae('1.3106082028470671626e4355') + assert hermite(-9.5, 100j).ae(-9.7900218581864768430e-23 - 9.7900218581864768430e-23j, abs_eps=0, rel_eps=eps) + assert hermite(-9.5, -100j).ae(-9.7900218581864768430e-23 + 9.7900218581864768430e-23j, abs_eps=0, rel_eps=eps) + assert hermite(2+3j, -1-j).ae(851.3677063883687676 - 1496.4373467871007997j) + +def test_gegenbauer(): + mp.dps = 15 + assert gegenbauer(1,2,3).ae(12) + assert gegenbauer(2,3,4).ae(381) + assert gegenbauer(0,0,0) == 0 + assert gegenbauer(2,-1,3) == 0 + assert gegenbauer(-7, 0.5, 3).ae(8989) + assert gegenbauer(1, -0.5, 3).ae(-3) + assert gegenbauer(1, -1.5, 3).ae(-9) + assert gegenbauer(1, -0.5, 3).ae(-3) + assert gegenbauer(-0.5, -0.5, 3).ae(-2.6383553159023906245) + assert gegenbauer(2+3j, 1-j, 3+4j).ae(14.880536623203696780 + 20.022029711598032898j) + #assert gegenbauer(-2, -0.5, 3).ae(-12) + +def test_legenp(): + mp.dps = 15 + assert legenp(2,0,4) == legendre(2,4) + assert legenp(-2, -1, 0.5).ae(0.43301270189221932338) + assert legenp(-2, -1, 0.5, type=3).ae(0.43301270189221932338j) + assert legenp(-2, 1, 0.5).ae(-0.86602540378443864676) + assert legenp(2+j, 3+4j, -j).ae(134742.98773236786148 + 429782.72924463851745j) + assert legenp(2+j, 3+4j, -j, type=3).ae(802.59463394152268507 - 251.62481308942906447j) + assert legenp(2,4,3).ae(0) + assert legenp(2,4,3,type=3).ae(0) + assert legenp(2,1,0.5).ae(-1.2990381056766579701) + assert legenp(2,1,0.5,type=3).ae(1.2990381056766579701j) + assert legenp(3,2,3).ae(-360) + assert legenp(3,3,3).ae(240j*2**0.5) + assert legenp(3,4,3).ae(0) + assert legenp(0,0.5,2).ae(0.52503756790433198939 - 0.52503756790433198939j) + assert legenp(-1,-0.5,2).ae(0.60626116232846498110 + 0.60626116232846498110j) + assert legenp(-2,0.5,2).ae(1.5751127037129959682 - 1.5751127037129959682j) + assert legenp(-2,0.5,-0.5).ae(-0.85738275810499171286) + +def test_legenq(): + mp.dps = 15 + f = legenq + # Evaluation at poles + assert isnan(f(3,2,1)) + assert isnan(f(3,2,-1)) + assert isnan(f(3,2,1,type=3)) + assert isnan(f(3,2,-1,type=3)) + # Evaluation at 0 + assert f(0,1,0,type=2).ae(-1) + assert f(-2,2,0,type=2,zeroprec=200).ae(0) + assert f(1.5,3,0,type=2).ae(-2.2239343475841951023) + assert f(0,1,0,type=3).ae(j) + assert f(-2,2,0,type=3,zeroprec=200).ae(0) + assert f(1.5,3,0,type=3).ae(2.2239343475841951022*(1-1j)) + # Standard case, degree 0 + assert f(0,0,-1.5).ae(-0.8047189562170501873 + 1.5707963267948966192j) + assert f(0,0,-0.5).ae(-0.54930614433405484570) + assert f(0,0,0,zeroprec=200).ae(0) + assert f(0,0,0.5).ae(0.54930614433405484570) + assert f(0,0,1.5).ae(0.8047189562170501873 - 1.5707963267948966192j) + assert f(0,0,-1.5,type=3).ae(-0.80471895621705018730) + assert f(0,0,-0.5,type=3).ae(-0.5493061443340548457 - 1.5707963267948966192j) + assert f(0,0,0,type=3).ae(-1.5707963267948966192j) + assert f(0,0,0.5,type=3).ae(0.5493061443340548457 - 1.5707963267948966192j) + assert f(0,0,1.5,type=3).ae(0.80471895621705018730) + # Standard case, degree 1 + assert f(1,0,-1.5).ae(0.2070784343255752810 - 2.3561944901923449288j) + assert f(1,0,-0.5).ae(-0.72534692783297257715) + assert f(1,0,0).ae(-1) + assert f(1,0,0.5).ae(-0.72534692783297257715) + assert f(1,0,1.5).ae(0.2070784343255752810 - 2.3561944901923449288j) + # Standard case, degree 2 + assert f(2,0,-1.5).ae(-0.0635669991240192885 + 4.5160394395353277803j) + assert f(2,0,-0.5).ae(0.81866326804175685571) + assert f(2,0,0,zeroprec=200).ae(0) + assert f(2,0,0.5).ae(-0.81866326804175685571) + assert f(2,0,1.5).ae(0.0635669991240192885 - 4.5160394395353277803j) + # Misc orders and degrees + assert f(2,3,1.5,type=2).ae(-5.7243340223994616228j) + assert f(2,3,1.5,type=3).ae(-5.7243340223994616228) + assert f(2,3,0.5,type=2).ae(-12.316805742712016310) + assert f(2,3,0.5,type=3).ae(-12.316805742712016310j) + assert f(2,3,-1.5,type=2).ae(-5.7243340223994616228j) + assert f(2,3,-1.5,type=3).ae(5.7243340223994616228) + assert f(2,3,-0.5,type=2).ae(-12.316805742712016310) + assert f(2,3,-0.5,type=3).ae(-12.316805742712016310j) + assert f(2+3j, 3+4j, 0.5, type=3).ae(0.0016119404873235186807 - 0.0005885900510718119836j) + assert f(2+3j, 3+4j, -1.5, type=3).ae(0.008451400254138808670 + 0.020645193304593235298j) + assert f(-2.5,1,-1.5).ae(3.9553395527435335749j) + assert f(-2.5,1,-0.5).ae(1.9290561746445456908) + assert f(-2.5,1,0).ae(1.2708196271909686299) + assert f(-2.5,1,0.5).ae(-0.31584812990742202869) + assert f(-2.5,1,1.5).ae(-3.9553395527435335742 + 0.2993235655044701706j) + assert f(-2.5,1,-1.5,type=3).ae(0.29932356550447017254j) + assert f(-2.5,1,-0.5,type=3).ae(-0.3158481299074220287 - 1.9290561746445456908j) + assert f(-2.5,1,0,type=3).ae(1.2708196271909686292 - 1.2708196271909686299j) + assert f(-2.5,1,0.5,type=3).ae(1.9290561746445456907 + 0.3158481299074220287j) + assert f(-2.5,1,1.5,type=3).ae(-0.29932356550447017254) + +def test_agm(): + mp.dps = 15 + assert agm(0,0) == 0 + assert agm(0,1) == 0 + assert agm(1,1) == 1 + assert agm(7,7) == 7 + assert agm(j,j) == j + assert (1/agm(1,sqrt(2))).ae(0.834626841674073186) + assert agm(1,2).ae(1.4567910310469068692) + assert agm(1,3).ae(1.8636167832448965424) + assert agm(1,j).ae(0.599070117367796104+0.599070117367796104j) + assert agm(2) == agm(1,2) + assert agm(-3,4).ae(0.63468509766550907+1.3443087080896272j) + +def test_gammainc(): + mp.dps = 15 + assert gammainc(2,5).ae(6*exp(-5)) + assert gammainc(2,0,5).ae(1-6*exp(-5)) + assert gammainc(2,3,5).ae(-6*exp(-5)+4*exp(-3)) + assert gammainc(-2.5,-0.5).ae(-0.9453087204829418812-5.3164237738936178621j) + assert gammainc(0,2,4).ae(0.045121158298212213088) + assert gammainc(0,3).ae(0.013048381094197037413) + assert gammainc(0,2+j,1-j).ae(0.00910653685850304839-0.22378752918074432574j) + assert gammainc(0,1-j).ae(0.00028162445198141833+0.17932453503935894015j) + assert gammainc(3,4,5,True).ae(0.11345128607046320253) + assert gammainc(3.5,0,inf).ae(gamma(3.5)) + assert gammainc(-150.5,500).ae('6.9825435345798951153e-627') + assert gammainc(-150.5,800).ae('4.6885137549474089431e-788') + assert gammainc(-3.5, -20.5).ae(0.27008820585226911 - 1310.31447140574997636j) + assert gammainc(-3.5, -200.5).ae(0.27008820585226911 - 5.3264597096208368435e76j) # XXX real part + assert gammainc(0,0,2) == inf + assert gammainc(1,b=1).ae(0.6321205588285576784) + assert gammainc(3,2,2) == 0 + assert gammainc(2,3+j,3-j).ae(-0.28135485191849314194j) + assert gammainc(4+0j,1).ae(5.8860710587430771455) + # GH issue #301 + assert gammainc(-1,-1).ae(-0.8231640121031084799 + 3.1415926535897932385j) + assert gammainc(-2,-1).ae(1.7707229202810768576 - 1.5707963267948966192j) + assert gammainc(-3,-1).ae(-1.4963349162467073643 + 0.5235987755982988731j) + assert gammainc(-4,-1).ae(1.05365418617643814992 - 0.13089969389957471827j) + # Regularized upper gamma + assert isnan(gammainc(0, 0, regularized=True)) + assert gammainc(-1, 0, regularized=True) == inf + assert gammainc(1, 0, regularized=True) == 1 + assert gammainc(0, 5, regularized=True) == 0 + assert gammainc(0, 2+3j, regularized=True) == 0 + assert gammainc(0, 5000, regularized=True) == 0 + assert gammainc(0, 10**30, regularized=True) == 0 + assert gammainc(-1, 5, regularized=True) == 0 + assert gammainc(-1, 5000, regularized=True) == 0 + assert gammainc(-1, 10**30, regularized=True) == 0 + assert gammainc(-1, -5, regularized=True) == 0 + assert gammainc(-1, -5000, regularized=True) == 0 + assert gammainc(-1, -10**30, regularized=True) == 0 + assert gammainc(-1, 3+4j, regularized=True) == 0 + assert gammainc(1, 5, regularized=True).ae(exp(-5)) + assert gammainc(1, 5000, regularized=True).ae(exp(-5000)) + assert gammainc(1, 10**30, regularized=True).ae(exp(-10**30)) + assert gammainc(1, 3+4j, regularized=True).ae(exp(-3-4j)) + assert gammainc(-1000000,2).ae('1.3669297209397347754e-301037', abs_eps=0, rel_eps=8*eps) + assert gammainc(-1000000,2,regularized=True) == 0 + assert gammainc(-1000000,3+4j).ae('-1.322575609404222361e-698979 - 4.9274570591854533273e-698978j', abs_eps=0, rel_eps=8*eps) + assert gammainc(-1000000,3+4j,regularized=True) == 0 + assert gammainc(2+3j, 4+5j, regularized=True).ae(0.085422013530993285774-0.052595379150390078503j) + assert gammainc(1000j, 1000j, regularized=True).ae(0.49702647628921131761 + 0.00297355675013575341j) + # Generalized + assert gammainc(3,4,2) == -gammainc(3,2,4) + assert gammainc(4, 2, 3).ae(1.2593494302978947396) + assert gammainc(4, 2, 3, regularized=True).ae(0.20989157171631578993) + assert gammainc(0, 2, 3).ae(0.035852129613864082155) + assert gammainc(0, 2, 3, regularized=True) == 0 + assert gammainc(-1, 2, 3).ae(0.015219822548487616132) + assert gammainc(-1, 2, 3, regularized=True) == 0 + assert gammainc(0, 2, 3).ae(0.035852129613864082155) + assert gammainc(0, 2, 3, regularized=True) == 0 + # Should use upper gammas + assert gammainc(5, 10000, 12000).ae('1.1359381951461801687e-4327', abs_eps=0, rel_eps=8*eps) + # Should use lower gammas + assert gammainc(10000, 2, 3).ae('8.1244514125995785934e4765') + # GH issue 306 + assert gammainc(3,-1-1j) == 0 + assert gammainc(3,-1+1j) == 0 + assert gammainc(2,-1) == 0 + assert gammainc(2,-1+0j) == 0 + assert gammainc(2+0j,-1) == 0 + +def test_gammainc_expint_n(): + # These tests are intended to check all cases of the low-level code + # for upper gamma and expint with small integer index. + # Need to cover positive/negative arguments; small/large/huge arguments + # for both positive and negative indices, as well as indices 0 and 1 + # which may be special-cased + mp.dps = 15 + assert expint(-3,3.5).ae(0.021456366563296693987) + assert expint(-2,3.5).ae(0.014966633183073309405) + assert expint(-1,3.5).ae(0.011092916359219041088) + assert expint(0,3.5).ae(0.0086278238349481430685) + assert expint(1,3.5).ae(0.0069701398575483929193) + assert expint(2,3.5).ae(0.0058018939208991255223) + assert expint(3,3.5).ae(0.0049453773495857807058) + assert expint(-3,-3.5).ae(-4.6618170604073311319) + assert expint(-2,-3.5).ae(-5.5996974157555515963) + assert expint(-1,-3.5).ae(-6.7582555017739415818) + assert expint(0,-3.5).ae(-9.4615577024835182145) + assert expint(1,-3.5).ae(-13.925353995152335292 - 3.1415926535897932385j) + assert expint(2,-3.5).ae(-15.62328702434085977 - 10.995574287564276335j) + assert expint(3,-3.5).ae(-10.783026313250347722 - 19.242255003237483586j) + assert expint(-3,350).ae(2.8614825451252838069e-155, abs_eps=0, rel_eps=8*eps) + assert expint(-2,350).ae(2.8532837224504675901e-155, abs_eps=0, rel_eps=8*eps) + assert expint(-1,350).ae(2.8451316155828634555e-155, abs_eps=0, rel_eps=8*eps) + assert expint(0,350).ae(2.8370258275042797989e-155, abs_eps=0, rel_eps=8*eps) + assert expint(1,350).ae(2.8289659656701459404e-155, abs_eps=0, rel_eps=8*eps) + assert expint(2,350).ae(2.8209516419468505006e-155, abs_eps=0, rel_eps=8*eps) + assert expint(3,350).ae(2.8129824725501272171e-155, abs_eps=0, rel_eps=8*eps) + assert expint(-3,-350).ae(-2.8528796154044839443e+149) + assert expint(-2,-350).ae(-2.8610072121701264351e+149) + assert expint(-1,-350).ae(-2.8691813842677537647e+149) + assert expint(0,-350).ae(-2.8774025343659421709e+149) + u = expint(1,-350) + assert u.ae(-2.8856710698020863568e+149) + assert u.imag.ae(-3.1415926535897932385) + u = expint(2,-350) + assert u.ae(-2.8939874026504650534e+149) + assert u.imag.ae(-1099.5574287564276335) + u = expint(3,-350) + assert u.ae(-2.9023519497915044349e+149) + assert u.imag.ae(-192422.55003237483586) + assert expint(-3,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) + assert expint(-2,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) + assert expint(-1,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) + assert expint(0,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) + assert expint(1,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) + assert expint(2,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) + assert expint(3,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) + assert expint(-3,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871') + assert expint(-2,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871') + assert expint(-1,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871') + assert expint(0,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871') + u = expint(1,-350000000000000000000000) + assert u.ae('-3.7805306852415755699e+152003068666138139677871') + assert u.imag.ae(-3.1415926535897932385) + u = expint(2,-350000000000000000000000) + assert u.imag.ae(-1.0995574287564276335e+24) + assert u.ae('-3.7805306852415755699e+152003068666138139677871') + u = expint(3,-350000000000000000000000) + assert u.imag.ae(-1.9242255003237483586e+47) + assert u.ae('-3.7805306852415755699e+152003068666138139677871') + # Small case; no branch cut + assert gammainc(-3,3.5).ae(0.00010020262545203707109) + assert gammainc(-2,3.5).ae(0.00040370427343557393517) + assert gammainc(-1,3.5).ae(0.0016576839773997501492) + assert gammainc(0,3.5).ae(0.0069701398575483929193) + assert gammainc(1,3.5).ae(0.03019738342231850074) + assert gammainc(2,3.5).ae(0.13588822540043325333) + assert gammainc(3,3.5).ae(0.64169439772426814072) + # Small case; with branch cut + assert gammainc(-3,-3.5).ae(0.03595832954467563286 + 0.52359877559829887308j) + assert gammainc(-2,-3.5).ae(-0.88024704597962022221 - 1.5707963267948966192j) + assert gammainc(-1,-3.5).ae(4.4637962926688170771 + 3.1415926535897932385j) + assert gammainc(0,-3.5).ae(-13.925353995152335292 - 3.1415926535897932385j) + assert gammainc(1,-3.5).ae(33.115451958692313751) + assert gammainc(2,-3.5).ae(-82.788629896730784377) + assert gammainc(3,-3.5).ae(240.08702670051927469) + # Asymptotic case; no branch cut + assert gammainc(-3,350).ae(6.5424095113340358813e-163, abs_eps=0, rel_eps=8*eps) + assert gammainc(-2,350).ae(2.296312222489899769e-160, abs_eps=0, rel_eps=8*eps) + assert gammainc(-1,350).ae(8.059861834133858573e-158, abs_eps=0, rel_eps=8*eps) + assert gammainc(0,350).ae(2.8289659656701459404e-155, abs_eps=0, rel_eps=8*eps) + assert gammainc(1,350).ae(9.9295903962649792963e-153, abs_eps=0, rel_eps=8*eps) + assert gammainc(2,350).ae(3.485286229089007733e-150, abs_eps=0, rel_eps=8*eps) + assert gammainc(3,350).ae(1.2233453960006379793e-147, abs_eps=0, rel_eps=8*eps) + # Asymptotic case; branch cut + u = gammainc(-3,-350) + assert u.ae(6.7889565783842895085e+141) + assert u.imag.ae(0.52359877559829887308) + u = gammainc(-2,-350) + assert u.ae(-2.3692668977889832121e+144) + assert u.imag.ae(-1.5707963267948966192) + u = gammainc(-1,-350) + assert u.ae(8.2685354361441858669e+146) + assert u.imag.ae(3.1415926535897932385) + u = gammainc(0,-350) + assert u.ae(-2.8856710698020863568e+149) + assert u.imag.ae(-3.1415926535897932385) + u = gammainc(1,-350) + assert u.ae(1.0070908870280797598e+152) + assert u.imag == 0 + u = gammainc(2,-350) + assert u.ae(-3.5147471957279983618e+154) + assert u.imag == 0 + u = gammainc(3,-350) + assert u.ae(1.2266568422179417091e+157) + assert u.imag == 0 + # Extreme asymptotic case + assert gammainc(-3,350000000000000000000000).ae('5.0362468738874738859e-152003068666138139677990', abs_eps=0, rel_eps=8*eps) + assert gammainc(-2,350000000000000000000000).ae('1.7626864058606158601e-152003068666138139677966', abs_eps=0, rel_eps=8*eps) + assert gammainc(-1,350000000000000000000000).ae('6.1694024205121555102e-152003068666138139677943', abs_eps=0, rel_eps=8*eps) + assert gammainc(0,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) + assert gammainc(1,350000000000000000000000).ae('7.5575179651273905e-152003068666138139677896', abs_eps=0, rel_eps=8*eps) + assert gammainc(2,350000000000000000000000).ae('2.645131287794586675e-152003068666138139677872', abs_eps=0, rel_eps=8*eps) + assert gammainc(3,350000000000000000000000).ae('9.2579595072810533625e-152003068666138139677849', abs_eps=0, rel_eps=8*eps) + u = gammainc(-3,-350000000000000000000000) + assert u.ae('8.8175642804468234866e+152003068666138139677800') + assert u.imag.ae(0.52359877559829887308) + u = gammainc(-2,-350000000000000000000000) + assert u.ae('-3.0861474981563882203e+152003068666138139677824') + assert u.imag.ae(-1.5707963267948966192) + u = gammainc(-1,-350000000000000000000000) + assert u.ae('1.0801516243547358771e+152003068666138139677848') + assert u.imag.ae(3.1415926535897932385) + u = gammainc(0,-350000000000000000000000) + assert u.ae('-3.7805306852415755699e+152003068666138139677871') + assert u.imag.ae(-3.1415926535897932385) + assert gammainc(1,-350000000000000000000000).ae('1.3231857398345514495e+152003068666138139677895') + assert gammainc(2,-350000000000000000000000).ae('-4.6311500894209300731e+152003068666138139677918') + assert gammainc(3,-350000000000000000000000).ae('1.6209025312973255256e+152003068666138139677942') + +def test_incomplete_beta(): + mp.dps = 15 + assert betainc(-2,-3,0.5,0.75).ae(63.4305673311255413583969) + assert betainc(4.5,0.5+2j,2.5,6).ae(0.2628801146130621387903065 + 0.5162565234467020592855378j) + assert betainc(4,5,0,6).ae(90747.77142857142857142857) + +def test_erf(): + mp.dps = 15 + assert erf(0) == 0 + assert erf(1).ae(0.84270079294971486934) + assert erf(3+4j).ae(-120.186991395079444098 - 27.750337293623902498j) + assert erf(-4-3j).ae(-0.99991066178539168236 + 0.00004972026054496604j) + assert erf(pi).ae(0.99999112385363235839) + assert erf(1j).ae(1.6504257587975428760j) + assert erf(-1j).ae(-1.6504257587975428760j) + assert isinstance(erf(1), mpf) + assert isinstance(erf(-1), mpf) + assert isinstance(erf(0), mpf) + assert isinstance(erf(0j), mpc) + assert erf(inf) == 1 + assert erf(-inf) == -1 + assert erfi(0) == 0 + assert erfi(1/pi).ae(0.371682698493894314) + assert erfi(inf) == inf + assert erfi(-inf) == -inf + assert erf(1+0j) == erf(1) + assert erfc(1+0j) == erfc(1) + assert erf(0.2+0.5j).ae(1 - erfc(0.2+0.5j)) + assert erfc(0) == 1 + assert erfc(1).ae(1-erf(1)) + assert erfc(-1).ae(1-erf(-1)) + assert erfc(1/pi).ae(1-erf(1/pi)) + assert erfc(-10) == 2 + assert erfc(-1000000) == 2 + assert erfc(-inf) == 2 + assert erfc(inf) == 0 + assert isnan(erfc(nan)) + assert (erfc(10**4)*mpf(10)**43429453).ae('3.63998738656420') + assert erf(8+9j).ae(-1072004.2525062051158 + 364149.91954310255423j) + assert erfc(8+9j).ae(1072005.2525062051158 - 364149.91954310255423j) + assert erfc(-8-9j).ae(-1072003.2525062051158 + 364149.91954310255423j) + mp.dps = 50 + # This one does not use the asymptotic series + assert (erfc(10)*10**45).ae('2.0884875837625447570007862949577886115608181193212') + # This one does + assert (erfc(50)*10**1088).ae('2.0709207788416560484484478751657887929322509209954') + mp.dps = 15 + assert str(erfc(10**50)) == '3.66744826532555e-4342944819032518276511289189166050822943970058036665661144537831658646492088707747292249493384317534' + assert erfinv(0) == 0 + assert erfinv(0.5).ae(0.47693627620446987338) + assert erfinv(-0.5).ae(-0.47693627620446987338) + assert erfinv(1) == inf + assert erfinv(-1) == -inf + assert erf(erfinv(0.95)).ae(0.95) + assert erf(erfinv(0.999999999995)).ae(0.999999999995) + assert erf(erfinv(-0.999999999995)).ae(-0.999999999995) + mp.dps = 50 + assert erf(erfinv('0.99999999999999999999999999999995')).ae('0.99999999999999999999999999999995') + assert erf(erfinv('0.999999999999999999999999999999995')).ae('0.999999999999999999999999999999995') + assert erf(erfinv('-0.999999999999999999999999999999995')).ae('-0.999999999999999999999999999999995') + mp.dps = 15 + # Complex asymptotic expansions + v = erfc(50j) + assert v.real == 1 + assert v.imag.ae('-6.1481820666053078736e+1083') + assert erfc(-100+5j).ae(2) + assert (erfc(100+5j)*10**4335).ae(2.3973567853824133572 - 3.9339259530609420597j) + assert erfc(100+100j).ae(0.00065234366376857698698 - 0.0039357263629214118437j) + +def test_pdf(): + mp.dps = 15 + assert npdf(-inf) == 0 + assert npdf(inf) == 0 + assert npdf(5,0,2).ae(npdf(5+4,4,2)) + assert quadts(lambda x: npdf(x,-0.5,0.8), [-inf, inf]) == 1 + assert ncdf(0) == 0.5 + assert ncdf(3,3) == 0.5 + assert ncdf(-inf) == 0 + assert ncdf(inf) == 1 + assert ncdf(10) == 1 + # Verify that this is computed accurately + assert (ncdf(-10)*10**24).ae(7.619853024160526) + +def test_lambertw(): + mp.dps = 15 + assert lambertw(0) == 0 + assert lambertw(0+0j) == 0 + assert lambertw(inf) == inf + assert isnan(lambertw(nan)) + assert lambertw(inf,1).real == inf + assert lambertw(inf,1).imag.ae(2*pi) + assert lambertw(-inf,1).real == inf + assert lambertw(-inf,1).imag.ae(3*pi) + assert lambertw(0,-1) == -inf + assert lambertw(0,1) == -inf + assert lambertw(0,3) == -inf + assert lambertw(e).ae(1) + assert lambertw(1).ae(0.567143290409783873) + assert lambertw(-pi/2).ae(j*pi/2) + assert lambertw(-log(2)/2).ae(-log(2)) + assert lambertw(0.25).ae(0.203888354702240164) + assert lambertw(-0.25).ae(-0.357402956181388903) + assert lambertw(-1./10000,0).ae(-0.000100010001500266719) + assert lambertw(-0.25,-1).ae(-2.15329236411034965) + assert lambertw(0.25,-1).ae(-3.00899800997004620-4.07652978899159763j) + assert lambertw(-0.25,-1).ae(-2.15329236411034965) + assert lambertw(0.25,1).ae(-3.00899800997004620+4.07652978899159763j) + assert lambertw(-0.25,1).ae(-3.48973228422959210+7.41405453009603664j) + assert lambertw(-4).ae(0.67881197132094523+1.91195078174339937j) + assert lambertw(-4,1).ae(-0.66743107129800988+7.76827456802783084j) + assert lambertw(-4,-1).ae(0.67881197132094523-1.91195078174339937j) + assert lambertw(1000).ae(5.24960285240159623) + assert lambertw(1000,1).ae(4.91492239981054535+5.44652615979447070j) + assert lambertw(1000,-1).ae(4.91492239981054535-5.44652615979447070j) + assert lambertw(1000,5).ae(3.5010625305312892+29.9614548941181328j) + assert lambertw(3+4j).ae(1.281561806123775878+0.533095222020971071j) + assert lambertw(-0.4+0.4j).ae(-0.10396515323290657+0.61899273315171632j) + assert lambertw(3+4j,1).ae(-0.11691092896595324+5.61888039871282334j) + assert lambertw(3+4j,-1).ae(0.25856740686699742-3.85211668616143559j) + assert lambertw(-0.5,-1).ae(-0.794023632344689368-0.770111750510379110j) + assert lambertw(-1./10000,1).ae(-11.82350837248724344+6.80546081842002101j) + assert lambertw(-1./10000,-1).ae(-11.6671145325663544) + assert lambertw(-1./10000,-2).ae(-11.82350837248724344-6.80546081842002101j) + assert lambertw(-1./100000,4).ae(-14.9186890769540539+26.1856750178782046j) + assert lambertw(-1./100000,5).ae(-15.0931437726379218666+32.5525721210262290086j) + assert lambertw((2+j)/10).ae(0.173704503762911669+0.071781336752835511j) + assert lambertw((2+j)/10,1).ae(-3.21746028349820063+4.56175438896292539j) + assert lambertw((2+j)/10,-1).ae(-3.03781405002993088-3.53946629633505737j) + assert lambertw((2+j)/10,4).ae(-4.6878509692773249+23.8313630697683291j) + assert lambertw(-(2+j)/10).ae(-0.226933772515757933-0.164986470020154580j) + assert lambertw(-(2+j)/10,1).ae(-2.43569517046110001+0.76974067544756289j) + assert lambertw(-(2+j)/10,-1).ae(-3.54858738151989450-6.91627921869943589j) + assert lambertw(-(2+j)/10,4).ae(-4.5500846928118151+20.6672982215434637j) + mp.dps = 50 + assert lambertw(pi).ae('1.073658194796149172092178407024821347547745350410314531') + mp.dps = 15 + # Former bug in generated branch + assert lambertw(-0.5+0.002j).ae(-0.78917138132659918344 + 0.76743539379990327749j) + assert lambertw(-0.5-0.002j).ae(-0.78917138132659918344 - 0.76743539379990327749j) + assert lambertw(-0.448+0.4j).ae(-0.11855133765652382241 + 0.66570534313583423116j) + assert lambertw(-0.448-0.4j).ae(-0.11855133765652382241 - 0.66570534313583423116j) + assert lambertw(-0.65475+0.0001j).ae(-0.61053421111385310898+1.0396534993944097723803j) + # Huge branch index + w = lambertw(1,10**20) + assert w.real.ae(-47.889578926290259164) + assert w.imag.ae(6.2831853071795864769e+20) + +def test_lambertw_hard(): + def check(x,y): + y = convert(y) + type_ok = True + if isinstance(y, mpf): + type_ok = isinstance(x, mpf) + real_ok = abs(x.real-y.real) <= abs(y.real)*8*eps + imag_ok = abs(x.imag-y.imag) <= abs(y.imag)*8*eps + #print x, y, abs(x.real-y.real), abs(x.imag-y.imag) + return real_ok and imag_ok + # Evaluation near 0 + mp.dps = 15 + assert check(lambertw(1e-10), 9.999999999000000000e-11) + assert check(lambertw(-1e-10), -1.000000000100000000e-10) + assert check(lambertw(1e-10j), 9.999999999999999999733e-21 + 9.99999999999999999985e-11j) + assert check(lambertw(-1e-10j), 9.999999999999999999733e-21 - 9.99999999999999999985e-11j) + assert check(lambertw(1e-10,1), -26.303186778379041559 + 3.265093911703828397j) + assert check(lambertw(-1e-10,1), -26.326236166739163892 + 6.526183280686333315j) + assert check(lambertw(1e-10j,1), -26.312931726911421551 + 4.896366881798013421j) + assert check(lambertw(-1e-10j,1), -26.297238779529035066 + 1.632807161345576513j) + assert check(lambertw(1e-10,-1), -26.303186778379041559 - 3.265093911703828397j) + assert check(lambertw(-1e-10,-1), -26.295238819246925694) + assert check(lambertw(1e-10j,-1), -26.297238779529035028 - 1.6328071613455765135j) + assert check(lambertw(-1e-10j,-1), -26.312931726911421551 - 4.896366881798013421j) + # Test evaluation very close to the branch point -1/e + # on the -1, 0, and 1 branches + add = lambda x, y: fadd(x,y,exact=True) + sub = lambda x, y: fsub(x,y,exact=True) + addj = lambda x, y: fadd(x,fmul(y,1j,exact=True),exact=True) + subj = lambda x, y: fadd(x,fmul(y,-1j,exact=True),exact=True) + mp.dps = 1500 + a = -1/e + 10*eps + d3 = mpf('1e-3') + d10 = mpf('1e-10') + d20 = mpf('1e-20') + d40 = mpf('1e-40') + d80 = mpf('1e-80') + d300 = mpf('1e-300') + d1000 = mpf('1e-1000') + mp.dps = 15 + # ---- Branch 0 ---- + # -1/e + eps + assert check(lambertw(add(a,d3)), -0.92802015005456704876) + assert check(lambertw(add(a,d10)), -0.99997668374140088071) + assert check(lambertw(add(a,d20)), -0.99999999976683560186) + assert lambertw(add(a,d40)) == -1 + assert lambertw(add(a,d80)) == -1 + assert lambertw(add(a,d300)) == -1 + assert lambertw(add(a,d1000)) == -1 + # -1/e - eps + assert check(lambertw(sub(a,d3)), -0.99819016149860989001+0.07367191188934638577j) + assert check(lambertw(sub(a,d10)), -0.9999999998187812114595992+0.0000233164398140346109194j) + assert check(lambertw(sub(a,d20)), -0.99999999999999999998187+2.331643981597124203344e-10j) + assert check(lambertw(sub(a,d40)), -1.0+2.33164398159712420336e-20j) + assert check(lambertw(sub(a,d80)), -1.0+2.33164398159712420336e-40j) + assert check(lambertw(sub(a,d300)), -1.0+2.33164398159712420336e-150j) + assert check(lambertw(sub(a,d1000)), mpc(-1,'2.33164398159712420336e-500')) + # -1/e + eps*j + assert check(lambertw(addj(a,d3)), -0.94790387486938526634+0.05036819639190132490j) + assert check(lambertw(addj(a,d10)), -0.9999835127872943680999899+0.0000164870314895821225256j) + assert check(lambertw(addj(a,d20)), -0.999999999835127872929987+1.64872127051890935830e-10j) + assert check(lambertw(addj(a,d40)), -0.9999999999999999999835+1.6487212707001281468305e-20j) + assert check(lambertw(addj(a,d80)), -1.0 + 1.64872127070012814684865e-40j) + assert check(lambertw(addj(a,d300)), -1.0 + 1.64872127070012814684865e-150j) + assert check(lambertw(addj(a,d1000)), mpc(-1.0,'1.64872127070012814684865e-500')) + # -1/e - eps*j + assert check(lambertw(subj(a,d3)), -0.94790387486938526634-0.05036819639190132490j) + assert check(lambertw(subj(a,d10)), -0.9999835127872943680999899-0.0000164870314895821225256j) + assert check(lambertw(subj(a,d20)), -0.999999999835127872929987-1.64872127051890935830e-10j) + assert check(lambertw(subj(a,d40)), -0.9999999999999999999835-1.6487212707001281468305e-20j) + assert check(lambertw(subj(a,d80)), -1.0 - 1.64872127070012814684865e-40j) + assert check(lambertw(subj(a,d300)), -1.0 - 1.64872127070012814684865e-150j) + assert check(lambertw(subj(a,d1000)), mpc(-1.0,'-1.64872127070012814684865e-500')) + # ---- Branch 1 ---- + assert check(lambertw(addj(a,d3),1), -3.088501303219933378005990 + 7.458676867597474813950098j) + assert check(lambertw(addj(a,d80),1), -3.088843015613043855957087 + 7.461489285654254556906117j) + assert check(lambertw(addj(a,d300),1), -3.088843015613043855957087 + 7.461489285654254556906117j) + assert check(lambertw(addj(a,d1000),1), -3.088843015613043855957087 + 7.461489285654254556906117j) + assert check(lambertw(subj(a,d3),1), -1.0520914180450129534365906 + 0.0539925638125450525673175j) + assert check(lambertw(subj(a,d10),1), -1.0000164872127056318529390 + 0.000016487393927159250398333077j) + assert check(lambertw(subj(a,d20),1), -1.0000000001648721270700128 + 1.64872127088134693542628e-10j) + assert check(lambertw(subj(a,d40),1), -1.000000000000000000016487 + 1.64872127070012814686677e-20j) + assert check(lambertw(subj(a,d80),1), -1.0 + 1.64872127070012814684865e-40j) + assert check(lambertw(subj(a,d300),1), -1.0 + 1.64872127070012814684865e-150j) + assert check(lambertw(subj(a,d1000),1), mpc(-1.0, '1.64872127070012814684865e-500')) + # ---- Branch -1 ---- + # -1/e + eps + assert check(lambertw(add(a,d3),-1), -1.075608941186624989414945) + assert check(lambertw(add(a,d10),-1), -1.000023316621036696460620) + assert check(lambertw(add(a,d20),-1), -1.000000000233164398177834) + assert lambertw(add(a,d40),-1) == -1 + assert lambertw(add(a,d80),-1) == -1 + assert lambertw(add(a,d300),-1) == -1 + assert lambertw(add(a,d1000),-1) == -1 + # -1/e - eps + assert check(lambertw(sub(a,d3),-1), -0.99819016149860989001-0.07367191188934638577j) + assert check(lambertw(sub(a,d10),-1), -0.9999999998187812114595992-0.0000233164398140346109194j) + assert check(lambertw(sub(a,d20),-1), -0.99999999999999999998187-2.331643981597124203344e-10j) + assert check(lambertw(sub(a,d40),-1), -1.0-2.33164398159712420336e-20j) + assert check(lambertw(sub(a,d80),-1), -1.0-2.33164398159712420336e-40j) + assert check(lambertw(sub(a,d300),-1), -1.0-2.33164398159712420336e-150j) + assert check(lambertw(sub(a,d1000),-1), mpc(-1,'-2.33164398159712420336e-500')) + # -1/e + eps*j + assert check(lambertw(addj(a,d3),-1), -1.0520914180450129534365906 - 0.0539925638125450525673175j) + assert check(lambertw(addj(a,d10),-1), -1.0000164872127056318529390 - 0.0000164873939271592503983j) + assert check(lambertw(addj(a,d20),-1), -1.0000000001648721270700 - 1.64872127088134693542628e-10j) + assert check(lambertw(addj(a,d40),-1), -1.00000000000000000001648 - 1.6487212707001281468667726e-20j) + assert check(lambertw(addj(a,d80),-1), -1.0 - 1.64872127070012814684865e-40j) + assert check(lambertw(addj(a,d300),-1), -1.0 - 1.64872127070012814684865e-150j) + assert check(lambertw(addj(a,d1000),-1), mpc(-1.0,'-1.64872127070012814684865e-500')) + # -1/e - eps*j + assert check(lambertw(subj(a,d3),-1), -3.088501303219933378005990-7.458676867597474813950098j) + assert check(lambertw(subj(a,d10),-1), -3.088843015579260686911033-7.461489285372968780020716j) + assert check(lambertw(subj(a,d20),-1), -3.088843015613043855953708-7.461489285654254556877988j) + assert check(lambertw(subj(a,d40),-1), -3.088843015613043855957087-7.461489285654254556906117j) + assert check(lambertw(subj(a,d80),-1), -3.088843015613043855957087 - 7.461489285654254556906117j) + assert check(lambertw(subj(a,d300),-1), -3.088843015613043855957087 - 7.461489285654254556906117j) + assert check(lambertw(subj(a,d1000),-1), -3.088843015613043855957087 - 7.461489285654254556906117j) + # One more case, testing higher precision + mp.dps = 500 + x = -1/e + mpf('1e-13') + ans = "-0.99999926266961377166355784455394913638782494543377383"\ + "744978844374498153493943725364881490261187530235150668593869563"\ + "168276697689459394902153960200361935311512317183678882" + mp.dps = 15 + assert lambertw(x).ae(ans) + mp.dps = 50 + assert lambertw(x).ae(ans) + mp.dps = 150 + assert lambertw(x).ae(ans) + +def test_meijerg(): + mp.dps = 15 + assert meijerg([[2,3],[1]],[[0.5,2],[3,4]], 2.5).ae(4.2181028074787439386) + assert meijerg([[],[1+j]],[[1],[1]], 3+4j).ae(271.46290321152464592 - 703.03330399954820169j) + assert meijerg([[0.25],[1]],[[0.5],[2]],0) == 0 + assert meijerg([[0],[]],[[0,0,'1/3','2/3'], []], '2/27').ae(2.2019391389653314120) + # Verify 1/z series being used + assert meijerg([[-3],[-0.5]], [[-1],[-2.5]], -0.5).ae(-1.338096165935754898687431) + assert meijerg([[1-(-1)],[1-(-2.5)]], [[1-(-3)],[1-(-0.5)]], -2.0).ae(-1.338096165935754898687431) + assert meijerg([[-3],[-0.5]], [[-1],[-2.5]], -1).ae(-(pi+4)/(4*pi)) + a = 2.5 + b = 1.25 + for z in [mpf(0.25), mpf(2)]: + x1 = hyp1f1(a,b,z) + x2 = gamma(b)/gamma(a)*meijerg([[1-a],[]],[[0],[1-b]],-z) + x3 = gamma(b)/gamma(a)*meijerg([[1-0],[1-(1-b)]],[[1-(1-a)],[]],-1/z) + assert x1.ae(x2) + assert x1.ae(x3) + +def test_appellf1(): + mp.dps = 15 + assert appellf1(2,-2,1,1,2,3).ae(-1.75) + assert appellf1(2,1,-2,1,2,3).ae(-8) + assert appellf1(2,1,-2,1,0.5,0.25).ae(1.5) + assert appellf1(-2,1,3,2,3,3).ae(19) + assert appellf1(1,2,3,4,0.5,0.125).ae( 1.53843285792549786518) + +def test_coulomb(): + # Note: most tests are doctests + # Test for a bug: + mp.dps = 15 + assert coulombg(mpc(-5,0),2,3).ae(20.087729487721430394) + +def test_hyper_param_accuracy(): + mp.dps = 15 + As = [n+1e-10 for n in range(-5,-1)] + Bs = [n+1e-10 for n in range(-12,-5)] + assert hyper(As,Bs,10).ae(-381757055858.652671927) + assert legenp(0.5, 100, 0.25).ae(-2.4124576567211311755e+144) + assert (hyp1f1(1000,1,-100)*10**24).ae(5.2589445437370169113) + assert (hyp2f1(10, -900, 10.5, 0.99)*10**24).ae(1.9185370579660768203) + assert (hyp2f1(1000,1.5,-3.5,-1.5)*10**385).ae(-2.7367529051334000764) + assert hyp2f1(-5, 10, 3, 0.5, zeroprec=500) == 0 + assert (hyp1f1(-10000, 1000, 100)*10**424).ae(-3.1046080515824859974) + assert (hyp2f1(1000,1.5,-3.5,-0.75,maxterms=100000)*10**231).ae(-4.0534790813913998643) + assert legenp(2, 3, 0.25) == 0 + pytest.raises(ValueError, lambda: hypercomb(lambda a: [([],[],[],[],[a],[-a],0.5)], [3])) + assert hypercomb(lambda a: [([],[],[],[],[a],[-a],0.5)], [3], infprec=200) == inf + assert meijerg([[],[]],[[0,0,0,0],[]],0.1).ae(1.5680822343832351418) + assert (besselk(400,400)*10**94).ae(1.4387057277018550583) + mp.dps = 5 + (hyp1f1(-5000.5, 1500, 100)*10**185).ae(8.5185229673381935522) + (hyp1f1(-5000, 1500, 100)*10**185).ae(9.1501213424563944311) + mp.dps = 15 + (hyp1f1(-5000.5, 1500, 100)*10**185).ae(8.5185229673381935522) + (hyp1f1(-5000, 1500, 100)*10**185).ae(9.1501213424563944311) + assert hyp0f1(fadd(-20,'1e-100',exact=True), 0.25).ae(1.85014429040102783e+49) + assert hyp0f1((-20*10**100+1, 10**100), 0.25).ae(1.85014429040102783e+49) + +def test_hypercomb_zero_pow(): + # check that 0^0 = 1 + assert hypercomb(lambda a: (([0],[a],[],[],[],[],0),), [0]) == 1 + assert meijerg([[-1.5],[]],[[0],[-0.75]],0).ae(1.4464090846320771425) + +def test_spherharm(): + mp.dps = 15 + t = 0.5; r = 0.25 + assert spherharm(0,0,t,r).ae(0.28209479177387814347) + assert spherharm(1,-1,t,r).ae(0.16048941205971996369 - 0.04097967481096344271j) + assert spherharm(1,0,t,r).ae(0.42878904414183579379) + assert spherharm(1,1,t,r).ae(-0.16048941205971996369 - 0.04097967481096344271j) + assert spherharm(2,-2,t,r).ae(0.077915886919031181734 - 0.042565643022253962264j) + assert spherharm(2,-1,t,r).ae(0.31493387233497459884 - 0.08041582001959297689j) + assert spherharm(2,0,t,r).ae(0.41330596756220761898) + assert spherharm(2,1,t,r).ae(-0.31493387233497459884 - 0.08041582001959297689j) + assert spherharm(2,2,t,r).ae(0.077915886919031181734 + 0.042565643022253962264j) + assert spherharm(3,-3,t,r).ae(0.033640236589690881646 - 0.031339125318637082197j) + assert spherharm(3,-2,t,r).ae(0.18091018743101461963 - 0.09883168583167010241j) + assert spherharm(3,-1,t,r).ae(0.42796713930907320351 - 0.10927795157064962317j) + assert spherharm(3,0,t,r).ae(0.27861659336351639787) + assert spherharm(3,1,t,r).ae(-0.42796713930907320351 - 0.10927795157064962317j) + assert spherharm(3,2,t,r).ae(0.18091018743101461963 + 0.09883168583167010241j) + assert spherharm(3,3,t,r).ae(-0.033640236589690881646 - 0.031339125318637082197j) + assert spherharm(0,-1,t,r) == 0 + assert spherharm(0,-2,t,r) == 0 + assert spherharm(0,1,t,r) == 0 + assert spherharm(0,2,t,r) == 0 + assert spherharm(1,2,t,r) == 0 + assert spherharm(1,3,t,r) == 0 + assert spherharm(1,-2,t,r) == 0 + assert spherharm(1,-3,t,r) == 0 + assert spherharm(2,3,t,r) == 0 + assert spherharm(2,4,t,r) == 0 + assert spherharm(2,-3,t,r) == 0 + assert spherharm(2,-4,t,r) == 0 + assert spherharm(3,4.5,0.5,0.25).ae(-22.831053442240790148 + 10.910526059510013757j) + assert spherharm(2+3j, 1-j, 1+j, 3+4j).ae(-2.6582752037810116935 - 1.0909214905642160211j) + assert spherharm(-6,2.5,t,r).ae(0.39383644983851448178 + 0.28414687085358299021j) + assert spherharm(-3.5, 3, 0.5, 0.25).ae(0.014516852987544698924 - 0.015582769591477628495j) + assert spherharm(-3, 3, 0.5, 0.25) == 0 + assert spherharm(-6, 3, 0.5, 0.25).ae(-0.16544349818782275459 - 0.15412657723253924562j) + assert spherharm(-6, 1.5, 0.5, 0.25).ae(0.032208193499767402477 + 0.012678000924063664921j) + assert spherharm(3,0,0,1).ae(0.74635266518023078283) + assert spherharm(3,-2,0,1) == 0 + assert spherharm(3,-2,1,1).ae(-0.16270707338254028971 - 0.35552144137546777097j) + +def test_qfunctions(): + mp.dps = 15 + assert qp(2,3,100).ae('2.7291482267247332183e2391') + +def test_issue_239(): + mp.prec = 150 + x = ldexp(2476979795053773,-52) + assert betainc(206, 385, 0, 0.55, 1).ae('0.99999999999999999999996570910644857895771110649954') + mp.dps = 15 + pytest.raises(ValueError, lambda: hyp2f1(-5,5,0.5,0.5)) + +# Extra stress testing for Bessel functions +# Reference zeros generated with the aid of scipy.special +# jn_zero, jnp_zero, yn_zero, ynp_zero + +V = 15 +M = 15 + +jn_small_zeros = \ +[[2.4048255576957728, + 5.5200781102863106, + 8.6537279129110122, + 11.791534439014282, + 14.930917708487786, + 18.071063967910923, + 21.211636629879259, + 24.352471530749303, + 27.493479132040255, + 30.634606468431975, + 33.775820213573569, + 36.917098353664044, + 40.058425764628239, + 43.19979171317673, + 46.341188371661814], + [3.8317059702075123, + 7.0155866698156188, + 10.173468135062722, + 13.323691936314223, + 16.470630050877633, + 19.615858510468242, + 22.760084380592772, + 25.903672087618383, + 29.046828534916855, + 32.189679910974404, + 35.332307550083865, + 38.474766234771615, + 41.617094212814451, + 44.759318997652822, + 47.901460887185447], + [5.1356223018406826, + 8.4172441403998649, + 11.619841172149059, + 14.795951782351261, + 17.959819494987826, + 21.116997053021846, + 24.270112313573103, + 27.420573549984557, + 30.569204495516397, + 33.7165195092227, + 36.86285651128381, + 40.008446733478192, + 43.153453778371463, + 46.297996677236919, + 49.442164110416873], + [6.3801618959239835, + 9.7610231299816697, + 13.015200721698434, + 16.223466160318768, + 19.409415226435012, + 22.582729593104442, + 25.748166699294978, + 28.908350780921758, + 32.064852407097709, + 35.218670738610115, + 38.370472434756944, + 41.520719670406776, + 44.669743116617253, + 47.817785691533302, + 50.965029906205183], + [7.5883424345038044, + 11.064709488501185, + 14.37253667161759, + 17.615966049804833, + 20.826932956962388, + 24.01901952477111, + 27.199087765981251, + 30.371007667117247, + 33.537137711819223, + 36.699001128744649, + 39.857627302180889, + 43.01373772335443, + 46.167853512924375, + 49.320360686390272, + 52.471551398458023], + [8.771483815959954, + 12.338604197466944, + 15.700174079711671, + 18.980133875179921, + 22.217799896561268, + 25.430341154222704, + 28.626618307291138, + 31.811716724047763, + 34.988781294559295, + 38.159868561967132, + 41.326383254047406, + 44.489319123219673, + 47.649399806697054, + 50.80716520300633, + 53.963026558378149], + [9.9361095242176849, + 13.589290170541217, + 17.003819667816014, + 20.320789213566506, + 23.58608443558139, + 26.820151983411405, + 30.033722386570469, + 33.233041762847123, + 36.422019668258457, + 39.603239416075404, + 42.778481613199507, + 45.949015998042603, + 49.11577372476426, + 52.279453903601052, + 55.440592068853149], + [11.086370019245084, + 14.821268727013171, + 18.287582832481726, + 21.641541019848401, + 24.934927887673022, + 28.191188459483199, + 31.42279419226558, + 34.637089352069324, + 37.838717382853611, + 41.030773691585537, + 44.21540850526126, + 47.394165755570512, + 50.568184679795566, + 53.738325371963291, + 56.905249991978781], + [12.225092264004655, + 16.037774190887709, + 19.554536430997055, + 22.94517313187462, + 26.266814641176644, + 29.54565967099855, + 32.795800037341462, + 36.025615063869571, + 39.240447995178135, + 42.443887743273558, + 45.638444182199141, + 48.825930381553857, + 52.007691456686903, + 55.184747939289049, + 58.357889025269694], + [13.354300477435331, + 17.241220382489128, + 20.807047789264107, + 24.233885257750552, + 27.583748963573006, + 30.885378967696675, + 34.154377923855096, + 37.400099977156589, + 40.628553718964528, + 43.843801420337347, + 47.048700737654032, + 50.245326955305383, + 53.435227157042058, + 56.619580266508436, + 59.799301630960228], + [14.475500686554541, + 18.433463666966583, + 22.046985364697802, + 25.509450554182826, + 28.887375063530457, + 32.211856199712731, + 35.499909205373851, + 38.761807017881651, + 42.004190236671805, + 45.231574103535045, + 48.447151387269394, + 51.653251668165858, + 54.851619075963349, + 58.043587928232478, + 61.230197977292681], + [15.589847884455485, + 19.61596690396692, + 23.275853726263409, + 26.773322545509539, + 30.17906117878486, + 33.526364075588624, + 36.833571341894905, + 40.111823270954241, + 43.368360947521711, + 46.608132676274944, + 49.834653510396724, + 53.050498959135054, + 56.257604715114484, + 59.457456908388002, + 62.651217388202912], + [16.698249933848246, + 20.789906360078443, + 24.494885043881354, + 28.026709949973129, + 31.45996003531804, + 34.829986990290238, + 38.156377504681354, + 41.451092307939681, + 44.721943543191147, + 47.974293531269048, + 51.211967004101068, + 54.437776928325074, + 57.653844811906946, + 60.8618046824805, + 64.062937824850136], + [17.801435153282442, + 21.95624406783631, + 25.705103053924724, + 29.270630441874802, + 32.731053310978403, + 36.123657666448762, + 39.469206825243883, + 42.780439265447158, + 46.06571091157561, + 49.330780096443524, + 52.579769064383396, + 55.815719876305778, + 59.040934037249271, + 62.257189393731728, + 65.465883797232125], + [18.899997953174024, + 23.115778347252756, + 26.907368976182104, + 30.505950163896036, + 33.993184984781542, + 37.408185128639695, + 40.772827853501868, + 44.100590565798301, + 47.400347780543231, + 50.678236946479898, + 53.93866620912693, + 57.184898598119301, + 60.419409852130297, + 63.644117508962281, + 66.860533012260103]] + +jnp_small_zeros = \ +[[0.0, + 3.8317059702075123, + 7.0155866698156188, + 10.173468135062722, + 13.323691936314223, + 16.470630050877633, + 19.615858510468242, + 22.760084380592772, + 25.903672087618383, + 29.046828534916855, + 32.189679910974404, + 35.332307550083865, + 38.474766234771615, + 41.617094212814451, + 44.759318997652822], + [1.8411837813406593, + 5.3314427735250326, + 8.5363163663462858, + 11.706004902592064, + 14.863588633909033, + 18.015527862681804, + 21.16436985918879, + 24.311326857210776, + 27.457050571059246, + 30.601922972669094, + 33.746182898667383, + 36.889987409236811, + 40.033444053350675, + 43.176628965448822, + 46.319597561173912], + [3.0542369282271403, + 6.7061331941584591, + 9.9694678230875958, + 13.170370856016123, + 16.347522318321783, + 19.512912782488205, + 22.671581772477426, + 25.826037141785263, + 28.977672772993679, + 32.127327020443474, + 35.275535050674691, + 38.422654817555906, + 41.568934936074314, + 44.714553532819734, + 47.859641607992093], + [4.2011889412105285, + 8.0152365983759522, + 11.345924310743006, + 14.585848286167028, + 17.78874786606647, + 20.9724769365377, + 24.144897432909265, + 27.310057930204349, + 30.470268806290424, + 33.626949182796679, + 36.781020675464386, + 39.933108623659488, + 43.083652662375079, + 46.232971081836478, + 49.381300092370349], + [5.3175531260839944, + 9.2823962852416123, + 12.681908442638891, + 15.964107037731551, + 19.196028800048905, + 22.401032267689004, + 25.589759681386733, + 28.767836217666503, + 31.938539340972783, + 35.103916677346764, + 38.265316987088158, + 41.423666498500732, + 44.579623137359257, + 47.733667523865744, + 50.886159153182682], + [6.4156163757002403, + 10.519860873772308, + 13.9871886301403, + 17.312842487884625, + 20.575514521386888, + 23.803581476593863, + 27.01030789777772, + 30.20284907898166, + 33.385443901010121, + 36.560777686880356, + 39.730640230067416, + 42.896273163494417, + 46.058566273567043, + 49.218174614666636, + 52.375591529563596], + [7.501266144684147, + 11.734935953042708, + 15.268181461097873, + 18.637443009666202, + 21.931715017802236, + 25.183925599499626, + 28.409776362510085, + 31.617875716105035, + 34.81339298429743, + 37.999640897715301, + 41.178849474321413, + 44.352579199070217, + 47.521956905768113, + 50.687817781723741, + 53.85079463676896], + [8.5778364897140741, + 12.932386237089576, + 16.529365884366944, + 19.941853366527342, + 23.268052926457571, + 26.545032061823576, + 29.790748583196614, + 33.015178641375142, + 36.224380548787162, + 39.422274578939259, + 42.611522172286684, + 45.793999658055002, + 48.971070951900596, + 52.143752969301988, + 55.312820330403446], + [9.6474216519972168, + 14.115518907894618, + 17.774012366915256, + 21.229062622853124, + 24.587197486317681, + 27.889269427955092, + 31.155326556188325, + 34.39662855427218, + 37.620078044197086, + 40.830178681822041, + 44.030010337966153, + 47.221758471887113, + 50.407020967034367, + 53.586995435398319, + 56.762598475105272], + [10.711433970699945, + 15.28673766733295, + 19.004593537946053, + 22.501398726777283, + 25.891277276839136, + 29.218563499936081, + 32.505247352375523, + 35.763792928808799, + 39.001902811514218, + 42.224638430753279, + 45.435483097475542, + 48.636922645305525, + 51.830783925834728, + 55.01844255063594, + 58.200955824859509], + [11.770876674955582, + 16.447852748486498, + 20.223031412681701, + 23.760715860327448, + 27.182021527190532, + 30.534504754007074, + 33.841965775135715, + 37.118000423665604, + 40.371068905333891, + 43.606764901379516, + 46.828959446564562, + 50.040428970943456, + 53.243223214220535, + 56.438892058982552, + 59.628631306921512], + [12.826491228033465, + 17.600266557468326, + 21.430854238060294, + 25.008518704644261, + 28.460857279654847, + 31.838424458616998, + 35.166714427392629, + 38.460388720328256, + 41.728625562624312, + 44.977526250903469, + 48.211333836373288, + 51.433105171422278, + 54.645106240447105, + 57.849056857839799, + 61.046288512821078], + [13.878843069697276, + 18.745090916814406, + 22.629300302835503, + 26.246047773946584, + 29.72897816891134, + 33.131449953571661, + 36.480548302231658, + 39.791940718940855, + 43.075486800191012, + 46.337772104541405, + 49.583396417633095, + 52.815686826850452, + 56.037118687012179, + 59.249577075517968, + 62.454525995970462], + [14.928374492964716, + 19.88322436109951, + 23.81938909003628, + 27.474339750968247, + 30.987394331665278, + 34.414545662167183, + 37.784378506209499, + 41.113512376883377, + 44.412454519229281, + 47.688252845993366, + 50.945849245830813, + 54.188831071035124, + 57.419876154678179, + 60.641030026538746, + 63.853885828967512], + [15.975438807484321, + 21.015404934568315, + 25.001971500138194, + 28.694271223110755, + 32.236969407878118, + 35.688544091185301, + 39.078998185245057, + 42.425854432866141, + 45.740236776624833, + 49.029635055514276, + 52.299319390331728, + 55.553127779547459, + 58.793933759028134, + 62.02393848337554, + 65.244860767043859]] + +yn_small_zeros = \ +[[0.89357696627916752, + 3.9576784193148579, + 7.0860510603017727, + 10.222345043496417, + 13.361097473872763, + 16.500922441528091, + 19.64130970088794, + 22.782028047291559, + 25.922957653180923, + 29.064030252728398, + 32.205204116493281, + 35.346452305214321, + 38.487756653081537, + 41.629104466213808, + 44.770486607221993], + [2.197141326031017, + 5.4296810407941351, + 8.5960058683311689, + 11.749154830839881, + 14.897442128336725, + 18.043402276727856, + 21.188068934142213, + 24.331942571356912, + 27.475294980449224, + 30.618286491641115, + 33.761017796109326, + 36.90355531614295, + 40.045944640266876, + 43.188218097393211, + 46.330399250701687], + [3.3842417671495935, + 6.7938075132682675, + 10.023477979360038, + 13.209986710206416, + 16.378966558947457, + 19.539039990286384, + 22.69395593890929, + 25.845613720902269, + 28.995080395650151, + 32.143002257627551, + 35.289793869635804, + 38.435733485446343, + 41.581014867297885, + 44.725777117640461, + 47.870122696676504], + [4.5270246611496439, + 8.0975537628604907, + 11.396466739595867, + 14.623077742393873, + 17.81845523294552, + 20.997284754187761, + 24.166235758581828, + 27.328799850405162, + 30.486989604098659, + 33.642049384702463, + 36.794791029185579, + 39.945767226378749, + 43.095367507846703, + 46.2438744334407, + 49.391498015725107], + [5.6451478942208959, + 9.3616206152445429, + 12.730144474090465, + 15.999627085382479, + 19.22442895931681, + 22.424810599698521, + 25.610267054939328, + 28.785893657666548, + 31.954686680031668, + 35.118529525584828, + 38.278668089521758, + 41.435960629910073, + 44.591018225353424, + 47.744288086361052, + 50.896105199722123], + [6.7471838248710219, + 10.597176726782031, + 14.033804104911233, + 17.347086393228382, + 20.602899017175335, + 23.826536030287532, + 27.030134937138834, + 30.220335654231385, + 33.401105611047908, + 36.574972486670962, + 39.743627733020277, + 42.908248189569535, + 46.069679073215439, + 49.228543693445843, + 52.385312123112282], + [7.8377378223268716, + 11.811037107609447, + 15.313615118517857, + 18.670704965906724, + 21.958290897126571, + 25.206207715021249, + 28.429037095235496, + 31.634879502950644, + 34.828638524084437, + 38.013473399691765, + 41.19151880917741, + 44.364272633271975, + 47.53281875312084, + 50.697961822183806, + 53.860312300118388], + [8.919605734873789, + 13.007711435388313, + 16.573915129085334, + 19.974342312352426, + 23.293972585596648, + 26.5667563757203, + 29.809531451608321, + 33.031769327150685, + 36.239265816598239, + 39.435790312675323, + 42.623910919472727, + 45.805442883111651, + 48.981708325514764, + 52.153694518185572, + 55.322154420959698], + [9.9946283820824834, + 14.190361295800141, + 17.817887841179873, + 21.26093227125945, + 24.612576377421522, + 27.910524883974868, + 31.173701563441602, + 34.412862242025045, + 37.634648706110989, + 40.843415321050884, + 44.04214994542435, + 47.232978012841169, + 50.417456447370186, + 53.596753874948731, + 56.771765754432457], + [11.064090256031013, + 15.361301343575925, + 19.047949646361388, + 22.532765416313869, + 25.91620496332662, + 29.2394205079349, + 32.523270869465881, + 35.779715464475261, + 39.016196664616095, + 42.237627509803703, + 45.4474001519274, + 48.647941127433196, + 51.841036928216499, + 55.028034667184916, + 58.209970905250097], + [12.128927704415439, + 16.522284394784426, + 20.265984501212254, + 23.791669719454272, + 27.206568881574774, + 30.555020011020762, + 33.859683872746356, + 37.133649760307504, + 40.385117593813002, + 43.619533085646856, + 46.840676630553575, + 50.051265851897857, + 53.253310556711732, + 56.448332488918971, + 59.637507005589829], + [13.189846995683845, + 17.674674253171487, + 21.473493977824902, + 25.03913093040942, + 28.485081336558058, + 31.858644293774859, + 35.184165245422787, + 38.475796636190897, + 41.742455848758449, + 44.990096293791186, + 48.222870660068338, + 51.443777308699826, + 54.655042589416311, + 57.858358441436511, + 61.055036135780528], + [14.247395665073945, + 18.819555894710682, + 22.671697117872794, + 26.276375544903892, + 29.752925495549038, + 33.151412708998983, + 36.497763772987645, + 39.807134090704376, + 43.089121522203808, + 46.350163579538652, + 49.594769786270069, + 52.82620892320143, + 56.046916910756961, + 59.258751140598783, + 62.463155567737854], + [15.30200785858925, + 19.957808654258601, + 23.861599172945054, + 27.504429642227545, + 31.011103429019229, + 34.434283425782942, + 37.801385632318459, + 41.128514139788358, + 44.425913324440663, + 47.700482714581842, + 50.957073905278458, + 54.199216028087261, + 57.429547607017405, + 60.65008661807661, + 63.862406280068586], + [16.354034360047551, + 21.090156519983806, + 25.044040298785627, + 28.724161640881914, + 32.260472459522644, + 35.708083982611664, + 39.095820003878235, + 42.440684315990936, + 45.75353669045622, + 49.041718113283529, + 52.310408280968073, + 55.56338698149062, + 58.803488508906895, + 62.032886550960831, + 65.253280088312461]] + +ynp_small_zeros = \ +[[2.197141326031017, + 5.4296810407941351, + 8.5960058683311689, + 11.749154830839881, + 14.897442128336725, + 18.043402276727856, + 21.188068934142213, + 24.331942571356912, + 27.475294980449224, + 30.618286491641115, + 33.761017796109326, + 36.90355531614295, + 40.045944640266876, + 43.188218097393211, + 46.330399250701687], + [3.6830228565851777, + 6.9414999536541757, + 10.123404655436613, + 13.285758156782854, + 16.440058007293282, + 19.590241756629495, + 22.738034717396327, + 25.884314618788867, + 29.029575819372535, + 32.174118233366201, + 35.318134458192094, + 38.461753870997549, + 41.605066618873108, + 44.74813744908079, + 47.891014070791065], + [5.0025829314460639, + 8.3507247014130795, + 11.574195465217647, + 14.760909306207676, + 17.931285939466855, + 21.092894504412739, + 24.249231678519058, + 27.402145837145258, + 30.552708880564553, + 33.70158627151572, + 36.849213419846257, + 39.995887376143356, + 43.141817835750686, + 46.287157097544201, + 49.432018469138281], + [6.2536332084598136, + 9.6987879841487711, + 12.972409052292216, + 16.19044719506921, + 19.38238844973613, + 22.559791857764261, + 25.728213194724094, + 28.890678419054777, + 32.048984005266337, + 35.204266606440635, + 38.357281675961019, + 41.508551443818436, + 44.658448731963676, + 47.807246956681162, + 50.95515126455207], + [7.4649217367571329, + 11.005169149809189, + 14.3317235192331, + 17.58443601710272, + 20.801062338411128, + 23.997004122902644, + 27.179886689853435, + 30.353960608554323, + 33.521797098666792, + 36.685048382072301, + 39.844826969405863, + 43.001910515625288, + 46.15685955107263, + 49.310088614282257, + 52.461911043685864], + [8.6495562436971983, + 12.280868725807848, + 15.660799304540377, + 18.949739756016503, + 22.192841809428241, + 25.409072788867674, + 28.608039283077593, + 31.795195353138159, + 34.973890634255288, + 38.14630522169358, + 41.313923188794905, + 44.477791768537617, + 47.638672065035628, + 50.797131066967842, + 53.953600129601663], + [9.8147970120105779, + 13.532811875789828, + 16.965526446046053, + 20.291285512443867, + 23.56186260680065, + 26.799499736027237, + 30.015665481543419, + 33.216968050039509, + 36.407516858984748, + 39.590015243560459, + 42.766320595957378, + 45.937754257017323, + 49.105283450953203, + 52.269633324547373, + 55.431358715604255], + [10.965152105242974, + 14.765687379508912, + 18.250123150217555, + 21.612750053384621, + 24.911310600813573, + 28.171051927637585, + 31.40518108895689, + 34.621401012564177, + 37.824552065973114, + 41.017847386464902, + 44.203512240871601, + 47.3831408366063, + 50.557907466622796, + 53.728697478957026, + 56.896191727313342], + [12.103641941939539, + 15.982840905145284, + 19.517731005559611, + 22.916962141504605, + 26.243700855690533, + 29.525960140695407, + 32.778568197561124, + 36.010261572392516, + 39.226578757802172, + 42.43122493258747, + 45.626783824134354, + 48.815117837929515, + 51.997606404328863, + 55.175294723956816, + 58.348990221754937], + [13.232403808592215, + 17.186756572616758, + 20.770762917490496, + 24.206152448722253, + 27.561059462697153, + 30.866053571250639, + 34.137476603379774, + 37.385039772270268, + 40.614946085165892, + 43.831373184731238, + 47.037251786726299, + 50.234705848765229, + 53.425316228549359, + 56.610286079882087, + 59.790548623216652], + [14.35301374369987, + 18.379337301642568, + 22.011118775283494, + 25.482116178696707, + 28.865046588695164, + 32.192853922166294, + 35.483296655830277, + 38.747005493021857, + 41.990815194320955, + 45.219355876831731, + 48.435892856078888, + 51.642803925173029, + 54.84186659475857, + 58.034439083840155, + 61.221578745109862], + [15.466672066554263, + 19.562077985759503, + 23.240325531101082, + 26.746322986645901, + 30.157042415639891, + 33.507642948240263, + 36.817212798512775, + 40.097251300178642, + 43.355193847719752, + 46.596103410173672, + 49.823567279972794, + 53.040208868780832, + 56.247996968470062, + 59.448441365714251, + 62.642721301357187], + [16.574317035530872, + 20.73617763753932, + 24.459631728238804, + 27.999993668839644, + 31.438208790267783, + 34.811512070805535, + 38.140243708611251, + 41.436725143893739, + 44.708963264433333, + 47.962435051891027, + 51.201037321915983, + 54.427630745992975, + 57.644369734615238, + 60.852911791989989, + 64.054555435720397], + [17.676697936439624, + 21.9026148697762, + 25.670073356263225, + 29.244155124266438, + 32.709534477396028, + 36.105399554497548, + 39.453272918267025, + 42.766255701958017, + 46.052899215578358, + 49.319076602061401, + 52.568982147952547, + 55.805705507386287, + 59.031580956740466, + 62.248409689597653, + 65.457606670836759], + [18.774423978290318, + 23.06220035979272, + 26.872520985976736, + 30.479680663499762, + 33.971869047372436, + 37.390118854896324, + 40.757072537673599, + 44.086572292170345, + 47.387688809191869, + 50.66667461073936, + 53.928009929563275, + 57.175005343085052, + 60.410169281219877, + 63.635442539153021, + 66.85235358587768]] + +@pytest.mark.slow +def test_bessel_zeros_extra(): + mp.dps = 15 + for v in range(V): + for m in range(1,M+1): + print(v, m, "of", V, M) + # Twice to test cache (if used) + assert besseljzero(v,m).ae(jn_small_zeros[v][m-1]) + assert besseljzero(v,m).ae(jn_small_zeros[v][m-1]) + assert besseljzero(v,m,1).ae(jnp_small_zeros[v][m-1]) + assert besseljzero(v,m,1).ae(jnp_small_zeros[v][m-1]) + assert besselyzero(v,m).ae(yn_small_zeros[v][m-1]) + assert besselyzero(v,m).ae(yn_small_zeros[v][m-1]) + assert besselyzero(v,m,1).ae(ynp_small_zeros[v][m-1]) + assert besselyzero(v,m,1).ae(ynp_small_zeros[v][m-1]) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_gammazeta.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_gammazeta.py new file mode 100644 index 0000000000000000000000000000000000000000..6a18a7964d746561dfd5f81177cd78ccc46d2a5d --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_gammazeta.py @@ -0,0 +1,698 @@ +from mpmath import * +from mpmath.libmp import round_up, from_float, mpf_zeta_int + +def test_zeta_int_bug(): + assert mpf_zeta_int(0, 10) == from_float(-0.5) + +def test_bernoulli(): + assert bernfrac(0) == (1,1) + assert bernfrac(1) == (-1,2) + assert bernfrac(2) == (1,6) + assert bernfrac(3) == (0,1) + assert bernfrac(4) == (-1,30) + assert bernfrac(5) == (0,1) + assert bernfrac(6) == (1,42) + assert bernfrac(8) == (-1,30) + assert bernfrac(10) == (5,66) + assert bernfrac(12) == (-691,2730) + assert bernfrac(18) == (43867,798) + p, q = bernfrac(228) + assert p % 10**10 == 164918161 + assert q == 625170 + p, q = bernfrac(1000) + assert p % 10**10 == 7950421099 + assert q == 342999030 + mp.dps = 15 + assert bernoulli(0) == 1 + assert bernoulli(1) == -0.5 + assert bernoulli(2).ae(1./6) + assert bernoulli(3) == 0 + assert bernoulli(4).ae(-1./30) + assert bernoulli(5) == 0 + assert bernoulli(6).ae(1./42) + assert str(bernoulli(10)) == '0.0757575757575758' + assert str(bernoulli(234)) == '7.62772793964344e+267' + assert str(bernoulli(10**5)) == '-5.82229431461335e+376755' + assert str(bernoulli(10**8+2)) == '1.19570355039953e+676752584' + + mp.dps = 50 + assert str(bernoulli(10)) == '0.075757575757575757575757575757575757575757575757576' + assert str(bernoulli(234)) == '7.6277279396434392486994969020496121553385863373331e+267' + assert str(bernoulli(10**5)) == '-5.8222943146133508236497045360612887555320691004308e+376755' + assert str(bernoulli(10**8+2)) == '1.1957035503995297272263047884604346914602088317782e+676752584' + + mp.dps = 1000 + assert bernoulli(10).ae(mpf(5)/66) + + mp.dps = 50000 + assert bernoulli(10).ae(mpf(5)/66) + + mp.dps = 15 + +def test_bernpoly_eulerpoly(): + mp.dps = 15 + assert bernpoly(0,-1).ae(1) + assert bernpoly(0,0).ae(1) + assert bernpoly(0,'1/2').ae(1) + assert bernpoly(0,'3/4').ae(1) + assert bernpoly(0,1).ae(1) + assert bernpoly(0,2).ae(1) + assert bernpoly(1,-1).ae('-3/2') + assert bernpoly(1,0).ae('-1/2') + assert bernpoly(1,'1/2').ae(0) + assert bernpoly(1,'3/4').ae('1/4') + assert bernpoly(1,1).ae('1/2') + assert bernpoly(1,2).ae('3/2') + assert bernpoly(2,-1).ae('13/6') + assert bernpoly(2,0).ae('1/6') + assert bernpoly(2,'1/2').ae('-1/12') + assert bernpoly(2,'3/4').ae('-1/48') + assert bernpoly(2,1).ae('1/6') + assert bernpoly(2,2).ae('13/6') + assert bernpoly(3,-1).ae(-3) + assert bernpoly(3,0).ae(0) + assert bernpoly(3,'1/2').ae(0) + assert bernpoly(3,'3/4').ae('-3/64') + assert bernpoly(3,1).ae(0) + assert bernpoly(3,2).ae(3) + assert bernpoly(4,-1).ae('119/30') + assert bernpoly(4,0).ae('-1/30') + assert bernpoly(4,'1/2').ae('7/240') + assert bernpoly(4,'3/4').ae('7/3840') + assert bernpoly(4,1).ae('-1/30') + assert bernpoly(4,2).ae('119/30') + assert bernpoly(5,-1).ae(-5) + assert bernpoly(5,0).ae(0) + assert bernpoly(5,'1/2').ae(0) + assert bernpoly(5,'3/4').ae('25/1024') + assert bernpoly(5,1).ae(0) + assert bernpoly(5,2).ae(5) + assert bernpoly(10,-1).ae('665/66') + assert bernpoly(10,0).ae('5/66') + assert bernpoly(10,'1/2').ae('-2555/33792') + assert bernpoly(10,'3/4').ae('-2555/34603008') + assert bernpoly(10,1).ae('5/66') + assert bernpoly(10,2).ae('665/66') + assert bernpoly(11,-1).ae(-11) + assert bernpoly(11,0).ae(0) + assert bernpoly(11,'1/2').ae(0) + assert bernpoly(11,'3/4').ae('-555731/4194304') + assert bernpoly(11,1).ae(0) + assert bernpoly(11,2).ae(11) + assert eulerpoly(0,-1).ae(1) + assert eulerpoly(0,0).ae(1) + assert eulerpoly(0,'1/2').ae(1) + assert eulerpoly(0,'3/4').ae(1) + assert eulerpoly(0,1).ae(1) + assert eulerpoly(0,2).ae(1) + assert eulerpoly(1,-1).ae('-3/2') + assert eulerpoly(1,0).ae('-1/2') + assert eulerpoly(1,'1/2').ae(0) + assert eulerpoly(1,'3/4').ae('1/4') + assert eulerpoly(1,1).ae('1/2') + assert eulerpoly(1,2).ae('3/2') + assert eulerpoly(2,-1).ae(2) + assert eulerpoly(2,0).ae(0) + assert eulerpoly(2,'1/2').ae('-1/4') + assert eulerpoly(2,'3/4').ae('-3/16') + assert eulerpoly(2,1).ae(0) + assert eulerpoly(2,2).ae(2) + assert eulerpoly(3,-1).ae('-9/4') + assert eulerpoly(3,0).ae('1/4') + assert eulerpoly(3,'1/2').ae(0) + assert eulerpoly(3,'3/4').ae('-11/64') + assert eulerpoly(3,1).ae('-1/4') + assert eulerpoly(3,2).ae('9/4') + assert eulerpoly(4,-1).ae(2) + assert eulerpoly(4,0).ae(0) + assert eulerpoly(4,'1/2').ae('5/16') + assert eulerpoly(4,'3/4').ae('57/256') + assert eulerpoly(4,1).ae(0) + assert eulerpoly(4,2).ae(2) + assert eulerpoly(5,-1).ae('-3/2') + assert eulerpoly(5,0).ae('-1/2') + assert eulerpoly(5,'1/2').ae(0) + assert eulerpoly(5,'3/4').ae('361/1024') + assert eulerpoly(5,1).ae('1/2') + assert eulerpoly(5,2).ae('3/2') + assert eulerpoly(10,-1).ae(2) + assert eulerpoly(10,0).ae(0) + assert eulerpoly(10,'1/2').ae('-50521/1024') + assert eulerpoly(10,'3/4').ae('-36581523/1048576') + assert eulerpoly(10,1).ae(0) + assert eulerpoly(10,2).ae(2) + assert eulerpoly(11,-1).ae('-699/4') + assert eulerpoly(11,0).ae('691/4') + assert eulerpoly(11,'1/2').ae(0) + assert eulerpoly(11,'3/4').ae('-512343611/4194304') + assert eulerpoly(11,1).ae('-691/4') + assert eulerpoly(11,2).ae('699/4') + # Potential accuracy issues + assert bernpoly(10000,10000).ae('5.8196915936323387117e+39999') + assert bernpoly(200,17.5).ae(3.8048418524583064909e244) + assert eulerpoly(200,17.5).ae(-3.7309911582655785929e275) + +def test_gamma(): + mp.dps = 15 + assert gamma(0.25).ae(3.6256099082219083119) + assert gamma(0.0001).ae(9999.4228832316241908) + assert gamma(300).ae('1.0201917073881354535e612') + assert gamma(-0.5).ae(-3.5449077018110320546) + assert gamma(-7.43).ae(0.00026524416464197007186) + #assert gamma(Rational(1,2)) == gamma(0.5) + #assert gamma(Rational(-7,3)).ae(gamma(mpf(-7)/3)) + assert gamma(1+1j).ae(0.49801566811835604271 - 0.15494982830181068512j) + assert gamma(-1+0.01j).ae(-0.422733904013474115 + 99.985883082635367436j) + assert gamma(20+30j).ae(-1453876687.5534810 + 1163777777.8031573j) + # Should always give exact factorials when they can + # be represented as mpfs under the current working precision + fact = 1 + for i in range(1, 18): + assert gamma(i) == fact + fact *= i + for dps in [170, 600]: + fact = 1 + mp.dps = dps + for i in range(1, 105): + assert gamma(i) == fact + fact *= i + mp.dps = 100 + assert gamma(0.5).ae(sqrt(pi)) + mp.dps = 15 + assert factorial(0) == fac(0) == 1 + assert factorial(3) == 6 + assert isnan(gamma(nan)) + assert gamma(1100).ae('4.8579168073569433667e2866') + assert rgamma(0) == 0 + assert rgamma(-1) == 0 + assert rgamma(2) == 1.0 + assert rgamma(3) == 0.5 + assert loggamma(2+8j).ae(-8.5205176753667636926 + 10.8569497125597429366j) + assert loggamma('1e10000').ae('2.302485092994045684017991e10004') + assert loggamma('1e10000j').ae(mpc('-1.570796326794896619231322e10000','2.302485092994045684017991e10004')) + +def test_fac2(): + mp.dps = 15 + assert [fac2(n) for n in range(10)] == [1,1,2,3,8,15,48,105,384,945] + assert fac2(-5).ae(1./3) + assert fac2(-11).ae(-1./945) + assert fac2(50).ae(5.20469842636666623e32) + assert fac2(0.5+0.75j).ae(0.81546769394688069176-0.34901016085573266889j) + assert fac2(inf) == inf + assert isnan(fac2(-inf)) + +def test_gamma_quotients(): + mp.dps = 15 + h = 1e-8 + ep = 1e-4 + G = gamma + assert gammaprod([-1],[-3,-4]) == 0 + assert gammaprod([-1,0],[-5]) == inf + assert abs(gammaprod([-1],[-2]) - G(-1+h)/G(-2+h)) < 1e-4 + assert abs(gammaprod([-4,-3],[-2,0]) - G(-4+h)*G(-3+h)/G(-2+h)/G(0+h)) < 1e-4 + assert rf(3,0) == 1 + assert rf(2.5,1) == 2.5 + assert rf(-5,2) == 20 + assert rf(j,j).ae(gamma(2*j)/gamma(j)) + assert rf('-255.5815971722918','-0.5119253100282322').ae('-0.1952720278805729485') # issue 421 + assert ff(-2,0) == 1 + assert ff(-2,1) == -2 + assert ff(4,3) == 24 + assert ff(3,4) == 0 + assert binomial(0,0) == 1 + assert binomial(1,0) == 1 + assert binomial(0,-1) == 0 + assert binomial(3,2) == 3 + assert binomial(5,2) == 10 + assert binomial(5,3) == 10 + assert binomial(5,5) == 1 + assert binomial(-1,0) == 1 + assert binomial(-2,-4) == 3 + assert binomial(4.5, 1.5) == 6.5625 + assert binomial(1100,1) == 1100 + assert binomial(1100,2) == 604450 + assert beta(1,1) == 1 + assert beta(0,0) == inf + assert beta(3,0) == inf + assert beta(-1,-1) == inf + assert beta(1.5,1).ae(2/3.) + assert beta(1.5,2.5).ae(pi/16) + assert (10**15*beta(10,100)).ae(2.3455339739604649879) + assert beta(inf,inf) == 0 + assert isnan(beta(-inf,inf)) + assert isnan(beta(-3,inf)) + assert isnan(beta(0,inf)) + assert beta(inf,0.5) == beta(0.5,inf) == 0 + assert beta(inf,-1.5) == inf + assert beta(inf,-0.5) == -inf + assert beta(1+2j,-1-j/2).ae(1.16396542451069943086+0.08511695947832914640j) + assert beta(-0.5,0.5) == 0 + assert beta(-3,3).ae(-1/3.) + assert beta('-255.5815971722918','-0.5119253100282322').ae('18.157330562703710339') # issue 421 + +def test_zeta(): + mp.dps = 15 + assert zeta(2).ae(pi**2 / 6) + assert zeta(2.0).ae(pi**2 / 6) + assert zeta(mpc(2)).ae(pi**2 / 6) + assert zeta(100).ae(1) + assert zeta(0).ae(-0.5) + assert zeta(0.5).ae(-1.46035450880958681) + assert zeta(-1).ae(-mpf(1)/12) + assert zeta(-2) == 0 + assert zeta(-3).ae(mpf(1)/120) + assert zeta(-4) == 0 + assert zeta(-100) == 0 + assert isnan(zeta(nan)) + assert zeta(1e-30).ae(-0.5) + assert zeta(-1e-30).ae(-0.5) + # Zeros in the critical strip + assert zeta(mpc(0.5, 14.1347251417346937904)).ae(0) + assert zeta(mpc(0.5, 21.0220396387715549926)).ae(0) + assert zeta(mpc(0.5, 25.0108575801456887632)).ae(0) + assert zeta(mpc(1e-30,1e-40)).ae(-0.5) + assert zeta(mpc(-1e-30,1e-40)).ae(-0.5) + mp.dps = 50 + im = '236.5242296658162058024755079556629786895294952121891237' + assert zeta(mpc(0.5, im)).ae(0, 1e-46) + mp.dps = 15 + # Complex reflection formula + assert (zeta(-60+3j) / 10**34).ae(8.6270183987866146+15.337398548226238j) + # issue #358 + assert zeta(0,0.5) == 0 + assert zeta(0,0) == 0.5 + assert zeta(0,0.5,1).ae(-0.34657359027997265) + # see issue #390 + assert zeta(-1.5,0.5j).ae(-0.13671400162512768475 + 0.11411333638426559139j) + +def test_altzeta(): + mp.dps = 15 + assert altzeta(-2) == 0 + assert altzeta(-4) == 0 + assert altzeta(-100) == 0 + assert altzeta(0) == 0.5 + assert altzeta(-1) == 0.25 + assert altzeta(-3) == -0.125 + assert altzeta(-5) == 0.25 + assert altzeta(-21) == 1180529130.25 + assert altzeta(1).ae(log(2)) + assert altzeta(2).ae(pi**2/12) + assert altzeta(10).ae(73*pi**10/6842880) + assert altzeta(50) < 1 + assert altzeta(60, rounding='d') < 1 + assert altzeta(60, rounding='u') == 1 + assert altzeta(10000, rounding='d') < 1 + assert altzeta(10000, rounding='u') == 1 + assert altzeta(3+0j) == altzeta(3) + s = 3+4j + assert altzeta(s).ae((1-2**(1-s))*zeta(s)) + s = -3+4j + assert altzeta(s).ae((1-2**(1-s))*zeta(s)) + assert altzeta(-100.5).ae(4.58595480083585913e+108) + assert altzeta(1.3).ae(0.73821404216623045) + assert altzeta(1e-30).ae(0.5) + assert altzeta(-1e-30).ae(0.5) + assert altzeta(mpc(1e-30,1e-40)).ae(0.5) + assert altzeta(mpc(-1e-30,1e-40)).ae(0.5) + +def test_zeta_huge(): + mp.dps = 15 + assert zeta(inf) == 1 + mp.dps = 50 + assert zeta(100).ae('1.0000000000000000000000000000007888609052210118073522') + assert zeta(40*pi).ae('1.0000000000000000000000000000000000000148407238666182') + mp.dps = 10000 + v = zeta(33000) + mp.dps = 15 + assert str(v-1) == '1.02363019598118e-9934' + assert zeta(pi*1000, rounding=round_up) > 1 + assert zeta(3000, rounding=round_up) > 1 + assert zeta(pi*1000) == 1 + assert zeta(3000) == 1 + +def test_zeta_negative(): + mp.dps = 150 + a = -pi*10**40 + mp.dps = 15 + assert str(zeta(a)) == '2.55880492708712e+1233536161668617575553892558646631323374078' + mp.dps = 50 + assert str(zeta(a)) == '2.5588049270871154960875033337384432038436330847333e+1233536161668617575553892558646631323374078' + mp.dps = 15 + +def test_polygamma(): + mp.dps = 15 + psi0 = lambda z: psi(0,z) + psi1 = lambda z: psi(1,z) + assert psi0(3) == psi(0,3) == digamma(3) + #assert psi2(3) == psi(2,3) == tetragamma(3) + #assert psi3(3) == psi(3,3) == pentagamma(3) + assert psi0(pi).ae(0.97721330794200673) + assert psi0(-pi).ae(7.8859523853854902) + assert psi0(-pi+1).ae(7.5676424992016996) + assert psi0(pi+j).ae(1.04224048313859376 + 0.35853686544063749j) + assert psi0(-pi-j).ae(1.3404026194821986 - 2.8824392476809402j) + assert findroot(psi0, 1).ae(1.4616321449683622) + assert psi0(1e-10).ae(-10000000000.57722) + assert psi0(1e-40).ae(-1.000000000000000e+40) + assert psi0(1e-10+1e-10j).ae(-5000000000.577215 + 5000000000.000000j) + assert psi0(1e-40+1e-40j).ae(-5.000000000000000e+39 + 5.000000000000000e+39j) + assert psi0(inf) == inf + assert psi1(inf) == 0 + assert psi(2,inf) == 0 + assert psi1(pi).ae(0.37424376965420049) + assert psi1(-pi).ae(53.030438740085385) + assert psi1(pi+j).ae(0.32935710377142464 - 0.12222163911221135j) + assert psi1(-pi-j).ae(-0.30065008356019703 + 0.01149892486928227j) + assert (10**6*psi(4,1+10*pi*j)).ae(-6.1491803479004446 - 0.3921316371664063j) + assert psi0(1+10*pi*j).ae(3.4473994217222650 + 1.5548808324857071j) + assert isnan(psi0(nan)) + assert isnan(psi0(-inf)) + assert psi0(-100.5).ae(4.615124601338064) + assert psi0(3+0j).ae(psi0(3)) + assert psi0(-100+3j).ae(4.6106071768714086321+3.1117510556817394626j) + assert isnan(psi(2,mpc(0,inf))) + assert isnan(psi(2,mpc(0,nan))) + assert isnan(psi(2,mpc(0,-inf))) + assert isnan(psi(2,mpc(1,inf))) + assert isnan(psi(2,mpc(1,nan))) + assert isnan(psi(2,mpc(1,-inf))) + assert isnan(psi(2,mpc(inf,inf))) + assert isnan(psi(2,mpc(nan,nan))) + assert isnan(psi(2,mpc(-inf,-inf))) + mp.dps = 30 + # issue #534 + assert digamma(-0.75+1j).ae(mpc('0.46317279488182026118963809283042317', '2.4821070143037957102007677817351115')) + mp.dps = 15 + +def test_polygamma_high_prec(): + mp.dps = 100 + assert str(psi(0,pi)) == "0.9772133079420067332920694864061823436408346099943256380095232865318105924777141317302075654362928734" + assert str(psi(10,pi)) == "-12.98876181434889529310283769414222588307175962213707170773803550518307617769657562747174101900659238" + +def test_polygamma_identities(): + mp.dps = 15 + psi0 = lambda z: psi(0,z) + psi1 = lambda z: psi(1,z) + psi2 = lambda z: psi(2,z) + assert psi0(0.5).ae(-euler-2*log(2)) + assert psi0(1).ae(-euler) + assert psi1(0.5).ae(0.5*pi**2) + assert psi1(1).ae(pi**2/6) + assert psi1(0.25).ae(pi**2 + 8*catalan) + assert psi2(1).ae(-2*apery) + mp.dps = 20 + u = -182*apery+4*sqrt(3)*pi**3 + mp.dps = 15 + assert psi(2,5/6.).ae(u) + assert psi(3,0.5).ae(pi**4) + +def test_foxtrot_identity(): + # A test of the complex digamma function. + # See http://mathworld.wolfram.com/FoxTrotSeries.html and + # http://mathworld.wolfram.com/DigammaFunction.html + psi0 = lambda z: psi(0,z) + mp.dps = 50 + a = (-1)**fraction(1,3) + b = (-1)**fraction(2,3) + x = -psi0(0.5*a) - psi0(-0.5*b) + psi0(0.5*(1+a)) + psi0(0.5*(1-b)) + y = 2*pi*sech(0.5*sqrt(3)*pi) + assert x.ae(y) + mp.dps = 15 + +def test_polygamma_high_order(): + mp.dps = 100 + assert str(psi(50, pi)) == "-1344100348958402765749252447726432491812.641985273160531055707095989227897753035823152397679626136483" + assert str(psi(50, pi + 14*e)) == "-0.00000000000000000189793739550804321623512073101895801993019919886375952881053090844591920308111549337295143780341396" + assert str(psi(50, pi + 14*e*j)) == ("(-0.0000000000000000522516941152169248975225472155683565752375889510631513244785" + "9377385233700094871256507814151956624433 - 0.00000000000000001813157041407010184" + "702414110218205348527862196327980417757665282244728963891298080199341480881811613j)") + mp.dps = 15 + assert str(psi(50, pi)) == "-1.34410034895841e+39" + assert str(psi(50, pi + 14*e)) == "-1.89793739550804e-18" + assert str(psi(50, pi + 14*e*j)) == "(-5.2251694115217e-17 - 1.81315704140701e-17j)" + +def test_harmonic(): + mp.dps = 15 + assert harmonic(0) == 0 + assert harmonic(1) == 1 + assert harmonic(2) == 1.5 + assert harmonic(3).ae(1. + 1./2 + 1./3) + assert harmonic(10**10).ae(23.603066594891989701) + assert harmonic(10**1000).ae(2303.162308658947) + assert harmonic(0.5).ae(2-2*log(2)) + assert harmonic(inf) == inf + assert harmonic(2+0j) == 1.5+0j + assert harmonic(1+2j).ae(1.4918071802755104+0.92080728264223022j) + +def test_gamma_huge_1(): + mp.dps = 500 + x = mpf(10**10) / 7 + mp.dps = 15 + assert str(gamma(x)) == "6.26075321389519e+12458010678" + mp.dps = 50 + assert str(gamma(x)) == "6.2607532138951929201303779291707455874010420783933e+12458010678" + mp.dps = 15 + +def test_gamma_huge_2(): + mp.dps = 500 + x = mpf(10**100) / 19 + mp.dps = 15 + assert str(gamma(x)) == (\ + "1.82341134776679e+5172997469323364168990133558175077136829182824042201886051511" + "9656908623426021308685461258226190190661") + mp.dps = 50 + assert str(gamma(x)) == (\ + "1.82341134776678875374414910350027596939980412984e+5172997469323364168990133558" + "1750771368291828240422018860515119656908623426021308685461258226190190661") + +def test_gamma_huge_3(): + mp.dps = 500 + x = 10**80 // 3 + 10**70*j / 7 + mp.dps = 15 + y = gamma(x) + assert str(y.real) == (\ + "-6.82925203918106e+2636286142112569524501781477865238132302397236429627932441916" + "056964386399485392600") + assert str(y.imag) == (\ + "8.54647143678418e+26362861421125695245017814778652381323023972364296279324419160" + "56964386399485392600") + mp.dps = 50 + y = gamma(x) + assert str(y.real) == (\ + "-6.8292520391810548460682736226799637356016538421817e+26362861421125695245017814" + "77865238132302397236429627932441916056964386399485392600") + assert str(y.imag) == (\ + "8.5464714367841748507479306948130687511711420234015e+263628614211256952450178147" + "7865238132302397236429627932441916056964386399485392600") + +def test_gamma_huge_4(): + x = 3200+11500j + mp.dps = 15 + assert str(gamma(x)) == \ + "(8.95783268539713e+5164 - 1.94678798329735e+5164j)" + mp.dps = 50 + assert str(gamma(x)) == (\ + "(8.9578326853971339570292952697675570822206567327092e+5164" + " - 1.9467879832973509568895402139429643650329524144794e+51" + "64j)") + mp.dps = 15 + +def test_gamma_huge_5(): + mp.dps = 500 + x = 10**60 * j / 3 + mp.dps = 15 + y = gamma(x) + assert str(y.real) == "-3.27753899634941e-227396058973640224580963937571892628368354580620654233316839" + assert str(y.imag) == "-7.1519888950416e-227396058973640224580963937571892628368354580620654233316841" + mp.dps = 50 + y = gamma(x) + assert str(y.real) == (\ + "-3.2775389963494132168950056995974690946983219123935e-22739605897364022458096393" + "7571892628368354580620654233316839") + assert str(y.imag) == (\ + "-7.1519888950415979749736749222530209713136588885897e-22739605897364022458096393" + "7571892628368354580620654233316841") + mp.dps = 15 + +def test_gamma_huge_7(): + mp.dps = 100 + a = 3 + j/mpf(10)**1000 + mp.dps = 15 + y = gamma(a) + assert str(y.real) == "2.0" + # wrong + #assert str(y.imag) == "2.16735365342606e-1000" + assert str(y.imag) == "1.84556867019693e-1000" + mp.dps = 50 + y = gamma(a) + assert str(y.real) == "2.0" + #assert str(y.imag) == "2.1673536534260596065418805612488708028522563689298e-1000" + assert str(y.imag) == "1.8455686701969342787869758198351951379156813281202e-1000" + +def test_stieltjes(): + mp.dps = 15 + assert stieltjes(0).ae(+euler) + mp.dps = 25 + assert stieltjes(1).ae('-0.07281584548367672486058637587') + assert stieltjes(2).ae('-0.009690363192872318484530386035') + assert stieltjes(3).ae('0.002053834420303345866160046543') + assert stieltjes(4).ae('0.002325370065467300057468170178') + mp.dps = 15 + assert stieltjes(1).ae(-0.07281584548367672486058637587) + assert stieltjes(2).ae(-0.009690363192872318484530386035) + assert stieltjes(3).ae(0.002053834420303345866160046543) + assert stieltjes(4).ae(0.0023253700654673000574681701775) + +def test_barnesg(): + mp.dps = 15 + assert barnesg(0) == barnesg(-1) == 0 + assert [superfac(i) for i in range(8)] == [1, 1, 2, 12, 288, 34560, 24883200, 125411328000] + assert str(superfac(1000)) == '3.24570818422368e+1177245' + assert isnan(barnesg(nan)) + assert isnan(superfac(nan)) + assert isnan(hyperfac(nan)) + assert barnesg(inf) == inf + assert superfac(inf) == inf + assert hyperfac(inf) == inf + assert isnan(superfac(-inf)) + assert barnesg(0.7).ae(0.8068722730141471) + assert barnesg(2+3j).ae(-0.17810213864082169+0.04504542715447838j) + assert [hyperfac(n) for n in range(7)] == [1, 1, 4, 108, 27648, 86400000, 4031078400000] + assert [hyperfac(n) for n in range(0,-7,-1)] == [1,1,-1,-4,108,27648,-86400000] + a = barnesg(-3+0j) + assert a == 0 and isinstance(a, mpc) + a = hyperfac(-3+0j) + assert a == -4 and isinstance(a, mpc) + +def test_polylog(): + mp.dps = 15 + zs = [mpmathify(z) for z in [0, 0.5, 0.99, 4, -0.5, -4, 1j, 3+4j]] + for z in zs: assert polylog(1, z).ae(-log(1-z)) + for z in zs: assert polylog(0, z).ae(z/(1-z)) + for z in zs: assert polylog(-1, z).ae(z/(1-z)**2) + for z in zs: assert polylog(-2, z).ae(z*(1+z)/(1-z)**3) + for z in zs: assert polylog(-3, z).ae(z*(1+4*z+z**2)/(1-z)**4) + assert polylog(3, 7).ae(5.3192579921456754382-5.9479244480803301023j) + assert polylog(3, -7).ae(-4.5693548977219423182) + assert polylog(2, 0.9).ae(1.2997147230049587252) + assert polylog(2, -0.9).ae(-0.75216317921726162037) + assert polylog(2, 0.9j).ae(-0.17177943786580149299+0.83598828572550503226j) + assert polylog(2, 1.1).ae(1.9619991013055685931-0.2994257606855892575j) + assert polylog(2, -1.1).ae(-0.89083809026228260587) + assert polylog(2, 1.1*sqrt(j)).ae(0.58841571107611387722+1.09962542118827026011j) + assert polylog(-2, 0.9).ae(1710) + assert polylog(-2, -0.9).ae(-90/6859.) + assert polylog(3, 0.9).ae(1.0496589501864398696) + assert polylog(-3, 0.9).ae(48690) + assert polylog(-3, -4).ae(-0.0064) + assert polylog(0.5+j/3, 0.5+j/2).ae(0.31739144796565650535 + 0.99255390416556261437j) + assert polylog(3+4j,1).ae(zeta(3+4j)) + assert polylog(3+4j,-1).ae(-altzeta(3+4j)) + # issue 390 + assert polylog(1.5, -48.910886523731889).ae(-6.272992229311817) + assert polylog(1.5, 200).ae(-8.349608319033686529 - 8.159694826434266042j) + assert polylog(-2+0j, -2).ae(mpf(1)/13.5) + assert polylog(-2+0j, 1.25).ae(-180) + +def test_bell_polyexp(): + mp.dps = 15 + # TODO: more tests for polyexp + assert (polyexp(0,1e-10)*10**10).ae(1.00000000005) + assert (polyexp(1,1e-10)*10**10).ae(1.0000000001) + assert polyexp(5,3j).ae(-607.7044517476176454+519.962786482001476087j) + assert polyexp(-1,3.5).ae(12.09537536175543444) + # bell(0,x) = 1 + assert bell(0,0) == 1 + assert bell(0,1) == 1 + assert bell(0,2) == 1 + assert bell(0,inf) == 1 + assert bell(0,-inf) == 1 + assert isnan(bell(0,nan)) + # bell(1,x) = x + assert bell(1,4) == 4 + assert bell(1,0) == 0 + assert bell(1,inf) == inf + assert bell(1,-inf) == -inf + assert isnan(bell(1,nan)) + # bell(2,x) = x*(1+x) + assert bell(2,-1) == 0 + assert bell(2,0) == 0 + # large orders / arguments + assert bell(10) == 115975 + assert bell(10,1) == 115975 + assert bell(10, -8) == 11054008 + assert bell(5,-50) == -253087550 + assert bell(50,-50).ae('3.4746902914629720259e74') + mp.dps = 80 + assert bell(50,-50) == 347469029146297202586097646631767227177164818163463279814268368579055777450 + assert bell(40,50) == 5575520134721105844739265207408344706846955281965031698187656176321717550 + assert bell(74) == 5006908024247925379707076470957722220463116781409659160159536981161298714301202 + mp.dps = 15 + assert bell(10,20j) == 7504528595600+15649605360020j + # continuity of the generalization + assert bell(0.5,0).ae(sinc(pi*0.5)) + +def test_primezeta(): + mp.dps = 15 + assert primezeta(0.9).ae(1.8388316154446882243 + 3.1415926535897932385j) + assert primezeta(4).ae(0.076993139764246844943) + assert primezeta(1) == inf + assert primezeta(inf) == 0 + assert isnan(primezeta(nan)) + +def test_rs_zeta(): + mp.dps = 15 + assert zeta(0.5+100000j).ae(1.0730320148577531321 + 5.7808485443635039843j) + assert zeta(0.75+100000j).ae(1.837852337251873704 + 1.9988492668661145358j) + assert zeta(0.5+1000000j, derivative=3).ae(1647.7744105852674733 - 1423.1270943036622097j) + assert zeta(1+1000000j, derivative=3).ae(3.4085866124523582894 - 18.179184721525947301j) + assert zeta(1+1000000j, derivative=1).ae(-0.10423479366985452134 - 0.74728992803359056244j) + assert zeta(0.5-1000000j, derivative=1).ae(11.636804066002521459 + 17.127254072212996004j) + # Additional sanity tests using fp arithmetic. + # Some more high-precision tests are found in the docstrings + def ae(x, y, tol=1e-6): + return abs(x-y) < tol*abs(y) + assert ae(fp.zeta(0.5-100000j), 1.0730320148577531321 - 5.7808485443635039843j) + assert ae(fp.zeta(0.75-100000j), 1.837852337251873704 - 1.9988492668661145358j) + assert ae(fp.zeta(0.5+1e6j), 0.076089069738227100006 + 2.8051021010192989554j) + assert ae(fp.zeta(0.5+1e6j, derivative=1), 11.636804066002521459 - 17.127254072212996004j) + assert ae(fp.zeta(1+1e6j), 0.94738726251047891048 + 0.59421999312091832833j) + assert ae(fp.zeta(1+1e6j, derivative=1), -0.10423479366985452134 - 0.74728992803359056244j) + assert ae(fp.zeta(0.5+100000j, derivative=1), 10.766962036817482375 - 30.92705282105996714j) + assert ae(fp.zeta(0.5+100000j, derivative=2), -119.40515625740538429 + 217.14780631141830251j) + assert ae(fp.zeta(0.5+100000j, derivative=3), 1129.7550282628460881 - 1685.4736895169690346j) + assert ae(fp.zeta(0.5+100000j, derivative=4), -10407.160819314958615 + 13777.786698628045085j) + assert ae(fp.zeta(0.75+100000j, derivative=1), -0.41742276699594321475 - 6.4453816275049955949j) + assert ae(fp.zeta(0.75+100000j, derivative=2), -9.214314279161977266 + 35.07290795337967899j) + assert ae(fp.zeta(0.75+100000j, derivative=3), 110.61331857820103469 - 236.87847130518129926j) + assert ae(fp.zeta(0.75+100000j, derivative=4), -1054.334275898559401 + 1769.9177890161596383j) + +def test_siegelz(): + mp.dps = 15 + assert siegelz(100000).ae(5.87959246868176504171) + assert siegelz(100000, derivative=2).ae(-54.1172711010126452832) + assert siegelz(100000, derivative=3).ae(-278.930831343966552538) + assert siegelz(100000+j,derivative=1).ae(678.214511857070283307-379.742160779916375413j) + + + +def test_zeta_near_1(): + # Test for a former bug in mpf_zeta and mpc_zeta + mp.dps = 15 + s1 = fadd(1, '1e-10', exact=True) + s2 = fadd(1, '-1e-10', exact=True) + s3 = fadd(1, '1e-10j', exact=True) + assert zeta(s1).ae(1.000000000057721566490881444e10) + assert zeta(s2).ae(-9.99999999942278433510574872e9) + z = zeta(s3) + assert z.real.ae(0.57721566490153286060) + assert z.imag.ae(-9.9999999999999999999927184e9) + mp.dps = 30 + s1 = fadd(1, '1e-50', exact=True) + s2 = fadd(1, '-1e-50', exact=True) + s3 = fadd(1, '1e-50j', exact=True) + assert zeta(s1).ae('1e50') + assert zeta(s2).ae('-1e50') + z = zeta(s3) + assert z.real.ae('0.57721566490153286060651209008240243104215933593992') + assert z.imag.ae('-1e50') diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_hp.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_hp.py new file mode 100644 index 0000000000000000000000000000000000000000..9eba0af798f64ac3f8d464e2d3bf231567a48c9b --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_hp.py @@ -0,0 +1,291 @@ +""" +Check that the output from irrational functions is accurate for +high-precision input, from 5 to 200 digits. The reference values were +verified with Mathematica. +""" + +import time +from mpmath import * + +precs = [5, 15, 28, 35, 57, 80, 100, 150, 200] + +# sqrt(3) + pi/2 +a = \ +"3.302847134363773912758768033145623809041389953497933538543279275605"\ +"841220051904536395163599428307109666700184672047856353516867399774243594"\ +"67433521615861420725323528325327484262075464241255915238845599752675" + +# e + 1/euler**2 +b = \ +"5.719681166601007617111261398629939965860873957353320734275716220045750"\ +"31474116300529519620938123730851145473473708966080207482581266469342214"\ +"824842256999042984813905047895479210702109260221361437411947323431" + +# sqrt(a) +sqrt_a = \ +"1.817373691447021556327498239690365674922395036495564333152483422755"\ +"144321726165582817927383239308173567921345318453306994746434073691275094"\ +"484777905906961689902608644112196725896908619756404253109722911487" + +# sqrt(a+b*i).real +sqrt_abi_real = \ +"2.225720098415113027729407777066107959851146508557282707197601407276"\ +"89160998185797504198062911768240808839104987021515555650875977724230130"\ +"3584116233925658621288393930286871862273400475179312570274423840384" + +# sqrt(a+b*i).imag +sqrt_abi_imag = \ +"1.2849057639084690902371581529110949983261182430040898147672052833653668"\ +"0629534491275114877090834296831373498336559849050755848611854282001250"\ +"1924311019152914021365263161630765255610885489295778894976075186" + +# log(a) +log_a = \ +"1.194784864491089550288313512105715261520511949410072046160598707069"\ +"4336653155025770546309137440687056366757650909754708302115204338077595203"\ +"83005773986664564927027147084436553262269459110211221152925732612" + +# log(a+b*i).real +log_abi_real = \ +"1.8877985921697018111624077550443297276844736840853590212962006811663"\ +"04949387789489704203167470111267581371396245317618589339274243008242708"\ +"014251531496104028712866224020066439049377679709216784954509456421" + +# log(a+b*i).imag +log_abi_imag = \ +"1.0471204952840802663567714297078763189256357109769672185219334169734948"\ +"4265809854092437285294686651806426649541504240470168212723133326542181"\ +"8300136462287639956713914482701017346851009323172531601894918640" + +# exp(a) +exp_a = \ +"27.18994224087168661137253262213293847994194869430518354305430976149"\ +"382792035050358791398632888885200049857986258414049540376323785711941636"\ +"100358982497583832083513086941635049329804685212200507288797531143" + +# exp(a+b*i).real +exp_abi_real = \ +"22.98606617170543596386921087657586890620262522816912505151109385026"\ +"40160179326569526152851983847133513990281518417211964710397233157168852"\ +"4963130831190142571659948419307628119985383887599493378056639916701" + +# exp(a+b*i).imag +exp_abi_imag = \ +"-14.523557450291489727214750571590272774669907424478129280902375851196283"\ +"3377162379031724734050088565710975758824441845278120105728824497308303"\ +"6065619788140201636218705414429933685889542661364184694108251449" + +# a**b +pow_a_b = \ +"928.7025342285568142947391505837660251004990092821305668257284426997"\ +"361966028275685583421197860603126498884545336686124793155581311527995550"\ +"580229264427202446131740932666832138634013168125809402143796691154" + +# (a**(a+b*i)).real +pow_a_abi_real = \ +"44.09156071394489511956058111704382592976814280267142206420038656267"\ +"67707916510652790502399193109819563864568986234654864462095231138500505"\ +"8197456514795059492120303477512711977915544927440682508821426093455" + +# (a**(a+b*i)).imag +pow_a_abi_imag = \ +"27.069371511573224750478105146737852141664955461266218367212527612279886"\ +"9322304536553254659049205414427707675802193810711302947536332040474573"\ +"8166261217563960235014674118610092944307893857862518964990092301" + +# ((a+b*i)**(a+b*i)).real +pow_abi_abi_real = \ +"-0.15171310677859590091001057734676423076527145052787388589334350524"\ +"8084195882019497779202452975350579073716811284169068082670778986235179"\ +"0813026562962084477640470612184016755250592698408112493759742219150452"\ + +# ((a+b*i)**(a+b*i)).imag +pow_abi_abi_imag = \ +"1.2697592504953448936553147870155987153192995316950583150964099070426"\ +"4736837932577176947632535475040521749162383347758827307504526525647759"\ +"97547638617201824468382194146854367480471892602963428122896045019902" + +# sin(a) +sin_a = \ +"-0.16055653857469062740274792907968048154164433772938156243509084009"\ +"38437090841460493108570147191289893388608611542655654723437248152535114"\ +"528368009465836614227575701220612124204622383149391870684288862269631" + +# sin(1000*a) +sin_1000a = \ +"-0.85897040577443833776358106803777589664322997794126153477060795801"\ +"09151695416961724733492511852267067419573754315098042850381158563024337"\ +"216458577140500488715469780315833217177634490142748614625281171216863" + +# sin(a+b*i) +sin_abi_real = \ +"-24.4696999681556977743346798696005278716053366404081910969773939630"\ +"7149215135459794473448465734589287491880563183624997435193637389884206"\ +"02151395451271809790360963144464736839412254746645151672423256977064" + +sin_abi_imag = \ +"-150.42505378241784671801405965872972765595073690984080160750785565810981"\ +"8314482499135443827055399655645954830931316357243750839088113122816583"\ +"7169201254329464271121058839499197583056427233866320456505060735" + +# cos +cos_a = \ +"-0.98702664499035378399332439243967038895709261414476495730788864004"\ +"05406821549361039745258003422386169330787395654908532996287293003581554"\ +"257037193284199198069707141161341820684198547572456183525659969145501" + +cos_1000a = \ +"-0.51202523570982001856195696460663971099692261342827540426136215533"\ +"52686662667660613179619804463250686852463876088694806607652218586060613"\ +"951310588158830695735537073667299449753951774916401887657320950496820" + +# tan +tan_a = \ +"0.162666873675188117341401059858835168007137819495998960250142156848"\ +"639654718809412181543343168174807985559916643549174530459883826451064966"\ +"7996119428949951351938178809444268785629011625179962457123195557310" + +tan_abi_real = \ +"6.822696615947538488826586186310162599974827139564433912601918442911"\ +"1026830824380070400102213741875804368044342309515353631134074491271890"\ +"467615882710035471686578162073677173148647065131872116479947620E-6" + +tan_abi_imag = \ +"0.9999795833048243692245661011298447587046967777739649018690797625964167"\ +"1446419978852235960862841608081413169601038230073129482874832053357571"\ +"62702259309150715669026865777947502665936317953101462202542168429" + + +def test_hp(): + for dps in precs: + mp.dps = dps + 8 + aa = mpf(a) + bb = mpf(b) + a1000 = 1000*mpf(a) + abi = mpc(aa, bb) + mp.dps = dps + assert (sqrt(3) + pi/2).ae(aa) + assert (e + 1/euler**2).ae(bb) + + assert sqrt(aa).ae(mpf(sqrt_a)) + assert sqrt(abi).ae(mpc(sqrt_abi_real, sqrt_abi_imag)) + + assert log(aa).ae(mpf(log_a)) + assert log(abi).ae(mpc(log_abi_real, log_abi_imag)) + + assert exp(aa).ae(mpf(exp_a)) + assert exp(abi).ae(mpc(exp_abi_real, exp_abi_imag)) + + assert (aa**bb).ae(mpf(pow_a_b)) + assert (aa**abi).ae(mpc(pow_a_abi_real, pow_a_abi_imag)) + assert (abi**abi).ae(mpc(pow_abi_abi_real, pow_abi_abi_imag)) + + assert sin(a).ae(mpf(sin_a)) + assert sin(a1000).ae(mpf(sin_1000a)) + assert sin(abi).ae(mpc(sin_abi_real, sin_abi_imag)) + + assert cos(a).ae(mpf(cos_a)) + assert cos(a1000).ae(mpf(cos_1000a)) + + assert tan(a).ae(mpf(tan_a)) + assert tan(abi).ae(mpc(tan_abi_real, tan_abi_imag)) + + # check that complex cancellation is avoided so that both + # real and imaginary parts have high relative accuracy. + # abs_eps should be 0, but has to be set to 1e-205 to pass the + # 200-digit case, probably due to slight inaccuracy in the + # precomputed input + assert (tan(abi).real).ae(mpf(tan_abi_real), abs_eps=1e-205) + assert (tan(abi).imag).ae(mpf(tan_abi_imag), abs_eps=1e-205) + mp.dps = 460 + assert str(log(3))[-20:] == '02166121184001409826' + mp.dps = 15 + +# Since str(a) can differ in the last digit from rounded a, and I want +# to compare the last digits of big numbers with the results in Mathematica, +# I made this hack to get the last 20 digits of rounded a + +def last_digits(a): + r = repr(a) + s = str(a) + #dps = mp.dps + #mp.dps += 3 + m = 10 + r = r.replace(s[:-m],'') + r = r.replace("mpf('",'').replace("')",'') + num0 = 0 + for c in r: + if c == '0': + num0 += 1 + else: + break + b = float(int(r))/10**(len(r) - m) + if b >= 10**m - 0.5: # pragma: no cover + raise NotImplementedError + n = int(round(b)) + sn = str(n) + s = s[:-m] + '0'*num0 + sn + return s[-20:] + +# values checked with Mathematica +def test_log_hp(): + mp.dps = 2000 + a = mpf(10)**15000/3 + r = log(a) + res = last_digits(r) + # Mathematica N[Log[10^15000/3], 2000] + # ...7443804441768333470331 + assert res == '43804441768333470331' + + # see issue 145 + r = log(mpf(3)/2) + # Mathematica N[Log[3/2], 2000] + # ...69653749808140753263288 + res = last_digits(r) + assert res == '53749808140753263288' + + mp.dps = 10000 + r = log(2) + res = last_digits(r) + # Mathematica N[Log[2], 10000] + # ...695615913401856601359655561 + assert res == '13401856601359655561' + r = log(mpf(10)**10/3) + res = last_digits(r) + # Mathematica N[Log[10^10/3], 10000] + # ...587087654020631943060007154 + assert res == '54020631943060007154', res + r = log(mpf(10)**100/3) + res = last_digits(r) + # Mathematica N[Log[10^100/3], 10000] + # ,,,59246336539088351652334666 + assert res == '36539088351652334666', res + mp.dps += 10 + a = 1 - mpf(1)/10**10 + mp.dps -= 10 + r = log(a) + res = last_digits(r) + # ...3310334360482956137216724048322957404 + # 372167240483229574038733026370 + # Mathematica N[Log[1 - 10^-10]*10^10, 10000] + # ...60482956137216724048322957404 + assert res == '37216724048322957404', res + mp.dps = 10000 + mp.dps += 100 + a = 1 + mpf(1)/10**100 + mp.dps -= 100 + + r = log(a) + res = last_digits(+r) + # Mathematica N[Log[1 + 10^-100]*10^10, 10030] + # ...3994733877377412241546890854692521568292338268273 10^-91 + assert res == '39947338773774122415', res + + mp.dps = 15 + +def test_exp_hp(): + mp.dps = 4000 + r = exp(mpf(1)/10) + # IntegerPart[N[Exp[1/10] * 10^4000, 4000]] + # ...92167105162069688129 + assert int(r * 10**mp.dps) % 10**20 == 92167105162069688129 diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_identify.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_identify.py new file mode 100644 index 0000000000000000000000000000000000000000..f75ab0bc4f04ecb614011e7f4599989465cab785 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_identify.py @@ -0,0 +1,19 @@ +from mpmath import * + +def test_pslq(): + mp.dps = 15 + assert pslq([3*pi+4*e/7, pi, e, log(2)]) == [7, -21, -4, 0] + assert pslq([4.9999999999999991, 1]) == [1, -5] + assert pslq([2,1]) == [1, -2] + +def test_identify(): + mp.dps = 20 + assert identify(zeta(4), ['log(2)', 'pi**4']) == '((1/90)*pi**4)' + mp.dps = 15 + assert identify(exp(5)) == 'exp(5)' + assert identify(exp(4)) == 'exp(4)' + assert identify(log(5)) == 'log(5)' + assert identify(exp(3*pi), ['pi']) == 'exp((3*pi))' + assert identify(3, full=True) == ['3', '3', '1/(1/3)', 'sqrt(9)', + '1/sqrt((1/9))', '(sqrt(12)/2)**2', '1/(sqrt(12)/6)**2'] + assert identify(pi+1, {'a':+pi}) == '(1 + 1*a)' diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_interval.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_interval.py new file mode 100644 index 0000000000000000000000000000000000000000..251fd8b7ddb00074e8ae27cce4a01d8f4f8fe151 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_interval.py @@ -0,0 +1,453 @@ +from mpmath import * + +def test_interval_identity(): + iv.dps = 15 + assert mpi(2) == mpi(2, 2) + assert mpi(2) != mpi(-2, 2) + assert not (mpi(2) != mpi(2, 2)) + assert mpi(-1, 1) == mpi(-1, 1) + assert str(mpi('0.1')) == "[0.099999999999999991673, 0.10000000000000000555]" + assert repr(mpi('0.1')) == "mpi('0.099999999999999992', '0.10000000000000001')" + u = mpi(-1, 3) + assert -1 in u + assert 2 in u + assert 3 in u + assert -1.1 not in u + assert 3.1 not in u + assert mpi(-1, 3) in u + assert mpi(0, 1) in u + assert mpi(-1.1, 2) not in u + assert mpi(2.5, 3.1) not in u + w = mpi(-inf, inf) + assert mpi(-5, 5) in w + assert mpi(2, inf) in w + assert mpi(0, 2) in mpi(0, 10) + assert not (3 in mpi(-inf, 0)) + +def test_interval_hash(): + assert hash(mpi(3)) == hash(3) + assert hash(mpi(3.25)) == hash(3.25) + assert hash(mpi(3,4)) == hash(mpi(3,4)) + assert hash(iv.mpc(3)) == hash(3) + assert hash(iv.mpc(3,4)) == hash(3+4j) + assert hash(iv.mpc((1,3),(2,4))) == hash(iv.mpc((1,3),(2,4))) + +def test_interval_arithmetic(): + iv.dps = 15 + assert mpi(2) + mpi(3,4) == mpi(5,6) + assert mpi(1, 2)**2 == mpi(1, 4) + assert mpi(1) + mpi(0, 1e-50) == mpi(1, mpf('1.0000000000000002')) + x = 1 / (1 / mpi(3)) + assert x.a < 3 < x.b + x = mpi(2) ** mpi(0.5) + iv.dps += 5 + sq = iv.sqrt(2) + iv.dps -= 5 + assert x.a < sq < x.b + assert mpi(1) / mpi(1, inf) + assert mpi(2, 3) / inf == mpi(0, 0) + assert mpi(0) / inf == 0 + assert mpi(0) / 0 == mpi(-inf, inf) + assert mpi(inf) / 0 == mpi(-inf, inf) + assert mpi(0) * inf == mpi(-inf, inf) + assert 1 / mpi(2, inf) == mpi(0, 0.5) + assert str((mpi(50, 50) * mpi(-10, -10)) / 3) == \ + '[-166.66666666666668561, -166.66666666666665719]' + assert mpi(0, 4) ** 3 == mpi(0, 64) + assert mpi(2,4).mid == 3 + iv.dps = 30 + a = mpi(iv.pi) + iv.dps = 15 + b = +a + assert b.a < a.a + assert b.b > a.b + a = mpi(iv.pi) + assert a == +a + assert abs(mpi(-1,2)) == mpi(0,2) + assert abs(mpi(0.5,2)) == mpi(0.5,2) + assert abs(mpi(-3,2)) == mpi(0,3) + assert abs(mpi(-3,-0.5)) == mpi(0.5,3) + assert mpi(0) * mpi(2,3) == mpi(0) + assert mpi(2,3) * mpi(0) == mpi(0) + assert mpi(1,3).delta == 2 + assert mpi(1,2) - mpi(3,4) == mpi(-3,-1) + assert mpi(-inf,0) - mpi(0,inf) == mpi(-inf,0) + assert mpi(-inf,0) - mpi(-inf,inf) == mpi(-inf,inf) + assert mpi(0,inf) - mpi(-inf,1) == mpi(-1,inf) + +def test_interval_mul(): + assert mpi(-1, 0) * inf == mpi(-inf, 0) + assert mpi(-1, 0) * -inf == mpi(0, inf) + assert mpi(0, 1) * inf == mpi(0, inf) + assert mpi(0, 1) * mpi(0, inf) == mpi(0, inf) + assert mpi(-1, 1) * inf == mpi(-inf, inf) + assert mpi(-1, 1) * mpi(0, inf) == mpi(-inf, inf) + assert mpi(-1, 1) * mpi(-inf, inf) == mpi(-inf, inf) + assert mpi(-inf, 0) * mpi(0, 1) == mpi(-inf, 0) + assert mpi(-inf, 0) * mpi(0, 0) * mpi(-inf, 0) + assert mpi(-inf, 0) * mpi(-inf, inf) == mpi(-inf, inf) + assert mpi(-5,0)*mpi(-32,28) == mpi(-140,160) + assert mpi(2,3) * mpi(-1,2) == mpi(-3,6) + # Should be undefined? + assert mpi(inf, inf) * 0 == mpi(-inf, inf) + assert mpi(-inf, -inf) * 0 == mpi(-inf, inf) + assert mpi(0) * mpi(-inf,2) == mpi(-inf,inf) + assert mpi(0) * mpi(-2,inf) == mpi(-inf,inf) + assert mpi(-2,inf) * mpi(0) == mpi(-inf,inf) + assert mpi(-inf,2) * mpi(0) == mpi(-inf,inf) + +def test_interval_pow(): + assert mpi(3)**2 == mpi(9, 9) + assert mpi(-3)**2 == mpi(9, 9) + assert mpi(-3, 1)**2 == mpi(0, 9) + assert mpi(-3, -1)**2 == mpi(1, 9) + assert mpi(-3, -1)**3 == mpi(-27, -1) + assert mpi(-3, 1)**3 == mpi(-27, 1) + assert mpi(-2, 3)**2 == mpi(0, 9) + assert mpi(-3, 2)**2 == mpi(0, 9) + assert mpi(4) ** -1 == mpi(0.25, 0.25) + assert mpi(-4) ** -1 == mpi(-0.25, -0.25) + assert mpi(4) ** -2 == mpi(0.0625, 0.0625) + assert mpi(-4) ** -2 == mpi(0.0625, 0.0625) + assert mpi(0, 1) ** inf == mpi(0, 1) + assert mpi(0, 1) ** -inf == mpi(1, inf) + assert mpi(0, inf) ** inf == mpi(0, inf) + assert mpi(0, inf) ** -inf == mpi(0, inf) + assert mpi(1, inf) ** inf == mpi(1, inf) + assert mpi(1, inf) ** -inf == mpi(0, 1) + assert mpi(2, 3) ** 1 == mpi(2, 3) + assert mpi(2, 3) ** 0 == 1 + assert mpi(1,3) ** mpi(2) == mpi(1,9) + +def test_interval_sqrt(): + assert mpi(4) ** 0.5 == mpi(2) + +def test_interval_div(): + assert mpi(0.5, 1) / mpi(-1, 0) == mpi(-inf, -0.5) + assert mpi(0, 1) / mpi(0, 1) == mpi(0, inf) + assert mpi(inf, inf) / mpi(inf, inf) == mpi(0, inf) + assert mpi(inf, inf) / mpi(2, inf) == mpi(0, inf) + assert mpi(inf, inf) / mpi(2, 2) == mpi(inf, inf) + assert mpi(0, inf) / mpi(2, inf) == mpi(0, inf) + assert mpi(0, inf) / mpi(2, 2) == mpi(0, inf) + assert mpi(2, inf) / mpi(2, 2) == mpi(1, inf) + assert mpi(2, inf) / mpi(2, inf) == mpi(0, inf) + assert mpi(-4, 8) / mpi(1, inf) == mpi(-4, 8) + assert mpi(-4, 8) / mpi(0.5, inf) == mpi(-8, 16) + assert mpi(-inf, 8) / mpi(0.5, inf) == mpi(-inf, 16) + assert mpi(-inf, inf) / mpi(0.5, inf) == mpi(-inf, inf) + assert mpi(8, inf) / mpi(0.5, inf) == mpi(0, inf) + assert mpi(-8, inf) / mpi(0.5, inf) == mpi(-16, inf) + assert mpi(-4, 8) / mpi(inf, inf) == mpi(0, 0) + assert mpi(0, 8) / mpi(inf, inf) == mpi(0, 0) + assert mpi(0, 0) / mpi(inf, inf) == mpi(0, 0) + assert mpi(-inf, 0) / mpi(inf, inf) == mpi(-inf, 0) + assert mpi(-inf, 8) / mpi(inf, inf) == mpi(-inf, 0) + assert mpi(-inf, inf) / mpi(inf, inf) == mpi(-inf, inf) + assert mpi(-8, inf) / mpi(inf, inf) == mpi(0, inf) + assert mpi(0, inf) / mpi(inf, inf) == mpi(0, inf) + assert mpi(8, inf) / mpi(inf, inf) == mpi(0, inf) + assert mpi(inf, inf) / mpi(inf, inf) == mpi(0, inf) + assert mpi(-1, 2) / mpi(0, 1) == mpi(-inf, +inf) + assert mpi(0, 1) / mpi(0, 1) == mpi(0.0, +inf) + assert mpi(-1, 0) / mpi(0, 1) == mpi(-inf, 0.0) + assert mpi(-0.5, -0.25) / mpi(0, 1) == mpi(-inf, -0.25) + assert mpi(0.5, 1) / mpi(0, 1) == mpi(0.5, +inf) + assert mpi(0.5, 4) / mpi(0, 1) == mpi(0.5, +inf) + assert mpi(-1, -0.5) / mpi(0, 1) == mpi(-inf, -0.5) + assert mpi(-4, -0.5) / mpi(0, 1) == mpi(-inf, -0.5) + assert mpi(-1, 2) / mpi(-2, 0.5) == mpi(-inf, +inf) + assert mpi(0, 1) / mpi(-2, 0.5) == mpi(-inf, +inf) + assert mpi(-1, 0) / mpi(-2, 0.5) == mpi(-inf, +inf) + assert mpi(-0.5, -0.25) / mpi(-2, 0.5) == mpi(-inf, +inf) + assert mpi(0.5, 1) / mpi(-2, 0.5) == mpi(-inf, +inf) + assert mpi(0.5, 4) / mpi(-2, 0.5) == mpi(-inf, +inf) + assert mpi(-1, -0.5) / mpi(-2, 0.5) == mpi(-inf, +inf) + assert mpi(-4, -0.5) / mpi(-2, 0.5) == mpi(-inf, +inf) + assert mpi(-1, 2) / mpi(-1, 0) == mpi(-inf, +inf) + assert mpi(0, 1) / mpi(-1, 0) == mpi(-inf, 0.0) + assert mpi(-1, 0) / mpi(-1, 0) == mpi(0.0, +inf) + assert mpi(-0.5, -0.25) / mpi(-1, 0) == mpi(0.25, +inf) + assert mpi(0.5, 1) / mpi(-1, 0) == mpi(-inf, -0.5) + assert mpi(0.5, 4) / mpi(-1, 0) == mpi(-inf, -0.5) + assert mpi(-1, -0.5) / mpi(-1, 0) == mpi(0.5, +inf) + assert mpi(-4, -0.5) / mpi(-1, 0) == mpi(0.5, +inf) + assert mpi(-1, 2) / mpi(0.5, 1) == mpi(-2.0, 4.0) + assert mpi(0, 1) / mpi(0.5, 1) == mpi(0.0, 2.0) + assert mpi(-1, 0) / mpi(0.5, 1) == mpi(-2.0, 0.0) + assert mpi(-0.5, -0.25) / mpi(0.5, 1) == mpi(-1.0, -0.25) + assert mpi(0.5, 1) / mpi(0.5, 1) == mpi(0.5, 2.0) + assert mpi(0.5, 4) / mpi(0.5, 1) == mpi(0.5, 8.0) + assert mpi(-1, -0.5) / mpi(0.5, 1) == mpi(-2.0, -0.5) + assert mpi(-4, -0.5) / mpi(0.5, 1) == mpi(-8.0, -0.5) + assert mpi(-1, 2) / mpi(-2, -0.5) == mpi(-4.0, 2.0) + assert mpi(0, 1) / mpi(-2, -0.5) == mpi(-2.0, 0.0) + assert mpi(-1, 0) / mpi(-2, -0.5) == mpi(0.0, 2.0) + assert mpi(-0.5, -0.25) / mpi(-2, -0.5) == mpi(0.125, 1.0) + assert mpi(0.5, 1) / mpi(-2, -0.5) == mpi(-2.0, -0.25) + assert mpi(0.5, 4) / mpi(-2, -0.5) == mpi(-8.0, -0.25) + assert mpi(-1, -0.5) / mpi(-2, -0.5) == mpi(0.25, 2.0) + assert mpi(-4, -0.5) / mpi(-2, -0.5) == mpi(0.25, 8.0) + # Should be undefined? + assert mpi(0, 0) / mpi(0, 0) == mpi(-inf, inf) + assert mpi(0, 0) / mpi(0, 1) == mpi(-inf, inf) + +def test_interval_cos_sin(): + iv.dps = 15 + cos = iv.cos + sin = iv.sin + tan = iv.tan + pi = iv.pi + # Around 0 + assert cos(mpi(0)) == 1 + assert sin(mpi(0)) == 0 + assert cos(mpi(0,1)) == mpi(0.54030230586813965399, 1.0) + assert sin(mpi(0,1)) == mpi(0, 0.8414709848078966159) + assert cos(mpi(1,2)) == mpi(-0.4161468365471424069, 0.54030230586813976501) + assert sin(mpi(1,2)) == mpi(0.84147098480789650488, 1.0) + assert sin(mpi(1,2.5)) == mpi(0.59847214410395643824, 1.0) + assert cos(mpi(-1, 1)) == mpi(0.54030230586813965399, 1.0) + assert cos(mpi(-1, 0.5)) == mpi(0.54030230586813965399, 1.0) + assert cos(mpi(-1, 1.5)) == mpi(0.070737201667702906405, 1.0) + assert sin(mpi(-1,1)) == mpi(-0.8414709848078966159, 0.8414709848078966159) + assert sin(mpi(-1,0.5)) == mpi(-0.8414709848078966159, 0.47942553860420300538) + assert mpi(-0.8414709848078966159, 1.00000000000000002e-100) in sin(mpi(-1,1e-100)) + assert mpi(-2.00000000000000004e-100, 1.00000000000000002e-100) in sin(mpi(-2e-100,1e-100)) + # Same interval + assert cos(mpi(2, 2.5)) + assert cos(mpi(3.5, 4)) == mpi(-0.93645668729079634129, -0.65364362086361182946) + assert cos(mpi(5, 5.5)) == mpi(0.28366218546322624627, 0.70866977429126010168) + assert mpi(0.59847214410395654927, 0.90929742682568170942) in sin(mpi(2, 2.5)) + assert sin(mpi(3.5, 4)) == mpi(-0.75680249530792831347, -0.35078322768961983646) + assert sin(mpi(5, 5.5)) == mpi(-0.95892427466313856499, -0.70554032557039181306) + # Higher roots + iv.dps = 55 + w = 4*10**50 + mpi(0.5) + for p in [15, 40, 80]: + iv.dps = p + assert 0 in sin(4*mpi(pi)) + assert 0 in sin(4*10**50*mpi(pi)) + assert 0 in cos((4+0.5)*mpi(pi)) + assert 0 in cos(w*mpi(pi)) + assert 1 in cos(4*mpi(pi)) + assert 1 in cos(4*10**50*mpi(pi)) + iv.dps = 15 + assert cos(mpi(2,inf)) == mpi(-1,1) + assert sin(mpi(2,inf)) == mpi(-1,1) + assert cos(mpi(-inf,2)) == mpi(-1,1) + assert sin(mpi(-inf,2)) == mpi(-1,1) + u = tan(mpi(0.5,1)) + assert mpf(u.a).ae(mp.tan(0.5)) + assert mpf(u.b).ae(mp.tan(1)) + v = iv.cot(mpi(0.5,1)) + assert mpf(v.a).ae(mp.cot(1)) + assert mpf(v.b).ae(mp.cot(0.5)) + # Sanity check of evaluation at n*pi and (n+1/2)*pi + for n in range(-5,7,2): + x = iv.cos(n*iv.pi) + assert -1 in x + assert x >= -1 + assert x != -1 + x = iv.sin((n+0.5)*iv.pi) + assert -1 in x + assert x >= -1 + assert x != -1 + for n in range(-6,8,2): + x = iv.cos(n*iv.pi) + assert 1 in x + assert x <= 1 + if n: + assert x != 1 + x = iv.sin((n+0.5)*iv.pi) + assert 1 in x + assert x <= 1 + assert x != 1 + for n in range(-6,7): + x = iv.cos((n+0.5)*iv.pi) + assert x.a < 0 < x.b + x = iv.sin(n*iv.pi) + if n: + assert x.a < 0 < x.b + +def test_interval_complex(): + # TODO: many more tests + iv.dps = 15 + mp.dps = 15 + assert iv.mpc(2,3) == 2+3j + assert iv.mpc(2,3) != 2+4j + assert iv.mpc(2,3) != 1+3j + assert 1+3j in iv.mpc([1,2],[3,4]) + assert 2+5j not in iv.mpc([1,2],[3,4]) + assert iv.mpc(1,2) + 1j == 1+3j + assert iv.mpc([1,2],[2,3]) + 2+3j == iv.mpc([3,4],[5,6]) + assert iv.mpc([2,4],[4,8]) / 2 == iv.mpc([1,2],[2,4]) + assert iv.mpc([1,2],[2,4]) * 2j == iv.mpc([-8,-4],[2,4]) + assert iv.mpc([2,4],[4,8]) / 2j == iv.mpc([2,4],[-2,-1]) + assert iv.exp(2+3j).ae(mp.exp(2+3j)) + assert iv.log(2+3j).ae(mp.log(2+3j)) + assert (iv.mpc(2,3) ** iv.mpc(0.5,2)).ae(mp.mpc(2,3) ** mp.mpc(0.5,2)) + assert 1j in (iv.mpf(-1) ** 0.5) + assert 1j in (iv.mpc(-1) ** 0.5) + assert abs(iv.mpc(0)) == 0 + assert abs(iv.mpc(inf)) == inf + assert abs(iv.mpc(3,4)) == 5 + assert abs(iv.mpc(4)) == 4 + assert abs(iv.mpc(0,4)) == 4 + assert abs(iv.mpc(0,[2,3])) == iv.mpf([2,3]) + assert abs(iv.mpc(0,[-3,2])) == iv.mpf([0,3]) + assert abs(iv.mpc([3,5],[4,12])) == iv.mpf([5,13]) + assert abs(iv.mpc([3,5],[-4,12])) == iv.mpf([3,13]) + assert iv.mpc(2,3) ** 0 == 1 + assert iv.mpc(2,3) ** 1 == (2+3j) + assert iv.mpc(2,3) ** 2 == (2+3j)**2 + assert iv.mpc(2,3) ** 3 == (2+3j)**3 + assert iv.mpc(2,3) ** 4 == (2+3j)**4 + assert iv.mpc(2,3) ** 5 == (2+3j)**5 + assert iv.mpc(2,2) ** (-1) == (2+2j) ** (-1) + assert iv.mpc(2,2) ** (-2) == (2+2j) ** (-2) + assert iv.cos(2).ae(mp.cos(2)) + assert iv.sin(2).ae(mp.sin(2)) + assert iv.cos(2+3j).ae(mp.cos(2+3j)) + assert iv.sin(2+3j).ae(mp.sin(2+3j)) + +def test_interval_complex_arg(): + mp.dps = 15 + iv.dps = 15 + assert iv.arg(3) == 0 + assert iv.arg(0) == 0 + assert iv.arg([0,3]) == 0 + assert iv.arg(-3).ae(pi) + assert iv.arg(2+3j).ae(iv.arg(2+3j)) + z = iv.mpc([-2,-1],[3,4]) + t = iv.arg(z) + assert t.a.ae(mp.arg(-1+4j)) + assert t.b.ae(mp.arg(-2+3j)) + z = iv.mpc([-2,1],[3,4]) + t = iv.arg(z) + assert t.a.ae(mp.arg(1+3j)) + assert t.b.ae(mp.arg(-2+3j)) + z = iv.mpc([1,2],[3,4]) + t = iv.arg(z) + assert t.a.ae(mp.arg(2+3j)) + assert t.b.ae(mp.arg(1+4j)) + z = iv.mpc([1,2],[-2,3]) + t = iv.arg(z) + assert t.a.ae(mp.arg(1-2j)) + assert t.b.ae(mp.arg(1+3j)) + z = iv.mpc([1,2],[-4,-3]) + t = iv.arg(z) + assert t.a.ae(mp.arg(1-4j)) + assert t.b.ae(mp.arg(2-3j)) + z = iv.mpc([-1,2],[-4,-3]) + t = iv.arg(z) + assert t.a.ae(mp.arg(-1-3j)) + assert t.b.ae(mp.arg(2-3j)) + z = iv.mpc([-2,-1],[-4,-3]) + t = iv.arg(z) + assert t.a.ae(mp.arg(-2-3j)) + assert t.b.ae(mp.arg(-1-4j)) + z = iv.mpc([-2,-1],[-3,3]) + t = iv.arg(z) + assert t.a.ae(-mp.pi) + assert t.b.ae(mp.pi) + z = iv.mpc([-2,2],[-3,3]) + t = iv.arg(z) + assert t.a.ae(-mp.pi) + assert t.b.ae(mp.pi) + +def test_interval_ae(): + iv.dps = 15 + x = iv.mpf([1,2]) + assert x.ae(1) is None + assert x.ae(1.5) is None + assert x.ae(2) is None + assert x.ae(2.01) is False + assert x.ae(0.99) is False + x = iv.mpf(3.5) + assert x.ae(3.5) is True + assert x.ae(3.5+1e-15) is True + assert x.ae(3.5-1e-15) is True + assert x.ae(3.501) is False + assert x.ae(3.499) is False + assert x.ae(iv.mpf([3.5,3.501])) is None + assert x.ae(iv.mpf([3.5,4.5+1e-15])) is None + +def test_interval_nstr(): + iv.dps = n = 30 + x = mpi(1, 2) + # FIXME: error_dps should not be necessary + assert iv.nstr(x, n, mode='plusminus', error_dps=6) == '1.5 +- 0.5' + assert iv.nstr(x, n, mode='plusminus', use_spaces=False, error_dps=6) == '1.5+-0.5' + assert iv.nstr(x, n, mode='percent') == '1.5 (33.33%)' + assert iv.nstr(x, n, mode='brackets', use_spaces=False) == '[1.0,2.0]' + assert iv.nstr(x, n, mode='brackets' , brackets=('<', '>')) == '<1.0, 2.0>' + x = mpi('5.2582327113062393041', '5.2582327113062749951') + assert iv.nstr(x, n, mode='diff') == '5.2582327113062[393041, 749951]' + assert iv.nstr(iv.cos(mpi(1)), n, mode='diff', use_spaces=False) == '0.54030230586813971740093660744[2955,3053]' + assert iv.nstr(mpi('1e123', '1e129'), n, mode='diff') == '[1.0e+123, 1.0e+129]' + exp = iv.exp + assert iv.nstr(iv.exp(mpi('5000.1')), n, mode='diff') == '3.2797365856787867069110487[0926, 1191]e+2171' + iv.dps = 15 + +def test_mpi_from_str(): + iv.dps = 15 + assert iv.convert('1.5 +- 0.5') == mpi(mpf('1.0'), mpf('2.0')) + assert mpi(1, 2) in iv.convert('1.5 (33.33333333333333333333333333333%)') + assert iv.convert('[1, 2]') == mpi(1, 2) + assert iv.convert('1[2, 3]') == mpi(12, 13) + assert iv.convert('1.[23,46]e-8') == mpi('1.23e-8', '1.46e-8') + assert iv.convert('12[3.4,5.9]e4') == mpi('123.4e+4', '125.9e4') + +def test_interval_gamma(): + mp.dps = 15 + iv.dps = 15 + # TODO: need many more tests + assert iv.rgamma(0) == 0 + assert iv.fac(0) == 1 + assert iv.fac(1) == 1 + assert iv.fac(2) == 2 + assert iv.fac(3) == 6 + assert iv.gamma(0) == [-inf,inf] + assert iv.gamma(1) == 1 + assert iv.gamma(2) == 1 + assert iv.gamma(3) == 2 + assert -3.5449077018110320546 in iv.gamma(-0.5) + assert iv.loggamma(1) == 0 + assert iv.loggamma(2) == 0 + assert 0.69314718055994530942 in iv.loggamma(3) + # Test tight log-gamma endpoints based on monotonicity + xs = [iv.mpc([2,3],[1,4]), + iv.mpc([2,3],[-4,-1]), + iv.mpc([2,3],[-1,4]), + iv.mpc([2,3],[-4,1]), + iv.mpc([2,3],[-4,4]), + iv.mpc([-3,-2],[2,4]), + iv.mpc([-3,-2],[-4,-2])] + for x in xs: + ys = [mp.loggamma(mp.mpc(x.a,x.c)), + mp.loggamma(mp.mpc(x.b,x.c)), + mp.loggamma(mp.mpc(x.a,x.d)), + mp.loggamma(mp.mpc(x.b,x.d))] + if 0 in x.imag: + ys += [mp.loggamma(x.a), mp.loggamma(x.b)] + min_real = min([y.real for y in ys]) + max_real = max([y.real for y in ys]) + min_imag = min([y.imag for y in ys]) + max_imag = max([y.imag for y in ys]) + z = iv.loggamma(x) + assert z.a.ae(min_real) + assert z.b.ae(max_real) + assert z.c.ae(min_imag) + assert z.d.ae(max_imag) + +def test_interval_conversions(): + mp.dps = 15 + iv.dps = 15 + for a, b in ((-0.0, 0), (0.0, 0.5), (1.0, 1), \ + ('-inf', 20.5), ('-inf', float(sqrt(2)))): + r = mpi(a, b) + assert int(r.b) == int(b) + assert float(r.a) == float(a) + assert float(r.b) == float(b) + assert complex(r.a) == complex(a) + assert complex(r.b) == complex(b) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_levin.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_levin.py new file mode 100644 index 0000000000000000000000000000000000000000..b14855df4de1a45da27080dcd239267842a4ac7a --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_levin.py @@ -0,0 +1,153 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +from mpmath import mp +from mpmath import libmp + +xrange = libmp.backend.xrange + +# Attention: +# These tests run with 15-20 decimal digits precision. For higher precision the +# working precision must be raised. + +def test_levin_0(): + mp.dps = 17 + eps = mp.mpf(mp.eps) + with mp.extraprec(2 * mp.prec): + L = mp.levin(method = "levin", variant = "u") + S, s, n = [], 0, 1 + while 1: + s += mp.one / (n * n) + n += 1 + S.append(s) + v, e = L.update_psum(S) + if e < eps: + break + if n > 1000: raise RuntimeError("iteration limit exceeded") + eps = mp.exp(0.9 * mp.log(eps)) + err = abs(v - mp.pi ** 2 / 6) + assert err < eps + w = mp.nsum(lambda n: 1/(n * n), [1, mp.inf], method = "levin", levin_variant = "u") + err = abs(v - w) + assert err < eps + +def test_levin_1(): + mp.dps = 17 + eps = mp.mpf(mp.eps) + with mp.extraprec(2 * mp.prec): + L = mp.levin(method = "levin", variant = "v") + A, n = [], 1 + while 1: + s = mp.mpf(n) ** (2 + 3j) + n += 1 + A.append(s) + v, e = L.update(A) + if e < eps: + break + if n > 1000: raise RuntimeError("iteration limit exceeded") + eps = mp.exp(0.9 * mp.log(eps)) + err = abs(v - mp.zeta(-2-3j)) + assert err < eps + w = mp.nsum(lambda n: n ** (2 + 3j), [1, mp.inf], method = "levin", levin_variant = "v") + err = abs(v - w) + assert err < eps + +def test_levin_2(): + # [2] A. Sidi - "Pratical Extrapolation Methods" p.373 + mp.dps = 17 + z=mp.mpf(10) + eps = mp.mpf(mp.eps) + with mp.extraprec(2 * mp.prec): + L = mp.levin(method = "sidi", variant = "t") + n = 0 + while 1: + s = (-1)**n * mp.fac(n) * z ** (-n) + v, e = L.step(s) + n += 1 + if e < eps: + break + if n > 1000: raise RuntimeError("iteration limit exceeded") + eps = mp.exp(0.9 * mp.log(eps)) + exact = mp.quad(lambda x: mp.exp(-x)/(1+x/z),[0,mp.inf]) + # there is also a symbolic expression for the integral: + # exact = z * mp.exp(z) * mp.expint(1,z) + err = abs(v - exact) + assert err < eps + w = mp.nsum(lambda n: (-1) ** n * mp.fac(n) * z ** (-n), [0, mp.inf], method = "sidi", levin_variant = "t") + assert err < eps + +def test_levin_3(): + mp.dps = 17 + z=mp.mpf(2) + eps = mp.mpf(mp.eps) + with mp.extraprec(7*mp.prec): # we need copious amount of precision to sum this highly divergent series + L = mp.levin(method = "levin", variant = "t") + n, s = 0, 0 + while 1: + s += (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n)) + n += 1 + v, e = L.step_psum(s) + if e < eps: + break + if n > 1000: raise RuntimeError("iteration limit exceeded") + eps = mp.exp(0.8 * mp.log(eps)) + exact = mp.quad(lambda x: mp.exp( -x * x / 2 - z * x ** 4), [0,mp.inf]) * 2 / mp.sqrt(2 * mp.pi) + # there is also a symbolic expression for the integral: + # exact = mp.exp(mp.one / (32 * z)) * mp.besselk(mp.one / 4, mp.one / (32 * z)) / (4 * mp.sqrt(z * mp.pi)) + err = abs(v - exact) + assert err < eps + w = mp.nsum(lambda n: (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n)), [0, mp.inf], method = "levin", levin_variant = "t", workprec = 8*mp.prec, steps = [2] + [1 for x in xrange(1000)]) + err = abs(v - w) + assert err < eps + +def test_levin_nsum(): + mp.dps = 17 + + with mp.extraprec(mp.prec): + z = mp.mpf(10) ** (-10) + a = mp.nsum(lambda n: n**(-(1+z)), [1, mp.inf], method = "l") - 1 / z + assert abs(a - mp.euler) < 1e-10 + + eps = mp.exp(0.8 * mp.log(mp.eps)) + + a = mp.nsum(lambda n: (-1)**(n-1) / n, [1, mp.inf], method = "sidi") + assert abs(a - mp.log(2)) < eps + + z = 2 + 1j + f = lambda n: mp.rf(2 / mp.mpf(3), n) * mp.rf(4 / mp.mpf(3), n) * z**n / (mp.rf(1 / mp.mpf(3), n) * mp.fac(n)) + v = mp.nsum(f, [0, mp.inf], method = "levin", steps = [10 for x in xrange(1000)]) + exact = mp.hyp2f1(2 / mp.mpf(3), 4 / mp.mpf(3), 1 / mp.mpf(3), z) + assert abs(exact - v) < eps + +def test_cohen_alt_0(): + mp.dps = 17 + AC = mp.cohen_alt() + S, s, n = [], 0, 1 + while 1: + s += -((-1) ** n) * mp.one / (n * n) + n += 1 + S.append(s) + v, e = AC.update_psum(S) + if e < mp.eps: + break + if n > 1000: raise RuntimeError("iteration limit exceeded") + eps = mp.exp(0.9 * mp.log(mp.eps)) + err = abs(v - mp.pi ** 2 / 12) + assert err < eps + +def test_cohen_alt_1(): + mp.dps = 17 + A = [] + AC = mp.cohen_alt() + n = 1 + while 1: + A.append( mp.loggamma(1 + mp.one / (2 * n - 1))) + A.append(-mp.loggamma(1 + mp.one / (2 * n))) + n += 1 + v, e = AC.update(A) + if e < mp.eps: + break + if n > 1000: raise RuntimeError("iteration limit exceeded") + v = mp.exp(v) + err = abs(v - 1.06215090557106) + assert err < 1e-12 diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_linalg.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..14256a79f8953d3e4ef8b296258560d48204f547 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_linalg.py @@ -0,0 +1,332 @@ +# TODO: don't use round + +from __future__ import division + +import pytest +from mpmath import * +xrange = libmp.backend.xrange + +# XXX: these shouldn't be visible(?) +LU_decomp = mp.LU_decomp +L_solve = mp.L_solve +U_solve = mp.U_solve +householder = mp.householder +improve_solution = mp.improve_solution + +A1 = matrix([[3, 1, 6], + [2, 1, 3], + [1, 1, 1]]) +b1 = [2, 7, 4] + +A2 = matrix([[ 2, -1, -1, 2], + [ 6, -2, 3, -1], + [-4, 2, 3, -2], + [ 2, 0, 4, -3]]) +b2 = [3, -3, -2, -1] + +A3 = matrix([[ 1, 0, -1, -1, 0], + [ 0, 1, 1, 0, -1], + [ 4, -5, 2, 0, 0], + [ 0, 0, -2, 9,-12], + [ 0, 5, 0, 0, 12]]) +b3 = [0, 0, 0, 0, 50] + +A4 = matrix([[10.235, -4.56, 0., -0.035, 5.67], + [-2.463, 1.27, 3.97, -8.63, 1.08], + [-6.58, 0.86, -0.257, 9.32, -43.6 ], + [ 9.83, 7.39, -17.25, 0.036, 24.86], + [-9.31, 34.9, 78.56, 1.07, 65.8 ]]) +b4 = [8.95, 20.54, 7.42, 5.60, 58.43] + +A5 = matrix([[ 1, 2, -4], + [-2, -3, 5], + [ 3, 5, -8]]) + +A6 = matrix([[ 1.377360, 2.481400, 5.359190], + [ 2.679280, -1.229560, 25.560210], + [-1.225280+1.e6, 9.910180, -35.049900-1.e6]]) +b6 = [23.500000, -15.760000, 2.340000] + +A7 = matrix([[1, -0.5], + [2, 1], + [-2, 6]]) +b7 = [3, 2, -4] + +A8 = matrix([[1, 2, 3], + [-1, 0, 1], + [-1, -2, -1], + [1, 0, -1]]) +b8 = [1, 2, 3, 4] + +A9 = matrix([[ 4, 2, -2], + [ 2, 5, -4], + [-2, -4, 5.5]]) +b9 = [10, 16, -15.5] + +A10 = matrix([[1.0 + 1.0j, 2.0, 2.0], + [4.0, 5.0, 6.0], + [7.0, 8.0, 9.0]]) +b10 = [1.0, 1.0 + 1.0j, 1.0] + + +def test_LU_decomp(): + A = A3.copy() + b = b3 + A, p = LU_decomp(A) + y = L_solve(A, b, p) + x = U_solve(A, y) + assert p == [2, 1, 2, 3] + assert [round(i, 14) for i in x] == [3.78953107960742, 2.9989094874591098, + -0.081788440567070006, 3.8713195201744801, 2.9171210468920399] + A = A4.copy() + b = b4 + A, p = LU_decomp(A) + y = L_solve(A, b, p) + x = U_solve(A, y) + assert p == [0, 3, 4, 3] + assert [round(i, 14) for i in x] == [2.6383625899619201, 2.6643834462368399, + 0.79208015947958998, -2.5088376454101899, -1.0567657691375001] + A = randmatrix(3) + bak = A.copy() + LU_decomp(A, overwrite=1) + assert A != bak + +def test_inverse(): + for A in [A1, A2, A5]: + inv = inverse(A) + assert mnorm(A*inv - eye(A.rows), 1) < 1.e-14 + +def test_householder(): + mp.dps = 15 + A, b = A8, b8 + H, p, x, r = householder(extend(A, b)) + assert H == matrix( + [[mpf('3.0'), mpf('-2.0'), mpf('-1.0'), 0], + [-1.0,mpf('3.333333333333333'),mpf('-2.9999999999999991'),mpf('2.0')], + [-1.0, mpf('-0.66666666666666674'),mpf('2.8142135623730948'), + mpf('-2.8284271247461898')], + [1.0, mpf('-1.3333333333333333'),mpf('-0.20000000000000018'), + mpf('4.2426406871192857')]]) + assert p == [-2, -2, mpf('-1.4142135623730949')] + assert round(norm(r, 2), 10) == 4.2426406870999998 + + y = [102.102, 58.344, 36.463, 24.310, 17.017, 12.376, 9.282, 7.140, 5.610, + 4.488, 3.6465, 3.003] + + def coeff(n): + # similiar to Hilbert matrix + A = [] + for i in range(1, 13): + A.append([1. / (i + j - 1) for j in range(1, n + 1)]) + return matrix(A) + + residuals = [] + refres = [] + for n in range(2, 7): + A = coeff(n) + H, p, x, r = householder(extend(A, y)) + x = matrix(x) + y = matrix(y) + residuals.append(norm(r, 2)) + refres.append(norm(residual(A, x, y), 2)) + assert [round(res, 10) for res in residuals] == [15.1733888877, + 0.82378073210000002, 0.302645887, 0.0260109244, + 0.00058653999999999998] + assert norm(matrix(residuals) - matrix(refres), inf) < 1.e-13 + + def hilbert_cmplx(n): + # Complexified Hilbert matrix + A = hilbert(2*n,n) + v = randmatrix(2*n, 2, min=-1, max=1) + v = v.apply(lambda x: exp(1J*pi()*x)) + A = diag(v[:,0])*A*diag(v[:n,1]) + return A + + residuals_cmplx = [] + refres_cmplx = [] + for n in range(2, 10): + A = hilbert_cmplx(n) + H, p, x, r = householder(A.copy()) + residuals_cmplx.append(norm(r, 2)) + refres_cmplx.append(norm(residual(A[:,:n-1], x, A[:,n-1]), 2)) + assert norm(matrix(residuals_cmplx) - matrix(refres_cmplx), inf) < 1.e-13 + +def test_factorization(): + A = randmatrix(5) + P, L, U = lu(A) + assert mnorm(P*A - L*U, 1) < 1.e-15 + +def test_solve(): + assert norm(residual(A6, lu_solve(A6, b6), b6), inf) < 1.e-10 + assert norm(residual(A7, lu_solve(A7, b7), b7), inf) < 1.5 + assert norm(residual(A8, lu_solve(A8, b8), b8), inf) <= 3 + 1.e-10 + assert norm(residual(A6, qr_solve(A6, b6)[0], b6), inf) < 1.e-10 + assert norm(residual(A7, qr_solve(A7, b7)[0], b7), inf) < 1.5 + assert norm(residual(A8, qr_solve(A8, b8)[0], b8), 2) <= 4.3 + assert norm(residual(A10, lu_solve(A10, b10), b10), 2) < 1.e-10 + assert norm(residual(A10, qr_solve(A10, b10)[0], b10), 2) < 1.e-10 + +def test_solve_overdet_complex(): + A = matrix([[1, 2j], [3, 4j], [5, 6]]) + b = matrix([1 + j, 2, -j]) + assert norm(residual(A, lu_solve(A, b), b)) < 1.0208 + +def test_singular(): + mp.dps = 15 + A = [[5.6, 1.2], [7./15, .1]] + B = repr(zeros(2)) + b = [1, 2] + for i in ['lu_solve(%s, %s)' % (A, b), 'lu_solve(%s, %s)' % (B, b), + 'qr_solve(%s, %s)' % (A, b), 'qr_solve(%s, %s)' % (B, b)]: + pytest.raises((ZeroDivisionError, ValueError), lambda: eval(i)) + +def test_cholesky(): + assert fp.cholesky(fp.matrix(A9)) == fp.matrix([[2, 0, 0], [1, 2, 0], [-1, -3/2, 3/2]]) + x = fp.cholesky_solve(A9, b9) + assert fp.norm(fp.residual(A9, x, b9), fp.inf) == 0 + +def test_det(): + assert det(A1) == 1 + assert round(det(A2), 14) == 8 + assert round(det(A3)) == 1834 + assert round(det(A4)) == 4443376 + assert det(A5) == 1 + assert round(det(A6)) == 78356463 + assert det(zeros(3)) == 0 + +def test_cond(): + mp.dps = 15 + A = matrix([[1.2969, 0.8648], [0.2161, 0.1441]]) + assert cond(A, lambda x: mnorm(x,1)) == mpf('327065209.73817754') + assert cond(A, lambda x: mnorm(x,inf)) == mpf('327065209.73817754') + assert cond(A, lambda x: mnorm(x,'F')) == mpf('249729266.80008656') + +@extradps(50) +def test_precision(): + A = randmatrix(10, 10) + assert mnorm(inverse(inverse(A)) - A, 1) < 1.e-45 + +def test_interval_matrix(): + mp.dps = 15 + iv.dps = 15 + a = iv.matrix([['0.1','0.3','1.0'],['7.1','5.5','4.8'],['3.2','4.4','5.6']]) + b = iv.matrix(['4','0.6','0.5']) + c = iv.lu_solve(a, b) + assert c[0].delta < 1e-13 + assert c[1].delta < 1e-13 + assert c[2].delta < 1e-13 + assert 5.25823271130625686059275 in c[0] + assert -13.155049396267837541163 in c[1] + assert 7.42069154774972557628979 in c[2] + +def test_LU_cache(): + A = randmatrix(3) + LU = LU_decomp(A) + assert A._LU == LU_decomp(A) + A[0,0] = -1000 + assert A._LU is None + +def test_improve_solution(): + A = randmatrix(5, min=1e-20, max=1e20) + b = randmatrix(5, 1, min=-1000, max=1000) + x1 = lu_solve(A, b) + randmatrix(5, 1, min=-1e-5, max=1.e-5) + x2 = improve_solution(A, x1, b) + assert norm(residual(A, x2, b), 2) < norm(residual(A, x1, b), 2) + +def test_exp_pade(): + for i in range(3): + dps = 15 + extra = 15 + mp.dps = dps + extra + dm = 0 + N = 3 + dg = range(1,N+1) + a = diag(dg) + expa = diag([exp(x) for x in dg]) + # choose a random matrix not close to be singular + # to avoid adding too much extra precision in computing + # m**-1 * M * m + while abs(dm) < 0.01: + m = randmatrix(N) + dm = det(m) + m = m/dm + a1 = m**-1 * a * m + e2 = m**-1 * expa * m + mp.dps = dps + e1 = expm(a1, method='pade') + mp.dps = dps + extra + d = e2 - e1 + #print d + mp.dps = dps + assert norm(d, inf).ae(0) + mp.dps = 15 + +def test_qr(): + mp.dps = 15 # used default value for dps + lowlimit = -9 # lower limit of matrix element value + uplimit = 9 # uppter limit of matrix element value + maxm = 4 # max matrix size + flg = False # toggle to create real vs complex matrix + zero = mpf('0.0') + + for k in xrange(0,10): + exdps = 0 + mode = 'full' + flg = bool(k % 2) + + # generate arbitrary matrix size (2 to maxm) + num1 = nint(maxm*rand()) + num2 = nint(maxm*rand()) + m = int(max(num1, num2)) + n = int(min(num1, num2)) + + # create matrix + A = mp.matrix(m,n) + + # populate matrix values with arbitrary integers + if flg: + flg = False + dtype = 'complex' + for j in xrange(0,n): + for i in xrange(0,m): + val = nint(lowlimit + (uplimit-lowlimit)*rand()) + val2 = nint(lowlimit + (uplimit-lowlimit)*rand()) + A[i,j] = mpc(val, val2) + else: + flg = True + dtype = 'real' + for j in xrange(0,n): + for i in xrange(0,m): + val = nint(lowlimit + (uplimit-lowlimit)*rand()) + A[i,j] = mpf(val) + + # perform A -> QR decomposition + Q, R = qr(A, mode, edps = exdps) + + #print('\n\n A = \n', nstr(A, 4)) + #print('\n Q = \n', nstr(Q, 4)) + #print('\n R = \n', nstr(R, 4)) + #print('\n Q*R = \n', nstr(Q*R, 4)) + + maxnorm = mpf('1.0E-11') + n1 = norm(A - Q * R) + #print '\n Norm of A - Q * R = ', n1 + assert n1 <= maxnorm + + if dtype == 'real': + n1 = norm(eye(m) - Q.T * Q) + #print ' Norm of I - Q.T * Q = ', n1 + assert n1 <= maxnorm + + n1 = norm(eye(m) - Q * Q.T) + #print ' Norm of I - Q * Q.T = ', n1 + assert n1 <= maxnorm + + if dtype == 'complex': + n1 = norm(eye(m) - Q.T * Q.conjugate()) + #print ' Norm of I - Q.T * Q.conjugate() = ', n1 + assert n1 <= maxnorm + + n1 = norm(eye(m) - Q.conjugate() * Q.T) + #print ' Norm of I - Q.conjugate() * Q.T = ', n1 + assert n1 <= maxnorm diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_matrices.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..1547b90664dba66a98a7f026a04a4ed1aa1ed3b4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_matrices.py @@ -0,0 +1,253 @@ +import pytest +import sys +from mpmath import * + +def test_matrix_basic(): + A1 = matrix(3) + for i in range(3): + A1[i,i] = 1 + assert A1 == eye(3) + assert A1 == matrix(A1) + A2 = matrix(3, 2) + assert not A2._matrix__data + A3 = matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + assert list(A3) == list(range(1, 10)) + A3[1,1] = 0 + assert not (1, 1) in A3._matrix__data + A4 = matrix([[1, 2, 3], [4, 5, 6]]) + A5 = matrix([[6, -1], [3, 2], [0, -3]]) + assert A4 * A5 == matrix([[12, -6], [39, -12]]) + assert A1 * A3 == A3 * A1 == A3 + pytest.raises(ValueError, lambda: A2*A2) + l = [[10, 20, 30], [40, 0, 60], [70, 80, 90]] + A6 = matrix(l) + assert A6.tolist() == l + assert A6 == eval(repr(A6)) + A6 = fp.matrix(A6) + assert A6 == eval(repr(A6)) + assert A6*1j == eval(repr(A6*1j)) + assert A3 * 10 == 10 * A3 == A6 + assert A2.rows == 3 + assert A2.cols == 2 + A3.rows = 2 + A3.cols = 2 + assert len(A3._matrix__data) == 3 + assert A4 + A4 == 2*A4 + pytest.raises(ValueError, lambda: A4 + A2) + assert sum(A1 - A1) == 0 + A7 = matrix([[1, 2], [3, 4], [5, 6], [7, 8]]) + x = matrix([10, -10]) + assert A7*x == matrix([-10, -10, -10, -10]) + A8 = ones(5) + assert sum((A8 + 1) - (2 - zeros(5))) == 0 + assert (1 + ones(4)) / 2 - 1 == zeros(4) + assert eye(3)**10 == eye(3) + pytest.raises(ValueError, lambda: A7**2) + A9 = randmatrix(3) + A10 = matrix(A9) + A9[0,0] = -100 + assert A9 != A10 + assert nstr(A9) + +def test_matmul(): + """ + Test the PEP465 "@" matrix multiplication syntax. + To avoid syntax errors when importing this file in Python 3.5 and below, we have to use exec() - sorry for that. + """ + # TODO remove exec() wrapper as soon as we drop support for Python <= 3.5 + if sys.hexversion < 0x30500f0: + # we are on Python < 3.5 + pytest.skip("'@' (__matmul__) is only supported in Python 3.5 or newer") + A4 = matrix([[1, 2, 3], [4, 5, 6]]) + A5 = matrix([[6, -1], [3, 2], [0, -3]]) + exec("assert A4 @ A5 == A4 * A5") + +def test_matrix_slices(): + A = matrix([ [1, 2, 3], + [4, 5 ,6], + [7, 8 ,9]]) + V = matrix([1,2,3,4,5]) + + # Get slice + assert A[:,:] == A + assert A[:,1] == matrix([[2],[5],[8]]) + assert A[2,:] == matrix([[7, 8 ,9]]) + assert A[1:3,1:3] == matrix([[5,6],[8,9]]) + assert V[2:4] == matrix([3,4]) + pytest.raises(IndexError, lambda: A[:,1:6]) + + # Assign slice with matrix + A1 = matrix(3) + A1[:,:] = A + assert A1[:,:] == matrix([[1, 2, 3], + [4, 5 ,6], + [7, 8 ,9]]) + A1[0,:] = matrix([[10, 11, 12]]) + assert A1 == matrix([ [10, 11, 12], + [4, 5 ,6], + [7, 8 ,9]]) + A1[:,2] = matrix([[13], [14], [15]]) + assert A1 == matrix([ [10, 11, 13], + [4, 5 ,14], + [7, 8 ,15]]) + A1[:2,:2] = matrix([[16, 17], [18 , 19]]) + assert A1 == matrix([ [16, 17, 13], + [18, 19 ,14], + [7, 8 ,15]]) + V[1:3] = 10 + assert V == matrix([1,10,10,4,5]) + with pytest.raises(ValueError): + A1[2,:] = A[:,1] + + with pytest.raises(IndexError): + A1[2,1:20] = A[:,:] + + # Assign slice with scalar + A1[:,2] = 10 + assert A1 == matrix([ [16, 17, 10], + [18, 19 ,10], + [7, 8 ,10]]) + A1[:,:] = 40 + for x in A1: + assert x == 40 + + +def test_matrix_power(): + A = matrix([[1, 2], [3, 4]]) + assert A**2 == A*A + assert A**3 == A*A*A + assert A**-1 == inverse(A) + assert A**-2 == inverse(A*A) + +def test_matrix_transform(): + A = matrix([[1, 2], [3, 4], [5, 6]]) + assert A.T == A.transpose() == matrix([[1, 3, 5], [2, 4, 6]]) + swap_row(A, 1, 2) + assert A == matrix([[1, 2], [5, 6], [3, 4]]) + l = [1, 2] + swap_row(l, 0, 1) + assert l == [2, 1] + assert extend(eye(3), [1,2,3]) == matrix([[1,0,0,1],[0,1,0,2],[0,0,1,3]]) + +def test_matrix_conjugate(): + A = matrix([[1 + j, 0], [2, j]]) + assert A.conjugate() == matrix([[mpc(1, -1), 0], [2, mpc(0, -1)]]) + assert A.transpose_conj() == A.H == matrix([[mpc(1, -1), 2], + [0, mpc(0, -1)]]) + +def test_matrix_creation(): + assert diag([1, 2, 3]) == matrix([[1, 0, 0], [0, 2, 0], [0, 0, 3]]) + A1 = ones(2, 3) + assert A1.rows == 2 and A1.cols == 3 + for a in A1: + assert a == 1 + A2 = zeros(3, 2) + assert A2.rows == 3 and A2.cols == 2 + for a in A2: + assert a == 0 + assert randmatrix(10) != randmatrix(10) + one = mpf(1) + assert hilbert(3) == matrix([[one, one/2, one/3], + [one/2, one/3, one/4], + [one/3, one/4, one/5]]) + +def test_norms(): + # matrix norms + A = matrix([[1, -2], [-3, -1], [2, 1]]) + assert mnorm(A,1) == 6 + assert mnorm(A,inf) == 4 + assert mnorm(A,'F') == sqrt(20) + # vector norms + assert norm(-3) == 3 + x = [1, -2, 7, -12] + assert norm(x, 1) == 22 + assert round(norm(x, 2), 10) == 14.0712472795 + assert round(norm(x, 10), 10) == 12.0054633727 + assert norm(x, inf) == 12 + +def test_vector(): + x = matrix([0, 1, 2, 3, 4]) + assert x == matrix([[0], [1], [2], [3], [4]]) + assert x[3] == 3 + assert len(x._matrix__data) == 4 + assert list(x) == list(range(5)) + x[0] = -10 + x[4] = 0 + assert x[0] == -10 + assert len(x) == len(x.T) == 5 + assert x.T*x == matrix([[114]]) + +def test_matrix_copy(): + A = ones(6) + B = A.copy() + C = +A + assert A == B + assert A == C + B[0,0] = 0 + assert A != B + C[0,0] = 42 + assert A != C + +def test_matrix_numpy(): + try: + import numpy + except ImportError: + return + l = [[1, 2], [3, 4], [5, 6]] + a = numpy.array(l) + assert matrix(l) == matrix(a) + +def test_interval_matrix_scalar_mult(): + """Multiplication of iv.matrix and any scalar type""" + a = mpi(-1, 1) + b = a + a * 2j + c = mpf(42) + d = c + c * 2j + e = 1.234 + f = fp.convert(e) + g = e + e * 3j + h = fp.convert(g) + M = iv.ones(1) + for x in [a, b, c, d, e, f, g, h]: + assert x * M == iv.matrix([x]) + assert M * x == iv.matrix([x]) + +@pytest.mark.xfail() +def test_interval_matrix_matrix_mult(): + """Multiplication of iv.matrix and other matrix types""" + A = ones(1) + B = fp.ones(1) + M = iv.ones(1) + for X in [A, B, M]: + assert X * M == iv.matrix(X) + assert X * M == X + assert M * X == iv.matrix(X) + assert M * X == X + +def test_matrix_conversion_to_iv(): + # Test that matrices with foreign datatypes are properly converted + for other_type_eye in [eye(3), fp.eye(3), iv.eye(3)]: + A = iv.matrix(other_type_eye) + B = iv.eye(3) + assert type(A[0,0]) == type(B[0,0]) + assert A.tolist() == B.tolist() + +def test_interval_matrix_mult_bug(): + # regression test for interval matrix multiplication: + # result must be nonzero-width and contain the exact result + x = convert('1.00000000000001') # note: this is implicitly rounded to some near mpf float value + A = matrix([[x]]) + B = iv.matrix(A) + C = iv.matrix([[x]]) + assert B == C + B = B * B + C = C * C + assert B == C + assert B[0, 0].delta > 1e-16 + assert B[0, 0].delta < 3e-16 + assert C[0, 0].delta > 1e-16 + assert C[0, 0].delta < 3e-16 + assert mp.mpf('1.00000000000001998401444325291756783368705994138804689654') in B[0, 0] + assert mp.mpf('1.00000000000001998401444325291756783368705994138804689654') in C[0, 0] + # the following caused an error before the bug was fixed + assert iv.matrix(mp.eye(2)) * (iv.ones(2) + mpi(1, 2)) == iv.matrix([[mpi(2, 3), mpi(2, 3)], [mpi(2, 3), mpi(2, 3)]]) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_mpmath.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_mpmath.py new file mode 100644 index 0000000000000000000000000000000000000000..9f1fe36ae9b1b0feca4677eeb90396bfa7ed8f7a --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_mpmath.py @@ -0,0 +1,7 @@ +from mpmath.libmp import * +from mpmath import * + +def test_newstyle_classes(): + for cls in [mp, fp, iv, mpf, mpc]: + for s in cls.__class__.__mro__: + assert isinstance(s, type) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_ode.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_ode.py new file mode 100644 index 0000000000000000000000000000000000000000..6b6dbffa79cfd4ca6dbf14f8591296ee48b16682 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_ode.py @@ -0,0 +1,73 @@ +#from mpmath.calculus import ODE_step_euler, ODE_step_rk4, odeint, arange +from mpmath import odefun, cos, sin, mpf, sinc, mp + +''' +solvers = [ODE_step_euler, ODE_step_rk4] + +def test_ode1(): + """ + Let's solve: + + x'' + w**2 * x = 0 + + i.e. x1 = x, x2 = x1': + + x1' = x2 + x2' = -x1 + """ + def derivs((x1, x2), t): + return x2, -x1 + + for solver in solvers: + t = arange(0, 3.1415926, 0.005) + sol = odeint(derivs, (0., 1.), t, solver) + x1 = [a[0] for a in sol] + x2 = [a[1] for a in sol] + # the result is x1 = sin(t), x2 = cos(t) + # let's just check the end points for t = pi + assert abs(x1[-1]) < 1e-2 + assert abs(x2[-1] - (-1)) < 1e-2 + +def test_ode2(): + """ + Let's solve: + + x' - x = 0 + + i.e. x = exp(x) + + """ + def derivs((x), t): + return x + + for solver in solvers: + t = arange(0, 1, 1e-3) + sol = odeint(derivs, (1.,), t, solver) + x = [a[0] for a in sol] + # the result is x = exp(t) + # let's just check the end point for t = 1, i.e. x = e + assert abs(x[-1] - 2.718281828) < 1e-2 +''' + +def test_odefun_rational(): + mp.dps = 15 + # A rational function + f = lambda t: 1/(1+mpf(t)**2) + g = odefun(lambda x, y: [-2*x*y[0]**2], 0, [f(0)]) + assert f(2).ae(g(2)[0]) + +def test_odefun_sinc_large(): + mp.dps = 15 + # Sinc function; test for large x + f = sinc + g = odefun(lambda x, y: [(cos(x)-y[0])/x], 1, [f(1)], tol=0.01, degree=5) + assert abs(f(100) - g(100)[0])/f(100) < 0.01 + +def test_odefun_harmonic(): + mp.dps = 15 + # Harmonic oscillator + f = odefun(lambda x, y: [-y[1], y[0]], 0, [1, 0]) + for x in [0, 1, 2.5, 8, 3.7]: # we go back to 3.7 to check caching + c, s = f(x) + assert c.ae(cos(x)) + assert s.ae(sin(x)) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_pickle.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..c3d96e73a53603e0fa3f9525c5c0059725bdffb7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_pickle.py @@ -0,0 +1,27 @@ +import os +import tempfile +import pickle + +from mpmath import * + +def pickler(obj): + fn = tempfile.mktemp() + + f = open(fn, 'wb') + pickle.dump(obj, f) + f.close() + + f = open(fn, 'rb') + obj2 = pickle.load(f) + f.close() + os.remove(fn) + + return obj2 + +def test_pickle(): + + obj = mpf('0.5') + assert obj == pickler(obj) + + obj = mpc('0.5','0.2') + assert obj == pickler(obj) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_power.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_power.py new file mode 100644 index 0000000000000000000000000000000000000000..7a2447a62c36f9e02df79b9a40a8603f8a69b1d8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_power.py @@ -0,0 +1,156 @@ +from mpmath import * +from mpmath.libmp import * + +import random + +def test_fractional_pow(): + mp.dps = 15 + assert mpf(16) ** 2.5 == 1024 + assert mpf(64) ** 0.5 == 8 + assert mpf(64) ** -0.5 == 0.125 + assert mpf(16) ** -2.5 == 0.0009765625 + assert (mpf(10) ** 0.5).ae(3.1622776601683791) + assert (mpf(10) ** 2.5).ae(316.2277660168379) + assert (mpf(10) ** -0.5).ae(0.31622776601683794) + assert (mpf(10) ** -2.5).ae(0.0031622776601683794) + assert (mpf(10) ** 0.3).ae(1.9952623149688795) + assert (mpf(10) ** -0.3).ae(0.50118723362727224) + +def test_pow_integer_direction(): + """ + Test that inexact integer powers are rounded in the right + direction. + """ + random.seed(1234) + for prec in [10, 53, 200]: + for i in range(50): + a = random.randint(1<<(prec-1), 1< ab + + +def test_pow_epsilon_rounding(): + """ + Stress test directed rounding for powers with integer exponents. + Basically, we look at the following cases: + + >>> 1.0001 ** -5 # doctest: +SKIP + 0.99950014996500702 + >>> 0.9999 ** -5 # doctest: +SKIP + 1.000500150035007 + >>> (-1.0001) ** -5 # doctest: +SKIP + -0.99950014996500702 + >>> (-0.9999) ** -5 # doctest: +SKIP + -1.000500150035007 + + >>> 1.0001 ** -6 # doctest: +SKIP + 0.99940020994401269 + >>> 0.9999 ** -6 # doctest: +SKIP + 1.0006002100560125 + >>> (-1.0001) ** -6 # doctest: +SKIP + 0.99940020994401269 + >>> (-0.9999) ** -6 # doctest: +SKIP + 1.0006002100560125 + + etc. + + We run the tests with values a very small epsilon away from 1: + small enough that the result is indistinguishable from 1 when + rounded to nearest at the output precision. We check that the + result is not erroneously rounded to 1 in cases where the + rounding should be done strictly away from 1. + """ + + def powr(x, n, r): + return make_mpf(mpf_pow_int(x._mpf_, n, mp.prec, r)) + + for (inprec, outprec) in [(100, 20), (5000, 3000)]: + + mp.prec = inprec + + pos10001 = mpf(1) + mpf(2)**(-inprec+5) + pos09999 = mpf(1) - mpf(2)**(-inprec+5) + neg10001 = -pos10001 + neg09999 = -pos09999 + + mp.prec = outprec + r = round_up + assert powr(pos10001, 5, r) > 1 + assert powr(pos09999, 5, r) == 1 + assert powr(neg10001, 5, r) < -1 + assert powr(neg09999, 5, r) == -1 + assert powr(pos10001, 6, r) > 1 + assert powr(pos09999, 6, r) == 1 + assert powr(neg10001, 6, r) > 1 + assert powr(neg09999, 6, r) == 1 + + assert powr(pos10001, -5, r) == 1 + assert powr(pos09999, -5, r) > 1 + assert powr(neg10001, -5, r) == -1 + assert powr(neg09999, -5, r) < -1 + assert powr(pos10001, -6, r) == 1 + assert powr(pos09999, -6, r) > 1 + assert powr(neg10001, -6, r) == 1 + assert powr(neg09999, -6, r) > 1 + + r = round_down + assert powr(pos10001, 5, r) == 1 + assert powr(pos09999, 5, r) < 1 + assert powr(neg10001, 5, r) == -1 + assert powr(neg09999, 5, r) > -1 + assert powr(pos10001, 6, r) == 1 + assert powr(pos09999, 6, r) < 1 + assert powr(neg10001, 6, r) == 1 + assert powr(neg09999, 6, r) < 1 + + assert powr(pos10001, -5, r) < 1 + assert powr(pos09999, -5, r) == 1 + assert powr(neg10001, -5, r) > -1 + assert powr(neg09999, -5, r) == -1 + assert powr(pos10001, -6, r) < 1 + assert powr(pos09999, -6, r) == 1 + assert powr(neg10001, -6, r) < 1 + assert powr(neg09999, -6, r) == 1 + + r = round_ceiling + assert powr(pos10001, 5, r) > 1 + assert powr(pos09999, 5, r) == 1 + assert powr(neg10001, 5, r) == -1 + assert powr(neg09999, 5, r) > -1 + assert powr(pos10001, 6, r) > 1 + assert powr(pos09999, 6, r) == 1 + assert powr(neg10001, 6, r) > 1 + assert powr(neg09999, 6, r) == 1 + + assert powr(pos10001, -5, r) == 1 + assert powr(pos09999, -5, r) > 1 + assert powr(neg10001, -5, r) > -1 + assert powr(neg09999, -5, r) == -1 + assert powr(pos10001, -6, r) == 1 + assert powr(pos09999, -6, r) > 1 + assert powr(neg10001, -6, r) == 1 + assert powr(neg09999, -6, r) > 1 + + r = round_floor + assert powr(pos10001, 5, r) == 1 + assert powr(pos09999, 5, r) < 1 + assert powr(neg10001, 5, r) < -1 + assert powr(neg09999, 5, r) == -1 + assert powr(pos10001, 6, r) == 1 + assert powr(pos09999, 6, r) < 1 + assert powr(neg10001, 6, r) == 1 + assert powr(neg09999, 6, r) < 1 + + assert powr(pos10001, -5, r) < 1 + assert powr(pos09999, -5, r) == 1 + assert powr(neg10001, -5, r) == -1 + assert powr(neg09999, -5, r) < -1 + assert powr(pos10001, -6, r) < 1 + assert powr(pos09999, -6, r) == 1 + assert powr(neg10001, -6, r) < 1 + assert powr(neg09999, -6, r) == 1 + + mp.dps = 15 diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_quad.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_quad.py new file mode 100644 index 0000000000000000000000000000000000000000..fc71c5f5ef9c0ecd876c988e7d033b321f065cdc --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_quad.py @@ -0,0 +1,95 @@ +import pytest +from mpmath import * + +def ae(a, b): + return abs(a-b) < 10**(-mp.dps+5) + +def test_basic_integrals(): + for prec in [15, 30, 100]: + mp.dps = prec + assert ae(quadts(lambda x: x**3 - 3*x**2, [-2, 4]), -12) + assert ae(quadgl(lambda x: x**3 - 3*x**2, [-2, 4]), -12) + assert ae(quadts(sin, [0, pi]), 2) + assert ae(quadts(sin, [0, 2*pi]), 0) + assert ae(quadts(exp, [-inf, -1]), 1/e) + assert ae(quadts(lambda x: exp(-x), [0, inf]), 1) + assert ae(quadts(lambda x: exp(-x*x), [-inf, inf]), sqrt(pi)) + assert ae(quadts(lambda x: 1/(1+x*x), [-1, 1]), pi/2) + assert ae(quadts(lambda x: 1/(1+x*x), [-inf, inf]), pi) + assert ae(quadts(lambda x: 2*sqrt(1-x*x), [-1, 1]), pi) + mp.dps = 15 + +def test_multiple_intervals(): + y,err = quad(lambda x: sign(x), [-0.5, 0.9, 1], maxdegree=2, error=True) + assert abs(y-0.5) < 2*err + +def test_quad_symmetry(): + assert quadts(sin, [-1, 1]) == 0 + assert quadgl(sin, [-1, 1]) == 0 + +def test_quad_infinite_mirror(): + # Check mirrored infinite interval + assert ae(quad(lambda x: exp(-x*x), [inf,-inf]), -sqrt(pi)) + assert ae(quad(lambda x: exp(x), [0,-inf]), -1) + +def test_quadgl_linear(): + assert quadgl(lambda x: x, [0, 1], maxdegree=1).ae(0.5) + +def test_complex_integration(): + assert quadts(lambda x: x, [0, 1+j]).ae(j) + +def test_quadosc(): + mp.dps = 15 + assert quadosc(lambda x: sin(x)/x, [0, inf], period=2*pi).ae(pi/2) + +# Double integrals +def test_double_trivial(): + assert ae(quadts(lambda x, y: x, [0, 1], [0, 1]), 0.5) + assert ae(quadts(lambda x, y: x, [-1, 1], [-1, 1]), 0.0) + +def test_double_1(): + assert ae(quadts(lambda x, y: cos(x+y/2), [-pi/2, pi/2], [0, pi]), 4) + +def test_double_2(): + assert ae(quadts(lambda x, y: (x-1)/((1-x*y)*log(x*y)), [0, 1], [0, 1]), euler) + +def test_double_3(): + assert ae(quadts(lambda x, y: 1/sqrt(1+x*x+y*y), [-1, 1], [-1, 1]), 4*log(2+sqrt(3))-2*pi/3) + +def test_double_4(): + assert ae(quadts(lambda x, y: 1/(1-x*x * y*y), [0, 1], [0, 1]), pi**2 / 8) + +def test_double_5(): + assert ae(quadts(lambda x, y: 1/(1-x*y), [0, 1], [0, 1]), pi**2 / 6) + +def test_double_6(): + assert ae(quadts(lambda x, y: exp(-(x+y)), [0, inf], [0, inf]), 1) + +def test_double_7(): + assert ae(quadts(lambda x, y: exp(-x*x-y*y), [-inf, inf], [-inf, inf]), pi) + + +# Test integrals from "Experimentation in Mathematics" by Borwein, +# Bailey & Girgensohn +def test_expmath_integrals(): + for prec in [15, 30, 50]: + mp.dps = prec + assert ae(quadts(lambda x: x/sinh(x), [0, inf]), pi**2 / 4) + assert ae(quadts(lambda x: log(x)**2 / (1+x**2), [0, inf]), pi**3 / 8) + assert ae(quadts(lambda x: (1+x**2)/(1+x**4), [0, inf]), pi/sqrt(2)) + assert ae(quadts(lambda x: log(x)/cosh(x)**2, [0, inf]), log(pi)-2*log(2)-euler) + assert ae(quadts(lambda x: log(1+x**3)/(1-x+x**2), [0, inf]), 2*pi*log(3)/sqrt(3)) + assert ae(quadts(lambda x: log(x)**2 / (x**2+x+1), [0, 1]), 8*pi**3 / (81*sqrt(3))) + assert ae(quadts(lambda x: log(cos(x))**2, [0, pi/2]), pi/2 * (log(2)**2+pi**2/12)) + assert ae(quadts(lambda x: x**2 / sin(x)**2, [0, pi/2]), pi*log(2)) + assert ae(quadts(lambda x: x**2/sqrt(exp(x)-1), [0, inf]), 4*pi*(log(2)**2 + pi**2/12)) + assert ae(quadts(lambda x: x*exp(-x)*sqrt(1-exp(-2*x)), [0, inf]), pi*(1+2*log(2))/8) + mp.dps = 15 + +# Do not reach full accuracy +@pytest.mark.xfail +def test_expmath_fail(): + assert ae(quadts(lambda x: sqrt(tan(x)), [0, pi/2]), pi*sqrt(2)/2) + assert ae(quadts(lambda x: atan(x)/(x*sqrt(1-x**2)), [0, 1]), pi*log(1+sqrt(2))/2) + assert ae(quadts(lambda x: log(1+x**2)/x**2, [0, 1]), pi/2-log(2)) + assert ae(quadts(lambda x: x**2/((1+x**4)*sqrt(1-x**4)), [0, 1]), pi/8) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_rootfinding.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_rootfinding.py new file mode 100644 index 0000000000000000000000000000000000000000..7c3c06463682eb1fd60efeb75b809bbb932a241c --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_rootfinding.py @@ -0,0 +1,91 @@ +import pytest +from mpmath import * +from mpmath.calculus.optimization import Secant, Muller, Bisection, Illinois, \ + Pegasus, Anderson, Ridder, ANewton, Newton, MNewton, MDNewton + +def test_findroot(): + # old tests, assuming secant + mp.dps = 15 + assert findroot(lambda x: 4*x-3, mpf(5)).ae(0.75) + assert findroot(sin, mpf(3)).ae(pi) + assert findroot(sin, (mpf(3), mpf(3.14))).ae(pi) + assert findroot(lambda x: x*x+1, mpc(2+2j)).ae(1j) + # test all solvers with 1 starting point + f = lambda x: cos(x) + for solver in [Newton, Secant, MNewton, Muller, ANewton]: + x = findroot(f, 2., solver=solver) + assert abs(f(x)) < eps + # test all solvers with interval of 2 points + for solver in [Secant, Muller, Bisection, Illinois, Pegasus, Anderson, + Ridder]: + x = findroot(f, (1., 2.), solver=solver) + assert abs(f(x)) < eps + # test types + f = lambda x: (x - 2)**2 + + assert isinstance(findroot(f, 1, tol=1e-10), mpf) + assert isinstance(iv.findroot(f, 1., tol=1e-10), iv.mpf) + assert isinstance(fp.findroot(f, 1, tol=1e-10), float) + assert isinstance(fp.findroot(f, 1+0j, tol=1e-10), complex) + + # issue 401 + with pytest.raises(ValueError): + with workprec(2): + findroot(lambda x: x**2 - 4456178*x + 60372201703370, + mpc(real='5.278e+13', imag='-5.278e+13')) + + # issue 192 + with pytest.raises(ValueError): + findroot(lambda x: -1, 0) + + # issue 387 + with pytest.raises(ValueError): + findroot(lambda p: (1 - p)**30 - 1, 0.9) + +def test_bisection(): + # issue 273 + assert findroot(lambda x: x**2-1,(0,2),solver='bisect') == 1 + +def test_mnewton(): + f = lambda x: polyval([1,3,3,1],x) + x = findroot(f, -0.9, solver='mnewton') + assert abs(f(x)) < eps + +def test_anewton(): + f = lambda x: (x - 2)**100 + x = findroot(f, 1., solver=ANewton) + assert abs(f(x)) < eps + +def test_muller(): + f = lambda x: (2 + x)**3 + 2 + x = findroot(f, 1., solver=Muller) + assert abs(f(x)) < eps + +def test_multiplicity(): + for i in range(1, 5): + assert multiplicity(lambda x: (x - 1)**i, 1) == i + assert multiplicity(lambda x: x**2, 1) == 0 + +def test_multidimensional(): + def f(*x): + return [3*x[0]**2-2*x[1]**2-1, x[0]**2-2*x[0]+x[1]**2+2*x[1]-8] + assert mnorm(jacobian(f, (1,-2)) - matrix([[6,8],[0,-2]]),1) < 1.e-7 + for x, error in MDNewton(mp, f, (1,-2), verbose=0, + norm=lambda x: norm(x, inf)): + pass + assert norm(f(*x), 2) < 1e-14 + # The Chinese mathematician Zhu Shijie was the very first to solve this + # nonlinear system 700 years ago + f1 = lambda x, y: -x + 2*y + f2 = lambda x, y: (x**2 + x*(y**2 - 2) - 4*y) / (x + 4) + f3 = lambda x, y: sqrt(x**2 + y**2) + def f(x, y): + f1x = f1(x, y) + return (f2(x, y) - f1x, f3(x, y) - f1x) + x = findroot(f, (10, 10)) + assert [int(round(i)) for i in x] == [3, 4] + +def test_trivial(): + assert findroot(lambda x: 0, 1) == 1 + assert findroot(lambda x: x, 0) == 0 + #assert findroot(lambda x, y: x + y, (1, -1)) == (1, -1) diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_special.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_special.py new file mode 100644 index 0000000000000000000000000000000000000000..30825abd89ada00f937260cb51ef649546be7021 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_special.py @@ -0,0 +1,113 @@ +from mpmath import * + +def test_special(): + assert inf == inf + assert inf != -inf + assert -inf == -inf + assert inf != nan + assert nan != nan + assert isnan(nan) + assert --inf == inf + assert abs(inf) == inf + assert abs(-inf) == inf + assert abs(nan) != abs(nan) + + assert isnan(inf - inf) + assert isnan(inf + (-inf)) + assert isnan(-inf - (-inf)) + + assert isnan(inf + nan) + assert isnan(-inf + nan) + + assert mpf(2) + inf == inf + assert 2 + inf == inf + assert mpf(2) - inf == -inf + assert 2 - inf == -inf + + assert inf > 3 + assert 3 < inf + assert 3 > -inf + assert -inf < 3 + assert inf > mpf(3) + assert mpf(3) < inf + assert mpf(3) > -inf + assert -inf < mpf(3) + + assert not (nan < 3) + assert not (nan > 3) + + assert isnan(inf * 0) + assert isnan(-inf * 0) + assert inf * 3 == inf + assert inf * -3 == -inf + assert -inf * 3 == -inf + assert -inf * -3 == inf + assert inf * inf == inf + assert -inf * -inf == inf + + assert isnan(nan / 3) + assert inf / -3 == -inf + assert inf / 3 == inf + assert 3 / inf == 0 + assert -3 / inf == 0 + assert 0 / inf == 0 + assert isnan(inf / inf) + assert isnan(inf / -inf) + assert isnan(inf / nan) + + assert mpf('inf') == mpf('+inf') == inf + assert mpf('-inf') == -inf + assert isnan(mpf('nan')) + + assert isinf(inf) + assert isinf(-inf) + assert not isinf(mpf(0)) + assert not isinf(nan) + +def test_special_powers(): + assert inf**3 == inf + assert isnan(inf**0) + assert inf**-3 == 0 + assert (-inf)**2 == inf + assert (-inf)**3 == -inf + assert isnan((-inf)**0) + assert (-inf)**-2 == 0 + assert (-inf)**-3 == 0 + assert isnan(nan**5) + assert isnan(nan**0) + +def test_functions_special(): + assert exp(inf) == inf + assert exp(-inf) == 0 + assert isnan(exp(nan)) + assert log(inf) == inf + assert isnan(log(nan)) + assert isnan(sin(inf)) + assert isnan(sin(nan)) + assert atan(inf).ae(pi/2) + assert atan(-inf).ae(-pi/2) + assert isnan(sqrt(nan)) + assert sqrt(inf) == inf + +def test_convert_special(): + float_inf = 1e300 * 1e300 + float_ninf = -float_inf + float_nan = float_inf/float_ninf + assert mpf(3) * float_inf == inf + assert mpf(3) * float_ninf == -inf + assert isnan(mpf(3) * float_nan) + assert not (mpf(3) < float_nan) + assert not (mpf(3) > float_nan) + assert not (mpf(3) <= float_nan) + assert not (mpf(3) >= float_nan) + assert float(mpf('1e1000')) == float_inf + assert float(mpf('-1e1000')) == float_ninf + assert float(mpf('1e100000000000000000')) == float_inf + assert float(mpf('-1e100000000000000000')) == float_ninf + assert float(mpf('1e-100000000000000000')) == 0.0 + +def test_div_bug(): + assert isnan(nan/1) + assert isnan(nan/2) + assert inf/2 == inf + assert (-inf)/2 == -inf diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_str.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_str.py new file mode 100644 index 0000000000000000000000000000000000000000..569244f252c057ec1029b7efbd8b0ffbfbc47522 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_str.py @@ -0,0 +1,14 @@ +from mpmath import nstr, matrix, inf + +def test_nstr(): + m = matrix([[0.75, 0.190940654, -0.0299195971], + [0.190940654, 0.65625, 0.205663228], + [-0.0299195971, 0.205663228, 0.64453125e-20]]) + assert nstr(m, 4, min_fixed=-inf) == \ + '''[ 0.75 0.1909 -0.02992] +[ 0.1909 0.6563 0.2057] +[-0.02992 0.2057 0.000000000000000000006445]''' + assert nstr(m, 4) == \ + '''[ 0.75 0.1909 -0.02992] +[ 0.1909 0.6563 0.2057] +[-0.02992 0.2057 6.445e-21]''' diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_summation.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_summation.py new file mode 100644 index 0000000000000000000000000000000000000000..04ffd29f994e1e6310678eec292c0e03f2d6c725 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_summation.py @@ -0,0 +1,53 @@ +from mpmath import * + +def test_sumem(): + mp.dps = 15 + assert sumem(lambda k: 1/k**2.5, [50, 100]).ae(0.0012524505324784962) + assert sumem(lambda k: k**4 + 3*k + 1, [10, 100]).ae(2050333103) + +def test_nsum(): + mp.dps = 15 + assert nsum(lambda x: x**2, [1, 3]) == 14 + assert nsum(lambda k: 1/factorial(k), [0, inf]).ae(e) + assert nsum(lambda k: (-1)**(k+1) / k, [1, inf]).ae(log(2)) + assert nsum(lambda k: (-1)**(k+1) / k**2, [1, inf]).ae(pi**2 / 12) + assert nsum(lambda k: (-1)**k / log(k), [2, inf]).ae(0.9242998972229388) + assert nsum(lambda k: 1/k**2, [1, inf]).ae(pi**2 / 6) + assert nsum(lambda k: 2**k/fac(k), [0, inf]).ae(exp(2)) + assert nsum(lambda k: 1/k**2, [4, inf], method='e').ae(0.2838229557371153) + assert abs(fp.nsum(lambda k: 1/k**4, [1, fp.inf]) - 1.082323233711138) < 1e-5 + assert abs(fp.nsum(lambda k: 1/k**4, [1, fp.inf], method='e') - 1.082323233711138) < 1e-4 + +def test_nprod(): + mp.dps = 15 + assert nprod(lambda k: exp(1/k**2), [1,inf], method='r').ae(exp(pi**2/6)) + assert nprod(lambda x: x**2, [1, 3]) == 36 + +def test_fsum(): + mp.dps = 15 + assert fsum([]) == 0 + assert fsum([-4]) == -4 + assert fsum([2,3]) == 5 + assert fsum([1e-100,1]) == 1 + assert fsum([1,1e-100]) == 1 + assert fsum([1e100,1]) == 1e100 + assert fsum([1,1e100]) == 1e100 + assert fsum([1e-100,0]) == 1e-100 + assert fsum([1e-100,1e100,1e-100]) == 1e100 + assert fsum([2,1+1j,1]) == 4+1j + assert fsum([2,inf,3]) == inf + assert fsum([2,-1], absolute=1) == 3 + assert fsum([2,-1], squared=1) == 5 + assert fsum([1,1+j], squared=1) == 1+2j + assert fsum([1,3+4j], absolute=1) == 6 + assert fsum([1,2+3j], absolute=1, squared=1) == 14 + assert isnan(fsum([inf,-inf])) + assert fsum([inf,-inf], absolute=1) == inf + assert fsum([inf,-inf], squared=1) == inf + assert fsum([inf,-inf], absolute=1, squared=1) == inf + assert iv.fsum([1,mpi(2,3)]) == mpi(3,4) + +def test_fprod(): + mp.dps = 15 + assert fprod([]) == 1 + assert fprod([2,3]) == 6 diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_trig.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_trig.py new file mode 100644 index 0000000000000000000000000000000000000000..c70a2a0ff4c44c784404ecdb15357d5b91a992d6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_trig.py @@ -0,0 +1,136 @@ +from mpmath import * +from mpmath.libmp import * + +def test_trig_misc_hard(): + mp.prec = 53 + # Worst-case input for an IEEE double, from a paper by Kahan + x = ldexp(6381956970095103,797) + assert cos(x) == mpf('-4.6871659242546277e-19') + assert sin(x) == 1 + + mp.prec = 150 + a = mpf(10**50) + mp.prec = 53 + assert sin(a).ae(-0.7896724934293100827) + assert cos(a).ae(-0.6135286082336635622) + + # Check relative accuracy close to x = zero + assert sin(1e-100) == 1e-100 # when rounding to nearest + assert sin(1e-6).ae(9.999999999998333e-007, rel_eps=2e-15, abs_eps=0) + assert sin(1e-6j).ae(1.0000000000001666e-006j, rel_eps=2e-15, abs_eps=0) + assert sin(-1e-6j).ae(-1.0000000000001666e-006j, rel_eps=2e-15, abs_eps=0) + assert cos(1e-100) == 1 + assert cos(1e-6).ae(0.9999999999995) + assert cos(-1e-6j).ae(1.0000000000005) + assert tan(1e-100) == 1e-100 + assert tan(1e-6).ae(1.0000000000003335e-006, rel_eps=2e-15, abs_eps=0) + assert tan(1e-6j).ae(9.9999999999966644e-007j, rel_eps=2e-15, abs_eps=0) + assert tan(-1e-6j).ae(-9.9999999999966644e-007j, rel_eps=2e-15, abs_eps=0) + +def test_trig_near_zero(): + mp.dps = 15 + + for r in [round_nearest, round_down, round_up, round_floor, round_ceiling]: + assert sin(0, rounding=r) == 0 + assert cos(0, rounding=r) == 1 + + a = mpf('1e-100') + b = mpf('-1e-100') + + assert sin(a, rounding=round_nearest) == a + assert sin(a, rounding=round_down) < a + assert sin(a, rounding=round_floor) < a + assert sin(a, rounding=round_up) >= a + assert sin(a, rounding=round_ceiling) >= a + assert sin(b, rounding=round_nearest) == b + assert sin(b, rounding=round_down) > b + assert sin(b, rounding=round_floor) <= b + assert sin(b, rounding=round_up) <= b + assert sin(b, rounding=round_ceiling) > b + + assert cos(a, rounding=round_nearest) == 1 + assert cos(a, rounding=round_down) < 1 + assert cos(a, rounding=round_floor) < 1 + assert cos(a, rounding=round_up) == 1 + assert cos(a, rounding=round_ceiling) == 1 + assert cos(b, rounding=round_nearest) == 1 + assert cos(b, rounding=round_down) < 1 + assert cos(b, rounding=round_floor) < 1 + assert cos(b, rounding=round_up) == 1 + assert cos(b, rounding=round_ceiling) == 1 + + +def test_trig_near_n_pi(): + + mp.dps = 15 + a = [n*pi for n in [1, 2, 6, 11, 100, 1001, 10000, 100001]] + mp.dps = 135 + a.append(10**100 * pi) + mp.dps = 15 + + assert sin(a[0]) == mpf('1.2246467991473531772e-16') + assert sin(a[1]) == mpf('-2.4492935982947063545e-16') + assert sin(a[2]) == mpf('-7.3478807948841190634e-16') + assert sin(a[3]) == mpf('4.8998251578625894243e-15') + assert sin(a[4]) == mpf('1.9643867237284719452e-15') + assert sin(a[5]) == mpf('-8.8632615209684813458e-15') + assert sin(a[6]) == mpf('-4.8568235395684898392e-13') + assert sin(a[7]) == mpf('3.9087342299491231029e-11') + assert sin(a[8]) == mpf('-1.369235466754566993528e-36') + + r = round_nearest + assert cos(a[0], rounding=r) == -1 + assert cos(a[1], rounding=r) == 1 + assert cos(a[2], rounding=r) == 1 + assert cos(a[3], rounding=r) == -1 + assert cos(a[4], rounding=r) == 1 + assert cos(a[5], rounding=r) == -1 + assert cos(a[6], rounding=r) == 1 + assert cos(a[7], rounding=r) == -1 + assert cos(a[8], rounding=r) == 1 + + r = round_up + assert cos(a[0], rounding=r) == -1 + assert cos(a[1], rounding=r) == 1 + assert cos(a[2], rounding=r) == 1 + assert cos(a[3], rounding=r) == -1 + assert cos(a[4], rounding=r) == 1 + assert cos(a[5], rounding=r) == -1 + assert cos(a[6], rounding=r) == 1 + assert cos(a[7], rounding=r) == -1 + assert cos(a[8], rounding=r) == 1 + + r = round_down + assert cos(a[0], rounding=r) > -1 + assert cos(a[1], rounding=r) < 1 + assert cos(a[2], rounding=r) < 1 + assert cos(a[3], rounding=r) > -1 + assert cos(a[4], rounding=r) < 1 + assert cos(a[5], rounding=r) > -1 + assert cos(a[6], rounding=r) < 1 + assert cos(a[7], rounding=r) > -1 + assert cos(a[8], rounding=r) < 1 + + r = round_floor + assert cos(a[0], rounding=r) == -1 + assert cos(a[1], rounding=r) < 1 + assert cos(a[2], rounding=r) < 1 + assert cos(a[3], rounding=r) == -1 + assert cos(a[4], rounding=r) < 1 + assert cos(a[5], rounding=r) == -1 + assert cos(a[6], rounding=r) < 1 + assert cos(a[7], rounding=r) == -1 + assert cos(a[8], rounding=r) < 1 + + r = round_ceiling + assert cos(a[0], rounding=r) > -1 + assert cos(a[1], rounding=r) == 1 + assert cos(a[2], rounding=r) == 1 + assert cos(a[3], rounding=r) > -1 + assert cos(a[4], rounding=r) == 1 + assert cos(a[5], rounding=r) > -1 + assert cos(a[6], rounding=r) == 1 + assert cos(a[7], rounding=r) > -1 + assert cos(a[8], rounding=r) == 1 + + mp.dps = 15 diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/test_visualization.py b/venv/lib/python3.10/site-packages/mpmath/tests/test_visualization.py new file mode 100644 index 0000000000000000000000000000000000000000..81ffd05194322f00e4c75dc02bc862b383468bff --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/test_visualization.py @@ -0,0 +1,32 @@ +""" +Limited tests of the visualization module. Right now it just makes +sure that passing custom Axes works. + +""" + +from mpmath import mp, fp + +def test_axes(): + try: + import matplotlib + version = matplotlib.__version__.split("-")[0] + version = version.split(".")[:2] + if [int(_) for _ in version] < [0,99]: + raise ImportError + import pylab + except ImportError: + print("\nSkipping test (pylab not available or too old version)\n") + return + fig = pylab.figure() + axes = fig.add_subplot(111) + for ctx in [mp, fp]: + ctx.plot(lambda x: x**2, [0, 3], axes=axes) + assert axes.get_xlabel() == 'x' + assert axes.get_ylabel() == 'f(x)' + + fig = pylab.figure() + axes = fig.add_subplot(111) + for ctx in [mp, fp]: + ctx.cplot(lambda z: z, [-2, 2], [-10, 10], axes=axes) + assert axes.get_xlabel() == 'Re(z)' + assert axes.get_ylabel() == 'Im(z)' diff --git a/venv/lib/python3.10/site-packages/mpmath/tests/torture.py b/venv/lib/python3.10/site-packages/mpmath/tests/torture.py new file mode 100644 index 0000000000000000000000000000000000000000..845d5c6d7d017e51e1ed9a8fe3106cfa32fd967f --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/tests/torture.py @@ -0,0 +1,224 @@ +""" +Torture tests for asymptotics and high precision evaluation of +special functions. + +(Other torture tests may also be placed here.) + +Running this file (gmpy recommended!) takes several CPU minutes. +With Python 2.6+, multiprocessing is used automatically to run tests +in parallel if many cores are available. (A single test may take between +a second and several minutes; possibly more.) + +The idea: + +* We evaluate functions at positive, negative, imaginary, 45- and 135-degree + complex values with magnitudes between 10^-20 to 10^20, at precisions between + 5 and 150 digits (we can go even higher for fast functions). + +* Comparing the result from two different precision levels provides + a strong consistency check (particularly for functions that use + different algorithms at different precision levels). + +* That the computation finishes at all (without failure), within reasonable + time, provides a check that evaluation works at all: that the code runs, + that it doesn't get stuck in an infinite loop, and that it doesn't use + some extremely slowly algorithm where it could use a faster one. + +TODO: + +* Speed up those functions that take long to finish! +* Generalize to test more cases; more options. +* Implement a timeout mechanism. +* Some functions are notably absent, including the following: + * inverse trigonometric functions (some become inaccurate for complex arguments) + * ci, si (not implemented properly for large complex arguments) + * zeta functions (need to modify test not to try too large imaginary values) + * and others... + +""" + + +import sys, os +from timeit import default_timer as clock + +if "-nogmpy" in sys.argv: + sys.argv.remove('-nogmpy') + os.environ['MPMATH_NOGMPY'] = 'Y' + +filt = '' +if not sys.argv[-1].endswith(".py"): + filt = sys.argv[-1] + +from mpmath import * +from mpmath.libmp.backend import exec_ + +def test_asymp(f, maxdps=150, verbose=False, huge_range=False): + dps = [5,15,25,50,90,150,500,1500,5000,10000] + dps = [p for p in dps if p <= maxdps] + def check(x,y,p,inpt): + if abs(x-y)/abs(y) < workprec(20)(power)(10, -p+1): + return + print() + print("Error!") + print("Input:", inpt) + print("dps =", p) + print("Result 1:", x) + print("Result 2:", y) + print("Absolute error:", abs(x-y)) + print("Relative error:", abs(x-y)/abs(y)) + raise AssertionError + exponents = range(-20,20) + if huge_range: + exponents += [-1000, -100, -50, 50, 100, 1000] + for n in exponents: + if verbose: + sys.stdout.write(". ") + mp.dps = 25 + xpos = mpf(10)**n / 1.1287 + xneg = -xpos + ximag = xpos*j + xcomplex1 = xpos*(1+j) + xcomplex2 = xpos*(-1+j) + for i in range(len(dps)): + if verbose: + print("Testing dps = %s" % dps[i]) + mp.dps = dps[i] + new = f(xpos), f(xneg), f(ximag), f(xcomplex1), f(xcomplex2) + if i != 0: + p = dps[i-1] + check(prev[0], new[0], p, xpos) + check(prev[1], new[1], p, xneg) + check(prev[2], new[2], p, ximag) + check(prev[3], new[3], p, xcomplex1) + check(prev[4], new[4], p, xcomplex2) + prev = new + if verbose: + print() + +a1, a2, a3, a4, a5 = 1.5, -2.25, 3.125, 4, 2 + +def test_bernoulli_huge(): + p, q = bernfrac(9000) + assert p % 10**10 == 9636701091 + assert q == 4091851784687571609141381951327092757255270 + mp.dps = 15 + assert str(bernoulli(10**100)) == '-2.58183325604736e+987675256497386331227838638980680030172857347883537824464410652557820800494271520411283004120790908623' + mp.dps = 50 + assert str(bernoulli(10**100)) == '-2.5818332560473632073252488656039475548106223822913e+987675256497386331227838638980680030172857347883537824464410652557820800494271520411283004120790908623' + mp.dps = 15 + +cases = """\ +test_bernoulli_huge() +test_asymp(lambda z: +pi, maxdps=10000) +test_asymp(lambda z: +e, maxdps=10000) +test_asymp(lambda z: +ln2, maxdps=10000) +test_asymp(lambda z: +ln10, maxdps=10000) +test_asymp(lambda z: +phi, maxdps=10000) +test_asymp(lambda z: +catalan, maxdps=5000) +test_asymp(lambda z: +euler, maxdps=5000) +test_asymp(lambda z: +glaisher, maxdps=1000) +test_asymp(lambda z: +khinchin, maxdps=1000) +test_asymp(lambda z: +twinprime, maxdps=150) +test_asymp(lambda z: stieltjes(2), maxdps=150) +test_asymp(lambda z: +mertens, maxdps=150) +test_asymp(lambda z: +apery, maxdps=5000) +test_asymp(sqrt, maxdps=10000, huge_range=True) +test_asymp(cbrt, maxdps=5000, huge_range=True) +test_asymp(lambda z: root(z,4), maxdps=5000, huge_range=True) +test_asymp(lambda z: root(z,-5), maxdps=5000, huge_range=True) +test_asymp(exp, maxdps=5000, huge_range=True) +test_asymp(expm1, maxdps=1500) +test_asymp(ln, maxdps=5000, huge_range=True) +test_asymp(cosh, maxdps=5000) +test_asymp(sinh, maxdps=5000) +test_asymp(tanh, maxdps=1500) +test_asymp(sin, maxdps=5000, huge_range=True) +test_asymp(cos, maxdps=5000, huge_range=True) +test_asymp(tan, maxdps=1500) +test_asymp(agm, maxdps=1500, huge_range=True) +test_asymp(ellipk, maxdps=1500) +test_asymp(ellipe, maxdps=1500) +test_asymp(lambertw, huge_range=True) +test_asymp(lambda z: lambertw(z,-1)) +test_asymp(lambda z: lambertw(z,1)) +test_asymp(lambda z: lambertw(z,4)) +test_asymp(gamma) +test_asymp(loggamma) # huge_range=True ? +test_asymp(ei) +test_asymp(e1) +test_asymp(li, huge_range=True) +test_asymp(ci) +test_asymp(si) +test_asymp(chi) +test_asymp(shi) +test_asymp(erf) +test_asymp(erfc) +test_asymp(erfi) +test_asymp(lambda z: besselj(2, z)) +test_asymp(lambda z: bessely(2, z)) +test_asymp(lambda z: besseli(2, z)) +test_asymp(lambda z: besselk(2, z)) +test_asymp(lambda z: besselj(-2.25, z)) +test_asymp(lambda z: bessely(-2.25, z)) +test_asymp(lambda z: besseli(-2.25, z)) +test_asymp(lambda z: besselk(-2.25, z)) +test_asymp(airyai) +test_asymp(airybi) +test_asymp(lambda z: hyp0f1(a1, z)) +test_asymp(lambda z: hyp1f1(a1, a2, z)) +test_asymp(lambda z: hyp1f2(a1, a2, a3, z)) +test_asymp(lambda z: hyp2f0(a1, a2, z)) +test_asymp(lambda z: hyperu(a1, a2, z)) +test_asymp(lambda z: hyp2f1(a1, a2, a3, z)) +test_asymp(lambda z: hyp2f2(a1, a2, a3, a4, z)) +test_asymp(lambda z: hyp2f3(a1, a2, a3, a4, a5, z)) +test_asymp(lambda z: coulombf(a1, a2, z)) +test_asymp(lambda z: coulombg(a1, a2, z)) +test_asymp(lambda z: polylog(2,z)) +test_asymp(lambda z: polylog(3,z)) +test_asymp(lambda z: polylog(-2,z)) +test_asymp(lambda z: expint(4, z)) +test_asymp(lambda z: expint(-4, z)) +test_asymp(lambda z: expint(2.25, z)) +test_asymp(lambda z: gammainc(2.5, z, 5)) +test_asymp(lambda z: gammainc(2.5, 5, z)) +test_asymp(lambda z: hermite(3, z)) +test_asymp(lambda z: hermite(2.5, z)) +test_asymp(lambda z: legendre(3, z)) +test_asymp(lambda z: legendre(4, z)) +test_asymp(lambda z: legendre(2.5, z)) +test_asymp(lambda z: legenp(a1, a2, z)) +test_asymp(lambda z: legenq(a1, a2, z), maxdps=90) # abnormally slow +test_asymp(lambda z: jtheta(1, z, 0.5)) +test_asymp(lambda z: jtheta(2, z, 0.5)) +test_asymp(lambda z: jtheta(3, z, 0.5)) +test_asymp(lambda z: jtheta(4, z, 0.5)) +test_asymp(lambda z: jtheta(1, z, 0.5, 1)) +test_asymp(lambda z: jtheta(2, z, 0.5, 1)) +test_asymp(lambda z: jtheta(3, z, 0.5, 1)) +test_asymp(lambda z: jtheta(4, z, 0.5, 1)) +test_asymp(barnesg, maxdps=90) +""" + +def testit(line): + if filt in line: + print(line) + t1 = clock() + exec_(line, globals(), locals()) + t2 = clock() + elapsed = t2-t1 + print("Time:", elapsed, "for", line, "(OK)") + +if __name__ == '__main__': + try: + from multiprocessing import Pool + mapf = Pool(None).map + print("Running tests with multiprocessing") + except ImportError: + print("Not using multiprocessing") + mapf = map + t1 = clock() + tasks = cases.splitlines() + mapf(testit, tasks) + t2 = clock() + print("Cumulative wall time:", t2-t1) diff --git a/venv/lib/python3.10/site-packages/mpmath/usertools.py b/venv/lib/python3.10/site-packages/mpmath/usertools.py new file mode 100644 index 0000000000000000000000000000000000000000..8028a4c46f1c635a6857f1f2de48ac6675d3c6d3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/usertools.py @@ -0,0 +1,93 @@ + +def monitor(f, input='print', output='print'): + """ + Returns a wrapped copy of *f* that monitors evaluation by calling + *input* with every input (*args*, *kwargs*) passed to *f* and + *output* with every value returned from *f*. The default action + (specify using the special string value ``'print'``) is to print + inputs and outputs to stdout, along with the total evaluation + count:: + + >>> from mpmath import * + >>> mp.dps = 5; mp.pretty = False + >>> diff(monitor(exp), 1) # diff will eval f(x-h) and f(x+h) + in 0 (mpf('0.99999999906867742538452148'),) {} + out 0 mpf('2.7182818259274480055282064') + in 1 (mpf('1.0000000009313225746154785'),) {} + out 1 mpf('2.7182818309906424675501024') + mpf('2.7182808') + + To disable either the input or the output handler, you may + pass *None* as argument. + + Custom input and output handlers may be used e.g. to store + results for later analysis:: + + >>> mp.dps = 15 + >>> input = [] + >>> output = [] + >>> findroot(monitor(sin, input.append, output.append), 3.0) + mpf('3.1415926535897932') + >>> len(input) # Count number of evaluations + 9 + >>> print(input[3]); print(output[3]) + ((mpf('3.1415076583334066'),), {}) + 8.49952562843408e-5 + >>> print(input[4]); print(output[4]) + ((mpf('3.1415928201669122'),), {}) + -1.66577118985331e-7 + + """ + if not input: + input = lambda v: None + elif input == 'print': + incount = [0] + def input(value): + args, kwargs = value + print("in %s %r %r" % (incount[0], args, kwargs)) + incount[0] += 1 + if not output: + output = lambda v: None + elif output == 'print': + outcount = [0] + def output(value): + print("out %s %r" % (outcount[0], value)) + outcount[0] += 1 + def f_monitored(*args, **kwargs): + input((args, kwargs)) + v = f(*args, **kwargs) + output(v) + return v + return f_monitored + +def timing(f, *args, **kwargs): + """ + Returns time elapsed for evaluating ``f()``. Optionally arguments + may be passed to time the execution of ``f(*args, **kwargs)``. + + If the first call is very quick, ``f`` is called + repeatedly and the best time is returned. + """ + once = kwargs.get('once') + if 'once' in kwargs: + del kwargs['once'] + if args or kwargs: + if len(args) == 1 and not kwargs: + arg = args[0] + g = lambda: f(arg) + else: + g = lambda: f(*args, **kwargs) + else: + g = f + from timeit import default_timer as clock + t1=clock(); v=g(); t2=clock(); t=t2-t1 + if t > 0.05 or once: + return t + for i in range(3): + t1=clock(); + # Evaluate multiple times because the timer function + # has a significant overhead + g();g();g();g();g();g();g();g();g();g() + t2=clock() + t=min(t,(t2-t1)/10) + return t diff --git a/venv/lib/python3.10/site-packages/mpmath/visualization.py b/venv/lib/python3.10/site-packages/mpmath/visualization.py new file mode 100644 index 0000000000000000000000000000000000000000..17e12e97bead4f2977b59361a4de7672f0e9b75f --- /dev/null +++ b/venv/lib/python3.10/site-packages/mpmath/visualization.py @@ -0,0 +1,313 @@ +""" +Plotting (requires matplotlib) +""" + +from colorsys import hsv_to_rgb, hls_to_rgb +from .libmp import NoConvergence +from .libmp.backend import xrange + +class VisualizationMethods(object): + plot_ignore = (ValueError, ArithmeticError, ZeroDivisionError, NoConvergence) + +def plot(ctx, f, xlim=[-5,5], ylim=None, points=200, file=None, dpi=None, + singularities=[], axes=None): + r""" + Shows a simple 2D plot of a function `f(x)` or list of functions + `[f_0(x), f_1(x), \ldots, f_n(x)]` over a given interval + specified by *xlim*. Some examples:: + + plot(lambda x: exp(x)*li(x), [1, 4]) + plot([cos, sin], [-4, 4]) + plot([fresnels, fresnelc], [-4, 4]) + plot([sqrt, cbrt], [-4, 4]) + plot(lambda t: zeta(0.5+t*j), [-20, 20]) + plot([floor, ceil, abs, sign], [-5, 5]) + + Points where the function raises a numerical exception or + returns an infinite value are removed from the graph. + Singularities can also be excluded explicitly + as follows (useful for removing erroneous vertical lines):: + + plot(cot, ylim=[-5, 5]) # bad + plot(cot, ylim=[-5, 5], singularities=[-pi, 0, pi]) # good + + For parts where the function assumes complex values, the + real part is plotted with dashes and the imaginary part + is plotted with dots. + + .. note :: This function requires matplotlib (pylab). + """ + if file: + axes = None + fig = None + if not axes: + import pylab + fig = pylab.figure() + axes = fig.add_subplot(111) + if not isinstance(f, (tuple, list)): + f = [f] + a, b = xlim + colors = ['b', 'r', 'g', 'm', 'k'] + for n, func in enumerate(f): + x = ctx.arange(a, b, (b-a)/float(points)) + segments = [] + segment = [] + in_complex = False + for i in xrange(len(x)): + try: + if i != 0: + for sing in singularities: + if x[i-1] <= sing and x[i] >= sing: + raise ValueError + v = func(x[i]) + if ctx.isnan(v) or abs(v) > 1e300: + raise ValueError + if hasattr(v, "imag") and v.imag: + re = float(v.real) + im = float(v.imag) + if not in_complex: + in_complex = True + segments.append(segment) + segment = [] + segment.append((float(x[i]), re, im)) + else: + if in_complex: + in_complex = False + segments.append(segment) + segment = [] + if hasattr(v, "real"): + v = v.real + segment.append((float(x[i]), v)) + except ctx.plot_ignore: + if segment: + segments.append(segment) + segment = [] + if segment: + segments.append(segment) + for segment in segments: + x = [s[0] for s in segment] + y = [s[1] for s in segment] + if not x: + continue + c = colors[n % len(colors)] + if len(segment[0]) == 3: + z = [s[2] for s in segment] + axes.plot(x, y, '--'+c, linewidth=3) + axes.plot(x, z, ':'+c, linewidth=3) + else: + axes.plot(x, y, c, linewidth=3) + axes.set_xlim([float(_) for _ in xlim]) + if ylim: + axes.set_ylim([float(_) for _ in ylim]) + axes.set_xlabel('x') + axes.set_ylabel('f(x)') + axes.grid(True) + if fig: + if file: + pylab.savefig(file, dpi=dpi) + else: + pylab.show() + +def default_color_function(ctx, z): + if ctx.isinf(z): + return (1.0, 1.0, 1.0) + if ctx.isnan(z): + return (0.5, 0.5, 0.5) + pi = 3.1415926535898 + a = (float(ctx.arg(z)) + ctx.pi) / (2*ctx.pi) + a = (a + 0.5) % 1.0 + b = 1.0 - float(1/(1.0+abs(z)**0.3)) + return hls_to_rgb(a, b, 0.8) + +blue_orange_colors = [ + (-1.0, (0.0, 0.0, 0.0)), + (-0.95, (0.1, 0.2, 0.5)), # dark blue + (-0.5, (0.0, 0.5, 1.0)), # blueish + (-0.05, (0.4, 0.8, 0.8)), # cyanish + ( 0.0, (1.0, 1.0, 1.0)), + ( 0.05, (1.0, 0.9, 0.3)), # yellowish + ( 0.5, (0.9, 0.5, 0.0)), # orangeish + ( 0.95, (0.7, 0.1, 0.0)), # redish + ( 1.0, (0.0, 0.0, 0.0)), + ( 2.0, (0.0, 0.0, 0.0)), +] + +def phase_color_function(ctx, z): + if ctx.isinf(z): + return (1.0, 1.0, 1.0) + if ctx.isnan(z): + return (0.5, 0.5, 0.5) + pi = 3.1415926535898 + w = float(ctx.arg(z)) / pi + w = max(min(w, 1.0), -1.0) + for i in range(1,len(blue_orange_colors)): + if blue_orange_colors[i][0] > w: + a, (ra, ga, ba) = blue_orange_colors[i-1] + b, (rb, gb, bb) = blue_orange_colors[i] + s = (w-a) / (b-a) + return ra+(rb-ra)*s, ga+(gb-ga)*s, ba+(bb-ba)*s + +def cplot(ctx, f, re=[-5,5], im=[-5,5], points=2000, color=None, + verbose=False, file=None, dpi=None, axes=None): + """ + Plots the given complex-valued function *f* over a rectangular part + of the complex plane specified by the pairs of intervals *re* and *im*. + For example:: + + cplot(lambda z: z, [-2, 2], [-10, 10]) + cplot(exp) + cplot(zeta, [0, 1], [0, 50]) + + By default, the complex argument (phase) is shown as color (hue) and + the magnitude is show as brightness. You can also supply a + custom color function (*color*). This function should take a + complex number as input and return an RGB 3-tuple containing + floats in the range 0.0-1.0. + + Alternatively, you can select a builtin color function by passing + a string as *color*: + + * "default" - default color scheme + * "phase" - a color scheme that only renders the phase of the function, + with white for positive reals, black for negative reals, gold in the + upper half plane, and blue in the lower half plane. + + To obtain a sharp image, the number of points may need to be + increased to 100,000 or thereabout. Since evaluating the + function that many times is likely to be slow, the 'verbose' + option is useful to display progress. + + .. note :: This function requires matplotlib (pylab). + """ + if color is None or color == "default": + color = ctx.default_color_function + if color == "phase": + color = ctx.phase_color_function + import pylab + if file: + axes = None + fig = None + if not axes: + fig = pylab.figure() + axes = fig.add_subplot(111) + rea, reb = re + ima, imb = im + dre = reb - rea + dim = imb - ima + M = int(ctx.sqrt(points*dre/dim)+1) + N = int(ctx.sqrt(points*dim/dre)+1) + x = pylab.linspace(rea, reb, M) + y = pylab.linspace(ima, imb, N) + # Note: we have to be careful to get the right rotation. + # Test with these plots: + # cplot(lambda z: z if z.real < 0 else 0) + # cplot(lambda z: z if z.imag < 0 else 0) + w = pylab.zeros((N, M, 3)) + for n in xrange(N): + for m in xrange(M): + z = ctx.mpc(x[m], y[n]) + try: + v = color(f(z)) + except ctx.plot_ignore: + v = (0.5, 0.5, 0.5) + w[n,m] = v + if verbose: + print(str(n) + ' of ' + str(N)) + rea, reb, ima, imb = [float(_) for _ in [rea, reb, ima, imb]] + axes.imshow(w, extent=(rea, reb, ima, imb), origin='lower') + axes.set_xlabel('Re(z)') + axes.set_ylabel('Im(z)') + if fig: + if file: + pylab.savefig(file, dpi=dpi) + else: + pylab.show() + +def splot(ctx, f, u=[-5,5], v=[-5,5], points=100, keep_aspect=True, \ + wireframe=False, file=None, dpi=None, axes=None): + """ + Plots the surface defined by `f`. + + If `f` returns a single component, then this plots the surface + defined by `z = f(x,y)` over the rectangular domain with + `x = u` and `y = v`. + + If `f` returns three components, then this plots the parametric + surface `x, y, z = f(u,v)` over the pairs of intervals `u` and `v`. + + For example, to plot a simple function:: + + >>> from mpmath import * + >>> f = lambda x, y: sin(x+y)*cos(y) + >>> splot(f, [-pi,pi], [-pi,pi]) # doctest: +SKIP + + Plotting a donut:: + + >>> r, R = 1, 2.5 + >>> f = lambda u, v: [r*cos(u), (R+r*sin(u))*cos(v), (R+r*sin(u))*sin(v)] + >>> splot(f, [0, 2*pi], [0, 2*pi]) # doctest: +SKIP + + .. note :: This function requires matplotlib (pylab) 0.98.5.3 or higher. + """ + import pylab + import mpl_toolkits.mplot3d as mplot3d + if file: + axes = None + fig = None + if not axes: + fig = pylab.figure() + axes = mplot3d.axes3d.Axes3D(fig) + ua, ub = u + va, vb = v + du = ub - ua + dv = vb - va + if not isinstance(points, (list, tuple)): + points = [points, points] + M, N = points + u = pylab.linspace(ua, ub, M) + v = pylab.linspace(va, vb, N) + x, y, z = [pylab.zeros((M, N)) for i in xrange(3)] + xab, yab, zab = [[0, 0] for i in xrange(3)] + for n in xrange(N): + for m in xrange(M): + fdata = f(ctx.convert(u[m]), ctx.convert(v[n])) + try: + x[m,n], y[m,n], z[m,n] = fdata + except TypeError: + x[m,n], y[m,n], z[m,n] = u[m], v[n], fdata + for c, cab in [(x[m,n], xab), (y[m,n], yab), (z[m,n], zab)]: + if c < cab[0]: + cab[0] = c + if c > cab[1]: + cab[1] = c + if wireframe: + axes.plot_wireframe(x, y, z, rstride=4, cstride=4) + else: + axes.plot_surface(x, y, z, rstride=4, cstride=4) + axes.set_xlabel('x') + axes.set_ylabel('y') + axes.set_zlabel('z') + if keep_aspect: + dx, dy, dz = [cab[1] - cab[0] for cab in [xab, yab, zab]] + maxd = max(dx, dy, dz) + if dx < maxd: + delta = maxd - dx + axes.set_xlim3d(xab[0] - delta / 2.0, xab[1] + delta / 2.0) + if dy < maxd: + delta = maxd - dy + axes.set_ylim3d(yab[0] - delta / 2.0, yab[1] + delta / 2.0) + if dz < maxd: + delta = maxd - dz + axes.set_zlim3d(zab[0] - delta / 2.0, zab[1] + delta / 2.0) + if fig: + if file: + pylab.savefig(file, dpi=dpi) + else: + pylab.show() + + +VisualizationMethods.plot = plot +VisualizationMethods.default_color_function = default_color_function +VisualizationMethods.phase_color_function = phase_color_function +VisualizationMethods.cplot = cplot +VisualizationMethods.splot = splot diff --git a/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/METADATA b/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..183fc6559786e4cb5414bcd1f6d141e150e04ef5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/METADATA @@ -0,0 +1,272 @@ +Metadata-Version: 2.4 +Name: msgpack +Version: 1.1.1 +Summary: MessagePack serializer +Author-email: Inada Naoki +License: Apache 2.0 +Project-URL: Homepage, https://msgpack.org/ +Project-URL: Documentation, https://msgpack-python.readthedocs.io/ +Project-URL: Repository, https://github.com/msgpack/msgpack-python/ +Project-URL: Tracker, https://github.com/msgpack/msgpack-python/issues +Project-URL: Changelog, https://github.com/msgpack/msgpack-python/blob/main/ChangeLog.rst +Keywords: msgpack,messagepack,serializer,serialization,binary +Classifier: Development Status :: 5 - Production/Stable +Classifier: Operating System :: OS Independent +Classifier: Topic :: File Formats +Classifier: Intended Audience :: Developers +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 +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +License-File: COPYING +Dynamic: license-file + +# MessagePack for Python + +[![Build Status](https://github.com/msgpack/msgpack-python/actions/workflows/wheel.yml/badge.svg)](https://github.com/msgpack/msgpack-python/actions/workflows/wheel.yml) +[![Documentation Status](https://readthedocs.org/projects/msgpack-python/badge/?version=latest)](https://msgpack-python.readthedocs.io/en/latest/?badge=latest) + +## What's this + +[MessagePack](https://msgpack.org/) is an efficient binary serialization format. +It lets you exchange data among multiple languages like JSON. +But it's faster and smaller. +This package provides CPython bindings for reading and writing MessagePack data. + +## Install + +``` +$ pip install msgpack +``` + +### Pure Python implementation + +The extension module in msgpack (`msgpack._cmsgpack`) does not support PyPy. + +But msgpack provides a pure Python implementation (`msgpack.fallback`) for PyPy. + + +### Windows + +When you can't use a binary distribution, you need to install Visual Studio +or Windows SDK on Windows. +Without extension, using pure Python implementation on CPython runs slowly. + + +## How to use + +### One-shot pack & unpack + +Use `packb` for packing and `unpackb` for unpacking. +msgpack provides `dumps` and `loads` as an alias for compatibility with +`json` and `pickle`. + +`pack` and `dump` packs to a file-like object. +`unpack` and `load` unpacks from a file-like object. + +```pycon +>>> import msgpack +>>> msgpack.packb([1, 2, 3]) +'\x93\x01\x02\x03' +>>> msgpack.unpackb(_) +[1, 2, 3] +``` + +Read the docstring for options. + + +### Streaming unpacking + +`Unpacker` is a "streaming unpacker". It unpacks multiple objects from one +stream (or from bytes provided through its `feed` method). + +```py +import msgpack +from io import BytesIO + +buf = BytesIO() +for i in range(100): + buf.write(msgpack.packb(i)) + +buf.seek(0) + +unpacker = msgpack.Unpacker(buf) +for unpacked in unpacker: + print(unpacked) +``` + + +### Packing/unpacking of custom data type + +It is also possible to pack/unpack custom data types. Here is an example for +`datetime.datetime`. + +```py +import datetime +import msgpack + +useful_dict = { + "id": 1, + "created": datetime.datetime.now(), +} + +def decode_datetime(obj): + if '__datetime__' in obj: + obj = datetime.datetime.strptime(obj["as_str"], "%Y%m%dT%H:%M:%S.%f") + return obj + +def encode_datetime(obj): + if isinstance(obj, datetime.datetime): + return {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f")} + return obj + + +packed_dict = msgpack.packb(useful_dict, default=encode_datetime) +this_dict_again = msgpack.unpackb(packed_dict, object_hook=decode_datetime) +``` + +`Unpacker`'s `object_hook` callback receives a dict; the +`object_pairs_hook` callback may instead be used to receive a list of +key-value pairs. + +NOTE: msgpack can encode datetime with tzinfo into standard ext type for now. +See `datetime` option in `Packer` docstring. + + +### Extended types + +It is also possible to pack/unpack custom data types using the **ext** type. + +```pycon +>>> import msgpack +>>> import array +>>> def default(obj): +... if isinstance(obj, array.array) and obj.typecode == 'd': +... return msgpack.ExtType(42, obj.tostring()) +... raise TypeError("Unknown type: %r" % (obj,)) +... +>>> def ext_hook(code, data): +... if code == 42: +... a = array.array('d') +... a.fromstring(data) +... return a +... return ExtType(code, data) +... +>>> data = array.array('d', [1.2, 3.4]) +>>> packed = msgpack.packb(data, default=default) +>>> unpacked = msgpack.unpackb(packed, ext_hook=ext_hook) +>>> data == unpacked +True +``` + + +### Advanced unpacking control + +As an alternative to iteration, `Unpacker` objects provide `unpack`, +`skip`, `read_array_header` and `read_map_header` methods. The former two +read an entire message from the stream, respectively de-serialising and returning +the result, or ignoring it. The latter two methods return the number of elements +in the upcoming container, so that each element in an array, or key-value pair +in a map, can be unpacked or skipped individually. + + +## Notes + +### string and binary type in old msgpack spec + +Early versions of msgpack didn't distinguish string and binary types. +The type for representing both string and binary types was named **raw**. + +You can pack into and unpack from this old spec using `use_bin_type=False` +and `raw=True` options. + +```pycon +>>> import msgpack +>>> msgpack.unpackb(msgpack.packb([b'spam', 'eggs'], use_bin_type=False), raw=True) +[b'spam', b'eggs'] +>>> msgpack.unpackb(msgpack.packb([b'spam', 'eggs'], use_bin_type=True), raw=False) +[b'spam', 'eggs'] +``` + +### ext type + +To use the **ext** type, pass `msgpack.ExtType` object to packer. + +```pycon +>>> import msgpack +>>> packed = msgpack.packb(msgpack.ExtType(42, b'xyzzy')) +>>> msgpack.unpackb(packed) +ExtType(code=42, data='xyzzy') +``` + +You can use it with `default` and `ext_hook`. See below. + + +### Security + +To unpacking data received from unreliable source, msgpack provides +two security options. + +`max_buffer_size` (default: `100*1024*1024`) limits the internal buffer size. +It is used to limit the preallocated list size too. + +`strict_map_key` (default: `True`) limits the type of map keys to bytes and str. +While msgpack spec doesn't limit the types of the map keys, +there is a risk of the hashdos. +If you need to support other types for map keys, use `strict_map_key=False`. + + +### Performance tips + +CPython's GC starts when growing allocated object. +This means unpacking may cause useless GC. +You can use `gc.disable()` when unpacking large message. + +List is the default sequence type of Python. +But tuple is lighter than list. +You can use `use_list=False` while unpacking when performance is important. + + +## Major breaking changes in the history + +### msgpack 0.5 + +Package name on PyPI was changed from `msgpack-python` to `msgpack` from 0.5. + +When upgrading from msgpack-0.4 or earlier, do `pip uninstall msgpack-python` before +`pip install -U msgpack`. + + +### msgpack 1.0 + +* Python 2 support + + * The extension module does not support Python 2 anymore. + The pure Python implementation (`msgpack.fallback`) is used for Python 2. + + * msgpack 1.0.6 drops official support of Python 2.7, as pip and + GitHub Action (setup-python) no longer support Python 2.7. + +* Packer + + * Packer uses `use_bin_type=True` by default. + Bytes are encoded in bin type in msgpack. + * The `encoding` option is removed. UTF-8 is used always. + +* Unpacker + + * Unpacker uses `raw=False` by default. It assumes str types are valid UTF-8 string + and decode them to Python str (unicode) object. + * `encoding` option is removed. You can use `raw=True` to support old format (e.g. unpack into bytes, not str). + * Default value of `max_buffer_size` is changed from 0 to 100 MiB to avoid DoS attack. + You need to pass `max_buffer_size=0` if you have large but safe data. + * Default value of `strict_map_key` is changed to True to avoid hashdos. + You need to pass `strict_map_key=False` if you have data which contain map keys + which type is not bytes or str. diff --git a/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/RECORD b/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..64ef38636a9ba99b91deac8b9e8a9b800d03af18 --- /dev/null +++ b/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/RECORD @@ -0,0 +1,15 @@ +msgpack-1.1.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +msgpack-1.1.1.dist-info/METADATA,sha256=xR8Th3-hQ5cUO1ANM5u28wpE2SDUViUoTojrjQd1rBA,8365 +msgpack-1.1.1.dist-info/RECORD,, +msgpack-1.1.1.dist-info/WHEEL,sha256=DTnKjM5OInJxWADod3iQyWxWcdG-eRwxzGww236swpY,151 +msgpack-1.1.1.dist-info/licenses/COPYING,sha256=SS3tuoXaWHL3jmCRvNH-pHTWYNNay03ulkuKqz8AdCc,614 +msgpack-1.1.1.dist-info/top_level.txt,sha256=2tykSY1pXdiA2xYTDR6jPw0qI5ZGxRihyhf4S5hZyXk,8 +msgpack/__init__.py,sha256=q2T5PRsITVpeytgS0WiSqok9IY8V_aFiC8VVlXTCTgA,1109 +msgpack/__pycache__/__init__.cpython-310.pyc,, +msgpack/__pycache__/exceptions.cpython-310.pyc,, +msgpack/__pycache__/ext.cpython-310.pyc,, +msgpack/__pycache__/fallback.cpython-310.pyc,, +msgpack/_cmsgpack.cpython-310-x86_64-linux-gnu.so,sha256=nO8DdJG0S5PVHOhJuzzJ5XLE7pSjIc7WuYnEKWhH5zI,1360616 +msgpack/exceptions.py,sha256=dCTWei8dpkrMsQDcjQk74ATl9HsIBH0ybt8zOPNqMYc,1081 +msgpack/ext.py,sha256=kteJv03n9tYzd5oo3xYopVTo4vRaAxonBQQJhXohZZo,5726 +msgpack/fallback.py,sha256=0g1Pzp0vtmBEmJ5w9F3s_-JMVURP8RS4G1cc5TRaAsI,32390 diff --git a/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/WHEEL b/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d170d6d9582d145f12244c4135d9446d597e1029 --- /dev/null +++ b/venv/lib/python3.10/site-packages/msgpack-1.1.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/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/licenses/COPYING b/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/licenses/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..f067af3aae15a5b494f0eeb15a7064c176e30fd5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/licenses/COPYING @@ -0,0 +1,14 @@ +Copyright (C) 2008-2011 INADA Naoki + + 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. + diff --git a/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..3aae276bcd9d36403f6ea98de540624ae6b974cf --- /dev/null +++ b/venv/lib/python3.10/site-packages/msgpack-1.1.1.dist-info/top_level.txt @@ -0,0 +1 @@ +msgpack diff --git a/venv/lib/python3.10/site-packages/multidict/__pycache__/_abc.cpython-310.pyc b/venv/lib/python3.10/site-packages/multidict/__pycache__/_abc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8463e45073ff4ce8923195df769128de33d1ec89 Binary files /dev/null and b/venv/lib/python3.10/site-packages/multidict/__pycache__/_abc.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/multidict/__pycache__/_compat.cpython-310.pyc b/venv/lib/python3.10/site-packages/multidict/__pycache__/_compat.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bf3e0a61174f8a5550eac72e47f35e2a7a164ec Binary files /dev/null and b/venv/lib/python3.10/site-packages/multidict/__pycache__/_compat.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/multidict/_multidict_py.py b/venv/lib/python3.10/site-packages/multidict/_multidict_py.py new file mode 100644 index 0000000000000000000000000000000000000000..6b68d52eeff981cc8082e3426ba037ae1aedb2c1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/multidict/_multidict_py.py @@ -0,0 +1,1242 @@ +import enum +import functools +import reprlib +import sys +from array import array +from collections.abc import ( + ItemsView, + Iterable, + Iterator, + KeysView, + Mapping, + ValuesView, +) +from dataclasses import dataclass +from typing import ( + TYPE_CHECKING, + Any, + ClassVar, + Generic, + NoReturn, + Optional, + TypeVar, + Union, + cast, + overload, +) + +from ._abc import MDArg, MultiMapping, MutableMultiMapping, SupportsKeys + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + + +class istr(str): + """Case insensitive str.""" + + __is_istr__ = True + __istr_identity__: Optional[str] = None + + +_V = TypeVar("_V") +_T = TypeVar("_T") + +_SENTINEL = enum.Enum("_SENTINEL", "sentinel") +sentinel = _SENTINEL.sentinel + +_version = array("Q", [0]) + + +class _Iter(Generic[_T]): + __slots__ = ("_size", "_iter") + + def __init__(self, size: int, iterator: Iterator[_T]): + self._size = size + self._iter = iterator + + def __iter__(self) -> Self: + return self + + def __next__(self) -> _T: + return next(self._iter) + + def __length_hint__(self) -> int: + return self._size + + +class _ViewBase(Generic[_V]): + def __init__( + self, + md: "MultiDict[_V]", + ): + self._md = md + + def __len__(self) -> int: + return len(self._md) + + +class _ItemsView(_ViewBase[_V], ItemsView[str, _V]): + def __contains__(self, item: object) -> bool: + if not isinstance(item, (tuple, list)) or len(item) != 2: + return False + key, value = item + try: + identity = self._md._identity(key) + except TypeError: + return False + hash_ = hash(identity) + for slot, idx, e in self._md._keys.iter_hash(hash_): + if e.identity == identity and value == e.value: + return True + return False + + def __iter__(self) -> _Iter[tuple[str, _V]]: + return _Iter(len(self), self._iter(self._md._version)) + + def _iter(self, version: int) -> Iterator[tuple[str, _V]]: + for e in self._md._keys.iter_entries(): + if version != self._md._version: + raise RuntimeError("Dictionary changed during iteration") + yield self._md._key(e.key), e.value + + @reprlib.recursive_repr() + def __repr__(self) -> str: + lst = [] + for e in self._md._keys.iter_entries(): + lst.append(f"'{e.key}': {e.value!r}") + body = ", ".join(lst) + return f"<{self.__class__.__name__}({body})>" + + def _parse_item( + self, arg: Union[tuple[str, _V], _T] + ) -> Optional[tuple[int, str, str, _V]]: + if not isinstance(arg, tuple): + return None + if len(arg) != 2: + return None + try: + identity = self._md._identity(arg[0]) + return (hash(identity), identity, arg[0], arg[1]) + except TypeError: + return None + + def _tmp_set(self, it: Iterable[_T]) -> set[tuple[str, _V]]: + tmp = set() + for arg in it: + item = self._parse_item(arg) + if item is None: + continue + else: + tmp.add((item[1], item[3])) + return tmp + + def __and__(self, other: Iterable[Any]) -> set[tuple[str, _V]]: + ret = set() + try: + it = iter(other) + except TypeError: + return NotImplemented + for arg in it: + item = self._parse_item(arg) + if item is None: + continue + hash_, identity, key, value = item + for slot, idx, e in self._md._keys.iter_hash(hash_): + e.hash = -1 + if e.identity == identity and e.value == value: + ret.add((e.key, e.value)) + self._md._keys.restore_hash(hash_) + return ret + + def __rand__(self, other: Iterable[_T]) -> set[_T]: + ret = set() + try: + it = iter(other) + except TypeError: + return NotImplemented + for arg in it: + item = self._parse_item(arg) + if item is None: + continue + hash_, identity, key, value = item + for slot, idx, e in self._md._keys.iter_hash(hash_): + if e.identity == identity and e.value == value: + ret.add(arg) + break + return ret + + def __or__(self, other: Iterable[_T]) -> set[Union[tuple[str, _V], _T]]: + ret: set[Union[tuple[str, _V], _T]] = set(self) + try: + it = iter(other) + except TypeError: + return NotImplemented + for arg in it: + item: Optional[tuple[int, str, str, _V]] = self._parse_item(arg) + if item is None: + ret.add(arg) + continue + hash_, identity, key, value = item + for slot, idx, e in self._md._keys.iter_hash(hash_): + if e.identity == identity and e.value == value: # pragma: no branch + break + else: + ret.add(arg) + return ret + + def __ror__(self, other: Iterable[_T]) -> set[Union[tuple[str, _V], _T]]: + try: + ret: set[Union[tuple[str, _V], _T]] = set(other) + except TypeError: + return NotImplemented + tmp = self._tmp_set(ret) + + for e in self._md._keys.iter_entries(): + if (e.identity, e.value) not in tmp: + ret.add((e.key, e.value)) + return ret + + def __sub__(self, other: Iterable[_T]) -> set[Union[tuple[str, _V], _T]]: + ret: set[Union[tuple[str, _V], _T]] = set() + try: + it = iter(other) + except TypeError: + return NotImplemented + tmp = self._tmp_set(it) + + for e in self._md._keys.iter_entries(): + if (e.identity, e.value) not in tmp: + ret.add((e.key, e.value)) + + return ret + + def __rsub__(self, other: Iterable[_T]) -> set[_T]: + ret: set[_T] = set() + try: + it = iter(other) + except TypeError: + return NotImplemented + for arg in it: + item = self._parse_item(arg) + if item is None: + ret.add(arg) + continue + + hash_, identity, key, value = item + for slot, idx, e in self._md._keys.iter_hash(hash_): + if e.identity == identity and e.value == value: # pragma: no branch + break + else: + ret.add(arg) + return ret + + def __xor__(self, other: Iterable[_T]) -> set[Union[tuple[str, _V], _T]]: + try: + rgt = set(other) + except TypeError: + return NotImplemented + ret: set[Union[tuple[str, _V], _T]] = self - rgt + ret |= rgt - self + return ret + + __rxor__ = __xor__ + + def isdisjoint(self, other: Iterable[tuple[str, _V]]) -> bool: + for arg in other: + item = self._parse_item(arg) + if item is None: + continue + + hash_, identity, key, value = item + for slot, idx, e in self._md._keys.iter_hash(hash_): + if e.identity == identity and e.value == value: # pragma: no branch + return False + return True + + +class _ValuesView(_ViewBase[_V], ValuesView[_V]): + def __contains__(self, value: object) -> bool: + for e in self._md._keys.iter_entries(): + if e.value == value: + return True + return False + + def __iter__(self) -> _Iter[_V]: + return _Iter(len(self), self._iter(self._md._version)) + + def _iter(self, version: int) -> Iterator[_V]: + for e in self._md._keys.iter_entries(): + if version != self._md._version: + raise RuntimeError("Dictionary changed during iteration") + yield e.value + + @reprlib.recursive_repr() + def __repr__(self) -> str: + lst = [] + for e in self._md._keys.iter_entries(): + lst.append(repr(e.value)) + body = ", ".join(lst) + return f"<{self.__class__.__name__}({body})>" + + +class _KeysView(_ViewBase[_V], KeysView[str]): + def __contains__(self, key: object) -> bool: + if not isinstance(key, str): + return False + identity = self._md._identity(key) + hash_ = hash(identity) + for slot, idx, e in self._md._keys.iter_hash(hash_): + if e.identity == identity: # pragma: no branch + return True + return False + + def __iter__(self) -> _Iter[str]: + return _Iter(len(self), self._iter(self._md._version)) + + def _iter(self, version: int) -> Iterator[str]: + for e in self._md._keys.iter_entries(): + if version != self._md._version: + raise RuntimeError("Dictionary changed during iteration") + yield self._md._key(e.key) + + def __repr__(self) -> str: + lst = [] + for e in self._md._keys.iter_entries(): + lst.append(f"'{e.key}'") + body = ", ".join(lst) + return f"<{self.__class__.__name__}({body})>" + + def __and__(self, other: Iterable[object]) -> set[str]: + ret = set() + try: + it = iter(other) + except TypeError: + return NotImplemented + for key in it: + if not isinstance(key, str): + continue + identity = self._md._identity(key) + hash_ = hash(identity) + for slot, idx, e in self._md._keys.iter_hash(hash_): + if e.identity == identity: # pragma: no branch + ret.add(e.key) + break + return ret + + def __rand__(self, other: Iterable[_T]) -> set[_T]: + ret = set() + try: + it = iter(other) + except TypeError: + return NotImplemented + for key in it: + if not isinstance(key, str): + continue + if key in self._md: + ret.add(key) + return cast(set[_T], ret) + + def __or__(self, other: Iterable[_T]) -> set[Union[str, _T]]: + ret: set[Union[str, _T]] = set(self) + try: + it = iter(other) + except TypeError: + return NotImplemented + for key in it: + if not isinstance(key, str): + ret.add(key) + continue + if key not in self._md: + ret.add(key) + return ret + + def __ror__(self, other: Iterable[_T]) -> set[Union[str, _T]]: + try: + ret: set[Union[str, _T]] = set(other) + except TypeError: + return NotImplemented + + tmp = set() + for key in ret: + if not isinstance(key, str): + continue + identity = self._md._identity(key) + tmp.add(identity) + + for e in self._md._keys.iter_entries(): + if e.identity not in tmp: + ret.add(e.key) + return ret + + def __sub__(self, other: Iterable[object]) -> set[str]: + ret = set(self) + try: + it = iter(other) + except TypeError: + return NotImplemented + for key in it: + if not isinstance(key, str): + continue + identity = self._md._identity(key) + hash_ = hash(identity) + for slot, idx, e in self._md._keys.iter_hash(hash_): + if e.identity == identity: # pragma: no branch + ret.discard(e.key) + break + return ret + + def __rsub__(self, other: Iterable[_T]) -> set[_T]: + try: + ret: set[_T] = set(other) + except TypeError: + return NotImplemented + for key in other: + if not isinstance(key, str): + continue + if key in self._md: + ret.discard(key) # type: ignore[arg-type] + return ret + + def __xor__(self, other: Iterable[_T]) -> set[Union[str, _T]]: + try: + rgt = set(other) + except TypeError: + return NotImplemented + ret: set[Union[str, _T]] = self - rgt # type: ignore[assignment] + ret |= rgt - self + return ret + + __rxor__ = __xor__ + + def isdisjoint(self, other: Iterable[object]) -> bool: + for key in other: + if not isinstance(key, str): + continue + if key in self._md: + return False + return True + + +class _CSMixin: + _ci: ClassVar[bool] = False + + def _key(self, key: str) -> str: + return key + + def _identity(self, key: str) -> str: + if isinstance(key, str): + return key + else: + raise TypeError("MultiDict keys should be either str or subclasses of str") + + +class _CIMixin: + _ci: ClassVar[bool] = True + + def _key(self, key: str) -> str: + if type(key) is istr: + return key + else: + return istr(key) + + def _identity(self, key: str) -> str: + if isinstance(key, istr): + ret = key.__istr_identity__ + if ret is None: + ret = key.lower() + key.__istr_identity__ = ret + return ret + if isinstance(key, str): + return key.lower() + else: + raise TypeError("MultiDict keys should be either str or subclasses of str") + + +def estimate_log2_keysize(n: int) -> int: + # 7 == HT_MINSIZE - 1 + return (((n * 3 + 1) // 2) | 7).bit_length() + + +@dataclass +class _Entry(Generic[_V]): + hash: int + identity: str + key: str + value: _V + + +@dataclass +class _HtKeys(Generic[_V]): # type: ignore[misc] + LOG_MINSIZE: ClassVar[int] = 3 + MINSIZE: ClassVar[int] = 8 + PREALLOCATED_INDICES: ClassVar[dict[int, array]] = { # type: ignore[type-arg] + log2_size: array( + "b" if log2_size < 8 else "h", (-1 for i in range(1 << log2_size)) + ) + for log2_size in range(3, 10) + } + + log2_size: int + usable: int + + indices: array # type: ignore[type-arg] # in py3.9 array is not generic + entries: list[Optional[_Entry[_V]]] + + @functools.cached_property + def nslots(self) -> int: + return 1 << self.log2_size + + @functools.cached_property + def mask(self) -> int: + return self.nslots - 1 + + if sys.implementation.name != "pypy": + + def __sizeof__(self) -> int: + return ( + object.__sizeof__(self) + + sys.getsizeof(self.indices) + + sys.getsizeof(self.entries) + ) + + @classmethod + def new(cls, log2_size: int, entries: list[Optional[_Entry[_V]]]) -> Self: + size = 1 << log2_size + usable = (size << 1) // 3 + if log2_size < 10: + indices = cls.PREALLOCATED_INDICES[log2_size].__copy__() + elif log2_size < 16: + indices = array("h", (-1 for i in range(size))) + elif log2_size < 32: + indices = array("l", (-1 for i in range(size))) + else: # pragma: no cover # don't test huge multidicts + indices = array("q", (-1 for i in range(size))) + ret = cls( + log2_size=log2_size, + usable=usable, + indices=indices, + entries=entries, + ) + return ret + + def clone(self) -> "_HtKeys[_V]": + entries = [ + _Entry(e.hash, e.identity, e.key, e.value) if e is not None else None + for e in self.entries + ] + + return _HtKeys( + log2_size=self.log2_size, + usable=self.usable, + indices=self.indices.__copy__(), + entries=entries, + ) + + def build_indices(self, update: bool) -> None: + mask = self.mask + indices = self.indices + for idx, e in enumerate(self.entries): + assert e is not None + hash_ = e.hash + if update: + if hash_ == -1: + hash_ = hash(e.identity) + else: + assert hash_ != -1 + i = hash_ & mask + perturb = hash_ & sys.maxsize + while indices[i] != -1: + perturb >>= 5 + i = mask & (i * 5 + perturb + 1) + indices[i] = idx + + def find_empty_slot(self, hash_: int) -> int: + mask = self.mask + indices = self.indices + i = hash_ & mask + perturb = hash_ & sys.maxsize + ix = indices[i] + while ix != -1: + perturb >>= 5 + i = (i * 5 + perturb + 1) & mask + ix = indices[i] + return i + + def iter_hash(self, hash_: int) -> Iterator[tuple[int, int, _Entry[_V]]]: + mask = self.mask + indices = self.indices + entries = self.entries + i = hash_ & mask + perturb = hash_ & sys.maxsize + ix = indices[i] + while ix != -1: + if ix != -2: + e = entries[ix] + if e.hash == hash_: + yield i, ix, e + perturb >>= 5 + i = (i * 5 + perturb + 1) & mask + ix = indices[i] + + def del_idx(self, hash_: int, idx: int) -> None: + mask = self.mask + indices = self.indices + i = hash_ & mask + perturb = hash_ & sys.maxsize + ix = indices[i] + while ix != idx: + perturb >>= 5 + i = (i * 5 + perturb + 1) & mask + ix = indices[i] + indices[i] = -2 + + def iter_entries(self) -> Iterator[_Entry[_V]]: + return filter(None, self.entries) + + def restore_hash(self, hash_: int) -> None: + mask = self.mask + indices = self.indices + entries = self.entries + i = hash_ & mask + perturb = hash_ & sys.maxsize + ix = indices[i] + while ix != -1: + if ix != -2: + entry = entries[ix] + if entry.hash == -1: + entry.hash = hash_ + perturb >>= 5 + i = (i * 5 + perturb + 1) & mask + ix = indices[i] + + +class MultiDict(_CSMixin, MutableMultiMapping[_V]): + """Dictionary with the support for duplicate keys.""" + + __slots__ = ("_keys", "_used", "_version") + + def __init__(self, arg: MDArg[_V] = None, /, **kwargs: _V): + self._used = 0 + v = _version + v[0] += 1 + self._version = v[0] + if not kwargs: + md = None + if isinstance(arg, MultiDictProxy): + md = arg._md + elif isinstance(arg, MultiDict): + md = arg + if md is not None and md._ci is self._ci: + self._from_md(md) + return + + it = self._parse_args(arg, kwargs) + log2_size = estimate_log2_keysize(cast(int, next(it))) + if log2_size > 17: # pragma: no cover + # Don't overallocate really huge keys space in init + log2_size = 17 + self._keys: _HtKeys[_V] = _HtKeys.new(log2_size, []) + self._extend_items(cast(Iterator[_Entry[_V]], it)) + + def _from_md(self, md: "MultiDict[_V]") -> None: + # Copy everything as-is without compacting the new multidict, + # otherwise it requires reindexing + self._keys = md._keys.clone() + self._used = md._used + + @overload + def getall(self, key: str) -> list[_V]: ... + @overload + def getall(self, key: str, default: _T) -> Union[list[_V], _T]: ... + def getall( + self, key: str, default: Union[_T, _SENTINEL] = sentinel + ) -> Union[list[_V], _T]: + """Return a list of all values matching the key.""" + identity = self._identity(key) + hash_ = hash(identity) + res = [] + restore = [] + for slot, idx, e in self._keys.iter_hash(hash_): + if e.identity == identity: # pragma: no branch + res.append(e.value) + e.hash = -1 + restore.append(idx) + + if res: + entries = self._keys.entries + for idx in restore: + entries[idx].hash = hash_ # type: ignore[union-attr] + return res + if not res and default is not sentinel: + return default + raise KeyError("Key not found: %r" % key) + + @overload + def getone(self, key: str) -> _V: ... + @overload + def getone(self, key: str, default: _T) -> Union[_V, _T]: ... + def getone( + self, key: str, default: Union[_T, _SENTINEL] = sentinel + ) -> Union[_V, _T]: + """Get first value matching the key. + + Raises KeyError if the key is not found and no default is provided. + """ + identity = self._identity(key) + hash_ = hash(identity) + for slot, idx, e in self._keys.iter_hash(hash_): + if e.identity == identity: # pragma: no branch + return e.value + if default is not sentinel: + return default + raise KeyError("Key not found: %r" % key) + + # Mapping interface # + + def __getitem__(self, key: str) -> _V: + return self.getone(key) + + @overload + def get(self, key: str, /) -> Union[_V, None]: ... + @overload + def get(self, key: str, /, default: _T) -> Union[_V, _T]: ... + def get(self, key: str, default: Union[_T, None] = None) -> Union[_V, _T, None]: + """Get first value matching the key. + + If the key is not found, returns the default (or None if no default is provided) + """ + return self.getone(key, default) + + def __iter__(self) -> Iterator[str]: + return iter(self.keys()) + + def __len__(self) -> int: + return self._used + + def keys(self) -> KeysView[str]: + """Return a new view of the dictionary's keys.""" + return _KeysView(self) + + def items(self) -> ItemsView[str, _V]: + """Return a new view of the dictionary's items *(key, value) pairs).""" + return _ItemsView(self) + + def values(self) -> _ValuesView[_V]: + """Return a new view of the dictionary's values.""" + return _ValuesView(self) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Mapping): + return NotImplemented + if isinstance(other, MultiDictProxy): + return self == other._md + if isinstance(other, MultiDict): + lft = self._keys + rht = other._keys + if self._used != other._used: + return False + for e1, e2 in zip(lft.iter_entries(), rht.iter_entries()): + if e1.identity != e2.identity or e1.value != e2.value: + return False + return True + if self._used != len(other): + return False + for k, v in self.items(): + nv = other.get(k, sentinel) + if v != nv: + return False + return True + + def __contains__(self, key: object) -> bool: + if not isinstance(key, str): + return False + identity = self._identity(key) + hash_ = hash(identity) + for slot, idx, e in self._keys.iter_hash(hash_): + if e.identity == identity: # pragma: no branch + return True + return False + + @reprlib.recursive_repr() + def __repr__(self) -> str: + body = ", ".join(f"'{e.key}': {e.value!r}" for e in self._keys.iter_entries()) + return f"<{self.__class__.__name__}({body})>" + + if sys.implementation.name != "pypy": + + def __sizeof__(self) -> int: + return object.__sizeof__(self) + sys.getsizeof(self._keys) + + def __reduce__(self) -> tuple[type[Self], tuple[list[tuple[str, _V]]]]: + return (self.__class__, (list(self.items()),)) + + def add(self, key: str, value: _V) -> None: + identity = self._identity(key) + hash_ = hash(identity) + self._add_with_hash(_Entry(hash_, identity, key, value)) + self._incr_version() + + def copy(self) -> Self: + """Return a copy of itself.""" + cls = self.__class__ + return cls(self) + + __copy__ = copy + + def extend(self, arg: MDArg[_V] = None, /, **kwargs: _V) -> None: + """Extend current MultiDict with more values. + + This method must be used instead of update. + """ + it = self._parse_args(arg, kwargs) + newsize = self._used + cast(int, next(it)) + self._resize(estimate_log2_keysize(newsize), False) + self._extend_items(cast(Iterator[_Entry[_V]], it)) + + def _parse_args( + self, + arg: MDArg[_V], + kwargs: Mapping[str, _V], + ) -> Iterator[Union[int, _Entry[_V]]]: + identity_func = self._identity + if arg: + if isinstance(arg, MultiDictProxy): + arg = arg._md + if isinstance(arg, MultiDict): + yield len(arg) + len(kwargs) + if self._ci is not arg._ci: + for e in arg._keys.iter_entries(): + identity = identity_func(e.key) + yield _Entry(hash(identity), identity, e.key, e.value) + else: + for e in arg._keys.iter_entries(): + yield _Entry(e.hash, e.identity, e.key, e.value) + if kwargs: + for key, value in kwargs.items(): + identity = identity_func(key) + yield _Entry(hash(identity), identity, key, value) + else: + if hasattr(arg, "keys"): + arg = cast(SupportsKeys[_V], arg) + arg = [(k, arg[k]) for k in arg.keys()] + if kwargs: + arg = list(arg) + arg.extend(list(kwargs.items())) + try: + yield len(arg) + len(kwargs) # type: ignore[arg-type] + except TypeError: + yield 0 + for pos, item in enumerate(arg): + if not len(item) == 2: + raise ValueError( + f"multidict update sequence element #{pos}" + f"has length {len(item)}; 2 is required" + ) + identity = identity_func(item[0]) + yield _Entry(hash(identity), identity, item[0], item[1]) + else: + yield len(kwargs) + for key, value in kwargs.items(): + identity = identity_func(key) + yield _Entry(hash(identity), identity, key, value) + + def _extend_items(self, items: Iterable[_Entry[_V]]) -> None: + for e in items: + self._add_with_hash(e) + self._incr_version() + + def clear(self) -> None: + """Remove all items from MultiDict.""" + self._used = 0 + self._keys = _HtKeys.new(_HtKeys.LOG_MINSIZE, []) + self._incr_version() + + # Mapping interface # + + def __setitem__(self, key: str, value: _V) -> None: + identity = self._identity(key) + hash_ = hash(identity) + found = False + + for slot, idx, e in self._keys.iter_hash(hash_): + if e.identity == identity: # pragma: no branch + if not found: + e.key = key + e.value = value + e.hash = -1 + found = True + self._incr_version() + elif e.hash != -1: # pragma: no branch + self._del_at(slot, idx) + + if not found: + self._add_with_hash(_Entry(hash_, identity, key, value)) + else: + self._keys.restore_hash(hash_) + + def __delitem__(self, key: str) -> None: + found = False + identity = self._identity(key) + hash_ = hash(identity) + for slot, idx, e in self._keys.iter_hash(hash_): + if e.identity == identity: # pragma: no branch + self._del_at(slot, idx) + found = True + if not found: + raise KeyError(key) + else: + self._incr_version() + + @overload + def setdefault( + self: "MultiDict[Union[_T, None]]", key: str, default: None = None + ) -> Union[_T, None]: ... + @overload + def setdefault(self, key: str, default: _V) -> _V: ... + def setdefault(self, key: str, default: Union[_V, None] = None) -> Union[_V, None]: # type: ignore[misc] + """Return value for key, set value to default if key is not present.""" + identity = self._identity(key) + hash_ = hash(identity) + for slot, idx, e in self._keys.iter_hash(hash_): + if e.identity == identity: # pragma: no branch + return e.value + self.add(key, default) # type: ignore[arg-type] + return default + + @overload + def popone(self, key: str) -> _V: ... + @overload + def popone(self, key: str, default: _T) -> Union[_V, _T]: ... + def popone( + self, key: str, default: Union[_T, _SENTINEL] = sentinel + ) -> Union[_V, _T]: + """Remove specified key and return the corresponding value. + + If key is not found, d is returned if given, otherwise + KeyError is raised. + + """ + identity = self._identity(key) + hash_ = hash(identity) + for slot, idx, e in self._keys.iter_hash(hash_): + if e.identity == identity: # pragma: no branch + value = e.value + self._del_at(slot, idx) + self._incr_version() + return value + if default is sentinel: + raise KeyError(key) + else: + return default + + # Type checking will inherit signature for pop() if we don't confuse it here. + if not TYPE_CHECKING: + pop = popone + + @overload + def popall(self, key: str) -> list[_V]: ... + @overload + def popall(self, key: str, default: _T) -> Union[list[_V], _T]: ... + def popall( + self, key: str, default: Union[_T, _SENTINEL] = sentinel + ) -> Union[list[_V], _T]: + """Remove all occurrences of key and return the list of corresponding + values. + + If key is not found, default is returned if given, otherwise + KeyError is raised. + + """ + found = False + identity = self._identity(key) + hash_ = hash(identity) + ret = [] + for slot, idx, e in self._keys.iter_hash(hash_): + if e.identity == identity: # pragma: no branch + found = True + ret.append(e.value) + self._del_at(slot, idx) + self._incr_version() + + if not found: + if default is sentinel: + raise KeyError(key) + else: + return default + else: + return ret + + def popitem(self) -> tuple[str, _V]: + """Remove and return an arbitrary (key, value) pair.""" + if self._used <= 0: + raise KeyError("empty multidict") + + pos = len(self._keys.entries) - 1 + entry = self._keys.entries.pop() + + while entry is None: + pos -= 1 + entry = self._keys.entries.pop() + + ret = self._key(entry.key), entry.value + self._keys.del_idx(entry.hash, pos) + self._used -= 1 + self._incr_version() + return ret + + def update(self, arg: MDArg[_V] = None, /, **kwargs: _V) -> None: + """Update the dictionary, overwriting existing keys.""" + it = self._parse_args(arg, kwargs) + newsize = self._used + cast(int, next(it)) + log2_size = estimate_log2_keysize(newsize) + if log2_size > 17: # pragma: no cover + # Don't overallocate really huge keys space in update, + # duplicate keys could reduce the resulting anount of entries + log2_size = 17 + if log2_size > self._keys.log2_size: + self._resize(log2_size, False) + try: + self._update_items(cast(Iterator[_Entry[_V]], it)) + finally: + self._post_update() + + def _update_items(self, items: Iterator[_Entry[_V]]) -> None: + for entry in items: + found = False + hash_ = entry.hash + identity = entry.identity + for slot, idx, e in self._keys.iter_hash(hash_): + if e.identity == identity: # pragma: no branch + if not found: + found = True + e.key = entry.key + e.value = entry.value + e.hash = -1 + else: + self._del_at_for_upd(e) + if not found: + self._add_with_hash_for_upd(entry) + + def _post_update(self) -> None: + keys = self._keys + indices = keys.indices + entries = keys.entries + for slot in range(keys.nslots): + idx = indices[slot] + if idx >= 0: + e2 = entries[idx] + assert e2 is not None + if e2.key is None: + entries[idx] = None + indices[slot] = -2 + self._used -= 1 + if e2.hash == -1: + e2.hash = hash(e2.identity) + + self._incr_version() + + def merge(self, arg: MDArg[_V] = None, /, **kwargs: _V) -> None: + """Merge into the dictionary, adding non-existing keys.""" + it = self._parse_args(arg, kwargs) + newsize = self._used + cast(int, next(it)) + log2_size = estimate_log2_keysize(newsize) + if log2_size > 17: # pragma: no cover + # Don't overallocate really huge keys space in update, + # duplicate keys could reduce the resulting anount of entries + log2_size = 17 + if log2_size > self._keys.log2_size: + self._resize(log2_size, False) + try: + self._merge_items(cast(Iterator[_Entry[_V]], it)) + finally: + self._post_update() + + def _merge_items(self, items: Iterator[_Entry[_V]]) -> None: + for entry in items: + hash_ = entry.hash + identity = entry.identity + for slot, idx, e in self._keys.iter_hash(hash_): + if e.identity == identity: # pragma: no branch + break + else: + self._add_with_hash_for_upd(entry) + + def _incr_version(self) -> None: + v = _version + v[0] += 1 + self._version = v[0] + + def _resize(self, log2_newsize: int, update: bool) -> None: + oldkeys = self._keys + newentries = self._used + + if len(oldkeys.entries) == newentries: + entries = oldkeys.entries + else: + entries = [e for e in oldkeys.entries if e is not None] + newkeys: _HtKeys[_V] = _HtKeys.new(log2_newsize, entries) + newkeys.usable -= newentries + newkeys.build_indices(update) + self._keys = newkeys + + def _add_with_hash(self, entry: _Entry[_V]) -> None: + if self._keys.usable <= 0: + self._resize((self._used * 3 | _HtKeys.MINSIZE - 1).bit_length(), False) + keys = self._keys + slot = keys.find_empty_slot(entry.hash) + keys.indices[slot] = len(keys.entries) + keys.entries.append(entry) + self._incr_version() + self._used += 1 + keys.usable -= 1 + + def _add_with_hash_for_upd(self, entry: _Entry[_V]) -> None: + if self._keys.usable <= 0: + self._resize((self._used * 3 | _HtKeys.MINSIZE - 1).bit_length(), True) + keys = self._keys + slot = keys.find_empty_slot(entry.hash) + keys.indices[slot] = len(keys.entries) + entry.hash = -1 + keys.entries.append(entry) + self._incr_version() + self._used += 1 + keys.usable -= 1 + + def _del_at(self, slot: int, idx: int) -> None: + self._keys.entries[idx] = None + self._keys.indices[slot] = -2 + self._used -= 1 + + def _del_at_for_upd(self, entry: _Entry[_V]) -> None: + entry.key = None # type: ignore[assignment] + entry.value = None # type: ignore[assignment] + + +class CIMultiDict(_CIMixin, MultiDict[_V]): + """Dictionary with the support for duplicate case-insensitive keys.""" + + +class MultiDictProxy(_CSMixin, MultiMapping[_V]): + """Read-only proxy for MultiDict instance.""" + + __slots__ = ("_md",) + + _md: MultiDict[_V] + + def __init__(self, arg: Union[MultiDict[_V], "MultiDictProxy[_V]"]): + if not isinstance(arg, (MultiDict, MultiDictProxy)): + raise TypeError( + f"ctor requires MultiDict or MultiDictProxy instance, not {type(arg)}" + ) + if isinstance(arg, MultiDictProxy): + self._md = arg._md + else: + self._md = arg + + def __reduce__(self) -> NoReturn: + raise TypeError(f"can't pickle {self.__class__.__name__} objects") + + @overload + def getall(self, key: str) -> list[_V]: ... + @overload + def getall(self, key: str, default: _T) -> Union[list[_V], _T]: ... + def getall( + self, key: str, default: Union[_T, _SENTINEL] = sentinel + ) -> Union[list[_V], _T]: + """Return a list of all values matching the key.""" + if default is not sentinel: + return self._md.getall(key, default) + else: + return self._md.getall(key) + + @overload + def getone(self, key: str) -> _V: ... + @overload + def getone(self, key: str, default: _T) -> Union[_V, _T]: ... + def getone( + self, key: str, default: Union[_T, _SENTINEL] = sentinel + ) -> Union[_V, _T]: + """Get first value matching the key. + + Raises KeyError if the key is not found and no default is provided. + """ + if default is not sentinel: + return self._md.getone(key, default) + else: + return self._md.getone(key) + + # Mapping interface # + + def __getitem__(self, key: str) -> _V: + return self.getone(key) + + @overload + def get(self, key: str, /) -> Union[_V, None]: ... + @overload + def get(self, key: str, /, default: _T) -> Union[_V, _T]: ... + def get(self, key: str, default: Union[_T, None] = None) -> Union[_V, _T, None]: + """Get first value matching the key. + + If the key is not found, returns the default (or None if no default is provided) + """ + return self._md.getone(key, default) + + def __iter__(self) -> Iterator[str]: + return iter(self._md.keys()) + + def __len__(self) -> int: + return len(self._md) + + def keys(self) -> KeysView[str]: + """Return a new view of the dictionary's keys.""" + return self._md.keys() + + def items(self) -> ItemsView[str, _V]: + """Return a new view of the dictionary's items *(key, value) pairs).""" + return self._md.items() + + def values(self) -> _ValuesView[_V]: + """Return a new view of the dictionary's values.""" + return self._md.values() + + def __eq__(self, other: object) -> bool: + return self._md == other + + def __contains__(self, key: object) -> bool: + return key in self._md + + @reprlib.recursive_repr() + def __repr__(self) -> str: + body = ", ".join(f"'{k}': {v!r}" for k, v in self.items()) + return f"<{self.__class__.__name__}({body})>" + + def copy(self) -> MultiDict[_V]: + """Return a copy of itself.""" + return MultiDict(self._md) + + +class CIMultiDictProxy(_CIMixin, MultiDictProxy[_V]): + """Read-only proxy for CIMultiDict instance.""" + + def __init__(self, arg: Union[MultiDict[_V], MultiDictProxy[_V]]): + if not isinstance(arg, (CIMultiDict, CIMultiDictProxy)): + raise TypeError( + "ctor requires CIMultiDict or CIMultiDictProxy instance" + f", not {type(arg)}" + ) + + super().__init__(arg) + + def copy(self) -> CIMultiDict[_V]: + """Return a copy of itself.""" + return CIMultiDict(self._md) + + +def getversion(md: Union[MultiDict[object], MultiDictProxy[object]]) -> int: + if isinstance(md, MultiDictProxy): + md = md._md + elif not isinstance(md, MultiDict): + raise TypeError("Parameter should be multidict or proxy") + return md._version diff --git a/venv/lib/python3.10/site-packages/multidict/py.typed b/venv/lib/python3.10/site-packages/multidict/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..dfe8cc048e7100a97025b954fffa31e4ff859a7d --- /dev/null +++ b/venv/lib/python3.10/site-packages/multidict/py.typed @@ -0,0 +1 @@ +PEP-561 marker. \ No newline at end of file diff --git a/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/COPYING b/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..17f34bc3d8ae0889ae327ae0c16bf78870c41527 --- /dev/null +++ b/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/COPYING @@ -0,0 +1,28 @@ +Copyright (c) 2006-2008, R Oudkerk + +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. +3. Neither the name of author 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 AUTHOR 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 AUTHOR 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/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/LICENSE b/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0f46bc0edd00d1950d98fec0f78e4366691391d5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/LICENSE @@ -0,0 +1,38 @@ +Copyright (c) 2008-2016 California Institute of Technology. +Copyright (c) 2016-2024 The Uncertainty Quantification Foundation. +All rights reserved. + +This software forks the python package "multiprocessing". Licence and +copyright information for multiprocessing can be found in "COPYING". + +This software is available subject to the conditions and terms laid +out below. By downloading and using this software you are agreeing +to the following conditions. + +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 names of the copyright holders nor the names of any of + the 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. + diff --git a/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/METADATA b/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..1e8d30dd497e6ac867b1f7f11f79ac2704525be0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/METADATA @@ -0,0 +1,203 @@ +Metadata-Version: 2.1 +Name: multiprocess +Version: 0.70.16 +Summary: better multiprocessing and multithreading in Python +Home-page: https://github.com/uqfoundation/multiprocess +Download-URL: https://pypi.org/project/multiprocess/#files +Author: Mike McKerns +Author-email: mmckerns@uqfoundation.org +Maintainer: Mike McKerns +Maintainer-email: mmckerns@uqfoundation.org +License: BSD-3-Clause +Project-URL: Documentation, http://multiprocess.rtfd.io +Project-URL: Source Code, https://github.com/uqfoundation/multiprocess +Project-URL: Bug Tracker, https://github.com/uqfoundation/multiprocess/issues +Platform: Linux +Platform: Windows +Platform: Mac +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: BSD License +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 :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Software Development +Requires-Python: >=3.8 +License-File: LICENSE +License-File: COPYING +Requires-Dist: dill (>=0.3.8) + +----------------------------------------------------------------- +multiprocess: better multiprocessing and multithreading in Python +----------------------------------------------------------------- + +About Multiprocess +================== + +``multiprocess`` is a fork of ``multiprocessing``. ``multiprocess`` extends ``multiprocessing`` to provide enhanced serialization, using `dill`. ``multiprocess`` leverages ``multiprocessing`` to support the spawning of processes using the API of the Python standard library's ``threading`` module. ``multiprocessing`` has been distributed as part of the standard library since Python 2.6. + +``multiprocess`` is part of ``pathos``, a Python framework for heterogeneous computing. +``multiprocess`` is in active development, so any user feedback, bug reports, comments, +or suggestions are highly appreciated. A list of issues is located at https://github.com/uqfoundation/multiprocess/issues, with a legacy list maintained at https://uqfoundation.github.io/project/pathos/query. + + +Major Features +============== + +``multiprocess`` enables: + + - objects to be transferred between processes using pipes or multi-producer/multi-consumer queues + - objects to be shared between processes using a server process or (for simple data) shared memory + +``multiprocess`` provides: + + - equivalents of all the synchronization primitives in ``threading`` + - a ``Pool`` class to facilitate submitting tasks to worker processes + - enhanced serialization, using ``dill`` + + +Current Release +=============== + +The latest released version of ``multiprocess`` is available from: + + https://pypi.org/project/multiprocess + +``multiprocess`` is distributed under a 3-clause BSD license, and is a fork of ``multiprocessing``. + + +Development Version +=================== + +You can get the latest development version with all the shiny new features at: + + https://github.com/uqfoundation + +If you have a new contribution, please submit a pull request. + + +Installation +============ + +``multiprocess`` can be installed with ``pip``:: + + $ pip install multiprocess + +For Python 2, a C compiler is required to build the included extension module from source. Python 3 and binary installs do not require a C compiler. + + +Requirements +============ + +``multiprocess`` requires: + + - ``python`` (or ``pypy``), **>=3.8** + - ``setuptools``, **>=42** + - ``dill``, **>=0.3.8** + + +Basic Usage +=========== + +The ``multiprocess.Process`` class follows the API of ``threading.Thread``. +For example :: + + from multiprocess import Process, Queue + + def f(q): + q.put('hello world') + + if __name__ == '__main__': + q = Queue() + p = Process(target=f, args=[q]) + p.start() + print (q.get()) + p.join() + +Synchronization primitives like locks, semaphores and conditions are +available, for example :: + + >>> from multiprocess import Condition + >>> c = Condition() + >>> print (c) + ), 0> + >>> c.acquire() + True + >>> print (c) + ), 0> + +One can also use a manager to create shared objects either in shared +memory or in a server process, for example :: + + >>> from multiprocess import Manager + >>> manager = Manager() + >>> l = manager.list(range(10)) + >>> l.reverse() + >>> print (l) + [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + >>> print (repr(l)) + + +Tasks can be offloaded to a pool of worker processes in various ways, +for example :: + + >>> from multiprocess import Pool + >>> def f(x): return x*x + ... + >>> p = Pool(4) + >>> result = p.map_async(f, range(10)) + >>> print (result.get(timeout=1)) + [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + +When ``dill`` is installed, serialization is extended to most objects, +for example :: + + >>> from multiprocess import Pool + >>> p = Pool(4) + >>> print (p.map(lambda x: (lambda y:y**2)(x) + x, xrange(10))) + [0, 2, 6, 12, 20, 30, 42, 56, 72, 90] + + +More Information +================ + +Probably the best way to get started is to look at the documentation at +http://multiprocess.rtfd.io. Also see ``multiprocess.tests`` for scripts that +demonstrate how ``multiprocess`` can be used to leverge multiple processes +to execute Python in parallel. You can run the test suite with +``python -m multiprocess.tests``. As ``multiprocess`` conforms to the +``multiprocessing`` interface, the examples and documentation found at +http://docs.python.org/library/multiprocessing.html also apply to +``multiprocess`` if one will ``import multiprocessing as multiprocess``. +See https://github.com/uqfoundation/multiprocess/tree/master/py3.12/examples +for a set of examples that demonstrate some basic use cases and benchmarking +for running Python code in parallel. Please feel free to submit a ticket on +github, or ask a question on stackoverflow (**@Mike McKerns**). If you would +like to share how you use ``multiprocess`` in your work, please send an email +(to **mmckerns at uqfoundation dot org**). + + +Citation +======== + +If you use ``multiprocess`` to do research that leads to publication, we ask that you +acknowledge use of ``multiprocess`` by citing the following in your publication:: + + M.M. McKerns, L. Strand, T. Sullivan, A. Fang, M.A.G. Aivazis, + "Building a framework for predictive science", Proceedings of + the 10th Python in Science Conference, 2011; + http://arxiv.org/pdf/1202.1056 + + Michael McKerns and Michael Aivazis, + "pathos: a framework for heterogeneous computing", 2010- ; + https://uqfoundation.github.io/project/pathos + +Please see https://uqfoundation.github.io/project/pathos or +http://arxiv.org/pdf/1202.1056 for further information. diff --git a/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/RECORD b/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f9b6e322f58b95c8384ea9203fc06bd289e0c564 --- /dev/null +++ b/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/RECORD @@ -0,0 +1,73 @@ +_multiprocess/__init__.py,sha256=zX5_h36TGSL0brHRtBvCL5E59ccW7yjL79i-Y399ODM,321 +_multiprocess/__pycache__/__init__.cpython-310.pyc,, +multiprocess-0.70.16.dist-info/COPYING,sha256=n3_yfLkw0sMgLuB-PS1hRvTeZ20GmjPaMWbJjNuoOpU,1493 +multiprocess-0.70.16.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +multiprocess-0.70.16.dist-info/LICENSE,sha256=6XUJedJKg2dhI98BD3PMtVtZvRFT-oGczkOr5B4tEEA,1930 +multiprocess-0.70.16.dist-info/METADATA,sha256=Sv2eH2CjjyjVYaryTKqHkbJTlxlVA-SbmziCgkBJeQ0,7151 +multiprocess-0.70.16.dist-info/RECORD,, +multiprocess-0.70.16.dist-info/WHEEL,sha256=KxatxaZA14OswIJTdImHhiM2tdZgU-xLZEzs-sYveVc,94 +multiprocess-0.70.16.dist-info/top_level.txt,sha256=qtJc8GNdvi6suNpISX0Myln9AXJBYrNuas1MCqRPPqg,27 +multiprocess/__info__.py,sha256=84TUBn1oJMNpbVvXKs0lKyfLYaZvRr-ZVh1zHM9VeCY,7997 +multiprocess/__init__.py,sha256=XWUBDGorUkDW04h64xe51pUV9N5gzvSDj3tNT2ekifw,1856 +multiprocess/__pycache__/__info__.cpython-310.pyc,, +multiprocess/__pycache__/__init__.cpython-310.pyc,, +multiprocess/__pycache__/connection.cpython-310.pyc,, +multiprocess/__pycache__/context.cpython-310.pyc,, +multiprocess/__pycache__/forkserver.cpython-310.pyc,, +multiprocess/__pycache__/heap.cpython-310.pyc,, +multiprocess/__pycache__/managers.cpython-310.pyc,, +multiprocess/__pycache__/pool.cpython-310.pyc,, +multiprocess/__pycache__/popen_fork.cpython-310.pyc,, +multiprocess/__pycache__/popen_forkserver.cpython-310.pyc,, +multiprocess/__pycache__/popen_spawn_posix.cpython-310.pyc,, +multiprocess/__pycache__/popen_spawn_win32.cpython-310.pyc,, +multiprocess/__pycache__/process.cpython-310.pyc,, +multiprocess/__pycache__/queues.cpython-310.pyc,, +multiprocess/__pycache__/reduction.cpython-310.pyc,, +multiprocess/__pycache__/resource_sharer.cpython-310.pyc,, +multiprocess/__pycache__/resource_tracker.cpython-310.pyc,, +multiprocess/__pycache__/shared_memory.cpython-310.pyc,, +multiprocess/__pycache__/sharedctypes.cpython-310.pyc,, +multiprocess/__pycache__/spawn.cpython-310.pyc,, +multiprocess/__pycache__/synchronize.cpython-310.pyc,, +multiprocess/__pycache__/util.cpython-310.pyc,, +multiprocess/connection.py,sha256=TO9BbLVlLVjTjr0fP7lIumBgiLwaFVnpqMBgFG6iL9s,31843 +multiprocess/context.py,sha256=2fYvgfnu3B8wj8UyNndHUHgeuVDoVxlkFFKryycstaU,11610 +multiprocess/dummy/__init__.py,sha256=kSekDqD_NCy0FDg7XnxZSgW-Ldg1_iRr07sNwDajKpA,3061 +multiprocess/dummy/__pycache__/__init__.cpython-310.pyc,, +multiprocess/dummy/__pycache__/connection.cpython-310.pyc,, +multiprocess/dummy/connection.py,sha256=1j3Rl5_enBM-_kMO6HDmum3kPAoFE4Zs485HV5H-V6s,1598 +multiprocess/forkserver.py,sha256=hiltKfLImDYJyAcezNAgMDaQznB2LtYWgwre0QroLRg,12138 +multiprocess/heap.py,sha256=9rt5u5m5rkhJNfDWiCLpYDoWIt0LbElmx52yMqk7phQ,11626 +multiprocess/managers.py,sha256=Y5m_aCdLE4mSCuyVrwMWg5Nh9f4OdSHDlSajyOgyGao,47562 +multiprocess/pool.py,sha256=FTmtfoqkuN8Dd48f5TgdkokoxYN75xcnR78Hw-bLSng,32759 +multiprocess/popen_fork.py,sha256=Nvq5vVId24UfkOQxXhxZbcXuo8d6YMc409yRXAamTd0,2374 +multiprocess/popen_forkserver.py,sha256=SrEbV8Wv0Uu_UegkaW-cayXRdjTGXr560Yyy90pj-yE,2227 +multiprocess/popen_spawn_posix.py,sha256=l7XSWqR5UWiUSJh35qeSElLuNfUeEYwvH5HzKRnnyqg,2029 +multiprocess/popen_spawn_win32.py,sha256=A9uvlPmhO8JBzNcEU_Gmix2Q_qYJW1NXZgXPwtN5Ao0,4011 +multiprocess/process.py,sha256=GIIo2NiBsX1r_m0J1TcnbdeSulGLWHElRCuYRkkdgQ4,12083 +multiprocess/queues.py,sha256=sgXCXnIOVrPScqI3lwRD9t3IshqIBMEksLtouPH9Nzc,12139 +multiprocess/reduction.py,sha256=NQQ6KbDhmuAyaDeWaIarTZQokGPhcFda1poNnPm5uNc,9637 +multiprocess/resource_sharer.py,sha256=nEApLhMQqd8KunfaNKl3n8vdeiCGPxKrSL1Ja0nNAEk,5132 +multiprocess/resource_tracker.py,sha256=_D2iX4IWRe3dOwLoLjfCnXNbDAM4pRzA8qEMTcRfutw,9056 +multiprocess/shared_memory.py,sha256=UTAecHECIOHElP9Tg6yURCo4pKZiLy65TkASjEXeGus,18458 +multiprocess/sharedctypes.py,sha256=d-9SKRJHRlJJC331IxEoWOUXIeY9zxCbhWejXOmzGw0,6306 +multiprocess/spawn.py,sha256=cgtV66HhV_yIVzvdblc8bVdSpem16Ks0BOFu_bV5PDQ,9293 +multiprocess/synchronize.py,sha256=6q1ijwWyWLWLO8uUtaYT9MKepAYKfdzWPSEZGyJFP4s,11829 +multiprocess/tests/__init__.py,sha256=k00IjwhAUV_O1bp81895vN1gLnFzBM3iM-QTn5VrQnU,199087 +multiprocess/tests/__main__.py,sha256=RauIRQrO0HwRq_clLqbBk4gwo5Xw3-ASLuC029XaHeA,912 +multiprocess/tests/__pycache__/__init__.cpython-310.pyc,, +multiprocess/tests/__pycache__/__main__.cpython-310.pyc,, +multiprocess/tests/__pycache__/mp_fork_bomb.cpython-310.pyc,, +multiprocess/tests/__pycache__/mp_preload.cpython-310.pyc,, +multiprocess/tests/__pycache__/test_multiprocessing_fork.cpython-310.pyc,, +multiprocess/tests/__pycache__/test_multiprocessing_forkserver.cpython-310.pyc,, +multiprocess/tests/__pycache__/test_multiprocessing_main_handling.cpython-310.pyc,, +multiprocess/tests/__pycache__/test_multiprocessing_spawn.cpython-310.pyc,, +multiprocess/tests/mp_fork_bomb.py,sha256=6ADOEzh1aXHZ21aOGoBPhKcgB5sj15G9tQVgSc6GrlY,448 +multiprocess/tests/mp_preload.py,sha256=1-WvLFMaPoH-vZbpUaJvvZHFxTpA9tgmct2vblQy99M,365 +multiprocess/tests/test_multiprocessing_fork.py,sha256=ue1SQLJFxm1oc_3F2gR_WRtt39jhaj0l_Ht6Y1MBmFo,476 +multiprocess/tests/test_multiprocessing_forkserver.py,sha256=VFlUuZI60gyRbNxfHWDlgmy3zm-dPTldLWuKQZ8KObs,391 +multiprocess/tests/test_multiprocessing_main_handling.py,sha256=mtmN0K-spqZCcZVNLf_HrhP186-knpY6eaoFonL1U4U,12018 +multiprocess/tests/test_multiprocessing_spawn.py,sha256=2UAisJX58GZCbYuDFay_x97R9akhzzjIA4VuUUzITOY,276 +multiprocess/util.py,sha256=OPI3CZ34BNwwwa7AqW-eGhnuSUsu-ozy2NRU8BYKuwg,14012 diff --git a/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/WHEEL b/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..6d6b3dada5abf9570af11d88980a1299e01af0ad --- /dev/null +++ b/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.37.1) +Root-Is-Purelib: true +Tag: py310-none-any + diff --git a/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..d547cb06bfcaf32e902f6d3c00ec331470ab2f71 --- /dev/null +++ b/venv/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/top_level.txt @@ -0,0 +1,2 @@ +_multiprocess +multiprocess diff --git a/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/LICENSE b/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ac450e30899281e84e3ca524a09a57b612b76a80 --- /dev/null +++ b/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/LICENSE @@ -0,0 +1,25 @@ +BSD 2-Clause License + +Copyright (c) 2018-2020, Ewald de Wit +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. + +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/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..4665c5a37a3f2043e03d01a3a3c2c3138d38951e --- /dev/null +++ b/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/METADATA @@ -0,0 +1,87 @@ +Metadata-Version: 2.1 +Name: nest-asyncio +Version: 1.6.0 +Summary: Patch asyncio to allow nested event loops +Home-page: https://github.com/erdewit/nest_asyncio +Author: Ewald R. de Wit +Author-email: ewald.de.wit@gmail.com +License: BSD +Keywords: asyncio,nested,eventloop +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +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.12 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Framework :: AsyncIO +Requires-Python: >=3.5 +Description-Content-Type: text/x-rst +License-File: LICENSE + +|Build| |Status| |PyPiVersion| |License| |Downloads| + +Introduction +------------ + +By design asyncio `does not allow `_ +its event loop to be nested. This presents a practical problem: +When in an environment where the event loop is +already running it's impossible to run tasks and wait +for the result. Trying to do so will give the error +"``RuntimeError: This event loop is already running``". + +The issue pops up in various environments, such as web servers, +GUI applications and in Jupyter notebooks. + +This module patches asyncio to allow nested use of ``asyncio.run`` and +``loop.run_until_complete``. + +Installation +------------ + +.. code-block:: + + pip3 install nest_asyncio + +Python 3.5 or higher is required. + +Usage +----- + +.. code-block:: python + + import nest_asyncio + nest_asyncio.apply() + +Optionally the specific loop that needs patching can be given +as argument to ``apply``, otherwise the current event loop is used. +An event loop can be patched whether it is already running +or not. Only event loops from asyncio can be patched; +Loops from other projects, such as uvloop or quamash, +generally can't be patched. + + +.. |Build| image:: https://github.com/erdewit/nest_asyncio/actions/workflows/test.yml/badge.svg?branche=master + :alt: Build + :target: https://github.com/erdewit/nest_asyncio/actions + +.. |PyPiVersion| image:: https://img.shields.io/pypi/v/nest_asyncio.svg + :alt: PyPi + :target: https://pypi.python.org/pypi/nest_asyncio + +.. |Status| image:: https://img.shields.io/badge/status-stable-green.svg + :alt: + +.. |License| image:: https://img.shields.io/badge/license-BSD-blue.svg + :alt: + +.. |Downloads| image:: https://static.pepy.tech/badge/nest-asyncio/month + :alt: Number of downloads + :target: https://pepy.tech/project/nest-asyncio + diff --git a/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..d69c27f5ea889947e651cefed80253074a1755eb --- /dev/null +++ b/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/RECORD @@ -0,0 +1,8 @@ +__pycache__/nest_asyncio.cpython-310.pyc,, +nest_asyncio-1.6.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +nest_asyncio-1.6.0.dist-info/LICENSE,sha256=vs6faGVf8jt3QTJGwGUDhrh9p8NoIwPdDujj6nYw6Fs,1322 +nest_asyncio-1.6.0.dist-info/METADATA,sha256=f3uY-eGiipWX1w35FYF1oi0FRGzksyiQjZIOcpPTW9I,2812 +nest_asyncio-1.6.0.dist-info/RECORD,, +nest_asyncio-1.6.0.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92 +nest_asyncio-1.6.0.dist-info/top_level.txt,sha256=cQFBM_fPbDdhVVihWwS-29WiW17LZ3r4lSXyvwFzNzs,13 +nest_asyncio.py,sha256=KkW14bq07D5BoOTpkjlwv8dFX5uRw9Z84TR_u5wR7_o,7490 diff --git a/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1f37c02f2eb2e26b306202feaccb31e522b8b169 --- /dev/null +++ b/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.40.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..eab423b8e58043a91461f9fa867ca9e4ce85d51c --- /dev/null +++ b/venv/lib/python3.10/site-packages/nest_asyncio-1.6.0.dist-info/top_level.txt @@ -0,0 +1 @@ +nest_asyncio diff --git a/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b2ef543b933135817ff56c1e5354c1c90e29f59a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/METADATA @@ -0,0 +1,102 @@ +Metadata-Version: 2.1 +Name: ninja +Version: 1.13.0 +Summary: Ninja is a small build system with a focus on speed +Keywords: build,c++,cross-compilation,cross-platform,fortran,ninja +Author-Email: Jean-Christophe Fillion-Robin , Henry Schreiner +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: C +Classifier: Programming Language :: C++ +Classifier: Programming Language :: Fortran +Classifier: Programming Language :: Python +Classifier: Topic :: Software Development :: Build Tools +Classifier: Typing :: Typed +Project-URL: Bug Tracker, https://github.com/scikit-build/ninja-python-distributions/issues +Project-URL: Documentation, https://github.com/scikit-build/ninja-python-distributions#readme +Project-URL: Download, https://github.com/ninja-build/ninja/releases +Project-URL: Homepage, http://ninja-build.org/ +Project-URL: Mailing list, https://groups.google.com/forum/#!forum/scikit-build +Project-URL: Source Code, https://github.com/scikit-build/ninja-python-distributions +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst + +========================== +Ninja Python Distributions +========================== + +`Ninja `_ is a small build system with a focus on speed. + +The latest Ninja python wheels provide `ninja 1.13.0.gd74ef.kitware.jobserver-pipe-1 `_ executable +and `ninja_syntax.py` for generating `.ninja` files. + +.. image:: https://raw.githubusercontent.com/scikit-build/ninja-python-distributions/master/ninja-python-distributions-logo.png + +Latest Release +-------------- + +.. table:: + + +----------------------------------------------------------------------+---------------------------------------------------------------------------+ + | Versions | Downloads | + +======================================================================+===========================================================================+ + | .. image:: https://img.shields.io/pypi/v/ninja.svg | .. image:: https://img.shields.io/badge/downloads-2535k%20total-green.svg | + | :target: https://pypi.python.org/pypi/ninja | :target: https://pypi.python.org/pypi/ninja | + +----------------------------------------------------------------------+---------------------------------------------------------------------------+ + +Build Status +------------ + +.. table:: + + +---------------+-------------------------------------------------------------------------------------------------------------+ + | | GitHub Actions (Windows, macOS, Linux) | + +===============+=============================================================================================================+ + | PyPI | .. image:: https://github.com/scikit-build/ninja-python-distributions/actions/workflows/build.yml/badge.svg | + | | :target: https://github.com/scikit-build/ninja-python-distributions/actions/workflows/build.yml | + +---------------+-------------------------------------------------------------------------------------------------------------+ + +Maintainers +----------- + +* `How to update ninja version ? `_ + +* `How to make a release ? `_ + + +Miscellaneous +------------- + +* Documentation: https://github.com/scikit-build/ninja-python-distributions#readme +* Source code: https://github.com/scikit-build/ninja-python-distributions +* Mailing list: https://groups.google.com/forum/#!forum/scikit-build + +Python Version Support +---------------------- + +Versions after 1.11.1.1 no longer support Python 2-3.6, and require manylinux2010+ on linux. +Versions after 1.13 no longer support Python 3.7, and require manylinux2014+/musllinux_1_2+ on linux. + +License +------- + +This project is maintained by Jean-Christophe Fillion-Robin from Kitware Inc. +It is covered by the `Apache License, Version 2.0 `_. + +Ninja is also distributed under the `Apache License, Version 2.0 `_. +For more information about Ninja, visit https://ninja-build.org + +Logo was originally created by Libby Rose from Kitware Inc. +It is covered by `CC BY 4.0 `_. + + +History +------- + +ninja-python-distributions was initially developed in November 2016 by +Jean-Christophe Fillion-Robin to facilitate the distribution of project using +`scikit-build `_ and depending on CMake +and Ninja. diff --git a/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..d1cfa16ec57a954cbaa3d436f1bc7661f4dc9276 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/RECORD @@ -0,0 +1,18 @@ +../../../bin/ninja,sha256=aW-WKKednOUDFM-VVtfNGh0exSuP1Sgo9vnbFxlWW2c,372384 +ninja-1.13.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +ninja-1.13.0.dist-info/METADATA,sha256=jXb8Tjgs7c0ivK6qdIrzmz-nkxtyRCOW0VyxgWWdCk4,5148 +ninja-1.13.0.dist-info/RECORD,, +ninja-1.13.0.dist-info/WHEEL,sha256=zzOwTeuxXsHOT9QV_vcZk1hX9KJAUdqJD7e-2jGJxLA,150 +ninja-1.13.0.dist-info/licenses/AUTHORS.rst,sha256=bGE1t_Lhm2ir8S7n_jbLDohP84fpJ5sNCuxvDVsKNQg,142 +ninja-1.13.0.dist-info/licenses/LICENSE_Apache_20,sha256=c7p036pSC0mkAbXSFFmoUjoUbzt1GKgz7qXvqFEwv2g,10273 +ninja/__init__.py,sha256=taDHI20kpmjxOT72PiSyE42Pvz3KLXlwMfTZvvnRMKM,1533 +ninja/__main__.py,sha256=6iPLwHHAc2TMbojFVcUzERrzN0RvIsywuZc4KpJCg_4,100 +ninja/__pycache__/__init__.cpython-310.pyc,, +ninja/__pycache__/__main__.cpython-310.pyc,, +ninja/__pycache__/_version.cpython-310.pyc,, +ninja/__pycache__/ninja_syntax.cpython-310.pyc,, +ninja/_version.py,sha256=M85oP8JJdZ4yZHcp9qfGYLKUYvnN3kTyQosVcYPCPow,19 +ninja/_version.pyi,sha256=j5kbzfm6lOn8BzASXWjGIA1yT0OlHTWqlbyZ8Si_o0E,118 +ninja/ninja_syntax.py,sha256=RCXZ6Roda3lwnbhtQw6I6bJcpE98mXUZ9jocnvC4IQY,8148 +ninja/ninja_syntax.pyi,sha256=5IHH7N9CTKnMDDetFKHOsPK0SOSK_7Q4YtgzhIMNLE0,1576 +ninja/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..0a6a9a310a0d2edd46721b7b00182339807a1e25 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: scikit-build-core 0.11.5 +Root-Is-Purelib: false +Tag: py3-none-manylinux_2_17_x86_64 +Tag: py3-none-manylinux2014_x86_64 + diff --git a/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/licenses/AUTHORS.rst b/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/licenses/AUTHORS.rst new file mode 100644 index 0000000000000000000000000000000000000000..b1b06c180f71d5a97709335823145b230576f2c5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/licenses/AUTHORS.rst @@ -0,0 +1,5 @@ +======= +Credits +======= + +Please see the GitHub project page at https://github.com/scikit-build/ninja-python-distributions/graphs/contributors diff --git a/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/licenses/LICENSE_Apache_20 b/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/licenses/LICENSE_Apache_20 new file mode 100644 index 0000000000000000000000000000000000000000..37ec93a14fdcd0d6e525d97c0cfa6b314eaa98d8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ninja-1.13.0.dist-info/licenses/LICENSE_Apache_20 @@ -0,0 +1,191 @@ +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: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +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 +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. diff --git a/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/License.txt b/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/License.txt new file mode 100644 index 0000000000000000000000000000000000000000..b491c70e0aef319022ded661e111ddbd45b8a17f --- /dev/null +++ b/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.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/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/METADATA b/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..4d22d2b0a860e67abb882c6ec18c0a5dc468a39f --- /dev/null +++ b/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/METADATA @@ -0,0 +1,44 @@ +Metadata-Version: 2.2 +Name: nvidia-cufile-cu12 +Version: 1.13.1.3 +Summary: cuFile GPUDirect libraries +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 + +cuFile GPUDirect libraries diff --git a/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/RECORD b/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..db7b35b42aa60cfaaf791a1e1084a4a2d775cd23 --- /dev/null +++ b/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/RECORD @@ -0,0 +1,17 @@ +nvidia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/__pycache__/__init__.cpython-310.pyc,, +nvidia/cufile/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cufile/__pycache__/__init__.cpython-310.pyc,, +nvidia/cufile/include/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cufile/include/__pycache__/__init__.cpython-310.pyc,, +nvidia/cufile/include/cufile.h,sha256=5bNDkZZNOF_qHbDBkN04OfwF09BEcrAxxPW61HJSzX0,29530 +nvidia/cufile/lib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cufile/lib/__pycache__/__init__.cpython-310.pyc,, +nvidia/cufile/lib/libcufile.so.0,sha256=ovSFQXf2ZsGoxxm0huTLERnr_dhY66pjSctjxVSdJ-g,3209496 +nvidia/cufile/lib/libcufile_rdma.so.1,sha256=mpEoGEkKqSa07RW1ACaa4GTXKHgDFBjOYLjIu773fM8,46528 +nvidia_cufile_cu12-1.13.1.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +nvidia_cufile_cu12-1.13.1.3.dist-info/License.txt,sha256=rW9YU_ugyg0VnQ9Y1JrkmDDC-Mk_epJki5zpCttMbM0,59262 +nvidia_cufile_cu12-1.13.1.3.dist-info/METADATA,sha256=33E6JjiagFLRf-48FSFWPgYLJKA3mDs4if_1T5Bu8og,1673 +nvidia_cufile_cu12-1.13.1.3.dist-info/RECORD,, +nvidia_cufile_cu12-1.13.1.3.dist-info/WHEEL,sha256=ygM8qpYgOvrn5C-8vbfzPi-0iFPECh71lLWqkqrTjYw,144 +nvidia_cufile_cu12-1.13.1.3.dist-info/top_level.txt,sha256=fTkAtiFuL16nUrB9ytDDtpytz2t0B4NvYTnRzwAhO14,7 diff --git a/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/WHEEL b/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..287a9d7e1a3d4435e9542cc8216b8c5eaf2c0ed2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.8.0) +Root-Is-Purelib: true +Tag: py3-none-manylinux2014_x86_64 +Tag: py3-none-manylinux_2_17_x86_64 + diff --git a/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..862f7abf232cdfbb928609856247292e81c9decb --- /dev/null +++ b/venv/lib/python3.10/site-packages/nvidia_cufile_cu12-1.13.1.3.dist-info/top_level.txt @@ -0,0 +1 @@ +nvidia diff --git a/venv/lib/python3.10/site-packages/patsy/__init__.py b/venv/lib/python3.10/site-packages/patsy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..50431ec93857b82503d65d345cc3612df7aa634f --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/__init__.py @@ -0,0 +1,140 @@ +# This file is part of Patsy +# Copyright (C) 2011-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +"""patsy is a Python package for describing statistical models and building +design matrices. It is closely inspired by the 'formula' mini-language used in +R and S.""" + +from patsy.version import __version__ + +# Do this first, to make it easy to check for warnings while testing: +import os + +if os.environ.get("PATSY_FORCE_NO_WARNINGS"): + import warnings + + warnings.filterwarnings("error", module="^patsy") + warnings.filterwarnings( + "ignore", + "is_categorical_dtype is deprecated", + DeprecationWarning, + module="^patsy", + ) + del warnings +del os + +import patsy.origin + + +class PatsyError(Exception): + """This is the main error type raised by Patsy functions. + + In addition to the usual Python exception features, you can pass a second + argument to this function specifying the origin of the error; this is + included in any error message, and used to help the user locate errors + arising from malformed formulas. This second argument should be an + :class:`Origin` object, or else an arbitrary object with a ``.origin`` + attribute. (If it is neither of these things, then it will simply be + ignored.) + + For ordinary display to the user with default formatting, use + ``str(exc)``. If you want to do something cleverer, you can use the + ``.message`` and ``.origin`` attributes directly. (The latter may be + None.) + """ + + def __init__(self, message, origin=None): + Exception.__init__(self, message) + self.message = message + self.origin = None + self.set_origin(origin) + + def __str__(self): + if self.origin is None: + return self.message + else: + return "%s\n%s" % (self.message, self.origin.caretize(indent=4)) + + def set_origin(self, origin): + # This is useful to modify an exception to add origin information as + # it "passes by", without losing traceback information. (In Python 3 + # we can use the built-in exception wrapping stuff, but it will be + # some time before we can count on that...) + if self.origin is None: + if hasattr(origin, "origin"): + origin = origin.origin + if not isinstance(origin, patsy.origin.Origin): + origin = None + self.origin = origin + + +__all__ = ["PatsyError"] + +# We make a rich API available for explicit use. To see what exactly is +# exported, check each module's __all__, or import this module and look at its +# __all__. + + +def _reexport(mod): + __all__.extend(mod.__all__) + for var in mod.__all__: + globals()[var] = getattr(mod, var) + + +# This used to have less copy-paste, but explicit import statements make +# packaging tools like py2exe and py2app happier. Sigh. +import patsy.highlevel + +_reexport(patsy.highlevel) + +import patsy.build + +_reexport(patsy.build) + +import patsy.constraint + +_reexport(patsy.constraint) + +import patsy.contrasts + +_reexport(patsy.contrasts) + +import patsy.desc + +_reexport(patsy.desc) + +import patsy.design_info + +_reexport(patsy.design_info) + +import patsy.eval + +_reexport(patsy.eval) + +import patsy.origin + +_reexport(patsy.origin) + +import patsy.state + +_reexport(patsy.state) + +import patsy.user_util + +_reexport(patsy.user_util) + +import patsy.missing + +_reexport(patsy.missing) + +import patsy.splines + +_reexport(patsy.splines) + +import patsy.mgcv_cubic_splines + +_reexport(patsy.mgcv_cubic_splines) + +# XX FIXME: we aren't exporting any of the explicit parsing interface +# yet. Need to figure out how to do that. diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eeab07e86fd59c9ab9ffed889ce709614cdd716b Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/build.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/build.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe6f3f636fc99a1b6187b286155422f5b0b44c3d Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/build.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/builtins.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/builtins.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b41a7645aefec3dc4482325b565b7594a8cacc4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/builtins.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/categorical.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/categorical.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee031c69ccc933ec1c18cb1d43df473bce5dcacc Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/categorical.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/compat.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/compat.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d4212e9e160156ba2700490582085b1ee16821e Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/compat.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/compat_ordereddict.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/compat_ordereddict.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..999bc61341953398378d92dccf7d773e80c7b1de Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/compat_ordereddict.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/constraint.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/constraint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b80829b93e46880fe58436868126d45d009f16ef Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/constraint.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/contrasts.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/contrasts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b601406dda25be0f40425e16ff2160bd45eb68e Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/contrasts.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/desc.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/desc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80866abcd73854a42f1645075e4df6f0a47921c1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/desc.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/design_info.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/design_info.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5a71daffb7882c87e6bde55b833c1430acfd978 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/design_info.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/eval.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/eval.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e2adbd1f4d39e9f113cba88a1d833d16131963d Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/eval.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/highlevel.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/highlevel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e5c4f12e83ff69c099b3177bebeb345e0abd480 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/highlevel.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/infix_parser.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/infix_parser.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71fed3d69ff1b0a3420c4dc3a067983dc5881789 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/infix_parser.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/mgcv_cubic_splines.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/mgcv_cubic_splines.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b2cfc34046258fff6598587f7ff7aed9637f380 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/mgcv_cubic_splines.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/missing.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/missing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b9675c976e4ea5807bd1935fa1998532598b4dd Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/missing.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/origin.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/origin.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac889780b522f1b42dfa0e5b990bc5b01c6469a2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/origin.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/parse_formula.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/parse_formula.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95f919297447ae8061b43b72253d5ecd9e501eec Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/parse_formula.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/redundancy.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/redundancy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d98c96f8b37bc36e17dc5c5cda95c55a7e6e5e5e Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/redundancy.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/splines.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/splines.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6aa2ccfea54f6dc4a5efc9526994efb829d49769 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/splines.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/state.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f3fe656a682b966777cc67bcf2a910fd6ce83a3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/state.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/test_build.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/test_build.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b16c799a5096eaa97bfea3de3a3e78f083b91b44 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/test_build.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/test_highlevel.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/test_highlevel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba9f1b4bfd3f2afe4cf5f602d29ce67e40eac7ec Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/test_highlevel.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/test_regressions.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/test_regressions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b420d150a464ff1dfc47b72965465a59c371ec3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/test_regressions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/test_state.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/test_state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4fc402addacb587a19d925da3d61e70241566990 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/test_state.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/tokens.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/tokens.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8724ae95d9796a25725fd46f0e9db8e854bff4d0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/tokens.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/user_util.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/user_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..234ebe8e60a0196c76a515f607548f9442c6e9a9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/user_util.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/util.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65bf7cd52c267e9fcf5e9d0d690d97438021f3d6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/util.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/__pycache__/version.cpython-310.pyc b/venv/lib/python3.10/site-packages/patsy/__pycache__/version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b49835ab6f399f6ac7f57eed4f12360ec2752eb7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/patsy/__pycache__/version.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/patsy/build.py b/venv/lib/python3.10/site-packages/patsy/build.py new file mode 100644 index 0000000000000000000000000000000000000000..b6d6475c6adfd02b2d2704a4670da97cb33c33db --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/build.py @@ -0,0 +1,1028 @@ +# This file is part of Patsy +# Copyright (C) 2011-2015 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file defines the core design matrix building functions. + +# These are made available in the patsy.* namespace +__all__ = ["design_matrix_builders", "build_design_matrices"] + +import itertools + +import numpy as np +from patsy import PatsyError +from patsy.categorical import guess_categorical, CategoricalSniffer, categorical_to_int +from patsy.util import ( + atleast_2d_column_default, + have_pandas, + asarray_or_pandas, + safe_issubdtype, +) +from patsy.design_info import DesignMatrix, DesignInfo, FactorInfo, SubtermInfo +from patsy.redundancy import pick_contrasts_for_term +from patsy.eval import EvalEnvironment +from patsy.contrasts import code_contrast_matrix, Treatment +from patsy.compat import OrderedDict +from patsy.missing import NAAction + +if have_pandas: + import pandas + + +class _MockFactor(object): + def __init__(self, name="MOCKMOCK"): + self._name = name + + def eval(self, state, env): + return env["mock"] + + def name(self): + return self._name + + +def _max_allowed_dim(dim, arr, factor): + if arr.ndim > dim: + msg = ( + "factor '%s' evaluates to an %s-dimensional array; I only " + "handle arrays with dimension <= %s" % (factor.name(), arr.ndim, dim) + ) + raise PatsyError(msg, factor) + + +def test__max_allowed_dim(): + import pytest + + f = _MockFactor() + _max_allowed_dim(1, np.array(1), f) + _max_allowed_dim(1, np.array([1]), f) + pytest.raises(PatsyError, _max_allowed_dim, 1, np.array([[1]]), f) + pytest.raises(PatsyError, _max_allowed_dim, 1, np.array([[[1]]]), f) + _max_allowed_dim(2, np.array(1), f) + _max_allowed_dim(2, np.array([1]), f) + _max_allowed_dim(2, np.array([[1]]), f) + pytest.raises(PatsyError, _max_allowed_dim, 2, np.array([[[1]]]), f) + + +def _eval_factor(factor_info, data, NA_action): + factor = factor_info.factor + result = factor.eval(factor_info.state, data) + # Returns either a 2d ndarray, or a DataFrame, plus is_NA mask + if factor_info.type == "numerical": + result = atleast_2d_column_default(result, preserve_pandas=True) + _max_allowed_dim(2, result, factor) + if result.shape[1] != factor_info.num_columns: + raise PatsyError( + "when evaluating factor %s, I got %s columns " + "instead of the %s I was expecting" + % (factor.name(), factor_info.num_columns, result.shape[1]), + factor, + ) + if not safe_issubdtype(np.asarray(result).dtype, np.number): + raise PatsyError( + "when evaluating numeric factor %s, " + "I got non-numeric data of type '%s'" % (factor.name(), result.dtype), + factor, + ) + return result, NA_action.is_numerical_NA(result) + # returns either a 1d ndarray or a pandas.Series, plus is_NA mask + else: + assert factor_info.type == "categorical" + result = categorical_to_int( + result, factor_info.categories, NA_action, origin=factor_info.factor + ) + assert result.ndim == 1 + return result, np.asarray(result == -1) + + +def test__eval_factor_numerical(): + import pytest + + naa = NAAction() + f = _MockFactor() + + fi1 = FactorInfo(f, "numerical", {}, num_columns=1, categories=None) + + assert fi1.factor is f + eval123, is_NA = _eval_factor(fi1, {"mock": [1, 2, 3]}, naa) + assert eval123.shape == (3, 1) + assert np.all(eval123 == [[1], [2], [3]]) + assert is_NA.shape == (3,) + assert np.all(~is_NA) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": [[[1]]]}, naa) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": [[1, 2]]}, naa) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": ["a", "b"]}, naa) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": [True, False]}, naa) + fi2 = FactorInfo(_MockFactor(), "numerical", {}, num_columns=2, categories=None) + eval123321, is_NA = _eval_factor(fi2, {"mock": [[1, 3], [2, 2], [3, 1]]}, naa) + assert eval123321.shape == (3, 2) + assert np.all(eval123321 == [[1, 3], [2, 2], [3, 1]]) + assert is_NA.shape == (3,) + assert np.all(~is_NA) + pytest.raises(PatsyError, _eval_factor, fi2, {"mock": [1, 2, 3]}, naa) + pytest.raises(PatsyError, _eval_factor, fi2, {"mock": [[1, 2, 3]]}, naa) + + ev_nan, is_NA = _eval_factor( + fi1, {"mock": [1, 2, np.nan]}, NAAction(NA_types=["NaN"]) + ) + assert np.array_equal(is_NA, [False, False, True]) + ev_nan, is_NA = _eval_factor(fi1, {"mock": [1, 2, np.nan]}, NAAction(NA_types=[])) + assert np.array_equal(is_NA, [False, False, False]) + + if have_pandas: + eval_ser, _ = _eval_factor( + fi1, {"mock": pandas.Series([1, 2, 3], index=[10, 20, 30])}, naa + ) + assert isinstance(eval_ser, pandas.DataFrame) + assert np.array_equal(eval_ser, [[1], [2], [3]]) + assert np.array_equal(eval_ser.index, [10, 20, 30]) + eval_df1, _ = _eval_factor( + fi1, {"mock": pandas.DataFrame([[2], [1], [3]], index=[20, 10, 30])}, naa + ) + assert isinstance(eval_df1, pandas.DataFrame) + assert np.array_equal(eval_df1, [[2], [1], [3]]) + assert np.array_equal(eval_df1.index, [20, 10, 30]) + eval_df2, _ = _eval_factor( + fi2, + {"mock": pandas.DataFrame([[2, 3], [1, 4], [3, -1]], index=[20, 30, 10])}, + naa, + ) + assert isinstance(eval_df2, pandas.DataFrame) + assert np.array_equal(eval_df2, [[2, 3], [1, 4], [3, -1]]) + assert np.array_equal(eval_df2.index, [20, 30, 10]) + + pytest.raises( + PatsyError, + _eval_factor, + fi2, + {"mock": pandas.Series([1, 2, 3], index=[10, 20, 30])}, + naa, + ) + pytest.raises( + PatsyError, + _eval_factor, + fi1, + {"mock": pandas.DataFrame([[2, 3], [1, 4], [3, -1]], index=[20, 30, 10])}, + naa, + ) + + +def test__eval_factor_categorical(): + import pytest + from patsy.categorical import C + + naa = NAAction() + f = _MockFactor() + fi1 = FactorInfo(f, "categorical", {}, num_columns=None, categories=("a", "b")) + assert fi1.factor is f + cat1, _ = _eval_factor(fi1, {"mock": ["b", "a", "b"]}, naa) + assert cat1.shape == (3,) + assert np.all(cat1 == [1, 0, 1]) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": ["c"]}, naa) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": C(["a", "c"])}, naa) + pytest.raises( + PatsyError, _eval_factor, fi1, {"mock": C(["a", "b"], levels=["b", "a"])}, naa + ) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": [1, 0, 1]}, naa) + bad_cat = np.asarray(["b", "a", "a", "b"]) + bad_cat.resize((2, 2)) + pytest.raises(PatsyError, _eval_factor, fi1, {"mock": bad_cat}, naa) + + cat1_NA, is_NA = _eval_factor( + fi1, {"mock": ["a", None, "b"]}, NAAction(NA_types=["None"]) + ) + assert np.array_equal(is_NA, [False, True, False]) + assert np.array_equal(cat1_NA, [0, -1, 1]) + pytest.raises( + PatsyError, _eval_factor, fi1, {"mock": ["a", None, "b"]}, NAAction(NA_types=[]) + ) + + fi2 = FactorInfo( + _MockFactor(), "categorical", {}, num_columns=None, categories=[False, True] + ) + cat2, _ = _eval_factor(fi2, {"mock": [True, False, False, True]}, naa) + assert cat2.shape == (4,) + assert np.all(cat2 == [1, 0, 0, 1]) + + if have_pandas: + s = pandas.Series(["b", "a"], index=[10, 20]) + cat_s, _ = _eval_factor(fi1, {"mock": s}, naa) + assert isinstance(cat_s, pandas.Series) + assert np.array_equal(cat_s, [1, 0]) + assert np.array_equal(cat_s.index, [10, 20]) + sbool = pandas.Series([True, False], index=[11, 21]) + cat_sbool, _ = _eval_factor(fi2, {"mock": sbool}, naa) + assert isinstance(cat_sbool, pandas.Series) + assert np.array_equal(cat_sbool, [1, 0]) + assert np.array_equal(cat_sbool.index, [11, 21]) + + +def _column_combinations(columns_per_factor): + # For consistency with R, the left-most item iterates fastest: + iterators = [range(n) for n in reversed(columns_per_factor)] + for reversed_combo in itertools.product(*iterators): + yield reversed_combo[::-1] + + +def test__column_combinations(): + assert list(_column_combinations([2, 3])) == [ + (0, 0), + (1, 0), + (0, 1), + (1, 1), + (0, 2), + (1, 2), + ] + assert list(_column_combinations([3])) == [(0,), (1,), (2,)] + assert list(_column_combinations([])) == [()] + + +def _subterm_column_combinations(factor_infos, subterm): + columns_per_factor = [] + for factor in subterm.factors: + if factor in subterm.contrast_matrices: + columns = subterm.contrast_matrices[factor].matrix.shape[1] + else: + columns = factor_infos[factor].num_columns + columns_per_factor.append(columns) + return _column_combinations(columns_per_factor) + + +def _subterm_column_names_iter(factor_infos, subterm): + total = 0 + for i, column_idxs in enumerate( + _subterm_column_combinations(factor_infos, subterm) + ): + name_pieces = [] + for factor, column_idx in zip(subterm.factors, column_idxs): + fi = factor_infos[factor] + if fi.type == "numerical": + if fi.num_columns > 1: + name_pieces.append("%s[%s]" % (factor.name(), column_idx)) + else: + assert column_idx == 0 + name_pieces.append(factor.name()) + else: + assert fi.type == "categorical" + contrast = subterm.contrast_matrices[factor] + suffix = contrast.column_suffixes[column_idx] + name_pieces.append("%s%s" % (factor.name(), suffix)) + if not name_pieces: + yield "Intercept" + else: + yield ":".join(name_pieces) + total += 1 + assert total == subterm.num_columns + + +def _build_subterm(subterm, factor_infos, factor_values, out): + assert subterm.num_columns == out.shape[1] + out[...] = 1 + for i, column_idxs in enumerate( + _subterm_column_combinations(factor_infos, subterm) + ): + for factor, column_idx in zip(subterm.factors, column_idxs): + if factor_infos[factor].type == "categorical": + contrast = subterm.contrast_matrices[factor] + if np.any(factor_values[factor] < 0): + raise PatsyError( + "can't build a design matrix " "containing missing values", + factor, + ) + out[:, i] *= contrast.matrix[factor_values[factor], column_idx] + else: + assert factor_infos[factor].type == "numerical" + assert ( + factor_values[factor].shape[1] == factor_infos[factor].num_columns + ) + out[:, i] *= factor_values[factor][:, column_idx] + + +def test__subterm_column_names_iter_and__build_subterm(): + import pytest + from patsy.contrasts import ContrastMatrix + from patsy.categorical import C + + f1 = _MockFactor("f1") + f2 = _MockFactor("f2") + f3 = _MockFactor("f3") + contrast = ContrastMatrix(np.array([[0, 0.5], [3, 0]]), ["[c1]", "[c2]"]) + + factor_infos1 = { + f1: FactorInfo(f1, "numerical", {}, num_columns=1, categories=None), + f2: FactorInfo(f2, "categorical", {}, num_columns=None, categories=["a", "b"]), + f3: FactorInfo(f3, "numerical", {}, num_columns=1, categories=None), + } + contrast_matrices = {f2: contrast} + subterm1 = SubtermInfo([f1, f2, f3], contrast_matrices, 2) + assert list(_subterm_column_names_iter(factor_infos1, subterm1)) == [ + "f1:f2[c1]:f3", + "f1:f2[c2]:f3", + ] + + mat = np.empty((3, 2)) + _build_subterm( + subterm1, + factor_infos1, + { + f1: atleast_2d_column_default([1, 2, 3]), + f2: np.asarray([0, 0, 1]), + f3: atleast_2d_column_default([7.5, 2, -12]), + }, + mat, + ) + assert np.allclose(mat, [[0, 0.5 * 1 * 7.5], [0, 0.5 * 2 * 2], [3 * 3 * -12, 0]]) + # Check that missing categorical values blow up + pytest.raises( + PatsyError, + _build_subterm, + subterm1, + factor_infos1, + { + f1: atleast_2d_column_default([1, 2, 3]), + f2: np.asarray([0, -1, 1]), + f3: atleast_2d_column_default([7.5, 2, -12]), + }, + mat, + ) + + factor_infos2 = dict(factor_infos1) + factor_infos2[f1] = FactorInfo(f1, "numerical", {}, num_columns=2, categories=None) + subterm2 = SubtermInfo([f1, f2, f3], contrast_matrices, 4) + assert list(_subterm_column_names_iter(factor_infos2, subterm2)) == [ + "f1[0]:f2[c1]:f3", + "f1[1]:f2[c1]:f3", + "f1[0]:f2[c2]:f3", + "f1[1]:f2[c2]:f3", + ] + + mat2 = np.empty((3, 4)) + _build_subterm( + subterm2, + factor_infos2, + { + f1: atleast_2d_column_default([[1, 2], [3, 4], [5, 6]]), + f2: np.asarray([0, 0, 1]), + f3: atleast_2d_column_default([7.5, 2, -12]), + }, + mat2, + ) + assert np.allclose( + mat2, + [ + [0, 0, 0.5 * 1 * 7.5, 0.5 * 2 * 7.5], + [0, 0, 0.5 * 3 * 2, 0.5 * 4 * 2], + [3 * 5 * -12, 3 * 6 * -12, 0, 0], + ], + ) + + subterm_int = SubtermInfo([], {}, 1) + assert list(_subterm_column_names_iter({}, subterm_int)) == ["Intercept"] + + mat3 = np.empty((3, 1)) + _build_subterm(subterm_int, {}, {f1: [1, 2, 3], f2: [1, 2, 3], f3: [1, 2, 3]}, mat3) + assert np.allclose(mat3, 1) + + +def _factors_memorize(factors, data_iter_maker, eval_env): + # First, start off the memorization process by setting up each factor's + # state and finding out how many passes it will need: + factor_states = {} + passes_needed = {} + for factor in factors: + state = {} + which_pass = factor.memorize_passes_needed(state, eval_env) + factor_states[factor] = state + passes_needed[factor] = which_pass + # Now, cycle through the data until all the factors have finished + # memorizing everything: + memorize_needed = set() + for factor, passes in passes_needed.items(): + if passes > 0: + memorize_needed.add(factor) + which_pass = 0 + while memorize_needed: + for data in data_iter_maker(): + for factor in memorize_needed: + state = factor_states[factor] + factor.memorize_chunk(state, which_pass, data) + for factor in list(memorize_needed): + factor.memorize_finish(factor_states[factor], which_pass) + if which_pass == passes_needed[factor] - 1: + memorize_needed.remove(factor) + which_pass += 1 + return factor_states + + +def test__factors_memorize(): + class MockFactor(object): + def __init__(self, requested_passes, token): + self._requested_passes = requested_passes + self._token = token + self._chunk_in_pass = 0 + self._seen_passes = 0 + + def memorize_passes_needed(self, state, eval_env): + state["calls"] = [] + state["token"] = self._token + return self._requested_passes + + def memorize_chunk(self, state, which_pass, data): + state["calls"].append(("memorize_chunk", which_pass)) + assert data["chunk"] == self._chunk_in_pass + self._chunk_in_pass += 1 + + def memorize_finish(self, state, which_pass): + state["calls"].append(("memorize_finish", which_pass)) + self._chunk_in_pass = 0 + + class Data(object): + CHUNKS = 3 + + def __init__(self): + self.calls = 0 + self.data = [{"chunk": i} for i in range(self.CHUNKS)] + + def __call__(self): + self.calls += 1 + return iter(self.data) + + data = Data() + f0 = MockFactor(0, "f0") + f1 = MockFactor(1, "f1") + f2a = MockFactor(2, "f2a") + f2b = MockFactor(2, "f2b") + factor_states = _factors_memorize(set([f0, f1, f2a, f2b]), data, {}) + assert data.calls == 2 + mem_chunks0 = [("memorize_chunk", 0)] * data.CHUNKS + mem_chunks1 = [("memorize_chunk", 1)] * data.CHUNKS + expected = { + f0: { + "calls": [], + "token": "f0", + }, + f1: { + "calls": mem_chunks0 + [("memorize_finish", 0)], + "token": "f1", + }, + f2a: { + "calls": mem_chunks0 + + [("memorize_finish", 0)] + + mem_chunks1 + + [("memorize_finish", 1)], + "token": "f2a", + }, + f2b: { + "calls": mem_chunks0 + + [("memorize_finish", 0)] + + mem_chunks1 + + [("memorize_finish", 1)], + "token": "f2b", + }, + } + assert factor_states == expected + + +def _examine_factor_types(factors, factor_states, data_iter_maker, NA_action): + num_column_counts = {} + cat_sniffers = {} + examine_needed = set(factors) + for data in data_iter_maker(): + for factor in list(examine_needed): + value = factor.eval(factor_states[factor], data) + if factor in cat_sniffers or guess_categorical(value): + if factor not in cat_sniffers: + cat_sniffers[factor] = CategoricalSniffer(NA_action, factor.origin) + done = cat_sniffers[factor].sniff(value) + if done: + examine_needed.remove(factor) + else: + # Numeric + value = atleast_2d_column_default(value) + _max_allowed_dim(2, value, factor) + column_count = value.shape[1] + num_column_counts[factor] = column_count + examine_needed.remove(factor) + if not examine_needed: + break + # Pull out the levels + cat_levels_contrasts = {} + for factor, sniffer in cat_sniffers.items(): + cat_levels_contrasts[factor] = sniffer.levels_contrast() + return (num_column_counts, cat_levels_contrasts) + + +def test__examine_factor_types(): + from patsy.categorical import C + + class MockFactor(object): + def __init__(self): + # You should check this using 'is', not '==' + from patsy.origin import Origin + + self.origin = Origin("MOCK", 1, 2) + + def eval(self, state, data): + return state[data] + + def name(self): + return "MOCK MOCK" + + # This hacky class can only be iterated over once, but it keeps track of + # how far it got. + class DataIterMaker(object): + def __init__(self): + self.i = -1 + + def __call__(self): + return self + + def __iter__(self): + return self + + def next(self): + self.i += 1 + if self.i > 1: + raise StopIteration + return self.i + + __next__ = next + + num_1dim = MockFactor() + num_1col = MockFactor() + num_4col = MockFactor() + categ_1col = MockFactor() + bool_1col = MockFactor() + string_1col = MockFactor() + object_1col = MockFactor() + object_levels = (object(), object(), object()) + factor_states = { + num_1dim: ([1, 2, 3], [4, 5, 6]), + num_1col: ([[1], [2], [3]], [[4], [5], [6]]), + num_4col: (np.zeros((3, 4)), np.ones((3, 4))), + categ_1col: ( + C(["a", "b", "c"], levels=("a", "b", "c"), contrast="MOCK CONTRAST"), + C(["c", "b", "a"], levels=("a", "b", "c"), contrast="MOCK CONTRAST"), + ), + bool_1col: ([True, True, False], [False, True, True]), + # It has to read through all the data to see all the possible levels: + string_1col: (["a", "a", "a"], ["c", "b", "a"]), + object_1col: ([object_levels[0]] * 3, object_levels), + } + + it = DataIterMaker() + ( + num_column_counts, + cat_levels_contrasts, + ) = _examine_factor_types(factor_states.keys(), factor_states, it, NAAction()) + assert it.i == 2 + iterations = 0 + assert num_column_counts == {num_1dim: 1, num_1col: 1, num_4col: 4} + assert cat_levels_contrasts == { + categ_1col: (("a", "b", "c"), "MOCK CONTRAST"), + bool_1col: ((False, True), None), + string_1col: (("a", "b", "c"), None), + object_1col: (tuple(sorted(object_levels, key=id)), None), + } + + # Check that it doesn't read through all the data if that's not necessary: + it = DataIterMaker() + no_read_necessary = [num_1dim, num_1col, num_4col, categ_1col, bool_1col] + ( + num_column_counts, + cat_levels_contrasts, + ) = _examine_factor_types(no_read_necessary, factor_states, it, NAAction()) + assert it.i == 0 + assert num_column_counts == {num_1dim: 1, num_1col: 1, num_4col: 4} + assert cat_levels_contrasts == { + categ_1col: (("a", "b", "c"), "MOCK CONTRAST"), + bool_1col: ((False, True), None), + } + + # Illegal inputs: + bool_3col = MockFactor() + num_3dim = MockFactor() + # no such thing as a multi-dimensional Categorical + # categ_3dim = MockFactor() + string_3col = MockFactor() + object_3col = MockFactor() + illegal_factor_states = { + num_3dim: (np.zeros((3, 3, 3)), np.ones((3, 3, 3))), + string_3col: ([["a", "b", "c"]], [["b", "c", "a"]]), + object_3col: ([[[object()]]], [[[object()]]]), + } + import pytest + + for illegal_factor in illegal_factor_states: + it = DataIterMaker() + try: + _examine_factor_types( + [illegal_factor], illegal_factor_states, it, NAAction() + ) + except PatsyError as e: + assert e.origin is illegal_factor.origin + else: + assert False + + +def _make_subterm_infos(terms, num_column_counts, cat_levels_contrasts): + # Sort each term into a bucket based on the set of numeric factors it + # contains: + term_buckets = OrderedDict() + bucket_ordering = [] + for term in terms: + num_factors = [] + for factor in term.factors: + if factor in num_column_counts: + num_factors.append(factor) + bucket = frozenset(num_factors) + if bucket not in term_buckets: + bucket_ordering.append(bucket) + term_buckets.setdefault(bucket, []).append(term) + # Special rule: if there is a no-numerics bucket, then it always comes + # first: + if frozenset() in term_buckets: + bucket_ordering.remove(frozenset()) + bucket_ordering.insert(0, frozenset()) + term_to_subterm_infos = OrderedDict() + new_term_order = [] + # Then within each bucket, work out which sort of contrasts we want to use + # for each term to avoid redundancy + for bucket in bucket_ordering: + bucket_terms = term_buckets[bucket] + # Sort by degree of interaction + bucket_terms.sort(key=lambda t: len(t.factors)) + new_term_order += bucket_terms + used_subterms = set() + for term in bucket_terms: + subterm_infos = [] + factor_codings = pick_contrasts_for_term( + term, num_column_counts, used_subterms + ) + # Construct one SubtermInfo for each subterm + for factor_coding in factor_codings: + subterm_factors = [] + contrast_matrices = {} + subterm_columns = 1 + # In order to preserve factor ordering information, the + # coding_for_term just returns dicts, and we refer to + # the original factors to figure out which are included in + # each subterm, and in what order + for factor in term.factors: + # Numeric factors are included in every subterm + if factor in num_column_counts: + subterm_factors.append(factor) + subterm_columns *= num_column_counts[factor] + elif factor in factor_coding: + subterm_factors.append(factor) + levels, contrast = cat_levels_contrasts[factor] + # This is where the default coding is set to + # Treatment: + coded = code_contrast_matrix( + factor_coding[factor], levels, contrast, default=Treatment + ) + contrast_matrices[factor] = coded + subterm_columns *= coded.matrix.shape[1] + subterm_infos.append( + SubtermInfo(subterm_factors, contrast_matrices, subterm_columns) + ) + term_to_subterm_infos[term] = subterm_infos + assert new_term_order == list(term_to_subterm_infos) + return term_to_subterm_infos + + +def design_matrix_builders(termlists, data_iter_maker, eval_env, NA_action="drop"): + """Construct several :class:`DesignInfo` objects from termlists. + + This is one of Patsy's fundamental functions. This function and + :func:`build_design_matrices` together form the API to the core formula + interpretation machinery. + + :arg termlists: A list of termlists, where each termlist is a list of + :class:`Term` objects which together specify a design matrix. + :arg data_iter_maker: A zero-argument callable which returns an iterator + over dict-like data objects. This must be a callable rather than a + simple iterator because sufficiently complex formulas may require + multiple passes over the data (e.g. if there are nested stateful + transforms). + :arg eval_env: Either a :class:`EvalEnvironment` which will be used to + look up any variables referenced in `termlists` that cannot be + found in `data_iter_maker`, or else a depth represented as an + integer which will be passed to :meth:`EvalEnvironment.capture`. + ``eval_env=0`` means to use the context of the function calling + :func:`design_matrix_builders` for lookups. If calling this function + from a library, you probably want ``eval_env=1``, which means that + variables should be resolved in *your* caller's namespace. + :arg NA_action: An :class:`NAAction` object or string, used to determine + what values count as 'missing' for purposes of determining the levels of + categorical factors. + :returns: A list of :class:`DesignInfo` objects, one for each + termlist passed in. + + This function performs zero or more iterations over the data in order to + sniff out any necessary information about factor types, set up stateful + transforms, pick column names, etc. + + See :ref:`formulas` for details. + + .. versionadded:: 0.2.0 + The ``NA_action`` argument. + .. versionadded:: 0.4.0 + The ``eval_env`` argument. + """ + # People upgrading from versions prior to 0.4.0 could potentially have + # passed NA_action as the 3rd positional argument. Fortunately + # EvalEnvironment.capture only accepts int and EvalEnvironment objects, + # and we improved its error messages to make this clear. + eval_env = EvalEnvironment.capture(eval_env, reference=1) + if isinstance(NA_action, str): + NA_action = NAAction(NA_action) + all_factors = set() + for termlist in termlists: + for term in termlist: + all_factors.update(term.factors) + factor_states = _factors_memorize(all_factors, data_iter_maker, eval_env) + # Now all the factors have working eval methods, so we can evaluate them + # on some data to find out what type of data they return. + (num_column_counts, cat_levels_contrasts) = _examine_factor_types( + all_factors, factor_states, data_iter_maker, NA_action + ) + # Now we need the factor infos, which encapsulate the knowledge of + # how to turn any given factor into a chunk of data: + factor_infos = {} + for factor in all_factors: + if factor in num_column_counts: + fi = FactorInfo( + factor, + "numerical", + factor_states[factor], + num_columns=num_column_counts[factor], + categories=None, + ) + else: + assert factor in cat_levels_contrasts + categories = cat_levels_contrasts[factor][0] + fi = FactorInfo( + factor, + "categorical", + factor_states[factor], + num_columns=None, + categories=categories, + ) + factor_infos[factor] = fi + # And now we can construct the DesignInfo for each termlist: + design_infos = [] + for termlist in termlists: + term_to_subterm_infos = _make_subterm_infos( + termlist, num_column_counts, cat_levels_contrasts + ) + assert isinstance(term_to_subterm_infos, OrderedDict) + assert frozenset(term_to_subterm_infos) == frozenset(termlist) + this_design_factor_infos = {} + for term in termlist: + for factor in term.factors: + this_design_factor_infos[factor] = factor_infos[factor] + column_names = [] + for subterms in term_to_subterm_infos.values(): + for subterm in subterms: + for column_name in _subterm_column_names_iter(factor_infos, subterm): + column_names.append(column_name) + design_infos.append( + DesignInfo( + column_names, + factor_infos=this_design_factor_infos, + term_codings=term_to_subterm_infos, + ) + ) + return design_infos + + +def _build_design_matrix(design_info, factor_info_to_values, dtype): + factor_to_values = {} + need_reshape = False + num_rows = None + for factor_info, value in factor_info_to_values.items(): + # It's possible that the same factor appears in multiple different + # FactorInfo objects (e.g. if someone is simultaneously building two + # DesignInfo objects that started out as part of different + # formulas). Skip any factor_info that is not our expected + # factor_info. + if design_info.factor_infos.get(factor_info.factor) is not factor_info: + continue + factor_to_values[factor_info.factor] = value + if num_rows is not None: + assert num_rows == value.shape[0] + else: + num_rows = value.shape[0] + if num_rows is None: + # We have no dependence on the data -- e.g. an empty termlist, or + # only an intercept term. + num_rows = 1 + need_reshape = True + shape = (num_rows, len(design_info.column_names)) + m = DesignMatrix(np.empty(shape, dtype=dtype), design_info) + start_column = 0 + for term, subterms in design_info.term_codings.items(): + for subterm in subterms: + end_column = start_column + subterm.num_columns + m_slice = m[:, start_column:end_column] + _build_subterm(subterm, design_info.factor_infos, factor_to_values, m_slice) + start_column = end_column + assert start_column == m.shape[1] + return need_reshape, m + + +class _CheckMatch(object): + def __init__(self, name, eq_fn): + self._name = name + self._eq_fn = eq_fn + self.value = None + self._value_desc = None + self._value_origin = None + + def check(self, seen_value, desc, origin): + if self.value is None: + self.value = seen_value + self._value_desc = desc + self._value_origin = origin + else: + if not self._eq_fn(self.value, seen_value): + msg = "%s mismatch between %s and %s" % ( + self._name, + self._value_desc, + desc, + ) + if isinstance(self.value, int): + msg += " (%r versus %r)" % (self.value, seen_value) + # XX FIXME: this is a case where having discontiguous Origins + # would be useful... + raise PatsyError(msg, origin) + + +def build_design_matrices( + design_infos, data, NA_action="drop", return_type="matrix", dtype=np.dtype(float) +): + """Construct several design matrices from :class:`DesignMatrixBuilder` + objects. + + This is one of Patsy's fundamental functions. This function and + :func:`design_matrix_builders` together form the API to the core formula + interpretation machinery. + + :arg design_infos: A list of :class:`DesignInfo` objects describing the + design matrices to be built. + :arg data: A dict-like object which will be used to look up data. + :arg NA_action: What to do with rows that contain missing values. You can + ``"drop"`` them, ``"raise"`` an error, or for customization, pass an + :class:`NAAction` object. See :class:`NAAction` for details on what + values count as 'missing' (and how to alter this). + :arg return_type: Either ``"matrix"`` or ``"dataframe"``. See below. + :arg dtype: The dtype of the returned matrix. Useful if you want to use + single-precision or extended-precision. + + This function returns either a list of :class:`DesignMatrix` objects (for + ``return_type="matrix"``) or a list of :class:`pandas.DataFrame` objects + (for ``return_type="dataframe"``). In both cases, all returned design + matrices will have ``.design_info`` attributes containing the appropriate + :class:`DesignInfo` objects. + + Note that unlike :func:`design_matrix_builders`, this function takes only + a simple data argument, not any kind of iterator. That's because this + function doesn't need a global view of the data -- everything that depends + on the whole data set is already encapsulated in the ``design_infos``. If + you are incrementally processing a large data set, simply call this + function for each chunk. + + Index handling: This function always checks for indexes in the following + places: + + * If ``data`` is a :class:`pandas.DataFrame`, its ``.index`` attribute. + * If any factors evaluate to a :class:`pandas.Series` or + :class:`pandas.DataFrame`, then their ``.index`` attributes. + + If multiple indexes are found, they must be identical (same values in the + same order). If no indexes are found, then a default index is generated + using ``np.arange(num_rows)``. One way or another, we end up with a single + index for all the data. If ``return_type="dataframe"``, then this index is + used as the index of the returned DataFrame objects. Examining this index + makes it possible to determine which rows were removed due to NAs. + + Determining the number of rows in design matrices: This is not as obvious + as it might seem, because it's possible to have a formula like "~ 1" that + doesn't depend on the data (it has no factors). For this formula, it's + obvious what every row in the design matrix should look like (just the + value ``1``); but, how many rows like this should there be? To determine + the number of rows in a design matrix, this function always checks in the + following places: + + * If ``data`` is a :class:`pandas.DataFrame`, then its number of rows. + * The number of entries in any factors present in any of the design + * matrices being built. + + All these values much match. In particular, if this function is called to + generate multiple design matrices at once, then they must all have the + same number of rows. + + .. versionadded:: 0.2.0 + The ``NA_action`` argument. + + """ + if isinstance(NA_action, str): + NA_action = NAAction(NA_action) + if return_type == "dataframe" and not have_pandas: + raise PatsyError( + "pandas.DataFrame was requested, but pandas " "is not installed" + ) + if return_type not in ("matrix", "dataframe"): + raise PatsyError( + "unrecognized output type %r, should be " + "'matrix' or 'dataframe'" % (return_type,) + ) + # Evaluate factors + factor_info_to_values = {} + factor_info_to_isNAs = {} + rows_checker = _CheckMatch("Number of rows", lambda a, b: a == b) + index_checker = _CheckMatch("Index", lambda a, b: a.equals(b)) + if have_pandas and isinstance(data, pandas.DataFrame): + index_checker.check(data.index, "data.index", None) + rows_checker.check(data.shape[0], "data argument", None) + for design_info in design_infos: + # We look at evaluators rather than factors here, because it might + # happen that we have the same factor twice, but with different + # memorized state. + for factor_info in design_info.factor_infos.values(): + if factor_info not in factor_info_to_values: + value, is_NA = _eval_factor(factor_info, data, NA_action) + factor_info_to_isNAs[factor_info] = is_NA + # value may now be a Series, DataFrame, or ndarray + name = factor_info.factor.name() + origin = factor_info.factor.origin + rows_checker.check(value.shape[0], name, origin) + if have_pandas and isinstance(value, (pandas.Series, pandas.DataFrame)): + index_checker.check(value.index, name, origin) + # Strategy: we work with raw ndarrays for doing the actual + # combining; DesignMatrixBuilder objects never sees pandas + # objects. Then at the end, if a DataFrame was requested, we + # convert. So every entry in this dict is either a 2-d array + # of floats, or a 1-d array of integers (representing + # categories). + value = np.asarray(value) + factor_info_to_values[factor_info] = value + # Handle NAs + values = list(factor_info_to_values.values()) + is_NAs = list(factor_info_to_isNAs.values()) + origins = [factor_info.factor.origin for factor_info in factor_info_to_values] + pandas_index = index_checker.value + num_rows = rows_checker.value + # num_rows is None iff evaluator_to_values (and associated sets like + # 'values') are empty, i.e., we have no actual evaluators involved + # (formulas like "~ 1"). + if return_type == "dataframe" and num_rows is not None: + if pandas_index is None: + pandas_index = np.arange(num_rows) + values.append(pandas_index) + is_NAs.append(np.zeros(len(pandas_index), dtype=bool)) + origins.append(None) + new_values = NA_action.handle_NA(values, is_NAs, origins) + # NA_action may have changed the number of rows. + if new_values: + num_rows = new_values[0].shape[0] + if return_type == "dataframe" and num_rows is not None: + pandas_index = new_values.pop() + factor_info_to_values = dict(zip(factor_info_to_values, new_values)) + # Build factor values into matrices + results = [] + for design_info in design_infos: + results.append(_build_design_matrix(design_info, factor_info_to_values, dtype)) + matrices = [] + for need_reshape, matrix in results: + if need_reshape: + # There is no data-dependence, at all -- a formula like "1 ~ 1". + # In this case the builder just returns a single-row matrix, and + # we have to broadcast it vertically to the appropriate size. If + # we can figure out what that is... + assert matrix.shape[0] == 1 + if num_rows is not None: + matrix = DesignMatrix( + np.repeat(matrix, num_rows, axis=0), matrix.design_info + ) + else: + raise PatsyError( + "No design matrix has any non-trivial factors, " + "the data object is not a DataFrame. " + "I can't tell how many rows the design matrix should " + "have!" + ) + matrices.append(matrix) + if return_type == "dataframe": + assert have_pandas + for i, matrix in enumerate(matrices): + di = matrix.design_info + matrices[i] = pandas.DataFrame( + matrix, columns=di.column_names, index=pandas_index + ) + matrices[i].design_info = di + return matrices + + +# It should be possible to do just the factors -> factor_infos stuff +# alone, since that, well, makes logical sense to do. diff --git a/venv/lib/python3.10/site-packages/patsy/builtins.py b/venv/lib/python3.10/site-packages/patsy/builtins.py new file mode 100644 index 0000000000000000000000000000000000000000..fb4b319329c84ad768257e6699edf49a2f4a884a --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/builtins.py @@ -0,0 +1,107 @@ +# This file is part of Patsy +# Copyright (C) 2011-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This module sets up the namespace of stuff that is available to formulas by +# default. All formulas are interpreted in an environment that acts as if +# from patsy.builtins import * +# has been executed. (Of course, you can also execute this yourself if you +# want to use these in your regular code for some reason.) + +__all__ = ["I", "Q"] + +from patsy.contrasts import ContrastMatrix, Treatment, Poly, Sum, Helmert, Diff + +__all__ += ["ContrastMatrix", "Treatment", "Poly", "Sum", "Helmert", "Diff"] + +from patsy.categorical import C + +__all__ += ["C"] + +from patsy.state import center, standardize, scale + +__all__ += ["center", "standardize", "scale"] + +from patsy.splines import bs + +__all__ += ["bs"] + +from patsy.mgcv_cubic_splines import cr, cc, te + +__all__ += ["cr", "cc", "te"] + + +def I(x): + """The identity function. Simply returns its input unchanged. + + Since Patsy's formula parser ignores anything inside a function call + syntax, this is useful to 'hide' arithmetic operations from it. For + instance:: + + y ~ x1 + x2 + + has ``x1`` and ``x2`` as two separate predictors. But in:: + + y ~ I(x1 + x2) + + we instead have a single predictor, defined to be the sum of ``x1`` and + ``x2``.""" + return x + + +def test_I(): + assert I(1) == 1 + assert I(None) is None + + +def Q(name): + """A way to 'quote' variable names, especially ones that do not otherwise + meet Python's variable name rules. + + If ``x`` is a variable, ``Q("x")`` returns the value of ``x``. (Note that + ``Q`` takes the *string* ``"x"``, not the value of ``x`` itself.) This + works even if instead of ``x``, we have a variable name that would not + otherwise be legal in Python. + + For example, if you have a column of data named ``weight.in.kg``, then you + can't write:: + + y ~ weight.in.kg + + because Python will try to find a variable named ``weight``, that has an + attribute named ``in``, that has an attribute named ``kg``. (And worse + yet, ``in`` is a reserved word, which makes this example doubly broken.) + Instead, write:: + + y ~ Q("weight.in.kg") + + and all will be well. Note, though, that this requires embedding a Python + string inside your formula, which may require some care with your quote + marks. Some standard options include:: + + my_fit_function("y ~ Q('weight.in.kg')", ...) + my_fit_function('y ~ Q("weight.in.kg")', ...) + my_fit_function("y ~ Q(\\"weight.in.kg\\")", ...) + + Note also that ``Q`` is an ordinary Python function, which means that you + can use it in more complex expressions. For example, this is a legal + formula:: + + y ~ np.sqrt(Q("weight.in.kg")) + """ + from patsy.eval import EvalEnvironment + + env = EvalEnvironment.capture(1) + try: + return env.namespace[name] + except KeyError: + raise NameError("no data named %r found" % (name,)) + + +def test_Q(): + a = 1 + assert Q("a") == 1 + assert Q("Q") is Q + import pytest + + pytest.raises(NameError, Q, "asdfsadfdsad") diff --git a/venv/lib/python3.10/site-packages/patsy/categorical.py b/venv/lib/python3.10/site-packages/patsy/categorical.py new file mode 100644 index 0000000000000000000000000000000000000000..7d5be9c513926a9cef922824d4fca47dd7c47c4e --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/categorical.py @@ -0,0 +1,528 @@ +# This file is part of Patsy +# Copyright (C) 2011-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +__all__ = ["C", "guess_categorical", "CategoricalSniffer", "categorical_to_int"] + +# How we handle categorical data: the big picture +# ----------------------------------------------- +# +# There is no Python/NumPy standard for how to represent categorical data. +# There is no Python/NumPy standard for how to represent missing data. +# +# Together, these facts mean that when we receive some data object, we must be +# able to heuristically infer what levels it has -- and this process must be +# sensitive to the current missing data handling, because maybe 'None' is a +# level and maybe it is missing data. +# +# We don't know how missing data is represented until we get into the actual +# builder code, so anything which runs before this -- e.g., the 'C()' builtin +# -- cannot actually do *anything* meaningful with the data. +# +# Therefore, C() simply takes some data and arguments, and boxes them all up +# together into an object called (appropriately enough) _CategoricalBox. All +# the actual work of handling the various different sorts of categorical data +# (lists, string arrays, bool arrays, pandas.Categorical, etc.) happens inside +# the builder code, and we just extend this so that it also accepts +# _CategoricalBox objects as yet another categorical type. +# +# Originally this file contained a container type (called 'Categorical'), and +# the various sniffing, conversion, etc., functions were written as methods on +# that type. But we had to get rid of that type, so now this file just +# provides a set of plain old functions which are used by patsy.build to +# handle the different stages of categorical data munging. + +import numpy as np + +from patsy import PatsyError +from patsy.util import ( + SortAnythingKey, + safe_scalar_isnan, + iterable, + have_pandas, + have_pandas_categorical, + have_pandas_categorical_dtype, + safe_is_pandas_categorical, + pandas_Categorical_from_codes, + pandas_Categorical_categories, + pandas_Categorical_codes, + safe_issubdtype, + no_pickling, + assert_no_pickling, +) + +if have_pandas: + import pandas + + +# Objects of this type will always be treated as categorical, with the +# specified levels and contrast (if given). +class _CategoricalBox(object): + def __init__(self, data, contrast, levels): + self.data = data + self.contrast = contrast + self.levels = levels + + __getstate__ = no_pickling + + +def C(data, contrast=None, levels=None): + """ + Marks some `data` as being categorical, and specifies how to interpret + it. + + This is used for three reasons: + + * To explicitly mark some data as categorical. For instance, integer data + is by default treated as numerical. If you have data that is stored + using an integer type, but where you want patsy to treat each different + value as a different level of a categorical factor, you can wrap it in a + call to `C` to accomplish this. E.g., compare:: + + dmatrix("a", {"a": [1, 2, 3]}) + dmatrix("C(a)", {"a": [1, 2, 3]}) + + * To explicitly set the levels or override the default level ordering for + categorical data, e.g.:: + + dmatrix("C(a, levels=["a2", "a1"])", balanced(a=2)) + * To override the default coding scheme for categorical data. The + `contrast` argument can be any of: + + * A :class:`ContrastMatrix` object + * A simple 2d ndarray (which is treated the same as a ContrastMatrix + object except that you can't specify column names) + * An object with methods called `code_with_intercept` and + `code_without_intercept`, like the built-in contrasts + (:class:`Treatment`, :class:`Diff`, :class:`Poly`, etc.). See + :ref:`categorical-coding` for more details. + * A callable that returns one of the above. + """ + if isinstance(data, _CategoricalBox): + if contrast is None: + contrast = data.contrast + if levels is None: + levels = data.levels + data = data.data + return _CategoricalBox(data, contrast, levels) + + +def test_C(): + c1 = C("asdf") + assert isinstance(c1, _CategoricalBox) + assert c1.data == "asdf" + assert c1.levels is None + assert c1.contrast is None + c2 = C("DATA", "CONTRAST", "LEVELS") + assert c2.data == "DATA" + assert c2.contrast == "CONTRAST" + assert c2.levels == "LEVELS" + c3 = C(c2, levels="NEW LEVELS") + assert c3.data == "DATA" + assert c3.contrast == "CONTRAST" + assert c3.levels == "NEW LEVELS" + c4 = C(c2, "NEW CONTRAST") + assert c4.data == "DATA" + assert c4.contrast == "NEW CONTRAST" + assert c4.levels == "LEVELS" + + assert_no_pickling(c4) + + +def guess_categorical(data): + if safe_is_pandas_categorical(data): + return True + if isinstance(data, _CategoricalBox): + return True + data = np.asarray(data) + if safe_issubdtype(data.dtype, np.number): + return False + return True + + +def test_guess_categorical(): + if have_pandas_categorical: + c = pandas.Categorical([1, 2, 3]) + assert guess_categorical(c) + if have_pandas_categorical_dtype: + assert guess_categorical(pandas.Series(c)) + assert guess_categorical(C([1, 2, 3])) + assert guess_categorical([True, False]) + assert guess_categorical(["a", "b"]) + assert guess_categorical(["a", "b", np.nan]) + assert guess_categorical(["a", "b", None]) + assert not guess_categorical([1, 2, 3]) + assert not guess_categorical([1, 2, 3, np.nan]) + assert not guess_categorical([1.0, 2.0, 3.0]) + assert not guess_categorical([1.0, 2.0, 3.0, np.nan]) + + +def _categorical_shape_fix(data): + # helper function + # data should not be a _CategoricalBox or pandas Categorical or anything + # -- it should be an actual iterable of data, but which might have the + # wrong shape. + if hasattr(data, "ndim") and data.ndim > 1: + raise PatsyError("categorical data cannot be >1-dimensional") + # coerce scalars into 1d, which is consistent with what we do for numeric + # factors. (See statsmodels/statsmodels#1881) + if not iterable(data) or isinstance(data, (str, bytes)): + data = [data] + return data + + +class CategoricalSniffer(object): + def __init__(self, NA_action, origin=None): + self._NA_action = NA_action + self._origin = origin + self._contrast = None + self._levels = None + self._level_set = set() + + def levels_contrast(self): + if self._levels is None: + levels = list(self._level_set) + levels.sort(key=SortAnythingKey) + self._levels = levels + return tuple(self._levels), self._contrast + + def sniff(self, data): + if hasattr(data, "contrast"): + self._contrast = data.contrast + # returns a bool: are we confident that we found all the levels? + if isinstance(data, _CategoricalBox): + if data.levels is not None: + self._levels = tuple(data.levels) + return True + else: + # unbox and fall through + data = data.data + if safe_is_pandas_categorical(data): + # pandas.Categorical has its own NA detection, so don't try to + # second-guess it. + self._levels = tuple(pandas_Categorical_categories(data)) + return True + # fastpath to avoid doing an item-by-item iteration over boolean + # arrays, as requested by #44 + if hasattr(data, "dtype") and safe_issubdtype(data.dtype, np.bool_): + self._level_set = set([True, False]) + return True + + data = _categorical_shape_fix(data) + + for value in data: + if self._NA_action.is_categorical_NA(value): + continue + if value is True or value is False: + self._level_set.update([True, False]) + else: + try: + self._level_set.add(value) + except TypeError: + raise PatsyError( + "Error interpreting categorical data: " + "all items must be hashable", + self._origin, + ) + # If everything we've seen is boolean, assume that everything else + # would be too. Otherwise we need to keep looking. + return self._level_set == set([True, False]) + + __getstate__ = no_pickling + + +def test_CategoricalSniffer(): + from patsy.missing import NAAction + + def t(NA_types, datas, exp_finish_fast, exp_levels, exp_contrast=None): + sniffer = CategoricalSniffer(NAAction(NA_types=NA_types)) + for data in datas: + done = sniffer.sniff(data) + if done: + assert exp_finish_fast + break + else: + assert not exp_finish_fast + assert sniffer.levels_contrast() == (exp_levels, exp_contrast) + + if have_pandas_categorical: + # We make sure to test with both boxed and unboxed pandas objects, + # because we used to have a bug where boxed pandas objects would be + # treated as categorical, but their levels would be lost... + preps = [lambda x: x, C] + if have_pandas_categorical_dtype: + preps += [pandas.Series, lambda x: C(pandas.Series(x))] + for prep in preps: + t([], [prep(pandas.Categorical([1, 2, None]))], True, (1, 2)) + # check order preservation + t( + [], + [prep(pandas_Categorical_from_codes([1, 0], ["a", "b"]))], + True, + ("a", "b"), + ) + t( + [], + [prep(pandas_Categorical_from_codes([1, 0], ["b", "a"]))], + True, + ("b", "a"), + ) + # check that if someone sticks a .contrast field onto our object + obj = prep(pandas.Categorical(["a", "b"])) + obj.contrast = "CONTRAST" + t([], [obj], True, ("a", "b"), "CONTRAST") + + t([], [C([1, 2]), C([3, 2])], False, (1, 2, 3)) + # check order preservation + t([], [C([1, 2], levels=[1, 2, 3]), C([4, 2])], True, (1, 2, 3)) + t([], [C([1, 2], levels=[3, 2, 1]), C([4, 2])], True, (3, 2, 1)) + + # do some actual sniffing with NAs in + t(["None", "NaN"], [C([1, np.nan]), C([10, None])], False, (1, 10)) + # But 'None' can be a type if we don't make it represent NA: + sniffer = CategoricalSniffer(NAAction(NA_types=["NaN"])) + sniffer.sniff(C([1, np.nan, None])) + # The level order here is different on py2 and py3 :-( Because there's no + # consistent way to sort mixed-type values on both py2 and py3. Honestly + # people probably shouldn't use this, but I don't know how to give a + # sensible error. + levels, _ = sniffer.levels_contrast() + assert set(levels) == set([None, 1]) + + # bool special cases + t(["None", "NaN"], [C([True, np.nan, None])], True, (False, True)) + t([], [C([10, 20]), C([False]), C([30, 40])], False, (False, True, 10, 20, 30, 40)) + # exercise the fast-path + t([], [np.asarray([True, False]), ["foo"]], True, (False, True)) + + # check tuples too + t( + ["None", "NaN"], + [C([("b", 2), None, ("a", 1), np.nan, ("c", None)])], + False, + (("a", 1), ("b", 2), ("c", None)), + ) + + # contrasts + t([], [C([10, 20], contrast="FOO")], False, (10, 20), "FOO") + + # no box + t([], [[10, 30], [20]], False, (10, 20, 30)) + t([], [["b", "a"], ["a"]], False, ("a", "b")) + + # 0d + t([], ["b"], False, ("b",)) + + import pytest + + # unhashable level error: + sniffer = CategoricalSniffer(NAAction()) + pytest.raises(PatsyError, sniffer.sniff, [{}]) + + # >1d is illegal + pytest.raises(PatsyError, sniffer.sniff, np.asarray([["b"]])) + + +# returns either a 1d ndarray or a pandas.Series +def categorical_to_int(data, levels, NA_action, origin=None): + assert isinstance(levels, tuple) + # In this function, missing values are always mapped to -1 + + if safe_is_pandas_categorical(data): + data_levels_tuple = tuple(pandas_Categorical_categories(data)) + if not data_levels_tuple == levels: + raise PatsyError( + "mismatching levels: expected %r, got %r" % (levels, data_levels_tuple), + origin, + ) + # pandas.Categorical also uses -1 to indicate NA, and we don't try to + # second-guess its NA detection, so we can just pass it back. + return pandas_Categorical_codes(data) + + if isinstance(data, _CategoricalBox): + if data.levels is not None and tuple(data.levels) != levels: + raise PatsyError( + "mismatching levels: expected %r, got %r" + % (levels, tuple(data.levels)), + origin, + ) + data = data.data + + data = _categorical_shape_fix(data) + + try: + level_to_int = dict(zip(levels, range(len(levels)))) + except TypeError: + raise PatsyError( + "Error interpreting categorical data: " "all items must be hashable", origin + ) + + # fastpath to avoid doing an item-by-item iteration over boolean arrays, + # as requested by #44 + if hasattr(data, "dtype") and safe_issubdtype(data.dtype, np.bool_): + if level_to_int[False] == 0 and level_to_int[True] == 1: + return data.astype(np.int_) + out = np.empty(len(data), dtype=int) + for i, value in enumerate(data): + if NA_action.is_categorical_NA(value): + out[i] = -1 + else: + try: + out[i] = level_to_int[value] + except KeyError: + SHOW_LEVELS = 4 + level_strs = [] + if len(levels) <= SHOW_LEVELS: + level_strs += [repr(level) for level in levels] + else: + level_strs += [repr(level) for level in levels[: SHOW_LEVELS // 2]] + level_strs.append("...") + level_strs += [repr(level) for level in levels[-SHOW_LEVELS // 2 :]] + level_str = "[%s]" % (", ".join(level_strs)) + raise PatsyError( + "Error converting data to categorical: " + "observation with value %r does not match " + "any of the expected levels (expected: %s)" % (value, level_str), + origin, + ) + except TypeError: + raise PatsyError( + "Error converting data to categorical: " + "encountered unhashable value %r" % (value,), + origin, + ) + if have_pandas and isinstance(data, pandas.Series): + out = pandas.Series(out, index=data.index) + return out + + +def test_categorical_to_int(): + import pytest + from patsy.missing import NAAction + + if have_pandas: + s = pandas.Series(["a", "b", "c"], index=[10, 20, 30]) + c_pandas = categorical_to_int(s, ("a", "b", "c"), NAAction()) + assert np.all(c_pandas == [0, 1, 2]) + assert np.all(c_pandas.index == [10, 20, 30]) + # Input must be 1-dimensional + pytest.raises( + PatsyError, + categorical_to_int, + pandas.DataFrame({10: s}), + ("a", "b", "c"), + NAAction(), + ) + if have_pandas_categorical: + constructors = [pandas_Categorical_from_codes] + if have_pandas_categorical_dtype: + + def Series_from_codes(codes, categories): + c = pandas_Categorical_from_codes(codes, categories) + return pandas.Series(c) + + constructors.append(Series_from_codes) + for con in constructors: + cat = con([1, 0, -1], ("a", "b")) + conv = categorical_to_int(cat, ("a", "b"), NAAction()) + assert np.all(conv == [1, 0, -1]) + # Trust pandas NA marking + cat2 = con([1, 0, -1], ("a", "None")) + conv2 = categorical_to_int(cat, ("a", "b"), NAAction(NA_types=["None"])) + assert np.all(conv2 == [1, 0, -1]) + # But levels must match + pytest.raises( + PatsyError, + categorical_to_int, + con([1, 0], ("a", "b")), + ("a", "c"), + NAAction(), + ) + pytest.raises( + PatsyError, + categorical_to_int, + con([1, 0], ("a", "b")), + ("b", "a"), + NAAction(), + ) + + def t(data, levels, expected, NA_action=NAAction()): + got = categorical_to_int(data, levels, NA_action) + assert np.array_equal(got, expected) + + t(["a", "b", "a"], ("a", "b"), [0, 1, 0]) + t(np.asarray(["a", "b", "a"]), ("a", "b"), [0, 1, 0]) + t(np.asarray(["a", "b", "a"], dtype=object), ("a", "b"), [0, 1, 0]) + t([0, 1, 2], (1, 2, 0), [2, 0, 1]) + t(np.asarray([0, 1, 2]), (1, 2, 0), [2, 0, 1]) + t(np.asarray([0, 1, 2], dtype=float), (1, 2, 0), [2, 0, 1]) + t(np.asarray([0, 1, 2], dtype=object), (1, 2, 0), [2, 0, 1]) + t(["a", "b", "a"], ("a", "d", "z", "b"), [0, 3, 0]) + t([("a", 1), ("b", 0), ("a", 1)], (("a", 1), ("b", 0)), [0, 1, 0]) + + pytest.raises( + PatsyError, categorical_to_int, ["a", "b", "a"], ("a", "c"), NAAction() + ) + + t(C(["a", "b", "a"]), ("a", "b"), [0, 1, 0]) + t(C(["a", "b", "a"]), ("b", "a"), [1, 0, 1]) + t(C(["a", "b", "a"], levels=["b", "a"]), ("b", "a"), [1, 0, 1]) + # Mismatch between C() levels and expected levels + pytest.raises( + PatsyError, + categorical_to_int, + C(["a", "b", "a"], levels=["a", "b"]), + ("b", "a"), + NAAction(), + ) + + # ndim == 0 is okay + t("a", ("a", "b"), [0]) + t("b", ("a", "b"), [1]) + t(True, (False, True), [1]) + + # ndim == 2 is disallowed + pytest.raises( + PatsyError, + categorical_to_int, + np.asarray([["a", "b"], ["b", "a"]]), + ("a", "b"), + NAAction(), + ) + + # levels must be hashable + pytest.raises( + PatsyError, categorical_to_int, ["a", "b"], ("a", "b", {}), NAAction() + ) + pytest.raises( + PatsyError, categorical_to_int, ["a", "b", {}], ("a", "b"), NAAction() + ) + + t( + ["b", None, np.nan, "a"], + ("a", "b"), + [1, -1, -1, 0], + NAAction(NA_types=["None", "NaN"]), + ) + t( + ["b", None, np.nan, "a"], + ("a", "b", None), + [1, -1, -1, 0], + NAAction(NA_types=["None", "NaN"]), + ) + t( + ["b", None, np.nan, "a"], + ("a", "b", None), + [1, 2, -1, 0], + NAAction(NA_types=["NaN"]), + ) + + # Smoke test for the branch that formats the ellipsized list of levels in + # the error message: + pytest.raises( + PatsyError, + categorical_to_int, + ["a", "b", "q"], + ("a", "b", "c", "d", "e", "f", "g", "h"), + NAAction(), + ) diff --git a/venv/lib/python3.10/site-packages/patsy/compat.py b/venv/lib/python3.10/site-packages/patsy/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..5d56d228d7b48282f662d4c1e9ed2052aaf135da --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/compat.py @@ -0,0 +1,43 @@ +# This file is part of Patsy +# Copyright (C) 2012 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file contains compatibility code for supporting old versions of Python +# and numpy. (If we can concentrate it here, hopefully it'll make it easier to +# get rid of weird hacks once we drop support for old versions). + +##### Numpy + +import os + +# To force use of the compat code, set this env var to a non-empty value: +optional_dep_ok = not os.environ.get("PATSY_AVOID_OPTIONAL_DEPENDENCIES") + +##### Python standard library + +# The Python license requires that all derivative works contain a "brief +# summary of the changes made to Python". Both for license compliance, and for +# our own sanity, therefore, please add a note at the top of any snippets you +# add here explaining their provenance, any changes made, and what versions of +# Python require them: + +# OrderedDict is only available in Python 2.7+. compat_ordereddict.py has +# comments at the top. +import collections + +if optional_dep_ok and hasattr(collections, "OrderedDict"): + from collections import OrderedDict +else: + from patsy.compat_ordereddict import OrderedDict + +# 'raise from' available in Python 3+ +import sys +from patsy import PatsyError + + +def call_and_wrap_exc(msg, origin, f, *args, **kwargs): + try: + return f(*args, **kwargs) + except Exception as e: + new_exc = PatsyError("%s: %s: %s" % (msg, e.__class__.__name__, e), origin) + raise new_exc from e diff --git a/venv/lib/python3.10/site-packages/patsy/compat_ordereddict.py b/venv/lib/python3.10/site-packages/patsy/compat_ordereddict.py new file mode 100644 index 0000000000000000000000000000000000000000..644a6626160956a0fe610d9e6064193c84202e52 --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/compat_ordereddict.py @@ -0,0 +1,270 @@ +# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy. +# Passes Python2.7's test suite and incorporates all the latest updates. + +# Author: Raymond Hettinger +# License: MIT License +# http://code.activestate.com/recipes/576693/ revision 9, downloaded 2012-03-28 + +try: + from thread import get_ident as _get_ident +except ImportError: + # Hacked by njs -- I don't have dummy_thread and py3 doesn't have thread, + # so the import fails when nosetests3 tries to load this file. + # from dummy_thread import get_ident as _get_ident + def _get_ident(): + return "" + + +try: + from _abcoll import KeysView, ValuesView, ItemsView +except ImportError: + pass + + +class OrderedDict(dict): # pragma: no cover + "Dictionary that remembers insertion order" + + # An inherited dict maps keys to values. + # The inherited dict provides __getitem__, __len__, __contains__, and get. + # The remaining methods are order-aware. + # Big-O running times for all methods are the same as for regular dictionaries. + + # The internal self.__map dictionary maps keys to links in a doubly linked list. + # The circular doubly linked list starts and ends with a sentinel element. + # The sentinel element never gets deleted (this simplifies the algorithm). + # Each link is stored as a list of length three: [PREV, NEXT, KEY]. + + def __init__(self, *args, **kwds): + """Initialize an ordered dictionary. Signature is the same as for + regular dictionaries, but keyword arguments are not recommended + because their insertion order is arbitrary. + + """ + if len(args) > 1: + raise TypeError("expected at most 1 arguments, got %d" % len(args)) + try: + self.__root + except AttributeError: + self.__root = root = [] # sentinel node + root[:] = [root, root, None] + self.__map = {} + self.__update(*args, **kwds) + + def __setitem__(self, key, value, dict_setitem=dict.__setitem__): + "od.__setitem__(i, y) <==> od[i]=y" + # Setting a new item creates a new link which goes at the end of the linked + # list, and the inherited dictionary is updated with the new key/value pair. + if key not in self: + root = self.__root + last = root[0] + last[1] = root[0] = self.__map[key] = [last, root, key] + dict_setitem(self, key, value) + + def __delitem__(self, key, dict_delitem=dict.__delitem__): + "od.__delitem__(y) <==> del od[y]" + # Deleting an existing item uses self.__map to find the link which is + # then removed by updating the links in the predecessor and successor nodes. + dict_delitem(self, key) + link_prev, link_next, key = self.__map.pop(key) + link_prev[1] = link_next + link_next[0] = link_prev + + def __iter__(self): + "od.__iter__() <==> iter(od)" + root = self.__root + curr = root[1] + while curr is not root: + yield curr[2] + curr = curr[1] + + def __reversed__(self): + "od.__reversed__() <==> reversed(od)" + root = self.__root + curr = root[0] + while curr is not root: + yield curr[2] + curr = curr[0] + + def clear(self): + "od.clear() -> None. Remove all items from od." + try: + for node in self.__map.itervalues(): + del node[:] + root = self.__root + root[:] = [root, root, None] + self.__map.clear() + except AttributeError: + pass + dict.clear(self) + + def popitem(self, last=True): + """od.popitem() -> (k, v), return and remove a (key, value) pair. + Pairs are returned in LIFO order if last is true or FIFO order if false. + + """ + if not self: + raise KeyError("dictionary is empty") + root = self.__root + if last: + link = root[0] + link_prev = link[0] + link_prev[1] = root + root[0] = link_prev + else: + link = root[1] + link_next = link[1] + root[1] = link_next + link_next[0] = root + key = link[2] + del self.__map[key] + value = dict.pop(self, key) + return key, value + + # -- the following methods do not depend on the internal structure -- + + def keys(self): + "od.keys() -> list of keys in od" + return list(self) + + def values(self): + "od.values() -> list of values in od" + return [self[key] for key in self] + + def items(self): + "od.items() -> list of (key, value) pairs in od" + return [(key, self[key]) for key in self] + + def iterkeys(self): + "od.iterkeys() -> an iterator over the keys in od" + return iter(self) + + def itervalues(self): + "od.itervalues -> an iterator over the values in od" + for k in self: + yield self[k] + + def iteritems(self): + "od.iteritems -> an iterator over the (key, value) items in od" + for k in self: + yield (k, self[k]) + + def update(*args, **kwds): + """od.update(E, **F) -> None. Update od from dict/iterable E and F. + + If E is a dict instance, does: for k in E: od[k] = E[k] + If E has a .keys() method, does: for k in E.keys(): od[k] = E[k] + Or if E is an iterable of items, does: for k, v in E: od[k] = v + In either case, this is followed by: for k, v in F.items(): od[k] = v + + """ + if len(args) > 2: + raise TypeError( + "update() takes at most 2 positional " + "arguments (%d given)" % (len(args),) + ) + elif not args: + raise TypeError("update() takes at least 1 argument (0 given)") + self = args[0] + # Make progressively weaker assumptions about "other" + other = () + if len(args) == 2: + other = args[1] + if isinstance(other, dict): + for key in other: + self[key] = other[key] + elif hasattr(other, "keys"): + for key in other.keys(): + self[key] = other[key] + else: + for key, value in other: + self[key] = value + for key, value in kwds.items(): + self[key] = value + + __update = update # let subclasses override update without breaking __init__ + + __marker = object() + + def pop(self, key, default=__marker): + """od.pop(k[,d]) -> v, remove specified key and return the corresponding value. + If key is not found, d is returned if given, otherwise KeyError is raised. + + """ + if key in self: + result = self[key] + del self[key] + return result + if default is self.__marker: + raise KeyError(key) + return default + + def setdefault(self, key, default=None): + "od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od" + if key in self: + return self[key] + self[key] = default + return default + + def __repr__(self, _repr_running={}): + "od.__repr__() <==> repr(od)" + call_key = id(self), _get_ident() + if call_key in _repr_running: + return "..." + _repr_running[call_key] = 1 + try: + if not self: + return "%s()" % (self.__class__.__name__,) + return "%s(%r)" % (self.__class__.__name__, self.items()) + finally: + del _repr_running[call_key] + + def __reduce__(self): + "Return state information for pickling" + items = [[k, self[k]] for k in self] + inst_dict = vars(self).copy() + for k in vars(OrderedDict()): + inst_dict.pop(k, None) + if inst_dict: + return (self.__class__, (items,), inst_dict) + return self.__class__, (items,) + + def copy(self): + "od.copy() -> a shallow copy of od" + return self.__class__(self) + + @classmethod + def fromkeys(cls, iterable, value=None): + """OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S + and values equal to v (which defaults to None). + + """ + d = cls() + for key in iterable: + d[key] = value + return d + + def __eq__(self, other): + """od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive + while comparison to a regular mapping is order-insensitive. + + """ + if isinstance(other, OrderedDict): + return len(self) == len(other) and self.items() == other.items() + return dict.__eq__(self, other) + + def __ne__(self, other): + return not self == other + + # -- the following methods are only used in Python 2.7 -- + + def viewkeys(self): + "od.viewkeys() -> a set-like object providing a view on od's keys" + return KeysView(self) + + def viewvalues(self): + "od.viewvalues() -> an object providing a view on od's values" + return ValuesView(self) + + def viewitems(self): + "od.viewitems() -> a set-like object providing a view on od's items" + return ItemsView(self) diff --git a/venv/lib/python3.10/site-packages/patsy/constraint.py b/venv/lib/python3.10/site-packages/patsy/constraint.py new file mode 100644 index 0000000000000000000000000000000000000000..6147a70f57ebf321e105e0a19d26d35ce0f8e857 --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/constraint.py @@ -0,0 +1,561 @@ +# This file is part of Patsy +# Copyright (C) 2011-2012 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Interpreting linear constraints like "2*x1 + x2 = 0" + +# These are made available in the patsy.* namespace +__all__ = ["LinearConstraint"] + +import re + +try: + from collections.abc import Mapping +except ImportError: + from collections import Mapping +import numpy as np +from patsy import PatsyError +from patsy.origin import Origin +from patsy.util import ( + atleast_2d_column_default, + repr_pretty_delegate, + repr_pretty_impl, + no_pickling, + assert_no_pickling, +) +from patsy.infix_parser import Token, Operator, infix_parse +from patsy.parse_formula import _parsing_error_test + + +class LinearConstraint(object): + """A linear constraint in matrix form. + + This object represents a linear constraint of the form `Ax = b`. + + Usually you won't be constructing these by hand, but instead get them as + the return value from :meth:`DesignInfo.linear_constraint`. + + .. attribute:: coefs + + A 2-dimensional ndarray with float dtype, representing `A`. + + .. attribute:: constants + + A 2-dimensional single-column ndarray with float dtype, representing + `b`. + + .. attribute:: variable_names + + A list of strings giving the names of the variables being + constrained. (Used only for consistency checking.) + """ + + def __init__(self, variable_names, coefs, constants=None): + self.variable_names = list(variable_names) + self.coefs = np.atleast_2d(np.asarray(coefs, dtype=float)) + if constants is None: + constants = np.zeros(self.coefs.shape[0], dtype=float) + constants = np.asarray(constants, dtype=float) + self.constants = atleast_2d_column_default(constants) + if self.constants.ndim != 2 or self.constants.shape[1] != 1: + raise ValueError("constants is not (convertible to) a column matrix") + if self.coefs.ndim != 2 or self.coefs.shape[1] != len(variable_names): + raise ValueError("wrong shape for coefs") + if self.coefs.shape[0] == 0: + raise ValueError("must have at least one row in constraint matrix") + if self.coefs.shape[0] != self.constants.shape[0]: + raise ValueError("shape mismatch between coefs and constants") + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + assert not cycle + return repr_pretty_impl( + p, self, [self.variable_names, self.coefs, self.constants] + ) + + __getstate__ = no_pickling + + @classmethod + def combine(cls, constraints): + """Create a new LinearConstraint by ANDing together several existing + LinearConstraints. + + :arg constraints: An iterable of LinearConstraint objects. Their + :attr:`variable_names` attributes must all match. + :returns: A new LinearConstraint object. + """ + if not constraints: + raise ValueError("no constraints specified") + variable_names = constraints[0].variable_names + for constraint in constraints: + if constraint.variable_names != variable_names: + raise ValueError("variable names don't match") + coefs = np.vstack([c.coefs for c in constraints]) + constants = np.vstack([c.constants for c in constraints]) + return cls(variable_names, coefs, constants) + + +def test_LinearConstraint(): + try: + from numpy.testing import assert_equal + except ImportError: + from numpy.testing.utils import assert_equal + lc = LinearConstraint(["foo", "bar"], [1, 1]) + assert lc.variable_names == ["foo", "bar"] + assert_equal(lc.coefs, [[1, 1]]) + assert_equal(lc.constants, [[0]]) + + lc = LinearConstraint(["foo", "bar"], [[1, 1], [2, 3]], [10, 20]) + assert_equal(lc.coefs, [[1, 1], [2, 3]]) + assert_equal(lc.constants, [[10], [20]]) + + assert lc.coefs.dtype == np.dtype(float) + assert lc.constants.dtype == np.dtype(float) + + # statsmodels wants to be able to create degenerate constraints like this, + # see: + # https://github.com/pydata/patsy/issues/89 + # We used to forbid it, but I guess it's harmless, so why not. + lc = LinearConstraint(["a"], [[0]]) + assert_equal(lc.coefs, [[0]]) + + import pytest + + pytest.raises(ValueError, LinearConstraint, ["a"], [[1, 2]]) + pytest.raises(ValueError, LinearConstraint, ["a"], [[[1]]]) + pytest.raises(ValueError, LinearConstraint, ["a"], [[1, 2]], [3, 4]) + pytest.raises(ValueError, LinearConstraint, ["a", "b"], [[1, 2]], [3, 4]) + pytest.raises(ValueError, LinearConstraint, ["a"], [[1]], [[]]) + pytest.raises(ValueError, LinearConstraint, ["a", "b"], []) + pytest.raises(ValueError, LinearConstraint, ["a", "b"], np.zeros((0, 2))) + + assert_no_pickling(lc) + + +def test_LinearConstraint_combine(): + comb = LinearConstraint.combine( + [ + LinearConstraint(["a", "b"], [1, 0]), + LinearConstraint(["a", "b"], [0, 1], [1]), + ] + ) + assert comb.variable_names == ["a", "b"] + try: + from numpy.testing import assert_equal + except ImportError: + from numpy.testing.utils import assert_equal + assert_equal(comb.coefs, [[1, 0], [0, 1]]) + assert_equal(comb.constants, [[0], [1]]) + + import pytest + + pytest.raises(ValueError, LinearConstraint.combine, []) + pytest.raises( + ValueError, + LinearConstraint.combine, + [LinearConstraint(["a"], [1]), LinearConstraint(["b"], [1])], + ) + + +_ops = [ + Operator(",", 2, -100), + Operator("=", 2, 0), + Operator("+", 1, 100), + Operator("-", 1, 100), + Operator("+", 2, 100), + Operator("-", 2, 100), + Operator("*", 2, 200), + Operator("/", 2, 200), +] + +_atomic = ["NUMBER", "VARIABLE"] + + +def _token_maker(type, string): + def make_token(scanner, token_string): + if type == "__OP__": + actual_type = token_string + else: + actual_type = type + return Token(actual_type, Origin(string, *scanner.match.span()), token_string) + + return make_token + + +def _tokenize_constraint(string, variable_names): + lparen_re = r"\(" + rparen_re = r"\)" + op_re = "|".join([re.escape(op.token_type) for op in _ops]) + num_re = r"[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?" + whitespace_re = r"\s+" + + # Prefer long matches: + variable_names = sorted(variable_names, key=len, reverse=True) + variable_re = "|".join([re.escape(n) for n in variable_names]) + + lexicon = [ + (lparen_re, _token_maker(Token.LPAREN, string)), + (rparen_re, _token_maker(Token.RPAREN, string)), + (op_re, _token_maker("__OP__", string)), + (variable_re, _token_maker("VARIABLE", string)), + (num_re, _token_maker("NUMBER", string)), + (whitespace_re, None), + ] + + scanner = re.Scanner(lexicon) + tokens, leftover = scanner.scan(string) + if leftover: + offset = len(string) - len(leftover) + raise PatsyError( + "unrecognized token in constraint", Origin(string, offset, offset + 1) + ) + + return tokens + + +def test__tokenize_constraint(): + code = "2 * (a + b) = q" + tokens = _tokenize_constraint(code, ["a", "b", "q"]) + expecteds = [ + ("NUMBER", 0, 1, "2"), + ("*", 2, 3, "*"), + (Token.LPAREN, 4, 5, "("), + ("VARIABLE", 5, 6, "a"), + ("+", 7, 8, "+"), + ("VARIABLE", 9, 10, "b"), + (Token.RPAREN, 10, 11, ")"), + ("=", 12, 13, "="), + ("VARIABLE", 14, 15, "q"), + ] + for got, expected in zip(tokens, expecteds): + assert isinstance(got, Token) + assert got.type == expected[0] + assert got.origin == Origin(code, expected[1], expected[2]) + assert got.extra == expected[3] + + import pytest + + pytest.raises(PatsyError, _tokenize_constraint, "1 + @b", ["b"]) + # Shouldn't raise an error: + _tokenize_constraint("1 + @b", ["@b"]) + + # Check we aren't confused by names which are proper prefixes of other + # names: + for names in (["a", "aa"], ["aa", "a"]): + tokens = _tokenize_constraint("a aa a", names) + assert len(tokens) == 3 + assert [t.extra for t in tokens] == ["a", "aa", "a"] + + # Check that embedding ops and numbers inside a variable name works + tokens = _tokenize_constraint("2 * a[1,1],", ["a[1,1]"]) + assert len(tokens) == 4 + assert [t.type for t in tokens] == ["NUMBER", "*", "VARIABLE", ","] + assert [t.extra for t in tokens] == ["2", "*", "a[1,1]", ","] + + +def parse_constraint(string, variable_names): + return infix_parse(_tokenize_constraint(string, variable_names), _ops, _atomic) + + +class _EvalConstraint(object): + def __init__(self, variable_names): + self._variable_names = variable_names + self._N = len(variable_names) + + self._dispatch = { + ("VARIABLE", 0): self._eval_variable, + ("NUMBER", 0): self._eval_number, + ("+", 1): self._eval_unary_plus, + ("-", 1): self._eval_unary_minus, + ("+", 2): self._eval_binary_plus, + ("-", 2): self._eval_binary_minus, + ("*", 2): self._eval_binary_multiply, + ("/", 2): self._eval_binary_div, + ("=", 2): self._eval_binary_eq, + (",", 2): self._eval_binary_comma, + } + + # General scheme: there are 2 types we deal with: + # - linear combinations ("lincomb"s) of variables and constants, + # represented as ndarrays with size N+1 + # The last entry is the constant, so [10, 20, 30] means 10x + 20y + + # 30. + # - LinearConstraint objects + + def is_constant(self, coefs): + return np.all(coefs[: self._N] == 0) + + def _eval_variable(self, tree): + var = tree.token.extra + coefs = np.zeros((self._N + 1,), dtype=float) + coefs[self._variable_names.index(var)] = 1 + return coefs + + def _eval_number(self, tree): + coefs = np.zeros((self._N + 1,), dtype=float) + coefs[-1] = float(tree.token.extra) + return coefs + + def _eval_unary_plus(self, tree): + return self.eval(tree.args[0]) + + def _eval_unary_minus(self, tree): + return -1 * self.eval(tree.args[0]) + + def _eval_binary_plus(self, tree): + return self.eval(tree.args[0]) + self.eval(tree.args[1]) + + def _eval_binary_minus(self, tree): + return self.eval(tree.args[0]) - self.eval(tree.args[1]) + + def _eval_binary_div(self, tree): + left = self.eval(tree.args[0]) + right = self.eval(tree.args[1]) + if not self.is_constant(right): + raise PatsyError( + "Can't divide by a variable in a linear " "constraint", tree.args[1] + ) + return left / right[-1] + + def _eval_binary_multiply(self, tree): + left = self.eval(tree.args[0]) + right = self.eval(tree.args[1]) + if self.is_constant(left): + return left[-1] * right + elif self.is_constant(right): + return left * right[-1] + else: + raise PatsyError( + "Can't multiply one variable by another " "in a linear constraint", tree + ) + + def _eval_binary_eq(self, tree): + # Handle "a1 = a2 = a3", which is parsed as "(a1 = a2) = a3" + args = list(tree.args) + constraints = [] + for i, arg in enumerate(args): + if arg.type == "=": + constraints.append(self.eval(arg, constraint=True)) + # make our left argument be their right argument, or + # vice-versa + args[i] = arg.args[1 - i] + left = self.eval(args[0]) + right = self.eval(args[1]) + coefs = left[: self._N] - right[: self._N] + if np.all(coefs == 0): + raise PatsyError("no variables appear in constraint", tree) + constant = -left[-1] + right[-1] + constraint = LinearConstraint(self._variable_names, coefs, constant) + constraints.append(constraint) + return LinearConstraint.combine(constraints) + + def _eval_binary_comma(self, tree): + left = self.eval(tree.args[0], constraint=True) + right = self.eval(tree.args[1], constraint=True) + return LinearConstraint.combine([left, right]) + + def eval(self, tree, constraint=False): + key = (tree.type, len(tree.args)) + assert key in self._dispatch + val = self._dispatch[key](tree) + if constraint: + # Force it to be a constraint + if isinstance(val, LinearConstraint): + return val + else: + assert val.size == self._N + 1 + if np.all(val[: self._N] == 0): + raise PatsyError("term is constant, with no variables", tree) + return LinearConstraint(self._variable_names, val[: self._N], -val[-1]) + else: + # Force it to *not* be a constraint + if isinstance(val, LinearConstraint): + raise PatsyError("unexpected constraint object", tree) + return val + + +def linear_constraint(constraint_like, variable_names): + """This is the internal interface implementing + DesignInfo.linear_constraint, see there for docs.""" + if isinstance(constraint_like, LinearConstraint): + if constraint_like.variable_names != variable_names: + raise ValueError( + "LinearConstraint has wrong variable_names " + "(got %r, expected %r)" + % (constraint_like.variable_names, variable_names) + ) + return constraint_like + + if isinstance(constraint_like, Mapping): + # Simple conjunction-of-equality constraints can be specified as + # dicts. {"x": 1, "y": 2} -> tests x = 1 and y = 2. Keys can be + # either variable names, or variable indices. + coefs = np.zeros((len(constraint_like), len(variable_names)), dtype=float) + constants = np.zeros(len(constraint_like)) + used = set() + for i, (name, value) in enumerate(constraint_like.items()): + if name in variable_names: + idx = variable_names.index(name) + elif isinstance(name, int): + idx = name + else: + raise ValueError("unrecognized variable name/index %r" % (name,)) + if idx in used: + raise ValueError("duplicated constraint on %r" % (variable_names[idx],)) + used.add(idx) + coefs[i, idx] = 1 + constants[i] = value + return LinearConstraint(variable_names, coefs, constants) + + if isinstance(constraint_like, str): + constraint_like = [constraint_like] + # fall-through + + if ( + isinstance(constraint_like, list) + and constraint_like + and isinstance(constraint_like[0], str) + ): + constraints = [] + for code in constraint_like: + if not isinstance(code, str): + raise ValueError("expected a string, not %r" % (code,)) + tree = parse_constraint(code, variable_names) + evaluator = _EvalConstraint(variable_names) + constraints.append(evaluator.eval(tree, constraint=True)) + return LinearConstraint.combine(constraints) + + if isinstance(constraint_like, tuple): + if len(constraint_like) != 2: + raise ValueError("constraint tuple must have length 2") + coef, constants = constraint_like + return LinearConstraint(variable_names, coef, constants) + + # assume a raw ndarray + coefs = np.asarray(constraint_like, dtype=float) + return LinearConstraint(variable_names, coefs) + + +def _check_lincon(input, varnames, coefs, constants): + try: + from numpy.testing import assert_equal + except ImportError: + from numpy.testing.utils import assert_equal + got = linear_constraint(input, varnames) + print("got", got) + expected = LinearConstraint(varnames, coefs, constants) + print("expected", expected) + assert_equal(got.variable_names, expected.variable_names) + assert_equal(got.coefs, expected.coefs) + assert_equal(got.constants, expected.constants) + assert_equal(got.coefs.dtype, np.dtype(float)) + assert_equal(got.constants.dtype, np.dtype(float)) + + +def test_linear_constraint(): + import pytest + from patsy.compat import OrderedDict + + t = _check_lincon + + t(LinearConstraint(["a", "b"], [2, 3]), ["a", "b"], [[2, 3]], [[0]]) + pytest.raises( + ValueError, linear_constraint, LinearConstraint(["b", "a"], [2, 3]), ["a", "b"] + ) + + t({"a": 2}, ["a", "b"], [[1, 0]], [[2]]) + t(OrderedDict([("a", 2), ("b", 3)]), ["a", "b"], [[1, 0], [0, 1]], [[2], [3]]) + t(OrderedDict([("a", 2), ("b", 3)]), ["b", "a"], [[0, 1], [1, 0]], [[2], [3]]) + + t({0: 2}, ["a", "b"], [[1, 0]], [[2]]) + t(OrderedDict([(0, 2), (1, 3)]), ["a", "b"], [[1, 0], [0, 1]], [[2], [3]]) + + t(OrderedDict([("a", 2), (1, 3)]), ["a", "b"], [[1, 0], [0, 1]], [[2], [3]]) + + pytest.raises(ValueError, linear_constraint, {"q": 1}, ["a", "b"]) + pytest.raises(ValueError, linear_constraint, {"a": 1, 0: 2}, ["a", "b"]) + + t(np.array([2, 3]), ["a", "b"], [[2, 3]], [[0]]) + t(np.array([[2, 3], [4, 5]]), ["a", "b"], [[2, 3], [4, 5]], [[0], [0]]) + + t("a = 2", ["a", "b"], [[1, 0]], [[2]]) + t("a - 2", ["a", "b"], [[1, 0]], [[2]]) + t("a + 1 = 3", ["a", "b"], [[1, 0]], [[2]]) + t("a + b = 3", ["a", "b"], [[1, 1]], [[3]]) + t("a = 2, b = 3", ["a", "b"], [[1, 0], [0, 1]], [[2], [3]]) + t("b = 3, a = 2", ["a", "b"], [[0, 1], [1, 0]], [[3], [2]]) + + t(["a = 2", "b = 3"], ["a", "b"], [[1, 0], [0, 1]], [[2], [3]]) + + pytest.raises(ValueError, linear_constraint, ["a", {"b": 0}], ["a", "b"]) + + # Actual evaluator tests + t( + "2 * (a + b/3) + b + 2*3/4 = 1 + 2*3", + ["a", "b"], + [[2, 2.0 / 3 + 1]], + [[7 - 6.0 / 4]], + ) + t("+2 * -a", ["a", "b"], [[-2, 0]], [[0]]) + t("a - b, a + b = 2", ["a", "b"], [[1, -1], [1, 1]], [[0], [2]]) + t("a = 1, a = 2, a = 3", ["a", "b"], [[1, 0], [1, 0], [1, 0]], [[1], [2], [3]]) + t("a * 2", ["a", "b"], [[2, 0]], [[0]]) + t("-a = 1", ["a", "b"], [[-1, 0]], [[1]]) + t("(2 + a - a) * b", ["a", "b"], [[0, 2]], [[0]]) + + t("a = 1 = b", ["a", "b"], [[1, 0], [0, -1]], [[1], [-1]]) + t("a = (1 = b)", ["a", "b"], [[0, -1], [1, 0]], [[-1], [1]]) + t( + "a = 1, a = b = c", + ["a", "b", "c"], + [[1, 0, 0], [1, -1, 0], [0, 1, -1]], + [[1], [0], [0]], + ) + + # One should never do this of course, but test that it works anyway... + t("a + 1 = 2", ["a", "a + 1"], [[0, 1]], [[2]]) + + t(([10, 20], [30]), ["a", "b"], [[10, 20]], [[30]]) + t( + ([[10, 20], [20, 40]], [[30], [35]]), + ["a", "b"], + [[10, 20], [20, 40]], + [[30], [35]], + ) + # wrong-length tuple + pytest.raises(ValueError, linear_constraint, ([1, 0], [0], [0]), ["a", "b"]) + pytest.raises(ValueError, linear_constraint, ([1, 0],), ["a", "b"]) + + t([10, 20], ["a", "b"], [[10, 20]], [[0]]) + t([[10, 20], [20, 40]], ["a", "b"], [[10, 20], [20, 40]], [[0], [0]]) + t(np.array([10, 20]), ["a", "b"], [[10, 20]], [[0]]) + t(np.array([[10, 20], [20, 40]]), ["a", "b"], [[10, 20], [20, 40]], [[0], [0]]) + + # unknown object type + pytest.raises(ValueError, linear_constraint, None, ["a", "b"]) + + +_parse_eval_error_tests = [ + # Bad token + "a + oo", + # No pure constant equalities + "a = 1, <1 = 1>, b = 1", + "a = 1, ", + "a = 1, <1>, b = 2", + "a = 1, <2 * b = b + b>, c", + # No non-linearities + "a + + c", + "a + 2 / + c", + # Constraints are not numbers + "a = 1, 2 * <(a = b)>, c", + "a = 1, a + <(a = b)>, c", + "a = 1, <(a, b)> + 2, c", +] + + +def test_eval_errors(): + def doit(bad_code): + return linear_constraint(bad_code, ["a", "b", "c"]) + + _parsing_error_test(doit, _parse_eval_error_tests) diff --git a/venv/lib/python3.10/site-packages/patsy/contrasts.py b/venv/lib/python3.10/site-packages/patsy/contrasts.py new file mode 100644 index 0000000000000000000000000000000000000000..0ac9ac7532569963de42104332182f4627230e9e --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/contrasts.py @@ -0,0 +1,642 @@ +# This file is part of Patsy +# Copyright (C) 2011-2012 Nathaniel Smith +# See file LICENSE.txt for license information. + +# http://www.ats.ucla.edu/stat/r/library/contrast_coding.htm +# http://www.ats.ucla.edu/stat/sas/webbooks/reg/chapter5/sasreg5.htm + +# These are made available in the patsy.* namespace +__all__ = ["ContrastMatrix", "Treatment", "Poly", "Sum", "Helmert", "Diff"] + +import numpy as np +from patsy import PatsyError +from patsy.util import ( + repr_pretty_delegate, + repr_pretty_impl, + safe_issubdtype, + no_pickling, + assert_no_pickling, +) + + +class ContrastMatrix: + """A simple container for a matrix used for coding categorical factors. + + Attributes: + + .. attribute:: matrix + + A 2d ndarray, where each column corresponds to one column of the + resulting design matrix, and each row contains the entries for a single + categorical variable level. Usually n-by-n for a full rank coding or + n-by-(n-1) for a reduced rank coding, though other options are + possible. + + .. attribute:: column_suffixes + + A list of strings to be appended to the factor name, to produce the + final column names. E.g. for treatment coding the entries will look + like ``"[T.level1]"``. + """ + + def __init__(self, matrix, column_suffixes): + self.matrix = np.asarray(matrix) + self.column_suffixes = column_suffixes + if self.matrix.shape[1] != len(column_suffixes): + raise PatsyError("matrix and column_suffixes don't conform") + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + repr_pretty_impl(p, self, [self.matrix, self.column_suffixes]) + + __getstate__ = no_pickling + + +def test_ContrastMatrix(): + cm = ContrastMatrix([[1, 0], [0, 1]], ["a", "b"]) + assert np.array_equal(cm.matrix, np.eye(2)) + assert cm.column_suffixes == ["a", "b"] + # smoke test + repr(cm) + + import pytest + + pytest.raises(PatsyError, ContrastMatrix, [[1], [0]], ["a", "b"]) + + assert_no_pickling(cm) + + +# This always produces an object of the type that Python calls 'str' (whether +# that be a Python 2 string-of-bytes or a Python 3 string-of-unicode). It does +# *not* make any particular guarantees about being reversible or having other +# such useful programmatic properties -- it just produces something that will +# be nice for users to look at. +def _obj_to_readable_str(obj): + if isinstance(obj, str): + return obj + elif isinstance(obj, bytes): + try: + return obj.decode("utf-8") + except UnicodeDecodeError: + return repr(obj) + else: + return repr(obj) + + +def test__obj_to_readable_str(): + def t(obj, expected): + got = _obj_to_readable_str(obj) + assert type(got) is str + assert got == expected + + t(1, "1") + t(1.0, "1.0") + t("asdf", "asdf") + t("asdf", "asdf") + + # we can use "foo".encode here b/c this is python 3! + # a utf-8 encoded euro-sign comes out as a real euro sign. + t("\u20ac".encode("utf-8"), "\u20ac") + # but a iso-8859-15 euro sign can't be decoded, and we fall back on + # repr() + t("\u20ac".encode("iso-8859-15"), "b'\\xa4'") + + +def _name_levels(prefix, levels): + return ["[%s%s]" % (prefix, _obj_to_readable_str(level)) for level in levels] + + +def test__name_levels(): + assert _name_levels("a", ["b", "c"]) == ["[ab]", "[ac]"] + + +def _dummy_code(levels): + return ContrastMatrix(np.eye(len(levels)), _name_levels("", levels)) + + +def _get_level(levels, level_ref): + if level_ref in levels: + return levels.index(level_ref) + if isinstance(level_ref, int): + if level_ref < 0: + level_ref += len(levels) + if not (0 <= level_ref < len(levels)): + raise PatsyError("specified level %r is out of range" % (level_ref,)) + return level_ref + raise PatsyError("specified level %r not found" % (level_ref,)) + + +def test__get_level(): + assert _get_level(["a", "b", "c"], 0) == 0 + assert _get_level(["a", "b", "c"], -1) == 2 + assert _get_level(["a", "b", "c"], "b") == 1 + # For integer levels, we check identity before treating it as an index + assert _get_level([2, 1, 0], 0) == 2 + import pytest + + pytest.raises(PatsyError, _get_level, ["a", "b"], 2) + pytest.raises(PatsyError, _get_level, ["a", "b"], -3) + pytest.raises(PatsyError, _get_level, ["a", "b"], "c") + + +class Treatment: + """Treatment coding (also known as dummy coding). + + This is the default coding. + + For reduced-rank coding, one level is chosen as the "reference", and its + mean behaviour is represented by the intercept. Each column of the + resulting matrix represents the difference between the mean of one level + and this reference level. + + For full-rank coding, classic "dummy" coding is used, and each column of + the resulting matrix represents the mean of the corresponding level. + + The reference level defaults to the first level, or can be specified + explicitly. + + .. ipython:: python + + # reduced rank + dmatrix("C(a, Treatment)", balanced(a=3)) + # full rank + dmatrix("0 + C(a, Treatment)", balanced(a=3)) + # Setting a reference level + dmatrix("C(a, Treatment(1))", balanced(a=3)) + dmatrix("C(a, Treatment('a2'))", balanced(a=3)) + + Equivalent to R ``contr.treatment``. The R documentation suggests that + using ``Treatment(reference=-1)`` will produce contrasts that are + "equivalent to those produced by many (but not all) SAS procedures". + """ + + def __init__(self, reference=None): + self.reference = reference + + def code_with_intercept(self, levels): + return _dummy_code(levels) + + def code_without_intercept(self, levels): + if self.reference is None: + reference = 0 + else: + reference = _get_level(levels, self.reference) + eye = np.eye(len(levels) - 1) + contrasts = np.vstack( + (eye[:reference, :], np.zeros((1, len(levels) - 1)), eye[reference:, :]) + ) + names = _name_levels("T.", levels[:reference] + levels[reference + 1 :]) + return ContrastMatrix(contrasts, names) + + __getstate__ = no_pickling + + +def test_Treatment(): + t1 = Treatment() + matrix = t1.code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[a]", "[b]", "[c]"] + assert np.allclose(matrix.matrix, [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) + matrix = t1.code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[T.b]", "[T.c]"] + assert np.allclose(matrix.matrix, [[0, 0], [1, 0], [0, 1]]) + matrix = Treatment(reference=1).code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[T.a]", "[T.c]"] + assert np.allclose(matrix.matrix, [[1, 0], [0, 0], [0, 1]]) + matrix = Treatment(reference=-2).code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[T.a]", "[T.c]"] + assert np.allclose(matrix.matrix, [[1, 0], [0, 0], [0, 1]]) + matrix = Treatment(reference="b").code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[T.a]", "[T.c]"] + assert np.allclose(matrix.matrix, [[1, 0], [0, 0], [0, 1]]) + # Make sure the default is always the first level, even if there is a + # different level called 0. + matrix = Treatment().code_without_intercept([2, 1, 0]) + assert matrix.column_suffixes == ["[T.1]", "[T.0]"] + assert np.allclose(matrix.matrix, [[0, 0], [1, 0], [0, 1]]) + + +class Poly(object): + """Orthogonal polynomial contrast coding. + + This coding scheme treats the levels as ordered samples from an underlying + continuous scale, whose effect takes an unknown functional form which is + `Taylor-decomposed`__ into the sum of a linear, quadratic, etc. components. + + .. __: https://en.wikipedia.org/wiki/Taylor_series + + For reduced-rank coding, you get a linear column, a quadratic column, + etc., up to the number of levels provided. + + For full-rank coding, the same scheme is used, except that the zero-order + constant polynomial is also included. I.e., you get an intercept column + included as part of your categorical term. + + By default the levels are treated as equally spaced, but you can override + this by providing a value for the `scores` argument. + + Examples: + + .. ipython:: python + + # Reduced rank + dmatrix("C(a, Poly)", balanced(a=4)) + # Full rank + dmatrix("0 + C(a, Poly)", balanced(a=3)) + # Explicit scores + dmatrix("C(a, Poly([1, 2, 10]))", balanced(a=3)) + + This is equivalent to R's ``contr.poly``. (But note that in R, reduced + rank encodings are always dummy-coded, regardless of what contrast you + have set.) + """ + + def __init__(self, scores=None): + self.scores = scores + + def _code_either(self, intercept, levels): + n = len(levels) + scores = self.scores + if scores is None: + scores = np.arange(n) + scores = np.asarray(scores, dtype=float) + if len(scores) != n: + raise PatsyError( + "number of levels (%s) does not match" + " number of scores (%s)" % (n, len(scores)) + ) + # Strategy: just make a matrix whose columns are naive linear, + # quadratic, etc., functions of the raw scores, and then use 'qr' to + # orthogonalize each column against those to its left. + scores -= scores.mean() + raw_poly = scores.reshape((-1, 1)) ** np.arange(n).reshape((1, -1)) + q, r = np.linalg.qr(raw_poly) + q *= np.sign(np.diag(r)) + q /= np.sqrt(np.sum(q**2, axis=1)) + # The constant term is always all 1's -- we don't normalize it. + q[:, 0] = 1 + names = [".Constant", ".Linear", ".Quadratic", ".Cubic"] + names += ["^%s" % (i,) for i in range(4, n)] + names = names[:n] + if intercept: + return ContrastMatrix(q, names) + else: + # We always include the constant/intercept column as something to + # orthogonalize against, but we don't always return it: + return ContrastMatrix(q[:, 1:], names[1:]) + + def code_with_intercept(self, levels): + return self._code_either(True, levels) + + def code_without_intercept(self, levels): + return self._code_either(False, levels) + + __getstate__ = no_pickling + + +def test_Poly(): + t1 = Poly() + matrix = t1.code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == [".Constant", ".Linear", ".Quadratic"] + # Values from R 'options(digits=15); contr.poly(3)' + expected = [ + [1, -7.07106781186548e-01, 0.408248290463863], + [1, 0, -0.816496580927726], + [1, 7.07106781186547e-01, 0.408248290463863], + ] + print(matrix.matrix) + assert np.allclose(matrix.matrix, expected) + matrix = t1.code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == [".Linear", ".Quadratic"] + # Values from R 'options(digits=15); contr.poly(3)' + print(matrix.matrix) + assert np.allclose( + matrix.matrix, + [ + [-7.07106781186548e-01, 0.408248290463863], + [0, -0.816496580927726], + [7.07106781186547e-01, 0.408248290463863], + ], + ) + + matrix = Poly(scores=[0, 10, 11]).code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == [".Constant", ".Linear", ".Quadratic"] + # Values from R 'options(digits=15); contr.poly(3, scores=c(0, 10, 11))' + print(matrix.matrix) + assert np.allclose( + matrix.matrix, + [ + [1, -0.813733471206735, 0.0671156055214024], + [1, 0.348742916231458, -0.7382716607354268], + [1, 0.464990554975277, 0.6711560552140243], + ], + ) + + # we had an integer/float handling bug for score vectors whose mean was + # non-integer, so check one of those: + matrix = Poly(scores=[0, 10, 12]).code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == [".Constant", ".Linear", ".Quadratic"] + # Values from R 'options(digits=15); contr.poly(3, scores=c(0, 10, 12))' + print(matrix.matrix) + assert np.allclose( + matrix.matrix, + [ + [1, -0.806559132617443, 0.127000127000191], + [1, 0.293294230042706, -0.762000762001143], + [1, 0.513264902574736, 0.635000635000952], + ], + ) + + import pytest + + pytest.raises(PatsyError, Poly(scores=[0, 1]).code_with_intercept, ["a", "b", "c"]) + + matrix = t1.code_with_intercept(list(range(6))) + assert matrix.column_suffixes == [ + ".Constant", + ".Linear", + ".Quadratic", + ".Cubic", + "^4", + "^5", + ] + + +class Sum(object): + """Deviation coding (also known as sum-to-zero coding). + + Compares the mean of each level to the mean-of-means. (In a balanced + design, compares the mean of each level to the overall mean.) + + For full-rank coding, a standard intercept term is added. + + One level must be omitted to avoid redundancy; by default this is the last + level, but this can be adjusted via the `omit` argument. + + .. warning:: There are multiple definitions of 'deviation coding' in + use. Make sure this is the one you expect before trying to interpret + your results! + + Examples: + + .. ipython:: python + + # Reduced rank + dmatrix("C(a, Sum)", balanced(a=4)) + # Full rank + dmatrix("0 + C(a, Sum)", balanced(a=4)) + # Omit a different level + dmatrix("C(a, Sum(1))", balanced(a=3)) + dmatrix("C(a, Sum('a1'))", balanced(a=3)) + + This is equivalent to R's `contr.sum`. + """ + + def __init__(self, omit=None): + self.omit = omit + + def _omit_i(self, levels): + if self.omit is None: + # We assume below that this is positive + return len(levels) - 1 + else: + return _get_level(levels, self.omit) + + def _sum_contrast(self, levels): + n = len(levels) + omit_i = self._omit_i(levels) + eye = np.eye(n - 1) + out = np.empty((n, n - 1)) + out[:omit_i, :] = eye[:omit_i, :] + out[omit_i, :] = -1 + out[omit_i + 1 :, :] = eye[omit_i:, :] + return out + + def code_with_intercept(self, levels): + contrast = self.code_without_intercept(levels) + matrix = np.column_stack((np.ones(len(levels)), contrast.matrix)) + column_suffixes = ["[mean]"] + contrast.column_suffixes + return ContrastMatrix(matrix, column_suffixes) + + def code_without_intercept(self, levels): + matrix = self._sum_contrast(levels) + omit_i = self._omit_i(levels) + included_levels = levels[:omit_i] + levels[omit_i + 1 :] + return ContrastMatrix(matrix, _name_levels("S.", included_levels)) + + __getstate__ = no_pickling + + +def test_Sum(): + t1 = Sum() + matrix = t1.code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[mean]", "[S.a]", "[S.b]"] + assert np.allclose(matrix.matrix, [[1, 1, 0], [1, 0, 1], [1, -1, -1]]) + matrix = t1.code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[S.a]", "[S.b]"] + assert np.allclose(matrix.matrix, [[1, 0], [0, 1], [-1, -1]]) + # Check that it's not thrown off by negative integer term names + matrix = t1.code_without_intercept([-1, -2, -3]) + assert matrix.column_suffixes == ["[S.-1]", "[S.-2]"] + assert np.allclose(matrix.matrix, [[1, 0], [0, 1], [-1, -1]]) + t2 = Sum(omit=1) + matrix = t2.code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[mean]", "[S.a]", "[S.c]"] + assert np.allclose(matrix.matrix, [[1, 1, 0], [1, -1, -1], [1, 0, 1]]) + matrix = t2.code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[S.a]", "[S.c]"] + assert np.allclose(matrix.matrix, [[1, 0], [-1, -1], [0, 1]]) + matrix = t2.code_without_intercept([1, 0, 2]) + assert matrix.column_suffixes == ["[S.0]", "[S.2]"] + assert np.allclose(matrix.matrix, [[-1, -1], [1, 0], [0, 1]]) + t3 = Sum(omit=-3) + matrix = t3.code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[mean]", "[S.b]", "[S.c]"] + assert np.allclose(matrix.matrix, [[1, -1, -1], [1, 1, 0], [1, 0, 1]]) + matrix = t3.code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[S.b]", "[S.c]"] + assert np.allclose(matrix.matrix, [[-1, -1], [1, 0], [0, 1]]) + t4 = Sum(omit="a") + matrix = t3.code_with_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[mean]", "[S.b]", "[S.c]"] + assert np.allclose(matrix.matrix, [[1, -1, -1], [1, 1, 0], [1, 0, 1]]) + matrix = t3.code_without_intercept(["a", "b", "c"]) + assert matrix.column_suffixes == ["[S.b]", "[S.c]"] + assert np.allclose(matrix.matrix, [[-1, -1], [1, 0], [0, 1]]) + + +class Helmert(object): + """Helmert contrasts. + + Compares the second level with the first, the third with the average of + the first two, and so on. + + For full-rank coding, a standard intercept term is added. + + .. warning:: There are multiple definitions of 'Helmert coding' in + use. Make sure this is the one you expect before trying to interpret + your results! + + Examples: + + .. ipython:: python + + # Reduced rank + dmatrix("C(a, Helmert)", balanced(a=4)) + # Full rank + dmatrix("0 + C(a, Helmert)", balanced(a=4)) + + This is equivalent to R's `contr.helmert`. + """ + + def _helmert_contrast(self, levels): + n = len(levels) + # http://www.ats.ucla.edu/stat/sas/webbooks/reg/chapter5/sasreg5.htm#HELMERT + # contr = np.eye(n - 1) + # int_range = np.arange(n - 1., 1, -1) + # denom = np.repeat(int_range, np.arange(n - 2, 0, -1)) + # contr[np.tril_indices(n - 1, -1)] = -1. / denom + + # http://www.ats.ucla.edu/stat/r/library/contrast_coding.htm#HELMERT + # contr = np.zeros((n - 1., n - 1)) + # int_range = np.arange(n, 1, -1) + # denom = np.repeat(int_range[:-1], np.arange(n - 2, 0, -1)) + # contr[np.diag_indices(n - 1)] = (int_range - 1.) / int_range + # contr[np.tril_indices(n - 1, -1)] = -1. / denom + # contr = np.vstack((contr, -1./int_range)) + + # r-like + contr = np.zeros((n, n - 1)) + contr[1:][np.diag_indices(n - 1)] = np.arange(1, n) + contr[np.triu_indices(n - 1)] = -1 + return contr + + def code_with_intercept(self, levels): + contrast = np.column_stack( + (np.ones(len(levels)), self._helmert_contrast(levels)) + ) + column_suffixes = _name_levels("H.", ["intercept"] + list(levels[1:])) + return ContrastMatrix(contrast, column_suffixes) + + def code_without_intercept(self, levels): + contrast = self._helmert_contrast(levels) + return ContrastMatrix(contrast, _name_levels("H.", levels[1:])) + + __getstate__ = no_pickling + + +def test_Helmert(): + t1 = Helmert() + for levels in (["a", "b", "c", "d"], ("a", "b", "c", "d")): + matrix = t1.code_with_intercept(levels) + assert matrix.column_suffixes == ["[H.intercept]", "[H.b]", "[H.c]", "[H.d]"] + assert np.allclose( + matrix.matrix, + [[1, -1, -1, -1], [1, 1, -1, -1], [1, 0, 2, -1], [1, 0, 0, 3]], + ) + matrix = t1.code_without_intercept(levels) + assert matrix.column_suffixes == ["[H.b]", "[H.c]", "[H.d]"] + assert np.allclose( + matrix.matrix, [[-1, -1, -1], [1, -1, -1], [0, 2, -1], [0, 0, 3]] + ) + + +class Diff(object): + """Backward difference coding. + + This coding scheme is useful for ordered factors, and compares the mean of + each level with the preceding level. So you get the second level minus the + first, the third level minus the second, etc. + + For full-rank coding, a standard intercept term is added (which gives the + mean value for the first level). + + Examples: + + .. ipython:: python + + # Reduced rank + dmatrix("C(a, Diff)", balanced(a=3)) + # Full rank + dmatrix("0 + C(a, Diff)", balanced(a=3)) + """ + + def _diff_contrast(self, levels): + nlevels = len(levels) + contr = np.zeros((nlevels, nlevels - 1)) + int_range = np.arange(1, nlevels) + upper_int = np.repeat(int_range, int_range) + row_i, col_i = np.triu_indices(nlevels - 1) + # we want to iterate down the columns not across the rows + # it would be nice if the index functions had a row/col order arg + col_order = np.argsort(col_i) + contr[row_i[col_order], col_i[col_order]] = (upper_int - nlevels) / float( + nlevels + ) + lower_int = np.repeat(int_range, int_range[::-1]) + row_i, col_i = np.tril_indices(nlevels - 1) + # we want to iterate down the columns not across the rows + col_order = np.argsort(col_i) + contr[row_i[col_order] + 1, col_i[col_order]] = lower_int / float(nlevels) + return contr + + def code_with_intercept(self, levels): + contrast = np.column_stack((np.ones(len(levels)), self._diff_contrast(levels))) + return ContrastMatrix(contrast, _name_levels("D.", levels)) + + def code_without_intercept(self, levels): + contrast = self._diff_contrast(levels) + return ContrastMatrix(contrast, _name_levels("D.", levels[:-1])) + + __getstate__ = no_pickling + + +def test_diff(): + t1 = Diff() + matrix = t1.code_with_intercept(["a", "b", "c", "d"]) + assert matrix.column_suffixes == ["[D.a]", "[D.b]", "[D.c]", "[D.d]"] + assert np.allclose( + matrix.matrix, + [ + [1, -3 / 4.0, -1 / 2.0, -1 / 4.0], + [1, 1 / 4.0, -1 / 2.0, -1 / 4.0], + [1, 1 / 4.0, 1.0 / 2, -1 / 4.0], + [1, 1 / 4.0, 1 / 2.0, 3 / 4.0], + ], + ) + matrix = t1.code_without_intercept(["a", "b", "c", "d"]) + assert matrix.column_suffixes == ["[D.a]", "[D.b]", "[D.c]"] + assert np.allclose( + matrix.matrix, + [ + [-3 / 4.0, -1 / 2.0, -1 / 4.0], + [1 / 4.0, -1 / 2.0, -1 / 4.0], + [1 / 4.0, 2.0 / 4, -1 / 4.0], + [1 / 4.0, 1 / 2.0, 3 / 4.0], + ], + ) + + +# contrast can be: +# -- a ContrastMatrix +# -- a simple np.ndarray +# -- an object with code_with_intercept and code_without_intercept methods +# -- a function returning one of the above +# -- None, in which case the above rules are applied to 'default' +# This function always returns a ContrastMatrix. +def code_contrast_matrix(intercept, levels, contrast, default=None): + if contrast is None: + contrast = default + if callable(contrast): + contrast = contrast() + if isinstance(contrast, ContrastMatrix): + return contrast + as_array = np.asarray(contrast) + if safe_issubdtype(as_array.dtype, np.number): + return ContrastMatrix( + as_array, _name_levels("custom", range(as_array.shape[1])) + ) + if intercept: + return contrast.code_with_intercept(levels) + else: + return contrast.code_without_intercept(levels) diff --git a/venv/lib/python3.10/site-packages/patsy/desc.py b/venv/lib/python3.10/site-packages/patsy/desc.py new file mode 100644 index 0000000000000000000000000000000000000000..6f9d1afbb289aba8ed556584be2e70b76a69e116 --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/desc.py @@ -0,0 +1,668 @@ +# This file is part of Patsy +# Copyright (C) 2011-2012 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file defines the ModelDesc class, which describes a model at a high +# level, as a list of interactions of factors. It also has the code to convert +# a formula parse tree (from patsy.parse_formula) into a ModelDesc. + +from patsy import PatsyError +from patsy.parse_formula import ParseNode, Token, parse_formula +from patsy.eval import EvalEnvironment, EvalFactor +from patsy.util import uniqueify_list +from patsy.util import repr_pretty_delegate, repr_pretty_impl +from patsy.util import no_pickling, assert_no_pickling + +# These are made available in the patsy.* namespace +__all__ = ["Term", "ModelDesc", "INTERCEPT"] + + +# One might think it would make more sense for 'factors' to be a set, rather +# than a tuple-with-guaranteed-unique-entries-that-compares-like-a-set. The +# reason we do it this way is that it preserves the order that the user typed +# and is expecting, which then ends up producing nicer names in our final +# output, nicer column ordering, etc. (A similar comment applies to the +# ordering of terms in ModelDesc objects as a whole.) +class Term(object): + """The interaction between a collection of factor objects. + + This is one of the basic types used in representing formulas, and + corresponds to an expression like ``"a:b:c"`` in a formula string. + For details, see :ref:`formulas` and :ref:`expert-model-specification`. + + Terms are hashable and compare by value. + + Attributes: + + .. attribute:: factors + + A tuple of factor objects. + """ + + def __init__(self, factors): + self.factors = tuple(uniqueify_list(factors)) + + def __eq__(self, other): + return isinstance(other, Term) and frozenset(other.factors) == frozenset( + self.factors + ) + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash((Term, frozenset(self.factors))) + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + assert not cycle + repr_pretty_impl(p, self, [list(self.factors)]) + + def name(self): + """Return a human-readable name for this term.""" + if self.factors: + return ":".join([f.name() for f in self.factors]) + else: + return "Intercept" + + __getstate__ = no_pickling + + +INTERCEPT = Term([]) + + +class _MockFactor(object): + def __init__(self, name): + self._name = name + + def name(self): + return self._name + + +def test_Term(): + assert Term([1, 2, 1]).factors == (1, 2) + assert Term([1, 2]) == Term([2, 1]) + assert hash(Term([1, 2])) == hash(Term([2, 1])) + f1 = _MockFactor("a") + f2 = _MockFactor("b") + assert Term([f1, f2]).name() == "a:b" + assert Term([f2, f1]).name() == "b:a" + assert Term([]).name() == "Intercept" + + assert_no_pickling(Term([])) + + +class ModelDesc(object): + """A simple container representing the termlists parsed from a formula. + + This is a simple container object which has exactly the same + representational power as a formula string, but is a Python object + instead. You can construct one by hand, and pass it to functions like + :func:`dmatrix` or :func:`incr_dbuilder` that are expecting a formula + string, but without having to do any messy string manipulation. For + details see :ref:`expert-model-specification`. + + Attributes: + + .. attribute:: lhs_termlist + rhs_termlist + + Two termlists representing the left- and right-hand sides of a + formula, suitable for passing to :func:`design_matrix_builders`. + """ + + def __init__(self, lhs_termlist, rhs_termlist): + self.lhs_termlist = uniqueify_list(lhs_termlist) + self.rhs_termlist = uniqueify_list(rhs_termlist) + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + assert not cycle + return repr_pretty_impl( + p, + self, + [], + [("lhs_termlist", self.lhs_termlist), ("rhs_termlist", self.rhs_termlist)], + ) + + def describe(self): + """Returns a human-readable representation of this :class:`ModelDesc` + in pseudo-formula notation. + + .. warning:: There is no guarantee that the strings returned by this + function can be parsed as formulas. They are best-effort + descriptions intended for human users. However, if this ModelDesc + was created by parsing a formula, then it should work in + practice. If you *really* have to. + """ + + def term_code(term): + if term == INTERCEPT: + return "1" + else: + return term.name() + + result = " + ".join([term_code(term) for term in self.lhs_termlist]) + if result: + result += " ~ " + else: + result += "~ " + if self.rhs_termlist == [INTERCEPT]: + result += term_code(INTERCEPT) + else: + term_names = [] + if INTERCEPT not in self.rhs_termlist: + term_names.append("0") + term_names += [ + term_code(term) for term in self.rhs_termlist if term != INTERCEPT + ] + result += " + ".join(term_names) + return result + + @classmethod + def from_formula(cls, tree_or_string): + """Construct a :class:`ModelDesc` from a formula string. + + :arg tree_or_string: A formula string. (Or an unevaluated formula + parse tree, but the API for generating those isn't public yet. Shh, + it can be our secret.) + :returns: A new :class:`ModelDesc`. + """ + if isinstance(tree_or_string, ParseNode): + tree = tree_or_string + else: + tree = parse_formula(tree_or_string) + value = Evaluator().eval(tree, require_evalexpr=False) + assert isinstance(value, cls) + return value + + __getstate__ = no_pickling + + +def test_ModelDesc(): + f1 = _MockFactor("a") + f2 = _MockFactor("b") + m = ModelDesc([INTERCEPT, Term([f1])], [Term([f1]), Term([f1, f2])]) + assert m.lhs_termlist == [INTERCEPT, Term([f1])] + assert m.rhs_termlist == [Term([f1]), Term([f1, f2])] + print(m.describe()) + assert m.describe() == "1 + a ~ 0 + a + a:b" + + assert_no_pickling(m) + + assert ModelDesc([], []).describe() == "~ 0" + assert ModelDesc([INTERCEPT], []).describe() == "1 ~ 0" + assert ModelDesc([INTERCEPT], [INTERCEPT]).describe() == "1 ~ 1" + assert ModelDesc([INTERCEPT], [INTERCEPT, Term([f2])]).describe() == "1 ~ b" + + +def test_ModelDesc_from_formula(): + for input in ("y ~ x", parse_formula("y ~ x")): + md = ModelDesc.from_formula(input) + assert md.lhs_termlist == [ + Term([EvalFactor("y")]), + ] + assert md.rhs_termlist == [INTERCEPT, Term([EvalFactor("x")])] + + +class IntermediateExpr(object): + "This class holds an intermediate result while we're evaluating a tree." + + def __init__(self, intercept, intercept_origin, intercept_removed, terms): + self.intercept = intercept + self.intercept_origin = intercept_origin + self.intercept_removed = intercept_removed + self.terms = tuple(uniqueify_list(terms)) + if self.intercept: + assert self.intercept_origin + assert not (self.intercept and self.intercept_removed) + + __repr__ = repr_pretty_delegate + + def _pretty_repr_(self, p, cycle): # pragma: no cover + assert not cycle + return repr_pretty_impl( + p, + self, + [self.intercept, self.intercept_origin, self.intercept_removed, self.terms], + ) + + __getstate__ = no_pickling + + +def _maybe_add_intercept(doit, terms): + if doit: + return (INTERCEPT,) + terms + else: + return terms + + +def _eval_any_tilde(evaluator, tree): + exprs = [evaluator.eval(arg) for arg in tree.args] + if len(exprs) == 1: + # Formula was like: "~ foo" + # We pretend that instead it was like: "0 ~ foo" + exprs.insert(0, IntermediateExpr(False, None, True, [])) + assert len(exprs) == 2 + # Note that only the RHS gets an implicit intercept: + return ModelDesc( + _maybe_add_intercept(exprs[0].intercept, exprs[0].terms), + _maybe_add_intercept(not exprs[1].intercept_removed, exprs[1].terms), + ) + + +def _eval_binary_plus(evaluator, tree): + left_expr = evaluator.eval(tree.args[0]) + if tree.args[1].type == "ZERO": + return IntermediateExpr(False, None, True, left_expr.terms) + else: + right_expr = evaluator.eval(tree.args[1]) + if right_expr.intercept: + return IntermediateExpr( + True, + right_expr.intercept_origin, + False, + left_expr.terms + right_expr.terms, + ) + else: + return IntermediateExpr( + left_expr.intercept, + left_expr.intercept_origin, + left_expr.intercept_removed, + left_expr.terms + right_expr.terms, + ) + + +def _eval_binary_minus(evaluator, tree): + left_expr = evaluator.eval(tree.args[0]) + if tree.args[1].type == "ZERO": + return IntermediateExpr(True, tree.args[1], False, left_expr.terms) + elif tree.args[1].type == "ONE": + return IntermediateExpr(False, None, True, left_expr.terms) + else: + right_expr = evaluator.eval(tree.args[1]) + terms = [term for term in left_expr.terms if term not in right_expr.terms] + if right_expr.intercept: + return IntermediateExpr(False, None, True, terms) + else: + return IntermediateExpr( + left_expr.intercept, + left_expr.intercept_origin, + left_expr.intercept_removed, + terms, + ) + + +def _check_interactable(expr): + if expr.intercept: + raise PatsyError( + "intercept term cannot interact with " "anything else", + expr.intercept_origin, + ) + + +def _interaction(left_expr, right_expr): + for expr in (left_expr, right_expr): + _check_interactable(expr) + terms = [] + for l_term in left_expr.terms: + for r_term in right_expr.terms: + terms.append(Term(l_term.factors + r_term.factors)) + return IntermediateExpr(False, None, False, terms) + + +def _eval_binary_prod(evaluator, tree): + exprs = [evaluator.eval(arg) for arg in tree.args] + return IntermediateExpr( + False, None, False, exprs[0].terms + exprs[1].terms + _interaction(*exprs).terms + ) + + +# Division (nesting) is right-ward distributive: +# a / (b + c) -> a/b + a/c -> a + a:b + a:c +# But left-ward, in S/R it has a quirky behavior: +# (a + b)/c -> a + b + a:b:c +# This is because it's meaningless for a factor to be "nested" under two +# different factors. (This is documented in Chambers and Hastie (page 30) as a +# "Slightly more subtle..." rule, with no further elaboration. Hopefully we +# will do better.) +def _eval_binary_div(evaluator, tree): + left_expr = evaluator.eval(tree.args[0]) + right_expr = evaluator.eval(tree.args[1]) + terms = list(left_expr.terms) + _check_interactable(left_expr) + # Build a single giant combined term for everything on the left: + left_factors = [] + for term in left_expr.terms: + left_factors += list(term.factors) + left_combined_expr = IntermediateExpr(False, None, False, [Term(left_factors)]) + # Then interact it with everything on the right: + terms += list(_interaction(left_combined_expr, right_expr).terms) + return IntermediateExpr(False, None, False, terms) + + +def _eval_binary_interact(evaluator, tree): + exprs = [evaluator.eval(arg) for arg in tree.args] + return _interaction(*exprs) + + +def _eval_binary_power(evaluator, tree): + left_expr = evaluator.eval(tree.args[0]) + _check_interactable(left_expr) + power = -1 + if tree.args[1].type in ("ONE", "NUMBER"): + expr = tree.args[1].token.extra + try: + power = int(expr) + except ValueError: + pass + if power < 1: + raise PatsyError("'**' requires a positive integer", tree.args[1]) + all_terms = left_expr.terms + big_expr = left_expr + # Small optimization: (a + b)**100 is just the same as (a + b)**2. + power = min(len(left_expr.terms), power) + for i in range(1, power): + big_expr = _interaction(left_expr, big_expr) + all_terms = all_terms + big_expr.terms + return IntermediateExpr(False, None, False, all_terms) + + +def _eval_unary_plus(evaluator, tree): + return evaluator.eval(tree.args[0]) + + +def _eval_unary_minus(evaluator, tree): + if tree.args[0].type == "ZERO": + return IntermediateExpr(True, tree.origin, False, []) + elif tree.args[0].type == "ONE": + return IntermediateExpr(False, None, True, []) + else: + raise PatsyError("Unary minus can only be applied to 1 or 0", tree) + + +def _eval_zero(evaluator, tree): + return IntermediateExpr(False, None, True, []) + + +def _eval_one(evaluator, tree): + return IntermediateExpr(True, tree.origin, False, []) + + +def _eval_number(evaluator, tree): + raise PatsyError("numbers besides '0' and '1' are " "only allowed with **", tree) + + +def _eval_python_expr(evaluator, tree): + factor = EvalFactor(tree.token.extra, origin=tree.origin) + return IntermediateExpr(False, None, False, [Term([factor])]) + + +class Evaluator(object): + def __init__(self): + self._evaluators = {} + self.add_op("~", 2, _eval_any_tilde) + self.add_op("~", 1, _eval_any_tilde) + + self.add_op("+", 2, _eval_binary_plus) + self.add_op("-", 2, _eval_binary_minus) + self.add_op("*", 2, _eval_binary_prod) + self.add_op("/", 2, _eval_binary_div) + self.add_op(":", 2, _eval_binary_interact) + self.add_op("**", 2, _eval_binary_power) + + self.add_op("+", 1, _eval_unary_plus) + self.add_op("-", 1, _eval_unary_minus) + + self.add_op("ZERO", 0, _eval_zero) + self.add_op("ONE", 0, _eval_one) + self.add_op("NUMBER", 0, _eval_number) + self.add_op("PYTHON_EXPR", 0, _eval_python_expr) + + # Not used by Patsy -- provided for the convenience of eventual + # user-defined operators. + self.stash = {} + + # This should not be considered a public API yet (to use for actually + # adding new operator semantics) because I wrote in some of the relevant + # code sort of speculatively, but it isn't actually tested. + def add_op(self, op, arity, evaluator): + self._evaluators[op, arity] = evaluator + + def eval(self, tree, require_evalexpr=True): + result = None + assert isinstance(tree, ParseNode) + key = (tree.type, len(tree.args)) + if key not in self._evaluators: + raise PatsyError( + "I don't know how to evaluate this " "'%s' operator" % (tree.type,), + tree.token, + ) + result = self._evaluators[key](self, tree) + if require_evalexpr and not isinstance(result, IntermediateExpr): + if isinstance(result, ModelDesc): + raise PatsyError( + "~ can only be used once, and " "only at the top level", tree + ) + else: + raise PatsyError( + "custom operator returned an " + "object that I don't know how to " + "handle", + tree, + ) + return result + + +############# + +_eval_tests = { + "": (True, []), + " ": (True, []), + " \n ": (True, []), + "a": (True, ["a"]), + "1": (True, []), + "0": (False, []), + "- 1": (False, []), + "- 0": (True, []), + "+ 1": (True, []), + "+ 0": (False, []), + "0 + 1": (True, []), + "1 + 0": (False, []), + "1 - 0": (True, []), + "0 - 1": (False, []), + "1 + a": (True, ["a"]), + "0 + a": (False, ["a"]), + "a - 1": (False, ["a"]), + "a - 0": (True, ["a"]), + "1 - a": (True, []), + "a + b": (True, ["a", "b"]), + "(a + b)": (True, ["a", "b"]), + "a + ((((b))))": (True, ["a", "b"]), + "a + ((((+b))))": (True, ["a", "b"]), + "a + ((((b - a))))": (True, ["a", "b"]), + "a + a + a": (True, ["a"]), + "a + (b - a)": (True, ["a", "b"]), + "a + np.log(a, base=10)": (True, ["a", "np.log(a, base=10)"]), + # Note different spacing: + "a + np.log(a, base=10) - np . log(a , base = 10)": (True, ["a"]), + "a + (I(b) + c)": (True, ["a", "I(b)", "c"]), + "a + I(b + c)": (True, ["a", "I(b + c)"]), + "a:b": (True, [("a", "b")]), + "a:b:a": (True, [("a", "b")]), + "a:(b + c)": (True, [("a", "b"), ("a", "c")]), + "(a + b):c": (True, [("a", "c"), ("b", "c")]), + "a:(b - c)": (True, [("a", "b")]), + "c + a:c + a:(b - c)": (True, ["c", ("a", "c"), ("a", "b")]), + "(a - b):c": (True, [("a", "c")]), + "b + b:c + (a - b):c": (True, ["b", ("b", "c"), ("a", "c")]), + "a:b - a:b": (True, []), + "a:b - b:a": (True, []), + "1 - (a + b)": (True, []), + "a + b - (a + b)": (True, []), + "a * b": (True, ["a", "b", ("a", "b")]), + "a * b * a": (True, ["a", "b", ("a", "b")]), + "a * (b + c)": (True, ["a", "b", "c", ("a", "b"), ("a", "c")]), + "(a + b) * c": (True, ["a", "b", "c", ("a", "c"), ("b", "c")]), + "a * (b - c)": (True, ["a", "b", ("a", "b")]), + "c + a:c + a * (b - c)": (True, ["c", ("a", "c"), "a", "b", ("a", "b")]), + "(a - b) * c": (True, ["a", "c", ("a", "c")]), + "b + b:c + (a - b) * c": (True, ["b", ("b", "c"), "a", "c", ("a", "c")]), + "a/b": (True, ["a", ("a", "b")]), + "(a + b)/c": (True, ["a", "b", ("a", "b", "c")]), + "b + b:c + (a - b)/c": (True, ["b", ("b", "c"), "a", ("a", "c")]), + "a/(b + c)": (True, ["a", ("a", "b"), ("a", "c")]), + "a ** 2": (True, ["a"]), + "(a + b + c + d) ** 2": ( + True, + [ + "a", + "b", + "c", + "d", + ("a", "b"), + ("a", "c"), + ("a", "d"), + ("b", "c"), + ("b", "d"), + ("c", "d"), + ], + ), + "(a + b + c + d) ** 3": ( + True, + [ + "a", + "b", + "c", + "d", + ("a", "b"), + ("a", "c"), + ("a", "d"), + ("b", "c"), + ("b", "d"), + ("c", "d"), + ("a", "b", "c"), + ("a", "b", "d"), + ("a", "c", "d"), + ("b", "c", "d"), + ], + ), + "a + +a": (True, ["a"]), + "~ a + b": (True, ["a", "b"]), + "~ a*b": (True, ["a", "b", ("a", "b")]), + "~ a*b + 0": (False, ["a", "b", ("a", "b")]), + "~ -1": (False, []), + "0 ~ a + b": (True, ["a", "b"]), + "1 ~ a + b": (True, [], True, ["a", "b"]), + "y ~ a + b": (False, ["y"], True, ["a", "b"]), + "0 + y ~ a + b": (False, ["y"], True, ["a", "b"]), + "0 + y * z ~ a + b": (False, ["y", "z", ("y", "z")], True, ["a", "b"]), + "-1 ~ 1": (False, [], True, []), + "1 + y ~ a + b": (True, ["y"], True, ["a", "b"]), + # Check precedence: + "a + b * c": (True, ["a", "b", "c", ("b", "c")]), + "a * b + c": (True, ["a", "b", ("a", "b"), "c"]), + "a * b - a": (True, ["b", ("a", "b")]), + "a + b / c": (True, ["a", "b", ("b", "c")]), + "a / b + c": (True, ["a", ("a", "b"), "c"]), + "a*b:c": (True, ["a", ("b", "c"), ("a", "b", "c")]), + "a:b*c": (True, [("a", "b"), "c", ("a", "b", "c")]), + # Intercept handling: + "~ 1 + 1 + 0 + 1": (True, []), + "~ 0 + 1 + 0": (False, []), + "~ 0 - 1 - 1 + 0 + 1": (True, []), + "~ 1 - 1": (False, []), + "~ 0 + a + 1": (True, ["a"]), + "~ 1 + (a + 0)": (True, ["a"]), # This is correct, but perhaps surprising! + "~ 0 + (a + 1)": (True, ["a"]), # Also correct! + "~ 1 - (a + 1)": (False, []), +} + +# <> mark off where the error should be reported: +_eval_error_tests = [ + "a <+>", + "a + <(>", + "b + <(-a)>", + "a:<1>", + "(a + <1>)*b", + "a + <2>", + "a + <1.0>", + # eh, catching this is a hassle, we'll just leave the user some rope if + # they really want it: + # "a + <0x1>", + "a ** ", + "a ** <(1 + 1)>", + "a ** <1.5>", + "a + b <# asdf>", + "<)>", + "a + <)>", + "<*> a", + "a + <*>", + "a + ", + "a + ", + "a + ", + "a + <[bar>", + "a + <{bar>", + "a + <{bar[]>", + "a + foo<]>bar", + "a + foo[]<]>bar", + "a + foo{}<}>bar", + "a + foo<)>bar", + "a + b<)>", + "(a) <.>", + "<(>a + b", + " ~ b", + "y ~ <(a ~ b)>", + "<~ a> ~ b", + "~ <(a ~ b)>", + "1 + <-(a + b)>", + "<- a>", + "a + <-a**2>", +] + + +def _assert_terms_match(terms, expected_intercept, expecteds): # pragma: no cover + if expected_intercept: + expecteds = [()] + expecteds + assert len(terms) == len(expecteds) + for term, expected in zip(terms, expecteds): + if isinstance(term, Term): + if isinstance(expected, str): + expected = (expected,) + assert term.factors == tuple([EvalFactor(s) for s in expected]) + else: + assert term == expected + + +def _do_eval_formula_tests(tests): # pragma: no cover + for code, result in tests.items(): + if len(result) == 2: + result = (False, []) + result + model_desc = ModelDesc.from_formula(code) + print(repr(code)) + print(result) + print(model_desc) + lhs_intercept, lhs_termlist, rhs_intercept, rhs_termlist = result + _assert_terms_match(model_desc.lhs_termlist, lhs_intercept, lhs_termlist) + _assert_terms_match(model_desc.rhs_termlist, rhs_intercept, rhs_termlist) + + +def test_eval_formula(): + _do_eval_formula_tests(_eval_tests) + + +def test_eval_formula_error_reporting(): + from patsy.parse_formula import _parsing_error_test + + parse_fn = lambda formula: ModelDesc.from_formula(formula) + _parsing_error_test(parse_fn, _eval_error_tests) + + +def test_formula_factor_origin(): + from patsy.origin import Origin + + desc = ModelDesc.from_formula("a + b") + assert desc.rhs_termlist[1].factors[0].origin == Origin("a + b", 0, 1) + assert desc.rhs_termlist[2].factors[0].origin == Origin("a + b", 4, 5) diff --git a/venv/lib/python3.10/site-packages/patsy/design_info.py b/venv/lib/python3.10/site-packages/patsy/design_info.py new file mode 100644 index 0000000000000000000000000000000000000000..12a9510f01f4e30b2e3f4aa15c6ac7fde1f4440d --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/design_info.py @@ -0,0 +1,1322 @@ +# This file is part of Patsy +# Copyright (C) 2011-2015 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file defines the main class for storing metadata about a model +# design. It also defines a 'value-added' design matrix type -- a subclass of +# ndarray that represents a design matrix and holds metadata about its +# columns. The intent is that these are useful and usable data structures +# even if you're not using *any* of the rest of patsy to actually build +# your matrices. + + +# XX TMP TODO: +# +# - update design_matrix_builders and build_design_matrices docs +# - add tests and docs for new design info stuff +# - consider renaming design_matrix_builders (and I guess +# build_design_matrices too). Ditto for highlevel dbuilder functions. + +# These are made available in the patsy.* namespace +__all__ = ["DesignInfo", "FactorInfo", "SubtermInfo", "DesignMatrix"] + +import warnings + +import numpy as np + +from patsy import PatsyError +from patsy.util import atleast_2d_column_default +from patsy.compat import OrderedDict +from patsy.util import ( + repr_pretty_delegate, + repr_pretty_impl, + safe_issubdtype, + no_pickling, + assert_no_pickling, +) +from patsy.constraint import linear_constraint +from patsy.contrasts import ContrastMatrix +from patsy.desc import ModelDesc, Term + + +class FactorInfo: + """A FactorInfo object is a simple class that provides some metadata about + the role of a factor within a model. :attr:`DesignInfo.factor_infos` is + a dictionary which maps factor objects to FactorInfo objects for each + factor in the model. + + .. versionadded:: 0.4.0 + + Attributes: + + .. attribute:: factor + + The factor object being described. + + .. attribute:: type + + The type of the factor -- either the string ``"numerical"`` or the + string ``"categorical"``. + + .. attribute:: state + + An opaque object which holds the state needed to evaluate this + factor on new data (e.g., for prediction). See + :meth:`factor_protocol.eval`. + + .. attribute:: num_columns + + For numerical factors, the number of columns this factor produces. For + categorical factors, this attribute will always be ``None``. + + .. attribute:: categories + + For categorical factors, a tuple of the possible categories this factor + takes on, in order. For numerical factors, this attribute will always be + ``None``. + """ + + def __init__(self, factor, type, state, num_columns=None, categories=None): + self.factor = factor + self.type = type + if self.type not in ["numerical", "categorical"]: + raise ValueError( + "FactorInfo.type must be " + "'numerical' or 'categorical', not %r" % (self.type,) + ) + self.state = state + if self.type == "numerical": + if not isinstance(num_columns, int): + raise ValueError( + "For numerical factors, num_columns " "must be an integer" + ) + if categories is not None: + raise ValueError("For numerical factors, categories " "must be None") + else: + assert self.type == "categorical" + if num_columns is not None: + raise ValueError("For categorical factors, num_columns " "must be None") + categories = tuple(categories) + self.num_columns = num_columns + self.categories = categories + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + assert not cycle + + class FactorState(object): + def __repr__(self): + return "" + + kwlist = [ + ("factor", self.factor), + ("type", self.type), + # Don't put the state in people's faces, it will + # just encourage them to pay attention to the + # contents :-). Plus it's a bunch of gobbledygook + # they don't care about. They can always look at + # self.state if they want to know... + ("state", FactorState()), + ] + if self.type == "numerical": + kwlist.append(("num_columns", self.num_columns)) + else: + kwlist.append(("categories", self.categories)) + repr_pretty_impl(p, self, [], kwlist) + + __getstate__ = no_pickling + + +def test_FactorInfo(): + fi1 = FactorInfo("asdf", "numerical", {"a": 1}, num_columns=10) + assert fi1.factor == "asdf" + assert fi1.state == {"a": 1} + assert fi1.type == "numerical" + assert fi1.num_columns == 10 + assert fi1.categories is None + + # smoke test + repr(fi1) + + fi2 = FactorInfo("asdf", "categorical", {"a": 2}, categories=["z", "j"]) + assert fi2.factor == "asdf" + assert fi2.state == {"a": 2} + assert fi2.type == "categorical" + assert fi2.num_columns is None + assert fi2.categories == ("z", "j") + + # smoke test + repr(fi2) + + import pytest + + pytest.raises(ValueError, FactorInfo, "asdf", "non-numerical", {}) + pytest.raises(ValueError, FactorInfo, "asdf", "numerical", {}) + + pytest.raises(ValueError, FactorInfo, "asdf", "numerical", {}, num_columns="asdf") + pytest.raises( + ValueError, FactorInfo, "asdf", "numerical", {}, num_columns=1, categories=1 + ) + + pytest.raises(TypeError, FactorInfo, "asdf", "categorical", {}) + pytest.raises(ValueError, FactorInfo, "asdf", "categorical", {}, num_columns=1) + pytest.raises(TypeError, FactorInfo, "asdf", "categorical", {}, categories=1) + + +class SubtermInfo: + """A SubtermInfo object is a simple metadata container describing a single + primitive interaction and how it is coded in our design matrix. Our final + design matrix is produced by coding each primitive interaction in order + from left to right, and then stacking the resulting columns. For each + :class:`Term`, we have one or more of these objects which describe how + that term is encoded. :attr:`DesignInfo.term_codings` is a dictionary + which maps term objects to lists of SubtermInfo objects. + + To code a primitive interaction, the following steps are performed: + + * Evaluate each factor on the provided data. + * Encode each factor into one or more proto-columns. For numerical + factors, these proto-columns are identical to whatever the factor + evaluates to; for categorical factors, they are encoded using a + specified contrast matrix. + * Form all pairwise, elementwise products between proto-columns generated + by different factors. (For example, if factor 1 generated proto-columns + A and B, and factor 2 generated proto-columns C and D, then our final + columns are ``A * C``, ``B * C``, ``A * D``, ``B * D``.) + * The resulting columns are stored directly into the final design matrix. + + Sometimes multiple primitive interactions are needed to encode a single + term; this occurs, for example, in the formula ``"1 + a:b"`` when ``a`` + and ``b`` are categorical. See :ref:`formulas-building` for full details. + + .. versionadded:: 0.4.0 + + Attributes: + + .. attribute:: factors + + The factors which appear in this subterm's interaction. + + .. attribute:: contrast_matrices + + A dict mapping factor objects to :class:`ContrastMatrix` objects, + describing how each categorical factor in this interaction is coded. + + .. attribute:: num_columns + + The number of design matrix columns which this interaction generates. + + """ + + def __init__(self, factors, contrast_matrices, num_columns): + self.factors = tuple(factors) + factor_set = frozenset(factors) + if not isinstance(contrast_matrices, dict): + raise ValueError("contrast_matrices must be dict") + for factor, contrast_matrix in contrast_matrices.items(): + if factor not in factor_set: + raise ValueError("Unexpected factor in contrast_matrices dict") + if not isinstance(contrast_matrix, ContrastMatrix): + raise ValueError( + "Expected a ContrastMatrix, not %r" % (contrast_matrix,) + ) + self.contrast_matrices = contrast_matrices + if not isinstance(num_columns, int): + raise ValueError("num_columns must be an integer") + self.num_columns = num_columns + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + assert not cycle + repr_pretty_impl( + p, + self, + [], + [ + ("factors", self.factors), + ("contrast_matrices", self.contrast_matrices), + ("num_columns", self.num_columns), + ], + ) + + __getstate__ = no_pickling + + +def test_SubtermInfo(): + cm = ContrastMatrix(np.ones((2, 2)), ["[1]", "[2]"]) + s = SubtermInfo(["a", "x"], {"a": cm}, 4) + assert s.factors == ("a", "x") + assert s.contrast_matrices == {"a": cm} + assert s.num_columns == 4 + + # smoke test + repr(s) + + import pytest + + pytest.raises(TypeError, SubtermInfo, 1, {}, 1) + pytest.raises(ValueError, SubtermInfo, ["a", "x"], 1, 1) + pytest.raises(ValueError, SubtermInfo, ["a", "x"], {"z": cm}, 1) + pytest.raises(ValueError, SubtermInfo, ["a", "x"], {"a": 1}, 1) + pytest.raises(ValueError, SubtermInfo, ["a", "x"], {}, 1.5) + + +class DesignInfo(object): + """A DesignInfo object holds metadata about a design matrix. + + This is the main object that Patsy uses to pass metadata about a design + matrix to statistical libraries, in order to allow further downstream + processing like intelligent tests, prediction on new data, etc. Usually + encountered as the `.design_info` attribute on design matrices. + + """ + + def __init__(self, column_names, factor_infos=None, term_codings=None): + self.column_name_indexes = OrderedDict( + zip(column_names, range(len(column_names))) + ) + + if (factor_infos is None) != (term_codings is None): + raise ValueError( + "Must specify either both or neither of " + "factor_infos= and term_codings=" + ) + + self.factor_infos = factor_infos + self.term_codings = term_codings + + # factor_infos is a dict containing one entry for every factor + # mentioned in our terms + # and mapping each to FactorInfo object + if self.factor_infos is not None: + if not isinstance(self.factor_infos, dict): + raise ValueError("factor_infos should be a dict") + + if not isinstance(self.term_codings, OrderedDict): + raise ValueError("term_codings must be an OrderedDict") + for term, subterms in self.term_codings.items(): + if not isinstance(term, Term): + raise ValueError("expected a Term, not %r" % (term,)) + if not isinstance(subterms, list): + raise ValueError("term_codings must contain lists") + term_factors = set(term.factors) + for subterm in subterms: + if not isinstance(subterm, SubtermInfo): + raise ValueError("expected SubtermInfo, " "not %r" % (subterm,)) + if not term_factors.issuperset(subterm.factors): + raise ValueError("unexpected factors in subterm") + + all_factors = set() + for term in self.term_codings: + all_factors.update(term.factors) + if all_factors != set(self.factor_infos): + raise ValueError( + "Provided Term objects and factor_infos " "do not match" + ) + for factor, factor_info in self.factor_infos.items(): + if not isinstance(factor_info, FactorInfo): + raise ValueError( + "expected FactorInfo object, not %r" % (factor_info,) + ) + if factor != factor_info.factor: + raise ValueError("mismatched factor_info.factor") + + for term, subterms in self.term_codings.items(): + for subterm in subterms: + exp_cols = 1 + cat_factors = set() + for factor in subterm.factors: + fi = self.factor_infos[factor] + if fi.type == "numerical": + exp_cols *= fi.num_columns + else: + assert fi.type == "categorical" + cm = subterm.contrast_matrices[factor].matrix + if cm.shape[0] != len(fi.categories): + raise ValueError( + "Mismatched contrast matrix " + "for factor %r" % (factor,) + ) + cat_factors.add(factor) + exp_cols *= cm.shape[1] + if cat_factors != set(subterm.contrast_matrices): + raise ValueError( + "Mismatch between contrast_matrices " + "and categorical factors" + ) + if exp_cols != subterm.num_columns: + raise ValueError("Unexpected num_columns") + + if term_codings is None: + # Need to invent term information + self.term_slices = None + # We invent one term per column, with the same name as the column + term_names = column_names + slices = [slice(i, i + 1) for i in range(len(column_names))] + self.term_name_slices = OrderedDict(zip(term_names, slices)) + else: + # Need to derive term information from term_codings + self.term_slices = OrderedDict() + idx = 0 + for term, subterm_infos in self.term_codings.items(): + term_columns = 0 + for subterm_info in subterm_infos: + term_columns += subterm_info.num_columns + self.term_slices[term] = slice(idx, idx + term_columns) + idx += term_columns + if idx != len(self.column_names): + raise ValueError( + "mismatch between column_names and columns " "coded by given terms" + ) + self.term_name_slices = OrderedDict( + [(term.name(), slice_) for (term, slice_) in self.term_slices.items()] + ) + + # Guarantees: + # term_name_slices is never None + # The slices in term_name_slices are in order and exactly cover the + # whole range of columns. + # term_slices may be None + # If term_slices is not None, then its slices match the ones in + # term_name_slices. + assert self.term_name_slices is not None + if self.term_slices is not None: + assert list(self.term_slices.values()) == list( + self.term_name_slices.values() + ) + # These checks probably aren't necessary anymore now that we always + # generate the slices ourselves, but we'll leave them in just to be + # safe. + covered = 0 + for slice_ in self.term_name_slices.values(): + start, stop, step = slice_.indices(len(column_names)) + assert start == covered + assert step == 1 + covered = stop + assert covered == len(column_names) + # If there is any name overlap between terms and columns, they refer + # to the same columns. + for column_name, index in self.column_name_indexes.items(): + if column_name in self.term_name_slices: + slice_ = self.term_name_slices[column_name] + if slice_ != slice(index, index + 1): + raise ValueError("term/column name collision") + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + assert not cycle + repr_pretty_impl( + p, + self, + [self.column_names], + [("factor_infos", self.factor_infos), ("term_codings", self.term_codings)], + ) + + @property + def column_names(self): + "A list of the column names, in order." + return list(self.column_name_indexes) + + @property + def terms(self): + "A list of :class:`Terms`, in order, or else None." + if self.term_slices is None: + return None + return list(self.term_slices) + + @property + def term_names(self): + "A list of terms, in order." + return list(self.term_name_slices) + + @property + def builder(self): + ".. deprecated:: 0.4.0" + warnings.warn( + DeprecationWarning( + "The DesignInfo.builder attribute is deprecated starting in " + "patsy v0.4.0; distinct builder objects have been eliminated " + "and design_info.builder is now just a long-winded way of " + "writing 'design_info' (i.e. the .builder attribute just " + "returns self)" + ), + stacklevel=2, + ) + return self + + @property + def design_info(self): + ".. deprecated:: 0.4.0" + warnings.warn( + DeprecationWarning( + "Starting in patsy v0.4.0, the DesignMatrixBuilder class has " + "been merged into the DesignInfo class. So there's no need to " + "use builder.design_info to access the DesignInfo; 'builder' " + "already *is* a DesignInfo." + ), + stacklevel=2, + ) + return self + + def slice(self, columns_specifier): + """Locate a subset of design matrix columns, specified symbolically. + + A patsy design matrix has two levels of structure: the individual + columns (which are named), and the :ref:`terms ` in + the formula that generated those columns. This is a one-to-many + relationship: a single term may span several columns. This method + provides a user-friendly API for locating those columns. + + (While we talk about columns here, this is probably most useful for + indexing into other arrays that are derived from the design matrix, + such as regression coefficients or covariance matrices.) + + The `columns_specifier` argument can take a number of forms: + + * A term name + * A column name + * A :class:`Term` object + * An integer giving a raw index + * A raw slice object + + In all cases, a Python :func:`slice` object is returned, which can be + used directly for indexing. + + Example:: + + y, X = dmatrices("y ~ a", demo_data("y", "a", nlevels=3)) + betas = np.linalg.lstsq(X, y)[0] + a_betas = betas[X.design_info.slice("a")] + + (If you want to look up a single individual column by name, use + ``design_info.column_name_indexes[name]``.) + """ + if isinstance(columns_specifier, slice): + return columns_specifier + if np.issubdtype(type(columns_specifier), np.integer): + return slice(columns_specifier, columns_specifier + 1) + if self.term_slices is not None and columns_specifier in self.term_slices: + return self.term_slices[columns_specifier] + if columns_specifier in self.term_name_slices: + return self.term_name_slices[columns_specifier] + if columns_specifier in self.column_name_indexes: + idx = self.column_name_indexes[columns_specifier] + return slice(idx, idx + 1) + raise PatsyError("unknown column specified '%s'" % (columns_specifier,)) + + def linear_constraint(self, constraint_likes): + """Construct a linear constraint in matrix form from a (possibly + symbolic) description. + + Possible inputs: + + * A dictionary which is taken as a set of equality constraint. Keys + can be either string column names, or integer column indexes. + * A string giving a arithmetic expression referring to the matrix + columns by name. + * A list of such strings which are ANDed together. + * A tuple (A, b) where A and b are array_likes, and the constraint is + Ax = b. If necessary, these will be coerced to the proper + dimensionality by appending dimensions with size 1. + + The string-based language has the standard arithmetic operators, / * + + - and parentheses, plus "=" is used for equality and "," is used to + AND together multiple constraint equations within a string. You can + If no = appears in some expression, then that expression is assumed to + be equal to zero. Division is always float-based, even if + ``__future__.true_division`` isn't in effect. + + Returns a :class:`LinearConstraint` object. + + Examples:: + + di = DesignInfo(["x1", "x2", "x3"]) + + # Equivalent ways to write x1 == 0: + di.linear_constraint({"x1": 0}) # by name + di.linear_constraint({0: 0}) # by index + di.linear_constraint("x1 = 0") # string based + di.linear_constraint("x1") # can leave out "= 0" + di.linear_constraint("2 * x1 = (x1 + 2 * x1) / 3") + di.linear_constraint(([1, 0, 0], 0)) # constraint matrices + + # Equivalent ways to write x1 == 0 and x3 == 10 + di.linear_constraint({"x1": 0, "x3": 10}) + di.linear_constraint({0: 0, 2: 10}) + di.linear_constraint({0: 0, "x3": 10}) + di.linear_constraint("x1 = 0, x3 = 10") + di.linear_constraint("x1, x3 = 10") + di.linear_constraint(["x1", "x3 = 0"]) # list of strings + di.linear_constraint("x1 = 0, x3 - 10 = x1") + di.linear_constraint([[1, 0, 0], [0, 0, 1]], [0, 10]) + + # You can also chain together equalities, just like Python: + di.linear_constraint("x1 = x2 = 3") + """ + return linear_constraint(constraint_likes, self.column_names) + + def describe(self): + """Returns a human-readable string describing this design info. + + Example: + + .. ipython:: + + In [1]: y, X = dmatrices("y ~ x1 + x2", demo_data("y", "x1", "x2")) + + In [2]: y.design_info.describe() + Out[2]: 'y' + + In [3]: X.design_info.describe() + Out[3]: '1 + x1 + x2' + + .. warning:: + + There is no guarantee that the strings returned by this function + can be parsed as formulas, or that if they can be parsed as a + formula that they will produce a model equivalent to the one you + started with. This function produces a best-effort description + intended for humans to read. + + """ + + names = [] + for name in self.term_names: + if name == "Intercept": + names.append("1") + else: + names.append(name) + return " + ".join(names) + + def subset(self, which_terms): + """Create a new :class:`DesignInfo` for design matrices that contain a + subset of the terms that the current :class:`DesignInfo` does. + + For example, if ``design_info`` has terms ``x``, ``y``, and ``z``, + then:: + + design_info2 = design_info.subset(["x", "z"]) + + will return a new DesignInfo that can be used to construct design + matrices with only the columns corresponding to the terms ``x`` and + ``z``. After we do this, then in general these two expressions will + return the same thing (here we assume that ``x``, ``y``, and ``z`` + each generate a single column of the output):: + + build_design_matrix([design_info], data)[0][:, [0, 2]] + build_design_matrix([design_info2], data)[0] + + However, a critical difference is that in the second case, ``data`` + need not contain any values for ``y``. This is very useful when doing + prediction using a subset of a model, in which situation R usually + forces you to specify dummy values for ``y``. + + If using a formula to specify the terms to include, remember that like + any formula, the intercept term will be included by default, so use + ``0`` or ``-1`` in your formula if you want to avoid this. + + This method can also be used to reorder the terms in your design + matrix, in case you want to do that for some reason. I can't think of + any. + + Note that this method will generally *not* produce the same result as + creating a new model directly. Consider these DesignInfo objects:: + + design1 = dmatrix("1 + C(a)", data) + design2 = design1.subset("0 + C(a)") + design3 = dmatrix("0 + C(a)", data) + + Here ``design2`` and ``design3`` will both produce design matrices + that contain an encoding of ``C(a)`` without any intercept term. But + ``design3`` uses a full-rank encoding for the categorical term + ``C(a)``, while ``design2`` uses the same reduced-rank encoding as + ``design1``. + + :arg which_terms: The terms which should be kept in the new + :class:`DesignMatrixBuilder`. If this is a string, then it is parsed + as a formula, and then the names of the resulting terms are taken as + the terms to keep. If it is a list, then it can contain a mixture of + term names (as strings) and :class:`Term` objects. + + .. versionadded: 0.2.0 + New method on the class DesignMatrixBuilder. + + .. versionchanged: 0.4.0 + Moved from DesignMatrixBuilder to DesignInfo, as part of the + removal of DesignMatrixBuilder. + + """ + if isinstance(which_terms, str): + desc = ModelDesc.from_formula(which_terms) + if desc.lhs_termlist: + raise PatsyError("right-hand-side-only formula required") + which_terms = [term.name() for term in desc.rhs_termlist] + + if self.term_codings is None: + # This is a minimal DesignInfo + # If the name is unknown we just let the KeyError escape + new_names = [] + for t in which_terms: + new_names += self.column_names[self.term_name_slices[t]] + return DesignInfo(new_names) + else: + term_name_to_term = {} + for term in self.term_codings: + term_name_to_term[term.name()] = term + + new_column_names = [] + new_factor_infos = {} + new_term_codings = OrderedDict() + for name_or_term in which_terms: + term = term_name_to_term.get(name_or_term, name_or_term) + # If the name is unknown we just let the KeyError escape + s = self.term_slices[term] + new_column_names += self.column_names[s] + for f in term.factors: + new_factor_infos[f] = self.factor_infos[f] + new_term_codings[term] = self.term_codings[term] + return DesignInfo( + new_column_names, + factor_infos=new_factor_infos, + term_codings=new_term_codings, + ) + + @classmethod + def from_array(cls, array_like, default_column_prefix="column"): + """Find or construct a DesignInfo appropriate for a given array_like. + + If the input `array_like` already has a ``.design_info`` + attribute, then it will be returned. Otherwise, a new DesignInfo + object will be constructed, using names either taken from the + `array_like` (e.g., for a pandas DataFrame with named columns), or + constructed using `default_column_prefix`. + + This is how :func:`dmatrix` (for example) creates a DesignInfo object + if an arbitrary matrix is passed in. + + :arg array_like: An ndarray or pandas container. + :arg default_column_prefix: If it's necessary to invent column names, + then this will be used to construct them. + :returns: a DesignInfo object + """ + if hasattr(array_like, "design_info") and isinstance( + array_like.design_info, cls + ): + return array_like.design_info + arr = atleast_2d_column_default(array_like, preserve_pandas=True) + if arr.ndim > 2: + raise ValueError("design matrix can't have >2 dimensions") + columns = getattr(arr, "columns", range(arr.shape[1])) + if hasattr(columns, "dtype") and not safe_issubdtype(columns.dtype, np.integer): + column_names = [str(obj) for obj in columns] + else: + column_names = ["%s%s" % (default_column_prefix, i) for i in columns] + return DesignInfo(column_names) + + __getstate__ = no_pickling + + +def test_DesignInfo(): + import pytest + + class _MockFactor(object): + def __init__(self, name): + self._name = name + + def name(self): + return self._name + + f_x = _MockFactor("x") + f_y = _MockFactor("y") + t_x = Term([f_x]) + t_y = Term([f_y]) + factor_infos = { + f_x: FactorInfo(f_x, "numerical", {}, num_columns=3), + f_y: FactorInfo(f_y, "numerical", {}, num_columns=1), + } + term_codings = OrderedDict( + [(t_x, [SubtermInfo([f_x], {}, 3)]), (t_y, [SubtermInfo([f_y], {}, 1)])] + ) + di = DesignInfo(["x1", "x2", "x3", "y"], factor_infos, term_codings) + assert di.column_names == ["x1", "x2", "x3", "y"] + assert di.term_names == ["x", "y"] + assert di.terms == [t_x, t_y] + assert di.column_name_indexes == {"x1": 0, "x2": 1, "x3": 2, "y": 3} + assert di.term_name_slices == {"x": slice(0, 3), "y": slice(3, 4)} + assert di.term_slices == {t_x: slice(0, 3), t_y: slice(3, 4)} + assert di.describe() == "x + y" + + assert di.slice(1) == slice(1, 2) + assert di.slice("x1") == slice(0, 1) + assert di.slice("x2") == slice(1, 2) + assert di.slice("x3") == slice(2, 3) + assert di.slice("x") == slice(0, 3) + assert di.slice(t_x) == slice(0, 3) + assert di.slice("y") == slice(3, 4) + assert di.slice(t_y) == slice(3, 4) + assert di.slice(slice(2, 4)) == slice(2, 4) + pytest.raises(PatsyError, di.slice, "asdf") + + # smoke test + repr(di) + + assert_no_pickling(di) + + # One without term objects + di = DesignInfo(["a1", "a2", "a3", "b"]) + assert di.column_names == ["a1", "a2", "a3", "b"] + assert di.term_names == ["a1", "a2", "a3", "b"] + assert di.terms is None + assert di.column_name_indexes == {"a1": 0, "a2": 1, "a3": 2, "b": 3} + assert di.term_name_slices == { + "a1": slice(0, 1), + "a2": slice(1, 2), + "a3": slice(2, 3), + "b": slice(3, 4), + } + assert di.term_slices is None + assert di.describe() == "a1 + a2 + a3 + b" + + assert di.slice(1) == slice(1, 2) + assert di.slice("a1") == slice(0, 1) + assert di.slice("a2") == slice(1, 2) + assert di.slice("a3") == slice(2, 3) + assert di.slice("b") == slice(3, 4) + + # Check intercept handling in describe() + assert DesignInfo(["Intercept", "a", "b"]).describe() == "1 + a + b" + + # Failure modes + # must specify either both or neither of factor_infos and term_codings: + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "x3", "y"], factor_infos=factor_infos + ) + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "x3", "y"], term_codings=term_codings + ) + # factor_infos must be a dict + pytest.raises( + ValueError, + DesignInfo, + ["x1", "x2", "x3", "y"], + list(factor_infos), + term_codings, + ) + # wrong number of column names: + pytest.raises( + ValueError, + DesignInfo, + ["x1", "x2", "x3", "y1", "y2"], + factor_infos, + term_codings, + ) + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "x3"], factor_infos, term_codings + ) + # name overlap problems + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "y", "y2"], factor_infos, term_codings + ) + # duplicate name + pytest.raises( + ValueError, DesignInfo, ["x1", "x1", "x1", "y"], factor_infos, term_codings + ) + + # f_y is in factor_infos, but not mentioned in any term + term_codings_x_only = OrderedDict(term_codings) + del term_codings_x_only[t_y] + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "x3"], factor_infos, term_codings_x_only + ) + + # f_a is in a term, but not in factor_infos + f_a = _MockFactor("a") + t_a = Term([f_a]) + term_codings_with_a = OrderedDict(term_codings) + term_codings_with_a[t_a] = [SubtermInfo([f_a], {}, 1)] + pytest.raises( + ValueError, + DesignInfo, + ["x1", "x2", "x3", "y", "a"], + factor_infos, + term_codings_with_a, + ) + + # bad factor_infos + not_factor_infos = dict(factor_infos) + not_factor_infos[f_x] = "what is this I don't even" + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "x3", "y"], not_factor_infos, term_codings + ) + + mismatch_factor_infos = dict(factor_infos) + mismatch_factor_infos[f_x] = FactorInfo(f_a, "numerical", {}, num_columns=3) + pytest.raises( + ValueError, + DesignInfo, + ["x1", "x2", "x3", "y"], + mismatch_factor_infos, + term_codings, + ) + + # bad term_codings + pytest.raises( + ValueError, + DesignInfo, + ["x1", "x2", "x3", "y"], + factor_infos, + dict(term_codings), + ) + + not_term_codings = OrderedDict(term_codings) + not_term_codings["this is a string"] = term_codings[t_x] + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "x3", "y"], factor_infos, not_term_codings + ) + + non_list_term_codings = OrderedDict(term_codings) + non_list_term_codings[t_y] = tuple(term_codings[t_y]) + pytest.raises( + ValueError, + DesignInfo, + ["x1", "x2", "x3", "y"], + factor_infos, + non_list_term_codings, + ) + + non_subterm_term_codings = OrderedDict(term_codings) + non_subterm_term_codings[t_y][0] = "not a SubtermInfo" + pytest.raises( + ValueError, + DesignInfo, + ["x1", "x2", "x3", "y"], + factor_infos, + non_subterm_term_codings, + ) + + bad_subterm = OrderedDict(term_codings) + # f_x is a factor in this model, but it is not a factor in t_y + term_codings[t_y][0] = SubtermInfo([f_x], {}, 1) + pytest.raises( + ValueError, DesignInfo, ["x1", "x2", "x3", "y"], factor_infos, bad_subterm + ) + + # contrast matrix has wrong number of rows + factor_codings_a = { + f_a: FactorInfo(f_a, "categorical", {}, categories=["a1", "a2"]) + } + term_codings_a_bad_rows = OrderedDict( + [ + ( + t_a, + [ + SubtermInfo( + [f_a], {f_a: ContrastMatrix(np.ones((3, 2)), ["[1]", "[2]"])}, 2 + ) + ], + ) + ] + ) + pytest.raises( + ValueError, + DesignInfo, + ["a[1]", "a[2]"], + factor_codings_a, + term_codings_a_bad_rows, + ) + + # have a contrast matrix for a non-categorical factor + t_ax = Term([f_a, f_x]) + factor_codings_ax = { + f_a: FactorInfo(f_a, "categorical", {}, categories=["a1", "a2"]), + f_x: FactorInfo(f_x, "numerical", {}, num_columns=2), + } + term_codings_ax_extra_cm = OrderedDict( + [ + ( + t_ax, + [ + SubtermInfo( + [f_a, f_x], + { + f_a: ContrastMatrix(np.ones((2, 2)), ["[1]", "[2]"]), + f_x: ContrastMatrix(np.ones((2, 2)), ["[1]", "[2]"]), + }, + 4, + ) + ], + ) + ] + ) + pytest.raises( + ValueError, + DesignInfo, + ["a[1]:x[1]", "a[2]:x[1]", "a[1]:x[2]", "a[2]:x[2]"], + factor_codings_ax, + term_codings_ax_extra_cm, + ) + + # no contrast matrix for a categorical factor + term_codings_ax_missing_cm = OrderedDict([(t_ax, [SubtermInfo([f_a, f_x], {}, 4)])]) + # This actually fails before it hits the relevant check with a KeyError, + # but that's okay... the previous test still exercises the check. + pytest.raises( + (ValueError, KeyError), + DesignInfo, + ["a[1]:x[1]", "a[2]:x[1]", "a[1]:x[2]", "a[2]:x[2]"], + factor_codings_ax, + term_codings_ax_missing_cm, + ) + + # subterm num_columns doesn't match the value computed from the individual + # factors + term_codings_ax_wrong_subterm_columns = OrderedDict( + [ + ( + t_ax, + [ + SubtermInfo( + [f_a, f_x], + {f_a: ContrastMatrix(np.ones((2, 3)), ["[1]", "[2]", "[3]"])}, + # should be 2 * 3 = 6 + 5, + ) + ], + ) + ] + ) + pytest.raises( + ValueError, + DesignInfo, + ["a[1]:x[1]", "a[2]:x[1]", "a[3]:x[1]", "a[1]:x[2]", "a[2]:x[2]", "a[3]:x[2]"], + factor_codings_ax, + term_codings_ax_wrong_subterm_columns, + ) + + +def test_DesignInfo_from_array(): + di = DesignInfo.from_array([1, 2, 3]) + assert di.column_names == ["column0"] + di2 = DesignInfo.from_array([[1, 2], [2, 3], [3, 4]]) + assert di2.column_names == ["column0", "column1"] + di3 = DesignInfo.from_array([1, 2, 3], default_column_prefix="x") + assert di3.column_names == ["x0"] + di4 = DesignInfo.from_array([[1, 2], [2, 3], [3, 4]], default_column_prefix="x") + assert di4.column_names == ["x0", "x1"] + m = DesignMatrix([1, 2, 3], di3) + assert DesignInfo.from_array(m) is di3 + # But weird objects are ignored + m.design_info = "asdf" + di_weird = DesignInfo.from_array(m) + assert di_weird.column_names == ["column0"] + + import pytest + + pytest.raises(ValueError, DesignInfo.from_array, np.ones((2, 2, 2))) + + from patsy.util import have_pandas + + if have_pandas: + import pandas + + # with named columns + di5 = DesignInfo.from_array(pandas.DataFrame([[1, 2]], columns=["a", "b"])) + assert di5.column_names == ["a", "b"] + # with irregularly numbered columns + di6 = DesignInfo.from_array(pandas.DataFrame([[1, 2]], columns=[0, 10])) + assert di6.column_names == ["column0", "column10"] + # with .design_info attr + df = pandas.DataFrame([[1, 2]]) + df.design_info = di6 + assert DesignInfo.from_array(df) is di6 + + +def test_DesignInfo_linear_constraint(): + di = DesignInfo(["a1", "a2", "a3", "b"]) + con = di.linear_constraint(["2 * a1 = b + 1", "a3"]) + assert con.variable_names == ["a1", "a2", "a3", "b"] + assert np.all(con.coefs == [[2, 0, 0, -1], [0, 0, 1, 0]]) + assert np.all(con.constants == [[1], [0]]) + + +def test_DesignInfo_deprecated_attributes(): + d = DesignInfo(["a1", "a2"]) + + def check(attr): + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + assert getattr(d, attr) is d + assert len(w) == 1 + assert w[0].category is DeprecationWarning + + check("builder") + check("design_info") + + +# Idea: format with a reasonable amount of precision, then if that turns out +# to be higher than necessary, remove as many zeros as we can. But only do +# this while we can do it to *all* the ordinarily-formatted numbers, to keep +# decimal points aligned. +def _format_float_column(precision, col): + format_str = "%." + str(precision) + "f" + assert col.ndim == 1 + # We don't want to look at numbers like "1e-5" or "nan" when stripping. + simple_float_chars = set("+-0123456789.") + col_strs = np.array([format_str % (x,) for x in col], dtype=object) + # Really every item should have a decimal, but just in case, we don't want + # to strip zeros off the end of "10" or something like that. + mask = np.array( + [ + simple_float_chars.issuperset(col_str) and "." in col_str + for col_str in col_strs + ] + ) + mask_idxes = np.nonzero(mask)[0] + strip_char = "0" + if np.any(mask): + while True: + if np.all([s.endswith(strip_char) for s in col_strs[mask]]): + for idx in mask_idxes: + col_strs[idx] = col_strs[idx][:-1] + else: + if strip_char == "0": + strip_char = "." + else: + break + return col_strs + + +def test__format_float_column(): + def t(precision, numbers, expected): + got = _format_float_column(precision, np.asarray(numbers)) + print(got, expected) + assert np.array_equal(got, expected) + + # This acts weird on old python versions (e.g. it can be "-nan"), so don't + # hardcode it: + nan_string = "%.3f" % (np.nan,) + t(3, [1, 2.1234, 2.1239, np.nan], ["1.000", "2.123", "2.124", nan_string]) + t(3, [1, 2, 3, np.nan], ["1", "2", "3", nan_string]) + t(3, [1.0001, 2, 3, np.nan], ["1", "2", "3", nan_string]) + t(4, [1.0001, 2, 3, np.nan], ["1.0001", "2.0000", "3.0000", nan_string]) + + +# http://docs.scipy.org/doc/numpy/user/basics.subclassing.html#slightly-more-realistic-example-attribute-added-to-existing-array +class DesignMatrix(np.ndarray): + """A simple numpy array subclass that carries design matrix metadata. + + .. attribute:: design_info + + A :class:`DesignInfo` object containing metadata about this design + matrix. + + This class also defines a fancy __repr__ method with labeled + columns. Otherwise it is identical to a regular numpy ndarray. + + .. warning:: + + You should never check for this class using + :func:`isinstance`. Limitations of the numpy API mean that it is + impossible to prevent the creation of numpy arrays that have type + DesignMatrix, but that are not actually design matrices (and such + objects will behave like regular ndarrays in every way). Instead, check + for the presence of a ``.design_info`` attribute -- this will be + present only on "real" DesignMatrix objects. + """ + + def __new__(cls, input_array, design_info=None, default_column_prefix="column"): + """Create a DesignMatrix, or cast an existing matrix to a DesignMatrix. + + A call like:: + + DesignMatrix(my_array) + + will convert an arbitrary array_like object into a DesignMatrix. + + The return from this function is guaranteed to be a two-dimensional + ndarray with a real-valued floating point dtype, and a + ``.design_info`` attribute which matches its shape. If the + `design_info` argument is not given, then one is created via + :meth:`DesignInfo.from_array` using the given + `default_column_prefix`. + + Depending on the input array, it is possible this will pass through + its input unchanged, or create a view. + """ + # Pass through existing DesignMatrixes. The design_info check is + # necessary because numpy is sort of annoying and cannot be stopped + # from turning non-design-matrix arrays into DesignMatrix + # instances. (E.g., my_dm.diagonal() will return a DesignMatrix + # object, but one without a design_info attribute.) + if isinstance(input_array, DesignMatrix) and hasattr( + input_array, "design_info" + ): + return input_array + self = atleast_2d_column_default(input_array).view(cls) + # Upcast integer to floating point + if safe_issubdtype(self.dtype, np.integer): + self = np.asarray(self, dtype=float).view(cls) + if self.ndim > 2: + raise ValueError("DesignMatrix must be 2d") + assert self.ndim == 2 + if design_info is None: + design_info = DesignInfo.from_array(self, default_column_prefix) + if len(design_info.column_names) != self.shape[1]: + raise ValueError( + "wrong number of column names for design matrix " + "(got %s, wanted %s)" % (len(design_info.column_names), self.shape[1]) + ) + self.design_info = design_info + if not safe_issubdtype(self.dtype, np.floating): + raise ValueError("design matrix must be real-valued floating point") + return self + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + if not hasattr(self, "design_info"): + # Not a real DesignMatrix + p.pretty(np.asarray(self)) + return + assert not cycle + + # XX: could try calculating width of the current terminal window: + # http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python + # sadly it looks like ipython does not actually pass this information + # in, even if we use _repr_pretty_ -- the pretty-printer object has a + # fixed width it always uses. (As of IPython 0.12.) + MAX_TOTAL_WIDTH = 78 + SEP = 2 + INDENT = 2 + MAX_ROWS = 30 + PRECISION = 5 + + names = self.design_info.column_names + column_name_widths = [len(name) for name in names] + min_total_width = ( + INDENT + SEP * (self.shape[1] - 1) + np.sum(column_name_widths) + ) + if min_total_width <= MAX_TOTAL_WIDTH: + printable_part = np.asarray(self)[:MAX_ROWS, :] + formatted_cols = [ + _format_float_column(PRECISION, printable_part[:, i]) + for i in range(self.shape[1]) + ] + + def max_width(col): + assert col.ndim == 1 + if not col.shape[0]: + return 0 + else: + return max([len(s) for s in col]) + + column_num_widths = [max_width(col) for col in formatted_cols] + column_widths = [ + max(name_width, num_width) + for (name_width, num_width) in zip( + column_name_widths, column_num_widths + ) + ] + total_width = INDENT + SEP * (self.shape[1] - 1) + np.sum(column_widths) + print_numbers = total_width < MAX_TOTAL_WIDTH + else: + print_numbers = False + + p.begin_group(INDENT, "DesignMatrix with shape %s" % (self.shape,)) + p.breakable("\n" + " " * p.indentation) + if print_numbers: + # We can fit the numbers on the screen + sep = " " * SEP + # list() is for Py3 compatibility + for row in [names] + list(zip(*formatted_cols)): + cells = [cell.rjust(width) for (width, cell) in zip(column_widths, row)] + p.text(sep.join(cells)) + p.text("\n" + " " * p.indentation) + if MAX_ROWS < self.shape[0]: + p.text("[%s rows omitted]" % (self.shape[0] - MAX_ROWS,)) + p.text("\n" + " " * p.indentation) + else: + p.begin_group(2, "Columns:") + p.breakable("\n" + " " * p.indentation) + p.pretty(names) + p.end_group(2, "") + p.breakable("\n" + " " * p.indentation) + + p.begin_group(2, "Terms:") + p.breakable("\n" + " " * p.indentation) + for term_name, span in self.design_info.term_name_slices.items(): + if span.start != 0: + p.breakable(", ") + p.pretty(term_name) + if span.stop - span.start == 1: + coltext = "column %s" % (span.start,) + else: + coltext = "columns %s:%s" % (span.start, span.stop) + p.text(" (%s)" % (coltext,)) + p.end_group(2, "") + + if not print_numbers or self.shape[0] > MAX_ROWS: + # some data was not shown + p.breakable("\n" + " " * p.indentation) + p.text("(to view full data, use np.asarray(this_obj))") + + p.end_group(INDENT, "") + + # No __array_finalize__ method, because we don't want slices of this + # object to keep the design_info (they may have different columns!), or + # anything fancy like that. + + __reduce__ = no_pickling + + +def test_design_matrix(): + import pytest + + di = DesignInfo(["a1", "a2", "a3", "b"]) + mm = DesignMatrix([[12, 14, 16, 18]], di) + assert mm.design_info.column_names == ["a1", "a2", "a3", "b"] + + bad_di = DesignInfo(["a1"]) + pytest.raises(ValueError, DesignMatrix, [[12, 14, 16, 18]], bad_di) + + mm2 = DesignMatrix([[12, 14, 16, 18]]) + assert mm2.design_info.column_names == ["column0", "column1", "column2", "column3"] + + mm3 = DesignMatrix([12, 14, 16, 18]) + assert mm3.shape == (4, 1) + + # DesignMatrix always has exactly 2 dimensions + pytest.raises(ValueError, DesignMatrix, [[[1]]]) + + # DesignMatrix constructor passes through existing DesignMatrixes + mm4 = DesignMatrix(mm) + assert mm4 is mm + # But not if they are really slices: + mm5 = DesignMatrix(mm.diagonal()) + assert mm5 is not mm + + mm6 = DesignMatrix([[12, 14, 16, 18]], default_column_prefix="x") + assert mm6.design_info.column_names == ["x0", "x1", "x2", "x3"] + + assert_no_pickling(mm6) + + # Only real-valued matrices can be DesignMatrixs + pytest.raises(ValueError, DesignMatrix, [1, 2, 3j]) + pytest.raises(ValueError, DesignMatrix, ["a", "b", "c"]) + pytest.raises(ValueError, DesignMatrix, [1, 2, object()]) + + # Just smoke tests + repr(mm) + repr(DesignMatrix(np.arange(100))) + repr(DesignMatrix(np.arange(100) * 2.0)) + repr(mm[1:, :]) + repr(DesignMatrix(np.arange(100).reshape((1, 100)))) + repr(DesignMatrix([np.nan, np.inf])) + repr(DesignMatrix([np.nan, 0, 1e20, 20.5])) + # handling of zero-size matrices + repr(DesignMatrix(np.zeros((1, 0)))) + repr(DesignMatrix(np.zeros((0, 1)))) + repr(DesignMatrix(np.zeros((0, 0)))) diff --git a/venv/lib/python3.10/site-packages/patsy/eval.py b/venv/lib/python3.10/site-packages/patsy/eval.py new file mode 100644 index 0000000000000000000000000000000000000000..f63c4d3f71639064621645db26e58143048d6ba1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/eval.py @@ -0,0 +1,853 @@ +# This file is part of Patsy +# Copyright (C) 2011 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Utilities that require an over-intimate knowledge of Python's execution +# environment. + +# NB: if you add any __future__ imports to this file then you'll have to +# adjust the tests that deal with checking the caller's execution environment +# for __future__ flags! + +# These are made available in the patsy.* namespace +__all__ = ["EvalEnvironment", "EvalFactor"] + +import __future__ +import sys +import inspect +import tokenize +import ast +import numbers +from patsy import PatsyError +from patsy.util import PushbackAdapter, no_pickling, assert_no_pickling +from patsy.tokens import pretty_untokenize, normalize_token_spacing, python_tokenize +from patsy.compat import call_and_wrap_exc + + +def _all_future_flags(): + flags = 0 + for feature_name in __future__.all_feature_names: + feature = getattr(__future__, feature_name) + mr = feature.getMandatoryRelease() + # None means a planned feature was dropped, or at least postponed + # without a final decision; see, for example, + # https://docs.python.org/3.11/library/__future__.html#id2. + if mr is None or mr > sys.version_info: + flags |= feature.compiler_flag + return flags + + +_ALL_FUTURE_FLAGS = _all_future_flags() + + +# This is just a minimal dict-like object that does lookup in a 'stack' of +# dicts -- first it checks the first, then the second, etc. Assignments go +# into an internal, zeroth dict. +class VarLookupDict(object): + def __init__(self, dicts): + self._dicts = [{}] + list(dicts) + + def __getitem__(self, key): + for d in self._dicts: + try: + return d[key] + except KeyError: + pass + raise KeyError(key) + + def __setitem__(self, key, value): + self._dicts[0][key] = value + + def __contains__(self, key): + try: + self[key] + except KeyError: + return False + else: + return True + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + return default + + def __repr__(self): + return "%s(%r)" % (self.__class__.__name__, self._dicts) + + __getstate__ = no_pickling + + +def test_VarLookupDict(): + d1 = {"a": 1} + d2 = {"a": 2, "b": 3} + ds = VarLookupDict([d1, d2]) + assert ds["a"] == 1 + assert ds["b"] == 3 + assert "a" in ds + assert "c" not in ds + import pytest + + pytest.raises(KeyError, ds.__getitem__, "c") + ds["a"] = 10 + assert ds["a"] == 10 + assert d1["a"] == 1 + assert ds.get("c") is None + assert isinstance(repr(ds), str) + + assert_no_pickling(ds) + + +def ast_names(code): + """Iterator that yields all the (ast) names in a Python expression. + + :arg code: A string containing a Python expression. + """ + # Syntax that allows new name bindings to be introduced is tricky to + # handle here, so we just refuse to do so. + disallowed_ast_nodes = (ast.Lambda, ast.ListComp, ast.GeneratorExp) + disallowed_ast_nodes += (ast.DictComp, ast.SetComp) + + for node in ast.walk(ast.parse(code)): + if isinstance(node, disallowed_ast_nodes): + raise PatsyError( + "Lambda, list/dict/set comprehension, generator " + "expression in patsy formula not currently supported." + ) + if isinstance(node, ast.Name): + yield node.id + + +def test_ast_names(): + test_data = [ + ("np.log(x)", ["np", "x"]), + ("x", ["x"]), + ("center(x + 1)", ["center", "x"]), + ("dt.date.dt.month", ["dt"]), + ] + for code, expected in test_data: + assert set(ast_names(code)) == set(expected) + + +def test_ast_names_disallowed_nodes(): + import pytest + + def list_ast_names(code): + return list(ast_names(code)) + + pytest.raises(PatsyError, list_ast_names, "lambda x: x + y") + pytest.raises(PatsyError, list_ast_names, "[x + 1 for x in range(10)]") + pytest.raises(PatsyError, list_ast_names, "(x + 1 for x in range(10))") + pytest.raises(PatsyError, list_ast_names, "{x: True for x in range(10)}") + pytest.raises(PatsyError, list_ast_names, "{x + 1 for x in range(10)}") + + +class EvalEnvironment(object): + """Represents a Python execution environment. + + Encapsulates a namespace for variable lookup and set of __future__ + flags.""" + + def __init__(self, namespaces, flags=0): + assert not flags & ~_ALL_FUTURE_FLAGS + self._namespaces = list(namespaces) + self.flags = flags + + @property + def namespace(self): + """A dict-like object that can be used to look up variables accessible + from the encapsulated environment.""" + return VarLookupDict(self._namespaces) + + def with_outer_namespace(self, outer_namespace): + """Return a new EvalEnvironment with an extra namespace added. + + This namespace will be used only for variables that are not found in + any existing namespace, i.e., it is "outside" them all.""" + return self.__class__(self._namespaces + [outer_namespace], self.flags) + + def eval(self, expr, source_name="", inner_namespace={}): + """Evaluate some Python code in the encapsulated environment. + + :arg expr: A string containing a Python expression. + :arg source_name: A name for this string, for use in tracebacks. + :arg inner_namespace: A dict-like object that will be checked first + when `expr` attempts to access any variables. + :returns: The value of `expr`. + """ + code = compile(expr, source_name, "eval", self.flags, False) + return eval(code, {}, VarLookupDict([inner_namespace] + self._namespaces)) + + @classmethod + def capture(cls, eval_env=0, reference=0): + """Capture an execution environment from the stack. + + If `eval_env` is already an :class:`EvalEnvironment`, it is returned + unchanged. Otherwise, we walk up the stack by ``eval_env + reference`` + steps and capture that function's evaluation environment. + + For ``eval_env=0`` and ``reference=0``, the default, this captures the + stack frame of the function that calls :meth:`capture`. If ``eval_env + + reference`` is 1, then we capture that function's caller, etc. + + This somewhat complicated calling convention is designed to be + convenient for functions which want to capture their caller's + environment by default, but also allow explicit environments to be + specified. See the second example. + + Example:: + + x = 1 + this_env = EvalEnvironment.capture() + assert this_env.namespace["x"] == 1 + def child_func(): + return EvalEnvironment.capture(1) + this_env_from_child = child_func() + assert this_env_from_child.namespace["x"] == 1 + + Example:: + + # This function can be used like: + # my_model(formula_like, data) + # -> evaluates formula_like in caller's environment + # my_model(formula_like, data, eval_env=1) + # -> evaluates formula_like in caller's caller's environment + # my_model(formula_like, data, eval_env=my_env) + # -> evaluates formula_like in environment 'my_env' + def my_model(formula_like, data, eval_env=0): + eval_env = EvalEnvironment.capture(eval_env, reference=1) + return model_setup_helper(formula_like, data, eval_env) + + This is how :func:`dmatrix` works. + + .. versionadded: 0.2.0 + The ``reference`` argument. + """ + if isinstance(eval_env, cls): + return eval_env + elif isinstance(eval_env, numbers.Integral): + depth = eval_env + reference + else: + raise TypeError( + "Parameter 'eval_env' must be either an integer " + "or an instance of patsy.EvalEnvironment." + ) + frame = inspect.currentframe() + try: + for i in range(depth + 1): + if frame is None: + raise ValueError("call-stack is not that deep!") + frame = frame.f_back + return cls( + [frame.f_locals, frame.f_globals], + frame.f_code.co_flags & _ALL_FUTURE_FLAGS, + ) + # The try/finally is important to avoid a potential reference cycle -- + # any exception traceback will carry a reference to *our* frame, which + # contains a reference to our local variables, which would otherwise + # carry a reference to some parent frame, where the exception was + # caught...: + finally: + del frame + + def subset(self, names): + """Creates a new, flat EvalEnvironment that contains only + the variables specified.""" + vld = VarLookupDict(self._namespaces) + new_ns = dict((name, vld[name]) for name in names) + return EvalEnvironment([new_ns], self.flags) + + def _namespace_ids(self): + return [id(n) for n in self._namespaces] + + def __eq__(self, other): + return ( + isinstance(other, EvalEnvironment) + and self.flags == other.flags + and self._namespace_ids() == other._namespace_ids() + ) + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash((EvalEnvironment, self.flags, tuple(self._namespace_ids()))) + + __getstate__ = no_pickling + + +def _a(): # pragma: no cover + _a = 1 + return _b() + + +def _b(): # pragma: no cover + _b = 1 + return _c() + + +def _c(): # pragma: no cover + _c = 1 + return [ + EvalEnvironment.capture(), + EvalEnvironment.capture(0), + EvalEnvironment.capture(1), + EvalEnvironment.capture(0, reference=1), + EvalEnvironment.capture(2), + EvalEnvironment.capture(0, 2), + ] + + +def test_EvalEnvironment_capture_namespace(): + c0, c, b1, b2, a1, a2 = _a() + assert "test_EvalEnvironment_capture_namespace" in c0.namespace + assert "test_EvalEnvironment_capture_namespace" in c.namespace + assert "test_EvalEnvironment_capture_namespace" in b1.namespace + assert "test_EvalEnvironment_capture_namespace" in b2.namespace + assert "test_EvalEnvironment_capture_namespace" in a1.namespace + assert "test_EvalEnvironment_capture_namespace" in a2.namespace + assert c0.namespace["_c"] == 1 + assert c.namespace["_c"] == 1 + assert b1.namespace["_b"] == 1 + assert b2.namespace["_b"] == 1 + assert a1.namespace["_a"] == 1 + assert a2.namespace["_a"] == 1 + assert b1.namespace["_c"] is _c + assert b2.namespace["_c"] is _c + import pytest + + pytest.raises(ValueError, EvalEnvironment.capture, 10**6) + + assert EvalEnvironment.capture(b1) is b1 + + pytest.raises(TypeError, EvalEnvironment.capture, 1.2) + + assert_no_pickling(EvalEnvironment.capture()) + + +def test_EvalEnvironment_capture_flags(): + # This is the only __future__ feature currently usable in Python + # 3... fortunately it is probably not going anywhere. + TEST_FEATURE = "barry_as_FLUFL" + test_flag = getattr(__future__, TEST_FEATURE).compiler_flag + assert test_flag & _ALL_FUTURE_FLAGS + source = ( + "def f():\n" + " in_f = 'hi from f'\n" + " global RETURN_INNER, RETURN_OUTER, RETURN_INNER_FROM_OUTER\n" + " RETURN_INNER = EvalEnvironment.capture(0)\n" + " RETURN_OUTER = call_capture_0()\n" + " RETURN_INNER_FROM_OUTER = call_capture_1()\n" + "f()\n" + ) + code = compile(source, "", "exec", 0, 1) + env = { + "EvalEnvironment": EvalEnvironment, + "call_capture_0": lambda: EvalEnvironment.capture(0), + "call_capture_1": lambda: EvalEnvironment.capture(1), + } + env2 = dict(env) + exec(code, env) + assert env["RETURN_INNER"].namespace["in_f"] == "hi from f" + assert env["RETURN_INNER_FROM_OUTER"].namespace["in_f"] == "hi from f" + assert "in_f" not in env["RETURN_OUTER"].namespace + assert env["RETURN_INNER"].flags & _ALL_FUTURE_FLAGS == 0 + assert env["RETURN_OUTER"].flags & _ALL_FUTURE_FLAGS == 0 + assert env["RETURN_INNER_FROM_OUTER"].flags & _ALL_FUTURE_FLAGS == 0 + + code2 = compile( + ("from __future__ import %s\n" % (TEST_FEATURE,)) + source, + "", + "exec", + 0, + 1, + ) + exec(code2, env2) + assert env2["RETURN_INNER"].namespace["in_f"] == "hi from f" + assert env2["RETURN_INNER_FROM_OUTER"].namespace["in_f"] == "hi from f" + assert "in_f" not in env2["RETURN_OUTER"].namespace + assert env2["RETURN_INNER"].flags & _ALL_FUTURE_FLAGS == test_flag + assert env2["RETURN_OUTER"].flags & _ALL_FUTURE_FLAGS == 0 + assert env2["RETURN_INNER_FROM_OUTER"].flags & _ALL_FUTURE_FLAGS == test_flag + + +def test_EvalEnvironment_eval_namespace(): + env = EvalEnvironment([{"a": 1}]) + assert env.eval("2 * a") == 2 + assert env.eval("2 * a", inner_namespace={"a": 2}) == 4 + import pytest + + pytest.raises(NameError, env.eval, "2 * b") + a = 3 + env2 = EvalEnvironment.capture(0) + assert env2.eval("2 * a") == 6 + + env3 = env.with_outer_namespace({"a": 10, "b": 3}) + assert env3.eval("2 * a") == 2 + assert env3.eval("2 * b") == 6 + + +def test_EvalEnvironment_eval_flags(): + import pytest + + # This joke __future__ statement replaces "!=" with "<>": + # http://www.python.org/dev/peps/pep-0401/ + test_flag = __future__.barry_as_FLUFL.compiler_flag + assert test_flag & _ALL_FUTURE_FLAGS + + env = EvalEnvironment([{"a": 11}], flags=0) + assert env.eval("a != 0") == True + pytest.raises(SyntaxError, env.eval, "a <> 0") + assert env.subset(["a"]).flags == 0 + assert env.with_outer_namespace({"b": 10}).flags == 0 + + env2 = EvalEnvironment([{"a": 11}], flags=test_flag) + assert env2.eval("a <> 0") == True + pytest.raises(SyntaxError, env2.eval, "a != 0") + assert env2.subset(["a"]).flags == test_flag + assert env2.with_outer_namespace({"b": 10}).flags == test_flag + + +def test_EvalEnvironment_subset(): + env = EvalEnvironment([{"a": 1}, {"b": 2}, {"c": 3}]) + + subset_a = env.subset(["a"]) + assert subset_a.eval("a") == 1 + import pytest + + pytest.raises(NameError, subset_a.eval, "b") + pytest.raises(NameError, subset_a.eval, "c") + + subset_bc = env.subset(["b", "c"]) + assert subset_bc.eval("b * c") == 6 + pytest.raises(NameError, subset_bc.eval, "a") + + +def test_EvalEnvironment_eq(): + import pytest + + if sys.version_info >= (3, 13): + pytest.skip( + "`frame.f_locals` may return write-through proxies in Python 3.13+, " + "breaking direct comparison by ids." + ) + + # Two environments are eq only if they refer to exactly the same + # global/local dicts + env1 = EvalEnvironment.capture(0) + env2 = EvalEnvironment.capture(0) + assert env1 == env2 + assert hash(env1) == hash(env2) + capture_local_env = lambda: EvalEnvironment.capture(0) + env3 = capture_local_env() + env4 = capture_local_env() + assert env3 != env4 + + +_builtins_dict = {} +exec("from patsy.builtins import *", {}, _builtins_dict) +# This is purely to make the existence of patsy.builtins visible to systems +# like py2app and py2exe. It's basically free, since the above line guarantees +# that patsy.builtins will be present in sys.modules in any case. +import patsy.builtins + + +class EvalFactor(object): + def __init__(self, code, origin=None): + """A factor class that executes arbitrary Python code and supports + stateful transforms. + + :arg code: A string containing a Python expression, that will be + evaluated to produce this factor's value. + + This is the standard factor class that is used when parsing formula + strings and implements the standard stateful transform processing. See + :ref:`stateful-transforms` and :ref:`expert-model-specification`. + + Two EvalFactor's are considered equal (e.g., for purposes of + redundancy detection) if they contain the same token stream. Basically + this means that the source code must be identical except for + whitespace:: + + assert EvalFactor("a + b") == EvalFactor("a+b") + assert EvalFactor("a + b") != EvalFactor("b + a") + """ + + # For parsed formulas, the code will already have been normalized by + # the parser. But let's normalize anyway, so we can be sure of having + # consistent semantics for __eq__ and __hash__. + self.code = normalize_token_spacing(code) + self.origin = origin + + def name(self): + return self.code + + def __repr__(self): + return "%s(%r)" % (self.__class__.__name__, self.code) + + def __eq__(self, other): + return isinstance(other, EvalFactor) and self.code == other.code + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash((EvalFactor, self.code)) + + def memorize_passes_needed(self, state, eval_env): + # 'state' is just an empty dict which we can do whatever we want with, + # and that will be passed back to later memorize functions + state["transforms"] = {} + + eval_env = eval_env.with_outer_namespace(_builtins_dict) + env_namespace = eval_env.namespace + subset_names = [name for name in ast_names(self.code) if name in env_namespace] + eval_env = eval_env.subset(subset_names) + state["eval_env"] = eval_env + + # example code: == "2 * center(x)" + i = [0] + + def new_name_maker(token): + value = eval_env.namespace.get(token) + if hasattr(value, "__patsy_stateful_transform__"): + obj_name = "_patsy_stobj%s__%s__" % (i[0], token) + i[0] += 1 + obj = value.__patsy_stateful_transform__() + state["transforms"][obj_name] = obj + return obj_name + ".transform" + else: + return token + + # example eval_code: == "2 * _patsy_stobj0__center__.transform(x)" + eval_code = replace_bare_funcalls(self.code, new_name_maker) + state["eval_code"] = eval_code + # paranoia: verify that none of our new names appeared anywhere in the + # original code + if has_bare_variable_reference(state["transforms"], self.code): + raise PatsyError( + "names of this form are reserved for " "internal use (%s)" % (token,), + token.origin, + ) + # Pull out all the '_patsy_stobj0__center__.transform(x)' pieces + # to make '_patsy_stobj0__center__.memorize_chunk(x)' pieces + state["memorize_code"] = {} + for obj_name in state["transforms"]: + transform_calls = capture_obj_method_calls(obj_name, eval_code) + assert len(transform_calls) == 1 + transform_call = transform_calls[0] + transform_call_name, transform_call_code = transform_call + assert transform_call_name == obj_name + ".transform" + assert transform_call_code.startswith(transform_call_name + "(") + memorize_code = ( + obj_name + + ".memorize_chunk" + + transform_call_code[len(transform_call_name) :] + ) + state["memorize_code"][obj_name] = memorize_code + # Then sort the codes into bins, so that every item in bin number i + # depends only on items in bin (i-1) or less. (By 'depends', we mean + # that in something like: + # spline(center(x)) + # we have to first run: + # center.memorize_chunk(x) + # then + # center.memorize_finish(x) + # and only then can we run: + # spline.memorize_chunk(center.transform(x)) + # Since all of our objects have unique names, figuring out who + # depends on who is pretty easy -- we just check whether the + # memorization code for spline: + # spline.memorize_chunk(center.transform(x)) + # mentions the variable 'center' (which in the example, of course, it + # does). + pass_bins = [] + unsorted = set(state["transforms"]) + while unsorted: + pass_bin = set() + for obj_name in unsorted: + other_objs = unsorted.difference([obj_name]) + memorize_code = state["memorize_code"][obj_name] + if not has_bare_variable_reference(other_objs, memorize_code): + pass_bin.add(obj_name) + assert pass_bin + unsorted.difference_update(pass_bin) + pass_bins.append(pass_bin) + state["pass_bins"] = pass_bins + + return len(pass_bins) + + def _eval(self, code, memorize_state, data): + inner_namespace = VarLookupDict([data, memorize_state["transforms"]]) + return call_and_wrap_exc( + "Error evaluating factor", + self, + memorize_state["eval_env"].eval, + code, + inner_namespace=inner_namespace, + ) + + def memorize_chunk(self, state, which_pass, data): + for obj_name in state["pass_bins"][which_pass]: + self._eval(state["memorize_code"][obj_name], state, data) + + def memorize_finish(self, state, which_pass): + for obj_name in state["pass_bins"][which_pass]: + state["transforms"][obj_name].memorize_finish() + + def eval(self, memorize_state, data): + return self._eval(memorize_state["eval_code"], memorize_state, data) + + __getstate__ = no_pickling + + +def test_EvalFactor_basics(): + e = EvalFactor("a+b") + assert e.code == "a + b" + assert e.name() == "a + b" + e2 = EvalFactor("a +b", origin="asdf") + assert e == e2 + assert hash(e) == hash(e2) + assert e.origin is None + assert e2.origin == "asdf" + + assert_no_pickling(e) + + +def test_EvalFactor_memorize_passes_needed(): + from patsy.state import stateful_transform + + foo = stateful_transform(lambda: "FOO-OBJ") + bar = stateful_transform(lambda: "BAR-OBJ") + quux = stateful_transform(lambda: "QUUX-OBJ") + e = EvalFactor("foo(x) + bar(foo(y)) + quux(z, w)") + + state = {} + eval_env = EvalEnvironment.capture(0) + passes = e.memorize_passes_needed(state, eval_env) + print(passes) + print(state) + assert passes == 2 + for name in ["foo", "bar", "quux"]: + assert state["eval_env"].namespace[name] is locals()[name] + for name in ["w", "x", "y", "z", "e", "state"]: + assert name not in state["eval_env"].namespace + assert state["transforms"] == { + "_patsy_stobj0__foo__": "FOO-OBJ", + "_patsy_stobj1__bar__": "BAR-OBJ", + "_patsy_stobj2__foo__": "FOO-OBJ", + "_patsy_stobj3__quux__": "QUUX-OBJ", + } + assert ( + state["eval_code"] == "_patsy_stobj0__foo__.transform(x)" + " + _patsy_stobj1__bar__.transform(" + "_patsy_stobj2__foo__.transform(y))" + " + _patsy_stobj3__quux__.transform(z, w)" + ) + + assert state["memorize_code"] == { + "_patsy_stobj0__foo__": "_patsy_stobj0__foo__.memorize_chunk(x)", + "_patsy_stobj1__bar__": "_patsy_stobj1__bar__.memorize_chunk(_patsy_stobj2__foo__.transform(y))", + "_patsy_stobj2__foo__": "_patsy_stobj2__foo__.memorize_chunk(y)", + "_patsy_stobj3__quux__": "_patsy_stobj3__quux__.memorize_chunk(z, w)", + } + assert state["pass_bins"] == [ + set(["_patsy_stobj0__foo__", "_patsy_stobj2__foo__", "_patsy_stobj3__quux__"]), + set(["_patsy_stobj1__bar__"]), + ] + + +class _MockTransform(object): + # Adds up all memorized data, then subtracts that sum from each datum + def __init__(self): + self._sum = 0 + self._memorize_chunk_called = 0 + self._memorize_finish_called = 0 + + def memorize_chunk(self, data): + self._memorize_chunk_called += 1 + import numpy as np + + self._sum += np.sum(data) + + def memorize_finish(self): + self._memorize_finish_called += 1 + + def transform(self, data): + return data - self._sum + + +def test_EvalFactor_end_to_end(): + from patsy.state import stateful_transform + + foo = stateful_transform(_MockTransform) + e = EvalFactor("foo(x) + foo(foo(y))") + state = {} + eval_env = EvalEnvironment.capture(0) + passes = e.memorize_passes_needed(state, eval_env) + print(passes) + print(state) + assert passes == 2 + assert state["eval_env"].namespace["foo"] is foo + for name in ["x", "y", "e", "state"]: + assert name not in state["eval_env"].namespace + import numpy as np + + e.memorize_chunk(state, 0, {"x": np.array([1, 2]), "y": np.array([10, 11])}) + assert state["transforms"]["_patsy_stobj0__foo__"]._memorize_chunk_called == 1 + assert state["transforms"]["_patsy_stobj2__foo__"]._memorize_chunk_called == 1 + e.memorize_chunk(state, 0, {"x": np.array([12, -10]), "y": np.array([100, 3])}) + assert state["transforms"]["_patsy_stobj0__foo__"]._memorize_chunk_called == 2 + assert state["transforms"]["_patsy_stobj2__foo__"]._memorize_chunk_called == 2 + assert state["transforms"]["_patsy_stobj0__foo__"]._memorize_finish_called == 0 + assert state["transforms"]["_patsy_stobj2__foo__"]._memorize_finish_called == 0 + e.memorize_finish(state, 0) + assert state["transforms"]["_patsy_stobj0__foo__"]._memorize_finish_called == 1 + assert state["transforms"]["_patsy_stobj2__foo__"]._memorize_finish_called == 1 + assert state["transforms"]["_patsy_stobj1__foo__"]._memorize_chunk_called == 0 + assert state["transforms"]["_patsy_stobj1__foo__"]._memorize_finish_called == 0 + e.memorize_chunk(state, 1, {"x": np.array([1, 2]), "y": np.array([10, 11])}) + e.memorize_chunk(state, 1, {"x": np.array([12, -10]), "y": np.array([100, 3])}) + e.memorize_finish(state, 1) + for transform in state["transforms"].values(): + assert transform._memorize_chunk_called == 2 + assert transform._memorize_finish_called == 1 + # sums: + # 0: 1 + 2 + 12 + -10 == 5 + # 2: 10 + 11 + 100 + 3 == 124 + # 1: (10 - 124) + (11 - 124) + (100 - 124) + (3 - 124) == -372 + # results: + # 0: -4, -3, 7, -15 + # 2: -114, -113, -24, -121 + # 1: 258, 259, 348, 251 + # 0 + 1: 254, 256, 355, 236 + assert np.all( + e.eval(state, {"x": np.array([1, 2, 12, -10]), "y": np.array([10, 11, 100, 3])}) + == [254, 256, 355, 236] + ) + + +def annotated_tokens(code): + prev_was_dot = False + it = PushbackAdapter(python_tokenize(code)) + for token_type, token, origin in it: + props = {} + props["bare_ref"] = not prev_was_dot and token_type == tokenize.NAME + props["bare_funcall"] = ( + props["bare_ref"] and it.has_more() and it.peek()[1] == "(" + ) + yield (token_type, token, origin, props) + prev_was_dot = token == "." + + +def test_annotated_tokens(): + tokens_without_origins = [ + (token_type, token, props) + for (token_type, token, origin, props) in (annotated_tokens("a(b) + c.d")) + ] + assert tokens_without_origins == [ + (tokenize.NAME, "a", {"bare_ref": True, "bare_funcall": True}), + (tokenize.OP, "(", {"bare_ref": False, "bare_funcall": False}), + (tokenize.NAME, "b", {"bare_ref": True, "bare_funcall": False}), + (tokenize.OP, ")", {"bare_ref": False, "bare_funcall": False}), + (tokenize.OP, "+", {"bare_ref": False, "bare_funcall": False}), + (tokenize.NAME, "c", {"bare_ref": True, "bare_funcall": False}), + (tokenize.OP, ".", {"bare_ref": False, "bare_funcall": False}), + (tokenize.NAME, "d", {"bare_ref": False, "bare_funcall": False}), + ] + + # This was a bug: + assert len(list(annotated_tokens("x"))) == 1 + + +def has_bare_variable_reference(names, code): + for _, token, _, props in annotated_tokens(code): + if props["bare_ref"] and token in names: + return True + return False + + +def replace_bare_funcalls(code, replacer): + tokens = [] + for token_type, token, origin, props in annotated_tokens(code): + if props["bare_ref"] and props["bare_funcall"]: + token = replacer(token) + tokens.append((token_type, token)) + return pretty_untokenize(tokens) + + +def test_replace_bare_funcalls(): + def replacer1(token): + return {"a": "b", "foo": "_internal.foo.process"}.get(token, token) + + def t1(code, expected): + replaced = replace_bare_funcalls(code, replacer1) + print("%r -> %r" % (code, replaced)) + print("(wanted %r)" % (expected,)) + assert replaced == expected + + t1("foobar()", "foobar()") + t1("a()", "b()") + t1("foobar.a()", "foobar.a()") + t1("foo()", "_internal.foo.process()") + t1("a + 1", "a + 1") + t1("b() + a() * x[foo(2 ** 3)]", "b() + b() * x[_internal.foo.process(2 ** 3)]") + + +class _FuncallCapturer(object): + # captures the next funcall + def __init__(self, start_token_type, start_token): + self.func = [start_token] + self.tokens = [(start_token_type, start_token)] + self.paren_depth = 0 + self.started = False + self.done = False + + def add_token(self, token_type, token): + if self.done: + return + self.tokens.append((token_type, token)) + if token in ["(", "{", "["]: + self.paren_depth += 1 + if token in [")", "}", "]"]: + self.paren_depth -= 1 + assert self.paren_depth >= 0 + if not self.started: + if token == "(": + self.started = True + else: + assert token_type == tokenize.NAME or token == "." + self.func.append(token) + if self.started and self.paren_depth == 0: + self.done = True + + +# This is not a very general function -- it assumes that all references to the +# given object are of the form '.something(method call)'. +def capture_obj_method_calls(obj_name, code): + capturers = [] + for token_type, token, origin, props in annotated_tokens(code): + for capturer in capturers: + capturer.add_token(token_type, token) + if props["bare_ref"] and token == obj_name: + capturers.append(_FuncallCapturer(token_type, token)) + return [ + ("".join(capturer.func), pretty_untokenize(capturer.tokens)) + for capturer in capturers + ] + + +def test_capture_obj_method_calls(): + assert capture_obj_method_calls("foo", "a + foo.baz(bar) + b.c(d)") == [ + ("foo.baz", "foo.baz(bar)") + ] + assert capture_obj_method_calls("b", "a + foo.baz(bar) + b.c(d)") == [ + ("b.c", "b.c(d)") + ] + assert capture_obj_method_calls("foo", "foo.bar(foo.baz(quux))") == [ + ("foo.bar", "foo.bar(foo.baz(quux))"), + ("foo.baz", "foo.baz(quux)"), + ] + assert capture_obj_method_calls("bar", "foo[bar.baz(x(z[asdf])) ** 2]") == [ + ("bar.baz", "bar.baz(x(z[asdf]))") + ] diff --git a/venv/lib/python3.10/site-packages/patsy/highlevel.py b/venv/lib/python3.10/site-packages/patsy/highlevel.py new file mode 100644 index 0000000000000000000000000000000000000000..43a000e6b15d11f08c4101846f3fc19b076a4def --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/highlevel.py @@ -0,0 +1,324 @@ +# This file is part of Patsy +# Copyright (C) 2011-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# These are made available in the patsy.* namespace: +__all__ = ["dmatrix", "dmatrices", "incr_dbuilder", "incr_dbuilders"] + +# problems: +# statsmodels reluctant to pass around separate eval environment, suggesting +# that design_and_matrices-equivalent should return a formula_like +# is ModelDesc really the high-level thing? +# ModelDesign doesn't work -- need to work with the builder set +# want to be able to return either a matrix or a pandas dataframe + +import numpy as np + +from patsy import PatsyError +from patsy.design_info import DesignMatrix, DesignInfo +from patsy.eval import EvalEnvironment +from patsy.desc import ModelDesc +from patsy.build import design_matrix_builders, build_design_matrices +from patsy.util import have_pandas, asarray_or_pandas, atleast_2d_column_default + +if have_pandas: + import pandas + + +# Tries to build a (lhs, rhs) design given a formula_like and an incremental +# data source. If formula_like is not capable of doing this, then returns +# None. +def _try_incr_builders(formula_like, data_iter_maker, eval_env, NA_action): + if isinstance(formula_like, DesignInfo): + return ( + design_matrix_builders([[]], data_iter_maker, eval_env, NA_action)[0], + formula_like, + ) + if ( + isinstance(formula_like, tuple) + and len(formula_like) == 2 + and isinstance(formula_like[0], DesignInfo) + and isinstance(formula_like[1], DesignInfo) + ): + return formula_like + if hasattr(formula_like, "__patsy_get_model_desc__"): + formula_like = formula_like.__patsy_get_model_desc__(eval_env) + if not isinstance(formula_like, ModelDesc): + raise PatsyError( + "bad value from %r.__patsy_get_model_desc__" % (formula_like,) + ) + # fallthrough + if isinstance(formula_like, str): + formula_like = ModelDesc.from_formula(formula_like) + # fallthrough + if isinstance(formula_like, ModelDesc): + assert isinstance(eval_env, EvalEnvironment) + return design_matrix_builders( + [formula_like.lhs_termlist, formula_like.rhs_termlist], + data_iter_maker, + eval_env, + NA_action, + ) + else: + return None + + +def incr_dbuilder(formula_like, data_iter_maker, eval_env=0, NA_action="drop"): + """Construct a design matrix builder incrementally from a large data set. + + :arg formula_like: Similar to :func:`dmatrix`, except that explicit + matrices are not allowed. Must be a formula string, a + :class:`ModelDesc`, a :class:`DesignInfo`, or an object with a + ``__patsy_get_model_desc__`` method. + :arg data_iter_maker: A zero-argument callable which returns an iterator + over dict-like data objects. This must be a callable rather than a + simple iterator because sufficiently complex formulas may require + multiple passes over the data (e.g. if there are nested stateful + transforms). + :arg eval_env: Either a :class:`EvalEnvironment` which will be used to + look up any variables referenced in `formula_like` that cannot be + found in `data`, or else a depth represented as an + integer which will be passed to :meth:`EvalEnvironment.capture`. + ``eval_env=0`` means to use the context of the function calling + :func:`incr_dbuilder` for lookups. If calling this function from a + library, you probably want ``eval_env=1``, which means that variables + should be resolved in *your* caller's namespace. + :arg NA_action: An :class:`NAAction` object or string, used to determine + what values count as 'missing' for purposes of determining the levels of + categorical factors. + :returns: A :class:`DesignInfo` + + Tip: for `data_iter_maker`, write a generator like:: + + def iter_maker(): + for data_chunk in my_data_store: + yield data_chunk + + and pass `iter_maker` (*not* `iter_maker()`). + + .. versionadded:: 0.2.0 + The ``NA_action`` argument. + """ + eval_env = EvalEnvironment.capture(eval_env, reference=1) + design_infos = _try_incr_builders( + formula_like, data_iter_maker, eval_env, NA_action + ) + if design_infos is None: + raise PatsyError("bad formula-like object") + if len(design_infos[0].column_names) > 0: + raise PatsyError( + "encountered outcome variables for a model " "that does not expect them" + ) + return design_infos[1] + + +def incr_dbuilders(formula_like, data_iter_maker, eval_env=0, NA_action="drop"): + """Construct two design matrix builders incrementally from a large data + set. + + :func:`incr_dbuilders` is to :func:`incr_dbuilder` as :func:`dmatrices` is + to :func:`dmatrix`. See :func:`incr_dbuilder` for details. + """ + eval_env = EvalEnvironment.capture(eval_env, reference=1) + design_infos = _try_incr_builders( + formula_like, data_iter_maker, eval_env, NA_action + ) + if design_infos is None: + raise PatsyError("bad formula-like object") + if len(design_infos[0].column_names) == 0: + raise PatsyError("model is missing required outcome variables") + return design_infos + + +# This always returns a length-two tuple, +# response, predictors +# where +# response is a DesignMatrix (possibly with 0 columns) +# predictors is a DesignMatrix +# The input 'formula_like' could be like: +# (np.ndarray, np.ndarray) +# (DesignMatrix, DesignMatrix) +# (None, DesignMatrix) +# np.ndarray # for predictor-only models +# DesignMatrix +# (None, np.ndarray) +# "y ~ x" +# ModelDesc(...) +# DesignInfo +# (DesignInfo, DesignInfo) +# any object with a special method __patsy_get_model_desc__ +def _do_highlevel_design(formula_like, data, eval_env, NA_action, return_type): + if return_type == "dataframe" and not have_pandas: + raise PatsyError( + "pandas.DataFrame was requested, but pandas " "is not installed" + ) + if return_type not in ("matrix", "dataframe"): + raise PatsyError( + "unrecognized output type %r, should be " + "'matrix' or 'dataframe'" % (return_type,) + ) + + def data_iter_maker(): + return iter([data]) + + design_infos = _try_incr_builders( + formula_like, data_iter_maker, eval_env, NA_action + ) + if design_infos is not None: + return build_design_matrices( + design_infos, data, NA_action=NA_action, return_type=return_type + ) + else: + # No builders, but maybe we can still get matrices + if isinstance(formula_like, tuple): + if len(formula_like) != 2: + raise PatsyError( + "don't know what to do with a length %s " + "matrices tuple" % (len(formula_like),) + ) + (lhs, rhs) = formula_like + else: + # subok=True is necessary here to allow DesignMatrixes to pass + # through + (lhs, rhs) = (None, asarray_or_pandas(formula_like, subok=True)) + + # some sort of explicit matrix or matrices were given. Currently we + # have them in one of these forms: + # -- an ndarray or subclass + # -- a DesignMatrix + # -- a pandas.Series + # -- a pandas.DataFrame + # and we have to produce a standard output format. + def _regularize_matrix(m, default_column_prefix): + di = DesignInfo.from_array(m, default_column_prefix) + if have_pandas and isinstance(m, (pandas.Series, pandas.DataFrame)): + orig_index = m.index + else: + orig_index = None + if return_type == "dataframe": + m = atleast_2d_column_default(m, preserve_pandas=True) + m = pandas.DataFrame(m) + m.columns = di.column_names + m.design_info = di + return (m, orig_index) + else: + return (DesignMatrix(m, di), orig_index) + + rhs, rhs_orig_index = _regularize_matrix(rhs, "x") + if lhs is None: + lhs = np.zeros((rhs.shape[0], 0), dtype=float) + lhs, lhs_orig_index = _regularize_matrix(lhs, "y") + + assert isinstance(getattr(lhs, "design_info", None), DesignInfo) + assert isinstance(getattr(rhs, "design_info", None), DesignInfo) + if lhs.shape[0] != rhs.shape[0]: + raise PatsyError( + "shape mismatch: outcome matrix has %s rows, " + "predictor matrix has %s rows" % (lhs.shape[0], rhs.shape[0]) + ) + if rhs_orig_index is not None and lhs_orig_index is not None: + if not rhs_orig_index.equals(lhs_orig_index): + raise PatsyError( + "index mismatch: outcome and " "predictor have incompatible indexes" + ) + if return_type == "dataframe": + if rhs_orig_index is not None and lhs_orig_index is None: + lhs.index = rhs.index + if rhs_orig_index is None and lhs_orig_index is not None: + rhs.index = lhs.index + return (lhs, rhs) + + +def dmatrix(formula_like, data={}, eval_env=0, NA_action="drop", return_type="matrix"): + """Construct a single design matrix given a formula_like and data. + + :arg formula_like: An object that can be used to construct a design + matrix. See below. + :arg data: A dict-like object that can be used to look up variables + referenced in `formula_like`. + :arg eval_env: Either a :class:`EvalEnvironment` which will be used to + look up any variables referenced in `formula_like` that cannot be + found in `data`, or else a depth represented as an + integer which will be passed to :meth:`EvalEnvironment.capture`. + ``eval_env=0`` means to use the context of the function calling + :func:`dmatrix` for lookups. If calling this function from a library, + you probably want ``eval_env=1``, which means that variables should be + resolved in *your* caller's namespace. + :arg NA_action: What to do with rows that contain missing values. You can + ``"drop"`` them, ``"raise"`` an error, or for customization, pass an + :class:`NAAction` object. See :class:`NAAction` for details on what + values count as 'missing' (and how to alter this). + :arg return_type: Either ``"matrix"`` or ``"dataframe"``. See below. + + The `formula_like` can take a variety of forms. You can use any of the + following: + + * (The most common option) A formula string like ``"x1 + x2"`` (for + :func:`dmatrix`) or ``"y ~ x1 + x2"`` (for :func:`dmatrices`). For + details see :ref:`formulas`. + * A :class:`ModelDesc`, which is a Python object representation of a + formula. See :ref:`formulas` and :ref:`expert-model-specification` for + details. + * A :class:`DesignInfo`. + * An object that has a method called :meth:`__patsy_get_model_desc__`. + For details see :ref:`expert-model-specification`. + * A numpy array_like (for :func:`dmatrix`) or a tuple + (array_like, array_like) (for :func:`dmatrices`). These will have + metadata added, representation normalized, and then be returned + directly. In this case `data` and `eval_env` are + ignored. There is special handling for two cases: + + * :class:`DesignMatrix` objects will have their :class:`DesignInfo` + preserved. This allows you to set up custom column names and term + information even if you aren't using the rest of the patsy + machinery. + * :class:`pandas.DataFrame` or :class:`pandas.Series` objects will have + their (row) indexes checked. If two are passed in, their indexes must + be aligned. If ``return_type="dataframe"``, then their indexes will be + preserved on the output. + + Regardless of the input, the return type is always either: + + * A :class:`DesignMatrix`, if ``return_type="matrix"`` (the default) + * A :class:`pandas.DataFrame`, if ``return_type="dataframe"``. + + The actual contents of the design matrix is identical in both cases, and + in both cases a :class:`DesignInfo` object will be available in a + ``.design_info`` attribute on the return value. However, for + ``return_type="dataframe"``, any pandas indexes on the input (either in + `data` or directly passed through `formula_like`) will be preserved, which + may be useful for e.g. time-series models. + + .. versionadded:: 0.2.0 + The ``NA_action`` argument. + """ + eval_env = EvalEnvironment.capture(eval_env, reference=1) + (lhs, rhs) = _do_highlevel_design( + formula_like, data, eval_env, NA_action, return_type + ) + if lhs.shape[1] != 0: + raise PatsyError( + "encountered outcome variables for a model " "that does not expect them" + ) + return rhs + + +def dmatrices( + formula_like, data={}, eval_env=0, NA_action="drop", return_type="matrix" +): + """Construct two design matrices given a formula_like and data. + + This function is identical to :func:`dmatrix`, except that it requires + (and returns) two matrices instead of one. By convention, the first matrix + is the "outcome" or "y" data, and the second is the "predictor" or "x" + data. + + See :func:`dmatrix` for details. + """ + eval_env = EvalEnvironment.capture(eval_env, reference=1) + (lhs, rhs) = _do_highlevel_design( + formula_like, data, eval_env, NA_action, return_type + ) + if lhs.shape[1] == 0: + raise PatsyError("model is missing required outcome variables") + return (lhs, rhs) diff --git a/venv/lib/python3.10/site-packages/patsy/infix_parser.py b/venv/lib/python3.10/site-packages/patsy/infix_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..6c127b534fff08951ada0097df5af6ea24fc33e0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/infix_parser.py @@ -0,0 +1,296 @@ +# This file is part of Patsy +# Copyright (C) 2011 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file implements a simple "shunting yard algorithm" parser for infix +# languages with parentheses. It is used as the core of our parser for +# formulas, but is generic enough to be used for other purposes as well +# (e.g. parsing linear constraints). It just builds a parse tree; semantics +# are somebody else's problem. +# +# Plus it spends energy on tracking where each item in the parse tree comes +# from, to allow high-quality error reporting. +# +# You are expected to provide an collection of Operators, a collection of +# atomic types, and an iterator that provides Tokens. Each Operator should +# have a unique token_type (which is an arbitrary Python object), and each +# Token should have a matching token_type, or one of the special types +# Token.LPAREN, Token.RPAREN. Each Token is required to have a valid Origin +# attached, for error reporting. + +# XX: still seriously consider putting the magic intercept handling into the +# tokenizer. we'd still need separate term-sets that get pasted together by ~ +# to create the modeldesc, though... heck maybe we should just have a +# modeldesc be 1-or-more termsets, with the convention that if it's 1, then +# it's a rhs, and if it's 2, it's (lhs, rhs), and otherwise you're on your +# own. Test: would this be useful for multiple-group log-linear models, +# maybe? Answer: Perhaps. outcome ~ x1 + x2 ~ group. But lots of other +# plausible, maybe better ways to write this -- (outcome | group) ~ x1 + x2? +# "outcome ~ x1 + x2", group="group"? etc. + +__all__ = ["Token", "ParseNode", "Operator", "parse"] + +from patsy import PatsyError +from patsy.origin import Origin +from patsy.util import ( + repr_pretty_delegate, + repr_pretty_impl, + no_pickling, + assert_no_pickling, +) + + +class _UniqueValue: + def __init__(self, print_as): + self._print_as = print_as + + def __repr__(self): + return "%s(%r)" % (self.__class__.__name__, self._print_as) + + __getstate__ = no_pickling + + +class Token: + """A token with possible payload. + + .. attribute:: type + + An arbitrary object indicating the type of this token. Should be + :term:`hashable`, but otherwise it can be whatever you like. + """ + + LPAREN = _UniqueValue("LPAREN") + RPAREN = _UniqueValue("RPAREN") + + def __init__(self, type, origin, extra=None): + self.type = type + self.origin = origin + self.extra = extra + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + assert not cycle + kwargs = [] + if self.extra is not None: + kwargs = [("extra", self.extra)] + return repr_pretty_impl(p, self, [self.type, self.origin], kwargs) + + __getstate__ = no_pickling + + +class ParseNode(object): + def __init__(self, type, token, args, origin): + self.type = type + self.token = token + self.args = args + self.origin = origin + + __repr__ = repr_pretty_delegate + + def _repr_pretty_(self, p, cycle): + return repr_pretty_impl(p, self, [self.type, self.token, self.args]) + + __getstate__ = no_pickling + + +class Operator(object): + def __init__(self, token_type, arity, precedence): + self.token_type = token_type + self.arity = arity + self.precedence = precedence + + def __repr__(self): + return "%s(%r, %r, %r)" % ( + self.__class__.__name__, + self.token_type, + self.arity, + self.precedence, + ) + + __getstate__ = no_pickling + + +class _StackOperator(object): + def __init__(self, op, token): + self.op = op + self.token = token + + __getstate__ = no_pickling + + +_open_paren = Operator(Token.LPAREN, -1, -9999999) + + +class _ParseContext(object): + def __init__(self, unary_ops, binary_ops, atomic_types, trace): + self.op_stack = [] + self.noun_stack = [] + self.unary_ops = unary_ops + self.binary_ops = binary_ops + self.atomic_types = atomic_types + self.trace = trace + + __getstate__ = no_pickling + + +def _read_noun_context(token, c): + if token.type == Token.LPAREN: + if c.trace: + print("Pushing open-paren") + c.op_stack.append(_StackOperator(_open_paren, token)) + return True + elif token.type in c.unary_ops: + if c.trace: + print("Pushing unary op %r" % (token.type,)) + c.op_stack.append(_StackOperator(c.unary_ops[token.type], token)) + return True + elif token.type in c.atomic_types: + if c.trace: + print("Pushing noun %r (%r)" % (token.type, token.extra)) + c.noun_stack.append(ParseNode(token.type, token, [], token.origin)) + return False + else: + raise PatsyError( + "expected a noun, not '%s'" % (token.origin.relevant_code(),), token + ) + + +def _run_op(c): + assert c.op_stack + stackop = c.op_stack.pop() + args = [] + for i in range(stackop.op.arity): + args.append(c.noun_stack.pop()) + args.reverse() + if c.trace: + print("Reducing %r (%r)" % (stackop.op.token_type, args)) + node = ParseNode( + stackop.op.token_type, + stackop.token, + args, + Origin.combine([stackop.token] + args), + ) + c.noun_stack.append(node) + + +def _read_op_context(token, c): + if token.type == Token.RPAREN: + if c.trace: + print("Found close-paren") + while c.op_stack and c.op_stack[-1].op.token_type != Token.LPAREN: + _run_op(c) + if not c.op_stack: + raise PatsyError("missing '(' or extra ')'", token) + assert c.op_stack[-1].op.token_type == Token.LPAREN + # Expand the origin of the item on top of the noun stack to include + # the open and close parens: + combined = Origin.combine([c.op_stack[-1].token, c.noun_stack[-1].token, token]) + c.noun_stack[-1].origin = combined + # Pop the open-paren + c.op_stack.pop() + return False + elif token.type in c.binary_ops: + if c.trace: + print("Found binary operator %r" % (token.type)) + stackop = _StackOperator(c.binary_ops[token.type], token) + while c.op_stack and stackop.op.precedence <= c.op_stack[-1].op.precedence: + _run_op(c) + if c.trace: + print("Pushing binary operator %r" % (token.type)) + c.op_stack.append(stackop) + return True + else: + raise PatsyError( + "expected an operator, not '%s'" % (token.origin.relevant_code(),), token + ) + + +def infix_parse(tokens, operators, atomic_types, trace=False): + token_source = iter(tokens) + + unary_ops = {} + binary_ops = {} + for op in operators: + assert op.precedence > _open_paren.precedence + if op.arity == 1: + unary_ops[op.token_type] = op + elif op.arity == 2: + binary_ops[op.token_type] = op + else: + raise ValueError("operators must be unary or binary") + + c = _ParseContext(unary_ops, binary_ops, atomic_types, trace) + + # This is an implementation of Dijkstra's shunting yard algorithm: + # http://en.wikipedia.org/wiki/Shunting_yard_algorithm + # http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm + + want_noun = True + for token in token_source: + if c.trace: + print("Reading next token (want_noun=%r)" % (want_noun,)) + if want_noun: + want_noun = _read_noun_context(token, c) + else: + want_noun = _read_op_context(token, c) + if c.trace: + print("End of token stream") + + if want_noun: + raise PatsyError( + "expected a noun, but instead the expression ended", + c.op_stack[-1].token.origin, + ) + + while c.op_stack: + if c.op_stack[-1].op.token_type == Token.LPAREN: + raise PatsyError("Unmatched '('", c.op_stack[-1].token) + _run_op(c) + + assert len(c.noun_stack) == 1 + return c.noun_stack.pop() + + +# Much more thorough tests in parse_formula.py, this is just a smoke test: +def test_infix_parse(): + ops = [Operator("+", 2, 10), Operator("*", 2, 20), Operator("-", 1, 30)] + atomic = ["ATOM1", "ATOM2"] + # a + -b * (c + d) + mock_origin = Origin("asdf", 2, 3) + tokens = [ + Token("ATOM1", mock_origin, "a"), + Token("+", mock_origin, "+"), + Token("-", mock_origin, "-"), + Token("ATOM2", mock_origin, "b"), + Token("*", mock_origin, "*"), + Token(Token.LPAREN, mock_origin, "("), + Token("ATOM1", mock_origin, "c"), + Token("+", mock_origin, "+"), + Token("ATOM2", mock_origin, "d"), + Token(Token.RPAREN, mock_origin, ")"), + ] + tree = infix_parse(tokens, ops, atomic) + + def te(tree, type, extra): + assert tree.type == type + assert tree.token.extra == extra + + te(tree, "+", "+") + te(tree.args[0], "ATOM1", "a") + assert tree.args[0].args == [] + te(tree.args[1], "*", "*") + te(tree.args[1].args[0], "-", "-") + assert len(tree.args[1].args[0].args) == 1 + te(tree.args[1].args[0].args[0], "ATOM2", "b") + te(tree.args[1].args[1], "+", "+") + te(tree.args[1].args[1].args[0], "ATOM1", "c") + te(tree.args[1].args[1].args[1], "ATOM2", "d") + + import pytest + + # No ternary ops + pytest.raises(ValueError, infix_parse, [], [Operator("+", 3, 10)], ["ATOMIC"]) + + # smoke test just to make sure there are no egregious bugs in 'trace' + infix_parse(tokens, ops, atomic, trace=True) diff --git a/venv/lib/python3.10/site-packages/patsy/mgcv_cubic_splines.py b/venv/lib/python3.10/site-packages/patsy/mgcv_cubic_splines.py new file mode 100644 index 0000000000000000000000000000000000000000..7acaa38b4be9ddb44d82dd6534e101c4154fec2a --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/mgcv_cubic_splines.py @@ -0,0 +1,1253 @@ +# This file is part of Patsy +# Copyright (C) 2014 GDF Suez, http://www.gdfsuez.com/ +# See file LICENSE.txt for license information. + +# R package 'mgcv' compatible cubic spline basis functions + +# These are made available in the patsy.* namespace +__all__ = ["cr", "cc", "te"] + +import numpy as np + +from patsy.util import ( + have_pandas, + atleast_2d_column_default, + no_pickling, + assert_no_pickling, + safe_string_eq, +) +from patsy.state import stateful_transform + +if have_pandas: + import pandas + + +def _get_natural_f(knots): + """Returns mapping of natural cubic spline values to 2nd derivatives. + + .. note:: See 'Generalized Additive Models', Simon N. Wood, 2006, pp 145-146 + + :param knots: The 1-d array knots used for cubic spline parametrization, + must be sorted in ascending order. + :return: A 2-d array mapping natural cubic spline values at + knots to second derivatives. + + :raise ImportError: if scipy is not found, required for + ``linalg.solve_banded()`` + """ + try: + from scipy import linalg + except ImportError: # pragma: no cover + raise ImportError("Cubic spline functionality requires scipy.") + + h = knots[1:] - knots[:-1] + diag = (h[:-1] + h[1:]) / 3.0 + ul_diag = h[1:-1] / 6.0 + banded_b = np.array([np.r_[0.0, ul_diag], diag, np.r_[ul_diag, 0.0]]) + d = np.zeros((knots.size - 2, knots.size)) + for i in range(knots.size - 2): + d[i, i] = 1.0 / h[i] + d[i, i + 2] = 1.0 / h[i + 1] + d[i, i + 1] = -d[i, i] - d[i, i + 2] + + fm = linalg.solve_banded((1, 1), banded_b, d) + + return np.vstack([np.zeros(knots.size), fm, np.zeros(knots.size)]) + + +# Cyclic Cubic Regression Splines + + +def _map_cyclic(x, lbound, ubound): + """Maps values into the interval [lbound, ubound] in a cyclic fashion. + + :param x: The 1-d array values to be mapped. + :param lbound: The lower bound of the interval. + :param ubound: The upper bound of the interval. + :return: A new 1-d array containing mapped x values. + + :raise ValueError: if lbound >= ubound. + """ + if lbound >= ubound: + raise ValueError( + "Invalid argument: lbound (%r) should be " + "less than ubound (%r)." % (lbound, ubound) + ) + + x = np.copy(x) + x[x > ubound] = lbound + (x[x > ubound] - ubound) % (ubound - lbound) + x[x < lbound] = ubound - (lbound - x[x < lbound]) % (ubound - lbound) + + return x + + +def test__map_cyclic(): + x = np.array([1.5, 2.6, 0.1, 4.4, 10.7]) + x_orig = np.copy(x) + expected_mapped_x = np.array([3.0, 2.6, 3.1, 2.9, 3.2]) + mapped_x = _map_cyclic(x, 2.1, 3.6) + assert np.allclose(x, x_orig) + assert np.allclose(mapped_x, expected_mapped_x) + + +def test__map_cyclic_errors(): + import pytest + + x = np.linspace(0.2, 5.7, 10) + pytest.raises(ValueError, _map_cyclic, x, 4.5, 3.6) + pytest.raises(ValueError, _map_cyclic, x, 4.5, 4.5) + + +def _get_cyclic_f(knots): + """Returns mapping of cyclic cubic spline values to 2nd derivatives. + + .. note:: See 'Generalized Additive Models', Simon N. Wood, 2006, pp 146-147 + + :param knots: The 1-d array knots used for cubic spline parametrization, + must be sorted in ascending order. + :return: A 2-d array mapping cyclic cubic spline values at + knots to second derivatives. + """ + h = knots[1:] - knots[:-1] + n = knots.size - 1 + b = np.zeros((n, n)) + d = np.zeros((n, n)) + + b[0, 0] = (h[n - 1] + h[0]) / 3.0 + b[0, n - 1] = h[n - 1] / 6.0 + b[n - 1, 0] = h[n - 1] / 6.0 + + d[0, 0] = -1.0 / h[0] - 1.0 / h[n - 1] + d[0, n - 1] = 1.0 / h[n - 1] + d[n - 1, 0] = 1.0 / h[n - 1] + + for i in range(1, n): + b[i, i] = (h[i - 1] + h[i]) / 3.0 + b[i, i - 1] = h[i - 1] / 6.0 + b[i - 1, i] = h[i - 1] / 6.0 + + d[i, i] = -1.0 / h[i - 1] - 1.0 / h[i] + d[i, i - 1] = 1.0 / h[i - 1] + d[i - 1, i] = 1.0 / h[i - 1] + + return np.linalg.solve(b, d) + + +# Tensor Product + + +def _row_tensor_product(dms): + """Computes row-wise tensor product of given arguments. + + .. note:: Custom algorithm to precisely match what is done in 'mgcv', + in particular look out for order of result columns! + For reference implementation see 'mgcv' source code, + file 'mat.c', mgcv_tensor_mm(), l.62 + + :param dms: A sequence of 2-d arrays (marginal design matrices). + :return: The 2-d array row-wise tensor product of given arguments. + + :raise ValueError: if argument sequence is empty, does not contain only + 2-d arrays or if the arrays number of rows does not match. + """ + if len(dms) == 0: + raise ValueError("Tensor product arrays sequence should not be empty.") + for dm in dms: + if dm.ndim != 2: + raise ValueError("Tensor product arguments should be 2-d arrays.") + + tp_nrows = dms[0].shape[0] + tp_ncols = 1 + for dm in dms: + if dm.shape[0] != tp_nrows: + raise ValueError( + "Tensor product arguments should have " "same number of rows." + ) + tp_ncols *= dm.shape[1] + tp = np.zeros((tp_nrows, tp_ncols)) + tp[:, -dms[-1].shape[1] :] = dms[-1] + filled_tp_ncols = dms[-1].shape[1] + for dm in dms[-2::-1]: + p = -filled_tp_ncols * dm.shape[1] + for j in range(dm.shape[1]): + xj = dm[:, j] + for t in range(-filled_tp_ncols, 0): + tp[:, p] = tp[:, t] * xj + p += 1 + filled_tp_ncols *= dm.shape[1] + + return tp + + +def test__row_tensor_product_errors(): + import pytest + + pytest.raises(ValueError, _row_tensor_product, []) + pytest.raises(ValueError, _row_tensor_product, [np.arange(1, 5)]) + pytest.raises(ValueError, _row_tensor_product, [np.arange(1, 5), np.arange(1, 5)]) + pytest.raises( + ValueError, + _row_tensor_product, + [np.arange(1, 13).reshape((3, 4)), np.arange(1, 13).reshape((4, 3))], + ) + + +def test__row_tensor_product(): + # Testing cases where main input array should not be modified + dm1 = np.arange(1, 17).reshape((4, 4)) + assert np.array_equal(_row_tensor_product([dm1]), dm1) + ones = np.ones(4).reshape((4, 1)) + tp1 = _row_tensor_product([ones, dm1]) + assert np.array_equal(tp1, dm1) + tp2 = _row_tensor_product([dm1, ones]) + assert np.array_equal(tp2, dm1) + + # Testing cases where main input array should be scaled + twos = 2 * ones + tp3 = _row_tensor_product([twos, dm1]) + assert np.array_equal(tp3, 2 * dm1) + tp4 = _row_tensor_product([dm1, twos]) + assert np.array_equal(tp4, 2 * dm1) + + # Testing main cases + dm2 = np.array([[1, 2], [1, 2]]) + dm3 = np.arange(1, 7).reshape((2, 3)) + expected_tp5 = np.array([[1, 2, 3, 2, 4, 6], [4, 5, 6, 8, 10, 12]]) + tp5 = _row_tensor_product([dm2, dm3]) + assert np.array_equal(tp5, expected_tp5) + expected_tp6 = np.array([[1, 2, 2, 4, 3, 6], [4, 8, 5, 10, 6, 12]]) + tp6 = _row_tensor_product([dm3, dm2]) + assert np.array_equal(tp6, expected_tp6) + + +# Common code + + +def _find_knots_lower_bounds(x, knots): + """Finds knots lower bounds for given values. + + Returns an array of indices ``I`` such that + ``0 <= I[i] <= knots.size - 2`` for all ``i`` + and + ``knots[I[i]] < x[i] <= knots[I[i] + 1]`` if + ``np.min(knots) < x[i] <= np.max(knots)``, + ``I[i] = 0`` if ``x[i] <= np.min(knots)`` + ``I[i] = knots.size - 2`` if ``np.max(knots) < x[i]`` + + :param x: The 1-d array values whose knots lower bounds are to be found. + :param knots: The 1-d array knots used for cubic spline parametrization, + must be sorted in ascending order. + :return: An array of knots lower bounds indices. + """ + lb = np.searchsorted(knots, x) - 1 + + # I[i] = 0 for x[i] <= np.min(knots) + lb[lb == -1] = 0 + + # I[i] = knots.size - 2 for x[i] > np.max(knots) + lb[lb == knots.size - 1] = knots.size - 2 + + return lb + + +def _compute_base_functions(x, knots): + """Computes base functions used for building cubic splines basis. + + .. note:: See 'Generalized Additive Models', Simon N. Wood, 2006, p. 146 + and for the special treatment of ``x`` values outside ``knots`` range + see 'mgcv' source code, file 'mgcv.c', function 'crspl()', l.249 + + :param x: The 1-d array values for which base functions should be computed. + :param knots: The 1-d array knots used for cubic spline parametrization, + must be sorted in ascending order. + :return: 4 arrays corresponding to the 4 base functions ajm, ajp, cjm, cjp + + the 1-d array of knots lower bounds indices corresponding to + the given ``x`` values. + """ + j = _find_knots_lower_bounds(x, knots) + + h = knots[1:] - knots[:-1] + hj = h[j] + xj1_x = knots[j + 1] - x + x_xj = x - knots[j] + + ajm = xj1_x / hj + ajp = x_xj / hj + + cjm_3 = xj1_x * xj1_x * xj1_x / (6.0 * hj) + cjm_3[x > np.max(knots)] = 0.0 + cjm_1 = hj * xj1_x / 6.0 + cjm = cjm_3 - cjm_1 + + cjp_3 = x_xj * x_xj * x_xj / (6.0 * hj) + cjp_3[x < np.min(knots)] = 0.0 + cjp_1 = hj * x_xj / 6.0 + cjp = cjp_3 - cjp_1 + + return ajm, ajp, cjm, cjp, j + + +def _absorb_constraints(design_matrix, constraints): + """Absorb model parameters constraints into the design matrix. + + :param design_matrix: The (2-d array) initial design matrix. + :param constraints: The 2-d array defining initial model parameters + (``betas``) constraints (``np.dot(constraints, betas) = 0``). + :return: The new design matrix with absorbed parameters constraints. + + :raise ImportError: if scipy is not found, used for ``scipy.linalg.qr()`` + which is cleaner than numpy's version requiring a call like + ``qr(..., mode='complete')`` to get a full QR decomposition. + """ + try: + from scipy import linalg + except ImportError: # pragma: no cover + raise ImportError("Cubic spline functionality requires scipy.") + + m = constraints.shape[0] + q, r = linalg.qr(np.transpose(constraints)) + + return np.dot(design_matrix, q[:, m:]) + + +def _get_free_crs_dmatrix(x, knots, cyclic=False): + """Builds an unconstrained cubic regression spline design matrix. + + Returns design matrix with dimensions ``len(x) x n`` + for a cubic regression spline smoother + where + - ``n = len(knots)`` for natural CRS + - ``n = len(knots) - 1`` for cyclic CRS + + .. note:: See 'Generalized Additive Models', Simon N. Wood, 2006, p. 145 + + :param x: The 1-d array values. + :param knots: The 1-d array knots used for cubic spline parametrization, + must be sorted in ascending order. + :param cyclic: Indicates whether used cubic regression splines should + be cyclic or not. Default is ``False``. + :return: The (2-d array) design matrix. + """ + n = knots.size + if cyclic: + x = _map_cyclic(x, min(knots), max(knots)) + n -= 1 + + ajm, ajp, cjm, cjp, j = _compute_base_functions(x, knots) + + j1 = j + 1 + if cyclic: + j1[j1 == n] = 0 + + i = np.identity(n) + + if cyclic: + f = _get_cyclic_f(knots) + else: + f = _get_natural_f(knots) + + dmt = ajm * i[j, :].T + ajp * i[j1, :].T + cjm * f[j, :].T + cjp * f[j1, :].T + + return dmt.T + + +def _get_crs_dmatrix(x, knots, constraints=None, cyclic=False): + """Builds a cubic regression spline design matrix. + + Returns design matrix with dimensions len(x) x n + where: + - ``n = len(knots) - nrows(constraints)`` for natural CRS + - ``n = len(knots) - nrows(constraints) - 1`` for cyclic CRS + for a cubic regression spline smoother + + :param x: The 1-d array values. + :param knots: The 1-d array knots used for cubic spline parametrization, + must be sorted in ascending order. + :param constraints: The 2-d array defining model parameters (``betas``) + constraints (``np.dot(constraints, betas) = 0``). + :param cyclic: Indicates whether used cubic regression splines should + be cyclic or not. Default is ``False``. + :return: The (2-d array) design matrix. + """ + dm = _get_free_crs_dmatrix(x, knots, cyclic) + if constraints is not None: + dm = _absorb_constraints(dm, constraints) + + return dm + + +def _get_te_dmatrix(design_matrices, constraints=None): + """Builds tensor product design matrix, given the marginal design matrices. + + :param design_matrices: A sequence of 2-d arrays (marginal design matrices). + :param constraints: The 2-d array defining model parameters (``betas``) + constraints (``np.dot(constraints, betas) = 0``). + :return: The (2-d array) design matrix. + """ + dm = _row_tensor_product(design_matrices) + if constraints is not None: + dm = _absorb_constraints(dm, constraints) + + return dm + + +# Stateful Transforms + + +def _get_all_sorted_knots( + x, n_inner_knots=None, inner_knots=None, lower_bound=None, upper_bound=None +): + """Gets all knots locations with lower and upper exterior knots included. + + If needed, inner knots are computed as equally spaced quantiles of the + input data falling between given lower and upper bounds. + + :param x: The 1-d array data values. + :param n_inner_knots: Number of inner knots to compute. + :param inner_knots: Provided inner knots if any. + :param lower_bound: The lower exterior knot location. If unspecified, the + minimum of ``x`` values is used. + :param upper_bound: The upper exterior knot location. If unspecified, the + maximum of ``x`` values is used. + :return: The array of ``n_inner_knots + 2`` distinct knots. + + :raise ValueError: for various invalid parameters sets or if unable to + compute ``n_inner_knots + 2`` distinct knots. + """ + if lower_bound is None and x.size == 0: + raise ValueError( + "Cannot set lower exterior knot location: empty " + "input data and lower_bound not specified." + ) + elif lower_bound is None and x.size != 0: + lower_bound = np.min(x) + + if upper_bound is None and x.size == 0: + raise ValueError( + "Cannot set upper exterior knot location: empty " + "input data and upper_bound not specified." + ) + elif upper_bound is None and x.size != 0: + upper_bound = np.max(x) + + if upper_bound < lower_bound: + raise ValueError( + "lower_bound > upper_bound (%r > %r)" % (lower_bound, upper_bound) + ) + + if inner_knots is None and n_inner_knots is not None: + if n_inner_knots < 0: + raise ValueError( + "Invalid requested number of inner knots: %r" % (n_inner_knots,) + ) + + x = x[(lower_bound <= x) & (x <= upper_bound)] + x = np.unique(x) + + if x.size != 0: + inner_knots_q = np.linspace(0, 100, n_inner_knots + 2)[1:-1] + # .tolist() is necessary to work around a bug in numpy 1.8 + inner_knots = np.asarray(np.percentile(x, inner_knots_q.tolist())) + elif n_inner_knots == 0: + inner_knots = np.array([]) + else: + raise ValueError( + "No data values between lower_bound(=%r) and " + "upper_bound(=%r): cannot compute requested " + "%r inner knot(s)." % (lower_bound, upper_bound, n_inner_knots) + ) + elif inner_knots is not None: + inner_knots = np.unique(inner_knots) + if n_inner_knots is not None and n_inner_knots != inner_knots.size: + raise ValueError( + "Needed number of inner knots=%r does not match " + "provided number of inner knots=%r." % (n_inner_knots, inner_knots.size) + ) + n_inner_knots = inner_knots.size + if np.any(inner_knots < lower_bound): + raise ValueError( + "Some knot values (%s) fall below lower bound " + "(%r)." % (inner_knots[inner_knots < lower_bound], lower_bound) + ) + if np.any(inner_knots > upper_bound): + raise ValueError( + "Some knot values (%s) fall above upper bound " + "(%r)." % (inner_knots[inner_knots > upper_bound], upper_bound) + ) + else: + raise ValueError("Must specify either 'n_inner_knots' or 'inner_knots'.") + + all_knots = np.concatenate(([lower_bound, upper_bound], inner_knots)) + all_knots = np.unique(all_knots) + if all_knots.size != n_inner_knots + 2: + raise ValueError( + "Unable to compute n_inner_knots(=%r) + 2 distinct " + "knots: %r data value(s) found between " + "lower_bound(=%r) and upper_bound(=%r)." + % (n_inner_knots, x.size, lower_bound, upper_bound) + ) + + return all_knots + + +def test__get_all_sorted_knots(): + import pytest + + pytest.raises(ValueError, _get_all_sorted_knots, np.array([]), -1) + pytest.raises(ValueError, _get_all_sorted_knots, np.array([]), 0) + pytest.raises(ValueError, _get_all_sorted_knots, np.array([]), 0, lower_bound=1) + pytest.raises(ValueError, _get_all_sorted_knots, np.array([]), 0, upper_bound=5) + pytest.raises( + ValueError, _get_all_sorted_knots, np.array([]), 0, lower_bound=3, upper_bound=1 + ) + assert np.array_equal( + _get_all_sorted_knots(np.array([]), 0, lower_bound=1, upper_bound=5), [1, 5] + ) + pytest.raises( + ValueError, _get_all_sorted_knots, np.array([]), 0, lower_bound=1, upper_bound=1 + ) + x = np.arange(6) * 2 + pytest.raises(ValueError, _get_all_sorted_knots, x, -2) + assert np.array_equal(_get_all_sorted_knots(x, 0), [0, 10]) + assert np.array_equal( + _get_all_sorted_knots(x, 0, lower_bound=3, upper_bound=8), [3, 8] + ) + assert np.array_equal( + _get_all_sorted_knots(x, 2, lower_bound=1, upper_bound=9), [1, 4, 6, 9] + ) + pytest.raises(ValueError, _get_all_sorted_knots, x, 2, lower_bound=1, upper_bound=3) + pytest.raises( + ValueError, _get_all_sorted_knots, x, 1, lower_bound=1.3, upper_bound=1.4 + ) + assert np.array_equal( + _get_all_sorted_knots(x, 1, lower_bound=1, upper_bound=3), [1, 2, 3] + ) + pytest.raises(ValueError, _get_all_sorted_knots, x, 1, lower_bound=2, upper_bound=3) + pytest.raises(ValueError, _get_all_sorted_knots, x, 1, inner_knots=[2, 3]) + pytest.raises(ValueError, _get_all_sorted_knots, x, lower_bound=2, upper_bound=3) + assert np.array_equal(_get_all_sorted_knots(x, inner_knots=[3, 7]), [0, 3, 7, 10]) + assert np.array_equal( + _get_all_sorted_knots(x, inner_knots=[3, 7], lower_bound=2), [2, 3, 7, 10] + ) + pytest.raises( + ValueError, _get_all_sorted_knots, x, inner_knots=[3, 7], lower_bound=4 + ) + pytest.raises( + ValueError, _get_all_sorted_knots, x, inner_knots=[3, 7], upper_bound=6 + ) + + +def _get_centering_constraint_from_dmatrix(design_matrix): + """Computes the centering constraint from the given design matrix. + + We want to ensure that if ``b`` is the array of parameters, our + model is centered, ie ``np.mean(np.dot(design_matrix, b))`` is zero. + We can rewrite this as ``np.dot(c, b)`` being zero with ``c`` a 1-row + constraint matrix containing the mean of each column of ``design_matrix``. + + :param design_matrix: The 2-d array design matrix. + :return: A 2-d array (1 x ncols(design_matrix)) defining the + centering constraint. + """ + return design_matrix.mean(axis=0).reshape((1, design_matrix.shape[1])) + + +class CubicRegressionSpline(object): + """Base class for cubic regression spline stateful transforms + + This class contains all the functionality for the following stateful + transforms: + - ``cr(x, df=None, knots=None, lower_bound=None, upper_bound=None, constraints=None)`` + for natural cubic regression spline + - ``cc(x, df=None, knots=None, lower_bound=None, upper_bound=None, constraints=None)`` + for cyclic cubic regression spline + """ + + common_doc = """ + :arg df: The number of degrees of freedom to use for this spline. The + return value will have this many columns. You must specify at least one + of ``df`` and ``knots``. + :arg knots: The interior knots to use for the spline. If unspecified, then + equally spaced quantiles of the input data are used. You must specify at + least one of ``df`` and ``knots``. + :arg lower_bound: The lower exterior knot location. + :arg upper_bound: The upper exterior knot location. + :arg constraints: Either a 2-d array defining general linear constraints + (that is ``np.dot(constraints, betas)`` is zero, where ``betas`` denotes + the array of *initial* parameters, corresponding to the *initial* + unconstrained design matrix), or the string + ``'center'`` indicating that we should apply a centering constraint + (this constraint will be computed from the input data, remembered and + re-used for prediction from the fitted model). + The constraints are absorbed in the resulting design matrix which means + that the model is actually rewritten in terms of + *unconstrained* parameters. For more details see :ref:`spline-regression`. + + This is a stateful transforms (for details see + :ref:`stateful-transforms`). If ``knots``, ``lower_bound``, or + ``upper_bound`` are not specified, they will be calculated from the data + and then the chosen values will be remembered and re-used for prediction + from the fitted model. + + Using this function requires scipy be installed. + + .. versionadded:: 0.3.0 + """ + + def __init__(self, name, cyclic): + self._name = name + self._cyclic = cyclic + self._tmp = {} + self._all_knots = None + self._constraints = None + + def memorize_chunk( + self, + x, + df=None, + knots=None, + lower_bound=None, + upper_bound=None, + constraints=None, + ): + args = { + "df": df, + "knots": knots, + "lower_bound": lower_bound, + "upper_bound": upper_bound, + "constraints": constraints, + } + self._tmp["args"] = args + + x = np.atleast_1d(x) + if x.ndim == 2 and x.shape[1] == 1: + x = x[:, 0] + if x.ndim > 1: + raise ValueError( + "Input to %r must be 1-d, " "or a 2-d column vector." % (self._name,) + ) + + self._tmp.setdefault("xs", []).append(x) + + def memorize_finish(self): + args = self._tmp["args"] + xs = self._tmp["xs"] + # Guards against invalid subsequent memorize_chunk() calls. + del self._tmp + + x = np.concatenate(xs) + if args["df"] is None and args["knots"] is None: + raise ValueError("Must specify either 'df' or 'knots'.") + + constraints = args["constraints"] + n_constraints = 0 + if constraints is not None: + if safe_string_eq(constraints, "center"): + # Here we collect only number of constraints, + # actual centering constraint will be computed after all_knots + n_constraints = 1 + else: + constraints = np.atleast_2d(constraints) + if constraints.ndim != 2: + raise ValueError("Constraints must be 2-d array or " "1-d vector.") + n_constraints = constraints.shape[0] + + n_inner_knots = None + if args["df"] is not None: + min_df = 1 + if not self._cyclic and n_constraints == 0: + min_df = 2 + if args["df"] < min_df: + raise ValueError( + "'df'=%r must be greater than or equal to %r." + % (args["df"], min_df) + ) + n_inner_knots = args["df"] - 2 + n_constraints + if self._cyclic: + n_inner_knots += 1 + self._all_knots = _get_all_sorted_knots( + x, + n_inner_knots=n_inner_knots, + inner_knots=args["knots"], + lower_bound=args["lower_bound"], + upper_bound=args["upper_bound"], + ) + if constraints is not None: + if safe_string_eq(constraints, "center"): + # Now we can compute centering constraints + constraints = _get_centering_constraint_from_dmatrix( + _get_free_crs_dmatrix(x, self._all_knots, cyclic=self._cyclic) + ) + + df_before_constraints = self._all_knots.size + if self._cyclic: + df_before_constraints -= 1 + if constraints.shape[1] != df_before_constraints: + raise ValueError( + "Constraints array should have %r columns but" + " %r found." % (df_before_constraints, constraints.shape[1]) + ) + self._constraints = constraints + + def transform( + self, + x, + df=None, + knots=None, + lower_bound=None, + upper_bound=None, + constraints=None, + ): + x_orig = x + x = np.atleast_1d(x) + if x.ndim == 2 and x.shape[1] == 1: + x = x[:, 0] + if x.ndim > 1: + raise ValueError( + "Input to %r must be 1-d, " "or a 2-d column vector." % (self._name,) + ) + dm = _get_crs_dmatrix( + x, self._all_knots, self._constraints, cyclic=self._cyclic + ) + if have_pandas: + if isinstance(x_orig, (pandas.Series, pandas.DataFrame)): + dm = pandas.DataFrame(dm) + dm.index = x_orig.index + return dm + + __getstate__ = no_pickling + + +class CR(CubicRegressionSpline): + """cr(x, df=None, knots=None, lower_bound=None, upper_bound=None, constraints=None) + + Generates a natural cubic spline basis for ``x`` + (with the option of absorbing centering or more general parameters + constraints), allowing non-linear fits. The usual usage is something like:: + + y ~ 1 + cr(x, df=5, constraints='center') + + to fit ``y`` as a smooth function of ``x``, with 5 degrees of freedom + given to the smooth, and centering constraint absorbed in + the resulting design matrix. Note that in this example, due to the centering + constraint, 6 knots will get computed from the input data ``x`` + to achieve 5 degrees of freedom. + + + .. note:: This function reproduce the cubic regression splines 'cr' and 'cs' + as implemented in the R package 'mgcv' (GAM modelling). + + """ + + # Under python -OO, __doc__ will be defined but set to None + if __doc__: + __doc__ += CubicRegressionSpline.common_doc + + def __init__(self): + CubicRegressionSpline.__init__(self, name="cr", cyclic=False) + + +cr = stateful_transform(CR) + + +class CC(CubicRegressionSpline): + """cc(x, df=None, knots=None, lower_bound=None, upper_bound=None, constraints=None) + + Generates a cyclic cubic spline basis for ``x`` + (with the option of absorbing centering or more general parameters + constraints), allowing non-linear fits. The usual usage is something like:: + + y ~ 1 + cc(x, df=7, constraints='center') + + to fit ``y`` as a smooth function of ``x``, with 7 degrees of freedom + given to the smooth, and centering constraint absorbed in + the resulting design matrix. Note that in this example, due to the centering + and cyclic constraints, 9 knots will get computed from the input data ``x`` + to achieve 7 degrees of freedom. + + .. note:: This function reproduce the cubic regression splines 'cc' + as implemented in the R package 'mgcv' (GAM modelling). + + """ + + # Under python -OO, __doc__ will be defined but set to None + if __doc__: + __doc__ += CubicRegressionSpline.common_doc + + def __init__(self): + CubicRegressionSpline.__init__(self, name="cc", cyclic=True) + + +cc = stateful_transform(CC) + + +def test_crs_errors(): + import pytest + + # Invalid 'x' shape + pytest.raises(ValueError, cr, np.arange(16).reshape((4, 4)), df=4) + pytest.raises(ValueError, CR().transform, np.arange(16).reshape((4, 4)), df=4) + # Should provide at least 'df' or 'knots' + pytest.raises(ValueError, cr, np.arange(50)) + # Invalid constraints shape + pytest.raises( + ValueError, + cr, + np.arange(50), + df=4, + constraints=np.arange(27).reshape((3, 3, 3)), + ) + # Invalid nb of columns in constraints + # (should have df + 1 = 5, but 6 provided) + pytest.raises(ValueError, cr, np.arange(50), df=4, constraints=np.arange(6)) + # Too small 'df' for natural cubic spline + pytest.raises(ValueError, cr, np.arange(50), df=1) + # Too small 'df' for cyclic cubic spline + pytest.raises(ValueError, cc, np.arange(50), df=0) + + +def test_crs_compat(): + from patsy.test_state import check_stateful + from patsy.test_splines_crs_data import ( + R_crs_test_x, + R_crs_test_data, + R_crs_num_tests, + ) + + lines = R_crs_test_data.split("\n") + tests_ran = 0 + start_idx = lines.index("--BEGIN TEST CASE--") + while True: + if not lines[start_idx] == "--BEGIN TEST CASE--": + break + start_idx += 1 + stop_idx = lines.index("--END TEST CASE--", start_idx) + block = lines[start_idx:stop_idx] + test_data = {} + for line in block: + key, value = line.split("=", 1) + test_data[key] = value + # Translate the R output into Python calling conventions + adjust_df = 0 + if test_data["spline_type"] == "cr" or test_data["spline_type"] == "cs": + spline_type = CR + elif test_data["spline_type"] == "cc": + spline_type = CC + adjust_df += 1 + else: + raise ValueError( + "Unrecognized spline type %r" % (test_data["spline_type"],) + ) + kwargs = {} + if test_data["absorb_cons"] == "TRUE": + kwargs["constraints"] = "center" + adjust_df += 1 + if test_data["knots"] != "None": + all_knots = np.asarray(eval(test_data["knots"])) + all_knots.sort() + kwargs["knots"] = all_knots[1:-1] + kwargs["lower_bound"] = all_knots[0] + kwargs["upper_bound"] = all_knots[-1] + else: + kwargs["df"] = eval(test_data["nb_knots"]) - adjust_df + output = np.asarray(eval(test_data["output"])) + # Do the actual test + check_stateful(spline_type, False, R_crs_test_x, output, **kwargs) + tests_ran += 1 + # Set up for the next one + start_idx = stop_idx + 1 + assert tests_ran == R_crs_num_tests + + +test_crs_compat.slow = True + + +def test_crs_with_specific_constraint(): + from patsy.highlevel import incr_dbuilder, build_design_matrices, dmatrix + + x = (-1.5) ** np.arange(20) + # Hard coded R values for smooth: s(x, bs="cr", k=5) + # R> knots <- smooth$xp + knots_R = np.array( + [ + -2216.837820053100585937, + -50.456909179687500000, + -0.250000000000000000, + 33.637939453125000000, + 1477.891880035400390625, + ] + ) + # R> centering.constraint <- t(qr.X(attr(smooth, "qrc"))) + centering_constraint_R = np.array( + [ + [ + 0.064910676323168478574, + 1.4519875239407085132, + -2.1947446912471946234, + 1.6129783104357671153, + 0.064868180547550072235, + ] + ] + ) + # values for which we want a prediction + new_x = np.array([-3000.0, -200.0, 300.0, 2000.0]) + result1 = dmatrix( + "cr(new_x, knots=knots_R[1:-1], " + "lower_bound=knots_R[0], upper_bound=knots_R[-1], " + "constraints=centering_constraint_R)" + ) + + data_chunked = [{"x": x[:10]}, {"x": x[10:]}] + new_data = {"x": new_x} + builder = incr_dbuilder( + "cr(x, df=4, constraints='center')", lambda: iter(data_chunked) + ) + result2 = build_design_matrices([builder], new_data)[0] + + assert np.allclose(result1, result2, rtol=1e-12, atol=0.0) + + +class TE(object): + """te(s1, .., sn, constraints=None) + + Generates smooth of several covariates as a tensor product of the bases + of marginal univariate smooths ``s1, .., sn``. The marginal smooths are + required to transform input univariate data into some kind of smooth + functions basis producing a 2-d array output with the ``(i, j)`` element + corresponding to the value of the ``j`` th basis function at the ``i`` th + data point. + The resulting basis dimension is the product of the basis dimensions of + the marginal smooths. The usual usage is something like:: + + y ~ 1 + te(cr(x1, df=5), cc(x2, df=6), constraints='center') + + to fit ``y`` as a smooth function of both ``x1`` and ``x2``, with a natural + cubic spline for ``x1`` marginal smooth and a cyclic cubic spline for + ``x2`` (and centering constraint absorbed in the resulting design matrix). + + :arg constraints: Either a 2-d array defining general linear constraints + (that is ``np.dot(constraints, betas)`` is zero, where ``betas`` denotes + the array of *initial* parameters, corresponding to the *initial* + unconstrained design matrix), or the string + ``'center'`` indicating that we should apply a centering constraint + (this constraint will be computed from the input data, remembered and + re-used for prediction from the fitted model). + The constraints are absorbed in the resulting design matrix which means + that the model is actually rewritten in terms of + *unconstrained* parameters. For more details see :ref:`spline-regression`. + + Using this function requires scipy be installed. + + .. note:: This function reproduce the tensor product smooth 'te' as + implemented in the R package 'mgcv' (GAM modelling). + See also 'Generalized Additive Models', Simon N. Wood, 2006, pp 158-163 + + .. versionadded:: 0.3.0 + """ + + def __init__(self): + self._tmp = {} + self._constraints = None + + def memorize_chunk(self, *args, **kwargs): + constraints = self._tmp.setdefault("constraints", kwargs.get("constraints")) + if safe_string_eq(constraints, "center"): + args_2d = [] + for arg in args: + arg = atleast_2d_column_default(arg) + if arg.ndim != 2: + raise ValueError( + "Each tensor product argument must be " + "a 2-d array or 1-d vector." + ) + args_2d.append(arg) + + tp = _row_tensor_product(args_2d) + self._tmp.setdefault("count", 0) + self._tmp["count"] += tp.shape[0] + + chunk_sum = np.atleast_2d(tp.sum(axis=0)) + self._tmp.setdefault("sum", np.zeros(chunk_sum.shape)) + self._tmp["sum"] += chunk_sum + + def memorize_finish(self): + tmp = self._tmp + constraints = self._tmp["constraints"] + # Guards against invalid subsequent memorize_chunk() calls. + del self._tmp + + if constraints is not None: + if safe_string_eq(constraints, "center"): + constraints = np.atleast_2d(tmp["sum"] / tmp["count"]) + else: + constraints = np.atleast_2d(constraints) + if constraints.ndim != 2: + raise ValueError("Constraints must be 2-d array or " "1-d vector.") + + self._constraints = constraints + + def transform(self, *args, **kwargs): + args_2d = [] + for arg in args: + arg = atleast_2d_column_default(arg) + if arg.ndim != 2: + raise ValueError( + "Each tensor product argument must be " "a 2-d array or 1-d vector." + ) + args_2d.append(arg) + + return _get_te_dmatrix(args_2d, self._constraints) + + __getstate__ = no_pickling + + +te = stateful_transform(TE) + + +def test_te_errors(): + import pytest + + x = np.arange(27) + # Invalid input shape + pytest.raises(ValueError, te, x.reshape((3, 3, 3))) + pytest.raises(ValueError, te, x.reshape((3, 3, 3)), constraints="center") + # Invalid constraints shape + pytest.raises(ValueError, te, x, constraints=np.arange(8).reshape((2, 2, 2))) + + +def test_te_1smooth(): + from patsy.splines import bs + + # Tensor product of 1 smooth covariate should be the same + # as the smooth alone + x = (-1.5) ** np.arange(20) + assert np.allclose(cr(x, df=6), te(cr(x, df=6))) + assert np.allclose(cc(x, df=5), te(cc(x, df=5))) + assert np.allclose(bs(x, df=4), te(bs(x, df=4))) + # Adding centering constraint to tensor product + assert np.allclose( + cr(x, df=3, constraints="center"), te(cr(x, df=4), constraints="center") + ) + # Adding specific constraint + center_constraint = np.arange(1, 5) + assert np.allclose( + cr(x, df=3, constraints=center_constraint), + te(cr(x, df=4), constraints=center_constraint), + ) + + +def test_te_2smooths(): + from patsy.highlevel import incr_dbuilder, build_design_matrices + + x1 = (-1.5) ** np.arange(20) + x2 = (1.6) ** np.arange(20) + # Hard coded R results for smooth: te(x1, x2, bs=c("cs", "cc"), k=c(5,7)) + # Without centering constraint: + dmatrix_R_nocons = np.array( + [ + [ + -4.4303024184609255207e-06, + 7.9884438387230142235e-06, + 9.7987758194797719025e-06, + -7.2894213245475212959e-08, + 1.5907686862964493897e-09, + -3.2565884983072595159e-11, + 0.0170749607855874667439, + -3.0788499835965849050e-02, + -3.7765754357352458725e-02, + 2.8094376299826799787e-04, + -6.1310290747349201414e-06, + 1.2551314933193442915e-07, + -0.26012671685838206770, + 4.6904420337437874311e-01, + 0.5753384627946153129230, + -4.2800085814700449330e-03, + 9.3402525733484874533e-05, + -1.9121170389937518131e-06, + -0.0904312240489447832781, + 1.6305991924427923334e-01, + 2.0001237112941641638e-01, + -1.4879148887003382663e-03, + 3.2470731316462736135e-05, + -6.6473404365914134499e-07, + 2.0447857920168824846e-05, + -3.6870296695050991799e-05, + -4.5225801045409022233e-05, + 3.3643990293641665710e-07, + -7.3421200200015877329e-09, + 1.5030635073660743297e-10, + ], + [ + -9.4006130602653794302e-04, + 7.8681398069163730347e-04, + 2.4573006857381437217e-04, + -1.4524712230452725106e-04, + 7.8216741353106329551e-05, + -3.1304283003914264551e-04, + 3.6231183382798337611064, + -3.0324832476174168328e00, + -9.4707559178211142559e-01, + 5.5980126937492580286e-01, + -3.0145747744342332730e-01, + 1.2065077148806895302e00, + -35.17561267504181188315, + 2.9441339255948005160e01, + 9.1948319320782125885216, + -5.4349184288245195873e00, + 2.9267472035096449012e00, + -1.1713569391233907169e01, + 34.0275626863976370373166, + -2.8480442582712722555e01, + -8.8947340548151565542e00, + 5.2575353623762932642e00, + -2.8312249982592527786e00, + 1.1331265795534763541e01, + 7.9462158845078978420e-01, + -6.6508361863670617531e-01, + -2.0771242914526857892e-01, + 1.2277550230353953542e-01, + -6.6115593588420035198e-02, + 2.6461103043402139923e-01, + ], + ] + ) + # With centering constraint: + dmatrix_R_cons = np.array( + [ + [ + 0.00329998606323867252343, + 1.6537431155796576600e-04, + -1.2392262709790753433e-04, + 6.5405304166706783407e-05, + -6.6764045799537624095e-05, + -0.1386431081763726258504, + 0.124297283800864313830, + -3.5487293655619825405e-02, + -3.0527115315785902268e-03, + 5.2009247643311604277e-04, + -0.00384203992301702674378, + -0.058901915802819435064, + 0.266422358491648914036, + 0.5739281693874087597607, + -1.3171008503525844392e-03, + 8.2573456631878912413e-04, + 6.6730833453016958831e-03, + -0.1467677784718444955470, + 0.220757650934837484913, + 0.1983127687880171796664, + -1.6269930328365173316e-03, + -1.7785892412241208812e-03, + -3.2702835436351201243e-03, + -4.3252183044300757109e-02, + 4.3403766976235179376e-02, + 3.5973406402893762387e-05, + -5.4035858568225075046e-04, + 2.9565209382794241247e-04, + -2.2769990750264097637e-04, + ], + [ + 0.41547954838956052681098, + 1.9843570584107707994e-02, + -1.5746590234791378593e-02, + 8.3171184312221431434e-03, + -8.7233014052017516377e-03, + -15.9926770785086258541696, + 16.503663226274017716833, + -6.6005803955894726265e-01, + 1.3986092022708346283e-01, + -2.3516913533670955050e-01, + 0.72251037497207359905360, + -9.827337059999853963177, + 3.917078117294827688255, + 9.0171773596973618936090, + -5.0616811270787671617e00, + 3.0189990249009683865e00, + -1.0872720629943064097e01, + 26.9308504460453121964747, + -21.212262927009287949431, + -9.1088328555582247503253, + 5.2400156972500298025e00, + -3.0593641098325474736e00, + 1.0919392118399086300e01, + -4.6564290223265718538e00, + 4.8071307441606982991e00, + -1.9748377005689798924e-01, + 5.4664183716965096538e-02, + -2.8871392916916285148e-02, + 2.3592766838010845176e-01, + ], + ] + ) + new_x1 = np.array([11.390625, 656.84083557128906250]) + new_x2 = np.array([16.777216000000006346, 1844.6744073709567147]) + new_data = {"x1": new_x1, "x2": new_x2} + data_chunked = [{"x1": x1[:10], "x2": x2[:10]}, {"x1": x1[10:], "x2": x2[10:]}] + + builder = incr_dbuilder( + "te(cr(x1, df=5), cc(x2, df=6)) - 1", lambda: iter(data_chunked) + ) + dmatrix_nocons = build_design_matrices([builder], new_data)[0] + assert np.allclose(dmatrix_nocons, dmatrix_R_nocons, rtol=1e-12, atol=0.0) + + builder = incr_dbuilder( + "te(cr(x1, df=5), cc(x2, df=6), " "constraints='center') - 1", + lambda: iter(data_chunked), + ) + dmatrix_cons = build_design_matrices([builder], new_data)[0] + assert np.allclose(dmatrix_cons, dmatrix_R_cons, rtol=1e-12, atol=0.0) + + +def test_te_3smooths(): + from patsy.highlevel import incr_dbuilder, build_design_matrices + + x1 = (-1.5) ** np.arange(20) + x2 = (1.6) ** np.arange(20) + x3 = (-1.2) ** np.arange(20) + # Hard coded R results for smooth: te(x1, x2, x3, bs=c("cr", "cs", "cc"), k=c(3,3,4)) + design_matrix_R = np.array( + [ + [ + 7.2077663709837084334e-05, + 2.0648333344343273131e-03, + -4.7934014082310591768e-04, + 2.3923430783992746568e-04, + 6.8534265421922660466e-03, + -1.5909867344112936776e-03, + -6.8057712777151204314e-09, + -1.9496724335203412851e-07, + 4.5260614658693259131e-08, + 0.0101479754187435277507, + 0.290712501531622591333, + -0.067487370093906928759, + 0.03368233306025386619709, + 0.9649092451763204847381, + -0.2239985793289433757547, + -9.5819975394704535133e-07, + -2.7449874082511405643e-05, + 6.3723431275833230217e-06, + -1.5205851762850489204e-04, + -0.00435607204539782688624, + 0.00101123909269346416370, + -5.0470024059694933508e-04, + -1.4458319360584082416e-02, + 3.3564223914790921634e-03, + 1.4357783514933466209e-08, + 4.1131230514870551983e-07, + -9.5483976834512651038e-08, + ] + ] + ) + new_data = { + "x1": -38.443359375000000000, + "x2": 68.719476736000032702, + "x3": -5.1597803519999985156, + } + data_chunked = [ + {"x1": x1[:10], "x2": x2[:10], "x3": x3[:10]}, + {"x1": x1[10:], "x2": x2[10:], "x3": x3[10:]}, + ] + builder = incr_dbuilder( + "te(cr(x1, df=3), cr(x2, df=3), cc(x3, df=3)) - 1", lambda: iter(data_chunked) + ) + design_matrix = build_design_matrices([builder], new_data)[0] + assert np.allclose(design_matrix, design_matrix_R, rtol=1e-12, atol=0.0) diff --git a/venv/lib/python3.10/site-packages/patsy/missing.py b/venv/lib/python3.10/site-packages/patsy/missing.py new file mode 100644 index 0000000000000000000000000000000000000000..b4d8a01d19a4c013c6d0b32d044a4800b0d47289 --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/missing.py @@ -0,0 +1,269 @@ +# This file is part of Patsy +# Copyright (C) 2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Missing data detection/handling + +# First, how do we represent missing data? (i.e., which values count as +# "missing"?) In the long run, we want to use numpy's NA support... but that +# doesn't exist yet. Until then, people use various sorts of ad-hoc +# things. Some things that might be considered NA: +# NA (eventually) +# NaN (in float or object arrays) +# None (in object arrays) +# np.ma.masked (in numpy.ma masked arrays) +# Pandas compatibility considerations: +# For numeric arrays, None is unconditionally converted to NaN. +# For object arrays (including string arrays!), None and NaN are preserved, +# but pandas.isnull() returns True for both. +# np.ma compatibility considerations: +# Preserving array subtypes is a huge pain, because it means that we can't +# just call 'asarray' and be done... we already jump through tons of hoops +# to write code that can handle both ndarray's and pandas objects, and +# just thinking about adding another item to this list makes me tired. So +# for now we don't support np.ma missing values. Use pandas! + +# Next, what should be done once we find missing data? R's options: +# -- throw away those rows (from all aligned matrices) +# -- with or without preserving information on which rows were discarded +# -- error out +# -- carry on +# The 'carry on' option requires that we have some way to represent NA in our +# output array. To avoid further solidifying the use of NaN for this purpose, +# we'll leave this option out for now, until real NA support is +# available. Also, we always preserve information on which rows were +# discarded, using the pandas index functionality (currently this is only +# returned to the original caller if they used return_type="dataframe", +# though). + +import numpy as np +from patsy import PatsyError +from patsy.util import safe_isnan, safe_scalar_isnan, no_pickling, assert_no_pickling + +# These are made available in the patsy.* namespace +__all__ = ["NAAction"] + +_valid_NA_types = ["None", "NaN"] +_valid_NA_responses = ["raise", "drop"] + + +def _desc_options(options): + return ", ".join([repr(opt) for opt in options]) + + +class NAAction(object): + """An :class:`NAAction` object defines a strategy for handling missing + data. + + "NA" is short for "Not Available", and is used to refer to any value which + is somehow unmeasured or unavailable. In the long run, it is devoutly + hoped that numpy will gain first-class missing value support. Until then, + we work around this lack as best we're able. + + There are two parts to this: First, we have to determine what counts as + missing data. For numerical data, the default is to treat NaN values + (e.g., ``numpy.nan``) as missing. For categorical data, the default is to + treat NaN values, and also the Python object None, as missing. (This is + consistent with how pandas does things, so if you're already using + None/NaN to mark missing data in your pandas DataFrames, you're good to + go.) + + Second, we have to decide what to do with any missing data when we + encounter it. One option is to simply discard any rows which contain + missing data from our design matrices (``drop``). Another option is to + raise an error (``raise``). A third option would be to simply let the + missing values pass through into the returned design matrices. However, + this last option is not yet implemented, because of the lack of any + standard way to represent missing values in arbitrary numpy matrices; + we're hoping numpy will get this sorted out before we standardize on + anything ourselves. + + You can control how patsy handles missing data through the ``NA_action=`` + argument to functions like :func:`build_design_matrices` and + :func:`dmatrix`. If all you want to do is to choose between ``drop`` and + ``raise`` behaviour, you can pass one of those strings as the + ``NA_action=`` argument directly. If you want more fine-grained control + over how missing values are detected and handled, then you can create an + instance of this class, or your own object that implements the same + interface, and pass that as the ``NA_action=`` argument instead. + """ + + def __init__(self, on_NA="drop", NA_types=["None", "NaN"]): + """The :class:`NAAction` constructor takes the following arguments: + + :arg on_NA: How to handle missing values. The default is ``"drop"``, + which removes all rows from all matrices which contain any missing + values. Also available is ``"raise"``, which raises an exception + when any missing values are encountered. + :arg NA_types: Which rules are used to identify missing values, as a + list of strings. Allowed values are: + + * ``"None"``: treat the ``None`` object as missing in categorical + data. + * ``"NaN"``: treat floating point NaN values as missing in + categorical and numerical data. + + .. versionadded:: 0.2.0 + """ + self.on_NA = on_NA + if self.on_NA not in _valid_NA_responses: + raise ValueError( + "invalid on_NA action %r " + "(should be one of %s)" % (on_NA, _desc_options(_valid_NA_responses)) + ) + if isinstance(NA_types, str): + raise ValueError("NA_types should be a list of strings") + self.NA_types = tuple(NA_types) + for NA_type in self.NA_types: + if NA_type not in _valid_NA_types: + raise ValueError( + "invalid NA_type %r " + "(should be one of %s)" % (NA_type, _desc_options(_valid_NA_types)) + ) + + def is_categorical_NA(self, obj): + """Return True if `obj` is a categorical NA value. + + Note that here `obj` is a single scalar value.""" + if "NaN" in self.NA_types and safe_scalar_isnan(obj): + return True + if "None" in self.NA_types and obj is None: + return True + return False + + def is_numerical_NA(self, arr): + """Returns a 1-d mask array indicating which rows in an array of + numerical values contain at least one NA value. + + Note that here `arr` is a numpy array or pandas DataFrame.""" + mask = np.zeros(arr.shape, dtype=bool) + if "NaN" in self.NA_types: + mask |= np.isnan(arr) + if mask.ndim > 1: + mask = np.any(mask, axis=1) + return mask + + def handle_NA(self, values, is_NAs, origins): + """Takes a set of factor values that may have NAs, and handles them + appropriately. + + :arg values: A list of `ndarray` objects representing the data. + These may be 1- or 2-dimensional, and may be of varying dtype. All + will have the same number of rows (or entries, for 1-d arrays). + :arg is_NAs: A list with the same number of entries as `values`, + containing boolean `ndarray` objects that indicate which rows + contain NAs in the corresponding entry in `values`. + :arg origins: A list with the same number of entries as + `values`, containing information on the origin of each + value. If we encounter a problem with some particular value, we use + the corresponding entry in `origins` as the origin argument when + raising a :class:`PatsyError`. + :returns: A list of new values (which may have a differing number of + rows.) + """ + assert len(values) == len(is_NAs) == len(origins) + if len(values) == 0: + return values + if self.on_NA == "raise": + return self._handle_NA_raise(values, is_NAs, origins) + elif self.on_NA == "drop": + return self._handle_NA_drop(values, is_NAs, origins) + else: # pragma: no cover + assert False + + def _handle_NA_raise(self, values, is_NAs, origins): + for is_NA, origin in zip(is_NAs, origins): + if np.any(is_NA): + raise PatsyError("factor contains missing values", origin) + return values + + def _handle_NA_drop(self, values, is_NAs, origins): + total_mask = np.zeros(is_NAs[0].shape[0], dtype=bool) + for is_NA in is_NAs: + total_mask |= is_NA + good_mask = ~total_mask + # "..." to handle 1- versus 2-dim indexing + return [v[good_mask, ...] for v in values] + + __getstate__ = no_pickling + + +def test_NAAction_basic(): + import pytest + + pytest.raises(ValueError, NAAction, on_NA="pord") + pytest.raises(ValueError, NAAction, NA_types=("NaN", "asdf")) + pytest.raises(ValueError, NAAction, NA_types="NaN") + + assert_no_pickling(NAAction()) + + +def test_NAAction_NA_types_numerical(): + for NA_types in [[], ["NaN"], ["None"], ["NaN", "None"]]: + action = NAAction(NA_types=NA_types) + for extra_shape in [(), (1,), (2,)]: + arr = np.ones((4,) + extra_shape, dtype=float) + nan_rows = [0, 2] + if arr.ndim > 1 and arr.shape[1] > 1: + arr[nan_rows, [0, 1]] = np.nan + else: + arr[nan_rows] = np.nan + exp_NA_mask = np.zeros(4, dtype=bool) + if "NaN" in NA_types: + exp_NA_mask[nan_rows] = True + got_NA_mask = action.is_numerical_NA(arr) + assert np.array_equal(got_NA_mask, exp_NA_mask) + + +def test_NAAction_NA_types_categorical(): + for NA_types in [[], ["NaN"], ["None"], ["NaN", "None"]]: + action = NAAction(NA_types=NA_types) + assert not action.is_categorical_NA("a") + assert not action.is_categorical_NA(1) + assert action.is_categorical_NA(None) == ("None" in NA_types) + assert action.is_categorical_NA(np.nan) == ("NaN" in NA_types) + + +def test_NAAction_drop(): + action = NAAction("drop") + in_values = [ + np.asarray([-1, 2, -1, 4, 5]), + np.asarray([10.0, 20.0, 30.0, 40.0, 50.0]), + np.asarray([[1.0, np.nan], [3.0, 4.0], [10.0, 5.0], [6.0, 7.0], [8.0, np.nan]]), + ] + is_NAs = [ + np.asarray([True, False, True, False, False]), + np.zeros(5, dtype=bool), + np.asarray([True, False, False, False, True]), + ] + out_values = action.handle_NA(in_values, is_NAs, [None] * 3) + assert len(out_values) == 3 + assert np.array_equal(out_values[0], [2, 4]) + assert np.array_equal(out_values[1], [20.0, 40.0]) + assert np.array_equal(out_values[2], [[3.0, 4.0], [6.0, 7.0]]) + + +def test_NAAction_raise(): + action = NAAction(on_NA="raise") + + # no-NA just passes through: + in_arrs = [np.asarray([1.1, 1.2]), np.asarray([1, 2])] + is_NAs = [np.asarray([False, False])] * 2 + got_arrs = action.handle_NA(in_arrs, is_NAs, [None, None]) + assert np.array_equal(got_arrs[0], in_arrs[0]) + assert np.array_equal(got_arrs[1], in_arrs[1]) + + from patsy.origin import Origin + + o1 = Origin("asdf", 0, 1) + o2 = Origin("asdf", 2, 3) + + # NA raises an error with a correct origin + in_idx = np.arange(2) + in_arrs = [np.asarray([1.1, 1.2]), np.asarray([1.0, np.nan])] + is_NAs = [np.asarray([False, False]), np.asarray([False, True])] + try: + action.handle_NA(in_arrs, is_NAs, [o1, o2]) + assert False + except PatsyError as e: + assert e.origin is o2 diff --git a/venv/lib/python3.10/site-packages/patsy/origin.py b/venv/lib/python3.10/site-packages/patsy/origin.py new file mode 100644 index 0000000000000000000000000000000000000000..fcabf21f43fdb2d8d89fbe25d464546b0b4fb44e --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/origin.py @@ -0,0 +1,151 @@ +# This file is part of Patsy +# Copyright (C) 2011-2012 Nathaniel Smith +# See file LICENSE.txt for license information. + +# The core 'origin' tracking system. This point of this is to have machinery +# so if some object is ultimately derived from some portion of a string (e.g., +# a formula), then we can keep track of that, and use it to give proper error +# messages. + +# These are made available in the patsy.* namespace +__all__ = ["Origin"] + + +class Origin(object): + """This represents the origin of some object in some string. + + For example, if we have an object ``x1_obj`` that was produced by parsing + the ``x1`` in the formula ``"y ~ x1:x2"``, then we conventionally keep + track of that relationship by doing:: + + x1_obj.origin = Origin("y ~ x1:x2", 4, 6) + + Then later if we run into a problem, we can do:: + + raise PatsyError("invalid factor", x1_obj) + + and we'll produce a nice error message like:: + + PatsyError: invalid factor + y ~ x1:x2 + ^^ + + Origins are compared by value, and hashable. + """ + + def __init__(self, code, start, end): + self.code = code + self.start = start + self.end = end + + @classmethod + def combine(cls, origin_objs): + """Class method for combining a set of Origins into one large Origin + that spans them. + + Example usage: if we wanted to represent the origin of the "x1:x2" + term, we could do ``Origin.combine([x1_obj, x2_obj])``. + + Single argument is an iterable, and each element in the iterable + should be either: + + * An Origin object + * ``None`` + * An object that has a ``.origin`` attribute which fulfills the above + criteria. + + Returns either an Origin object, or None. + """ + origins = [] + for obj in origin_objs: + if obj is not None and not isinstance(obj, Origin): + obj = obj.origin + if obj is None: + continue + origins.append(obj) + if not origins: + return None + codes = set([o.code for o in origins]) + assert len(codes) == 1 + start = min([o.start for o in origins]) + end = max([o.end for o in origins]) + return cls(codes.pop(), start, end) + + def relevant_code(self): + """Extracts and returns the span of the original code represented by + this Origin. Example: ``x1``.""" + return self.code[self.start : self.end] + + def __eq__(self, other): + return ( + isinstance(other, Origin) + and self.code == other.code + and self.start == other.start + and self.end == other.end + ) + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash((Origin, self.code, self.start, self.end)) + + def caretize(self, indent=0): + """Produces a user-readable two line string indicating the origin of + some code. Example:: + + y ~ x1:x2 + ^^ + + If optional argument 'indent' is given, then both lines will be + indented by this much. The returned string does not have a trailing + newline. + """ + return "%s%s\n%s%s%s" % ( + " " * indent, + self.code, + " " * indent, + " " * self.start, + "^" * (self.end - self.start), + ) + + def __repr__(self): + return "%s<-%s (%s-%s)>" % ( + self.code[: self.start], + self.code[self.start : self.end], + self.code[self.end :], + self.start, + self.end, + ) + + # We reimplement patsy.util.no_pickling, to avoid circular import issues + def __getstate__(self): + raise NotImplementedError + + +def test_Origin(): + o1 = Origin("012345", 2, 4) + o2 = Origin("012345", 4, 5) + assert o1.caretize() == "012345\n ^^" + assert o2.caretize() == "012345\n ^" + o3 = Origin.combine([o1, o2]) + assert o3.code == "012345" + assert o3.start == 2 + assert o3.end == 5 + assert o3.caretize(indent=2) == " 012345\n ^^^" + assert o3 == Origin("012345", 2, 5) + + class ObjWithOrigin(object): + def __init__(self, origin=None): + self.origin = origin + + o4 = Origin.combine([ObjWithOrigin(o1), ObjWithOrigin(), None]) + assert o4 == o1 + o5 = Origin.combine([ObjWithOrigin(o1), o2]) + assert o5 == o3 + + assert Origin.combine([ObjWithOrigin(), ObjWithOrigin()]) is None + + from patsy.util import assert_no_pickling + + assert_no_pickling(Origin("", 0, 0)) diff --git a/venv/lib/python3.10/site-packages/patsy/parse_formula.py b/venv/lib/python3.10/site-packages/patsy/parse_formula.py new file mode 100644 index 0000000000000000000000000000000000000000..8d0c61599965a06c82e10710a0d0a7a1ae52b082 --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/parse_formula.py @@ -0,0 +1,295 @@ +# This file is part of Patsy +# Copyright (C) 2011 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file defines a parser for a simple language based on S/R "formulas" +# (which are described in sections 2.3 and 2.4 in Chambers & Hastie, 1992). It +# uses the machinery in patsy.parse_core to do the heavy-lifting -- its +# biggest job is to handle tokenization. + + +__all__ = ["parse_formula"] + +# The Python tokenizer +import tokenize + +from io import StringIO + +from patsy import PatsyError +from patsy.origin import Origin +from patsy.infix_parser import Token, Operator, infix_parse, ParseNode +from patsy.tokens import python_tokenize, pretty_untokenize +from patsy.util import PushbackAdapter + +_atomic_token_types = ["PYTHON_EXPR", "ZERO", "ONE", "NUMBER"] + + +def _is_a(f, v): + try: + f(v) + except ValueError: + return False + else: + return True + + +# Helper function for _tokenize_formula: +def _read_python_expr(it, end_tokens): + # Read out a full python expression, stopping when we hit an + # unnested end token. + pytypes = [] + token_strings = [] + origins = [] + bracket_level = 0 + for pytype, token_string, origin in it: + assert bracket_level >= 0 + if bracket_level == 0 and token_string in end_tokens: + it.push_back((pytype, token_string, origin)) + break + if token_string in ("(", "[", "{"): + bracket_level += 1 + if token_string in (")", "]", "}"): + bracket_level -= 1 + if bracket_level < 0: + raise PatsyError("unmatched close bracket", origin) + pytypes.append(pytype) + token_strings.append(token_string) + origins.append(origin) + # Either we found an end_token, or we hit the end of the string + if bracket_level == 0: + expr_text = pretty_untokenize(zip(pytypes, token_strings)) + if expr_text == "0": + token_type = "ZERO" + elif expr_text == "1": + token_type = "ONE" + elif _is_a(int, expr_text) or _is_a(float, expr_text): + token_type = "NUMBER" + else: + token_type = "PYTHON_EXPR" + return Token(token_type, Origin.combine(origins), extra=expr_text) + else: + raise PatsyError( + "unclosed bracket in embedded Python " "expression", Origin.combine(origins) + ) + + +def _tokenize_formula(code, operator_strings): + assert "(" not in operator_strings + assert ")" not in operator_strings + magic_token_types = { + "(": Token.LPAREN, + ")": Token.RPAREN, + } + for operator_string in operator_strings: + magic_token_types[operator_string] = operator_string + # Once we enter a Python expression, a ( does not end it, but any other + # "magic" token does: + end_tokens = set(magic_token_types) + end_tokens.remove("(") + + it = PushbackAdapter(python_tokenize(code)) + for pytype, token_string, origin in it: + if token_string in magic_token_types: + yield Token(magic_token_types[token_string], origin) + else: + it.push_back((pytype, token_string, origin)) + yield _read_python_expr(it, end_tokens) + + +def test__tokenize_formula(): + code = "y ~ a + (foo(b,c + 2)) + -1 + 0 + 10" + tokens = list(_tokenize_formula(code, ["+", "-", "~"])) + expecteds = [ + ("PYTHON_EXPR", Origin(code, 0, 1), "y"), + ("~", Origin(code, 2, 3), None), + ("PYTHON_EXPR", Origin(code, 4, 5), "a"), + ("+", Origin(code, 6, 7), None), + (Token.LPAREN, Origin(code, 8, 9), None), + ("PYTHON_EXPR", Origin(code, 9, 23), "foo(b, c + 2)"), + (Token.RPAREN, Origin(code, 23, 24), None), + ("+", Origin(code, 25, 26), None), + ("-", Origin(code, 27, 28), None), + ("ONE", Origin(code, 28, 29), "1"), + ("+", Origin(code, 30, 31), None), + ("ZERO", Origin(code, 32, 33), "0"), + ("+", Origin(code, 34, 35), None), + ("NUMBER", Origin(code, 36, 38), "10"), + ] + for got, expected in zip(tokens, expecteds): + assert isinstance(got, Token) + assert got.type == expected[0] + assert got.origin == expected[1] + assert got.extra == expected[2] + + +_unary_tilde = Operator("~", 1, -100) +_default_ops = [ + _unary_tilde, + Operator("~", 2, -100), + Operator("+", 2, 100), + Operator("-", 2, 100), + Operator("*", 2, 200), + Operator("/", 2, 200), + Operator(":", 2, 300), + Operator("**", 2, 500), + Operator("+", 1, 100), + Operator("-", 1, 100), +] + + +def parse_formula(code, extra_operators=[]): + if not code.strip(): + code = "~ 1" + + for op in extra_operators: + if op.precedence < 0: + raise ValueError("all operators must have precedence >= 0") + + operators = _default_ops + extra_operators + operator_strings = [op.token_type for op in operators] + tree = infix_parse( + _tokenize_formula(code, operator_strings), operators, _atomic_token_types + ) + if not isinstance(tree, ParseNode) or tree.type != "~": + tree = ParseNode("~", None, [tree], tree.origin) + return tree + + +############# + +_parser_tests = { + "": ["~", "1"], + " ": ["~", "1"], + " \n ": ["~", "1"], + "1": ["~", "1"], + "a": ["~", "a"], + "a ~ b": ["~", "a", "b"], + "(a ~ b)": ["~", "a", "b"], + "a ~ ((((b))))": ["~", "a", "b"], + "a ~ ((((+b))))": ["~", "a", ["+", "b"]], + "a + b + c": ["~", ["+", ["+", "a", "b"], "c"]], + "a + (b ~ c) + d": ["~", ["+", ["+", "a", ["~", "b", "c"]], "d"]], + "a + np.log(a, base=10)": ["~", ["+", "a", "np.log(a, base=10)"]], + # Note different spacing: + "a + np . log(a , base = 10)": ["~", ["+", "a", "np.log(a, base=10)"]], + # Check precedence + "a + b ~ c * d": ["~", ["+", "a", "b"], ["*", "c", "d"]], + "a + b * c": ["~", ["+", "a", ["*", "b", "c"]]], + "-a**2": ["~", ["-", ["**", "a", "2"]]], + "-a:b": ["~", ["-", [":", "a", "b"]]], + "a + b:c": ["~", ["+", "a", [":", "b", "c"]]], + "(a + b):c": ["~", [":", ["+", "a", "b"], "c"]], + "a*b:c": ["~", ["*", "a", [":", "b", "c"]]], + "a+b / c": ["~", ["+", "a", ["/", "b", "c"]]], + "~ a": ["~", "a"], + "-1": ["~", ["-", "1"]], +} + + +def _compare_trees(got, expected): + assert isinstance(got, ParseNode) + if got.args: + assert got.type == expected[0] + for arg, expected_arg in zip(got.args, expected[1:]): + _compare_trees(arg, expected_arg) + else: + assert got.type in _atomic_token_types + assert got.token.extra == expected + + +def _do_parse_test(test_cases, extra_operators): + for code, expected in test_cases.items(): + actual = parse_formula(code, extra_operators=extra_operators) + print(repr(code), repr(expected)) + print(actual) + _compare_trees(actual, expected) + + +def test_parse_formula(): + _do_parse_test(_parser_tests, []) + + +def test_parse_origin(): + tree = parse_formula("a ~ b + c") + assert tree.origin == Origin("a ~ b + c", 0, 9) + assert tree.token.origin == Origin("a ~ b + c", 2, 3) + assert tree.args[0].origin == Origin("a ~ b + c", 0, 1) + assert tree.args[1].origin == Origin("a ~ b + c", 4, 9) + assert tree.args[1].token.origin == Origin("a ~ b + c", 6, 7) + assert tree.args[1].args[0].origin == Origin("a ~ b + c", 4, 5) + assert tree.args[1].args[1].origin == Origin("a ~ b + c", 8, 9) + + +# <> mark off where the error should be reported: +_parser_error_tests = [ + "a <+>", + "a + <(>", + "a + b <# asdf>", + "<)>", + "a + <)>", + "<*> a", + "a + <*>", + "a + ", + "a + ", + "a + ", + "a + <[bar>", + "a + <{bar>", + "a + <{bar[]>", + "a + foo<]>bar", + "a + foo[]<]>bar", + "a + foo{}<}>bar", + "a + foo<)>bar", + "a + b<)>", + "(a) <.>", + "<(>a + b", + "a +< >'foo", # Not the best placement for the error +] + + +# Split out so it can also be used by tests of the evaluator (which also +# raises PatsyError's) +def _parsing_error_test(parse_fn, error_descs): # pragma: no cover + for error_desc in error_descs: + letters = [] + start = None + end = None + for letter in error_desc: + if letter == "<": + start = len(letters) + elif letter == ">": + end = len(letters) + else: + letters.append(letter) + bad_code = "".join(letters) + assert start is not None and end is not None + print(error_desc) + print(repr(bad_code), start, end) + try: + parse_fn(bad_code) + except PatsyError as e: + print(e) + assert e.origin.code == bad_code + assert e.origin.start in (0, start) + assert e.origin.end in (end, len(bad_code)) + else: + assert False, "parser failed to report an error!" + + +def test_parse_errors(extra_operators=[]): + def parse_fn(code): + return parse_formula(code, extra_operators=extra_operators) + + _parsing_error_test(parse_fn, _parser_error_tests) + + +_extra_op_parser_tests = { + "a | b": ["~", ["|", "a", "b"]], + "a * b|c": ["~", ["*", "a", ["|", "b", "c"]]], +} + + +def test_parse_extra_op(): + extra_operators = [Operator("|", 2, 250)] + _do_parse_test(_parser_tests, extra_operators=extra_operators) + _do_parse_test(_extra_op_parser_tests, extra_operators=extra_operators) + test_parse_errors(extra_operators=extra_operators) diff --git a/venv/lib/python3.10/site-packages/patsy/redundancy.py b/venv/lib/python3.10/site-packages/patsy/redundancy.py new file mode 100644 index 0000000000000000000000000000000000000000..c81d439f91044280c686b9b2fad7b68bf5d3e78c --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/redundancy.py @@ -0,0 +1,278 @@ +# This file is part of Patsy +# Copyright (C) 2011 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file has the code that figures out how each factor in some given Term +# should be coded. This is complicated by dealing with models with categorical +# factors like: +# 1 + a + a:b +# then technically 'a' (which represents the space of vectors that can be +# produced as linear combinations of the dummy coding of the levels of the +# factor a) is collinear with the intercept, and 'a:b' (which represents the +# space of vectors that can be produced as linear combinations of the dummy +# coding *of a new factor whose levels are the cartesian product of a and b) +# is collinear with both 'a' and the intercept. +# +# In such a case, the rule is that we find some way to code each term so that +# the full space of vectors that it represents *is present in the model* BUT +# there is no collinearity between the different terms. In effect, we have to +# choose a set of vectors that spans everything that that term wants to span, +# *except* that part of the vector space which was already spanned by earlier +# terms. + +# How? We replace each term with the set of "subterms" that it covers, like +# so: +# 1 -> () +# a -> (), a- +# a:b -> (), a-, b-, a-:b- +# where "-" means "coded so as not to span the intercept". So that example +# above expands to +# [()] + [() + a-] + [() + a- + b- + a-:b-] +# so we go through from left to right, and for each term we: +# 1) toss out all the subterms that have already been used (this is a simple +# equality test, no magic) +# 2) simplify the terms that are left, according to rules like +# () + a- = a+ +# (here + means, "coded to span the intercept") +# 3) use the resulting subterm list as our coding for this term! +# So in the above, we go: +# (): stays the same, coded as intercept +# () + a-: reduced to just a-, which is what we code +# () + a- + b- + a-:b-: reduced to b- + a-:b-, which is simplified to a+:b-. + +from patsy.util import no_pickling + + +# This should really be a named tuple, but those don't exist until Python +# 2.6... +class _ExpandedFactor(object): + """A factor, with an additional annotation for whether it is coded + full-rank (includes_intercept=True) or not. + + These objects are treated as immutable.""" + + def __init__(self, includes_intercept, factor): + self.includes_intercept = includes_intercept + self.factor = factor + + def __hash__(self): + return hash((_ExpandedFactor, self.includes_intercept, self.factor)) + + def __eq__(self, other): + return ( + isinstance(other, _ExpandedFactor) + and other.includes_intercept == self.includes_intercept + and other.factor == self.factor + ) + + def __ne__(self, other): + return not self == other + + def __repr__(self): + if self.includes_intercept: + suffix = "+" + else: + suffix = "-" + return "%r%s" % (self.factor, suffix) + + __getstate__ = no_pickling + + +class _Subterm(object): + "Also immutable." + + def __init__(self, efactors): + self.efactors = frozenset(efactors) + + def can_absorb(self, other): + # returns True if 'self' is like a-:b-, and 'other' is like a- + return len(self.efactors) - len( + other.efactors + ) == 1 and self.efactors.issuperset(other.efactors) + + def absorb(self, other): + diff = self.efactors.difference(other.efactors) + assert len(diff) == 1 + efactor = list(diff)[0] + assert not efactor.includes_intercept + new_factors = set(other.efactors) + new_factors.add(_ExpandedFactor(True, efactor.factor)) + return _Subterm(new_factors) + + def __hash__(self): + return hash((_Subterm, self.efactors)) + + def __eq__(self, other): + return isinstance(other, _Subterm) and self.efactors == self.efactors + + def __ne__(self, other): + return not self == other + + def __repr__(self): + return "%s(%r)" % (self.__class__.__name__, list(self.efactors)) + + __getstate__ = no_pickling + + +# For testing: takes a shorthand description of a list of subterms like +# [(), ("a-",), ("a-", "b+")] +# and expands it into a list of _Subterm and _ExpandedFactor objects. +def _expand_test_abbrevs(short_subterms): + subterms = [] + for subterm in short_subterms: + factors = [] + for factor_name in subterm: + assert factor_name[-1] in ("+", "-") + factors.append(_ExpandedFactor(factor_name[-1] == "+", factor_name[:-1])) + subterms.append(_Subterm(factors)) + return subterms + + +def test__Subterm(): + s_ab = _expand_test_abbrevs([["a-", "b-"]])[0] + s_abc = _expand_test_abbrevs([["a-", "b-", "c-"]])[0] + s_null = _expand_test_abbrevs([[]])[0] + s_cd = _expand_test_abbrevs([["c-", "d-"]])[0] + s_a = _expand_test_abbrevs([["a-"]])[0] + s_ap = _expand_test_abbrevs([["a+"]])[0] + s_abp = _expand_test_abbrevs([["a-", "b+"]])[0] + for bad in s_abc, s_null, s_cd, s_ap, s_abp: + assert not s_ab.can_absorb(bad) + assert s_ab.can_absorb(s_a) + assert s_ab.absorb(s_a) == s_abp + + +# Importantly, this preserves the order of the input. Both the items inside +# each subset are in the order they were in the original tuple, and the tuples +# are emitted so that they're sorted with respect to their elements position +# in the original tuple. +def _subsets_sorted(tupl): + def helper(seq): + if not seq: + yield () + else: + obj = seq[0] + for subset in _subsets_sorted(seq[1:]): + yield subset + yield (obj,) + subset + + # Transform each obj -> (idx, obj) tuple, so that we can later sort them + # by their position in the original list. + expanded = list(enumerate(tupl)) + expanded_subsets = list(helper(expanded)) + # This exploits Python's stable sort: we want short before long, and ties + # broken by natural ordering on the (idx, obj) entries in each subset. So + # we sort by the latter first, then by the former. + expanded_subsets.sort() + expanded_subsets.sort(key=len) + # And finally, we strip off the idx's: + for subset in expanded_subsets: + yield tuple([obj for (idx, obj) in subset]) + + +def test__subsets_sorted(): + assert list(_subsets_sorted((1, 2))) == [(), (1,), (2,), (1, 2)] + assert list(_subsets_sorted((1, 2, 3))) == [ + (), + (1,), + (2,), + (3,), + (1, 2), + (1, 3), + (2, 3), + (1, 2, 3), + ] + assert len(list(_subsets_sorted(range(5)))) == 2**5 + + +def _simplify_one_subterm(subterms): + # We simplify greedily from left to right. + # Returns True if succeeded, False otherwise + for short_i, short_subterm in enumerate(subterms): + for long_i, long_subterm in enumerate(subterms[short_i + 1 :]): + if long_subterm.can_absorb(short_subterm): + new_subterm = long_subterm.absorb(short_subterm) + subterms[short_i + 1 + long_i] = new_subterm + subterms.pop(short_i) + return True + return False + + +def _simplify_subterms(subterms): + while _simplify_one_subterm(subterms): + pass + + +def test__simplify_subterms(): + def t(given, expected): + given = _expand_test_abbrevs(given) + expected = _expand_test_abbrevs(expected) + print("testing if:", given, "->", expected) + _simplify_subterms(given) + assert given == expected + + t([("a-",)], [("a-",)]) + t([(), ("a-",)], [("a+",)]) + t([(), ("a-",), ("b-",), ("a-", "b-")], [("a+", "b+")]) + t([(), ("a-",), ("a-", "b-")], [("a+",), ("a-", "b-")]) + t([("a-",), ("b-",), ("a-", "b-")], [("b-",), ("a-", "b+")]) + + +# 'term' is a Term +# 'numeric_factors' is any set-like object which lists the +# numeric/non-categorical factors in this term. Such factors are just +# ignored by this routine. +# 'used_subterms' is a set which records which subterms have previously been +# used. E.g., a:b has subterms (), a, b, a:b, and if we're processing +# y ~ a + a:b +# then by the time we reach a:b, the () and a subterms will have already +# been used. This is an in/out argument, and should be treated as opaque by +# callers -- really it is a way for multiple invocations of this routine to +# talk to each other. Each time it is called, this routine adds the subterms +# of each factor to this set in place. So the first time this routine is +# called, pass in an empty set, and then just keep passing the same set to +# any future calls. +# Returns: a list of dicts. Each dict maps from factors to booleans. The +# coding for the given term should use a full-rank contrast for those factors +# which map to True, a (n-1)-rank contrast for those factors which map to +# False, and any factors which are not mentioned are numeric and should be +# added back in. These dicts should add columns to the design matrix from left +# to right. +def pick_contrasts_for_term(term, numeric_factors, used_subterms): + categorical_factors = [f for f in term.factors if f not in numeric_factors] + # Converts a term into an expanded list of subterms like: + # a:b -> 1 + a- + b- + a-:b- + # and discards the ones that have already been used. + subterms = [] + for subset in _subsets_sorted(categorical_factors): + subterm = _Subterm([_ExpandedFactor(False, f) for f in subset]) + if subterm not in used_subterms: + subterms.append(subterm) + used_subterms.update(subterms) + _simplify_subterms(subterms) + factor_codings = [] + for subterm in subterms: + factor_coding = {} + for expanded in subterm.efactors: + factor_coding[expanded.factor] = expanded.includes_intercept + factor_codings.append(factor_coding) + return factor_codings + + +def test_pick_contrasts_for_term(): + from patsy.desc import Term + + used = set() + codings = pick_contrasts_for_term(Term([]), set(), used) + assert codings == [{}] + codings = pick_contrasts_for_term(Term(["a", "x"]), set(["x"]), used) + assert codings == [{"a": False}] + codings = pick_contrasts_for_term(Term(["a", "b"]), set(), used) + assert codings == [{"a": True, "b": False}] + used_snapshot = set(used) + codings = pick_contrasts_for_term(Term(["c", "d"]), set(), used) + assert codings == [{"d": False}, {"c": False, "d": True}] + # Do it again backwards, to make sure we're deterministic with respect to + # order: + codings = pick_contrasts_for_term(Term(["d", "c"]), set(), used_snapshot) + assert codings == [{"c": False}, {"c": True, "d": False}] diff --git a/venv/lib/python3.10/site-packages/patsy/splines.py b/venv/lib/python3.10/site-packages/patsy/splines.py new file mode 100644 index 0000000000000000000000000000000000000000..6504b98f374096152e642ebadda2ff56242e853a --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/splines.py @@ -0,0 +1,429 @@ +# This file is part of Patsy +# Copyright (C) 2012-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# R-compatible spline basis functions + +# These are made available in the patsy.* namespace +__all__ = ["bs"] + +import numpy as np + +from patsy.util import have_pandas, no_pickling, assert_no_pickling +from patsy.state import stateful_transform + +if have_pandas: + import pandas + + +def _eval_bspline_basis(x, knots, degree): + try: + from scipy.interpolate import splev + except ImportError: # pragma: no cover + raise ImportError("spline functionality requires scipy") + # 'knots' are assumed to be already pre-processed. E.g. usually you + # want to include duplicate copies of boundary knots; you should do + # that *before* calling this constructor. + knots = np.atleast_1d(np.asarray(knots, dtype=float)) + assert knots.ndim == 1 + knots.sort() + degree = int(degree) + x = np.atleast_1d(x) + if x.ndim == 2 and x.shape[1] == 1: + x = x[:, 0] + assert x.ndim == 1 + # XX FIXME: when points fall outside of the boundaries, splev and R seem + # to handle them differently. I don't know why yet. So until we understand + # this and decide what to do with it, I'm going to play it safe and + # disallow such points. + if np.min(x) < np.min(knots) or np.max(x) > np.max(knots): + raise NotImplementedError( + "some data points fall outside the " + "outermost knots, and I'm not sure how " + "to handle them. (Patches accepted!)" + ) + # Thanks to Charles Harris for explaining splev. It's not well + # documented, but basically it computes an arbitrary b-spline basis + # given knots and degree on some specified points (or derivatives + # thereof, but we don't use that functionality), and then returns some + # linear combination of these basis functions. To get out the basis + # functions themselves, we use linear combinations like [1, 0, 0], [0, + # 1, 0], [0, 0, 1]. + # NB: This probably makes it rather inefficient (though I haven't checked + # to be sure -- maybe the fortran code actually skips computing the basis + # function for coefficients that are zero). + # Note: the order of a spline is the same as its degree + 1. + # Note: there are (len(knots) - order) basis functions. + n_bases = len(knots) - (degree + 1) + basis = np.empty((x.shape[0], n_bases), dtype=float) + for i in range(n_bases): + coefs = np.zeros((n_bases,)) + coefs[i] = 1 + basis[:, i] = splev(x, (knots, coefs, degree)) + return basis + + +def _R_compat_quantile(x, probs): + # return np.percentile(x, 100 * np.asarray(probs)) + probs = np.asarray(probs) + quantiles = np.asarray( + [np.percentile(x, 100 * prob) for prob in probs.ravel(order="C")] + ) + return quantiles.reshape(probs.shape, order="C") + + +def test__R_compat_quantile(): + def t(x, prob, expected): + assert np.allclose(_R_compat_quantile(x, prob), expected) + + t([10, 20], 0.5, 15) + t([10, 20], 0.3, 13) + t([10, 20], [0.3, 0.7], [13, 17]) + t(list(range(10)), [0.3, 0.7], [2.7, 6.3]) + + +class BS(object): + """bs(x, df=None, knots=None, degree=3, include_intercept=False, lower_bound=None, upper_bound=None) + + Generates a B-spline basis for ``x``, allowing non-linear fits. The usual + usage is something like:: + + y ~ 1 + bs(x, 4) + + to fit ``y`` as a smooth function of ``x``, with 4 degrees of freedom + given to the smooth. + + :arg df: The number of degrees of freedom to use for this spline. The + return value will have this many columns. You must specify at least one + of ``df`` and ``knots``. + :arg knots: The interior knots to use for the spline. If unspecified, then + equally spaced quantiles of the input data are used. You must specify at + least one of ``df`` and ``knots``. + :arg degree: The degree of the spline to use. + :arg include_intercept: If ``True``, then the resulting + spline basis will span the intercept term (i.e., the constant + function). If ``False`` (the default) then this will not be the case, + which is useful for avoiding overspecification in models that include + multiple spline terms and/or an intercept term. + :arg lower_bound: The lower exterior knot location. + :arg upper_bound: The upper exterior knot location. + + A spline with ``degree=0`` is piecewise constant with breakpoints at each + knot, and the default knot positions are quantiles of the input. So if you + find yourself in the situation of wanting to quantize a continuous + variable into ``num_bins`` equal-sized bins with a constant effect across + each bin, you can use ``bs(x, num_bins - 1, degree=0)``. (The ``- 1`` is + because one degree of freedom will be taken by the intercept; + alternatively, you could leave the intercept term out of your model and + use ``bs(x, num_bins, degree=0, include_intercept=True)``. + + A spline with ``degree=1`` is piecewise linear with breakpoints at each + knot. + + The default is ``degree=3``, which gives a cubic b-spline. + + This is a stateful transform (for details see + :ref:`stateful-transforms`). If ``knots``, ``lower_bound``, or + ``upper_bound`` are not specified, they will be calculated from the data + and then the chosen values will be remembered and re-used for prediction + from the fitted model. + + Using this function requires scipy be installed. + + .. note:: This function is very similar to the R function of the same + name. In cases where both return output at all (e.g., R's ``bs`` will + raise an error if ``degree=0``, while patsy's will not), they should + produce identical output given identical input and parameter settings. + + .. warning:: I'm not sure on what the proper handling of points outside + the lower/upper bounds is, so for now attempting to evaluate a spline + basis at such points produces an error. Patches gratefully accepted. + + .. versionadded:: 0.2.0 + """ + + def __init__(self): + self._tmp = {} + self._degree = None + self._all_knots = None + + def memorize_chunk( + self, + x, + df=None, + knots=None, + degree=3, + include_intercept=False, + lower_bound=None, + upper_bound=None, + ): + args = { + "df": df, + "knots": knots, + "degree": degree, + "include_intercept": include_intercept, + "lower_bound": lower_bound, + "upper_bound": upper_bound, + } + self._tmp["args"] = args + # XX: check whether we need x values before saving them + x = np.atleast_1d(x) + if x.ndim == 2 and x.shape[1] == 1: + x = x[:, 0] + if x.ndim > 1: + raise ValueError("input to 'bs' must be 1-d, " "or a 2-d column vector") + # There's no better way to compute exact quantiles than memorizing + # all data. + self._tmp.setdefault("xs", []).append(x) + + def memorize_finish(self): + tmp = self._tmp + args = tmp["args"] + del self._tmp + + if args["degree"] < 0: + raise ValueError( + "degree must be greater than 0 (not %r)" % (args["degree"],) + ) + if int(args["degree"]) != args["degree"]: + raise ValueError("degree must be an integer (not %r)" % (self._degree,)) + + # These are guaranteed to all be 1d vectors by the code above + x = np.concatenate(tmp["xs"]) + if args["df"] is None and args["knots"] is None: + raise ValueError("must specify either df or knots") + order = args["degree"] + 1 + if args["df"] is not None: + n_inner_knots = args["df"] - order + if not args["include_intercept"]: + n_inner_knots += 1 + if n_inner_knots < 0: + raise ValueError( + "df=%r is too small for degree=%r and " + "include_intercept=%r; must be >= %s" + % ( + args["df"], + args["degree"], + args["include_intercept"], + # We know that n_inner_knots is negative; + # if df were that much larger, it would + # have been zero, and things would work. + args["df"] - n_inner_knots, + ) + ) + if args["knots"] is not None: + if len(args["knots"]) != n_inner_knots: + raise ValueError( + "df=%s with degree=%r implies %s knots, " + "but %s knots were provided" + % ( + args["df"], + args["degree"], + n_inner_knots, + len(args["knots"]), + ) + ) + else: + # Need to compute inner knots + knot_quantiles = np.linspace(0, 1, n_inner_knots + 2)[1:-1] + inner_knots = _R_compat_quantile(x, knot_quantiles) + if args["knots"] is not None: + inner_knots = args["knots"] + if args["lower_bound"] is not None: + lower_bound = args["lower_bound"] + else: + lower_bound = np.min(x) + if args["upper_bound"] is not None: + upper_bound = args["upper_bound"] + else: + upper_bound = np.max(x) + if lower_bound > upper_bound: + raise ValueError( + "lower_bound > upper_bound (%r > %r)" % (lower_bound, upper_bound) + ) + inner_knots = np.asarray(inner_knots) + if inner_knots.ndim > 1: + raise ValueError("knots must be 1 dimensional") + if np.any(inner_knots < lower_bound): + raise ValueError( + "some knot values (%s) fall below lower bound " + "(%r)" % (inner_knots[inner_knots < lower_bound], lower_bound) + ) + if np.any(inner_knots > upper_bound): + raise ValueError( + "some knot values (%s) fall above upper bound " + "(%r)" % (inner_knots[inner_knots > upper_bound], upper_bound) + ) + all_knots = np.concatenate(([lower_bound, upper_bound] * order, inner_knots)) + all_knots.sort() + + self._degree = args["degree"] + self._all_knots = all_knots + + def transform( + self, + x, + df=None, + knots=None, + degree=3, + include_intercept=False, + lower_bound=None, + upper_bound=None, + ): + basis = _eval_bspline_basis(x, self._all_knots, self._degree) + if not include_intercept: + basis = basis[:, 1:] + if have_pandas: + if isinstance(x, (pandas.Series, pandas.DataFrame)): + basis = pandas.DataFrame(basis) + basis.index = x.index + return basis + + __getstate__ = no_pickling + + +bs = stateful_transform(BS) + + +def test_bs_compat(): + from patsy.test_state import check_stateful + from patsy.test_splines_bs_data import R_bs_test_x, R_bs_test_data, R_bs_num_tests + + lines = R_bs_test_data.split("\n") + tests_ran = 0 + start_idx = lines.index("--BEGIN TEST CASE--") + while True: + if not lines[start_idx] == "--BEGIN TEST CASE--": + break + start_idx += 1 + stop_idx = lines.index("--END TEST CASE--", start_idx) + block = lines[start_idx:stop_idx] + test_data = {} + for line in block: + key, value = line.split("=", 1) + test_data[key] = value + # Translate the R output into Python calling conventions + kwargs = { + "degree": int(test_data["degree"]), + # integer, or None + "df": eval(test_data["df"]), + # np.array() call, or None + "knots": eval(test_data["knots"]), + } + if test_data["Boundary.knots"] != "None": + lower, upper = eval(test_data["Boundary.knots"]) + kwargs["lower_bound"] = lower + kwargs["upper_bound"] = upper + kwargs["include_intercept"] = test_data["intercept"] == "TRUE" + # Special case: in R, setting intercept=TRUE increases the effective + # dof by 1. Adjust our arguments to match. + # if kwargs["df"] is not None and kwargs["include_intercept"]: + # kwargs["df"] += 1 + output = np.asarray(eval(test_data["output"])) + if kwargs["df"] is not None: + assert output.shape[1] == kwargs["df"] + # Do the actual test + check_stateful(BS, False, R_bs_test_x, output, **kwargs) + tests_ran += 1 + # Set up for the next one + start_idx = stop_idx + 1 + assert tests_ran == R_bs_num_tests + + +test_bs_compat.slow = 1 + + +# This isn't checked by the above, because R doesn't have zero degree +# b-splines. +def test_bs_0degree(): + x = np.logspace(-1, 1, 10) + result = bs(x, knots=[1, 4], degree=0, include_intercept=True) + assert result.shape[1] == 3 + expected_0 = np.zeros(10) + expected_0[x < 1] = 1 + assert np.array_equal(result[:, 0], expected_0) + expected_1 = np.zeros(10) + expected_1[(x >= 1) & (x < 4)] = 1 + assert np.array_equal(result[:, 1], expected_1) + expected_2 = np.zeros(10) + expected_2[x >= 4] = 1 + assert np.array_equal(result[:, 2], expected_2) + # Check handling of points that exactly fall on knots. They arbitrarily + # get included into the larger region, not the smaller. This is consistent + # with Python's half-open interval convention -- each basis function is + # constant on [knot[i], knot[i + 1]). + assert np.array_equal( + bs([0, 1, 2], degree=0, knots=[1], include_intercept=True), + [[1, 0], [0, 1], [0, 1]], + ) + + result_int = bs(x, knots=[1, 4], degree=0, include_intercept=True) + result_no_int = bs(x, knots=[1, 4], degree=0, include_intercept=False) + assert np.array_equal(result_int[:, 1:], result_no_int) + + +def test_bs_errors(): + import pytest + + x = np.linspace(-10, 10, 20) + # error checks: + # out of bounds + pytest.raises(NotImplementedError, bs, x, 3, lower_bound=0) + pytest.raises(NotImplementedError, bs, x, 3, upper_bound=0) + # must specify df or knots + pytest.raises(ValueError, bs, x) + # df/knots match/mismatch (with and without intercept) + # match: + bs(x, df=10, include_intercept=False, knots=[0] * 7) + bs(x, df=10, include_intercept=True, knots=[0] * 6) + bs(x, df=10, include_intercept=False, knots=[0] * 9, degree=1) + bs(x, df=10, include_intercept=True, knots=[0] * 8, degree=1) + # too many knots: + pytest.raises(ValueError, bs, x, df=10, include_intercept=False, knots=[0] * 8) + pytest.raises(ValueError, bs, x, df=10, include_intercept=True, knots=[0] * 7) + pytest.raises( + ValueError, bs, x, df=10, include_intercept=False, knots=[0] * 10, degree=1 + ) + pytest.raises( + ValueError, bs, x, df=10, include_intercept=True, knots=[0] * 9, degree=1 + ) + # too few knots: + pytest.raises(ValueError, bs, x, df=10, include_intercept=False, knots=[0] * 6) + pytest.raises(ValueError, bs, x, df=10, include_intercept=True, knots=[0] * 5) + pytest.raises( + ValueError, bs, x, df=10, include_intercept=False, knots=[0] * 8, degree=1 + ) + pytest.raises( + ValueError, bs, x, df=10, include_intercept=True, knots=[0] * 7, degree=1 + ) + # df too small + pytest.raises(ValueError, bs, x, df=1, degree=3) + pytest.raises(ValueError, bs, x, df=3, degree=5) + # bad degree + pytest.raises(ValueError, bs, x, df=10, degree=-1) + pytest.raises(ValueError, bs, x, df=10, degree=1.5) + # upper_bound < lower_bound + pytest.raises(ValueError, bs, x, 3, lower_bound=1, upper_bound=-1) + # multidimensional input + pytest.raises(ValueError, bs, np.column_stack((x, x)), 3) + # unsorted knots are okay, and get sorted + assert np.array_equal(bs(x, knots=[1, 4]), bs(x, knots=[4, 1])) + # 2d knots + pytest.raises(ValueError, bs, x, knots=[[0], [20]]) + # knots > upper_bound + pytest.raises(ValueError, bs, x, knots=[0, 20]) + pytest.raises(ValueError, bs, x, knots=[0, 4], upper_bound=3) + # knots < lower_bound + pytest.raises(ValueError, bs, x, knots=[-20, 0]) + pytest.raises(ValueError, bs, x, knots=[-4, 0], lower_bound=-3) + + +# differences between bs and ns (since the R code is a pile of copy-paste): +# - degree is always 3 +# - different number of interior knots given df (b/c fewer dof used at edges I +# guess) +# - boundary knots always repeated exactly 4 times (same as bs with degree=3) +# - complications at the end to handle boundary conditions +# the 'rcs' function uses slightly different conventions -- in particular it +# picks boundary knots that are not quite at the edges of the data, which +# makes sense for a natural spline. diff --git a/venv/lib/python3.10/site-packages/patsy/state.py b/venv/lib/python3.10/site-packages/patsy/state.py new file mode 100644 index 0000000000000000000000000000000000000000..8d674ba240d9af5d4c63728367ba555816100c18 --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/state.py @@ -0,0 +1,199 @@ +# This file is part of Patsy +# Copyright (C) 2011 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Stateful transform protocol: +# def __init__(self): +# pass +# def memorize_chunk(self, input_data): +# return None +# def memorize_finish(self): +# return None +# def transform(self, input_data): +# return output_data + +# BETTER WAY: always run the first row of data through the builder alone, and +# check that it gives the same output row as when running the whole block of +# data through at once. This gives us the same information, but it's robust +# against people writing their own centering functions. + +# QUESTION: right now we refuse to even fit a model that contains a +# my_transform(x)-style function. Maybe we should allow it to be fit (with a +# warning), and only disallow making predictions with it? Need to revisit this +# question once it's clearer what exactly our public API will look like, +# because right now I'm not sure how to tell whether we are being called for +# fitting versus being called for prediction. + +from functools import wraps +import numpy as np +from patsy.util import ( + atleast_2d_column_default, + asarray_or_pandas, + pandas_friendly_reshape, + wide_dtype_for, + safe_issubdtype, + no_pickling, + assert_no_pickling, +) + +# These are made available in the patsy.* namespace +__all__ = [ + "stateful_transform", + "center", + "standardize", + "scale", +] + + +def stateful_transform(class_): + """Create a stateful transform callable object from a class that fulfills + the :ref:`stateful transform protocol `. + """ + + @wraps(class_) + def stateful_transform_wrapper(*args, **kwargs): + transform = class_() + transform.memorize_chunk(*args, **kwargs) + transform.memorize_finish() + return transform.transform(*args, **kwargs) + + stateful_transform_wrapper.__patsy_stateful_transform__ = class_ + return stateful_transform_wrapper + + +# class NonIncrementalStatefulTransform(object): +# def __init__(self): +# self._data = [] +# +# def memorize_chunk(self, input_data, *args, **kwargs): +# self._data.append(input_data) +# self._args = _args +# self._kwargs = kwargs +# +# def memorize_finish(self): +# all_data = np.vstack(self._data) +# args = self._args +# kwargs = self._kwargs +# del self._data +# del self._args +# del self._kwargs +# self.memorize_all(all_data, *args, **kwargs) +# +# def memorize_all(self, input_data, *args, **kwargs): +# raise NotImplementedError +# +# def transform(self, input_data, *args, **kwargs): +# raise NotImplementedError +# +# class QuantileEstimatingTransform(NonIncrementalStatefulTransform): +# def memorize_all(self, input_data, *args, **kwargs): + + +class Center(object): + """center(x) + + A stateful transform that centers input data, i.e., subtracts the mean. + + If input has multiple columns, centers each column separately. + + Equivalent to ``standardize(x, rescale=False)`` + """ + + def __init__(self): + self._sum = None + self._count = 0 + + def memorize_chunk(self, x): + x = atleast_2d_column_default(x) + self._count += x.shape[0] + this_total = np.sum(x, 0, dtype=wide_dtype_for(x)) + # This is to handle potentially multi-column x's: + if self._sum is None: + self._sum = this_total + else: + self._sum += this_total + + def memorize_finish(self): + pass + + def transform(self, x): + x = asarray_or_pandas(x) + # This doesn't copy data unless our input is a DataFrame that has + # heterogeneous types. And in that case we're going to be munging the + # types anyway, so copying isn't a big deal. + x_arr = np.asarray(x) + if safe_issubdtype(x_arr.dtype, np.integer): + dt = float + else: + dt = x_arr.dtype + mean_val = np.asarray(self._sum / self._count, dtype=dt) + centered = atleast_2d_column_default(x, preserve_pandas=True) - mean_val + return pandas_friendly_reshape(centered, x.shape) + + __getstate__ = no_pickling + + +center = stateful_transform(Center) + + +# See: +# http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm +# or page 232 of Knuth vol. 3 (3rd ed.). +class Standardize(object): + """standardize(x, center=True, rescale=True, ddof=0) + + A stateful transform that standardizes input data, i.e. it subtracts the + mean and divides by the sample standard deviation. + + Either centering or rescaling or both can be disabled by use of keyword + arguments. The `ddof` argument controls the delta degrees of freedom when + computing the standard deviation (cf. :func:`numpy.std`). The default of + ``ddof=0`` produces the maximum likelihood estimate; use ``ddof=1`` if you + prefer the square root of the unbiased estimate of the variance. + + If input has multiple columns, standardizes each column separately. + + .. note:: This function computes the mean and standard deviation using a + memory-efficient online algorithm, making it suitable for use with + large incrementally processed data-sets. + """ + + def __init__(self): + self.current_n = 0 + self.current_mean = None + self.current_M2 = None + + def memorize_chunk(self, x, center=True, rescale=True, ddof=0): + x = atleast_2d_column_default(x) + if self.current_mean is None: + self.current_mean = np.zeros(x.shape[1], dtype=wide_dtype_for(x)) + self.current_M2 = np.zeros(x.shape[1], dtype=wide_dtype_for(x)) + # XX this can surely be vectorized but I am feeling lazy: + for i in range(x.shape[0]): + self.current_n += 1 + delta = x[i, :] - self.current_mean + self.current_mean += delta / self.current_n + self.current_M2 += delta * (x[i, :] - self.current_mean) + + def memorize_finish(self): + pass + + def transform(self, x, center=True, rescale=True, ddof=0): + # XX: this forces all inputs to double-precision real, even if the + # input is single- or extended-precision or complex. But I got all + # tangled up in knots trying to do that without breaking something + # else (e.g. by requiring an extra copy). + x = asarray_or_pandas(x, copy=True, dtype=float) + x_2d = atleast_2d_column_default(x, preserve_pandas=True) + if center: + x_2d -= self.current_mean + if rescale: + x_2d /= np.sqrt(self.current_M2 / (self.current_n - ddof)) + return pandas_friendly_reshape(x_2d, x.shape) + + __getstate__ = no_pickling + + +standardize = stateful_transform(Standardize) +# R compatibility: +scale = standardize diff --git a/venv/lib/python3.10/site-packages/patsy/test_build.py b/venv/lib/python3.10/site-packages/patsy/test_build.py new file mode 100644 index 0000000000000000000000000000000000000000..bad3be6556fc5f12d847b934222d3a5530c3506c --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/test_build.py @@ -0,0 +1,798 @@ +# This file is part of Patsy +# Copyright (C) 2012-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# There are a number of unit tests in build.py, but this file contains more +# thorough tests of the overall design matrix building system. (These are +# still not exhaustive end-to-end tests, though -- for that see +# test_highlevel.py.) + +import numpy as np +import pytest +from patsy import PatsyError +from patsy.util import atleast_2d_column_default, have_pandas, have_pandas_categorical +from patsy.desc import Term, INTERCEPT +from patsy.build import build_design_matrices, design_matrix_builders +from patsy.categorical import C +from patsy.user_util import balanced, LookupFactor +from patsy.design_info import DesignMatrix, DesignInfo + +if have_pandas: + import pandas + + +def assert_full_rank(m): + m = atleast_2d_column_default(m) + if m.shape[1] == 0: + return True + u, s, v = np.linalg.svd(m) + rank = np.sum(s > 1e-10) + assert rank == m.shape[1] + + +def test_assert_full_rank(): + assert_full_rank(np.eye(10)) + assert_full_rank([[1, 0], [1, 0], [1, 0], [1, 1]]) + pytest.raises(AssertionError, assert_full_rank, [[1, 0], [2, 0]]) + pytest.raises(AssertionError, assert_full_rank, [[1, 2], [2, 4]]) + pytest.raises(AssertionError, assert_full_rank, [[1, 2, 3], [1, 10, 100]]) + # col1 + col2 = col3 + pytest.raises(AssertionError, assert_full_rank, [[1, 2, 3], [1, 5, 6], [1, 6, 7]]) + + +def make_termlist(*entries): + terms = [] + for entry in entries: + terms.append(Term([LookupFactor(name) for name in entry])) + return terms + + +def check_design_matrix(mm, expected_rank, termlist, column_names=None): + assert_full_rank(mm) + assert set(mm.design_info.terms) == set(termlist) + if column_names is not None: + assert mm.design_info.column_names == column_names + assert mm.ndim == 2 + assert mm.shape[1] == expected_rank + + +def make_matrix(data, expected_rank, entries, column_names=None): + termlist = make_termlist(*entries) + + def iter_maker(): + yield data + + design_infos = design_matrix_builders([termlist], iter_maker, eval_env=0) + matrices = build_design_matrices(design_infos, data) + matrix = matrices[0] + assert design_infos[0].term_slices == matrix.design_info.term_slices + assert design_infos[0].column_names == matrix.design_info.column_names + assert matrix.design_info is design_infos[0] + check_design_matrix(matrix, expected_rank, termlist, column_names=column_names) + return matrix + + +def test_simple(): + data = balanced(a=2, b=2) + x1 = data["x1"] = np.linspace(0, 1, len(data["a"])) + x2 = data["x2"] = data["x1"] ** 2 + + m = make_matrix(data, 2, [["a"]], column_names=["a[a1]", "a[a2]"]) + assert np.allclose(m, [[1, 0], [1, 0], [0, 1], [0, 1]]) + + m = make_matrix(data, 2, [[], ["a"]], column_names=["Intercept", "a[T.a2]"]) + assert np.allclose(m, [[1, 0], [1, 0], [1, 1], [1, 1]]) + + m = make_matrix( + data, + 4, + [["a", "b"]], + column_names=["a[a1]:b[b1]", "a[a2]:b[b1]", "a[a1]:b[b2]", "a[a2]:b[b2]"], + ) + assert np.allclose(m, [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) + + m = make_matrix( + data, + 4, + [[], ["a"], ["b"], ["a", "b"]], + column_names=["Intercept", "a[T.a2]", "b[T.b2]", "a[T.a2]:b[T.b2]"], + ) + assert np.allclose(m, [[1, 0, 0, 0], [1, 0, 1, 0], [1, 1, 0, 0], [1, 1, 1, 1]]) + + m = make_matrix( + data, + 4, + [[], ["b"], ["a"], ["b", "a"]], + column_names=["Intercept", "b[T.b2]", "a[T.a2]", "b[T.b2]:a[T.a2]"], + ) + assert np.allclose(m, [[1, 0, 0, 0], [1, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]]) + + m = make_matrix( + data, + 4, + [["a"], ["x1"], ["a", "x1"]], + column_names=["a[a1]", "a[a2]", "x1", "a[T.a2]:x1"], + ) + assert np.allclose( + m, + [ + [1, 0, x1[0], 0], + [1, 0, x1[1], 0], + [0, 1, x1[2], x1[2]], + [0, 1, x1[3], x1[3]], + ], + ) + + m = make_matrix( + data, 3, [["x1"], ["x2"], ["x2", "x1"]], column_names=["x1", "x2", "x2:x1"] + ) + assert np.allclose(m, np.column_stack((x1, x2, x1 * x2))) + + +def test_R_bugs(): + data = balanced(a=2, b=2, c=2) + data["x"] = np.linspace(0, 1, len(data["a"])) + # For "1 + a:b", R produces a design matrix with too many columns (5 + # instead of 4), because it can't tell that there is a redundancy between + # the two terms. + make_matrix(data, 4, [[], ["a", "b"]]) + # For "0 + a:x + a:b", R produces a design matrix with too few columns (4 + # instead of 6), because it thinks that there is a redundancy which + # doesn't exist. + make_matrix(data, 6, [["a", "x"], ["a", "b"]]) + # This can be compared with "0 + a:c + a:b", where the redundancy does + # exist. Confusingly, adding another categorical factor increases the + # baseline dimensionality to 8, and then the redundancy reduces it to 6 + # again, so the result is the same as before but for different reasons. (R + # does get this one right, but we might as well test it.) + make_matrix(data, 6, [["a", "c"], ["a", "b"]]) + + +def test_redundancy_thoroughly(): + # To make sure there aren't any lurking bugs analogous to the ones that R + # has (see above), we check that we get the correct matrix rank for every + # possible combination of 2 categorical and 2 numerical factors. + data = balanced(a=2, b=2, repeat=5) + data["x1"] = np.linspace(0, 1, len(data["a"])) + data["x2"] = data["x1"] ** 2 + + def all_subsets(l): + if not l: + yield tuple() + else: + obj = l[0] + for subset in all_subsets(l[1:]): + yield tuple(sorted(subset)) + yield tuple(sorted((obj,) + subset)) + + all_terms = list(all_subsets(("a", "b", "x1", "x2"))) + all_termlist_templates = list(all_subsets(all_terms)) + print(len(all_termlist_templates)) + # eliminate some of the symmetric versions to speed things up + redundant = [ + [("b",), ("a",)], + [("x2",), ("x1",)], + [("b", "x2"), ("a", "x1")], + [("a", "b", "x2"), ("a", "b", "x1")], + [("b", "x1", "x2"), ("a", "x1", "x2")], + ] + count = 0 + import time + + start = time.time() + for termlist_template in all_termlist_templates: + termlist_set = set(termlist_template) + for dispreferred, preferred in redundant: + if dispreferred in termlist_set and preferred not in termlist_set: + break + else: + expanded_terms = set() + for term_template in termlist_template: + numeric = tuple([t for t in term_template if t.startswith("x")]) + rest = [t for t in term_template if not t.startswith("x")] + for subset_rest in all_subsets(rest): + expanded_terms.add(frozenset(subset_rest + numeric)) + # Because our categorical variables have 2 levels, each expanded + # term corresponds to 1 unique dimension of variation + expected_rank = len(expanded_terms) + if termlist_template in [(), ((),)]: + # No data dependence, should fail + pytest.raises( + PatsyError, make_matrix, data, expected_rank, termlist_template + ) + else: + make_matrix(data, expected_rank, termlist_template) + count += 1 + if count % 100 == 0: + print("Completed:", count) + print("Took %0.2f seconds" % (time.time() - start,)) + + +test_redundancy_thoroughly.slow = 1 + + +def test_data_types(): + basic_dict = {"a": ["a1", "a2", "a1", "a2"], "x": [1, 2, 3, 4]} + # On Python 2, this is identical to basic_dict: + basic_dict_bytes = dict(basic_dict) + basic_dict_bytes["a"] = [s.encode("ascii") for s in basic_dict_bytes["a"]] + # On Python 3, this is identical to basic_dict: + basic_dict_unicode = {"a": ["a1", "a2", "a1", "a2"], "x": [1, 2, 3, 4]} + basic_dict_unicode = dict(basic_dict) + basic_dict_unicode["a"] = [str(s) for s in basic_dict_unicode["a"]] + + structured_array_bytes = np.array( + list(zip(basic_dict["a"], basic_dict["x"])), dtype=[("a", "S2"), ("x", int)] + ) + structured_array_unicode = np.array( + list(zip(basic_dict["a"], basic_dict["x"])), dtype=[("a", "U2"), ("x", int)] + ) + recarray_bytes = structured_array_bytes.view(np.recarray) + recarray_unicode = structured_array_unicode.view(np.recarray) + datas = [ + basic_dict, + structured_array_bytes, + structured_array_unicode, + recarray_bytes, + recarray_unicode, + ] + if have_pandas: + df_bytes = pandas.DataFrame(basic_dict_bytes) + datas.append(df_bytes) + df_unicode = pandas.DataFrame(basic_dict_unicode) + datas.append(df_unicode) + for data in datas: + m = make_matrix( + data, + 4, + [["a"], ["a", "x"]], + column_names=["a[a1]", "a[a2]", "a[a1]:x", "a[a2]:x"], + ) + assert np.allclose(m, [[1, 0, 1, 0], [0, 1, 0, 2], [1, 0, 3, 0], [0, 1, 0, 4]]) + + +def test_build_design_matrices_dtype(): + data = {"x": [1, 2, 3]} + + def iter_maker(): + yield data + + builder = design_matrix_builders([make_termlist("x")], iter_maker, 0)[0] + + mat = build_design_matrices([builder], data)[0] + assert mat.dtype == np.dtype(np.float64) + + mat = build_design_matrices([builder], data, dtype=np.float32)[0] + assert mat.dtype == np.dtype(np.float32) + + if hasattr(np, "float128"): + mat = build_design_matrices([builder], data, dtype=np.float128)[0] + assert mat.dtype == np.dtype(np.float128) + + +def test_return_type(): + data = {"x": [1, 2, 3]} + + def iter_maker(): + yield data + + builder = design_matrix_builders([make_termlist("x")], iter_maker, 0)[0] + + # Check explicitly passing return_type="matrix" works + mat = build_design_matrices([builder], data, return_type="matrix")[0] + assert isinstance(mat, DesignMatrix) + + # Check that nonsense is detected + pytest.raises( + PatsyError, build_design_matrices, [builder], data, return_type="asdfsadf" + ) + + +def test_NA_action(): + initial_data = {"x": [1, 2, 3], "c": ["c1", "c2", "c1"]} + + def iter_maker(): + yield initial_data + + builder = design_matrix_builders([make_termlist("x", "c")], iter_maker, 0)[0] + + # By default drops rows containing either NaN or None + mat = build_design_matrices( + [builder], + {"x": [10.0, np.nan, 20.0], "c": np.asarray(["c1", "c2", None], dtype=object)}, + )[0] + assert mat.shape == (1, 3) + assert np.array_equal(mat, [[1.0, 0.0, 10.0]]) + + # NA_action="a string" also accepted: + mat = build_design_matrices( + [builder], + {"x": [10.0, np.nan, 20.0], "c": np.asarray(["c1", "c2", None], dtype=object)}, + NA_action="drop", + )[0] + assert mat.shape == (1, 3) + assert np.array_equal(mat, [[1.0, 0.0, 10.0]]) + + # And objects + from patsy.missing import NAAction + + # allows NaN's to pass through + NA_action = NAAction(NA_types=[]) + mat = build_design_matrices( + [builder], + {"x": [10.0, np.nan], "c": np.asarray(["c1", "c2"], dtype=object)}, + NA_action=NA_action, + )[0] + assert mat.shape == (2, 3) + # According to this (and only this) function, NaN == NaN. + np.testing.assert_array_equal(mat, [[1.0, 0.0, 10.0], [0.0, 1.0, np.nan]]) + + # NA_action="raise" + pytest.raises( + PatsyError, + build_design_matrices, + [builder], + {"x": [10.0, np.nan, 20.0], "c": np.asarray(["c1", "c2", None], dtype=object)}, + NA_action="raise", + ) + + +def test_NA_drop_preserves_levels(): + # Even if all instances of some level are dropped, we still include it in + # the output matrix (as an all-zeros column) + data = {"x": [1.0, np.nan, 3.0], "c": ["c1", "c2", "c3"]} + + def iter_maker(): + yield data + + design_info = design_matrix_builders([make_termlist("x", "c")], iter_maker, 0)[0] + + assert design_info.column_names == ["c[c1]", "c[c2]", "c[c3]", "x"] + + (mat,) = build_design_matrices([design_info], data) + + assert mat.shape == (2, 4) + assert np.array_equal(mat, [[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 3.0]]) + + +def test_return_type_pandas(): + if not have_pandas: + return + + data = pandas.DataFrame( + {"x": [1, 2, 3], "y": [4, 5, 6], "a": ["a1", "a2", "a1"]}, index=[10, 20, 30] + ) + + def iter_maker(): + yield data + + (int_builder,) = design_matrix_builders([make_termlist([])], iter_maker, 0) + (y_builder, x_builder) = design_matrix_builders( + [make_termlist("y"), make_termlist("x")], iter_maker, eval_env=0 + ) + (x_a_builder,) = design_matrix_builders( + [make_termlist("x", "a")], iter_maker, eval_env=0 + ) + (x_y_builder,) = design_matrix_builders( + [make_termlist("x", "y")], iter_maker, eval_env=0 + ) + # Index compatibility is always checked for pandas input, regardless of + # whether we're producing pandas output + pytest.raises( + PatsyError, + build_design_matrices, + [x_a_builder], + {"x": data["x"], "a": data["a"][::-1]}, + ) + pytest.raises( + PatsyError, + build_design_matrices, + [y_builder, x_builder], + {"x": data["x"], "y": data["y"][::-1]}, + ) + + # And we also check consistency between data.index and value indexes + # Creating a mismatch between these is a bit tricky. We want a data object + # such that isinstance(data, DataFrame), but data["x"].index != + # data.index. + class CheatingDataFrame(pandas.DataFrame): + def __getitem__(self, key): + if key == "x": + return pandas.DataFrame.__getitem__(self, key)[::-1] + else: + return pandas.DataFrame.__getitem__(self, key) + + pytest.raises( + PatsyError, build_design_matrices, [x_builder], CheatingDataFrame(data) + ) + + # A mix of pandas input and unindexed input is fine + (mat,) = build_design_matrices([x_y_builder], {"x": data["x"], "y": [40, 50, 60]}) + assert np.allclose(mat, [[1, 40], [2, 50], [3, 60]]) + + # with return_type="dataframe", we get out DataFrames with nice indices + # and nice column names and design_info + y_df, x_df = build_design_matrices( + [y_builder, x_builder], data, return_type="dataframe" + ) + assert isinstance(y_df, pandas.DataFrame) + assert isinstance(x_df, pandas.DataFrame) + assert np.array_equal(y_df, [[4], [5], [6]]) + assert np.array_equal(x_df, [[1], [2], [3]]) + assert np.array_equal(y_df.index, [10, 20, 30]) + assert np.array_equal(x_df.index, [10, 20, 30]) + assert np.array_equal(y_df.columns, ["y"]) + assert np.array_equal(x_df.columns, ["x"]) + assert y_df.design_info.column_names == ["y"] + assert x_df.design_info.column_names == ["x"] + assert y_df.design_info.term_names == ["y"] + assert x_df.design_info.term_names == ["x"] + # Same with mix of pandas and unindexed info, even if in different + # matrices + y_df, x_df = build_design_matrices( + [y_builder, x_builder], + {"y": [7, 8, 9], "x": data["x"]}, + return_type="dataframe", + ) + assert isinstance(y_df, pandas.DataFrame) + assert isinstance(x_df, pandas.DataFrame) + assert np.array_equal(y_df, [[7], [8], [9]]) + assert np.array_equal(x_df, [[1], [2], [3]]) + assert np.array_equal(y_df.index, [10, 20, 30]) + assert np.array_equal(x_df.index, [10, 20, 30]) + assert np.array_equal(y_df.columns, ["y"]) + assert np.array_equal(x_df.columns, ["x"]) + assert y_df.design_info.column_names == ["y"] + assert x_df.design_info.column_names == ["x"] + assert y_df.design_info.term_names == ["y"] + assert x_df.design_info.term_names == ["x"] + # Check categorical works for carrying index too + (x_a_df,) = build_design_matrices( + [x_a_builder], {"x": [-1, -2, -3], "a": data["a"]}, return_type="dataframe" + ) + assert isinstance(x_a_df, pandas.DataFrame) + assert np.array_equal(x_a_df, [[1, 0, -1], [0, 1, -2], [1, 0, -3]]) + assert np.array_equal(x_a_df.index, [10, 20, 30]) + # And if we have no indexed input, then we let pandas make up an index as + # per its usual rules: + (x_y_df,) = build_design_matrices( + [x_y_builder], {"y": [7, 8, 9], "x": [10, 11, 12]}, return_type="dataframe" + ) + assert isinstance(x_y_df, pandas.DataFrame) + assert np.array_equal(x_y_df, [[10, 7], [11, 8], [12, 9]]) + assert np.array_equal(x_y_df.index, [0, 1, 2]) + + # If 'data' is a DataFrame, then that suffices, even if no factors are + # available. + (int_df,) = build_design_matrices([int_builder], data, return_type="dataframe") + assert isinstance(int_df, pandas.DataFrame) + assert np.array_equal(int_df, [[1], [1], [1]]) + assert int_df.index.equals(pandas.Index([10, 20, 30])) + + import patsy.build + + had_pandas = patsy.build.have_pandas + try: + patsy.build.have_pandas = False + # return_type="dataframe" gives a nice error if pandas is not available + pytest.raises( + PatsyError, + build_design_matrices, + [x_builder], + {"x": [1, 2, 3]}, + return_type="dataframe", + ) + finally: + patsy.build.have_pandas = had_pandas + + (x_df,) = build_design_matrices( + [x_a_builder], + {"x": [1.0, np.nan, 3.0], "a": np.asarray([None, "a2", "a1"], dtype=object)}, + NA_action="drop", + return_type="dataframe", + ) + assert x_df.index.equals(pandas.Index([2])) + + +def test_data_mismatch(): + test_cases_twoway = [ + # Data type mismatch + ([1, 2, 3], [True, False, True]), + ( + C(["a", "b", "c"], levels=["c", "b", "a"]), + C(["a", "b", "c"], levels=["a", "b", "c"]), + ), + # column number mismatches + ([[1], [2], [3]], [[1, 1], [2, 2], [3, 3]]), + ([[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[1, 1], [2, 2], [3, 3]]), + ] + test_cases_oneway = [ + ([1, 2, 3], ["a", "b", "c"]), + ([1, 2, 3], C(["a", "b", "c"])), + ([True, False, True], C(["a", "b", "c"])), + ([True, False, True], ["a", "b", "c"]), + ] + setup_predict_only = [ + # This is not an error if both are fed in during make_builders, but it + # is an error to pass one to make_builders and the other to + # make_matrices. + (["a", "b", "c"], ["a", "b", "d"]), + ] + termlist = make_termlist(["x"]) + + def t_incremental(data1, data2): + def iter_maker(): + yield {"x": data1} + yield {"x": data2} + + try: + builders = design_matrix_builders([termlist], iter_maker, 0) + build_design_matrices(builders, {"x": data1}) + build_design_matrices(builders, {"x": data2}) + except PatsyError: + pass + else: + raise AssertionError + + def t_setup_predict(data1, data2): + def iter_maker(): + yield {"x": data1} + + builders = design_matrix_builders([termlist], iter_maker, 0) + pytest.raises(PatsyError, build_design_matrices, builders, {"x": data2}) + + for a, b in test_cases_twoway: + t_incremental(a, b) + t_incremental(b, a) + t_setup_predict(a, b) + t_setup_predict(b, a) + for a, b in test_cases_oneway: + t_incremental(a, b) + t_setup_predict(a, b) + for a, b in setup_predict_only: + t_setup_predict(a, b) + t_setup_predict(b, a) + + pytest.raises( + PatsyError, make_matrix, {"x": [1, 2, 3], "y": [1, 2, 3, 4]}, 2, [["x"], ["y"]] + ) + + +def test_data_independent_builder(): + data = {"x": [1, 2, 3]} + + def iter_maker(): + yield data + + # Trying to build a matrix that doesn't depend on the data at all is an + # error, if: + # - the index argument is not given + # - the data is not a DataFrame + # - there are no other matrices + null_builder = design_matrix_builders([make_termlist()], iter_maker, 0)[0] + pytest.raises(PatsyError, build_design_matrices, [null_builder], data) + + intercept_builder = design_matrix_builders( + [make_termlist([])], iter_maker, eval_env=0 + )[0] + pytest.raises(PatsyError, build_design_matrices, [intercept_builder], data) + + pytest.raises( + PatsyError, build_design_matrices, [null_builder, intercept_builder], data + ) + + # If data is a DataFrame, it sets the number of rows. + if have_pandas: + int_m, null_m = build_design_matrices( + [intercept_builder, null_builder], pandas.DataFrame(data) + ) + assert np.allclose(int_m, [[1], [1], [1]]) + assert null_m.shape == (3, 0) + + # If there are other matrices that do depend on the data, we make the + # data-independent matrices have the same number of rows. + x_termlist = make_termlist(["x"]) + + builders = design_matrix_builders( + [x_termlist, make_termlist()], iter_maker, eval_env=0 + ) + x_m, null_m = build_design_matrices(builders, data) + assert np.allclose(x_m, [[1], [2], [3]]) + assert null_m.shape == (3, 0) + + builders = design_matrix_builders( + [x_termlist, make_termlist([])], iter_maker, eval_env=0 + ) + x_m, null_m = build_design_matrices(builders, data) + x_m, intercept_m = build_design_matrices(builders, data) + assert np.allclose(x_m, [[1], [2], [3]]) + assert np.allclose(intercept_m, [[1], [1], [1]]) + + +def test_same_factor_in_two_matrices(): + data = {"x": [1, 2, 3], "a": ["a1", "a2", "a1"]} + + def iter_maker(): + yield data + + t1 = make_termlist(["x"]) + t2 = make_termlist(["x", "a"]) + builders = design_matrix_builders([t1, t2], iter_maker, eval_env=0) + m1, m2 = build_design_matrices(builders, data) + check_design_matrix(m1, 1, t1, column_names=["x"]) + assert np.allclose(m1, [[1], [2], [3]]) + check_design_matrix(m2, 2, t2, column_names=["x:a[a1]", "x:a[a2]"]) + assert np.allclose(m2, [[1, 0], [0, 2], [3, 0]]) + + +def test_eval_env_type_builder(): + data = {"x": [1, 2, 3]} + + def iter_maker(): + yield data + + pytest.raises( + TypeError, design_matrix_builders, [make_termlist("x")], iter_maker, "foo" + ) + + +def test_categorical(): + data_strings = {"a": ["a1", "a2", "a1"]} + data_categ = {"a": C(["a2", "a1", "a2"])} + datas = [data_strings, data_categ] + if have_pandas_categorical: + data_pandas = {"a": pandas.Categorical(["a1", "a2", "a2"])} + datas.append(data_pandas) + + def t(data1, data2): + def iter_maker(): + yield data1 + + builders = design_matrix_builders( + [make_termlist(["a"])], iter_maker, eval_env=0 + ) + build_design_matrices(builders, data2) + + for data1 in datas: + for data2 in datas: + t(data1, data2) + + +def test_contrast(): + from patsy.contrasts import ContrastMatrix, Sum + + values = ["a1", "a3", "a1", "a2"] + + # No intercept in model, full-rank coding of 'a' + m = make_matrix( + {"a": C(values)}, 3, [["a"]], column_names=["a[a1]", "a[a2]", "a[a3]"] + ) + + assert np.allclose(m, [[1, 0, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0]]) + + for s in (Sum, Sum()): + m = make_matrix( + {"a": C(values, s)}, + 3, + [["a"]], + column_names=["a[mean]", "a[S.a1]", "a[S.a2]"], + ) + # Output from R + assert np.allclose(m, [[1, 1, 0], [1, -1, -1], [1, 1, 0], [1, 0, 1]]) + + m = make_matrix( + {"a": C(values, Sum(omit=0))}, + 3, + [["a"]], + column_names=["a[mean]", "a[S.a2]", "a[S.a3]"], + ) + # Output from R + assert np.allclose(m, [[1, -1, -1], [1, 0, 1], [1, -1, -1], [1, 1, 0]]) + + # Intercept in model, non-full-rank coding of 'a' + m = make_matrix( + {"a": C(values)}, + 3, + [[], ["a"]], + column_names=["Intercept", "a[T.a2]", "a[T.a3]"], + ) + + assert np.allclose(m, [[1, 0, 0], [1, 0, 1], [1, 0, 0], [1, 1, 0]]) + + for s in (Sum, Sum()): + m = make_matrix( + {"a": C(values, s)}, + 3, + [[], ["a"]], + column_names=["Intercept", "a[S.a1]", "a[S.a2]"], + ) + # Output from R + assert np.allclose(m, [[1, 1, 0], [1, -1, -1], [1, 1, 0], [1, 0, 1]]) + + m = make_matrix( + {"a": C(values, Sum(omit=0))}, + 3, + [[], ["a"]], + column_names=["Intercept", "a[S.a2]", "a[S.a3]"], + ) + # Output from R + assert np.allclose(m, [[1, -1, -1], [1, 0, 1], [1, -1, -1], [1, 1, 0]]) + + # Weird ad hoc less-than-full-rank coding of 'a' + m = make_matrix( + {"a": C(values, [[7, 12], [2, 13], [8, -1]])}, + 2, + [["a"]], + column_names=["a[custom0]", "a[custom1]"], + ) + assert np.allclose(m, [[7, 12], [8, -1], [7, 12], [2, 13]]) + + m = make_matrix( + { + "a": C( + values, ContrastMatrix([[7, 12], [2, 13], [8, -1]], ["[foo]", "[bar]"]) + ) + }, + 2, + [["a"]], + column_names=["a[foo]", "a[bar]"], + ) + assert np.allclose(m, [[7, 12], [8, -1], [7, 12], [2, 13]]) + + +def test_DesignInfo_subset(): + # For each combination of: + # formula, term names, term objects, mixed term name and term objects + # check that results match subset of full build + # and that removed variables don't hurt + all_data = {"x": [1, 2], "y": [[3.1, 3.2], [4.1, 4.2]], "z": [5, 6]} + all_terms = make_termlist("x", "y", "z") + + def iter_maker(): + yield all_data + + all_builder = design_matrix_builders([all_terms], iter_maker, 0)[0] + full_matrix = build_design_matrices([all_builder], all_data)[0] + + def t(which_terms, variables, columns): + sub_design_info = all_builder.subset(which_terms) + sub_data = {} + for variable in variables: + sub_data[variable] = all_data[variable] + sub_matrix = build_design_matrices([sub_design_info], sub_data)[0] + sub_full_matrix = full_matrix[:, columns] + if not isinstance(which_terms, str): + assert len(which_terms) == len(sub_design_info.terms) + assert np.array_equal(sub_matrix, sub_full_matrix) + + t("~ 0 + x + y + z", ["x", "y", "z"], slice(None)) + t(["x", "y", "z"], ["x", "y", "z"], slice(None)) + t(all_terms, ["x", "y", "z"], slice(None)) + t([all_terms[0], "y", all_terms[2]], ["x", "y", "z"], slice(None)) + + t("~ 0 + x + z", ["x", "z"], [0, 3]) + t(["x", "z"], ["x", "z"], [0, 3]) + t([all_terms[0], all_terms[2]], ["x", "z"], [0, 3]) + t([all_terms[0], "z"], ["x", "z"], [0, 3]) + + t("~ 0 + z + x", ["x", "z"], [3, 0]) + t(["z", "x"], ["x", "z"], [3, 0]) + t([all_terms[2], all_terms[0]], ["x", "z"], [3, 0]) + t([all_terms[2], "x"], ["x", "z"], [3, 0]) + + t("~ 0 + y", ["y"], [1, 2]) + t(["y"], ["y"], [1, 2]) + t([all_terms[1]], ["y"], [1, 2]) + + # Formula can't have a LHS + pytest.raises(PatsyError, all_builder.subset, "a ~ a") + # Term must exist + pytest.raises(KeyError, all_builder.subset, "~ asdf") + pytest.raises(KeyError, all_builder.subset, ["asdf"]) + pytest.raises(KeyError, all_builder.subset, [Term(["asdf"])]) + + # Also check for a minimal DesignInfo (column names only) + min_di = DesignInfo(["a", "b", "c"]) + min_di_subset = min_di.subset(["c", "a"]) + assert min_di_subset.column_names == ["c", "a"] + assert min_di_subset.terms is None diff --git a/venv/lib/python3.10/site-packages/patsy/test_highlevel.py b/venv/lib/python3.10/site-packages/patsy/test_highlevel.py new file mode 100644 index 0000000000000000000000000000000000000000..35c86a1e2289df7bd14402d1b9abd91b1e813c7b --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/test_highlevel.py @@ -0,0 +1,981 @@ +# This file is part of Patsy +# Copyright (C) 2012-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Exhaustive end-to-end tests of the top-level API. + +import numpy as np +import pytest + +from patsy import PatsyError +from patsy.design_info import DesignMatrix, DesignInfo +from patsy.eval import EvalEnvironment +from patsy.desc import ModelDesc, Term, INTERCEPT +from patsy.categorical import C +from patsy.contrasts import Helmert +from patsy.user_util import balanced, LookupFactor +from patsy.build import design_matrix_builders, build_design_matrices +from patsy.highlevel import dmatrix, dmatrices, incr_dbuilder, incr_dbuilders +from patsy.util import ( + have_pandas, + have_pandas_categorical, + have_pandas_categorical_dtype, + pandas_Categorical_from_codes, +) +from patsy.origin import Origin + +if have_pandas: + import pandas + + +def check_result( + expect_full_designs, + lhs, + rhs, + data, + expected_rhs_values, + expected_rhs_names, + expected_lhs_values, + expected_lhs_names, +): # pragma: no cover + assert np.allclose(rhs, expected_rhs_values) + assert rhs.design_info.column_names == expected_rhs_names + if lhs is not None: + assert np.allclose(lhs, expected_lhs_values) + assert lhs.design_info.column_names == expected_lhs_names + else: + assert expected_lhs_values is None + assert expected_lhs_names is None + + if expect_full_designs: + if lhs is None: + (new_rhs,) = build_design_matrices([rhs.design_info], data) + else: + new_lhs, new_rhs = build_design_matrices( + [lhs.design_info, rhs.design_info], data + ) + assert np.allclose(new_lhs, lhs) + assert new_lhs.design_info.column_names == expected_lhs_names + assert np.allclose(new_rhs, rhs) + assert new_rhs.design_info.column_names == expected_rhs_names + else: + assert rhs.design_info.terms is None + assert lhs is None or lhs.design_info.terms is None + + +def dmatrix_pandas(formula_like, data={}, depth=0, return_type="matrix"): + return_type = "dataframe" + if isinstance(depth, int): + depth += 1 + return dmatrix(formula_like, data, depth, return_type=return_type) + + +def dmatrices_pandas(formula_like, data={}, depth=0, return_type="matrix"): + return_type = "dataframe" + if isinstance(depth, int): + depth += 1 + return dmatrices(formula_like, data, depth, return_type=return_type) + + +def t( + formula_like, + data, + depth, + expect_full_designs, + expected_rhs_values, + expected_rhs_names, + expected_lhs_values=None, + expected_lhs_names=None, +): # pragma: no cover + if isinstance(depth, int): + depth += 1 + + def data_iter_maker(): + return iter([data]) + + if ( + isinstance(formula_like, (str, ModelDesc, DesignInfo)) + or (isinstance(formula_like, tuple) and isinstance(formula_like[0], DesignInfo)) + or hasattr(formula_like, "__patsy_get_model_desc__") + ): + if expected_lhs_values is None: + builder = incr_dbuilder(formula_like, data_iter_maker, depth) + lhs = None + (rhs,) = build_design_matrices([builder], data) + else: + builders = incr_dbuilders(formula_like, data_iter_maker, depth) + lhs, rhs = build_design_matrices(builders, data) + check_result( + expect_full_designs, + lhs, + rhs, + data, + expected_rhs_values, + expected_rhs_names, + expected_lhs_values, + expected_lhs_names, + ) + else: + pytest.raises(PatsyError, incr_dbuilders, formula_like, data_iter_maker) + pytest.raises(PatsyError, incr_dbuilder, formula_like, data_iter_maker) + one_mat_fs = [dmatrix] + two_mat_fs = [dmatrices] + if have_pandas: + one_mat_fs.append(dmatrix_pandas) + two_mat_fs.append(dmatrices_pandas) + if expected_lhs_values is None: + for f in one_mat_fs: + rhs = f(formula_like, data, depth) + check_result( + expect_full_designs, + None, + rhs, + data, + expected_rhs_values, + expected_rhs_names, + expected_lhs_values, + expected_lhs_names, + ) + + # We inline assert_raises here to avoid complications with the + # depth argument. + for f in two_mat_fs: + try: + f(formula_like, data, depth) + except PatsyError: + pass + else: + raise AssertionError + else: + for f in one_mat_fs: + try: + f(formula_like, data, depth) + except PatsyError: + pass + else: + raise AssertionError + + for f in two_mat_fs: + (lhs, rhs) = f(formula_like, data, depth) + check_result( + expect_full_designs, + lhs, + rhs, + data, + expected_rhs_values, + expected_rhs_names, + expected_lhs_values, + expected_lhs_names, + ) + + +def t_invalid(formula_like, data, depth, exc=PatsyError): # pragma: no cover + if isinstance(depth, int): + depth += 1 + fs = [dmatrix, dmatrices] + if have_pandas: + fs += [dmatrix_pandas, dmatrices_pandas] + for f in fs: + try: + f(formula_like, data, depth) + except exc: + pass + else: + raise AssertionError + + +# Exercise all the different calling conventions for the high-level API +def test_formula_likes(): + # Plain array-like, rhs only + t([[1, 2, 3], [4, 5, 6]], {}, 0, False, [[1, 2, 3], [4, 5, 6]], ["x0", "x1", "x2"]) + t( + (None, [[1, 2, 3], [4, 5, 6]]), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["x0", "x1", "x2"], + ) + t( + np.asarray([[1, 2, 3], [4, 5, 6]]), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["x0", "x1", "x2"], + ) + t( + (None, np.asarray([[1, 2, 3], [4, 5, 6]])), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["x0", "x1", "x2"], + ) + dm = DesignMatrix([[1, 2, 3], [4, 5, 6]], default_column_prefix="foo") + t(dm, {}, 0, False, [[1, 2, 3], [4, 5, 6]], ["foo0", "foo1", "foo2"]) + t((None, dm), {}, 0, False, [[1, 2, 3], [4, 5, 6]], ["foo0", "foo1", "foo2"]) + + # Plain array-likes, lhs and rhs + t( + ([1, 2], [[1, 2, 3], [4, 5, 6]]), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["x0", "x1", "x2"], + [[1], [2]], + ["y0"], + ) + t( + ([[1], [2]], [[1, 2, 3], [4, 5, 6]]), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["x0", "x1", "x2"], + [[1], [2]], + ["y0"], + ) + t( + (np.asarray([1, 2]), np.asarray([[1, 2, 3], [4, 5, 6]])), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["x0", "x1", "x2"], + [[1], [2]], + ["y0"], + ) + t( + (np.asarray([[1], [2]]), np.asarray([[1, 2, 3], [4, 5, 6]])), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["x0", "x1", "x2"], + [[1], [2]], + ["y0"], + ) + x_dm = DesignMatrix([[1, 2, 3], [4, 5, 6]], default_column_prefix="foo") + y_dm = DesignMatrix([1, 2], default_column_prefix="bar") + t( + (y_dm, x_dm), + {}, + 0, + False, + [[1, 2, 3], [4, 5, 6]], + ["foo0", "foo1", "foo2"], + [[1], [2]], + ["bar0"], + ) + # number of rows must match + t_invalid(([1, 2, 3], [[1, 2, 3], [4, 5, 6]]), {}, 0) + + # tuples must have the right size + t_invalid(([[1, 2, 3]],), {}, 0) + t_invalid(([[1, 2, 3]], [[1, 2, 3]], [[1, 2, 3]]), {}, 0) + + # plain Series and DataFrames + if have_pandas: + # Names are extracted + t(pandas.DataFrame({"x": [1, 2, 3]}), {}, 0, False, [[1], [2], [3]], ["x"]) + t( + pandas.Series([1, 2, 3], name="asdf"), + {}, + 0, + False, + [[1], [2], [3]], + ["asdf"], + ) + t( + (pandas.DataFrame({"y": [4, 5, 6]}), pandas.DataFrame({"x": [1, 2, 3]})), + {}, + 0, + False, + [[1], [2], [3]], + ["x"], + [[4], [5], [6]], + ["y"], + ) + t( + (pandas.Series([4, 5, 6], name="y"), pandas.Series([1, 2, 3], name="x")), + {}, + 0, + False, + [[1], [2], [3]], + ["x"], + [[4], [5], [6]], + ["y"], + ) + # Or invented + t( + ( + pandas.DataFrame([[4, 5, 6]]), + pandas.DataFrame([[1, 2, 3]], columns=[7, 8, 9]), + ), + {}, + 0, + False, + [[1, 2, 3]], + ["x7", "x8", "x9"], + [[4, 5, 6]], + ["y0", "y1", "y2"], + ) + t(pandas.Series([1, 2, 3]), {}, 0, False, [[1], [2], [3]], ["x0"]) + # indices must match + t_invalid( + (pandas.DataFrame([[1]], index=[1]), pandas.DataFrame([[1]], index=[2])), + {}, + 0, + ) + + # Foreign ModelDesc factories + class ForeignModelSource(object): + def __patsy_get_model_desc__(self, data): + return ModelDesc([Term([LookupFactor("Y")])], [Term([LookupFactor("X")])]) + + foreign_model = ForeignModelSource() + t( + foreign_model, + {"Y": [1, 2], "X": [[1, 2], [3, 4]]}, + 0, + True, + [[1, 2], [3, 4]], + ["X[0]", "X[1]"], + [[1], [2]], + ["Y"], + ) + + class BadForeignModelSource(object): + def __patsy_get_model_desc__(self, data): + return data + + t_invalid(BadForeignModelSource(), {}, 0) + + # string formulas + t( + "y ~ x", + {"y": [1, 2], "x": [3, 4]}, + 0, + True, + [[1, 3], [1, 4]], + ["Intercept", "x"], + [[1], [2]], + ["y"], + ) + t("~ x", {"y": [1, 2], "x": [3, 4]}, 0, True, [[1, 3], [1, 4]], ["Intercept", "x"]) + t( + "x + y", + {"y": [1, 2], "x": [3, 4]}, + 0, + True, + [[1, 3, 1], [1, 4, 2]], + ["Intercept", "x", "y"], + ) + + # ModelDesc + desc = ModelDesc([], [Term([LookupFactor("x")])]) + t(desc, {"x": [1.5, 2.5, 3.5]}, 0, True, [[1.5], [2.5], [3.5]], ["x"]) + desc = ModelDesc([], [Term([]), Term([LookupFactor("x")])]) + t( + desc, + {"x": [1.5, 2.5, 3.5]}, + 0, + True, + [[1, 1.5], [1, 2.5], [1, 3.5]], + ["Intercept", "x"], + ) + desc = ModelDesc([Term([LookupFactor("y")])], [Term([]), Term([LookupFactor("x")])]) + t( + desc, + {"x": [1.5, 2.5, 3.5], "y": [10, 20, 30]}, + 0, + True, + [[1, 1.5], [1, 2.5], [1, 3.5]], + ["Intercept", "x"], + [[10], [20], [30]], + ["y"], + ) + + # builders + termlists = ( + [], + [Term([LookupFactor("x")])], + [Term([]), Term([LookupFactor("x")])], + ) + builders = design_matrix_builders( + termlists, lambda: iter([{"x": [1, 2, 3]}]), eval_env=0 + ) + # twople but with no LHS + t( + (builders[0], builders[2]), + {"x": [10, 20, 30]}, + 0, + True, + [[1, 10], [1, 20], [1, 30]], + ["Intercept", "x"], + ) + # single DesignInfo + t( + builders[2], + {"x": [10, 20, 30]}, + 0, + True, + [[1, 10], [1, 20], [1, 30]], + ["Intercept", "x"], + ) + # twople with LHS + t( + (builders[1], builders[2]), + {"x": [10, 20, 30]}, + 0, + True, + [[1, 10], [1, 20], [1, 30]], + ["Intercept", "x"], + [[10], [20], [30]], + ["x"], + ) + + # check depth arguments + x_in_env = [1, 2, 3] + t("~ x_in_env", {}, 0, True, [[1, 1], [1, 2], [1, 3]], ["Intercept", "x_in_env"]) + t( + "~ x_in_env", + {"x_in_env": [10, 20, 30]}, + 0, + True, + [[1, 10], [1, 20], [1, 30]], + ["Intercept", "x_in_env"], + ) + # Trying to pull x_in_env out of our *caller* shouldn't work. + t_invalid("~ x_in_env", {}, 1, exc=(NameError, PatsyError)) + + # But then again it should, if called from one down on the stack: + def check_nested_call(): + x_in_env = "asdf" + t( + "~ x_in_env", + {}, + 1, + True, + [[1, 1], [1, 2], [1, 3]], + ["Intercept", "x_in_env"], + ) + + check_nested_call() + # passing in an explicit EvalEnvironment also works: + e = EvalEnvironment.capture(1) + t_invalid("~ x_in_env", {}, e, exc=(NameError, PatsyError)) + e = EvalEnvironment.capture(0) + + def check_nested_call_2(): + x_in_env = "asdf" + t( + "~ x_in_env", + {}, + e, + True, + [[1, 1], [1, 2], [1, 3]], + ["Intercept", "x_in_env"], + ) + + check_nested_call_2() + + +def test_return_pandas(): + if not have_pandas: + return + # basic check of pulling a Series out of the environment + s1 = pandas.Series([1, 2, 3], name="AA", index=[10, 20, 30]) + s2 = pandas.Series([4, 5, 6], name="BB", index=[10, 20, 30]) + df1 = dmatrix("s1", return_type="dataframe") + assert np.allclose(df1, [[1, 1], [1, 2], [1, 3]]) + assert np.array_equal(df1.columns, ["Intercept", "s1"]) + assert df1.design_info.column_names == ["Intercept", "s1"] + assert np.array_equal(df1.index, [10, 20, 30]) + df2, df3 = dmatrices("s2 ~ s1", return_type="dataframe") + assert np.allclose(df2, [[4], [5], [6]]) + assert np.array_equal(df2.columns, ["s2"]) + assert df2.design_info.column_names == ["s2"] + assert np.array_equal(df2.index, [10, 20, 30]) + assert np.allclose(df3, [[1, 1], [1, 2], [1, 3]]) + assert np.array_equal(df3.columns, ["Intercept", "s1"]) + assert df3.design_info.column_names == ["Intercept", "s1"] + assert np.array_equal(df3.index, [10, 20, 30]) + # indices are preserved if pandas is passed in directly + df4 = dmatrix(s1, return_type="dataframe") + assert np.allclose(df4, [[1], [2], [3]]) + assert np.array_equal(df4.columns, ["AA"]) + assert df4.design_info.column_names == ["AA"] + assert np.array_equal(df4.index, [10, 20, 30]) + df5, df6 = dmatrices((s2, s1), return_type="dataframe") + assert np.allclose(df5, [[4], [5], [6]]) + assert np.array_equal(df5.columns, ["BB"]) + assert df5.design_info.column_names == ["BB"] + assert np.array_equal(df5.index, [10, 20, 30]) + assert np.allclose(df6, [[1], [2], [3]]) + assert np.array_equal(df6.columns, ["AA"]) + assert df6.design_info.column_names == ["AA"] + assert np.array_equal(df6.index, [10, 20, 30]) + # Both combinations of with-index and without-index + df7, df8 = dmatrices((s1, [10, 11, 12]), return_type="dataframe") + assert np.array_equal(df7.index, s1.index) + assert np.array_equal(df8.index, s1.index) + df9, df10 = dmatrices(([10, 11, 12], s1), return_type="dataframe") + assert np.array_equal(df9.index, s1.index) + assert np.array_equal(df10.index, s1.index) + # pandas must be available + import patsy.highlevel + + had_pandas = patsy.highlevel.have_pandas + try: + patsy.highlevel.have_pandas = False + pytest.raises(PatsyError, dmatrix, "x", {"x": [1]}, 0, return_type="dataframe") + pytest.raises( + PatsyError, + dmatrices, + "y ~ x", + {"x": [1], "y": [2]}, + 0, + return_type="dataframe", + ) + finally: + patsy.highlevel.have_pandas = had_pandas + + +def test_term_info(): + data = balanced(a=2, b=2) + rhs = dmatrix("a:b", data) + assert rhs.design_info.column_names == [ + "Intercept", + "b[T.b2]", + "a[T.a2]:b[b1]", + "a[T.a2]:b[b2]", + ] + assert rhs.design_info.term_names == ["Intercept", "a:b"] + assert len(rhs.design_info.terms) == 2 + assert rhs.design_info.terms[0] == INTERCEPT + + +def test_data_types(): + data = { + "a": [1, 2, 3], + "b": [1.0, 2.0, 3.0], + "c": np.asarray([1, 2, 3], dtype=np.float32), + "d": [True, False, True], + "e": ["foo", "bar", "baz"], + "f": C([1, 2, 3]), + "g": C(["foo", "bar", "baz"]), + "h": np.array(["foo", 1, (1, "hi")], dtype=object), + } + t("~ 0 + a", data, 0, True, [[1], [2], [3]], ["a"]) + t("~ 0 + b", data, 0, True, [[1], [2], [3]], ["b"]) + t("~ 0 + c", data, 0, True, [[1], [2], [3]], ["c"]) + t("~ 0 + d", data, 0, True, [[0, 1], [1, 0], [0, 1]], ["d[False]", "d[True]"]) + t( + "~ 0 + e", + data, + 0, + True, + [[0, 0, 1], [1, 0, 0], [0, 1, 0]], + ["e[bar]", "e[baz]", "e[foo]"], + ) + t( + "~ 0 + f", + data, + 0, + True, + [[1, 0, 0], [0, 1, 0], [0, 0, 1]], + ["f[1]", "f[2]", "f[3]"], + ) + t( + "~ 0 + g", + data, + 0, + True, + [[0, 0, 1], [1, 0, 0], [0, 1, 0]], + ["g[bar]", "g[baz]", "g[foo]"], + ) + # This depends on Python's sorting behavior: + t( + "~ 0 + h", + data, + 0, + True, + [[0, 1, 0], [1, 0, 0], [0, 0, 1]], + ["h[1]", "h[foo]", "h[(1, 'hi')]"], + ) + + +def test_categorical(): + data = balanced(a=2, b=2) + # There are more exhaustive tests for all the different coding options in + # test_build; let's just make sure that C() and stuff works. + t( + "~ C(a)", + data, + 0, + True, + [[1, 0], [1, 0], [1, 1], [1, 1]], + ["Intercept", "C(a)[T.a2]"], + ) + t( + "~ C(a, levels=['a2', 'a1'])", + data, + 0, + True, + [[1, 1], [1, 1], [1, 0], [1, 0]], + ["Intercept", "C(a, levels=['a2', 'a1'])[T.a1]"], + ) + t( + "~ C(a, Treatment(reference=-1))", + data, + 0, + True, + [[1, 1], [1, 1], [1, 0], [1, 0]], + ["Intercept", "C(a, Treatment(reference=-1))[T.a1]"], + ) + + # Different interactions + t( + "a*b", + data, + 0, + True, + [[1, 0, 0, 0], [1, 0, 1, 0], [1, 1, 0, 0], [1, 1, 1, 1]], + ["Intercept", "a[T.a2]", "b[T.b2]", "a[T.a2]:b[T.b2]"], + ) + t( + "0 + a:b", + data, + 0, + True, + [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], + ["a[a1]:b[b1]", "a[a2]:b[b1]", "a[a1]:b[b2]", "a[a2]:b[b2]"], + ) + t( + "1 + a + a:b", + data, + 0, + True, + [[1, 0, 0, 0], [1, 0, 1, 0], [1, 1, 0, 0], [1, 1, 0, 1]], + ["Intercept", "a[T.a2]", "a[a1]:b[T.b2]", "a[a2]:b[T.b2]"], + ) + + # Changing contrast with C() + data["a"] = C(data["a"], Helmert) + t("a", data, 0, True, [[1, -1], [1, -1], [1, 1], [1, 1]], ["Intercept", "a[H.a2]"]) + t( + "C(a, Treatment)", + data, + 0, + True, + [[1, 0], [1, 0], [1, 1], [1, 1]], + ["Intercept", "C(a, Treatment)[T.a2]"], + ) + # That didn't affect the original object + t("a", data, 0, True, [[1, -1], [1, -1], [1, 1], [1, 1]], ["Intercept", "a[H.a2]"]) + + +def test_builtins(): + data = {"x": [1, 2, 3], "y": [4, 5, 6], "a b c": [10, 20, 30]} + t("0 + I(x + y)", data, 0, True, [[1], [2], [3], [4], [5], [6]], ["I(x + y)"]) + t( + "Q('a b c')", + data, + 0, + True, + [[1, 10], [1, 20], [1, 30]], + ["Intercept", "Q('a b c')"], + ) + t("center(x)", data, 0, True, [[1, -1], [1, 0], [1, 1]], ["Intercept", "center(x)"]) + + +def test_incremental(): + # incr_dbuilder(s) + # stateful transformations + datas = [ + {"a": ["a2", "a2", "a2"], "x": [1, 2, 3]}, + {"a": ["a2", "a2", "a1"], "x": [4, 5, 6]}, + ] + x = np.asarray([1, 2, 3, 4, 5, 6]) + sin_center_x = np.sin(x - np.mean(x)) + x_col = sin_center_x - np.mean(sin_center_x) + + def data_iter_maker(): + return iter(datas) + + builders = incr_dbuilders("1 ~ a + center(np.sin(center(x)))", data_iter_maker) + lhs, rhs = build_design_matrices(builders, datas[1]) + assert lhs.design_info.column_names == ["Intercept"] + assert rhs.design_info.column_names == [ + "Intercept", + "a[T.a2]", + "center(np.sin(center(x)))", + ] + assert np.allclose(lhs, [[1], [1], [1]]) + assert np.allclose(rhs, np.column_stack(([1, 1, 1], [1, 1, 0], x_col[3:]))) + + builder = incr_dbuilder("~ a + center(np.sin(center(x)))", data_iter_maker) + (rhs,) = build_design_matrices([builder], datas[1]) + assert rhs.design_info.column_names == [ + "Intercept", + "a[T.a2]", + "center(np.sin(center(x)))", + ] + assert np.allclose(lhs, [[1], [1], [1]]) + assert np.allclose(rhs, np.column_stack(([1, 1, 1], [1, 1, 0], x_col[3:]))) + + pytest.raises(PatsyError, incr_dbuilder, "x ~ x", data_iter_maker) + pytest.raises(PatsyError, incr_dbuilders, "x", data_iter_maker) + + +def test_env_transform(): + t( + "~ np.sin(x)", + {"x": [1, 2, 3]}, + 0, + True, + [[1, np.sin(1)], [1, np.sin(2)], [1, np.sin(3)]], + ["Intercept", "np.sin(x)"], + ) + + +# Term ordering: +# 1) all 0-order no-numeric +# 2) all 1st-order no-numeric +# 3) all 2nd-order no-numeric +# 4) ... +# 5) all 0-order with the first numeric interaction encountered +# 6) all 1st-order with the first numeric interaction encountered +# 7) ... +# 8) all 0-order with the second numeric interaction encountered +# 9) ... +def test_term_order(): + data = balanced(a=2, b=2) + data["x1"] = np.linspace(0, 1, 4) + data["x2"] = data["x1"] ** 2 + + def t_terms(formula, order): + m = dmatrix(formula, data) + assert m.design_info.term_names == order + + t_terms("a + b + x1 + x2", ["Intercept", "a", "b", "x1", "x2"]) + t_terms("b + a + x2 + x1", ["Intercept", "b", "a", "x2", "x1"]) + t_terms("0 + x1 + a + x2 + b + 1", ["Intercept", "a", "b", "x1", "x2"]) + t_terms("0 + a:b + a + b + 1", ["Intercept", "a", "b", "a:b"]) + t_terms("a + a:x1 + x2 + x1 + b", ["Intercept", "a", "b", "x1", "a:x1", "x2"]) + t_terms( + "0 + a:x1:x2 + a + x2:x1:b + x2 + x1 + a:x1 + x1:x2 + x1:a:x2:a:b", + ["a", "x1:x2", "a:x1:x2", "x2:x1:b", "x1:a:x2:b", "x2", "x1", "a:x1"], + ) + + +def _check_division(expect_true_division): # pragma: no cover + # We evaluate the formula "I(x / y)" in our *caller's* scope, so the + # result depends on whether our caller has done 'from __future__ import + # division'. + data = {"x": 5, "y": 2} + m = dmatrix("0 + I(x / y)", data, 1) + if expect_true_division: + assert np.allclose(m, [[2.5]]) + else: + assert np.allclose(m, [[2]]) + + +def test_multicolumn(): + data = { + "a": ["a1", "a2"], + "X": [[1, 2], [3, 4]], + "Y": [[1, 3], [2, 4]], + } + t( + "X*Y", + data, + 0, + True, + [ + [1, 1, 2, 1, 3, 1 * 1, 2 * 1, 1 * 3, 2 * 3], + [1, 3, 4, 2, 4, 3 * 2, 4 * 2, 3 * 4, 4 * 4], + ], + [ + "Intercept", + "X[0]", + "X[1]", + "Y[0]", + "Y[1]", + "X[0]:Y[0]", + "X[1]:Y[0]", + "X[0]:Y[1]", + "X[1]:Y[1]", + ], + ) + t( + "a:X + Y", + data, + 0, + True, + [[1, 1, 0, 2, 0, 1, 3], [1, 0, 3, 0, 4, 2, 4]], + [ + "Intercept", + "a[a1]:X[0]", + "a[a2]:X[0]", + "a[a1]:X[1]", + "a[a2]:X[1]", + "Y[0]", + "Y[1]", + ], + ) + + +def test_dmatrix_dmatrices_no_data(): + x = [1, 2, 3] + y = [4, 5, 6] + assert np.allclose(dmatrix("x"), [[1, 1], [1, 2], [1, 3]]) + lhs, rhs = dmatrices("y ~ x") + assert np.allclose(lhs, [[4], [5], [6]]) + assert np.allclose(rhs, [[1, 1], [1, 2], [1, 3]]) + + +def test_designinfo_describe(): + lhs, rhs = dmatrices( + "y ~ x + a", {"y": [1, 2, 3], "x": [4, 5, 6], "a": ["a1", "a2", "a3"]} + ) + assert lhs.design_info.describe() == "y" + assert rhs.design_info.describe() == "1 + a + x" + + +def test_evalfactor_reraise(): + # This will produce a PatsyError, but buried inside the factor evaluation, + # so the original code has no way to give it an appropriate origin= + # attribute. EvalFactor should notice this, and add a useful origin: + def raise_patsy_error(x): + raise PatsyError("WHEEEEEE") + + formula = "raise_patsy_error(X) + Y" + try: + dmatrix(formula, {"X": [1, 2, 3], "Y": [4, 5, 6]}) + except PatsyError as e: + assert e.origin == Origin(formula, 0, formula.index(" ")) + else: + assert False + # This will produce a KeyError, which on Python 3 we can do wrap without + # destroying the traceback, so we do so. On Python 2 we let the original + # exception escape. + try: + dmatrix("1 + x[1]", {"x": {}}) + except Exception as e: + assert isinstance(e, PatsyError) + assert e.origin == Origin("1 + x[1]", 4, 8) + else: + assert False + + +def test_dmatrix_NA_action(): + data = {"x": [1, 2, 3, np.nan], "y": [np.nan, 20, 30, 40]} + + return_types = ["matrix"] + if have_pandas: + return_types.append("dataframe") + + for return_type in return_types: + mat = dmatrix("x + y", data=data, return_type=return_type) + assert np.array_equal(mat, [[1, 2, 20], [1, 3, 30]]) + if return_type == "dataframe": + assert mat.index.equals(pandas.Index([1, 2])) + pytest.raises( + PatsyError, + dmatrix, + "x + y", + data=data, + return_type=return_type, + NA_action="raise", + ) + + lmat, rmat = dmatrices("y ~ x", data=data, return_type=return_type) + assert np.array_equal(lmat, [[20], [30]]) + assert np.array_equal(rmat, [[1, 2], [1, 3]]) + if return_type == "dataframe": + assert lmat.index.equals(pandas.Index([1, 2])) + assert rmat.index.equals(pandas.Index([1, 2])) + pytest.raises( + PatsyError, + dmatrices, + "y ~ x", + data=data, + return_type=return_type, + NA_action="raise", + ) + + # Initial release for the NA handling code had problems with + # non-data-dependent matrices like "~ 1". + lmat, rmat = dmatrices("y ~ 1", data=data, return_type=return_type) + assert np.array_equal(lmat, [[20], [30], [40]]) + assert np.array_equal(rmat, [[1], [1], [1]]) + if return_type == "dataframe": + assert lmat.index.equals(pandas.Index([1, 2, 3])) + assert rmat.index.equals(pandas.Index([1, 2, 3])) + pytest.raises( + PatsyError, + dmatrices, + "y ~ 1", + data=data, + return_type=return_type, + NA_action="raise", + ) + + +def test_0d_data(): + # Use case from statsmodels/statsmodels#1881 + data_0d = {"x1": 1.1, "x2": 1.2, "a": "a1"} + + for formula, expected in [ + ("x1 + x2", [[1, 1.1, 1.2]]), + ("C(a, levels=('a1', 'a2')) + x1", [[1, 0, 1.1]]), + ]: + mat = dmatrix(formula, data_0d) + assert np.allclose(mat, expected) + + assert np.allclose( + build_design_matrices([mat.design_info], data_0d)[0], expected + ) + if have_pandas: + data_series = pandas.Series(data_0d) + assert np.allclose(dmatrix(formula, data_series), expected) + + assert np.allclose( + build_design_matrices([mat.design_info], data_series)[0], expected + ) + + +def test_env_not_saved_in_builder(): + x_in_env = [1, 2, 3] + design_matrix = dmatrix("x_in_env", {}) + + x_in_env = [10, 20, 30] + design_matrix2 = dmatrix(design_matrix.design_info, {}) + + assert np.allclose(design_matrix, design_matrix2) + + +def test_C_and_pandas_categorical(): + if not have_pandas_categorical: + return + + objs = [pandas_Categorical_from_codes([1, 0, 1], ["b", "a"])] + if have_pandas_categorical_dtype: + objs.append(pandas.Series(objs[0])) + for obj in objs: + d = {"obj": obj} + assert np.allclose(dmatrix("obj", d), [[1, 1], [1, 0], [1, 1]]) + + assert np.allclose(dmatrix("C(obj)", d), [[1, 1], [1, 0], [1, 1]]) + + assert np.allclose( + dmatrix("C(obj, levels=['b', 'a'])", d), [[1, 1], [1, 0], [1, 1]] + ) + + assert np.allclose( + dmatrix("C(obj, levels=['a', 'b'])", d), [[1, 0], [1, 1], [1, 0]] + ) diff --git a/venv/lib/python3.10/site-packages/patsy/test_regressions.py b/venv/lib/python3.10/site-packages/patsy/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..2760846382b940556c313412814572a8d79e82ff --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/test_regressions.py @@ -0,0 +1,24 @@ +# This file is part of Patsy +# Copyright (C) 2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Regression tests for fixed bugs (when not otherwise better covered somewhere +# else) + +from patsy import EvalEnvironment, dmatrix, build_design_matrices, PatsyError, Origin + + +def test_issue_11(): + # Give a sensible error message for level mismatches + # (At some points we've failed to put an origin= on these errors) + env = EvalEnvironment.capture() + data = {"X": [0, 1, 2, 3], "Y": [1, 2, 3, 4]} + formula = "C(X) + Y" + new_data = {"X": [0, 0, 1, 2, 3, 3, 4], "Y": [1, 2, 3, 4, 5, 6, 7]} + info = dmatrix(formula, data) + try: + build_design_matrices([info.design_info], new_data) + except PatsyError as e: + assert e.origin == Origin(formula, 0, 4) + else: + assert False diff --git a/venv/lib/python3.10/site-packages/patsy/test_splines_bs_data.py b/venv/lib/python3.10/site-packages/patsy/test_splines_bs_data.py new file mode 100644 index 0000000000000000000000000000000000000000..6b233fcdec9eac4ea77f0ab18f9de87963859fae --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/test_splines_bs_data.py @@ -0,0 +1,607 @@ +# This file auto-generated by tools/get-R-bs-test-vectors.R +# Using: R version 2.15.1 (2012-06-22) +import numpy as np + +R_bs_test_x = np.array( + [ + 1, + 1.5, + 2.25, + 3.375, + 5.0625, + 7.59375, + 11.390625, + 17.0859375, + 25.62890625, + 38.443359375, + 57.6650390625, + 86.49755859375, + 129.746337890625, + 194.6195068359375, + 291.92926025390625, + 437.893890380859375, + 656.8408355712890625, + 985.26125335693359375, + 1477.8918800354003906, + 2216.8378200531005859, + ] +) +R_bs_test_data = """ +--BEGIN TEST CASE-- +degree=1 +df=3 +intercept=TRUE +Boundary.knots=None +knots=None +output=np.array([1, 0.98937395581474985029, 0.97343488953687462573, 0.94952629012006184439, 0.91366339099484261688, 0.85986904230701377561, 0.77917751927527056921, 0.65814023472765570411, 0.47658430790623346196, 0.20425041767410004323, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.010626044185250137566, 0.026565110463125343049, 0.050473709879938155609, 0.086336609005157369245, 0.14013095769298619664, 0.22082248072472943079, 0.34185976527234429589, 0.52341569209376659355, 0.79574958232589998453, 0.99556855753085560234, 0.98227423012342263142, 0.96233273901227300851, 0.93242050234554862964, 0.88755214734546206135, 0.82024961484533231992, 0.71929581609513748575, 0.56786511796984540101, 0.34071907078190727391, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0044314424691443508181, 0.017725769876577403272, 0.037667260987726984556, 0.067579497654451342603, 0.11244785265453789702, 0.17975038515466773559, 0.28070418390486245874, 0.43213488203015459899, 0.6592809292180927816, 1, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=5 +intercept=TRUE +Boundary.knots=None +knots=None +output=np.array([1, 0.9161205766710354137, 0.79030144167758842322, 0.60157273918741804852, 0.31847968545216254199, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.083879423328964614059, 0.20969855832241152127, 0.39842726081258189597, 0.68152031454783745801, 0.9846005774783446185, 0.89220404234841199642, 0.7536092396535130078, 0.54571703561116458037, 0.23387872954764196698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015399422521655438748, 0.10779595765158807297, 0.24639076034648701996, 0.45428296438883541963, 0.76612127045235811629, 0.96572040707016604255, 0.86288162828066417021, 0.7086234600964114172, 0.47723620782003217666, 0.13015532940546331586, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.034279592929833957449, 0.13711837171933582979, 0.29137653990358863831, 0.52276379217996793436, 0.86984467059453673965, 0.94202898550724645244, 0.82608695652173913526, 0.65217391304347827052, 0.39130434782608697342, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.057971014492753623892, 0.17391304347826089249, 0.34782608695652178499, 0.60869565217391308209, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=12 +intercept=TRUE +Boundary.knots=None +knots=None +output=np.array([1, 0.52173913043478281626, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.47826086956521718374, 0.90243902439024414885, 0.36585365853658557977, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.097560975609755906657, 0.63414634146341442023, 0.77777777777777779011, 0.16666666666666651864, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.22222222222222218213, 0.83333333333333348136, 0.625, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.37499999999999994449, 0.96992481203007530066, 0.47368421052631592971, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.030075187969924695869, 0.52631578947368407029, 0.86440677966101697738, 0.30508474576271171763, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.13559322033898302262, 0.69491525423728828237, 0.72815533980582491935, 0.087378640776698143777, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.27184466019417513616, 0.91262135922330189786, 0.57446808510638269762, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.42553191489361730238, 0.9375, 0.4218750000000004996, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.062499999999999958367, 0.57812499999999944489, 0.82300884955752262595, 0.23893805309734547637, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.17699115044247745732, 0.76106194690265460689, 0.67346938775510212238, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.32653061224489787762, 1, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([]) +output=np.array([1, 0.99977435171677508929, 0.9994358792919375567, 0.99892817065468131332, 0.99816660769879694826, 0.99702426326497040066, 0.99531074661423057925, 0.99274047163812084715, 0.98888505917395630451, 0.98310194047770937953, 0.97442726243333910308, 0.96141524536678357737, 0.94189721976695039984, 0.91262018136720068906, 0.86870462376757595635, 0.8028312873681389128, 0.70402128276898334747, 0.55580627587024999947, 0.33348376552215003299, 0, 0, 0.00022564828322499611425, 0.00056412070806249024497, 0.001071829345318731563, 0.0018333923012030933775, 0.0029757367350296362075, 0.0046892533857694502358, 0.0072595283618791719288, 0.011114940826043754468, 0.01689805952229062741, 0.025572737566660935088, 0.038584754633216401809, 0.058102780233049600156, 0.087379818632799394207, 0.13129537623242407141, 0.19716871263186111496, 0.29597871723101670804, 0.44419372412975000053, 0.66651623447785002252, 1, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([100, ]) +output=np.array([1, 0.994949494949495028, 0.98737373737373745897, 0.97601010101010110542, 0.9589646464646465196, 0.93339646464646475188, 0.89504419191919204479, 0.83751578282828287314, 0.75122316919191922668, 0.62178424873737381251, 0.42762586805555558023, 0.13638829703282828731, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0050505050505050509344, 0.01262626262626262777, 0.023989898989898991721, 0.041035353535353535914, 0.066603535353535359143, 0.10495580808080809398, 0.16248421717171718237, 0.24877683080808082883, 0.37821575126262629851, 0.5723741319444445308, 0.86361170296717182371, 0.98594774828339049044, 0.95530148510216805757, 0.90933209033033446378, 0.84037799817258396207, 0.7369468599359582095, 0.58180015258101969167, 0.3490800915486118039, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.014052251716609454046, 0.044698514897831886916, 0.090667909669665536221, 0.15962200182741601018, 0.26305314006404173499, 0.41819984741898030833, 0.65091990845138814059, 1, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([1000, ]) +output=np.array([1, 0.99949949949949945527, 0.99874874874874874919, 0.99762262262262257906, 0.99593343343343343488, 0.9933996496496496631, 0.98959897397397400542, 0.98389796046046040789, 0.97534644019019023364, 0.96251915978478475022, 0.94327823917667663611, 0.91441685826451446495, 0.87112478689627126371, 0.80618667984390635084, 0.70877951926535909255, 0.5626687783975381496, 0.34350266709580673519, 0.014753500143209615295, 0, 0, 0, 0.00050050050050050049616, 0.0012512512512512512404, 0.0023773773773773775736, 0.0040665665665665668566, 0.0066003503503503499136, 0.0104010260260260258, 0.016102039539539540064, 0.02465355980980980799, 0.037480840215215215083, 0.056721760823323322254, 0.08558314173548547954, 0.12887521310372873629, 0.19381332015609359365, 0.29122048073464090745, 0.4373312216024618504, 0.6564973329041932093, 0.98524649985679035868, 0.60726740066762052717, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.39273259933237941732, 1, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([10, 100, 1000, ]) +output=np.array([1, 0.94444444444444441977, 0.86111111111111104943, 0.73611111111111104943, 0.54861111111111104943, 0.26736111111111110494, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.055555555555555552472, 0.13888888888888889506, 0.26388888888888889506, 0.45138888888888883955, 0.73263888888888883955, 0.98454861111111113825, 0.92126736111111118266, 0.82634548611111113825, 0.68396267361111118266, 0.47038845486111113825, 0.15002712673611112715, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015451388888888889506, 0.07873263888888888673, 0.17365451388888888951, 0.31603732638888892836, 0.52961154513888886175, 0.84997287326388892836, 0.96694851345486110272, 0.89486721462673612937, 0.78674526638454855831, 0.62456234402126731275, 0.38128796047634549993, 0.016376385158962673133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.033051486545138890338, 0.10513278537326388451, 0.21325473361545138618, 0.37543765597873263173, 0.61871203952365450007, 0.98362361484103733034, 0.60726740066762052717, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.39273259933237941732, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=3 +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.97919016410100090386, 0.9687852461515014113, 0.95317786922725200593, 0.92976680384087795339, 0.89465020576131693009, 0.84197530864197533962, 0.76296296296296306494, 0.64444444444444448639, 0.46666666666666667407, 0.2000000000000000111, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.020809835898999137771, 0.031214753848498706656, 0.046822130772748063454, 0.070233196159122088242, 0.1053497942386831393, 0.15802469135802471589, 0.23703703703703704608, 0.35555555555555556912, 0.53333333333333332593, 0.80000000000000004441, 0.99674423566950098863, 0.98697694267800384349, 0.9723260031907582368, 0.95034959395988971576, 0.9173849801135870452, 0.86793805934413292835, 0.7937676781899518641, 0.68251210645868021221, 0.51562874886177267886, 0.26530371246641143435, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0032557643304990334897, 0.013023057321996133959, 0.027673996809241787481, 0.049650406040110263428, 0.082615019886412982553, 0.13206194065586704389, 0.20623232181004816366, 0.3174878935413198433, 0.48437125113822732114, 0.73469628753358862117, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=5 +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.85634118967452310667, 0.78451178451178460449, 0.67676767676767679571, 0.51515151515151524908, 0.2727272727272727626, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.14365881032547700435, 0.21548821548821550653, 0.3232323232323232598, 0.48484848484848486194, 0.72727272727272729291, 0.9846005774783446185, 0.89220404234841199642, 0.7536092396535130078, 0.54571703561116458037, 0.23387872954764196698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015399422521655438748, 0.10779595765158807297, 0.24639076034648701996, 0.45428296438883541963, 0.76612127045235811629, 0.96572040707016604255, 0.86288162828066417021, 0.7086234600964114172, 0.47723620782003217666, 0.13015532940546331586, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.034279592929833957449, 0.13711837171933582979, 0.29137653990358863831, 0.52276379217996793436, 0.86984467059453673965, 0.9590229415870602514, 0.8770688247611807542, 0.7541376495223615084, 0.56974088666413258419, 0.29314574237678914237, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.040977058412939762477, 0.12293117523881928743, 0.24586235047763857486, 0.43025911333586747132, 0.70685425762321085763, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=12 +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.51111111111111118266, 0.2666666666666668295, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.48888888888888881734, 0.7333333333333331705, 0.90243902439024414885, 0.36585365853658557977, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.097560975609755906657, 0.63414634146341442023, 0.77777777777777779011, 0.16666666666666651864, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.22222222222222218213, 0.83333333333333348136, 0.625, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.37499999999999994449, 0.96992481203007530066, 0.47368421052631592971, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.030075187969924695869, 0.52631578947368407029, 0.86440677966101697738, 0.30508474576271171763, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.13559322033898302262, 0.69491525423728828237, 0.72815533980582491935, 0.087378640776698143777, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.27184466019417513616, 0.91262135922330189786, 0.57446808510638269762, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.42553191489361730238, 0.9375, 0.4218750000000004996, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.062499999999999958367, 0.57812499999999944489, 0.82300884955752262595, 0.23893805309734547637, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.17699115044247745732, 0.76106194690265460689, 0.80946623645948467818, 0.41649034915717175753, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.19053376354051526631, 0.58350965084282824247, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([]) +output=np.array([0.99966666666666659236, 0.99949999999999994404, 0.99924999999999997158, 0.99887499999999995737, 0.99831249999999993605, 0.9974687500000000151, 0.99620312499999996714, 0.99430468750000000622, 0.99145703124999995381, 0.98718554687499993072, 0.98077832031250000711, 0.97116748046875001066, 0.95675122070312501599, 0.93512683105468752398, 0.90269024658203123046, 0.85403536987304684569, 0.78105305480957032405, 0.67157958221435543056, 0.50736937332153320135, 0.26105405998229980202, 0.0003333333333333333222, 0.00050000000000000001041, 0.00075000000000000001561, 0.001124999999999999915, 0.0016874999999999999809, 0.0025312500000000000798, 0.0037968749999999999029, 0.0056953124999999998543, 0.0085429687499999993477, 0.012814453124999999889, 0.019221679687499999833, 0.02883251953124999975, 0.043248779296874997891, 0.064873168945312503775, 0.097309753417968741784, 0.14596463012695312655, 0.21894694519042967595, 0.32842041778564451393, 0.49263062667846679865, 0.73894594001770019798, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([100, ]) +output=np.array([0.98999999999999999112, 0.98499999999999998668, 0.97750000000000003553, 0.96625000000000005329, 0.94937499999999996891, 0.92406250000000000888, 0.88609375000000001332, 0.82914062499999996447, 0.74371093750000005773, 0.61556640625000003109, 0.42334960937499999112, 0.13502441406250001443, 0, 0, 0, 0, 0, 0, 0, 0, 0.010000000000000000208, 0.014999999999999999445, 0.022499999999999999167, 0.03375000000000000222, 0.050625000000000003331, 0.075937500000000004996, 0.11390625000000000056, 0.17085937500000000777, 0.25628906249999999778, 0.38443359375000002442, 0.57665039062500000888, 0.86497558593750001332, 0.98974264210668094766, 0.96737258384967661495, 0.93381749646417022692, 0.88348486538591053385, 0.80798591876852099425, 0.69473749884243662933, 0.52486486895331019298, 0.27005592411962048294, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.010257357893318963873, 0.032627416150323274024, 0.066182503535829731445, 0.11651513461408942451, 0.192014081231478978, 0.30526250115756325965, 0.47513513104668975151, 0.72994407588037946155, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([1000, ]) +output=np.array([0.99899999999999999911, 0.99850000000000005418, 0.99775000000000002576, 0.99662499999999998312, 0.9949375000000000302, 0.9924062500000000453, 0.98860937500000001243, 0.98291406250000001865, 0.97437109374999997247, 0.96155664062500001421, 0.94233496093750002132, 0.91350244140625003197, 0.87025366210937504796, 0.80538049316406257194, 0.7080707397460938024, 0.56210610961914064809, 0.34315916442871097214, 0.014738746643066406167, 0, 0, 0.0010000000000000000208, 0.0015000000000000000312, 0.0022500000000000002637, 0.0033749999999999999618, 0.0050625000000000001596, 0.0075937499999999998057, 0.011390624999999999709, 0.017085937499999998695, 0.025628906249999999778, 0.038443359374999999667, 0.0576650390624999995, 0.086497558593749995781, 0.12974633789062500755, 0.19461950683593751132, 0.29192926025390625311, 0.43789389038085940742, 0.65684083557128902786, 0.9852612533569335973, 0.76105405998229980202, 0.39158108997344970303, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.23894594001770019798, 0.60841891002655035248, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([10, 100, 1000, ]) +output=np.array([0.9000000000000000222, 0.85000000000000008882, 0.7750000000000000222, 0.66250000000000008882, 0.4937500000000000222, 0.24062500000000000555, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10000000000000000555, 0.1500000000000000222, 0.22500000000000000555, 0.3375000000000000222, 0.5062499999999999778, 0.7593750000000000222, 0.98454861111111113825, 0.92126736111111118266, 0.82634548611111113825, 0.68396267361111118266, 0.47038845486111113825, 0.15002712673611112715, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015451388888888889506, 0.07873263888888888673, 0.17365451388888888951, 0.31603732638888892836, 0.52961154513888886175, 0.84997287326388892836, 0.96694851345486110272, 0.89486721462673612937, 0.78674526638454855831, 0.62456234402126731275, 0.38128796047634549993, 0.016376385158962673133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.033051486545138890338, 0.10513278537326388451, 0.21325473361545138618, 0.37543765597873263173, 0.61871203952365450007, 0.98362361484103733034, 0.76105405998229980202, 0.39158108997344970303, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.23894594001770019798, 0.60841891002655035248, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=3 +intercept=FALSE +Boundary.knots=None +knots=None +output=np.array([0, 0.040686586141131603211, 0.10171646535282900803, 0.19326128417037510832, 0.33057851239669427956, 0.53655435473617296704, 0.84551811824539113704, 0.97622585438335818253, 0.92273402674591387118, 0.84249628528974740416, 0.72213967310549775913, 0.54160475482912329159, 0.27080237741456153477, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.023774145616641918083, 0.077265973254086212085, 0.1575037147102526236, 0.27786032689450229638, 0.45839524517087676392, 0.72919762258543852074, 0.98941973879980160689, 0.9418085633989089489, 0.87039180029756990642, 0.76326665564556128718, 0.60257893866754841383, 0.3615473632005290483, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.010580261200198394847, 0.058191436601091106606, 0.12960819970243014909, 0.23673334435443876833, 0.39742106133245164168, 0.63845263679947106272, 1, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=5 +intercept=FALSE +Boundary.knots=None +knots=None +output=np.array([0, 0.1342281879194630323, 0.33557046979865756686, 0.63758389261744941034, 0.98069963811821481148, 0.83594692400482528694, 0.61881785283474100012, 0.2931242460796145699, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.019300361881785188523, 0.16405307599517471306, 0.38118214716525899988, 0.70687575392038548561, 0.9581151832460734763, 0.80104712041884851281, 0.56544502617801106759, 0.21204188481675489975, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.041884816753926495947, 0.19895287958115145943, 0.4345549738219888769, 0.78795811518324510025, 0.93133047210300479168, 0.75965665236051571618, 0.50214592274678215844, 0.11587982832618169693, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.068669527896995374849, 0.2403433476394844226, 0.49785407725321800809, 0.88412017167381840022, 0.89905362776025266047, 0.70977917981072580211, 0.42586750788643545906, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10094637223974732565, 0.29022082018927419789, 0.57413249211356454094, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=12 +intercept=FALSE +Boundary.knots=None +knots=None +output=np.array([0, 0.53333333333333343695, 0.81818181818181801024, 0.16363636363636296922, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.18181818181818207303, 0.83636363636363708629, 0.57446808510638280865, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.42553191489361724686, 0.9000000000000000222, 0.29999999999999982236, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10000000000000003331, 0.70000000000000017764, 0.67346938775510178932, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.32653061224489815517, 0.96923076923076900702, 0.41538461538461529665, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.030769230769230916656, 0.58461538461538464784, 0.7714285714285711304, 0.085714285714284479956, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.22857142857142889736, 0.91428571428571558943, 0.5217391304347820391, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.47826086956521790539, 0.86086956521739110837, 0.23478260869565212299, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.13913043478260883612, 0.76521739130434784926, 0.62499999999999966693, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.37500000000000027756, 0.93599999999999949907, 0.35999999999999854339, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.064000000000000500933, 0.64000000000000145661, 0.7199999999999991962, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2800000000000008038, 1, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([]) +output=np.array([0, 0.00022564828322499611425, 0.00056412070806249024497, 0.001071829345318731563, 0.0018333923012030933775, 0.0029757367350296362075, 0.0046892533857694502358, 0.0072595283618791719288, 0.011114940826043754468, 0.01689805952229062741, 0.025572737566660935088, 0.038584754633216401809, 0.058102780233049600156, 0.087379818632799394207, 0.13129537623242407141, 0.19716871263186111496, 0.29597871723101670804, 0.44419372412975000053, 0.66651623447785002252, 1, ]).reshape((20, 1, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([100, ]) +output=np.array([0, 0.0050505050505050509344, 0.01262626262626262777, 0.023989898989898991721, 0.041035353535353535914, 0.066603535353535359143, 0.10495580808080809398, 0.16248421717171718237, 0.24877683080808082883, 0.37821575126262629851, 0.5723741319444445308, 0.86361170296717182371, 0.98594774828339049044, 0.95530148510216805757, 0.90933209033033446378, 0.84037799817258396207, 0.7369468599359582095, 0.58180015258101969167, 0.3490800915486118039, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.014052251716609454046, 0.044698514897831886916, 0.090667909669665536221, 0.15962200182741601018, 0.26305314006404173499, 0.41819984741898030833, 0.65091990845138814059, 1, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([1000, ]) +output=np.array([0, 0.00050050050050050049616, 0.0012512512512512512404, 0.0023773773773773775736, 0.0040665665665665668566, 0.0066003503503503499136, 0.0104010260260260258, 0.016102039539539540064, 0.02465355980980980799, 0.037480840215215215083, 0.056721760823323322254, 0.08558314173548547954, 0.12887521310372873629, 0.19381332015609359365, 0.29122048073464090745, 0.4373312216024618504, 0.6564973329041932093, 0.98524649985679035868, 0.60726740066762052717, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.39273259933237941732, 1, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([10, 100, 1000, ]) +output=np.array([0, 0.055555555555555552472, 0.13888888888888889506, 0.26388888888888889506, 0.45138888888888883955, 0.73263888888888883955, 0.98454861111111113825, 0.92126736111111118266, 0.82634548611111113825, 0.68396267361111118266, 0.47038845486111113825, 0.15002712673611112715, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015451388888888889506, 0.07873263888888888673, 0.17365451388888888951, 0.31603732638888892836, 0.52961154513888886175, 0.84997287326388892836, 0.96694851345486110272, 0.89486721462673612937, 0.78674526638454855831, 0.62456234402126731275, 0.38128796047634549993, 0.016376385158962673133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.033051486545138890338, 0.10513278537326388451, 0.21325473361545138618, 0.37543765597873263173, 0.61871203952365450007, 0.98362361484103733034, 0.60726740066762052717, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.39273259933237941732, 1, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=3 +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.075249853027630819735, 0.1128747795414462296, 0.16931216931216935828, 0.25396825396825400967, 0.38095238095238104226, 0.57142857142857150787, 0.85714285714285731732, 0.97622585438335818253, 0.92273402674591387118, 0.84249628528974740416, 0.72213967310549775913, 0.54160475482912329159, 0.27080237741456153477, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.023774145616641918083, 0.077265973254086212085, 0.1575037147102526236, 0.27786032689450229638, 0.45839524517087676392, 0.72919762258543852074, 0.99235077739698696053, 0.95792927568342844946, 0.90629702311309068286, 0.82884864425758408846, 0.71267607597432414135, 0.53841722354943410966, 0.27702894491209917316, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0076492226030130125794, 0.042070724316571522783, 0.093702976886909289389, 0.1711513557424159393, 0.28732392402567591416, 0.46158277645056589034, 0.72297105508790082684, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=5 +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.21164021164021157295, 0.31746031746031733167, 0.47619047619047605302, 0.71428571428571407953, 0.98069963811821481148, 0.83594692400482528694, 0.61881785283474100012, 0.2931242460796145699, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.019300361881785188523, 0.16405307599517471306, 0.38118214716525899988, 0.70687575392038548561, 0.9581151832460734763, 0.80104712041884851281, 0.56544502617801106759, 0.21204188481675489975, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.041884816753926495947, 0.19895287958115145943, 0.4345549738219888769, 0.78795811518324510025, 0.93133047210300479168, 0.75965665236051571618, 0.50214592274678215844, 0.11587982832618169693, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.068669527896995374849, 0.2403433476394844226, 0.49785407725321800809, 0.88412017167381840022, 0.93044657380826634174, 0.80003389969876526067, 0.60441488853451352803, 0.31098637178813609561, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.069553426191733672135, 0.19996610030123476709, 0.39558511146548641646, 0.68901362821186384888, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=12 +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.51612903225806461283, 0.77419354838709697475, 0.81818181818181801024, 0.16363636363636296922, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.18181818181818207303, 0.83636363636363708629, 0.57446808510638280865, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.42553191489361724686, 0.9000000000000000222, 0.29999999999999982236, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10000000000000003331, 0.70000000000000017764, 0.67346938775510178932, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.32653061224489815517, 0.96923076923076900702, 0.41538461538461529665, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.030769230769230916656, 0.58461538461538464784, 0.7714285714285711304, 0.085714285714284479956, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.22857142857142889736, 0.91428571428571558943, 0.5217391304347820391, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.47826086956521790539, 0.86086956521739110837, 0.23478260869565212299, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.13913043478260883612, 0.76521739130434784926, 0.62499999999999966693, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.37500000000000027756, 0.93599999999999949907, 0.35999999999999854339, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.064000000000000500933, 0.64000000000000145661, 0.84118724544512846197, 0.43281159087546033915, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.15881275455487159354, 0.56718840912453971637, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([]) +output=np.array([0.0003333333333333333222, 0.00050000000000000001041, 0.00075000000000000001561, 0.001124999999999999915, 0.0016874999999999999809, 0.0025312500000000000798, 0.0037968749999999999029, 0.0056953124999999998543, 0.0085429687499999993477, 0.012814453124999999889, 0.019221679687499999833, 0.02883251953124999975, 0.043248779296874997891, 0.064873168945312503775, 0.097309753417968741784, 0.14596463012695312655, 0.21894694519042967595, 0.32842041778564451393, 0.49263062667846679865, 0.73894594001770019798, ]).reshape((20, 1, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([100, ]) +output=np.array([0.010000000000000000208, 0.014999999999999999445, 0.022499999999999999167, 0.03375000000000000222, 0.050625000000000003331, 0.075937500000000004996, 0.11390625000000000056, 0.17085937500000000777, 0.25628906249999999778, 0.38443359375000002442, 0.57665039062500000888, 0.86497558593750001332, 0.98974264210668094766, 0.96737258384967661495, 0.93381749646417022692, 0.88348486538591053385, 0.80798591876852099425, 0.69473749884243662933, 0.52486486895331019298, 0.27005592411962048294, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.010257357893318963873, 0.032627416150323274024, 0.066182503535829731445, 0.11651513461408942451, 0.192014081231478978, 0.30526250115756325965, 0.47513513104668975151, 0.72994407588037946155, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([1000, ]) +output=np.array([0.0010000000000000000208, 0.0015000000000000000312, 0.0022500000000000002637, 0.0033749999999999999618, 0.0050625000000000001596, 0.0075937499999999998057, 0.011390624999999999709, 0.017085937499999998695, 0.025628906249999999778, 0.038443359374999999667, 0.0576650390624999995, 0.086497558593749995781, 0.12974633789062500755, 0.19461950683593751132, 0.29192926025390625311, 0.43789389038085940742, 0.65684083557128902786, 0.9852612533569335973, 0.76105405998229980202, 0.39158108997344970303, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.23894594001770019798, 0.60841891002655035248, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=1 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([10, 100, 1000, ]) +output=np.array([0.10000000000000000555, 0.1500000000000000222, 0.22500000000000000555, 0.3375000000000000222, 0.5062499999999999778, 0.7593750000000000222, 0.98454861111111113825, 0.92126736111111118266, 0.82634548611111113825, 0.68396267361111118266, 0.47038845486111113825, 0.15002712673611112715, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015451388888888889506, 0.07873263888888888673, 0.17365451388888888951, 0.31603732638888892836, 0.52961154513888886175, 0.84997287326388892836, 0.96694851345486110272, 0.89486721462673612937, 0.78674526638454855831, 0.62456234402126731275, 0.38128796047634549993, 0.016376385158962673133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.033051486545138890338, 0.10513278537326388451, 0.21325473361545138618, 0.37543765597873263173, 0.61871203952365450007, 0.98362361484103733034, 0.76105405998229980202, 0.39158108997344970303, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.23894594001770019798, 0.60841891002655035248, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=5 +intercept=TRUE +Boundary.knots=None +knots=None +output=np.array([1, 0.96845940607276881362, 0.92240303675860391142, 0.85609306993676004272, 0.76270864919645953162, 0.63576547531534310931, 0.47305239057526615731, 0.28507250058887945166, 0.10824783418564158655, 0.0085209665393945269174, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.031533426700978403612, 0.077552412011353655252, 0.14374742102560256196, 0.23683044051100490823, 0.36304322063581223601, 0.52407464745263665495, 0.70834870097260460575, 0.8774087197542927985, 0.96206652916722557034, 0.94530079752693674244, 0.90793500327984399956, 0.85375309463923021447, 0.77659028109030259213, 0.66978920735324132263, 0.52868210857343611586, 0.35651607003382906891, 0.175425242216674937, 0.037891852318801787225, 0, 0, 7.1666852050360488124e-06, 4.4542776169713856592e-05, 0.00015945105252372870864, 0.00046062008693220732759, 0.0011900631879368495612, 0.002868106285078954841, 0.0065607821717948554968, 0.014278782285967288324, 0.029185282443915855355, 0.053915675965905400513, 0.089616579303442189808, 0.13947317683937743293, 0.20621746127156848072, 0.28916251068209719577, 0.37804948423631462573, 0.44191546230800060613, 0.4167872147195200716, 0.22637517283088642861, 0, 0, 5.4104786148500394417e-10, 8.4538728357031864466e-09, 5.7985113780088147304e-08, 2.9020560343812349123e-07, 1.2408609078339073411e-06, 4.8556870182056249453e-06, 1.8016266721020254751e-05, 6.4663774098311141273e-05, 0.00022722184946421446292, 0.0007834394838982231728, 0.0024428479280998137424, 0.0067202853620942429314, 0.016883622849287124174, 0.039626432891546964354, 0.087460636122680179838, 0.179450426719582945, 0.32709043481102628714, 0.44917563313558994675, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.7023259593866311309e-08, 5.5694886140074439238e-06, 5.3443159298083143627e-05, 0.00030863478884180254799, 0.001421849073114332283, 0.0058077710675691540318, 0.022118040938587192612, 0.080697108252778662618, 0.28655734171472191374, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=12 +intercept=TRUE +Boundary.knots=None +knots=None +output=np.array([1, 0.25770097670924113631, 0.00075131480090157780165, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.64290814257309680801, 0.55191727963673464785, 0.16384783952351522629, 0.0025601224925549254108, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.097791408043809202599, 0.4223396450334132024, 0.68523715148898289851, 0.53751029745031897455, 0.17971670556949506659, 0.0066561742803516550301, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0015994726738528394164, 0.024991760528950617698, 0.14994115610379393777, 0.44102623014868380658, 0.69378612010084461659, 0.57911832988268308053, 0.21512754628498662046, 0.013768162962239142988, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00097385288370810028057, 0.018903349908442362848, 0.12592791140580222864, 0.39992732893636862013, 0.67912381051853998315, 0.61416869876328705757, 0.2513505357806551932, 0.023605422218318485722, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00056926292385829722204, 0.014298166900596829057, 0.10543398177170558438, 0.36126140155236396989, 0.66048745076429016265, 0.64290852334776726895, 0.28801011480255123143, 0.036001264350318869234, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00031466142476788003723, 0.010801736722109872915, 0.088001307706519454888, 0.32534582615335716493, 0.63869155767138829916, 0.66560703209160065885, 0.32480624491998255632, 0.050709395542809954094, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00016070574853527342459, 0.0081402282805572035579, 0.073225347399450108066, 0.29228033065100789134, 0.61441387376474365656, 0.68269380491744569017, 0.36150149884261828515, 0.067452174711159121334, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7.2980126610408391891e-05, 0.006111372907072773128, 0.06075244688059205922, 0.26203239546958334572, 0.58821589703491272694, 0.69467005250274826977, 0.39790980589205254825, 0.08594851807268334698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.7434434681658694525e-05, 0.004564404070160951038, 0.05026345997459336773, 0.22896647107718723357, 0.49280704180866574671, 0.39171522957479332216, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.9144147875867501007e-05, 0.0089113017089054759323, 0.10925932166656721067, 0.44968558969337457665, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.383063271446895644e-05, 0.072650662659148546041, 1, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([]) +output=np.array([1, 0.9993232078902789528, 0.99830859239281100059, 0.99678795718714330309, 0.99450990091574942298, 0.99109932847208381812, 0.98599810402219045802, 0.97837913458786918142, 0.96702443008955374371, 0.95015762953345339614, 0.92522695834704149487, 0.88865464163271656872, 0.83562330741598667139, 0.7600990769655836532, 0.65556596659430688145, 0.51745533329454529436, 0.34894530919915062173, 0.17170001728344266856, 0.037087203733223626789, 0, 0, 0.00067663938125675493745, 0.0016904532697119580269, 0.0032085988210942785123, 0.0054800274275235618532, 0.0088741592009194299184, 0.013936134910759763808, 0.021463528321228261819, 0.032607690503775640933, 0.048995387512752772152, 0.072844594278869884141, 0.10699389717286836299, 0.15464119556617272888, 0.21832955541935578081, 0.29724527028257624606, 0.38124822804791375086, 0.44010197217760271826, 0.41166179703994132399, 0.22237265440082615298, 0, 0, 1.5271697506625337419e-07, 9.5415795571804482003e-07, 3.4427604254568415078e-06, 1.0065494095385778498e-05, 2.6485976820866183047e-05, 6.5657954600734260006e-05, 0.00015695450829847096968, 0.00036650624565625982386, 0.00084215780726247437687, 0.0019117237011529813161, 0.0042940168564642817658, 0.0095393459205458924072, 0.020904202366139650049, 0.044925430954654600735, 0.093631406124953353576, 0.18502397635429304601, 0.32899518168053926148, 0.4444443765651269751, 0, 0, 1.1489366970270387462e-11, 1.7952135891047479178e-10, 1.2313370007669466487e-09, 6.1626316488486427104e-09, 2.6350175916113057325e-08, 1.0311244903883365944e-07, 3.825826041044410135e-07, 1.3731610143675871737e-06, 4.8251465313854754769e-06, 1.6723672935651049261e-05, 5.7444337950753896285e-05, 0.0001961510972947611009, 0.00066716524892103249485, 0.0022633321684622557078, 0.0076650325325876428328, 0.025928742268953787475, 0.087643003996076676576, 0.29609576530082332146, 1, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([100, ]) +output=np.array([1, 0.98492487882601165161, 0.96259746673448087773, 0.92974304223814019377, 0.88187654067159670923, 0.81320203136184721071, 0.71702357673990413378, 0.58746094552406258327, 0.42394246616286163087, 0.24039152271518871018, 0.078197326716827678106, 0.0025370634003338671768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015071708273510188089, 0.037381259008501491192, 0.070180462942842899987, 0.11790098280764790828, 0.18621717511273339074, 0.28155389351842002865, 0.40920060085307918829, 0.56848075164647782209, 0.74296035718046105067, 0.88664340493727211712, 0.92755941161894106539, 0.87470363121335126255, 0.79564729322794469635, 0.68622539174158070363, 0.5416556180357140482, 0.36526473871966497198, 0.17973006169687555378, 0.038821693326525116841, 0, 0, 3.4126433211387775282e-06, 2.1270238934697356366e-05, 7.6467258985853174243e-05, 0.00022233858750032365649, 0.00058020375050652503793, 0.0014202218581983020763, 0.003329890582419185209, 0.0075460478259266952628, 0.0165401227086783148, 0.03478495575013232366, 0.06861779430820802439, 0.12096540781627201921, 0.191329633412285538, 0.27905349779077742722, 0.37374631578125083742, 0.44360195032526716918, 0.42250875072786614473, 0.23095694223535656597, 0, 0, 2.5715731172923263021e-10, 4.0180829957692598212e-09, 2.7560031267981358852e-08, 1.3793325533914163604e-07, 5.8977491272702679876e-07, 2.3078834777630869564e-06, 8.5630404390810414166e-06, 3.0734364733920997454e-05, 0.00010799739567214114531, 0.00037431259576781883034, 0.0012857306725170922646, 0.0043281861315545133023, 0.012933767638577380737, 0.033975759516814023342, 0.080531027913042049771, 0.17293083479161802662, 0.32462175106248042367, 0.45442872954598834134, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.7748388221855075202e-06, 8.9305721192384863918e-05, 0.00074535095082784331034, 0.0040670382699930507364, 0.018202476163449766294, 0.07313943651277800273, 0.27579263489213001748, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([1000, ]) +output=np.array([1, 0.9984992498753757495, 0.99625094117633150592, 0.99288481020069696559, 0.98784984394255781481, 0.98032935528140474624, 0.96912034075214636974, 0.95246753354617186282, 0.92784773021983435459, 0.89171926591812056273, 0.83930429776320658597, 0.76459714573223325207, 0.66106035705829924165, 0.52397052211349615103, 0.35606843795797349372, 0.17813877131971986301, 0.040531281972235988498, 3.2113319168708665608e-06, 0, 0, 0, 0.0015004113953972979083, 0.0037469425348356701772, 0.0071075541598605747329, 0.012127833209738946019, 0.019611910086607075437, 0.030734076107229148234, 0.04718451762439003494, 0.071340002591639736784, 0.10641511473995685089, 0.15646348082190494888, 0.22590626848315542574, 0.31787571113275914225, 0.42998547021895328069, 0.54537912943555955092, 0.61788880868397033641, 0.56161589860385985329, 0.31265651834613988891, 0.067535071081621433908, 0, 0, 3.3870374289331948997e-07, 2.1158906445184196164e-06, 7.6329082682329570748e-06, 2.2309178641915861703e-05, 5.8676185825556269023e-05, 0.00014535443145101360611, 0.00034710023984489360048, 0.00080922144066932952776, 0.0018549168973065219106, 0.0041951273738663188637, 0.0093691710332807192491, 0.020628857715017115404, 0.044564197866965707395, 0.093532235391030102423, 0.18697094954821646962, 0.34034142027880176506, 0.49294319032437394767, 0.3494912754584255099, 0, 0, 2.5484057919113140944e-11, 3.9818840498614283815e-10, 2.7311742697999542126e-09, 1.3669061339914938246e-08, 5.844616252249814789e-08, 2.2870917347201761224e-07, 8.4858959306208503663e-07, 3.0457478565146930827e-06, 1.0702444616158128632e-05, 3.7094041022036097191e-05, 0.00012741475133052262828, 0.00043507409392457165433, 0.0014798098005849495782, 0.0050201972154368997708, 0.017001470448093195659, 0.057511399145102344577, 0.1943970799975693331, 0.52239901147403788872, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.060574641985915035625, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([10, 100, 1000, ]) +output=np.array([1, 0.84242112482853226396, 0.63852451989026048906, 0.39886884859396426473, 0.16511776352451987271, 0.019111497248478225702, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.1567541293972270211, 0.35648024152864221659, 0.58396161300859317222, 0.78843465486178421209, 0.87349958752470602263, 0.78872593441389438063, 0.64620704007646878608, 0.46633671277914778841, 0.26443067498670752569, 0.086017059388510438978, 0.0027907697403672538511, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00082460534200152601353, 0.0049930443273597038822, 0.017154488011057174995, 0.046372256997114502663, 0.10706684228609344989, 0.21001709629214043717, 0.349560411044427366, 0.52164005645501687614, 0.7052885939808604121, 0.84461817796425076033, 0.85332055763972392004, 0.74044769630139117833, 0.58689461845094414993, 0.39882902037092649028, 0.19953161831184262898, 0.045398720470901786361, 3.5969836861605402089e-06, 0, 0, 0, 1.4043223919767127475e-07, 2.1942537374636142735e-06, 1.5050386385262928333e-05, 7.5324616581368114944e-05, 0.0003220729407222703883, 0.001256955617244540557, 0.0042307394405898370374, 0.012003815755055342179, 0.030163701749655900952, 0.068814016157702301291, 0.14161203135855129909, 0.25097331049689530769, 0.38604331096967514636, 0.52843933204950088722, 0.62702364005086641541, 0.58518234575989880319, 0.32861311390225123041, 0.070981847410833104339, 0, 0, 0, 0, 0, 0, 0, 1.3676720629513371727e-08, 1.8094385139768081762e-06, 1.9415010780026244647e-05, 0.00011702928277625300924, 0.00055074648953661010323, 0.0022766412613576141911, 0.0085724666641985424603, 0.026852019770306118779, 0.070978550821878275134, 0.16387889672004127273, 0.32660594492319316995, 0.49935626095003893266, 0.36224174733681202554, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6.5265375148376491226e-06, 0.00021005080907461989208, 0.0017530967576943525671, 0.0095658449172495805396, 0.042812988846006136412, 0.17202702816402348773, 0.50620176326643973042, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.060574641985915035625, 1, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=5 +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.93886062842918460714, 0.90924840659363448392, 0.86600789475617090396, 0.80375207763469636024, 0.71607712169296244831, 0.5968951736881422665, 0.4441302646954225497, 0.26764334705075454313, 0.1016296296296296392, 0.0080000000000000019013, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.061118708396877156896, 0.090705266259710190524, 0.13388842602098646739, 0.1960165235067286571, 0.28340857382601336578, 0.40196904868840105385, 0.55338648582541094534, 0.72701318595705810566, 0.88717054427173769326, 0.96957793066711428498, 0.95879430886579075644, 0.93088336665495841071, 0.89004087164963097134, 0.83104478735029430059, 0.74753085865141255528, 0.63305354842556382788, 0.48423310979820943789, 0.30782602005074449769, 0.13273505055352541326, 0.018080241660177655966, 2.0660861734307157164e-05, 4.6319342966912629609e-05, 0.00010365288539398855667, 0.00023130996968619285063, 0.00051400448102423420497, 0.0011347651234567903995, 0.0024798322916666664696, 0.005331933984375000421, 0.011160902197265624297, 0.022290701165771482917, 0.040764443570473873901, 0.067755947834115426431, 0.10621083986053703185, 0.15942942065206799906, 0.22958192424619683347, 0.31428339352859285816, 0.39934193575081916583, 0.44659448090264364239, 0.38447678365411958046, 0.15324078379324712618, 2.3122039887776819585e-09, 7.8036884621246768168e-09, 2.6337448559670789633e-08, 8.888888888888889516e-08, 3.0000000000000003936e-07, 1.0125000000000002586e-06, 3.4171875000000000522e-06, 1.1533007812500000494e-05, 3.892390136718749976e-05, 0.0001313681671142578227, 0.00044121305262908775248, 0.0013584768001177710377, 0.0037270943566249025922, 0.0094033956626723494421, 0.022323349639243747489, 0.050359850764330853223, 0.10765352865786298464, 0.21357717575211032646, 0.36914715819588089785, 0.43210561538410807714, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.451110638240695161e-08, 2.208710808474044903e-06, 2.1194133207095667231e-05, 0.00012239633496539237658, 0.00056386746314699115034, 0.0023032072815124867565, 0.0087714257931084897019, 0.032002323294501686113, 0.11364100759647420558, 0.3965733591624671095, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=12 +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.19405161102201490264, 0.050007289692374980172, 0.00014579384749963551142, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.62621171786550611227, 0.59601302425037649968, 0.37359381834086596852, 0.11076923076923075873, 0.0017307692307692306051, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.17410393357590786545, 0.33496919687132054033, 0.56209998680912809377, 0.6845598495992195609, 0.49785783114523274318, 0.16619304988878053075, 0.0061552981440288964676, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0056327375365711959687, 0.019010489185927782058, 0.064160401002506278756, 0.20369706674784149314, 0.48150804971555583034, 0.70730977578155906915, 0.57961920601900573935, 0.21512754628498662046, 0.013768162962239142988, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00097385288370810028057, 0.018903349908442362848, 0.12592791140580222864, 0.39992732893636862013, 0.67912381051853998315, 0.61416869876328705757, 0.2513505357806551932, 0.023605422218318485722, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00056926292385829722204, 0.014298166900596829057, 0.10543398177170558438, 0.36126140155236396989, 0.66048745076429016265, 0.64290852334776726895, 0.28801011480255123143, 0.036001264350318869234, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00031466142476788003723, 0.010801736722109872915, 0.088001307706519454888, 0.32534582615335716493, 0.63869155767138829916, 0.66560703209160065885, 0.32480624491998255632, 0.050709395542809954094, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00016070574853527342459, 0.0081402282805572035579, 0.073225347399450108066, 0.29228033065100789134, 0.61441387376474365656, 0.68269380491744569017, 0.36150149884261828515, 0.067452174711159121334, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7.2980126610408391891e-05, 0.006111372907072773128, 0.06076004701308617556, 0.2632968675132925096, 0.60214193117458769677, 0.75884556552586945877, 0.54356876952344934661, 0.23438768460872402843, 0.031926653602217504313, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.9834302187538887846e-05, 0.0032999320264517715412, 0.03634723886267338111, 0.16935876914548009253, 0.40315927025443520915, 0.49317292913076199445, 0.23502476599459576345, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9.3311201208237671141e-06, 0.004343490617491435786, 0.053266330072947364049, 0.25527517275326377932, 0.49679177449105649256, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5.6301491679855540114e-06, 0.017164213507250107582, 0.23625680591213024662, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([]) +output=np.array([0.99900033329629622791, 0.99850074987500003765, 0.9977516870781251157, 0.9966287954511718894, 0.99494603816333004875, 0.99242545546139537826, 0.98865256904256049175, 0.98301118751693283837, 0.97458941720955349908, 0.96204716698765402327, 0.94343627795644391387, 0.91597241507140558792, 0.87578413786327058421, 0.81773305675994945041, 0.73555685971681306068, 0.62291325464817093316, 0.47647663168935677769, 0.30289524241999998821, 0.13060889169932207721, 0.017790631148623885227, 0.00099933344444444439057, 0.0014985003750000000684, 0.0022466262656250001253, 0.003367410521484375148, 0.0050454284787597655781, 0.0075553552955017096171, 0.011304291651615143086, 0.016891872202619076515, 0.02519288281652980882, 0.037464410913716578166, 0.055469506915694993809, 0.081581580145842852447, 0.11876628136094780075, 0.1701874001952980997, 0.23787846467254591953, 0.31938947503806314199, 0.40070172821401484065, 0.44437167848162473227, 0.38044436785608970464, 0.1510757732538548781, 3.3322222222222224585e-07, 7.4962500000000004377e-07, 1.6862343750000001263e-06, 3.7926035156249994121e-06, 8.5285524902343742213e-06, 1.9173024810791016186e-05, 4.3084569087982178912e-05, 9.675554396295546727e-05, 0.00021707648827975990682, 0.00048631783460495621712, 0.0010871132367784521085, 0.0024220359003474063384, 0.0053686857976677918383, 0.011806522493618208658, 0.025643231250562635581, 0.054587395598501557703, 0.11232581293261123534, 0.217309662419816918, 0.36939270915445387988, 0.42763873999331791786, 3.7037037037037035514e-11, 1.2500000000000000779e-10, 4.2187500000000000366e-10, 1.4238281249999998508e-09, 4.8054199218749994447e-09, 1.6218292236328128606e-08, 5.4736736297607425773e-08, 1.8473648500442501235e-07, 6.234856368899344564e-07, 2.1042640245035291742e-06, 7.1018910826994105393e-06, 2.3968882404110509299e-05, 8.0894978113872978626e-05, 0.00027302055113432129778, 0.00092144436007833422416, 0.003109874715264377993, 0.010495827164017276431, 0.035423416678558306003, 0.11955403129013431052, 0.40349485560420322861, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([100, ]) +output=np.array([0.97029899999999991156, 0.95567162499999991354, 0.93400735937500012351, 0.9021287441406251606, 0.8556839255371094799, 0.78904911782836917311, 0.69572725948715208322, 0.57001276798105227073, 0.41135095097535856468, 0.23325165409902481883, 0.075874787916011168787, 0.0024617100802805510704, 0, 0, 0, 0, 0, 0, 0, 0, 0.029691034444444444618, 0.044305991250000002768, 0.06594240796875000532, 0.097758673769531262421, 0.1440642544409179715, 0.21038931479278566439, 0.30302618229869843214, 0.4272397443474625911, 0.58266048231123623857, 0.75392639264340943761, 0.89747740349010274308, 0.94501107412874996161, 0.90598359089303848179, 0.84593074837236126307, 0.76092088936222046502, 0.64439302204983184286, 0.49290686036830000383, 0.31333990595172406257, 0.13511264658550559137, 0.018404101188231606484, 9.9644444444444446617e-06, 2.2379999999999999178e-05, 5.0219999999999996902e-05, 0.00011253937500000000703, 0.00025167585937500001371, 0.0005610808300781249848, 0.0012449161120605468141, 0.002741945576934814565, 0.0059698621442985533997, 0.012758825336830616898, 0.02643475186140507513, 0.051808149318846051512, 0.091620856894323976505, 0.14688590543057178373, 0.21984251899359169569, 0.30818245617558825966, 0.39752224089834975462, 0.44889001546541440479, 0.38890408238266155339, 0.15565065849749706861, 1.1111111111111110654e-09, 3.7499999999999996649e-09, 1.2656249999999997938e-08, 4.2714843750000004622e-08, 1.4416259765625001146e-07, 4.8654876708984372583e-07, 1.6421020889282224026e-06, 5.5420945501327518529e-06, 1.8704569106698035598e-05, 6.3127920735105882001e-05, 0.00021305673248098232295, 0.00071906647212331535352, 0.002394473001231371169, 0.0071486127371715351211, 0.018946704087009914874, 0.045842738337222695144, 0.10249145334758576198, 0.20932413300445151805, 0.3687199031810673433, 0.43701763935524273741, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0792114061605856464e-06, 3.473345989527011488e-05, 0.00028988755717800383316, 0.0015817834373569547059, 0.0070794453857644188549, 0.028445945578409920912, 0.10726336785076537317, 0.38892760095902845219, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([1000, ]) +output=np.array([0.99700299900000011188, 0.99550674662500016066, 0.99326517610937503644, 0.98990913343164044225, 0.9848892569724120305, 0.97739130722329725653, 0.96621588612179176714, 0.94961298739566668559, 0.92506696964451773368, 0.88904678238644452293, 0.83678890194350608045, 0.76230564732187677812, 0.65907915850713516548, 0.52240018193475146191, 0.35500130049334505111, 0.17760488924393591503, 0.040409809679633923452, 3.2017075519046728555e-06, 0, 0, 0.0029960014444444446613, 0.0044910048749999993689, 0.0067297664531250009357, 0.010079493029296874088, 0.015085171786376951053, 0.02255122235714721729, 0.033655024381153107738, 0.050097300181899548366, 0.074283671347553537068, 0.10950057690181402847, 0.15997106401940666687, 0.23050015162429349225, 0.3250574690342031281, 0.44299931223779698275, 0.57083333883520204211, 0.6679625481063525827, 0.65410023301458430911, 0.45433806106867219432, 0.19591333754898310193, 0.026685946722935827841, 9.9944444444444452216e-07, 2.2481249999999997573e-06, 5.0561718750000005462e-06, 1.1369267578125000521e-05, 2.5556824951171875081e-05, 5.7421764678955089446e-05, 0.00012892528684616086799, 0.00028915821297883983077, 0.00064748855101794003473, 0.0014463279196678473747, 0.0032187283638391594488, 0.0071222944066175568334, 0.015620687524320137074, 0.033781444174048706752, 0.071401027591217913759, 0.14510293850391842163, 0.2740024758137300509, 0.43938848718810108451, 0.4727098830096430615, 0.21327068651931446741, 1.1111111111111111947e-10, 3.750000000000000492e-10, 1.2656250000000001661e-09, 4.2714843749999999659e-09, 1.4416259765625000816e-08, 4.8654876708984385818e-08, 1.6421020889282225085e-07, 5.5420945501327514294e-07, 1.8704569106698034751e-06, 6.3127920735105875225e-06, 2.1305673248098235006e-05, 7.190664721233152451e-05, 0.00024268493434161889522, 0.00081906165340296394756, 0.0027643330802350029977, 0.0093296241457931361474, 0.031487481492051827558, 0.10627025003567493189, 0.31773412222685926132, 0.53482276673031980962, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.013642657214514538819, 0.22522060002743005125, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([10, 100, 1000, ]) +output=np.array([0.72899999999999987033, 0.61412500000000003197, 0.46548437500000000577, 0.29077539062500001865, 0.12037084960937501077, 0.013932281494140625472, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.26810999999999995946, 0.37949624999999997943, 0.52058109375000005681, 0.6792815039062500837, 0.81701452880859382066, 0.86124092926025386241, 0.77303028831905795659, 0.63334751997894722653, 0.45705661219484272628, 0.2591685045544720456, 0.084305319906679110353, 0.002735233422533945441, 0, 0, 0, 0, 0, 0, 0, 0, 0.0028890000000000000749, 0.0063753749999999990983, 0.013923140625000001921, 0.029904662109375004103, 0.062484875244140626604, 0.12438889535522459906, 0.22549483803134068305, 0.36206390866050391919, 0.53039385361573909705, 0.70984283151236515774, 0.8454844390975239099, 0.85252274549222006872, 0.73970724860508996201, 0.58630772383249318835, 0.39843019135055551816, 0.19933208669353075226, 0.045353321750430879156, 3.5933867024743799741e-06, 0, 0, 9.9999999999999995475e-07, 3.3749999999999998737e-06, 1.1390625000000002433e-05, 3.8443359375000005034e-05, 0.00012974633789062501275, 0.00043789389038085933673, 0.0014748635551852823811, 0.00458723586310897085, 0.012535204497088376849, 0.030902287796947387061, 0.069803749964903766267, 0.14306169398214990673, 0.2539595816136605011, 0.39367833655080086697, 0.54755337589389629915, 0.67082414394774525501, 0.67380308481828354861, 0.47157640817504958841, 0.20334679251999171479, 0.027698480049178006435, 0, 0, 0, 0, 0, 0, 1.009441616706038712e-08, 1.3354974400350171813e-06, 1.4329692329799520979e-05, 8.6376136215493001325e-05, 0.00040649103089326774291, 0.0016803271030961133663, 0.0063296923222741757059, 0.019902020690376800299, 0.053082350626863387955, 0.12474691161612924684, 0.25803204718826688868, 0.43676084046337160238, 0.48134381599312991984, 0.21958058358824134038, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.4774589754063323979e-06, 0.00011191892632920368619, 0.00093408212868467904808, 0.0050968577425946322637, 0.022811546243018676616, 0.091659157974876420694, 0.30166673427236384564, 0.52750033633515069909, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.013642657214514538819, 0.22522060002743005125, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=5 +intercept=FALSE +Boundary.knots=None +knots=None +output=np.array([0, 0.11681123728381428983, 0.2730259078882545376, 0.46749900909245512004, 0.67935641673089897097, 0.85057627482867270707, 0.88934886597560480759, 0.80216081429413377268, 0.67739211125208298458, 0.51560190205519351725, 0.32469390916595280983, 0.13698024292938629221, 0.017122530366173265709, 0, 0, 0, 0, 0, 0, 0, 0, 0.0003496520800200754106, 0.0021367360720303471555, 0.0074505054668944550172, 0.02064467788236522966, 0.049822794327671247883, 0.10672495197833482827, 0.1969631195446764349, 0.31985257188474064405, 0.47686971233712693863, 0.65666375567302859295, 0.82030294962505467815, 0.89243231477003071017, 0.82865930832017831165, 0.7146974084023058893, 0.56412932414843675044, 0.38041985226043306678, 0.187187199501233692, 0.04043243509226646798, 0, 0, 2.6689299275350298406e-08, 4.1702030117734841467e-07, 2.86034224577543261e-06, 1.4315525026353663709e-05, 6.1210311482175452555e-05, 0.00023952573005394856335, 0.00087599557622739540694, 0.0027528938137588820738, 0.0075078612376215788857, 0.018529647319498028513, 0.042210845625950982329, 0.088408426246782453872, 0.16366728062036642322, 0.25992689327612594763, 0.36501727743515482993, 0.44566378087513086603, 0.43199704724253940036, 0.23880246889964723556, 0, 0, 0, 0, 0, 0, 0, 0, 7.058496255109760934e-08, 2.4230494175743949962e-06, 2.0524370058046372483e-05, 0.00011268784152075793045, 0.00050596181960801099326, 0.0020367286170134709343, 0.0076722266846277449928, 0.025178647959627011715, 0.068676202883725015469, 0.1606491966704423624, 0.31804567985939574681, 0.46051790249468016469, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.1843748275951593331e-06, 0.00019705036194114395882, 0.0021771955326834735445, 0.013267170193993682234, 0.062770073396831202461, 0.26024719351340613871, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=12 +intercept=FALSE +Boundary.knots=None +knots=None +output=np.array([0, 0.67103518571234044288, 0.42848228882111855098, 0.069535818471346141911, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.13629558602559715963, 0.52330141887680614587, 0.67103578567914412556, 0.33835295499291540011, 0.045464904980911415022, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0030869584374568800715, 0.048215269973619155619, 0.25524093849303608472, 0.60346220790852211913, 0.66476640009174547963, 0.3023720875414114273, 0.032137228723967029009, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0223284561703245952e-06, 0.0041874573564736911752, 0.058175656367661768287, 0.28413057856289342107, 0.62749346465948352414, 0.64458417746071206, 0.26642650281928137446, 0.020972348618427394396, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9.1807309007930243297e-06, 0.0056381163644495775958, 0.070099504751495456123, 0.31573089553161143295, 0.64918292160807222757, 0.61885031117979483195, 0.23077208437307619726, 0.012169621636861570682, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.494304760976545528e-05, 0.0075476982837094025794, 0.084296696676371143941, 0.3501161628650154567, 0.66789290688121760731, 0.58719180485958433202, 0.19572881144127046715, 0.0058504368174458563218, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9.3878896275372805593e-05, 0.010061177336762315224, 0.10112604997332759471, 0.38726521207131708868, 0.68285613364861541541, 0.54940228374944388712, 0.16169301614535666611, 0.001987124003607085819, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00020895877237870428959, 0.013373361432237074534, 0.12100109812882933746, 0.42699888243551975542, 0.69315383369930994029, 0.50558220978145163027, 0.12915009496447266146, 0.00028659920802505926699, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00041395678128490346389, 0.017748396997590374508, 0.14439460468269080251, 0.46888258402048205165, 0.69769409523153691488, 0.45636616933565676835, 0.098685730485585029803, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00075854547264270536476, 0.023548082194459314664, 0.16992724106945886198, 0.46662458342302287617, 0.42010939261246582621, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0032285687345316718341, 0.076722648033295162695, 0.42847050190194924113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.052734374999999840405, 1, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([]) +output=np.array([0, 0.00067663938125675493745, 0.0016904532697119580269, 0.0032085988210942785123, 0.0054800274275235618532, 0.0088741592009194299184, 0.013936134910759763808, 0.021463528321228261819, 0.032607690503775640933, 0.048995387512752772152, 0.072844594278869884141, 0.10699389717286836299, 0.15464119556617272888, 0.21832955541935578081, 0.29724527028257624606, 0.38124822804791375086, 0.44010197217760271826, 0.41166179703994132399, 0.22237265440082615298, 0, 0, 1.5271697506625337419e-07, 9.5415795571804482003e-07, 3.4427604254568415078e-06, 1.0065494095385778498e-05, 2.6485976820866183047e-05, 6.5657954600734260006e-05, 0.00015695450829847096968, 0.00036650624565625982386, 0.00084215780726247437687, 0.0019117237011529813161, 0.0042940168564642817658, 0.0095393459205458924072, 0.020904202366139650049, 0.044925430954654600735, 0.093631406124953353576, 0.18502397635429304601, 0.32899518168053926148, 0.4444443765651269751, 0, 0, 1.1489366970270387462e-11, 1.7952135891047479178e-10, 1.2313370007669466487e-09, 6.1626316488486427104e-09, 2.6350175916113057325e-08, 1.0311244903883365944e-07, 3.825826041044410135e-07, 1.3731610143675871737e-06, 4.8251465313854754769e-06, 1.6723672935651049261e-05, 5.7444337950753896285e-05, 0.0001961510972947611009, 0.00066716524892103249485, 0.0022633321684622557078, 0.0076650325325876428328, 0.025928742268953787475, 0.087643003996076676576, 0.29609576530082332146, 1, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([100, ]) +output=np.array([0, 0.015071708273510188089, 0.037381259008501491192, 0.070180462942842899987, 0.11790098280764790828, 0.18621717511273339074, 0.28155389351842002865, 0.40920060085307918829, 0.56848075164647782209, 0.74296035718046105067, 0.88664340493727211712, 0.92755941161894106539, 0.87470363121335126255, 0.79564729322794469635, 0.68622539174158070363, 0.5416556180357140482, 0.36526473871966497198, 0.17973006169687555378, 0.038821693326525116841, 0, 0, 3.4126433211387775282e-06, 2.1270238934697356366e-05, 7.6467258985853174243e-05, 0.00022233858750032365649, 0.00058020375050652503793, 0.0014202218581983020763, 0.003329890582419185209, 0.0075460478259266952628, 0.0165401227086783148, 0.03478495575013232366, 0.06861779430820802439, 0.12096540781627201921, 0.191329633412285538, 0.27905349779077742722, 0.37374631578125083742, 0.44360195032526716918, 0.42250875072786614473, 0.23095694223535656597, 0, 0, 2.5715731172923263021e-10, 4.0180829957692598212e-09, 2.7560031267981358852e-08, 1.3793325533914163604e-07, 5.8977491272702679876e-07, 2.3078834777630869564e-06, 8.5630404390810414166e-06, 3.0734364733920997454e-05, 0.00010799739567214114531, 0.00037431259576781883034, 0.0012857306725170922646, 0.0043281861315545133023, 0.012933767638577380737, 0.033975759516814023342, 0.080531027913042049771, 0.17293083479161802662, 0.32462175106248042367, 0.45442872954598834134, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.7748388221855075202e-06, 8.9305721192384863918e-05, 0.00074535095082784331034, 0.0040670382699930507364, 0.018202476163449766294, 0.07313943651277800273, 0.27579263489213001748, 1, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([1000, ]) +output=np.array([0, 0.0015004113953972979083, 0.0037469425348356701772, 0.0071075541598605747329, 0.012127833209738946019, 0.019611910086607075437, 0.030734076107229148234, 0.04718451762439003494, 0.071340002591639736784, 0.10641511473995685089, 0.15646348082190494888, 0.22590626848315542574, 0.31787571113275914225, 0.42998547021895328069, 0.54537912943555955092, 0.61788880868397033641, 0.56161589860385985329, 0.31265651834613988891, 0.067535071081621433908, 0, 0, 3.3870374289331948997e-07, 2.1158906445184196164e-06, 7.6329082682329570748e-06, 2.2309178641915861703e-05, 5.8676185825556269023e-05, 0.00014535443145101360611, 0.00034710023984489360048, 0.00080922144066932952776, 0.0018549168973065219106, 0.0041951273738663188637, 0.0093691710332807192491, 0.020628857715017115404, 0.044564197866965707395, 0.093532235391030102423, 0.18697094954821646962, 0.34034142027880176506, 0.49294319032437394767, 0.3494912754584255099, 0, 0, 2.5484057919113140944e-11, 3.9818840498614283815e-10, 2.7311742697999542126e-09, 1.3669061339914938246e-08, 5.844616252249814789e-08, 2.2870917347201761224e-07, 8.4858959306208503663e-07, 3.0457478565146930827e-06, 1.0702444616158128632e-05, 3.7094041022036097191e-05, 0.00012741475133052262828, 0.00043507409392457165433, 0.0014798098005849495782, 0.0050201972154368997708, 0.017001470448093195659, 0.057511399145102344577, 0.1943970799975693331, 0.52239901147403788872, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.060574641985915035625, 1, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([10, 100, 1000, ]) +output=np.array([0, 0.1567541293972270211, 0.35648024152864221659, 0.58396161300859317222, 0.78843465486178421209, 0.87349958752470602263, 0.78872593441389438063, 0.64620704007646878608, 0.46633671277914778841, 0.26443067498670752569, 0.086017059388510438978, 0.0027907697403672538511, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00082460534200152601353, 0.0049930443273597038822, 0.017154488011057174995, 0.046372256997114502663, 0.10706684228609344989, 0.21001709629214043717, 0.349560411044427366, 0.52164005645501687614, 0.7052885939808604121, 0.84461817796425076033, 0.85332055763972392004, 0.74044769630139117833, 0.58689461845094414993, 0.39882902037092649028, 0.19953161831184262898, 0.045398720470901786361, 3.5969836861605402089e-06, 0, 0, 0, 1.4043223919767127475e-07, 2.1942537374636142735e-06, 1.5050386385262928333e-05, 7.5324616581368114944e-05, 0.0003220729407222703883, 0.001256955617244540557, 0.0042307394405898370374, 0.012003815755055342179, 0.030163701749655900952, 0.068814016157702301291, 0.14161203135855129909, 0.25097331049689530769, 0.38604331096967514636, 0.52843933204950088722, 0.62702364005086641541, 0.58518234575989880319, 0.32861311390225123041, 0.070981847410833104339, 0, 0, 0, 0, 0, 0, 0, 1.3676720629513371727e-08, 1.8094385139768081762e-06, 1.9415010780026244647e-05, 0.00011702928277625300924, 0.00055074648953661010323, 0.0022766412613576141911, 0.0085724666641985424603, 0.026852019770306118779, 0.070978550821878275134, 0.16387889672004127273, 0.32660594492319316995, 0.49935626095003893266, 0.36224174733681202554, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6.5265375148376491226e-06, 0.00021005080907461989208, 0.0017530967576943525671, 0.0095658449172495805396, 0.042812988846006136412, 0.17202702816402348773, 0.50620176326643973042, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.060574641985915035625, 1, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=5 +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.20791834248678603414, 0.29902312242189532654, 0.42058546782444744538, 0.57127689681172544311, 0.73389736255977222612, 0.86146730066325027941, 0.87986332643537079612, 0.79291382076038952054, 0.66958340212426392668, 0.50965824665676062732, 0.32095096582466564605, 0.13540118870728076739, 0.016925148588410078576, 0, 0, 0, 0, 0, 0, 0, 0.0012695557913002517882, 0.0028166847710175994465, 0.0062031625467877079053, 0.013503589345765960872, 0.028852424480264381862, 0.059752006107076843788, 0.11700693595529969293, 0.20637160010579103098, 0.32827217823508614281, 0.48461478028531612683, 0.66503213888472001436, 0.83266225254172265835, 0.91555098377957688793, 0.87163430177910428132, 0.78404142346700400612, 0.66397286412208100792, 0.507883804798330174, 0.32286071959112722096, 0.1392180359854287286, 0.018963308663199267973, 1.4499417527118528165e-07, 4.893553415402503421e-07, 1.6515742776983449575e-06, 5.5740631872319126435e-06, 1.8812463256907710572e-05, 6.3492063492063516403e-05, 0.000214285714285714356, 0.0007145407126011744112, 0.0021431007122621795712, 0.0057158011131347528228, 0.013955556387630695808, 0.03166115066306447734, 0.066415223634956249699, 0.12418853438999710725, 0.20209136094044644061, 0.29685688827833944803, 0.39377505733963352741, 0.45246903544196670488, 0.39638281649040951748, 0.1597891894713379668, 0, 0, 0, 0, 0, 0, 0, 3.8421218399486777976e-08, 1.3189283878698809637e-06, 1.117194478839918966e-05, 6.133890298378388427e-05, 0.00027540808793216300541, 0.0011086439970568826713, 0.0041767162702452207551, 0.013792752688869525796, 0.038347512235655537016, 0.093327637726685397368, 0.20095020769675242533, 0.36605493991801690834, 0.4433598240831516657, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4.4756065322375969297e-07, 7.4462903680102773569e-05, 0.0008227353639237797861, 0.0050135001353509671407, 0.023720037270153770254, 0.09834420760614477619, 0.37788767778231108219, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=12 +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.61574942641905272556, 0.5337910278271761344, 0.26630652260904380535, 0.04321728691476599965, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.21709357831448763965, 0.40428360185244682778, 0.62558529044677246844, 0.63046184489143586305, 0.30534794185536534572, 0.041029980550522253402, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0094918061936686368846, 0.032034845903631647968, 0.10810716461572758562, 0.32213341083732455195, 0.63646722104607222903, 0.66920132452213465513, 0.3023720875414114273, 0.032137228723967029009, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0223284561703245952e-06, 0.0041874573564736911752, 0.058175656367661768287, 0.28413057856289342107, 0.62749346465948352414, 0.64458417746071206, 0.26642650281928137446, 0.020972348618427394396, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9.1807309007930243297e-06, 0.0056381163644495775958, 0.070099504751495456123, 0.31573089553161143295, 0.64918292160807222757, 0.61885031117979483195, 0.23077208437307619726, 0.012169621636861570682, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.494304760976545528e-05, 0.0075476982837094025794, 0.084296696676371143941, 0.3501161628650154567, 0.66789290688121760731, 0.58719180485958433202, 0.19572881144127046715, 0.0058504368174458563218, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9.3878896275372805593e-05, 0.010061177336762315224, 0.10112604997332759471, 0.38726521207131708868, 0.68285613364861541541, 0.54940228374944388712, 0.16169301614535666611, 0.001987124003607085819, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00020895877237870428959, 0.013373361432237074534, 0.12100109812882933746, 0.42699888243551975542, 0.69315383369930994029, 0.50558220978145163027, 0.12915009496447266146, 0.00028659920802505926699, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00041395678128490346389, 0.017748396997590374508, 0.14460859026960704021, 0.4755254951851585199, 0.74591378938143138022, 0.59473172632230031365, 0.2566313326020329133, 0.03495652799821041129, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00054455988572647427617, 0.016905171029782832537, 0.12340338564379622899, 0.3685583814319431939, 0.50219016290765505772, 0.24887848966988834754, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0015327300102998579149, 0.03642329303773143151, 0.22969990963832651043, 0.49849681328683803638, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.011478594851985721506, 0.21766816904506322561, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([]) +output=np.array([0.00099933344444444439057, 0.0014985003750000000684, 0.0022466262656250001253, 0.003367410521484375148, 0.0050454284787597655781, 0.0075553552955017096171, 0.011304291651615143086, 0.016891872202619076515, 0.02519288281652980882, 0.037464410913716578166, 0.055469506915694993809, 0.081581580145842852447, 0.11876628136094780075, 0.1701874001952980997, 0.23787846467254591953, 0.31938947503806314199, 0.40070172821401484065, 0.44437167848162473227, 0.38044436785608970464, 0.1510757732538548781, 3.3322222222222224585e-07, 7.4962500000000004377e-07, 1.6862343750000001263e-06, 3.7926035156249994121e-06, 8.5285524902343742213e-06, 1.9173024810791016186e-05, 4.3084569087982178912e-05, 9.675554396295546727e-05, 0.00021707648827975990682, 0.00048631783460495621712, 0.0010871132367784521085, 0.0024220359003474063384, 0.0053686857976677918383, 0.011806522493618208658, 0.025643231250562635581, 0.054587395598501557703, 0.11232581293261123534, 0.217309662419816918, 0.36939270915445387988, 0.42763873999331791786, 3.7037037037037035514e-11, 1.2500000000000000779e-10, 4.2187500000000000366e-10, 1.4238281249999998508e-09, 4.8054199218749994447e-09, 1.6218292236328128606e-08, 5.4736736297607425773e-08, 1.8473648500442501235e-07, 6.234856368899344564e-07, 2.1042640245035291742e-06, 7.1018910826994105393e-06, 2.3968882404110509299e-05, 8.0894978113872978626e-05, 0.00027302055113432129778, 0.00092144436007833422416, 0.003109874715264377993, 0.010495827164017276431, 0.035423416678558306003, 0.11955403129013431052, 0.40349485560420322861, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([100, ]) +output=np.array([0.029691034444444444618, 0.044305991250000002768, 0.06594240796875000532, 0.097758673769531262421, 0.1440642544409179715, 0.21038931479278566439, 0.30302618229869843214, 0.4272397443474625911, 0.58266048231123623857, 0.75392639264340943761, 0.89747740349010274308, 0.94501107412874996161, 0.90598359089303848179, 0.84593074837236126307, 0.76092088936222046502, 0.64439302204983184286, 0.49290686036830000383, 0.31333990595172406257, 0.13511264658550559137, 0.018404101188231606484, 9.9644444444444446617e-06, 2.2379999999999999178e-05, 5.0219999999999996902e-05, 0.00011253937500000000703, 0.00025167585937500001371, 0.0005610808300781249848, 0.0012449161120605468141, 0.002741945576934814565, 0.0059698621442985533997, 0.012758825336830616898, 0.02643475186140507513, 0.051808149318846051512, 0.091620856894323976505, 0.14688590543057178373, 0.21984251899359169569, 0.30818245617558825966, 0.39752224089834975462, 0.44889001546541440479, 0.38890408238266155339, 0.15565065849749706861, 1.1111111111111110654e-09, 3.7499999999999996649e-09, 1.2656249999999997938e-08, 4.2714843750000004622e-08, 1.4416259765625001146e-07, 4.8654876708984372583e-07, 1.6421020889282224026e-06, 5.5420945501327518529e-06, 1.8704569106698035598e-05, 6.3127920735105882001e-05, 0.00021305673248098232295, 0.00071906647212331535352, 0.002394473001231371169, 0.0071486127371715351211, 0.018946704087009914874, 0.045842738337222695144, 0.10249145334758576198, 0.20932413300445151805, 0.3687199031810673433, 0.43701763935524273741, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0792114061605856464e-06, 3.473345989527011488e-05, 0.00028988755717800383316, 0.0015817834373569547059, 0.0070794453857644188549, 0.028445945578409920912, 0.10726336785076537317, 0.38892760095902845219, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([1000, ]) +output=np.array([0.0029960014444444446613, 0.0044910048749999993689, 0.0067297664531250009357, 0.010079493029296874088, 0.015085171786376951053, 0.02255122235714721729, 0.033655024381153107738, 0.050097300181899548366, 0.074283671347553537068, 0.10950057690181402847, 0.15997106401940666687, 0.23050015162429349225, 0.3250574690342031281, 0.44299931223779698275, 0.57083333883520204211, 0.6679625481063525827, 0.65410023301458430911, 0.45433806106867219432, 0.19591333754898310193, 0.026685946722935827841, 9.9944444444444452216e-07, 2.2481249999999997573e-06, 5.0561718750000005462e-06, 1.1369267578125000521e-05, 2.5556824951171875081e-05, 5.7421764678955089446e-05, 0.00012892528684616086799, 0.00028915821297883983077, 0.00064748855101794003473, 0.0014463279196678473747, 0.0032187283638391594488, 0.0071222944066175568334, 0.015620687524320137074, 0.033781444174048706752, 0.071401027591217913759, 0.14510293850391842163, 0.2740024758137300509, 0.43938848718810108451, 0.4727098830096430615, 0.21327068651931446741, 1.1111111111111111947e-10, 3.750000000000000492e-10, 1.2656250000000001661e-09, 4.2714843749999999659e-09, 1.4416259765625000816e-08, 4.8654876708984385818e-08, 1.6421020889282225085e-07, 5.5420945501327514294e-07, 1.8704569106698034751e-06, 6.3127920735105875225e-06, 2.1305673248098235006e-05, 7.190664721233152451e-05, 0.00024268493434161889522, 0.00081906165340296394756, 0.0027643330802350029977, 0.0093296241457931361474, 0.031487481492051827558, 0.10627025003567493189, 0.31773412222685926132, 0.53482276673031980962, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.013642657214514538819, 0.22522060002743005125, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=3 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([10, 100, 1000, ]) +output=np.array([0.26810999999999995946, 0.37949624999999997943, 0.52058109375000005681, 0.6792815039062500837, 0.81701452880859382066, 0.86124092926025386241, 0.77303028831905795659, 0.63334751997894722653, 0.45705661219484272628, 0.2591685045544720456, 0.084305319906679110353, 0.002735233422533945441, 0, 0, 0, 0, 0, 0, 0, 0, 0.0028890000000000000749, 0.0063753749999999990983, 0.013923140625000001921, 0.029904662109375004103, 0.062484875244140626604, 0.12438889535522459906, 0.22549483803134068305, 0.36206390866050391919, 0.53039385361573909705, 0.70984283151236515774, 0.8454844390975239099, 0.85252274549222006872, 0.73970724860508996201, 0.58630772383249318835, 0.39843019135055551816, 0.19933208669353075226, 0.045353321750430879156, 3.5933867024743799741e-06, 0, 0, 9.9999999999999995475e-07, 3.3749999999999998737e-06, 1.1390625000000002433e-05, 3.8443359375000005034e-05, 0.00012974633789062501275, 0.00043789389038085933673, 0.0014748635551852823811, 0.00458723586310897085, 0.012535204497088376849, 0.030902287796947387061, 0.069803749964903766267, 0.14306169398214990673, 0.2539595816136605011, 0.39367833655080086697, 0.54755337589389629915, 0.67082414394774525501, 0.67380308481828354861, 0.47157640817504958841, 0.20334679251999171479, 0.027698480049178006435, 0, 0, 0, 0, 0, 0, 1.009441616706038712e-08, 1.3354974400350171813e-06, 1.4329692329799520979e-05, 8.6376136215493001325e-05, 0.00040649103089326774291, 0.0016803271030961133663, 0.0063296923222741757059, 0.019902020690376800299, 0.053082350626863387955, 0.12474691161612924684, 0.25803204718826688868, 0.43676084046337160238, 0.48134381599312991984, 0.21958058358824134038, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.4774589754063323979e-06, 0.00011191892632920368619, 0.00093408212868467904808, 0.0050968577425946322637, 0.022811546243018676616, 0.091659157974876420694, 0.30166673427236384564, 0.52750033633515069909, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.013642657214514538819, 0.22522060002743005125, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=12 +intercept=TRUE +Boundary.knots=None +knots=None +output=np.array([1, 0.24780328615799376846, 0.0091743090758214639741, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.64369896942547122354, 0.57211971408849160436, 0.24237606578683060232, 0.044144491052264721309, 0.00040499520490831021667, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10612816657504857421, 0.39035389287158045457, 0.63115822592338399755, 0.61942792972003923868, 0.3746409686363950664, 0.1299270153679348283, 0.01456850160548600788, 2.4933115730197022697e-06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0023615475345642161081, 0.028071577965966144214, 0.12345862383415923125, 0.3183634697319876472, 0.55248624494736087165, 0.66157907323456133231, 0.54063561857561015511, 0.27886806629206489783, 0.077562585629719432712, 0.0043678218067639239253, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.026857613403984366e-06, 0.00028016915158263086755, 0.0029987443674941152358, 0.017947370921348515527, 0.071410333320899577192, 0.20176799613356366514, 0.41383987857855386583, 0.6154467549253210823, 0.65231295225138286042, 0.47044608242977714596, 0.21195012900662815736, 0.045727490940629646199, 0.00095767216067723433693, 0, 0, 0, 0, 0, 0, 0, 3.4493087511455702552e-09, 3.3684655772905958113e-07, 8.3400865772486489595e-06, 0.00011672374464387017944, 0.001056583561129178974, 0.0067076933166381781659, 0.030729882600253097258, 0.10383387100350169319, 0.2594160581947105304, 0.48008955662192837055, 0.64645432100283450882, 0.61990700734803594329, 0.39505102004440167951, 0.15152949559297854143, 0.022327498493473717928, 5.4255821339140527268e-05, 0, 0, 0, 0, 0, 0, 1.5550084505986725427e-12, 1.4829716211306275165e-08, 8.7432930709587782537e-07, 1.8221855962693547294e-05, 0.00022606146610042746276, 0.0018465551075490084856, 0.010668371345813800616, 0.044660809207147045274, 0.13839012473302086947, 0.31749140013695392737, 0.53873603574199457888, 0.65962064818889976081, 0.56521993555148342114, 0.310506638922921685, 0.095251921793756827439, 0.0074067894386825334357, 0, 0, 0, 0, 0, 0, 0, 9.1339471742565674011e-11, 5.7173996413972389293e-08, 2.2593599905185296879e-06, 4.0028808856421427135e-05, 0.00043513707847336695594, 0.0031885139595084076476, 0.016618589891805510966, 0.062812605113451408512, 0.1727378974109962384, 0.33696595086343833492, 0.43637044859132123609, 0.31354081400102012944, 0.068636818178064884499, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.7695168114557225724e-09, 5.9285591015796308443e-07, 1.6911296921410870622e-05, 0.00025529307410796154469, 0.0024263360322963763681, 0.015741731604329466804, 0.070644470707028478307, 0.21311252564833091383, 0.3762972750744253414, 0.24384934178453185338, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0868704401501409189e-12, 2.1860846716771802376e-07, 1.6330907178590211063e-05, 0.00037021035039809161273, 0.0048110469704648085865, 0.038471273482950811562, 0.18655513337806783891, 0.39552144655799137407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.6852398034939565224e-08, 3.1097414111410212796e-05, 0.0014848575331362907741, 0.028249998152729726558, 0.25456576340175340878, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00010485760000000057303, 0.030019840638976030833, 1, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([]) +output=np.array([1, 0.99887226764047176708, 0.99718257698671308731, 0.99465232914808876519, 0.99086659019744105503, 0.98520960330607720845, 0.9767725953351565904, 0.96422555375161622671, 0.94564705949867622348, 0.91831730137969458383, 0.87851085191767241955, 0.82140061321171964348, 0.74134024099742168445, 0.63306797132011838336, 0.49472136419952228437, 0.33351966492579832035, 0.17295333506564730675, 0.053041675157364839843, 0.0041245206602366912829, 0, 0, 0.0011272234177996938269, 0.0028142442804627715303, 0.0053362072774053633667, 0.0090999196124958610377, 0.014702372431044495246, 0.023009568696928141274, 0.035255048800207078319, 0.053144756365466998271, 0.078922539871719557536, 0.11527760116980134697, 0.16482753559964863355, 0.22865514515079901625, 0.30306893078627178406, 0.37385911082806172478, 0.40954833229285447782, 0.36355794566479110452, 0.2119513600790149388, 0.041217298467029310494, 0, 0, 5.0882687398560041373e-07, 3.1769391294621280289e-06, 1.1451280924188917779e-05, 3.3428733100138665235e-05, 8.7761935886847988286e-05, 0.00021681208262686383053, 0.00051561316170019592855, 0.0011946804469067555735, 0.0027131220507094727483, 0.0060506596144855023106, 0.013230141811374926397, 0.028210083582453096551, 0.058035333309565624582, 0.11300958063559926603, 0.20116335451605230067, 0.30568795867586873172, 0.33877798094471850421, 0.16475763686175207146, 0, 0, 1.1484182443411814437e-10, 1.7931887260774516498e-09, 1.2286988490864389756e-08, 6.1400553206305291637e-08, 2.6193586874264870438e-07, 1.0214767558696939837e-06, 3.7704802796487805225e-06, 1.3428054504627923681e-05, 4.6634530984498030184e-05, 0.00015879269432593164958, 0.00053096908751411363639, 0.00174019442073816092, 0.0055566565395111476577, 0.017080184681265514479, 0.049404053208565550104, 0.12851476524402274948, 0.27074730808567093465, 0.32929231067852438031, 0, 0, 1.2959854631941128047e-14, 5.06072933143619642e-13, 6.5918427455453850986e-12, 5.6389033989814727996e-11, 3.9088927700060016774e-10, 2.406265255469648607e-09, 1.378603437152614992e-08, 7.5464802427343835863e-08, 4.0078909822273000137e-07, 2.0836670196190539855e-06, 1.0654767572225721294e-05, 5.3673655611779830157e-05, 0.00026601408260545672708, 0.0012907432586925205419, 0.0060666130749972404027, 0.027014549341864656923, 0.10818900424286860551, 0.32906949849914446382, 0, 0, 5.8500579526198340832e-19, 5.7129472193553077444e-17, 1.4145822896898457119e-15, 2.0714622186680568112e-14, 2.3333104795078233906e-13, 2.2673496764008742317e-12, 2.0162390952550372537e-11, 1.6964293385718098169e-10, 1.3777936465799164788e-09, 1.0936695210263550545e-08, 8.5522170452256458058e-08, 6.6219297623306537514e-07, 5.0939619277349284707e-06, 3.9016396858695978102e-05, 0.00029798198173219142288, 0.00227144600780565184, 0.017292671490362138825, 0.13153873483331313121, 1, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([100, ]) +output=np.array([1, 0.97500126574733914087, 0.93844290960000364965, 0.88566924020111725824, 0.81098530154789516544, 0.70848516022771668155, 0.57441053105822748037, 0.41206430922482584212, 0.2392461015407435776, 0.092939125284492898893, 0.014299466806025581608, 4.7193863677059842883e-05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.024987397851780435848, 0.061486796626462968118, 0.1140799960900419352, 0.1882939537142028219, 0.28966625638367565765, 0.42117968175620157378, 0.57798465087862005429, 0.73943782746930653005, 0.86397935690336380432, 0.90462871246453147034, 0.85976637084822715718, 0.77601114642224255924, 0.66267521310641597232, 0.51785842958629058064, 0.34911766989097126057, 0.18104199448456753663, 0.055522321426452851678, 0.0043174157141209739547, 0, 0, 1.1333836374491041766e-05, 7.0253868335539153452e-05, 0.00025049169236306427153, 0.00071939598049462782393, 0.0018428967293926601032, 0.0043879998552115674279, 0.0098727402942039785283, 0.021048289930652556295, 0.042207103219050953746, 0.078361329513138483494, 0.1323267251748408424, 0.20305646979998087653, 0.28625091024051202426, 0.36712456913477936604, 0.41237454577086030127, 0.37209382828918063923, 0.21926721332006066101, 0.042943027456719351509, 0, 0, 2.5642163564224008165e-09, 3.9893896948733327568e-08, 2.7186958324120860093e-07, 1.3475047468249140318e-06, 5.6780166980285093331e-06, 2.1734507210374597486e-05, 7.8000238621073664019e-05, 0.00026616938183067457386, 0.00086607259863206911138, 0.0026688434677071591963, 0.0076602480569788727188, 0.020032890189762748295, 0.047362176442216685768, 0.10112516340575794516, 0.19128545657973258787, 0.30258229747242648688, 0.34436724521558481626, 0.17045464690987927048, 0, 0, 2.8979008849349871451e-13, 1.1299684644739179399e-11, 1.4686295227238142049e-10, 1.2521970298985838129e-09, 8.6372943219355255736e-09, 5.2772400925513216102e-08, 2.9891245041530529781e-07, 1.607880484564848822e-06, 8.3111564072833673416e-06, 4.1402961295506068027e-05, 0.00019754788193526286806, 0.00088468396831814228969, 0.0036015013400145573161, 0.013149579882492583999, 0.042768561910798960635, 0.12037399719492403172, 0.26730426029673903798, 0.33672081019045274619, 0, 0, 1.309371682920953332e-17, 1.2786832841024935257e-15, 3.1661464010829005262e-14, 4.6363882090260461786e-13, 5.2224622287067364928e-12, 5.0748274386406234902e-11, 4.5127867086219768747e-10, 3.7969821085404869e-09, 3.0838053235562167103e-08, 2.44787301750460405e-07, 1.9141743408195724709e-06, 1.4809071760067401229e-05, 0.00011002044182894339316, 0.0007361307065949982114, 0.0043501410333869746858, 0.022648326644076191561, 0.10074752233050462968, 0.32871166293410319925, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5.4793570769921117731e-10, 1.7842901170031562027e-07, 6.1272840845677704696e-06, 0.00010362481425005589904, 0.0012595559148250148798, 0.012791437410658173385, 0.11685243679472454015, 1, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([1000, ]) +output=np.array([1, 0.9975000012515636838, 0.99375938046297329631, 0.9881694981371595965, 0.97983186568317970355, 0.96743102855471574397, 0.94906548971852167096, 0.92204114544049331492, 0.88266217520230549898, 0.82612719043156179755, 0.74679100501527517775, 0.63932416597329111418, 0.50165120112244221406, 0.34054780971703357828, 0.17887753393501265586, 0.056398049910775530091, 0.0047824514208348522723, 6.9899702309353164834e-10, 0, 0, 0, 0.0024988701975066367374, 0.0062335737743966241481, 0.011805108206123089004, 0.020094017057672219906, 0.032374436158623724757, 0.050454096263104174225, 0.076816980711751164934, 0.11469423978741608017, 0.16787638509201657788, 0.23985925947403505254, 0.33155764168655321722, 0.4364690436594241274, 0.53267348082579712987, 0.57514542430970139186, 0.50463302930351572329, 0.30623588293439429897, 0.096587849561305616497, 0.0075106712808647091081, 0, 0, 1.1282962103271197581e-06, 7.0417854820895302466e-06, 2.536640667453833115e-05, 7.3981096505374880712e-05, 0.00019395448667024030114, 0.00047814948330325205252, 0.0011335173229715391711, 0.0026138368581788955919, 0.0058931764589364287604, 0.012998501527337540801, 0.027945386445582046098, 0.058044007669012950834, 0.1145680954987259581, 0.2086069927114643785, 0.33148565972609811414, 0.41061823564260202524, 0.3066625410662744966, 0.068889778730265194273, 0, 0, 2.5469057156714312774e-10, 3.976025713192789869e-09, 2.7235422387831816846e-08, 1.3603757883811768205e-07, 5.7993308882550318022e-07, 2.2591989366454093128e-06, 8.3259563410340815473e-06, 2.9580849000601624262e-05, 0.00010235971125482330811, 0.00034661758311907198181, 0.001149214388416119545, 0.0037170166582407206807, 0.011623043605661884797, 0.034525979049628140183, 0.094171296281739258482, 0.21954225794050497012, 0.36514412761590397949, 0.24346326935859208263, 0, 0, 2.8744101198050118059e-14, 1.1223436953991581798e-12, 1.4617253735361878953e-11, 1.2501806315302350017e-10, 8.6638386346496238246e-10, 5.3311050540562872207e-09, 3.0523721489433262118e-08, 1.6692682142232341016e-07, 8.8525020719146049419e-07, 4.5921420319874677743e-06, 2.3401813204582281116e-05, 0.0001172621098580812533, 0.00057627166059595505247, 0.0027575294458836020588, 0.012651024092369157759, 0.053782977897194939043, 0.19324936944781076487, 0.3997562713358867037, 0, 0, 1.2975755416333770318e-18, 1.2671636148763449243e-16, 3.1376225596317031531e-15, 4.5946189458816680778e-14, 5.1754130194391066624e-13, 5.0291082725267428713e-12, 4.4721309725082660758e-11, 3.762775062517599803e-10, 3.0560232936142684245e-09, 2.4258201074369941878e-08, 1.8969295269383146249e-07, 1.4687810219326831175e-06, 1.1298692185571222767e-05, 8.6540548310009559815e-05, 0.00066094068550206401882, 0.0050381941644688631871, 0.038356111609708157251, 0.27103704347500323646, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0093429658193878890871, 1, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=None +knots=np.array([10, 100, 1000, ]) +output=np.array([1, 0.75141884282545001739, 0.47347381451739223301, 0.21613090194838843749, 0.049696178730542467372, 0.0013661273532290147976, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.24594066521407775827, 0.51146600459087232515, 0.73649217207800155016, 0.8374180350990879651, 0.77783093616193677011, 0.63185158416405007298, 0.45327074014730833751, 0.26317071169481792703, 0.10223303781294215686, 0.015729413486628138208, 5.1913250044765826493e-05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0026391300640233733565, 0.015039867450995366219, 0.047247102051768179176, 0.1123025082166889399, 0.21868817428784292911, 0.36168436874353226962, 0.52963938325215309533, 0.69654238826126158024, 0.81185888378284087885, 0.81901416673831617388, 0.71604356256126133751, 0.5618949499117826818, 0.38144450577487010179, 0.20035909960120826256, 0.06317094299551503922, 0.0053567803596460189172, 7.8294021104867289565e-10, 0, 0, 0, 1.3617399508643758347e-06, 2.0307441416267721758e-05, 0.00012974796415461092966, 0.00058265627417901637731, 0.0021107453507099383297, 0.0064420295146436082692, 0.01698600253976614155, 0.039859183304507203593, 0.084333549165298365979, 0.1600060050847842974, 0.26809274258076365438, 0.39566435336691235802, 0.51703688602850017553, 0.58200587206136744634, 0.52329606670761874554, 0.32126381870611603331, 0.10151738768556310688, 0.0078939921772932797328, 0, 0, 1.5649080494945798507e-10, 5.9986253804949622248e-09, 7.5940397022685528773e-08, 6.2142631098330448954e-07, 4.0139943226430085122e-06, 2.1989865743143280786e-05, 0.00010363219420155694861, 0.00042588199885955281988, 0.0015624557228769457226, 0.0051797373818038370402, 0.015437236122329209276, 0.040650688803865277221, 0.093964606272201794956, 0.18957613958735397564, 0.32176934741298385267, 0.41523761089925581569, 0.31715186300322989466, 0.072004316292680670131, 0, 0, 7.1504090682135632783e-15, 6.9828213556773098054e-13, 1.7290156975971226543e-11, 2.531906923450678459e-10, 2.8519588261786051741e-09, 2.7712025453436415246e-08, 2.4184791568371559048e-07, 1.8337667890099757592e-06, 1.2054075181315261422e-05, 7.0420380839424076883e-05, 0.00037180990877366712185, 0.0017643270358445378374, 0.0073398980933030329166, 0.026537861233464601213, 0.082516974679995302999, 0.20957251000715282352, 0.36763462897045218192, 0.25222621956325630421, 0, 0, 0, 0, 0, 0, 0, 5.430767431219823664e-15, 1.8655102027007631066e-11, 9.7376457669355941836e-10, 1.9440860511832082848e-08, 2.5692762827202482626e-07, 2.7355768273926624709e-06, 2.5679592827130744701e-05, 0.00021368415859150435886, 0.0015066158869563137275, 0.0090029382862195743431, 0.045606751586747915073, 0.18361012124256628764, 0.40566571262016642985, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.2887678100169456754e-09, 4.196725335132502196e-07, 1.441162964935832764e-05, 0.00024372991766721753461, 0.0029625284410813028553, 0.030085998315248142776, 0.25286679352721525005, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0093429658193878890871, 1, ]).reshape((20, 9, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=12 +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.13756522087537645382, 0.03408911379396852015, 0.0012620658543943507734, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.63650820114425754603, 0.56442389527296787932, 0.36731014666049194295, 0.15313548110822144954, 0.027890905208072903215, 0.00025587978478329849409, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.21582542819545830204, 0.37161327360106727324, 0.54958413949399687048, 0.64871936385648787393, 0.56949455728677522703, 0.3353237146654387546, 0.11624293381549648252, 0.013034128145880629485, 2.2307127685738320293e-06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.010030255096273907323, 0.029534067226298671427, 0.080270381333806692381, 0.19129075916133608803, 0.37605173703394079165, 0.57813180094222393901, 0.65912921049582962052, 0.52910502202296083585, 0.27213902033160508598, 0.075690939564343556745, 0.0042624228385304534922, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7.0831944077479075004e-05, 0.00033917363922361448356, 0.0015696484900234396707, 0.006826920796842389158, 0.026357789549328776435, 0.084918297819850163677, 0.21706326994359459448, 0.42522472470932526356, 0.61970296224817356112, 0.65157393079529135616, 0.46867117785961504017, 0.21110309109651023696, 0.045544745506395555024, 0.00095384491778118137267, 0, 0, 0, 0, 0, 0, 6.2744556242273010119e-08, 4.764664739647606222e-07, 3.6181672866699010542e-06, 2.7475075557388156146e-05, 0.00020499609216608624608, 0.0013694324583970120431, 0.0075463637977772560911, 0.032410006481736260142, 0.10630697223991346367, 0.26202672571617779962, 0.48196986016032394851, 0.64730135891295237371, 0.6200897527822700761, 0.39505484728729772792, 0.15152949559297854143, 0.022327498493473717928, 5.4255821339140527268e-05, 0, 0, 0, 0, 0, 0, 1.5550084505986725427e-12, 1.4829716211306275165e-08, 8.7432930709587782537e-07, 1.8221879880749471527e-05, 0.00022607643762169348975, 0.0018471467411283852555, 0.010678853506751016453, 0.044774794636566098149, 0.13922623229659780719, 0.32186074315609991547, 0.55535177436803673245, 0.70594649934249964485, 0.65842055649705455433, 0.44019721934864292079, 0.20692042038665983683, 0.050925719374514837046, 0.0018364038370179928007, 0, 0, 0, 0, 0, 0, 6.7421415818675005971e-11, 4.2202475147942958715e-08, 1.6677264111419149931e-06, 2.9548372537568077557e-05, 0.0003214228907650466577, 0.0023601436034748866921, 0.012366085974335782813, 0.047309807190604125093, 0.13367877749039860924, 0.27692812785680914756, 0.41099272250632723491, 0.40841144311061738925, 0.22284961609469711163, 0.025059128845635693372, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.0448984495923750749e-09, 3.2161419941923913368e-07, 9.1740900392921949651e-06, 0.00013858698681402402734, 0.0013233320235020520645, 0.0087002635234140028586, 0.040418548886275447451, 0.13266384308046400009, 0.2919610966000151242, 0.36977070091947494834, 0.13378226109816304668, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4.2555387649176344133e-13, 8.5594084815015888324e-08, 6.3942127780347038856e-06, 0.00014495964162350503772, 0.001897132263692037548, 0.015703476623777332805, 0.085263653984348167225, 0.27486427411742569982, 0.34006034727733425171, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4.4090854418790210764e-09, 8.1360026955471610933e-06, 0.00038848261944930331932, 0.0074310477767932352905, 0.07805738431434718072, 0.38159617170452009294, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.2338141566056994185e-05, 0.0035323051795402063933, 0.11766568723732878654, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([]) +output=np.array([0.9983344440741356296, 0.99750249875031249402, 0.99625562078283180778, 0.99438764201972595913, 0.99159092854883290613, 0.98740766028786153274, 0.98115924126864673127, 0.97184596123454425332, 0.95800877113085403103, 0.93754892830310510021, 0.90751599227918267054, 0.86391429083558635149, 0.801669064575886825, 0.71507663977921398502, 0.59936827269939108032, 0.45433823528182060159, 0.29067165046987419874, 0.13661155030676189193, 0.033621821670569602969, 0.0012124176758172098417, 0.0016644455553086624083, 0.002495003748750156472, 0.0037387626499230611904, 0.0055997301828166279672, 0.0083806908754831561242, 0.012528591196985617434, 0.018697687754151010031, 0.027833351892417868001, 0.041273795716988054272, 0.060850651795732749183, 0.088929278684076601413, 0.12824165844093327049, 0.18119239198615591513, 0.2480374111869024234, 0.32305865186741777872, 0.38825858275226748928, 0.40740939128236214328, 0.33403355026188807919, 0.1632256493056772062, 0.017159494075893101661, 1.1100003703292180217e-06, 2.4962518746875000594e-06, 5.6123532398144536609e-06, 1.2613583192428893271e-05, 2.8332643039885458129e-05, 6.3586947395334136954e-05, 0.00014252672253270057788, 0.00031885525421459126778, 0.00071127791904317637373, 0.0015797796625579053637, 0.0034857420363066235133, 0.0076146085944587566657, 0.016381164929213501424, 0.034414525059745272595, 0.069651262704549549154, 0.13271586265443335861, 0.22841224706537738287, 0.32670272008482859061, 0.31696810306481593145, 0.097144158424494309045, 3.7012349794238681896e-10, 1.2487503125000001559e-09, 4.2124242480468747114e-09, 1.4206263137512205132e-08, 4.7892153138227467571e-08, 1.6136291046154529314e-07, 5.4321868305356652586e-07, 1.8263821320052253243e-06, 6.1287830369107454558e-06, 2.0506795807293100125e-05, 6.8314944883560930534e-05, 0.00022606641535874693596, 0.00074049070575379688161, 0.0023874614910316710632, 0.0075083864312185822493, 0.022682692646808663012, 0.064029150684570476648, 0.15976638757864897178, 0.30776038811264622153, 0.27497860584540806395, 6.1707818930041155992e-14, 3.1234375000000000385e-13, 1.5808447265625000092e-12, 8.0000230407714837838e-12, 4.0477309670448300476e-11, 2.0474318975195293786e-10, 1.0351972331039468262e-09, 5.2306989582536832363e-09, 2.6404574434177521861e-08, 1.3309725534797475592e-07, 6.6943159388078163953e-07, 3.3557879908853077946e-06, 1.6736492419104248054e-05, 8.2813468459374991711e-05, 0.00040470096744437702128, 0.0019383686901439161829, 0.0089744140037595811904, 0.039065023078631577746, 0.14941007561236896439, 0.3891805482645412928, 4.1152263374485595055e-18, 3.1249999999999996265e-17, 2.3730468749999997491e-16, 1.802032470703124905e-15, 1.3684184074401855573e-14, 1.0391427281498912374e-13, 7.8909900918882334723e-13, 5.9922206010276265389e-12, 4.550342518905353542e-11, 3.4554163502937537769e-10, 2.6239567910043193503e-09, 1.9925671881689045749e-08, 1.5131057085157624606e-07, 1.1490146474041569126e-06, 8.7253299787253137094e-06, 6.625797452594535961e-05, 0.00050314649405639756945, 0.0038207686892407699206, 0.02901396223392209775, 0.22032477571384589954, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([100, ]) +output=np.array([0.95099004990000002291, 0.92721650236562502823, 0.89244986942880866199, 0.84226263493375552738, 0.77123895238719930578, 0.67376233787836592448, 0.54625869959414907751, 0.39186905799172611076, 0.22752066204261220395, 0.088384183391962217735, 0.013598650651405662371, 4.4880894773220947292e-05, 0, 0, 0, 0, 0, 0, 0, 0, 0.048976959490485305615, 0.072709651432435309926, 0.10738526002140330595, 0.15737069698548675212, 0.22795032016720712109, 0.32446067835465053353, 0.44989711207706667428, 0.59997610680291524332, 0.75567735422921566979, 0.87844628783911327119, 0.92474207754597603781, 0.89365801028359981295, 0.82931282542333117913, 0.73973445494401424138, 0.62003614417178387619, 0.47000507098119359561, 0.30069481083090426887, 0.14132229342078814205, 0.034781194831623722663, 0.0012542251818798723622, 3.2979557543950620822e-05, 7.3809001036874996929e-05, 0.00016474549918236330078, 0.00036624856893145208737, 0.00080932434818232947688, 0.0017723123294799305975, 0.003828742087843573557, 0.008104291378262778317, 0.016639190251049165714, 0.032657698828719619599, 0.060108147688838667322, 0.10184799113601375464, 0.15884341152280503917, 0.23108234071251923525, 0.31281804868450863166, 0.38543973833058026157, 0.4110892044013776947, 0.34067876601502938838, 0.16765476842547211156, 0.017707951623962527032, 1.1050122962962964101e-08, 3.7191558750000007188e-08, 1.250033797265625178e-07, 4.1927333935913091575e-07, 1.401894586697731242e-06, 4.665382495865281394e-06, 1.5415847866808392633e-05, 5.0391939592239989756e-05, 0.00016203956276710770662, 0.00050812727751784608765, 0.0015332452896675867124, 0.004365181610267205789, 0.011468673667365519159, 0.027632876244132381638, 0.061266201119033726619, 0.12400124625180757032, 0.22211304163999795458, 0.32622078746654581405, 0.32211683874203467237, 0.099883337969340235674, 1.8476543209876543964e-12, 9.3431250000000011463e-12, 4.7218886718750000078e-11, 2.3843292297363282786e-10, 1.2024140499687195818e-09, 6.0518902752095459008e-09, 3.0369400855124124217e-08, 1.5170773682471650721e-07, 7.5254925311084902029e-07, 3.6922964379636862066e-06, 1.7800105408249686863e-05, 8.3338305189489776193e-05, 0.00037055336224994447902, 0.0015169299478213021069, 0.0056546686833628886926, 0.019188949419050076173, 0.058577982030935032975, 0.15402658068596292162, 0.30726533809094308536, 0.28101637370320353693, 1.2345679012345678054e-16, 9.3749999999999994959e-16, 7.1191406249999982613e-15, 5.4060974121093752673e-14, 4.1052552223205572084e-13, 3.1174281844496722735e-12, 2.3672970275664694964e-11, 1.7976661803082883009e-10, 1.3651027556716062823e-09, 1.0366249050881264123e-08, 7.8718703730129575545e-08, 5.9777015645067147174e-07, 4.5359107007994105463e-06, 3.3361176067584402466e-05, 0.00022366759792994563949, 0.0013435210788023243395, 0.0072639461407535297829, 0.035100831436999477275, 0.14396679069931464512, 0.39291034738734598175, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.1354749159583518215e-10, 3.6975445151343504115e-08, 1.2697433810604620809e-06, 2.1473938565867883887e-05, 0.00026101495603127997146, 0.0026507409746741200131, 0.024215069210611606804, 0.20722776413426768904, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([1000, ]) +output=np.array([0.9950099900049993451, 0.99252246627530493761, 0.98880051122183698631, 0.98323852246469989336, 0.9749424948799998436, 0.96260353805275378214, 0.94432964343891578896, 0.91744015090894337483, 0.87825768212583654737, 0.82200480749416604542, 0.74306451043607213425, 0.63613393199503898146, 0.4991479566148370739, 0.33884847274276985729, 0.17798493325279582389, 0.056116623078022197235, 0.0047585869404442801556, 6.9550902096181903072e-10, 0, 0, 0.0049866811037051986949, 0.0074700487125113432946, 0.011182664341492391802, 0.016723679332538900905, 0.024972650503249212151, 0.037206183352661716113, 0.055244396744596628579, 0.081608715488401706306, 0.11962663350752600344, 0.17331618121340841565, 0.2466772227646655824, 0.34167053826082144363, 0.45378166194157465441, 0.56434225055466613608, 0.6320750091698927875, 0.59733241830569760999, 0.42886959529414492298, 0.2049173244168793484, 0.050432732505854400984, 0.0018186265137258147626, 3.3277811103950621097e-06, 7.4812668695624991679e-06, 1.6811804138396487754e-05, 3.7755607955489316522e-05, 8.4711061600122608767e-05, 0.00018979511914756760698, 0.00042433325892820140772, 0.00094567009442594711366, 0.002097376821719070146, 0.0046178870868948916628, 0.010055306643782090104, 0.021527218530989256778, 0.04489775700844654549, 0.089884991503020608694, 0.16855047321618027434, 0.28372166497555245668, 0.39667928927647067017, 0.39859166318439254173, 0.21962210770558857065, 0.024829927856976751616, 1.1100002962962965174e-09, 3.7443772500000006212e-09, 1.2627790523437500951e-08, 4.2570810898681638324e-08, 1.4343375976686856963e-07, 4.8286151921739802212e-07, 1.6234543349501860428e-06, 5.4478341089133651746e-06, 1.8228467705229433379e-05, 6.0725950389411787269e-05, 0.000200959732568890164, 0.00065830362619350942834, 0.0021228688895969845957, 0.0066792918381076149537, 0.020201657448734186562, 0.057212961493873837338, 0.14427872595983071147, 0.29075824853504678158, 0.36564110074442957021, 0.13330127370825312072, 1.8509876543209877828e-13, 9.3684375000000001865e-13, 4.7411103515625013439e-12, 2.3989256927490236273e-11, 1.2134982390689849712e-10, 6.1360608361896876588e-10, 3.1008571052567070342e-09, 1.5656143551154886378e-08, 7.8940702751398238619e-08, 3.9721851623374797589e-07, 1.9925510408963188817e-06, 9.9478099413657914188e-06, 4.930161383220328208e-05, 0.00024154631749370003959, 0.0011617509224607792256, 0.0054175582232760775836, 0.023904363046940359239, 0.094270457100450164023, 0.27882003179675446392, 0.34581727191398570209, 1.2345679012345680828e-17, 9.3750000000000019611e-17, 7.1191406250000002335e-16, 5.4060974121093743207e-15, 4.1052552223205574609e-14, 3.1174281844496730813e-13, 2.3672970275664701427e-12, 1.7976661803082880424e-11, 1.3651027556716061272e-10, 1.0366249050881260814e-09, 7.8718703730129572237e-09, 5.9777015645067147174e-08, 4.5393171255472860584e-07, 3.4470439422124707377e-06, 2.6175989936175949598e-05, 0.00019877392357783613304, 0.0015094394821691928168, 0.011462306067722308894, 0.084705097520176186876, 0.41086218643981919918, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00077892972719669731786, 0.083370713567239546071, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=TRUE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([10, 100, 1000, ]) +output=np.array([0.59048999999999984833, 0.44370531250000000423, 0.27958155273437496069, 0.12762313629150390248, 0.029345096578598028197, 0.00080668454080820085113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.40055561099999992258, 0.53723465540624992798, 0.68096479632714856933, 0.79404388738027953387, 0.82432650645400162848, 0.74772850370839760714, 0.60695411066016569102, 0.43541006443525137604, 0.25280073560290239332, 0.098204648213291390046, 0.015109611834895182725, 4.9867660859134372328e-05, 0, 0, 0, 0, 0, 0, 0, 0, 0.0089449327889999999397, 0.01902900664771874778, 0.039353322248692389207, 0.078015642723590794549, 0.14535820079903546964, 0.24864829948443537, 0.38546024005089984943, 0.54588573189455047441, 0.70480915137930777448, 0.81344804238272472308, 0.81717844525199323513, 0.71389962178539645432, 0.56021095018500233209, 0.38030131620961826755, 0.19975862317934431345, 0.062981619616186521049, 0.0053407260835513798575, 7.8059373845321992395e-10, 0, 0, 9.4545814444444459148e-06, 3.1017290343749996553e-05, 0.00010028811495410157556, 0.00031713361145809936415, 0.00096922483761113851879, 0.0028119072707210087531, 0.0075647083349296134064, 0.01861553313384527869, 0.042046394339120052308, 0.087124325583113268467, 0.16371060089498334911, 0.27411331174625735985, 0.40781324509205862938, 0.54286075051770132927, 0.63352683070691229172, 0.61289306201898841042, 0.44453962951650222157, 0.21269241367644950436, 0.052346279846925344859, 0.0018876298723944570646, 1.6294444444444447802e-09, 8.1548437499999982349e-09, 4.0568422851562507446e-08, 1.9994451278686527012e-07, 9.7096128099918361425e-07, 4.602189952521174856e-06, 2.0919648984453888767e-05, 8.8510989072612499115e-05, 0.0003426071500521665281, 0.0012159913347531664096, 0.0039613824662355322237, 0.011728070771626651625, 0.030981021316488138728, 0.072628957837475555115, 0.15091202659488145432, 0.27128094978421118944, 0.39491276471324787689, 0.40566968711467132902, 0.22597501897826155481, 0.025700635234072819607, 1.1111111111111111028e-13, 8.4374999999999991361e-13, 6.4072265625000016033e-12, 4.8654876708984379097e-11, 3.694729700088501736e-10, 2.8056853660047051398e-09, 2.1305018189503776537e-08, 1.5953977978988917004e-07, 1.1111370996233737328e-06, 6.9846696024166045466e-06, 3.9856249948076781855e-05, 0.00020802815256623063945, 0.00098445759075916142167, 0.0041227618062229087065, 0.015186511992247679614, 0.04905127538388008579, 0.1347633037922978394, 0.28642046903795781443, 0.37096041450757122337, 0.1373866644432741313, 0, 0, 0, 0, 0, 0, 2.1835286481805527197e-15, 7.5005881261891668233e-12, 3.9151793493690686266e-10, 7.8165151445884371071e-09, 1.0330194469679949402e-07, 1.0998832941312460716e-06, 1.0325449816590390154e-05, 8.6094485881001237893e-05, 0.00061191613127527461416, 0.0037238993946882535668, 0.01960252770274439893, 0.08667615291637777164, 0.27442290749348607903, 0.35255941616703945218, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.6587525069769108936e-10, 1.1914310104321792976e-07, 4.09139533897260065e-06, 6.9193802045574309841e-05, 0.00084104819165634655664, 0.0085412764739499439509, 0.075516449446559150149, 0.39909494071597967357, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00077892972719669731786, 0.083370713567239546071, ]).reshape((20, 9, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=12 +intercept=FALSE +Boundary.knots=None +knots=None +output=np.array([0, 0.66169375447141842717, 0.42704385876993139481, 0.10949465799552411671, 0.0045536628406788173459, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.16320829536765205092, 0.50699791406824767925, 0.63821768315482607647, 0.43263056231744068114, 0.15013545271065373288, 0.016177354520514077713, 1.5876171140511428811e-06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0058674236731072158813, 0.063738396787633516682, 0.24043272488013067711, 0.50054000504763473955, 0.64199088129854386953, 0.51113227122624471654, 0.23070045750246975791, 0.045936684143309251815, 0.00066416458897031876996, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.5532476724270158346e-05, 0.0011936972661650952464, 0.011779052740953399256, 0.061287867695344819263, 0.20002288232936923928, 0.43156920172035251326, 0.62168249332663905182, 0.58254996098081013312, 0.32664310035477628347, 0.092349295039142950681, 0.0054390297948912662632, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.1496907292528123154e-08, 3.0758698527859495562e-06, 7.5879789673663857776e-05, 0.00098724833216487398006, 0.0078266015648352053879, 0.040722255850196634186, 0.14383543945950985621, 0.34844598770889789741, 0.57762867947116447453, 0.6345732251821071257, 0.43704729558185051452, 0.16650826117204259313, 0.023068804299786735412, 3.4807107343935620814e-05, 0, 0, 0, 0, 0, 0, 0, 0, 1.4388921206346279741e-09, 6.5376673591293467664e-07, 2.4182089760364024493e-05, 0.00039880176232783617072, 0.0037728522997899590664, 0.022917112728778440273, 0.09334968530661211239, 0.26084062164632215719, 0.49935247038577756928, 0.64262810933455249973, 0.53564397016856835076, 0.2604583835482605636, 0.059387695355091404958, 0.0015752311746957685552, 0, 0, 0, 0, 0, 0, 0, 0, 6.8376488468020759222e-12, 1.1492036416820246223e-07, 7.1697944771843335622e-06, 0.00015024167017123804383, 0.0017124892221411901899, 0.012184251164569406822, 0.05741986723560143363, 0.1846190190189749003, 0.40690335279758527154, 0.61033896958284106216, 0.60106063282500987732, 0.35935886624758728303, 0.11099693368003141214, 0.0086311215629592420023, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.2768033036904166236e-08, 1.8810563357318595251e-06, 5.2605966584901652059e-05, 0.00074031169779739149084, 0.0062001835283552559838, 0.03359211253079281978, 0.12126275319647328299, 0.28972724543117178708, 0.43422014732068858756, 0.34126033432252839139, 0.077899048558433395262, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0012735173756063062e-09, 1.0253040817926208576e-06, 4.44269427274169616e-05, 0.0007905173401505205099, 0.0078092535818893079463, 0.047648780279836128182, 0.17901740350372433164, 0.37155904838956399505, 0.26547319923364387506, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.3473917264272251468e-12, 1.2428631162803442157e-06, 9.5832983192035734268e-05, 0.0021733294132454694138, 0.025265394711489429919, 0.1581848201187764924, 0.40157681487049512459, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.3166956453278957354e-06, 0.00056295704181467877848, 0.017992654275869164604, 0.22701602442886983924, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6.2092132305915514147e-06, 0.019403791345598601914, 1, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([]) +output=np.array([0, 0.0011272234177996938269, 0.0028142442804627715303, 0.0053362072774053633667, 0.0090999196124958610377, 0.014702372431044495246, 0.023009568696928141274, 0.035255048800207078319, 0.053144756365466998271, 0.078922539871719557536, 0.11527760116980134697, 0.16482753559964863355, 0.22865514515079901625, 0.30306893078627178406, 0.37385911082806172478, 0.40954833229285447782, 0.36355794566479110452, 0.2119513600790149388, 0.041217298467029310494, 0, 0, 5.0882687398560041373e-07, 3.1769391294621280289e-06, 1.1451280924188917779e-05, 3.3428733100138665235e-05, 8.7761935886847988286e-05, 0.00021681208262686383053, 0.00051561316170019592855, 0.0011946804469067555735, 0.0027131220507094727483, 0.0060506596144855023106, 0.013230141811374926397, 0.028210083582453096551, 0.058035333309565624582, 0.11300958063559926603, 0.20116335451605230067, 0.30568795867586873172, 0.33877798094471850421, 0.16475763686175207146, 0, 0, 1.1484182443411814437e-10, 1.7931887260774516498e-09, 1.2286988490864389756e-08, 6.1400553206305291637e-08, 2.6193586874264870438e-07, 1.0214767558696939837e-06, 3.7704802796487805225e-06, 1.3428054504627923681e-05, 4.6634530984498030184e-05, 0.00015879269432593164958, 0.00053096908751411363639, 0.00174019442073816092, 0.0055566565395111476577, 0.017080184681265514479, 0.049404053208565550104, 0.12851476524402274948, 0.27074730808567093465, 0.32929231067852438031, 0, 0, 1.2959854631941128047e-14, 5.06072933143619642e-13, 6.5918427455453850986e-12, 5.6389033989814727996e-11, 3.9088927700060016774e-10, 2.406265255469648607e-09, 1.378603437152614992e-08, 7.5464802427343835863e-08, 4.0078909822273000137e-07, 2.0836670196190539855e-06, 1.0654767572225721294e-05, 5.3673655611779830157e-05, 0.00026601408260545672708, 0.0012907432586925205419, 0.0060666130749972404027, 0.027014549341864656923, 0.10818900424286860551, 0.32906949849914446382, 0, 0, 5.8500579526198340832e-19, 5.7129472193553077444e-17, 1.4145822896898457119e-15, 2.0714622186680568112e-14, 2.3333104795078233906e-13, 2.2673496764008742317e-12, 2.0162390952550372537e-11, 1.6964293385718098169e-10, 1.3777936465799164788e-09, 1.0936695210263550545e-08, 8.5522170452256458058e-08, 6.6219297623306537514e-07, 5.0939619277349284707e-06, 3.9016396858695978102e-05, 0.00029798198173219142288, 0.00227144600780565184, 0.017292671490362138825, 0.13153873483331313121, 1, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([100, ]) +output=np.array([0, 0.024987397851780435848, 0.061486796626462968118, 0.1140799960900419352, 0.1882939537142028219, 0.28966625638367565765, 0.42117968175620157378, 0.57798465087862005429, 0.73943782746930653005, 0.86397935690336380432, 0.90462871246453147034, 0.85976637084822715718, 0.77601114642224255924, 0.66267521310641597232, 0.51785842958629058064, 0.34911766989097126057, 0.18104199448456753663, 0.055522321426452851678, 0.0043174157141209739547, 0, 0, 1.1333836374491041766e-05, 7.0253868335539153452e-05, 0.00025049169236306427153, 0.00071939598049462782393, 0.0018428967293926601032, 0.0043879998552115674279, 0.0098727402942039785283, 0.021048289930652556295, 0.042207103219050953746, 0.078361329513138483494, 0.1323267251748408424, 0.20305646979998087653, 0.28625091024051202426, 0.36712456913477936604, 0.41237454577086030127, 0.37209382828918063923, 0.21926721332006066101, 0.042943027456719351509, 0, 0, 2.5642163564224008165e-09, 3.9893896948733327568e-08, 2.7186958324120860093e-07, 1.3475047468249140318e-06, 5.6780166980285093331e-06, 2.1734507210374597486e-05, 7.8000238621073664019e-05, 0.00026616938183067457386, 0.00086607259863206911138, 0.0026688434677071591963, 0.0076602480569788727188, 0.020032890189762748295, 0.047362176442216685768, 0.10112516340575794516, 0.19128545657973258787, 0.30258229747242648688, 0.34436724521558481626, 0.17045464690987927048, 0, 0, 2.8979008849349871451e-13, 1.1299684644739179399e-11, 1.4686295227238142049e-10, 1.2521970298985838129e-09, 8.6372943219355255736e-09, 5.2772400925513216102e-08, 2.9891245041530529781e-07, 1.607880484564848822e-06, 8.3111564072833673416e-06, 4.1402961295506068027e-05, 0.00019754788193526286806, 0.00088468396831814228969, 0.0036015013400145573161, 0.013149579882492583999, 0.042768561910798960635, 0.12037399719492403172, 0.26730426029673903798, 0.33672081019045274619, 0, 0, 1.309371682920953332e-17, 1.2786832841024935257e-15, 3.1661464010829005262e-14, 4.6363882090260461786e-13, 5.2224622287067364928e-12, 5.0748274386406234902e-11, 4.5127867086219768747e-10, 3.7969821085404869e-09, 3.0838053235562167103e-08, 2.44787301750460405e-07, 1.9141743408195724709e-06, 1.4809071760067401229e-05, 0.00011002044182894339316, 0.0007361307065949982114, 0.0043501410333869746858, 0.022648326644076191561, 0.10074752233050462968, 0.32871166293410319925, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5.4793570769921117731e-10, 1.7842901170031562027e-07, 6.1272840845677704696e-06, 0.00010362481425005589904, 0.0012595559148250148798, 0.012791437410658173385, 0.11685243679472454015, 1, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([1000, ]) +output=np.array([0, 0.0024988701975066367374, 0.0062335737743966241481, 0.011805108206123089004, 0.020094017057672219906, 0.032374436158623724757, 0.050454096263104174225, 0.076816980711751164934, 0.11469423978741608017, 0.16787638509201657788, 0.23985925947403505254, 0.33155764168655321722, 0.4364690436594241274, 0.53267348082579712987, 0.57514542430970139186, 0.50463302930351572329, 0.30623588293439429897, 0.096587849561305616497, 0.0075106712808647091081, 0, 0, 1.1282962103271197581e-06, 7.0417854820895302466e-06, 2.536640667453833115e-05, 7.3981096505374880712e-05, 0.00019395448667024030114, 0.00047814948330325205252, 0.0011335173229715391711, 0.0026138368581788955919, 0.0058931764589364287604, 0.012998501527337540801, 0.027945386445582046098, 0.058044007669012950834, 0.1145680954987259581, 0.2086069927114643785, 0.33148565972609811414, 0.41061823564260202524, 0.3066625410662744966, 0.068889778730265194273, 0, 0, 2.5469057156714312774e-10, 3.976025713192789869e-09, 2.7235422387831816846e-08, 1.3603757883811768205e-07, 5.7993308882550318022e-07, 2.2591989366454093128e-06, 8.3259563410340815473e-06, 2.9580849000601624262e-05, 0.00010235971125482330811, 0.00034661758311907198181, 0.001149214388416119545, 0.0037170166582407206807, 0.011623043605661884797, 0.034525979049628140183, 0.094171296281739258482, 0.21954225794050497012, 0.36514412761590397949, 0.24346326935859208263, 0, 0, 2.8744101198050118059e-14, 1.1223436953991581798e-12, 1.4617253735361878953e-11, 1.2501806315302350017e-10, 8.6638386346496238246e-10, 5.3311050540562872207e-09, 3.0523721489433262118e-08, 1.6692682142232341016e-07, 8.8525020719146049419e-07, 4.5921420319874677743e-06, 2.3401813204582281116e-05, 0.0001172621098580812533, 0.00057627166059595505247, 0.0027575294458836020588, 0.012651024092369157759, 0.053782977897194939043, 0.19324936944781076487, 0.3997562713358867037, 0, 0, 1.2975755416333770318e-18, 1.2671636148763449243e-16, 3.1376225596317031531e-15, 4.5946189458816680778e-14, 5.1754130194391066624e-13, 5.0291082725267428713e-12, 4.4721309725082660758e-11, 3.762775062517599803e-10, 3.0560232936142684245e-09, 2.4258201074369941878e-08, 1.8969295269383146249e-07, 1.4687810219326831175e-06, 1.1298692185571222767e-05, 8.6540548310009559815e-05, 0.00066094068550206401882, 0.0050381941644688631871, 0.038356111609708157251, 0.27103704347500323646, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0093429658193878890871, 1, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=None +knots=np.array([10, 100, 1000, ]) +output=np.array([0, 0.24594066521407775827, 0.51146600459087232515, 0.73649217207800155016, 0.8374180350990879651, 0.77783093616193677011, 0.63185158416405007298, 0.45327074014730833751, 0.26317071169481792703, 0.10223303781294215686, 0.015729413486628138208, 5.1913250044765826493e-05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0026391300640233733565, 0.015039867450995366219, 0.047247102051768179176, 0.1123025082166889399, 0.21868817428784292911, 0.36168436874353226962, 0.52963938325215309533, 0.69654238826126158024, 0.81185888378284087885, 0.81901416673831617388, 0.71604356256126133751, 0.5618949499117826818, 0.38144450577487010179, 0.20035909960120826256, 0.06317094299551503922, 0.0053567803596460189172, 7.8294021104867289565e-10, 0, 0, 0, 1.3617399508643758347e-06, 2.0307441416267721758e-05, 0.00012974796415461092966, 0.00058265627417901637731, 0.0021107453507099383297, 0.0064420295146436082692, 0.01698600253976614155, 0.039859183304507203593, 0.084333549165298365979, 0.1600060050847842974, 0.26809274258076365438, 0.39566435336691235802, 0.51703688602850017553, 0.58200587206136744634, 0.52329606670761874554, 0.32126381870611603331, 0.10151738768556310688, 0.0078939921772932797328, 0, 0, 1.5649080494945798507e-10, 5.9986253804949622248e-09, 7.5940397022685528773e-08, 6.2142631098330448954e-07, 4.0139943226430085122e-06, 2.1989865743143280786e-05, 0.00010363219420155694861, 0.00042588199885955281988, 0.0015624557228769457226, 0.0051797373818038370402, 0.015437236122329209276, 0.040650688803865277221, 0.093964606272201794956, 0.18957613958735397564, 0.32176934741298385267, 0.41523761089925581569, 0.31715186300322989466, 0.072004316292680670131, 0, 0, 7.1504090682135632783e-15, 6.9828213556773098054e-13, 1.7290156975971226543e-11, 2.531906923450678459e-10, 2.8519588261786051741e-09, 2.7712025453436415246e-08, 2.4184791568371559048e-07, 1.8337667890099757592e-06, 1.2054075181315261422e-05, 7.0420380839424076883e-05, 0.00037180990877366712185, 0.0017643270358445378374, 0.0073398980933030329166, 0.026537861233464601213, 0.082516974679995302999, 0.20957251000715282352, 0.36763462897045218192, 0.25222621956325630421, 0, 0, 0, 0, 0, 0, 0, 5.430767431219823664e-15, 1.8655102027007631066e-11, 9.7376457669355941836e-10, 1.9440860511832082848e-08, 2.5692762827202482626e-07, 2.7355768273926624709e-06, 2.5679592827130744701e-05, 0.00021368415859150435886, 0.0015066158869563137275, 0.0090029382862195743431, 0.045606751586747915073, 0.18361012124256628764, 0.40566571262016642985, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.2887678100169456754e-09, 4.196725335132502196e-07, 1.441162964935832764e-05, 0.00024372991766721753461, 0.0029625284410813028553, 0.030085998315248142776, 0.25286679352721525005, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0093429658193878890871, 1, ]).reshape((20, 8, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=12 +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=None +output=np.array([0.59169275909036811445, 0.45594291761992611356, 0.23025182795481774489, 0.058881690084655928519, 0.00244877119161214735, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2905201731274964505, 0.4652923293619554701, 0.60774274744642686752, 0.58452788522997400911, 0.36691850516129698168, 0.12666647389296178949, 0.013648531489621140711, 1.3394428704094372146e-06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.021589057498422929704, 0.061252310080865124409, 0.15611979121414976124, 0.33262545668279458466, 0.54628842278228206819, 0.6385151816856337037, 0.49255505710881447579, 0.221198927694986891, 0.044044707273317475205, 0.00063680989274803034839, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00027107258187882916, 0.00127840807191650788, 0.0057589114783163615832, 0.023748086219301876854, 0.082775728340449605813, 0.22525005798130448564, 0.44911867244320990977, 0.62614581126197998984, 0.57974912164267822234, 0.32404333353141845375, 0.091606580575315788018, 0.0053952866770240375319, 0, 0, 0, 0, 0, 0, 0, 0, 4.9568448953450556364e-07, 3.7641040924026516272e-06, 2.8583665451682636297e-05, 0.00021688034438166792803, 0.0015679187576233750197, 0.0095441043435020560953, 0.04427882227566239115, 0.1488738995058955239, 0.35313880391702157091, 0.58025580099074469675, 0.63531593964593435775, 0.4370910386997177155, 0.16650826117204259313, 0.023068804299786735412, 3.4807107343935620814e-05, 0, 0, 0, 0, 0, 0, 0, 0, 1.4388921206346279741e-09, 6.5376673591293467664e-07, 2.4182089760364024493e-05, 0.00039880176232783617072, 0.0037728522997899590664, 0.022917112728778440273, 0.09334968530661211239, 0.26084062164632215719, 0.49935247038577756928, 0.64262810933455249973, 0.53564397016856835076, 0.2604583835482605636, 0.059387695355091404958, 0.0015752311746957685552, 0, 0, 0, 0, 0, 0, 0, 0, 6.8376488468020759222e-12, 1.1492036416820246223e-07, 7.1697944771843335622e-06, 0.00015024502361066615209, 0.0017129832691462772674, 0.012198067843520864206, 0.057614376649993519208, 0.18625055189529041155, 0.41578120601587292837, 0.64273379913532080465, 0.68051701302793721204, 0.48636048533160558538, 0.22961899064651025704, 0.056512123157649481187, 0.0020378520142550187594, 0, 0, 0, 0, 0, 0, 0, 0, 9.4145936087959968535e-09, 1.3870093306447404973e-06, 3.87897484409095467e-05, 0.00054627415024945797078, 0.0045890968808638254312, 0.025078293403640077724, 0.092478958938429417502, 0.23258667138901650828, 0.39413899790146145197, 0.42298881551441958049, 0.23945155313138169473, 0.027468762021704565962, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5.4046605238618360691e-10, 5.5343723764345201347e-07, 2.3980715961026268597e-05, 0.00042724725529509507927, 0.004257128234965919765, 0.026669687498425763417, 0.10780673176995581031, 0.27416234388481963702, 0.37835275864003403701, 0.14369344182750692918, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.2897006858339270209e-12, 4.7885683674533647596e-07, 3.6923035679543052192e-05, 0.00083835438251815758755, 0.0099780154986416052382, 0.068735165020702704286, 0.25981214905110344704, 0.35274625004443893594, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5.7834701086365511565e-07, 0.00014053832363986818919, 0.0044940505180239382829, 0.063888867507214189279, 0.37188043953033556033, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6.344155240374716805e-07, 0.0019825485126170991519, 0.10217325456175885279, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([]) +output=np.array([0.0016644455553086624083, 0.002495003748750156472, 0.0037387626499230611904, 0.0055997301828166279672, 0.0083806908754831561242, 0.012528591196985617434, 0.018697687754151010031, 0.027833351892417868001, 0.041273795716988054272, 0.060850651795732749183, 0.088929278684076601413, 0.12824165844093327049, 0.18119239198615591513, 0.2480374111869024234, 0.32305865186741777872, 0.38825858275226748928, 0.40740939128236214328, 0.33403355026188807919, 0.1632256493056772062, 0.017159494075893101661, 1.1100003703292180217e-06, 2.4962518746875000594e-06, 5.6123532398144536609e-06, 1.2613583192428893271e-05, 2.8332643039885458129e-05, 6.3586947395334136954e-05, 0.00014252672253270057788, 0.00031885525421459126778, 0.00071127791904317637373, 0.0015797796625579053637, 0.0034857420363066235133, 0.0076146085944587566657, 0.016381164929213501424, 0.034414525059745272595, 0.069651262704549549154, 0.13271586265443335861, 0.22841224706537738287, 0.32670272008482859061, 0.31696810306481593145, 0.097144158424494309045, 3.7012349794238681896e-10, 1.2487503125000001559e-09, 4.2124242480468747114e-09, 1.4206263137512205132e-08, 4.7892153138227467571e-08, 1.6136291046154529314e-07, 5.4321868305356652586e-07, 1.8263821320052253243e-06, 6.1287830369107454558e-06, 2.0506795807293100125e-05, 6.8314944883560930534e-05, 0.00022606641535874693596, 0.00074049070575379688161, 0.0023874614910316710632, 0.0075083864312185822493, 0.022682692646808663012, 0.064029150684570476648, 0.15976638757864897178, 0.30776038811264622153, 0.27497860584540806395, 6.1707818930041155992e-14, 3.1234375000000000385e-13, 1.5808447265625000092e-12, 8.0000230407714837838e-12, 4.0477309670448300476e-11, 2.0474318975195293786e-10, 1.0351972331039468262e-09, 5.2306989582536832363e-09, 2.6404574434177521861e-08, 1.3309725534797475592e-07, 6.6943159388078163953e-07, 3.3557879908853077946e-06, 1.6736492419104248054e-05, 8.2813468459374991711e-05, 0.00040470096744437702128, 0.0019383686901439161829, 0.0089744140037595811904, 0.039065023078631577746, 0.14941007561236896439, 0.3891805482645412928, 4.1152263374485595055e-18, 3.1249999999999996265e-17, 2.3730468749999997491e-16, 1.802032470703124905e-15, 1.3684184074401855573e-14, 1.0391427281498912374e-13, 7.8909900918882334723e-13, 5.9922206010276265389e-12, 4.550342518905353542e-11, 3.4554163502937537769e-10, 2.6239567910043193503e-09, 1.9925671881689045749e-08, 1.5131057085157624606e-07, 1.1490146474041569126e-06, 8.7253299787253137094e-06, 6.625797452594535961e-05, 0.00050314649405639756945, 0.0038207686892407699206, 0.02901396223392209775, 0.22032477571384589954, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([100, ]) +output=np.array([0.048976959490485305615, 0.072709651432435309926, 0.10738526002140330595, 0.15737069698548675212, 0.22795032016720712109, 0.32446067835465053353, 0.44989711207706667428, 0.59997610680291524332, 0.75567735422921566979, 0.87844628783911327119, 0.92474207754597603781, 0.89365801028359981295, 0.82931282542333117913, 0.73973445494401424138, 0.62003614417178387619, 0.47000507098119359561, 0.30069481083090426887, 0.14132229342078814205, 0.034781194831623722663, 0.0012542251818798723622, 3.2979557543950620822e-05, 7.3809001036874996929e-05, 0.00016474549918236330078, 0.00036624856893145208737, 0.00080932434818232947688, 0.0017723123294799305975, 0.003828742087843573557, 0.008104291378262778317, 0.016639190251049165714, 0.032657698828719619599, 0.060108147688838667322, 0.10184799113601375464, 0.15884341152280503917, 0.23108234071251923525, 0.31281804868450863166, 0.38543973833058026157, 0.4110892044013776947, 0.34067876601502938838, 0.16765476842547211156, 0.017707951623962527032, 1.1050122962962964101e-08, 3.7191558750000007188e-08, 1.250033797265625178e-07, 4.1927333935913091575e-07, 1.401894586697731242e-06, 4.665382495865281394e-06, 1.5415847866808392633e-05, 5.0391939592239989756e-05, 0.00016203956276710770662, 0.00050812727751784608765, 0.0015332452896675867124, 0.004365181610267205789, 0.011468673667365519159, 0.027632876244132381638, 0.061266201119033726619, 0.12400124625180757032, 0.22211304163999795458, 0.32622078746654581405, 0.32211683874203467237, 0.099883337969340235674, 1.8476543209876543964e-12, 9.3431250000000011463e-12, 4.7218886718750000078e-11, 2.3843292297363282786e-10, 1.2024140499687195818e-09, 6.0518902752095459008e-09, 3.0369400855124124217e-08, 1.5170773682471650721e-07, 7.5254925311084902029e-07, 3.6922964379636862066e-06, 1.7800105408249686863e-05, 8.3338305189489776193e-05, 0.00037055336224994447902, 0.0015169299478213021069, 0.0056546686833628886926, 0.019188949419050076173, 0.058577982030935032975, 0.15402658068596292162, 0.30726533809094308536, 0.28101637370320353693, 1.2345679012345678054e-16, 9.3749999999999994959e-16, 7.1191406249999982613e-15, 5.4060974121093752673e-14, 4.1052552223205572084e-13, 3.1174281844496722735e-12, 2.3672970275664694964e-11, 1.7976661803082883009e-10, 1.3651027556716062823e-09, 1.0366249050881264123e-08, 7.8718703730129575545e-08, 5.9777015645067147174e-07, 4.5359107007994105463e-06, 3.3361176067584402466e-05, 0.00022366759792994563949, 0.0013435210788023243395, 0.0072639461407535297829, 0.035100831436999477275, 0.14396679069931464512, 0.39291034738734598175, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.1354749159583518215e-10, 3.6975445151343504115e-08, 1.2697433810604620809e-06, 2.1473938565867883887e-05, 0.00026101495603127997146, 0.0026507409746741200131, 0.024215069210611606804, 0.20722776413426768904, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([1000, ]) +output=np.array([0.0049866811037051986949, 0.0074700487125113432946, 0.011182664341492391802, 0.016723679332538900905, 0.024972650503249212151, 0.037206183352661716113, 0.055244396744596628579, 0.081608715488401706306, 0.11962663350752600344, 0.17331618121340841565, 0.2466772227646655824, 0.34167053826082144363, 0.45378166194157465441, 0.56434225055466613608, 0.6320750091698927875, 0.59733241830569760999, 0.42886959529414492298, 0.2049173244168793484, 0.050432732505854400984, 0.0018186265137258147626, 3.3277811103950621097e-06, 7.4812668695624991679e-06, 1.6811804138396487754e-05, 3.7755607955489316522e-05, 8.4711061600122608767e-05, 0.00018979511914756760698, 0.00042433325892820140772, 0.00094567009442594711366, 0.002097376821719070146, 0.0046178870868948916628, 0.010055306643782090104, 0.021527218530989256778, 0.04489775700844654549, 0.089884991503020608694, 0.16855047321618027434, 0.28372166497555245668, 0.39667928927647067017, 0.39859166318439254173, 0.21962210770558857065, 0.024829927856976751616, 1.1100002962962965174e-09, 3.7443772500000006212e-09, 1.2627790523437500951e-08, 4.2570810898681638324e-08, 1.4343375976686856963e-07, 4.8286151921739802212e-07, 1.6234543349501860428e-06, 5.4478341089133651746e-06, 1.8228467705229433379e-05, 6.0725950389411787269e-05, 0.000200959732568890164, 0.00065830362619350942834, 0.0021228688895969845957, 0.0066792918381076149537, 0.020201657448734186562, 0.057212961493873837338, 0.14427872595983071147, 0.29075824853504678158, 0.36564110074442957021, 0.13330127370825312072, 1.8509876543209877828e-13, 9.3684375000000001865e-13, 4.7411103515625013439e-12, 2.3989256927490236273e-11, 1.2134982390689849712e-10, 6.1360608361896876588e-10, 3.1008571052567070342e-09, 1.5656143551154886378e-08, 7.8940702751398238619e-08, 3.9721851623374797589e-07, 1.9925510408963188817e-06, 9.9478099413657914188e-06, 4.930161383220328208e-05, 0.00024154631749370003959, 0.0011617509224607792256, 0.0054175582232760775836, 0.023904363046940359239, 0.094270457100450164023, 0.27882003179675446392, 0.34581727191398570209, 1.2345679012345680828e-17, 9.3750000000000019611e-17, 7.1191406250000002335e-16, 5.4060974121093743207e-15, 4.1052552223205574609e-14, 3.1174281844496730813e-13, 2.3672970275664701427e-12, 1.7976661803082880424e-11, 1.3651027556716061272e-10, 1.0366249050881260814e-09, 7.8718703730129572237e-09, 5.9777015645067147174e-08, 4.5393171255472860584e-07, 3.4470439422124707377e-06, 2.6175989936175949598e-05, 0.00019877392357783613304, 0.0015094394821691928168, 0.011462306067722308894, 0.084705097520176186876, 0.41086218643981919918, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00077892972719669731786, 0.083370713567239546071, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +degree=5 +df=None +intercept=FALSE +Boundary.knots=np.array([0, 3000, ]) +knots=np.array([10, 100, 1000, ]) +output=np.array([0.40055561099999992258, 0.53723465540624992798, 0.68096479632714856933, 0.79404388738027953387, 0.82432650645400162848, 0.74772850370839760714, 0.60695411066016569102, 0.43541006443525137604, 0.25280073560290239332, 0.098204648213291390046, 0.015109611834895182725, 4.9867660859134372328e-05, 0, 0, 0, 0, 0, 0, 0, 0, 0.0089449327889999999397, 0.01902900664771874778, 0.039353322248692389207, 0.078015642723590794549, 0.14535820079903546964, 0.24864829948443537, 0.38546024005089984943, 0.54588573189455047441, 0.70480915137930777448, 0.81344804238272472308, 0.81717844525199323513, 0.71389962178539645432, 0.56021095018500233209, 0.38030131620961826755, 0.19975862317934431345, 0.062981619616186521049, 0.0053407260835513798575, 7.8059373845321992395e-10, 0, 0, 9.4545814444444459148e-06, 3.1017290343749996553e-05, 0.00010028811495410157556, 0.00031713361145809936415, 0.00096922483761113851879, 0.0028119072707210087531, 0.0075647083349296134064, 0.01861553313384527869, 0.042046394339120052308, 0.087124325583113268467, 0.16371060089498334911, 0.27411331174625735985, 0.40781324509205862938, 0.54286075051770132927, 0.63352683070691229172, 0.61289306201898841042, 0.44453962951650222157, 0.21269241367644950436, 0.052346279846925344859, 0.0018876298723944570646, 1.6294444444444447802e-09, 8.1548437499999982349e-09, 4.0568422851562507446e-08, 1.9994451278686527012e-07, 9.7096128099918361425e-07, 4.602189952521174856e-06, 2.0919648984453888767e-05, 8.8510989072612499115e-05, 0.0003426071500521665281, 0.0012159913347531664096, 0.0039613824662355322237, 0.011728070771626651625, 0.030981021316488138728, 0.072628957837475555115, 0.15091202659488145432, 0.27128094978421118944, 0.39491276471324787689, 0.40566968711467132902, 0.22597501897826155481, 0.025700635234072819607, 1.1111111111111111028e-13, 8.4374999999999991361e-13, 6.4072265625000016033e-12, 4.8654876708984379097e-11, 3.694729700088501736e-10, 2.8056853660047051398e-09, 2.1305018189503776537e-08, 1.5953977978988917004e-07, 1.1111370996233737328e-06, 6.9846696024166045466e-06, 3.9856249948076781855e-05, 0.00020802815256623063945, 0.00098445759075916142167, 0.0041227618062229087065, 0.015186511992247679614, 0.04905127538388008579, 0.1347633037922978394, 0.28642046903795781443, 0.37096041450757122337, 0.1373866644432741313, 0, 0, 0, 0, 0, 0, 2.1835286481805527197e-15, 7.5005881261891668233e-12, 3.9151793493690686266e-10, 7.8165151445884371071e-09, 1.0330194469679949402e-07, 1.0998832941312460716e-06, 1.0325449816590390154e-05, 8.6094485881001237893e-05, 0.00061191613127527461416, 0.0037238993946882535668, 0.01960252770274439893, 0.08667615291637777164, 0.27442290749348607903, 0.35255941616703945218, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.6587525069769108936e-10, 1.1914310104321792976e-07, 4.09139533897260065e-06, 6.9193802045574309841e-05, 0.00084104819165634655664, 0.0085412764739499439509, 0.075516449446559150149, 0.39909494071597967357, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00077892972719669731786, 0.083370713567239546071, ]).reshape((20, 8, ), order="F") +--END TEST CASE-- +""" +R_bs_num_tests = 72 diff --git a/venv/lib/python3.10/site-packages/patsy/test_splines_crs_data.py b/venv/lib/python3.10/site-packages/patsy/test_splines_crs_data.py new file mode 100644 index 0000000000000000000000000000000000000000..3b85f71d7e896de9b2f102b10dc1f76722146a63 --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/test_splines_crs_data.py @@ -0,0 +1,325 @@ +# This file auto-generated by tools/get-R-crs-test-vectors.R +# Using: R version 3.0.3 (2014-03-06) and package 'mgcv' version 1.7.28 +import numpy as np + +R_crs_test_x = np.array( + [ + 1, + -1.5, + 2.25, + -3.375, + 5.0625, + -7.59375, + 11.390625, + -17.0859375, + 25.628906250000000000, + -38.443359375000000000, + 57.665039062500000000, + -86.497558593750000000, + 129.74633789062500000, + -194.6195068359375, + 291.92926025390625000, + -437.89389038085937500, + 656.84083557128906250, + -985.26125335693359375, + 1477.8918800354003906, + -2216.8378200531005859, + ] +) +R_crs_test_data = """ +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=4 +knots=None +absorb_cons=FALSE +output=np.array([-1.693557754132211208e-05, -1.9836972061171899575e-05, -1.4954358368392469422e-05, -2.088026100812221311e-05, -9.5355264085171175196e-06, -1.8699295604068575353e-05, 4.9022718833308546933e-06, 1.7974067511175931267e-05, 3.744122291002612696e-05, 0.0002988262983956019303, 0.00010718085083579747424, 0.001935560671294481172, 0.00024699248283329116715, 0.010566342124751632037, 0.00048044994314723433668, 0.053454984128479515748, 0.00065729103443297996496, 0.25076507420610638643, 0, 1, 0.35560680685948470314, 0.46359416252769836131, 0.30168882277557279581, 0.54466866236250932598, 0.18063664369405590948, 0.72711735964503432239, -0.089776348720933471514, 1.1356863997659447652, -0.68566908660007752641, 2.0361466894716735432, -1.9628257407671605428, 3.9650378336575471394, -4.523225924226894179, 7.8266636243390204086, -8.7985820993738865781, 14.246329329102128014, -12.037110654561336887, 18.944322912930825709, 0, 0, 0.6444562685323340645, 0.53647236902629924504, 0.69836999393477805498, 0.45539628464397530205, 0.81940601333710849641, 0.27293213874197075341, 1.0897461189737138731, -0.13572091900106228457, 1.6852766572444068949, -1.0365718798973906356, 2.9606222279687766097, -2.967335129700412466, 5.5120421008950604147, -6.8380635660933348774, 9.743925990387539926, -13.301405831788731149, 12.784702352769150124, -18.197306344378148424, 0, 0, -4.6139814277377641984e-05, -4.6694581936484837246e-05, -4.3862351982477081188e-05, -4.4066745476440737986e-05, -3.3121504755945730075e-05, -3.0799091401098394798e-05, 2.5327475336172373395e-05, 1.6545167606241587368e-05, 0.00035498813276064257764, 0.00012636412732133810903, 0.0020963319475481821674, 0.00036173537157081639762, 0.010936830849001568516, 0.00083359962956235762136, 0.054175659043200374843, 0.0016215185581219158321, 0.25175101075775591086, 0.0022183572412113072327, 1, 0, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=7 +knots=None +absorb_cons=FALSE +output=np.array([-2.9605259404128104445e-07, 4.3004543792069181325e-07, -4.6506508782294522313e-07, 1.2225175036037286749e-06, -4.8490441759023038782e-07, 2.7062259965304665474e-06, 2.8104230735656565092e-07, -5.4449455566502238182e-06, 1.7542735683802410547e-06, -0.00011038827024139799939, 2.8120883750482203265e-06, -0.00053376130083573273665, -7.6784755538918750706e-07, 0.00061879177472234751789, -9.2078635815506674409e-06, 0.029574116402683980898, -1.6901017048743381161e-05, 0.21556638245963724576, 0, 1, 0.00010456869825724268133, -0.00015189629322606839636, 0.00016426557921581520349, -0.00043180524853199072667, 0.00017127302630398999017, -0.000955865732450367038, -9.9266916848531769006e-05, 0.0019305664182940607265, -0.00061962673904836988552, 0.042415216868389754579, -0.00099325736940550032363, 0.27732557133728741317, 0.00027121133522598855859, 1.1504608369631013076, 0.0032523082987030572759, 2.7821404636666882126, 0.0059696060348119403538, 4.1098324719022825136, 0, 0, -0.031642380707528651451, 0.046727930564370717681, -0.049706595580857972083, 0.14260551573254778845, -0.051827041873556585483, 0.44422176162356585838, 0.030038067097830360025, 1.2696071710389067455, 0.18749841492049976188, 2.6526069738107440621, 0.30055865997270758694, 3.4401400654673524038, -0.082068271523342908869, -0.89294447099362916909, -0.98414515128277502143, -10.707999025460104292, -1.8063966557448927208, -19.65451295888456329, 0, 0, 0.9404055233767310007, 1.0229997547271381109, 0.84839014691027592185, 0.9942253298077886603, 0.55270681506501917468, 0.71325376394101502875, -0.27008001161472772189, -0.36441609214674652861, -1.6858466263672904351, -2.2746949537899268101, -2.7024004611201863923, -3.6463202499480562579, 0.73789700429246496416, 0.99563659340566201816, 8.8487029815652924469, 11.939460983544531558, 16.241778413219694954, 21.914859168852931504, 0, 0, 0.091452250263845791256, -0.069826465452058242289, 0.20181123367547218472, -0.13689085681302756714, 0.50012121362724204499, -0.15708533369949770342, 1.2380919977577322655, 0.093217876961678852732, 2.4558884227495125785, 0.58186847095202909319, 3.1248015911458146832, 0.93273112726773044212, -0.80684053529361110524, -0.25468449792074498994, -9.6754590529148973843, -3.0541220021223365322, -17.759287695723489975, -5.6058354437652431201, 0, 0, -0.00032057317842933900735, 0.00025095691201626593508, -0.0006604553857512240455, 0.00049198690620599915858, -0.0011751018630891821651, 0.00056456602826813432217, 0.0020547291059278675364, -0.00033502584436379451204, 0.043190243671805170211, -0.002091240244288253107, 0.27856793393313283858, -0.0033522436217435750035, 1.1501216068412509763, 0.00091533825638770416853, 2.7780724886333088008, 0.010976540508122837117, 4.1023657110424904815, 0.02014742036749034293, 0, 0, 9.0759971803981566744e-07, -7.1050367876085636178e-07, 1.8698667331515860834e-06, -1.392902486538716717e-06, 3.3269224981118857968e-06, -1.5983868974364642471e-06, -5.7964722216058981582e-06, 9.4851778732840647118e-07, -0.00011258250904733756745, 5.9206732932833133743e-06, -0.00053727865043814320746, 9.4907982657877548258e-06, 0.00061975219556745361413, -2.5914854994384806915e-06, 0.029585633563949290115, -3.1076539587733474873e-05, 0.21558752218843252324, -5.7040932539508893209e-05, 1, 0, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=10 +knots=None +absorb_cons=FALSE +output=np.array([1.9320747025477182898e-08, 4.8242814281426965595e-08, -1.2568948282371909281e-08, -7.8978523641721503504e-08, -3.5770522726027550527e-08, -7.01473863118866388e-07, 2.1638270976696590321e-08, 2.2109425903379564006e-06, 8.5370349850805669926e-08, 3.744561791897189516e-05, -3.2925418782971613435e-08, -7.9813891850179092256e-05, -1.991767035296446912e-07, -0.0021868285157625511929, 3.7614188014338205365e-08, 0.0021874060835819046644, 4.688717754303082178e-07, 0.15874967738905676473, 0, 1, -1.4544731165165144453e-06, -3.6317372379498608116e-06, 9.4619516292459995175e-07, 5.9455330204143990165e-06, 2.6928184298539113977e-06, 5.2807216744776855019e-05, -1.6289371928530509096e-06, -0.00016644059132742171966, -6.4267121060004543239e-06, -0.002818920227187673988, 2.4786379329293728427e-06, 0.0060407977628119044478, 1.4994097295422416361e-05, 0.20920617714101982787, -2.8316102474873858596e-06, 1.0967921747761912865, -3.5296843934527352639e-05, 2.0750595382021144175, 0, 0, 9.7994633378747003421e-05, 0.00024468706579685965685, -6.3749578484895432179e-05, -0.00040057827261335182721, -0.00018142772925296013898, -0.0035578683345143034648, 0.00010974909140496827962, 0.011347453981486406438, 0.00043299755045772883848, 0.2521011214081396723, -0.00016699739084748591402, 1.1986460188118959191, -0.0010102222245463542399, 2.0307158061521746184, 0.00019077878093656664284, -0.33272379892704945226, 0.0023781128997935555708, -4.1474987648643217852, 0, 0, -0.0066281488228501295526, -0.016550113319571305159, 0.0043118860597063267057, 0.027486913394933615296, 0.012271386183288513286, 0.32813715189346348566, -0.007423195392682361074, 1.293350915313034033, -0.029287034456989179121, 1.9521712704316960263, 0.011295348749219022086, -0.66799495509124628967, 0.068329285161611297283, -4.0409215143626093791, -0.012903871453880378511, 0.76312128325689243535, -0.16085050450109564246, 9.5125283792626493806, 0, 0, 0.14341751361350341121, 0.77593360542645228861, -0.090432986778547594375, 1.1259563994195789238, -0.25736721450922656063, 1.1109363559631879603, 0.15568633342939960928, -0.56801737059939128027, 0.61423561827887318554, -2.241022016113413784, -0.23689682657495314544, 0.86431165517469521475, -1.4330669354534046889, 5.2285058979714911231, 0.27063229881828543277, -0.9873946118959923135, 3.3735101868301691219, -12.308160541801825616, 0, 0, 0.88922814381914494497, 0.26150528401135941792, 1.052718109833140403, -0.16738921270899279059, 0.90250428645253855109, -0.47638032258407536634, -0.44193283907468589033, 0.28817153685428037457, -1.7435755898887204118, 1.1369348754708179516, 0.6724577863061328431, -0.43849014288054521948, 4.0679186503944446684, -2.652571308655904847, -0.76821964733539216397, 0.50093366421426255286, -9.5760809678860194794, 6.2442835778727587837, 0, 0, -0.026500124336832579092, -0.021442252392463622551, 0.033954742484493150023, 0.014552615451508882013, 0.34654423116839672137, 0.041415928368598843579, 1.2822161222240113787, -0.025053284450302942821, 1.9082407187462107068, -0.09884374129233876316, -0.65105193196742539019, 0.038121802028613864521, -3.9384275866202003158, 0.23061133742043829487, 0.74376547607607035317, -0.043550566156846479138, 9.271252622511015673, -0.54287045269119871271, 0, 0, 0.00039179415524385585289, 0.00031701546211065640812, -0.0004962026403406965408, -0.0002151548273865228544, -0.0038300099283937543392, -0.00061231858622874310843, 0.011512077618593902564, 0.00037040318349176827237, 0.25275061773382700991, 0.0014613667327948419179, 1.1983955227256271048, -0.00056361619411026103298, 2.0292004728153583137, -0.0034095000078439544229, -0.33243763075564392029, 0.00064387838566091657681, -4.1439315955146351911, 0.0080261310368032780238, 0, 0, -5.8151558545865533576e-06, -4.7052624338916936783e-06, 7.3648257648012915326e-06, 3.1934086748705229843e-06, 5.6846444389557634026e-05, 9.088262200756952661e-06, -0.00016888399711670137003, -5.4976630258790269937e-06, -0.0028285602953466680576, -2.1690153357751540543e-05, 0.0060445157197113750028, 8.3654030236365385289e-06, 0.20922866828696309871, 5.0605078372050556115e-05, 1.0967879273608196478, -9.5566845852699449579e-06, 2.0750065929362113692, -0.00011912684827902968556, 0, 0, 7.7246635846578622837e-08, 6.2503173239414331853e-08, -9.7831946065279388105e-08, -4.2420200453005213882e-08, -7.5512964720790736305e-07, -1.2072551420034312034e-07, 2.2433999968030079565e-06, 7.3029164546350807041e-08, 3.7573673443748081119e-05, 2.8812493074646954793e-07, -7.9863279978354456061e-05, -1.1112328839252804556e-07, -0.0021871272808178477895, -6.7222137441255028355e-07, 0.0021874625048639208952, 1.2694788454839182361e-07, 0.15875038069671990049, 1.5824422420772902814e-06, 1, 0, ]).reshape((20, 10, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=12 +knots=None +absorb_cons=FALSE +output=np.array([-3.6802322454608713193e-09, -1.1576165417746612791e-08, 4.0903329323109361483e-09, 4.0685732923556337374e-08, 1.7703518712245050831e-09, 7.8790091688795366003e-08, -9.3409196093845724123e-09, -2.611905916838673793e-06, 3.0933985220706180644e-09, 5.5610182678566951338e-06, 1.6919855821268632348e-08, 0.00016301336905366541432, -1.4352199746873791695e-08, -0.00096630860312933643686, -2.1293612839737406843e-08, -0.0074687624866493825676, 3.8568109059678503697e-08, 0.11083787128447247783, 0, 1, 1.4460849968779115402e-07, 4.5486583496536781572e-07, -1.6072271234908852579e-07, -1.5986770411107210554e-06, -6.9562981611555798878e-08, -3.0959233519658970583e-06, 3.6703563262437939878e-07, 0.00010263042405151407538, -1.2154986136127495596e-07, -0.00021851080443170532329, -6.6483710865399255783e-07, -0.006405334542942880266, 5.6394540729725285131e-07, 0.039346935329722818042, 8.3669649095786947889e-07, 0.58363014399245827235, -1.5154685940796589346e-06, 1.5869193120902693739, 0, 0, -5.4865400297656400151e-06, -1.725790404504806206e-05, 6.09792368290666473e-06, 6.0654841172256407627e-05, 2.6392645247385444743e-06, 0.0001174613348200111455, -1.3925569348217424364e-05, -0.0038938646832389072101, 4.6116803743272812418e-06, 0.008333356501832860086, 2.5224350005560149737e-05, 0.3457041582444345118, -2.1396453586193263292e-05, 1.3943941859934374516, -3.1744806151200007029e-05, 1.0659241155872372087, 5.7497858861837635377e-05, -1.8607361322222011335, 0, 0, 0.00023256871331852414829, 0.00073154456479976239392, -0.00025848462913861898265, -0.0025710954976070178948, -0.00011187567233550075858, -0.0049790635547287236118, 0.00059029037024653681354, 0.20118319692573388702, -0.00019548432437836398673, 1.1583324452787904235, -0.0010692339057516754303, 1.5709796196933376589, 0.00090697336629712820011, -1.2050531219054301246, 0.0013456292455859321117, -1.7878746869280606191, -0.0024372743079464744345, 3.238292460253569427, 0, 0, -0.0096036016628270864243, -0.030208115694913360155, 0.010673763374229244122, 0.11304537553087100343, 0.0046197503419112585787, 0.84717528615215309529, -0.024375220124670693433, 1.6209052609300536041, 0.008072253382102512545, -0.43744451537192496904, 0.044152527520605257261, -2.3926752654369827233, -0.037452204143992279262, 2.0295771844456078625, -0.055565888790719414336, 3.0111781856549497682, 0.10064385386396751398, -5.4540039558593536029, 0, 0, 0.10357732090048776818, 0.85603572021517670976, -0.11294852267110891408, 1.0800087615333373581, -0.048885660842739625531, 0.2401585690492896441, 0.25793574452960393861, -1.2534276012546561319, -0.085419646489135220291, 0.4150930798449654624, -0.46721691129938069942, 2.2704203849822679473, 0.39631486857335096463, -1.9258749730998911964, 0.58799177288976445244, -2.8573206043806020915, -1.0650015567431445618, 5.1753290302415839719, 0, 0, 0.94933893888308096276, 0.20425894956750886844, 0.97636209569699528021, -0.2257137560392956932, 0.19529887869007700463, -0.097691991575737782694, -1.0167341121476407562, 0.51545291906204826482, 0.33670815416251220764, -0.17070067666802030137, 1.8416810448534708389, -0.93367563771983919096, -1.5621985497383736874, 0.79198660986818203433, -2.3177527963386914678, 1.1750293712615387243, 4.1980354999103974833, -2.1282748625244334306, 0, 0, -0.044595007867203530216, -0.03154770903003507182, 0.12905602059221518707, 0.036023951388023812969, 0.85410491166502156002, 0.015591657403950714977, 1.5843424307430495901, -0.082266367920763708299, -0.42533613529877184467, 0.027243855164596028628, -2.3264464741560830774, 0.14901478038204274412, 1.9733988782296159048, -0.12640118898597454966, 2.9278293524688816518, -0.18753487466867790889, -5.3030381750634045801, 0.33967300679089129645, 0, 0, 0.001079949373603220162, 0.00076398525832885994229, -0.0029588224413149436312, -0.00087238562334283919521, -0.0051468770632319233924, -0.000377580394132319148, 0.20206863248110379372, 0.0019922299995820589268, 1.1580392187922230463, -0.00065975959477697777422, 1.5693757688347129697, -0.0036086644319118939793, -1.2036926618559800062, 0.0030610351112528135301, -1.7858562430596849335, 0.0045414987038525046412, 3.234636548791644195, -0.0082258007893193495902, 0, 0, -2.5477139138140648842e-05, -1.8023214052146796125e-05, 6.9801726696616189999e-05, 2.058049242980996096e-05, 0.00012142023160711750383, 8.9075177709926672744e-06, -0.0039147530372612262053, -4.699879655023364312e-05, 0.0083402740223943259285, 1.5564421263354520723e-05, 0.34574199476944195153, 8.5132181268765064475e-05, 1.3943620913130563288, -7.2213030853402265731e-05, 1.0658764983780117941, -0.00010713872076029942911, -1.8606498854339041937, 0.00019405527365870157302, 0, 0, 6.7149986095353481289e-07, 4.7503707792034416037e-07, -1.8397611096343514486e-06, -5.4243915417817383743e-07, -3.2002678243831975437e-06, -2.3477506293900330442e-07, 0.00010318097750045069814, 1.2387452601072785849e-06, -0.00021869312922374677631, -4.1023078209430247345e-07, -0.00640633179860586148, -2.2438252417072174446e-06, 0.039347781247833550633, 1.9033157496282319598e-06, 0.58363139903719374324, 2.8238506569827991151e-06, 1.5869170388873774513, -5.1147065050188478719e-06, 0, 0, -1.7089420375974873326e-08, -1.2089516008577751082e-08, 4.6821232322022749866e-08, 1.3804873646549429766e-08, 8.1445619495631410706e-08, 5.9749375653827772664e-09, -2.6259172962527552498e-06, -3.1525603681672934994e-08, 5.5656583656398050473e-06, 1.0440220011988337053e-08, 0.00016303874883739764194, 5.7104513396781534087e-08, -0.00096633013142895208495, -4.8438674145699212406e-08, -0.0074687944270686538323, -7.1865943334113596723e-08, 0.11083792913663595425, 1.3016736807641509225e-07, 1, 0, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=4 +knots=np.array([-2500, -150, 300, 1500.0000000000000000, ]) +absorb_cons=FALSE +output=np.array([-0.0051418610449036764379, -0.0051207276560822079237, -0.0051517581620670691717, -0.0051036969019558836927, -0.0051724091286762859804, -0.0050616345732373531699, -0.0052108015793779615538, -0.0049476511776847470828, -0.00525764719160080711, -0.0045887810243909702562, -0.0051780211262217532009, -0.0032118234048454639452, -0.0042344880890217376918, 0.0033309098171163710467, -0.0002048781708894489937, 0.036873131791193267115, 0.0053670164361401782871, 0.19556964857406355929, 0.00027785197169554257113, 0.82912284340298503249, 0.65949448911253716332, 0.6654093842010145865, 0.65653556733089935005, 0.66984284447353759084, 0.64987461295218140744, 0.67980900603329297294, 0.63487206047522759533, 0.70218091452751663084, 0.60105778412747068451, 0.75218902517658670082, 0.52490094418674082544, 0.86229539201840321727, 0.35569403068909899446, 1.0895778496922625678, 0.014595118281322956924, 1.4713138143490975818, -0.3821845778229204238, 1.7530984807387750557, -0.019785804601727036839, 0.46986487896086814864, 0.35950128095327349431, 0.35338118891054576265, 0.36256112212690350116, 0.34879091185540550546, 0.36944502095300485456, 0.3384628569483467686, 0.38492806794448852781, 0.31523169436694697954, 0.41971361558839714867, 0.26307215994266325287, 0.49746707294522052312, 0.14713121281897215131, 0.66691371985704051006, -0.097089653687300894735, 0.9873402560545572193, -0.53105535871660392022, 1.2102463767433073727, -0.99135819513191647534, 0.044702741392222536398, -0.3124421698702265493, -0.013853909020907106964, -0.013669845455478047552, -0.013944931295735877447, -0.013530059426987159701, -0.014147224776509979491, -0.013210228408402318115, -0.014589326840338213628, -0.012464957716778975183, -0.015513752524267036478, -0.010672404094858929657, -0.017189996005739616169, -0.0062147814325298833885, -0.018373262457117778973, 0.004180894177922047858, -0.0017304961649907309174, 0.022868412576313085216, 0.16657118464347281384, 0.042690065819077735454, 0.97480521123780894399, 0.013454447506373390722, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=5 +knots=np.array([-400, -50, 10, 50, 100, ]) +absorb_cons=FALSE +output=np.array([-0.00093170433340244659687, -0.0012410506081968345274, -0.00078243418040293037045, -0.0014789118938009710238, -0.00046560203080319340248, -0.0020151841680895970881, 0.00010431589287147467922, -0.0030688678143442819739, 0.00055449747551044887423, -0.0028609656322684854333, -0.00014909864114985113439, 0.026923379556954812886, 0.00037005603844857983247, 0.24511712352852058072, 0.0023876748113693508323, 1.1555668732201982429, 0.0069273170504410850126, 3.402689781560706006, 0.017141512088352486159, 8.4587163253268489171, 0.084019186191167327671, 0.11446091282800011091, 0.069879045425061070418, 0.13908517998091646239, 0.040857714895860555715, 0.19963820957805075706, -0.009029120060764306635, 0.3576254481931359086, -0.047994837046959955285, 0.77395141822244861718, 0.012905315717303777676, 1.5659844614539342178, -0.032030405994604847775, 2.0431817208334850378, -0.20666651978408043244, -0.51809792415464139825, -0.59959777581040041294, -8.0018873070243543566, -1.4836931018696206674, -24.840413418481212204, 1.0495495283018867472, 1.0438716260482179266, 1.049399522569444354, 1.0346122703952109756, 1.0414030908228715244, 0.99920617535829048261, 0.98168936282733698651, 0.85586872666349445016, 0.66418975301951443946, 0.32605391435347208517, -0.11777757243608029392, -0.85263295720592457982, 0.29231857203837463555, -1.8526421434409372502, 1.8860972902309971477, 0.52133890068006216723, 5.472099406164398161, 8.051943344140203962, 13.540604167014549830, 24.995803341925523000, -0.15192966618287376268, -0.17994115928882439825, -0.13573193509615386065, -0.19726850771611939561, -0.093692687860718673609, -0.2254589026981791422, 0.031190848164371551277, -0.24103262443025505468, 0.43031985595064925487, -0.11127445668091072439, 1.0214738883945315706, 0.29750331491431342146, -1.0287095298822455103, 0.64642959712677627859, -6.6374375162553720386, -0.1819071733449817152, -19.257075485594906894, -2.8095088468476898669, -47.65126091660886232, -8.7216126122287835898, 0.019292656023222061468, 0.02284967102080309731, 0.017235801282051283617, 0.025049969233792938189, 0.011897484172789671297, 0.028629701929927506981, -0.0039554068238157324977, 0.030607317387968895062, -0.047069269398714280728, 0.014130089737258502702, 0.083547466965394667771, -0.037778198719277893136, 1.7680513078000272831, -0.082086298047844605263, 5.9556190709970859842, 0.023099323599362758808, 15.377646538190468561, 0.35676302817113519916, 36.577208339375580692, 1.1075063634576232108, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=7 +knots=np.array([-1000, -500, -250, 0, 250, 500, 1000, ]) +absorb_cons=FALSE +output=np.array([-4.3178765217391302305e-05, 6.5885993478260890537e-05, -9.6313081793478265121e-05, 0.00015008344269701090522, -0.00021248546106063178089, 0.00034663246069176721631, -0.00045706603540709121736, 0.00082099033067846731351, -0.00092573826895791448514, 0.0020071162494608137464, -0.0016063078222631245202, 0.0047785217809616390913, -0.0016924900384041397308, 0.0058508393862588175052, 0.00037271449492305578147, -0.023079518000319019372, -0.00039460853415255482939, 0.96024636175750266442, 0.0010388953913813049352, 4.2828168145345602014, 0.0006476814782608695956, -0.00098828990217391310055, 0.0014446962269021740039, -0.0022512516404551634157, 0.0031872819159094768759, -0.0051994869103765082446, 0.0068559905311063691277, -0.01231485496017700916, 0.013886074034368717928, -0.030106743741912203594, 0.024094617333946868887, -0.071677826714424588972, 0.02538735057606209683, -0.087762590793882266915, -0.0055907174238458371557, 0.77073211937350760703, 0.0059191280122883223325, 0.065812149128730040859, -0.015583430870719573377, -5.436090696106786524, -0.0031088710956521745793, 0.0047440075304347817733, -0.0069345418891304357392, 0.010808468249184780344, -0.015298953196365492127, 0.024985562378791605076, -0.032908754549310574589, 0.059430528454937264771, -0.066653155364969851604, 0.14814853819552065151, -0.11565416320294498453, 0.38547179702354089637, -0.12185928276509808144, 0.89303994817074205947, 0.026835443634460023205, 0.3158234170040984945, -0.028411814458983948584, -0.033037325841022327499, 0.07480046817945394666, 2.7299491962930431121, 0.99996527520000000333, 0.99992195380000004068, 0.99982468157500004047, 0.99960649719062499852, 0.99911787098710935773, 0.99802618626118166922, 0.9955959649107849474, 0.99021595070231704927, 0.97840786415926050967, 0.95284186025012007626, 0.89870074544754108281, 0.78829881686806935193, 0.57842205914062527761, 0.2362299420741153233, -0.10286920059876342171, -0.080364133358400105522, 0.1089119554261051559, 0.0088355638877152739563, -0.28673512802124018206, -0.73010269203186040077, 0.0031519622956521736561, -0.0046471747304347834143, 0.0071520025891304338586, -0.010320575886684784858, 0.016392005544802985134, -0.022542075546565051858, 0.038353001709637714323, -0.04736186631031753802, 0.093197128054721647961, -0.090485094976372942854, 0.23844273869784807229, -0.13266783181011393422, 0.6114558419262043909, -0.058789413728980027818, 0.96115953962745293016, 0.020964556528278284475, -0.40723600724543668194, -0.0023049297098387665911, 1.0721400439055068787, 0.19046157183439835214, -0.00065664547826086978963, 0.00096816140217391292219, -0.0014898486644021743334, 0.002150119976392662717, -0.0034132712039954154516, 0.0046962657388677176915, -0.0079705034644407205674, 0.0098670554813161497065, -0.019191613515453308236, 0.018851061453411026292, -0.047118889772279910766, 0.027639131627107058065, -0.098264441613631667294, 0.012247794526870834503, 0.1283332564542301879, -0.0043676159433913086874, 1.1341990151205716408, 0.00048019368954974300367, -2.1349300292885819985, -0.039679494132166315268, 4.3776365217391304853e-05, -6.4544093478260855155e-05, 9.93232442934782663e-05, -0.00014334133175951084961, 0.00022755141359969430562, -0.00031308438259118116136, 0.00053136689762938121937, -0.00065780369875441000935, 0.0012794409010302202311, -0.0012567374302274016227, 0.0031412593181519930102, -0.0018426087751404706099, 0.0065509627742421101121, -0.00081651963512472227127, -0.0082410361884569308111, 0.00029117439622608720607, 0.18701233167960798487, -3.2012912636649525446e-05, 2.2892691807041996022, 0.0026452996088110873087, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=4 +knots=None +absorb_cons=TRUE +output=np.array([0.17237877473947216256, 0.16160585322933293528, 0.17775653635702576283, 0.15351565450517737355, 0.18982763251278575445, 0.13530235680671015563, 0.21678099966619068795, 0.094474101590757947333, 0.27612342080317897608, 0.004254035614190725817, 0.4030409383688886571, -0.19022791859524765257, 0.65608982528520065625, -0.58588986559744449245, 1.0712259966408619327, -1.27728761497709975, 1.342827694119810289, -1.9788260499202323661, -0.052195429016186831173, -0.97077694213337639706, 0.68714996318883114768, 0.60683822144440202617, 0.72724727397328958745, 0.54653827251673237075, 0.81726443453130048766, 0.41083008335212661821, 1.0183156414681064916, 0.10689042936382432691, 1.4611707976831045386, -0.56312355687140791538, 2.4093551078217010364, -1.9991227596244038889, 4.3052173449842321418, -4.8778668329561920558, 7.4441765017641099433, -9.6842706472508055526, 9.6670625693150959989, -13.322034134461750554, 0.012161980255413960134, 0.22619930950229019673, -0.010768222248548299166, -0.01771835491152162767, -0.0072960943160139245939, -0.022933439873231927647, 0.00050471399250212036977, -0.034662450006663660107, 0.017964357449119585514, -0.060912800432191181732, 0.056636870493901259049, -0.11877531418126709151, 0.14054140101632672799, -0.24279484616490168425, 0.3140184596633784353, -0.49144965505677373763, 0.63173409697146676312, -0.90678479147331569887, 1.0347141866437283841, -1.2221561304860752983, 0.99694564370894334093, -0.056807630788862507887, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=7 +knots=None +absorb_cons=TRUE +output=np.array([-0.088612856492796668317, -0.10148345379387192777, -0.074820024844059834779, -0.097934158724637176974, -0.030963004348234846042, -0.058173986143542688598, 0.090101482080220576809, 0.10049075761090919823, 0.29596829876665797787, 0.41518677441788176541, 0.43034390532152527742, 0.83452635605264402496, -0.13348462782429343365, 0.98208889847295099962, -1.4362329672138189895, 0.92468785756571492129, -2.6216702734870915847, 0.6954743327776672368, -0.0022196047790754855691, -0.12327370541474826082, 0.24123862297275155964, 0.35840804363927752929, 0.18093342115646737778, 0.44250759269715284061, 0.043937153723061256327, 0.6202158021725746595, -0.24740540994207005365, 0.96645134975980595549, -0.72475992234705299833, 1.5060196314875564649, -1.0261673763863199405, 1.7262771004734287494, 0.32934388972170997034, -0.37505857126375657939, 3.4434877057227697428, -4.9947636565362447669, 6.275814996477087071, -9.1524782805583591028, 0.0068271591356862497413, 0.37917074789447108296, 0.35954055514606403365, 0.35954551446237459356, 0.35744096324407559351, 0.35584226884375003142, 0.34885947617865670223, 0.33862610062421411028, 0.32049681236018934261, 0.28089301373203690027, 0.25602145147051952323, 0.16597482970505655908, 0.12171945403305862998, 0.0018741765108557348514, -0.13785069799652086009, -0.10675519142579256715, -0.57612609827379823724, -0.22195090041542500647, -0.96232722728117126021, -0.44017455467682947701, -0.01453255272801050671, -0.80711739351329703229, 0.39138909874594340899, 0.2727563805116787754, 0.45531894883729062684, 0.19274617399836088683, 0.60538032158012156092, 0.036358318155975434538, 0.93314031181054180042, -0.23999550325584054211, 1.4531806967029836652, -0.67840171762003531608, 1.6665321594967388297, -0.95105942435581225514, -0.35463732068059222735, 0.31454920667339703044, -4.8088313747127671149, 3.2255742320619229524, -8.8757338424365990193, 5.937464168828833877, 0.0075040642903919140341, 0.41676510136746514057, -0.089133365834868971689, -0.10118952771068721874, -0.075725350737607874385, -0.097115177460207771643, -0.032342847263930989132, -0.056715061432944156861, 0.092352440078496370046, 0.098331113369192327256, 0.3400969886051333213, 0.37108103090272787083, 0.71036876576058238797, 0.55444750827998945386, 1.0162219858335352907, -0.16763759291903618243, 1.3370398275661443677, -1.8484727482821472488, 1.4719012302123679614, -3.3978810087925515049, -0.0022219907599747576801, -0.12340621941421109353, -0.013194863919370570376, -0.015072699772667915927, -0.011151244212216769591, -0.014503828881363881043, -0.0046275650331869689486, -0.0085121840139092009442, 0.013410603654954418931, 0.014660726583422474187, 0.044001710617309369722, 0.05545171716304433257, 0.063619527459568614436, 0.082887169332405197242, -0.019275003418586279108, -0.025046122964883565931, -0.18452246030655442, -0.27630735647963872159, -0.17524590664413686181, -0.50790642667837671009, 0.99966985744385294943, -0.01833564992966553106, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=10 +knots=None +absorb_cons=TRUE +output=np.array([0.017741203875868801626, 0.059666517581418020144, -0.0073055449468428850998, 0.071233532376632907601, -0.061951321114274808532, 0.023459686026844089879, -0.15952965061095217281, -0.21534242305337428225, -0.20894123625115404441, -0.40851053368902323637, 0.088769309083260417026, 0.1702312769628678002, 0.44867980227835829732, 1.1139500668975872433, -0.14345767930218020214, 0.86682083739859494553, -1.1837156997359956634, -0.21597943647408635037, -0.017918712309548733702, -0.23789999499399971938, -0.0050889918235734665428, -0.017199613011022536063, 0.002072270281447358229, -0.021223643286449593581, 0.017930549906902432111, -0.010400764195970725601, 0.046747049525783831991, 0.07425318574607586708, 0.061514150450350559007, 0.37070324197740467387, -0.026117581474140658115, 1.1506456698664466742, -0.13217536320689113327, 1.766217994670280067, 0.042129159012710096222, -0.26549271162309995287, 0.34842176083555986832, -3.4777238134306913686, 0.0052384550413758917964, 0.06954899473750200678, 0.040717410233940966313, 0.14267724274658066808, -0.01518518709909348792, 0.21755481940124130058, -0.15305036931474685913, 0.39059745188013861306, -0.43311720487012722591, 0.71916259556541839437, -0.58682103919738470843, 0.86959977149390199624, 0.24816600986825945729, -0.22985936815572685643, 1.2655729988498243266, -1.6266494012894197052, -0.39570727271363553834, 0.14945216327392790712, -3.3194533089504827394, 3.3989844591011317831, -0.047815351859148348679, -0.63482641896460045849, 0.12003828098968173654, 0.69730715192779646472, -0.080805333880490451404, 1.032100885251629574, -0.17573134714242774623, 1.0800934656851248761, 0.36589399540256600796, -0.28448323213545234633, 0.88954585755350989995, -1.7064483114238784278, -0.35386353683003346493, 0.6479603434190704947, -2.0242657690367202861, 4.0363385548625183574, 0.45966058247434787853, -0.6843648579769759932, 4.9332279555632334578, -9.2892931271418373029, 0.023611216265584832746, 0.31347722617275158852, 0.88792799224608875974, 0.25713275781065136893, 1.0532535169725301127, -0.17260864810915746426, 0.90704417033506612444, -0.47809553851771402488, -0.43024289925585679217, 0.30393926379684116368, -1.7282652053936073955, 1.1666632610962044403, 0.66595310521671158277, -0.45052173959023528171, 4.0350412627641443208, -2.7188693891544946091, -0.75770752213855696588, 0.51778556938925135444, -9.4893428981139695821, 6.4121669845342363914, 0.0013130525053329394382, 0.01743290360653331969, 0.018394340893766202016, 0.12954185558052447313, 0.015467038664664091788, 0.1947806488224434196, 0.18978123265431517952, 0.10064263984709266586, 0.87856041959654240792, -0.56951570226238645844, 1.3795704170465219462, -1.1253701882691806713, -0.4264441361865796698, 0.45357497790875550558, -2.8031655399252684013, 2.5198958573805381178, 0.38077992198436172444, -0.6254498513067092702, 6.2761716348405380828, -6.3399143661490446888, -0.045339936718340946575, -0.60196126440255459666, -0.004758953821358206937, -0.017005411359244829855, 0.0016248940817804027534, -0.020892741105429570719, 0.014155429774586492792, -0.0074074070841472963028, 0.057823550154750644192, 0.062836648910594553041, 0.313405031875580109, 0.11923488274498127149, 1.1726262403941665191, -0.048228614408167384819, 1.8989517069621104639, -0.26605941795394616456, -0.29079224977894058135, 0.067405260889645518541, -3.8003055548041984046, 0.6731217514912637423, 0.0052018569797349914138, 0.069063096056237921472, 0.017736305328008575982, 0.059663635167637223133, -0.0072989048214304030199, 0.071228621002306605203, -0.061895289364833461221, 0.02341525749747295701, -0.15969206961095888664, -0.21517495710840772727, -0.21175703601763257167, -0.40570100515546192455, 0.094808655216413129097, 0.16419386720169948379, 0.65787987528453284458, 0.90476706770574533145, 0.95333742847376501395, -0.22997392252730572415, 0.8913620730776831147, -2.2910886491383859465, -0.017918169107386142797, -0.23789278310346156919, 0.0060750632566522310557, 0.020430784619126868273, -0.0025017991326720841194, 0.024387881029101547703, -0.021213459590422957535, 0.0080142623794636578399, -0.054619250223539139721, -0.073674968074426458453, -0.071500525070803497285, -0.13890622902065649646, 0.030313398118739860038, 0.056217781624179681554, 0.1514331690285295462, 0.30977852573253761292, -0.046930667126897918084, -0.078740760116175548267, -0.2465351039505715991, -0.78443722293869766471, 0.99386473410822107066, -0.081455614651688740269, ]).reshape((20, 9, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=12 +knots=None +absorb_cons=TRUE +output=np.array([-0.10472685656120690745, -0.12767819762829035746, -0.076360123823526582232, -0.10958044510013424666, 0.0027880985603357523288, -0.00047490167664404706613, 0.06928482401745712782, 0.12032832514458154105, -0.15700287132688625635, -0.1737016309573724826, -0.34110464392275169354, -0.43703758617891158567, 0.21658232947898950482, 0.33207321984948795501, 0.31440967571649758305, 1.0125703207549268114, -0.77927839590651259982, 0.57499654812351752575, -0.03855715180341089815, -0.29753053676014623585, -0.045155067335396106842, -0.055061683622734447496, -0.032913973166337623377, -0.047180638471765484754, 0.0012046656812917998312, -8.5942102116568291834e-05, 0.029855775209106073798, 0.047937464934110683712, -0.067681928151560877271, -0.066458149628327731206, -0.14703046798660462935, 0.16005131398107033669, 0.09335066435731875778, 1.5205934362940900506, 0.13551522132064452997, 1.2508474777651827914, -0.33590194032153924963, -2.2969931440729616234, -0.016622640017795731193, -0.1282704446656750541, -0.15034574662694516478, -0.18284705677723475659, -0.11005017611978802627, -0.16012547886604538983, 0.0038970012572561371633, -0.0056574341249261998407, 0.10020869531895890137, 0.37404580513022472887, -0.22593678600553301905, 0.90889537861179725553, -0.49151450544890296079, 0.95180903084537338277, 0.31231202672612079496, -0.78416614637393700082, 0.4534081611517823962, -1.1711369929499528819, -1.1228952128467266647, 1.7833321983277987677, -0.05543814773678283625, -0.42779461349253811164, 0.021352229303511102015, 0.007531901115204664085, 0.033244696218130601051, 0.14543534382436593133, 0.0037956069961920194805, 0.8473147453077168878, -0.044854732714249959113, 1.5853682337831724869, 0.054480061579266131355, -0.38616534110945410774, 0.14497807394687750593, -2.2653864188032963867, -0.10147073278861845624, 1.9430514052120930746, -0.14850072666747962669, 2.8843894925937085816, 0.33098715709405579499, -5.1548937962780287947, 0.011396952652503542641, 0.087945848734329423735, -0.065952557774967432436, 0.64935218850878217989, -0.23655843353990058109, 0.90262481725902277141, -0.044372232611305732763, 0.23939481976571783117, 0.37009197410777977533, -1.0588087616813195435, -0.33957241343679639423, 0.13426223409097867711, -1.0193888969785738219, 1.5733219045695456817, 0.74691289987499476233, -1.4520157873552757, 1.0969502242749886722, -2.1629612193760392458, -2.3264786688505232348, 3.5372496286723378311, -0.062415510749811636826, -0.48163620876963536555, 0.8195140136919921714, 0.045981988292849676481, 0.88170239584467990923, -0.36155327574779005939, 0.19875523391830787756, -0.098276866020166997462, -0.93084557008965973512, 0.66449081424484612857, 0.14207954819710574834, -0.38575918922177282466, 1.418831177364036078, -1.467509312217160522, -1.2937127610296201841, 1.1548650229305499337, -1.9279955842607379157, 1.7067654635554521114, 3.232004184432778704, -3.3827058656451867158, -0.047797409383925140713, -0.36883400885657852131, -0.021262964105923369551, -0.0031022854611233788291, 0.1460681949195489493, 0.060436933823290558965, 0.85348373794725573838, 0.015696770625561979468, 1.5689066026927753761, -0.10905135306422376884, -0.39035761984884714826, 0.065894018981400556689, -2.2504521949512743539, 0.2449549909100549594, 1.9251468021185453861, -0.19161744080459083839, 2.8577824618961185088, -0.28309810920621092389, -5.1294237100882460467, 0.56511845971327800964, 0.0085901166188240788563, 0.066286587283785933233, -0.14931374206792483172, -0.18258953057237148343, -0.11261589846568037521, -0.15823359174408363481, -0.0011429154130191262681, -0.0010551192149562264085, 0.30156489541842562696, 0.17464289155956300159, 0.93257469826065064744, -0.24979099176207356092, 1.0795318316732362973, -0.62202008893514815213, -0.89266942187285236443, 0.42343196160757057278, -1.3343479845023715757, 0.62052301130682563368, 2.1155524024387766246, -1.4614021376163455201, -0.055370175087794709645, -0.42727009501042717554, -0.045179413406039932444, -0.055067758936182993612, -0.032853445083453579334, -0.047225270074522207597, 0.0013235626049733512782, -0.00019451554100623699175, 0.025957829199430799971, 0.051789330864583066338, -0.059352795367343585964, -0.074783156665720870726, 0.19867211632366271745, -0.18558562156573668589, 1.4877431595022336808, 0.12613921140813655342, 1.2014365403948221722, 0.18483406256944329149, -2.1966417328137768372, -0.43610504124242488455, -0.016624243563923207095, -0.1282828186071544585, -0.10472621487286955244, -0.1276780375015148794, -0.076361719159604879437, -0.10957926874689910557, 0.0027849647992298789088, -0.00047204001118300933926, 0.069387562012853995497, 0.1202268016798509892, -0.15722127080697423374, -0.17348334021941591576, -0.34750993698157911505, -0.4306340234217196361, 0.25592930937433366889, 0.29272786696227376391, 0.89803989341652912248, 0.42894253042841035128, 0.80764101265733667656, -1.0119267694495412968, -0.038557109538814519911, -0.29753021062070239555, -0.052405524507834276571, -0.063890551260129033184, -0.038210563318028127611, -0.054833362353974436643, 0.0013952838636999886825, -0.00023608614675063352537, 0.034667393120659889538, 0.060161039317539917459, -0.078558784282471219584, -0.086811135096279259948, -0.17052577031441601418, -0.21548879873646650807, 0.10741142530502149899, 0.14648050866337228304, 0.14986173697025292895, 0.21464206783358963371, -0.2791130852403586049, -0.50636714208926458802, 0.98070595851787800701, -0.14888461024604163208, ]).reshape((20, 11, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=4 +knots=np.array([-2500, -150, 300, 1500.0000000000000000, ]) +absorb_cons=TRUE +output=np.array([0.026705483244849264474, 0.029839625165101336945, 0.025137490946490849419, 0.032188537945938233698, 0.021607394654091297004, 0.037467894551815809911, 0.013655036980899055293, 0.049314030316796791942, -0.004274510570643489521, 0.07576300788030972122, -0.044664576703176542272, 0.1337724526334178321, -0.13422281221596993328, 0.251582066127820414, -0.31121876398729647617, 0.43612872129651875097, -0.47985225176217655152, 0.49291724756068344693, -0.081762536217311512776, -0.57008353784816034882, 0.10575886843256800118, 0.098523720643000009534, 0.10937645918695998448, 0.093097559739294566405, 0.11751580252413190708, 0.080890140328454290808, 0.13582591101899046948, 0.053438242334149517465, 0.17698108482519578355, -0.0081682818617542177903, 0.26907668054096511856, -0.14499960251139776268, 0.47046169477357585587, -0.43311804519238522593, 0.8566919676788534721, -0.94615480020651354653, 1.1710825622951557268, -1.4966789629626817693, 0.019850657594207062745, -0.7294516591807701511, -0.065495278981390098183, -0.065538150305470069257, -0.065472788689835886844, -0.065568482416232795607, -0.065419575517949940524, -0.065631137544391218719, -0.065286317209239316806, -0.065744866169428622937, -0.064914403751873434034, -0.065874953263984459273, -0.063671751390664124703, -0.065668915889071088898, -0.058354957302844213951, -0.064207225531959205567, -0.028319888642541334034, -0.061612158154530236032, 0.15860060924423530215, -0.060152247616144620401, 0.96974734313860999624, -0.071414854005294861605, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=5 +knots=np.array([-400, -50, 10, 50, 100, ]) +absorb_cons=TRUE +output=np.array([0.21482323419002713472, 0.24750397604597326739, 0.19883614002139288202, 0.27258973708238182221, 0.16379621347999451242, 0.33062932586024107451, 0.090229192760086424085, 0.46740970723200020442, -0.043673571594035724697, 0.78496238070321600055, -0.14225997541844798144, 1.352022453322457185, 0.3403195391608931919, 1.6947780812699095865, 1.6168904854104195756, -0.12774151466578054226, 4.4891751144718545774, -5.4563586958095688928, 10.951815529860082776, -17.445747353383097789, 0.78661625540292257064, 0.77643763922916775311, 0.79017886797586167624, 0.76625062041079372577, 0.79428060270008205013, 0.73589687070232667754, 0.78216715039058581915, 0.63518798334179016329, 0.65550344333732102342, 0.30392043723920803, 0.19412499069407199159, -0.42254129005404528208, -0.4561535986725677172, -1.1523051841355156366, -1.7794911913869626563, -0.26332862233794968043, -4.7570007749943510333, 2.9350973501194954629, -11.456397338110976492, 10.131555788148743247, 0.21540397689706236584, 0.19368025263260429947, 0.22641495625607274689, 0.1776489056064568528, 0.25155233513796670941, 0.14240007942952948028, 0.30993541465339075058, 0.067271686044363815382, 0.44245515455816608608, -0.080352654001592846433, 0.58572719290272645676, -0.30336068837952584465, 0.016951242449324648714, -0.3319833812262538153, -1.5163892893085060276, 0.9143206895602743467, -4.9664054857636248386, 4.3390336686705470726, -12.728941927787642996, 12.044637871668662399, -0.24478425848794690967, -0.24574753349402200797, -0.24311234670203171748, -0.24447893336440842948, -0.23629987575155153579, -0.23582487990744877004, -0.20434545124769434854, -0.19103328802457081315, -0.055793360625630179783, -0.0080996580588084746144, 0.39680666612040660368, 0.39418417396254185059, 1.016323619403686207, 0.62129681239849587904, 2.2740869262794469741, -0.76498115062552785037, 5.1040543667499091995, -4.782338947138994989, 11.471481107808449096, -13.821393989294298521, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cr +nb_knots=7 +knots=np.array([-1000, -500, -250, 0, 250, 500, 1000, ]) +absorb_cons=TRUE +output=np.array([0.18906235677058036426, 0.18778525841872689695, 0.18966313099776943574, 0.18676205783172145081, 0.19092371457093507137, 0.18426214279619892999, 0.19330747373751991369, 0.17770329603139525809, 0.19648166130871616564, 0.15897921699813499785, 0.19369977803300092445, 0.10544719310340035234, 0.15040730339948449323, 0.026126087939682636485, 0.014566423626603465513, 0.71038417591713942656, -0.0044258520659356658661, 0.37477303749040830061, 0.11191608928948779123, -3.5378245461949706652, -0.1717114269621455025, -0.1641796852631927095, -0.1753614922544594612, -0.15832977440814030579, -0.18329458477753993173, -0.14455385888762556368, -0.19975455127362412577, -0.11060689494904693553, -0.23004851008792162603, -0.021054716326888309186, -0.26742505651389464338, 0.22697177040482915955, -0.233733177660145508, 0.79112685520733139199, 0.0087978598061598800584, 0.36982567289124945731, -0.019154626403592486805, -0.30951045809435018263, -0.039292263384108856716, 1.0312889189371063914, 0.550395590305010729, 0.54949597448884435202, 0.55072323934346578689, 0.54860843215917232119, 0.55116651719216569472, 0.54595839995564021674, 0.5507105841767095944, 0.53682026836985941021, 0.54272290221675423272, 0.50167044456244525019, 0.49401178725604522057, 0.36566698512261336385, 0.28011631034896739001, -0.03551586186561946773, -0.15096545178713224877, 0.063629989613431983675, 0.133595751562454651, -0.72836523541381203994, -0.59095728594899554764, -5.2594893416580195122, -0.095090409079557833283, -0.1030766681400390461, -0.090988045895585706324, -0.10887508452680887128, -0.081496719465270400784, -0.12133034539926186579, -0.058865730473533696421, -0.14644031510302549237, -0.0020110794198277630838, -0.18907748512879404834, 0.15000794369741921042, -0.22502359947941463769, 0.5462684746707909822, -0.11817275982033918769, 0.95064928964895001329, 0.052430922211166117175, -0.40184197213040517838, -0.16340199015776293856, 1.0056597912908593617, -0.79932421729955860368, 0.03971313277885706039, 0.041414831889495302975, 0.038837883046586599289, 0.042648161751521966589, 0.036811186605924875459, 0.045290364726222026581, 0.031978640736114505305, 0.050580394866669355081, 0.019931365400903504337, 0.059364669508446515911, -0.010779243096346216579, 0.065589985310555209974, -0.071477633391997127954, 0.036649613012278252355, 0.13265213083724519683, -0.017297782300268411959, 1.1319824969476413035, 0.066678235503076957458, -2.1076119483122943699, 0.36704351417936742497, -0.098246537944137943277, -0.098542071754031859698, -0.098088618240313230068, -0.098745945231101361905, -0.097708943948828105852, -0.099149563571540588747, -0.096734808676916902992, -0.099784603436978008828, -0.093975228815392539139, -0.099897241328297553542, -0.085336692453571283412, -0.094243446676616243751, -0.058668216352278305947, -0.060228845196453252575, -0.018756415239227899883, 0.03177289587597233872, 0.19240899911984374326, -0.16120768980326213859, 2.2227564852817449648, -0.98762351160861328037, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=4 +knots=None +absorb_cons=FALSE +output=np.array([-1.693557754132211208e-05, -1.9836972061171899575e-05, -1.4954358368392469422e-05, -2.088026100812221311e-05, -9.5355264085171175196e-06, -1.8699295604068575353e-05, 4.9022718833308546933e-06, 1.7974067511175931267e-05, 3.744122291002612696e-05, 0.0002988262983956019303, 0.00010718085083579747424, 0.001935560671294481172, 0.00024699248283329116715, 0.010566342124751632037, 0.00048044994314723433668, 0.053454984128479515748, 0.00065729103443297996496, 0.25076507420610638643, 0, 1, 0.35560680685948470314, 0.46359416252769836131, 0.30168882277557279581, 0.54466866236250932598, 0.18063664369405590948, 0.72711735964503432239, -0.089776348720933471514, 1.1356863997659447652, -0.68566908660007752641, 2.0361466894716735432, -1.9628257407671605428, 3.9650378336575471394, -4.523225924226894179, 7.8266636243390204086, -8.7985820993738865781, 14.246329329102128014, -12.037110654561336887, 18.944322912930825709, 0, 0, 0.6444562685323340645, 0.53647236902629924504, 0.69836999393477805498, 0.45539628464397530205, 0.81940601333710849641, 0.27293213874197075341, 1.0897461189737138731, -0.13572091900106228457, 1.6852766572444068949, -1.0365718798973906356, 2.9606222279687766097, -2.967335129700412466, 5.5120421008950604147, -6.8380635660933348774, 9.743925990387539926, -13.301405831788731149, 12.784702352769150124, -18.197306344378148424, 0, 0, -4.6139814277377641984e-05, -4.6694581936484837246e-05, -4.3862351982477081188e-05, -4.4066745476440737986e-05, -3.3121504755945730075e-05, -3.0799091401098394798e-05, 2.5327475336172373395e-05, 1.6545167606241587368e-05, 0.00035498813276064257764, 0.00012636412732133810903, 0.0020963319475481821674, 0.00036173537157081639762, 0.010936830849001568516, 0.00083359962956235762136, 0.054175659043200374843, 0.0016215185581219158321, 0.25175101075775591086, 0.0022183572412113072327, 1, 0, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=7 +knots=None +absorb_cons=FALSE +output=np.array([-2.9605259404128104445e-07, 4.3004543792069181325e-07, -4.6506508782294522313e-07, 1.2225175036037286749e-06, -4.8490441759023038782e-07, 2.7062259965304665474e-06, 2.8104230735656565092e-07, -5.4449455566502238182e-06, 1.7542735683802410547e-06, -0.00011038827024139799939, 2.8120883750482203265e-06, -0.00053376130083573273665, -7.6784755538918750706e-07, 0.00061879177472234751789, -9.2078635815506674409e-06, 0.029574116402683980898, -1.6901017048743381161e-05, 0.21556638245963724576, 0, 1, 0.00010456869825724268133, -0.00015189629322606839636, 0.00016426557921581520349, -0.00043180524853199072667, 0.00017127302630398999017, -0.000955865732450367038, -9.9266916848531769006e-05, 0.0019305664182940607265, -0.00061962673904836988552, 0.042415216868389754579, -0.00099325736940550032363, 0.27732557133728741317, 0.00027121133522598855859, 1.1504608369631013076, 0.0032523082987030572759, 2.7821404636666882126, 0.0059696060348119403538, 4.1098324719022825136, 0, 0, -0.031642380707528651451, 0.046727930564370717681, -0.049706595580857972083, 0.14260551573254778845, -0.051827041873556585483, 0.44422176162356585838, 0.030038067097830360025, 1.2696071710389067455, 0.18749841492049976188, 2.6526069738107440621, 0.30055865997270758694, 3.4401400654673524038, -0.082068271523342908869, -0.89294447099362916909, -0.98414515128277502143, -10.707999025460104292, -1.8063966557448927208, -19.65451295888456329, 0, 0, 0.9404055233767310007, 1.0229997547271381109, 0.84839014691027592185, 0.9942253298077886603, 0.55270681506501917468, 0.71325376394101502875, -0.27008001161472772189, -0.36441609214674652861, -1.6858466263672904351, -2.2746949537899268101, -2.7024004611201863923, -3.6463202499480562579, 0.73789700429246496416, 0.99563659340566201816, 8.8487029815652924469, 11.939460983544531558, 16.241778413219694954, 21.914859168852931504, 0, 0, 0.091452250263845791256, -0.069826465452058242289, 0.20181123367547218472, -0.13689085681302756714, 0.50012121362724204499, -0.15708533369949770342, 1.2380919977577322655, 0.093217876961678852732, 2.4558884227495125785, 0.58186847095202909319, 3.1248015911458146832, 0.93273112726773044212, -0.80684053529361110524, -0.25468449792074498994, -9.6754590529148973843, -3.0541220021223365322, -17.759287695723489975, -5.6058354437652431201, 0, 0, -0.00032057317842933900735, 0.00025095691201626593508, -0.0006604553857512240455, 0.00049198690620599915858, -0.0011751018630891821651, 0.00056456602826813432217, 0.0020547291059278675364, -0.00033502584436379451204, 0.043190243671805170211, -0.002091240244288253107, 0.27856793393313283858, -0.0033522436217435750035, 1.1501216068412509763, 0.00091533825638770416853, 2.7780724886333088008, 0.010976540508122837117, 4.1023657110424904815, 0.02014742036749034293, 0, 0, 9.0759971803981566744e-07, -7.1050367876085636178e-07, 1.8698667331515860834e-06, -1.392902486538716717e-06, 3.3269224981118857968e-06, -1.5983868974364642471e-06, -5.7964722216058981582e-06, 9.4851778732840647118e-07, -0.00011258250904733756745, 5.9206732932833133743e-06, -0.00053727865043814320746, 9.4907982657877548258e-06, 0.00061975219556745361413, -2.5914854994384806915e-06, 0.029585633563949290115, -3.1076539587733474873e-05, 0.21558752218843252324, -5.7040932539508893209e-05, 1, 0, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=10 +knots=None +absorb_cons=FALSE +output=np.array([1.9320747025477182898e-08, 4.8242814281426965595e-08, -1.2568948282371909281e-08, -7.8978523641721503504e-08, -3.5770522726027550527e-08, -7.01473863118866388e-07, 2.1638270976696590321e-08, 2.2109425903379564006e-06, 8.5370349850805669926e-08, 3.744561791897189516e-05, -3.2925418782971613435e-08, -7.9813891850179092256e-05, -1.991767035296446912e-07, -0.0021868285157625511929, 3.7614188014338205365e-08, 0.0021874060835819046644, 4.688717754303082178e-07, 0.15874967738905676473, 0, 1, -1.4544731165165144453e-06, -3.6317372379498608116e-06, 9.4619516292459995175e-07, 5.9455330204143990165e-06, 2.6928184298539113977e-06, 5.2807216744776855019e-05, -1.6289371928530509096e-06, -0.00016644059132742171966, -6.4267121060004543239e-06, -0.002818920227187673988, 2.4786379329293728427e-06, 0.0060407977628119044478, 1.4994097295422416361e-05, 0.20920617714101982787, -2.8316102474873858596e-06, 1.0967921747761912865, -3.5296843934527352639e-05, 2.0750595382021144175, 0, 0, 9.7994633378747003421e-05, 0.00024468706579685965685, -6.3749578484895432179e-05, -0.00040057827261335182721, -0.00018142772925296013898, -0.0035578683345143034648, 0.00010974909140496827962, 0.011347453981486406438, 0.00043299755045772883848, 0.2521011214081396723, -0.00016699739084748591402, 1.1986460188118959191, -0.0010102222245463542399, 2.0307158061521746184, 0.00019077878093656664284, -0.33272379892704945226, 0.0023781128997935555708, -4.1474987648643217852, 0, 0, -0.0066281488228501295526, -0.016550113319571305159, 0.0043118860597063267057, 0.027486913394933615296, 0.012271386183288513286, 0.32813715189346348566, -0.007423195392682361074, 1.293350915313034033, -0.029287034456989179121, 1.9521712704316960263, 0.011295348749219022086, -0.66799495509124628967, 0.068329285161611297283, -4.0409215143626093791, -0.012903871453880378511, 0.76312128325689243535, -0.16085050450109564246, 9.5125283792626493806, 0, 0, 0.14341751361350341121, 0.77593360542645228861, -0.090432986778547594375, 1.1259563994195789238, -0.25736721450922656063, 1.1109363559631879603, 0.15568633342939960928, -0.56801737059939128027, 0.61423561827887318554, -2.241022016113413784, -0.23689682657495314544, 0.86431165517469521475, -1.4330669354534046889, 5.2285058979714911231, 0.27063229881828543277, -0.9873946118959923135, 3.3735101868301691219, -12.308160541801825616, 0, 0, 0.88922814381914494497, 0.26150528401135941792, 1.052718109833140403, -0.16738921270899279059, 0.90250428645253855109, -0.47638032258407536634, -0.44193283907468589033, 0.28817153685428037457, -1.7435755898887204118, 1.1369348754708179516, 0.6724577863061328431, -0.43849014288054521948, 4.0679186503944446684, -2.652571308655904847, -0.76821964733539216397, 0.50093366421426255286, -9.5760809678860194794, 6.2442835778727587837, 0, 0, -0.026500124336832579092, -0.021442252392463622551, 0.033954742484493150023, 0.014552615451508882013, 0.34654423116839672137, 0.041415928368598843579, 1.2822161222240113787, -0.025053284450302942821, 1.9082407187462107068, -0.09884374129233876316, -0.65105193196742539019, 0.038121802028613864521, -3.9384275866202003158, 0.23061133742043829487, 0.74376547607607035317, -0.043550566156846479138, 9.271252622511015673, -0.54287045269119871271, 0, 0, 0.00039179415524385585289, 0.00031701546211065640812, -0.0004962026403406965408, -0.0002151548273865228544, -0.0038300099283937543392, -0.00061231858622874310843, 0.011512077618593902564, 0.00037040318349176827237, 0.25275061773382700991, 0.0014613667327948419179, 1.1983955227256271048, -0.00056361619411026103298, 2.0292004728153583137, -0.0034095000078439544229, -0.33243763075564392029, 0.00064387838566091657681, -4.1439315955146351911, 0.0080261310368032780238, 0, 0, -5.8151558545865533576e-06, -4.7052624338916936783e-06, 7.3648257648012915326e-06, 3.1934086748705229843e-06, 5.6846444389557634026e-05, 9.088262200756952661e-06, -0.00016888399711670137003, -5.4976630258790269937e-06, -0.0028285602953466680576, -2.1690153357751540543e-05, 0.0060445157197113750028, 8.3654030236365385289e-06, 0.20922866828696309871, 5.0605078372050556115e-05, 1.0967879273608196478, -9.5566845852699449579e-06, 2.0750065929362113692, -0.00011912684827902968556, 0, 0, 7.7246635846578622837e-08, 6.2503173239414331853e-08, -9.7831946065279388105e-08, -4.2420200453005213882e-08, -7.5512964720790736305e-07, -1.2072551420034312034e-07, 2.2433999968030079565e-06, 7.3029164546350807041e-08, 3.7573673443748081119e-05, 2.8812493074646954793e-07, -7.9863279978354456061e-05, -1.1112328839252804556e-07, -0.0021871272808178477895, -6.7222137441255028355e-07, 0.0021874625048639208952, 1.2694788454839182361e-07, 0.15875038069671990049, 1.5824422420772902814e-06, 1, 0, ]).reshape((20, 10, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=12 +knots=None +absorb_cons=FALSE +output=np.array([-3.6802322454608713193e-09, -1.1576165417746612791e-08, 4.0903329323109361483e-09, 4.0685732923556337374e-08, 1.7703518712245050831e-09, 7.8790091688795366003e-08, -9.3409196093845724123e-09, -2.611905916838673793e-06, 3.0933985220706180644e-09, 5.5610182678566951338e-06, 1.6919855821268632348e-08, 0.00016301336905366541432, -1.4352199746873791695e-08, -0.00096630860312933643686, -2.1293612839737406843e-08, -0.0074687624866493825676, 3.8568109059678503697e-08, 0.11083787128447247783, 0, 1, 1.4460849968779115402e-07, 4.5486583496536781572e-07, -1.6072271234908852579e-07, -1.5986770411107210554e-06, -6.9562981611555798878e-08, -3.0959233519658970583e-06, 3.6703563262437939878e-07, 0.00010263042405151407538, -1.2154986136127495596e-07, -0.00021851080443170532329, -6.6483710865399255783e-07, -0.006405334542942880266, 5.6394540729725285131e-07, 0.039346935329722818042, 8.3669649095786947889e-07, 0.58363014399245827235, -1.5154685940796589346e-06, 1.5869193120902693739, 0, 0, -5.4865400297656400151e-06, -1.725790404504806206e-05, 6.09792368290666473e-06, 6.0654841172256407627e-05, 2.6392645247385444743e-06, 0.0001174613348200111455, -1.3925569348217424364e-05, -0.0038938646832389072101, 4.6116803743272812418e-06, 0.008333356501832860086, 2.5224350005560149737e-05, 0.3457041582444345118, -2.1396453586193263292e-05, 1.3943941859934374516, -3.1744806151200007029e-05, 1.0659241155872372087, 5.7497858861837635377e-05, -1.8607361322222011335, 0, 0, 0.00023256871331852414829, 0.00073154456479976239392, -0.00025848462913861898265, -0.0025710954976070178948, -0.00011187567233550075858, -0.0049790635547287236118, 0.00059029037024653681354, 0.20118319692573388702, -0.00019548432437836398673, 1.1583324452787904235, -0.0010692339057516754303, 1.5709796196933376589, 0.00090697336629712820011, -1.2050531219054301246, 0.0013456292455859321117, -1.7878746869280606191, -0.0024372743079464744345, 3.238292460253569427, 0, 0, -0.0096036016628270864243, -0.030208115694913360155, 0.010673763374229244122, 0.11304537553087100343, 0.0046197503419112585787, 0.84717528615215309529, -0.024375220124670693433, 1.6209052609300536041, 0.008072253382102512545, -0.43744451537192496904, 0.044152527520605257261, -2.3926752654369827233, -0.037452204143992279262, 2.0295771844456078625, -0.055565888790719414336, 3.0111781856549497682, 0.10064385386396751398, -5.4540039558593536029, 0, 0, 0.10357732090048776818, 0.85603572021517670976, -0.11294852267110891408, 1.0800087615333373581, -0.048885660842739625531, 0.2401585690492896441, 0.25793574452960393861, -1.2534276012546561319, -0.085419646489135220291, 0.4150930798449654624, -0.46721691129938069942, 2.2704203849822679473, 0.39631486857335096463, -1.9258749730998911964, 0.58799177288976445244, -2.8573206043806020915, -1.0650015567431445618, 5.1753290302415839719, 0, 0, 0.94933893888308096276, 0.20425894956750886844, 0.97636209569699528021, -0.2257137560392956932, 0.19529887869007700463, -0.097691991575737782694, -1.0167341121476407562, 0.51545291906204826482, 0.33670815416251220764, -0.17070067666802030137, 1.8416810448534708389, -0.93367563771983919096, -1.5621985497383736874, 0.79198660986818203433, -2.3177527963386914678, 1.1750293712615387243, 4.1980354999103974833, -2.1282748625244334306, 0, 0, -0.044595007867203530216, -0.03154770903003507182, 0.12905602059221518707, 0.036023951388023812969, 0.85410491166502156002, 0.015591657403950714977, 1.5843424307430495901, -0.082266367920763708299, -0.42533613529877184467, 0.027243855164596028628, -2.3264464741560830774, 0.14901478038204274412, 1.9733988782296159048, -0.12640118898597454966, 2.9278293524688816518, -0.18753487466867790889, -5.3030381750634045801, 0.33967300679089129645, 0, 0, 0.001079949373603220162, 0.00076398525832885994229, -0.0029588224413149436312, -0.00087238562334283919521, -0.0051468770632319233924, -0.000377580394132319148, 0.20206863248110379372, 0.0019922299995820589268, 1.1580392187922230463, -0.00065975959477697777422, 1.5693757688347129697, -0.0036086644319118939793, -1.2036926618559800062, 0.0030610351112528135301, -1.7858562430596849335, 0.0045414987038525046412, 3.234636548791644195, -0.0082258007893193495902, 0, 0, -2.5477139138140648842e-05, -1.8023214052146796125e-05, 6.9801726696616189999e-05, 2.058049242980996096e-05, 0.00012142023160711750383, 8.9075177709926672744e-06, -0.0039147530372612262053, -4.699879655023364312e-05, 0.0083402740223943259285, 1.5564421263354520723e-05, 0.34574199476944195153, 8.5132181268765064475e-05, 1.3943620913130563288, -7.2213030853402265731e-05, 1.0658764983780117941, -0.00010713872076029942911, -1.8606498854339041937, 0.00019405527365870157302, 0, 0, 6.7149986095353481289e-07, 4.7503707792034416037e-07, -1.8397611096343514486e-06, -5.4243915417817383743e-07, -3.2002678243831975437e-06, -2.3477506293900330442e-07, 0.00010318097750045069814, 1.2387452601072785849e-06, -0.00021869312922374677631, -4.1023078209430247345e-07, -0.00640633179860586148, -2.2438252417072174446e-06, 0.039347781247833550633, 1.9033157496282319598e-06, 0.58363139903719374324, 2.8238506569827991151e-06, 1.5869170388873774513, -5.1147065050188478719e-06, 0, 0, -1.7089420375974873326e-08, -1.2089516008577751082e-08, 4.6821232322022749866e-08, 1.3804873646549429766e-08, 8.1445619495631410706e-08, 5.9749375653827772664e-09, -2.6259172962527552498e-06, -3.1525603681672934994e-08, 5.5656583656398050473e-06, 1.0440220011988337053e-08, 0.00016303874883739764194, 5.7104513396781534087e-08, -0.00096633013142895208495, -4.8438674145699212406e-08, -0.0074687944270686538323, -7.1865943334113596723e-08, 0.11083792913663595425, 1.3016736807641509225e-07, 1, 0, ]).reshape((20, 12, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=4 +knots=np.array([-2500, -150, 300, 1500.0000000000000000, ]) +absorb_cons=FALSE +output=np.array([-0.0051418610449036764379, -0.0051207276560822079237, -0.0051517581620670691717, -0.0051036969019558836927, -0.0051724091286762859804, -0.0050616345732373531699, -0.0052108015793779615538, -0.0049476511776847470828, -0.00525764719160080711, -0.0045887810243909702562, -0.0051780211262217532009, -0.0032118234048454639452, -0.0042344880890217376918, 0.0033309098171163710467, -0.0002048781708894489937, 0.036873131791193267115, 0.0053670164361401782871, 0.19556964857406355929, 0.00027785197169554257113, 0.82912284340298503249, 0.65949448911253716332, 0.6654093842010145865, 0.65653556733089935005, 0.66984284447353759084, 0.64987461295218140744, 0.67980900603329297294, 0.63487206047522759533, 0.70218091452751663084, 0.60105778412747068451, 0.75218902517658670082, 0.52490094418674082544, 0.86229539201840321727, 0.35569403068909899446, 1.0895778496922625678, 0.014595118281322956924, 1.4713138143490975818, -0.3821845778229204238, 1.7530984807387750557, -0.019785804601727036839, 0.46986487896086814864, 0.35950128095327349431, 0.35338118891054576265, 0.36256112212690350116, 0.34879091185540550546, 0.36944502095300485456, 0.3384628569483467686, 0.38492806794448852781, 0.31523169436694697954, 0.41971361558839714867, 0.26307215994266325287, 0.49746707294522052312, 0.14713121281897215131, 0.66691371985704051006, -0.097089653687300894735, 0.9873402560545572193, -0.53105535871660392022, 1.2102463767433073727, -0.99135819513191647534, 0.044702741392222536398, -0.3124421698702265493, -0.013853909020907106964, -0.013669845455478047552, -0.013944931295735877447, -0.013530059426987159701, -0.014147224776509979491, -0.013210228408402318115, -0.014589326840338213628, -0.012464957716778975183, -0.015513752524267036478, -0.010672404094858929657, -0.017189996005739616169, -0.0062147814325298833885, -0.018373262457117778973, 0.004180894177922047858, -0.0017304961649907309174, 0.022868412576313085216, 0.16657118464347281384, 0.042690065819077735454, 0.97480521123780894399, 0.013454447506373390722, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=5 +knots=np.array([-400, -50, 10, 50, 100, ]) +absorb_cons=FALSE +output=np.array([-0.00093170433340244659687, -0.0012410506081968345274, -0.00078243418040293037045, -0.0014789118938009710238, -0.00046560203080319340248, -0.0020151841680895970881, 0.00010431589287147467922, -0.0030688678143442819739, 0.00055449747551044887423, -0.0028609656322684854333, -0.00014909864114985113439, 0.026923379556954812886, 0.00037005603844857983247, 0.24511712352852058072, 0.0023876748113693508323, 1.1555668732201982429, 0.0069273170504410850126, 3.402689781560706006, 0.017141512088352486159, 8.4587163253268489171, 0.084019186191167327671, 0.11446091282800011091, 0.069879045425061070418, 0.13908517998091646239, 0.040857714895860555715, 0.19963820957805075706, -0.009029120060764306635, 0.3576254481931359086, -0.047994837046959955285, 0.77395141822244861718, 0.012905315717303777676, 1.5659844614539342178, -0.032030405994604847775, 2.0431817208334850378, -0.20666651978408043244, -0.51809792415464139825, -0.59959777581040041294, -8.0018873070243543566, -1.4836931018696206674, -24.840413418481212204, 1.0495495283018867472, 1.0438716260482179266, 1.049399522569444354, 1.0346122703952109756, 1.0414030908228715244, 0.99920617535829048261, 0.98168936282733698651, 0.85586872666349445016, 0.66418975301951443946, 0.32605391435347208517, -0.11777757243608029392, -0.85263295720592457982, 0.29231857203837463555, -1.8526421434409372502, 1.8860972902309971477, 0.52133890068006216723, 5.472099406164398161, 8.051943344140203962, 13.540604167014549830, 24.995803341925523000, -0.15192966618287376268, -0.17994115928882439825, -0.13573193509615386065, -0.19726850771611939561, -0.093692687860718673609, -0.2254589026981791422, 0.031190848164371551277, -0.24103262443025505468, 0.43031985595064925487, -0.11127445668091072439, 1.0214738883945315706, 0.29750331491431342146, -1.0287095298822455103, 0.64642959712677627859, -6.6374375162553720386, -0.1819071733449817152, -19.257075485594906894, -2.8095088468476898669, -47.65126091660886232, -8.7216126122287835898, 0.019292656023222061468, 0.02284967102080309731, 0.017235801282051283617, 0.025049969233792938189, 0.011897484172789671297, 0.028629701929927506981, -0.0039554068238157324977, 0.030607317387968895062, -0.047069269398714280728, 0.014130089737258502702, 0.083547466965394667771, -0.037778198719277893136, 1.7680513078000272831, -0.082086298047844605263, 5.9556190709970859842, 0.023099323599362758808, 15.377646538190468561, 0.35676302817113519916, 36.577208339375580692, 1.1075063634576232108, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=7 +knots=np.array([-1000, -500, -250, 0, 250, 500, 1000, ]) +absorb_cons=FALSE +output=np.array([-4.3178765217391302305e-05, 6.5885993478260890537e-05, -9.6313081793478265121e-05, 0.00015008344269701090522, -0.00021248546106063178089, 0.00034663246069176721631, -0.00045706603540709121736, 0.00082099033067846731351, -0.00092573826895791448514, 0.0020071162494608137464, -0.0016063078222631245202, 0.0047785217809616390913, -0.0016924900384041397308, 0.0058508393862588175052, 0.00037271449492305578147, -0.023079518000319019372, -0.00039460853415255482939, 0.96024636175750266442, 0.0010388953913813049352, 4.2828168145345602014, 0.0006476814782608695956, -0.00098828990217391310055, 0.0014446962269021740039, -0.0022512516404551634157, 0.0031872819159094768759, -0.0051994869103765082446, 0.0068559905311063691277, -0.01231485496017700916, 0.013886074034368717928, -0.030106743741912203594, 0.024094617333946868887, -0.071677826714424588972, 0.02538735057606209683, -0.087762590793882266915, -0.0055907174238458371557, 0.77073211937350760703, 0.0059191280122883223325, 0.065812149128730040859, -0.015583430870719573377, -5.436090696106786524, -0.0031088710956521745793, 0.0047440075304347817733, -0.0069345418891304357392, 0.010808468249184780344, -0.015298953196365492127, 0.024985562378791605076, -0.032908754549310574589, 0.059430528454937264771, -0.066653155364969851604, 0.14814853819552065151, -0.11565416320294498453, 0.38547179702354089637, -0.12185928276509808144, 0.89303994817074205947, 0.026835443634460023205, 0.3158234170040984945, -0.028411814458983948584, -0.033037325841022327499, 0.07480046817945394666, 2.7299491962930431121, 0.99996527520000000333, 0.99992195380000004068, 0.99982468157500004047, 0.99960649719062499852, 0.99911787098710935773, 0.99802618626118166922, 0.9955959649107849474, 0.99021595070231704927, 0.97840786415926050967, 0.95284186025012007626, 0.89870074544754108281, 0.78829881686806935193, 0.57842205914062527761, 0.2362299420741153233, -0.10286920059876342171, -0.080364133358400105522, 0.1089119554261051559, 0.0088355638877152739563, -0.28673512802124018206, -0.73010269203186040077, 0.0031519622956521736561, -0.0046471747304347834143, 0.0071520025891304338586, -0.010320575886684784858, 0.016392005544802985134, -0.022542075546565051858, 0.038353001709637714323, -0.04736186631031753802, 0.093197128054721647961, -0.090485094976372942854, 0.23844273869784807229, -0.13266783181011393422, 0.6114558419262043909, -0.058789413728980027818, 0.96115953962745293016, 0.020964556528278284475, -0.40723600724543668194, -0.0023049297098387665911, 1.0721400439055068787, 0.19046157183439835214, -0.00065664547826086978963, 0.00096816140217391292219, -0.0014898486644021743334, 0.002150119976392662717, -0.0034132712039954154516, 0.0046962657388677176915, -0.0079705034644407205674, 0.0098670554813161497065, -0.019191613515453308236, 0.018851061453411026292, -0.047118889772279910766, 0.027639131627107058065, -0.098264441613631667294, 0.012247794526870834503, 0.1283332564542301879, -0.0043676159433913086874, 1.1341990151205716408, 0.00048019368954974300367, -2.1349300292885819985, -0.039679494132166315268, 4.3776365217391304853e-05, -6.4544093478260855155e-05, 9.93232442934782663e-05, -0.00014334133175951084961, 0.00022755141359969430562, -0.00031308438259118116136, 0.00053136689762938121937, -0.00065780369875441000935, 0.0012794409010302202311, -0.0012567374302274016227, 0.0031412593181519930102, -0.0018426087751404706099, 0.0065509627742421101121, -0.00081651963512472227127, -0.0082410361884569308111, 0.00029117439622608720607, 0.18701233167960798487, -3.2012912636649525446e-05, 2.2892691807041996022, 0.0026452996088110873087, ]).reshape((20, 7, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=4 +knots=None +absorb_cons=TRUE +output=np.array([0.17237877473947216256, 0.16160585322933293528, 0.17775653635702576283, 0.15351565450517737355, 0.18982763251278575445, 0.13530235680671015563, 0.21678099966619068795, 0.094474101590757947333, 0.27612342080317897608, 0.004254035614190725817, 0.4030409383688886571, -0.19022791859524765257, 0.65608982528520065625, -0.58588986559744449245, 1.0712259966408619327, -1.27728761497709975, 1.342827694119810289, -1.9788260499202323661, -0.052195429016186831173, -0.97077694213337639706, 0.68714996318883114768, 0.60683822144440202617, 0.72724727397328958745, 0.54653827251673237075, 0.81726443453130048766, 0.41083008335212661821, 1.0183156414681064916, 0.10689042936382432691, 1.4611707976831045386, -0.56312355687140791538, 2.4093551078217010364, -1.9991227596244038889, 4.3052173449842321418, -4.8778668329561920558, 7.4441765017641099433, -9.6842706472508055526, 9.6670625693150959989, -13.322034134461750554, 0.012161980255413960134, 0.22619930950229019673, -0.010768222248548299166, -0.01771835491152162767, -0.0072960943160139245939, -0.022933439873231927647, 0.00050471399250212036977, -0.034662450006663660107, 0.017964357449119585514, -0.060912800432191181732, 0.056636870493901259049, -0.11877531418126709151, 0.14054140101632672799, -0.24279484616490168425, 0.3140184596633784353, -0.49144965505677373763, 0.63173409697146676312, -0.90678479147331569887, 1.0347141866437283841, -1.2221561304860752983, 0.99694564370894334093, -0.056807630788862507887, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=7 +knots=None +absorb_cons=TRUE +output=np.array([-0.088612856492796668317, -0.10148345379387192777, -0.074820024844059834779, -0.097934158724637176974, -0.030963004348234846042, -0.058173986143542688598, 0.090101482080220576809, 0.10049075761090919823, 0.29596829876665797787, 0.41518677441788176541, 0.43034390532152527742, 0.83452635605264402496, -0.13348462782429343365, 0.98208889847295099962, -1.4362329672138189895, 0.92468785756571492129, -2.6216702734870915847, 0.6954743327776672368, -0.0022196047790754855691, -0.12327370541474826082, 0.24123862297275155964, 0.35840804363927752929, 0.18093342115646737778, 0.44250759269715284061, 0.043937153723061256327, 0.6202158021725746595, -0.24740540994207005365, 0.96645134975980595549, -0.72475992234705299833, 1.5060196314875564649, -1.0261673763863199405, 1.7262771004734287494, 0.32934388972170997034, -0.37505857126375657939, 3.4434877057227697428, -4.9947636565362447669, 6.275814996477087071, -9.1524782805583591028, 0.0068271591356862497413, 0.37917074789447108296, 0.35954055514606403365, 0.35954551446237459356, 0.35744096324407559351, 0.35584226884375003142, 0.34885947617865670223, 0.33862610062421411028, 0.32049681236018934261, 0.28089301373203690027, 0.25602145147051952323, 0.16597482970505655908, 0.12171945403305862998, 0.0018741765108557348514, -0.13785069799652086009, -0.10675519142579256715, -0.57612609827379823724, -0.22195090041542500647, -0.96232722728117126021, -0.44017455467682947701, -0.01453255272801050671, -0.80711739351329703229, 0.39138909874594340899, 0.2727563805116787754, 0.45531894883729062684, 0.19274617399836088683, 0.60538032158012156092, 0.036358318155975434538, 0.93314031181054180042, -0.23999550325584054211, 1.4531806967029836652, -0.67840171762003531608, 1.6665321594967388297, -0.95105942435581225514, -0.35463732068059222735, 0.31454920667339703044, -4.8088313747127671149, 3.2255742320619229524, -8.8757338424365990193, 5.937464168828833877, 0.0075040642903919140341, 0.41676510136746514057, -0.089133365834868971689, -0.10118952771068721874, -0.075725350737607874385, -0.097115177460207771643, -0.032342847263930989132, -0.056715061432944156861, 0.092352440078496370046, 0.098331113369192327256, 0.3400969886051333213, 0.37108103090272787083, 0.71036876576058238797, 0.55444750827998945386, 1.0162219858335352907, -0.16763759291903618243, 1.3370398275661443677, -1.8484727482821472488, 1.4719012302123679614, -3.3978810087925515049, -0.0022219907599747576801, -0.12340621941421109353, -0.013194863919370570376, -0.015072699772667915927, -0.011151244212216769591, -0.014503828881363881043, -0.0046275650331869689486, -0.0085121840139092009442, 0.013410603654954418931, 0.014660726583422474187, 0.044001710617309369722, 0.05545171716304433257, 0.063619527459568614436, 0.082887169332405197242, -0.019275003418586279108, -0.025046122964883565931, -0.18452246030655442, -0.27630735647963872159, -0.17524590664413686181, -0.50790642667837671009, 0.99966985744385294943, -0.01833564992966553106, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=10 +knots=None +absorb_cons=TRUE +output=np.array([0.017741203875868801626, 0.059666517581418020144, -0.0073055449468428850998, 0.071233532376632907601, -0.061951321114274808532, 0.023459686026844089879, -0.15952965061095217281, -0.21534242305337428225, -0.20894123625115404441, -0.40851053368902323637, 0.088769309083260417026, 0.1702312769628678002, 0.44867980227835829732, 1.1139500668975872433, -0.14345767930218020214, 0.86682083739859494553, -1.1837156997359956634, -0.21597943647408635037, -0.017918712309548733702, -0.23789999499399971938, -0.0050889918235734665428, -0.017199613011022536063, 0.002072270281447358229, -0.021223643286449593581, 0.017930549906902432111, -0.010400764195970725601, 0.046747049525783831991, 0.07425318574607586708, 0.061514150450350559007, 0.37070324197740467387, -0.026117581474140658115, 1.1506456698664466742, -0.13217536320689113327, 1.766217994670280067, 0.042129159012710096222, -0.26549271162309995287, 0.34842176083555986832, -3.4777238134306913686, 0.0052384550413758917964, 0.06954899473750200678, 0.040717410233940966313, 0.14267724274658066808, -0.01518518709909348792, 0.21755481940124130058, -0.15305036931474685913, 0.39059745188013861306, -0.43311720487012722591, 0.71916259556541839437, -0.58682103919738470843, 0.86959977149390199624, 0.24816600986825945729, -0.22985936815572685643, 1.2655729988498243266, -1.6266494012894197052, -0.39570727271363553834, 0.14945216327392790712, -3.3194533089504827394, 3.3989844591011317831, -0.047815351859148348679, -0.63482641896460045849, 0.12003828098968173654, 0.69730715192779646472, -0.080805333880490451404, 1.032100885251629574, -0.17573134714242774623, 1.0800934656851248761, 0.36589399540256600796, -0.28448323213545234633, 0.88954585755350989995, -1.7064483114238784278, -0.35386353683003346493, 0.6479603434190704947, -2.0242657690367202861, 4.0363385548625183574, 0.45966058247434787853, -0.6843648579769759932, 4.9332279555632334578, -9.2892931271418373029, 0.023611216265584832746, 0.31347722617275158852, 0.88792799224608875974, 0.25713275781065136893, 1.0532535169725301127, -0.17260864810915746426, 0.90704417033506612444, -0.47809553851771402488, -0.43024289925585679217, 0.30393926379684116368, -1.7282652053936073955, 1.1666632610962044403, 0.66595310521671158277, -0.45052173959023528171, 4.0350412627641443208, -2.7188693891544946091, -0.75770752213855696588, 0.51778556938925135444, -9.4893428981139695821, 6.4121669845342363914, 0.0013130525053329394382, 0.01743290360653331969, 0.018394340893766202016, 0.12954185558052447313, 0.015467038664664091788, 0.1947806488224434196, 0.18978123265431517952, 0.10064263984709266586, 0.87856041959654240792, -0.56951570226238645844, 1.3795704170465219462, -1.1253701882691806713, -0.4264441361865796698, 0.45357497790875550558, -2.8031655399252684013, 2.5198958573805381178, 0.38077992198436172444, -0.6254498513067092702, 6.2761716348405380828, -6.3399143661490446888, -0.045339936718340946575, -0.60196126440255459666, -0.004758953821358206937, -0.017005411359244829855, 0.0016248940817804027534, -0.020892741105429570719, 0.014155429774586492792, -0.0074074070841472963028, 0.057823550154750644192, 0.062836648910594553041, 0.313405031875580109, 0.11923488274498127149, 1.1726262403941665191, -0.048228614408167384819, 1.8989517069621104639, -0.26605941795394616456, -0.29079224977894058135, 0.067405260889645518541, -3.8003055548041984046, 0.6731217514912637423, 0.0052018569797349914138, 0.069063096056237921472, 0.017736305328008575982, 0.059663635167637223133, -0.0072989048214304030199, 0.071228621002306605203, -0.061895289364833461221, 0.02341525749747295701, -0.15969206961095888664, -0.21517495710840772727, -0.21175703601763257167, -0.40570100515546192455, 0.094808655216413129097, 0.16419386720169948379, 0.65787987528453284458, 0.90476706770574533145, 0.95333742847376501395, -0.22997392252730572415, 0.8913620730776831147, -2.2910886491383859465, -0.017918169107386142797, -0.23789278310346156919, 0.0060750632566522310557, 0.020430784619126868273, -0.0025017991326720841194, 0.024387881029101547703, -0.021213459590422957535, 0.0080142623794636578399, -0.054619250223539139721, -0.073674968074426458453, -0.071500525070803497285, -0.13890622902065649646, 0.030313398118739860038, 0.056217781624179681554, 0.1514331690285295462, 0.30977852573253761292, -0.046930667126897918084, -0.078740760116175548267, -0.2465351039505715991, -0.78443722293869766471, 0.99386473410822107066, -0.081455614651688740269, ]).reshape((20, 9, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=12 +knots=None +absorb_cons=TRUE +output=np.array([-0.10472685656120690745, -0.12767819762829035746, -0.076360123823526582232, -0.10958044510013424666, 0.0027880985603357523288, -0.00047490167664404706613, 0.06928482401745712782, 0.12032832514458154105, -0.15700287132688625635, -0.1737016309573724826, -0.34110464392275169354, -0.43703758617891158567, 0.21658232947898950482, 0.33207321984948795501, 0.31440967571649758305, 1.0125703207549268114, -0.77927839590651259982, 0.57499654812351752575, -0.03855715180341089815, -0.29753053676014623585, -0.045155067335396106842, -0.055061683622734447496, -0.032913973166337623377, -0.047180638471765484754, 0.0012046656812917998312, -8.5942102116568291834e-05, 0.029855775209106073798, 0.047937464934110683712, -0.067681928151560877271, -0.066458149628327731206, -0.14703046798660462935, 0.16005131398107033669, 0.09335066435731875778, 1.5205934362940900506, 0.13551522132064452997, 1.2508474777651827914, -0.33590194032153924963, -2.2969931440729616234, -0.016622640017795731193, -0.1282704446656750541, -0.15034574662694516478, -0.18284705677723475659, -0.11005017611978802627, -0.16012547886604538983, 0.0038970012572561371633, -0.0056574341249261998407, 0.10020869531895890137, 0.37404580513022472887, -0.22593678600553301905, 0.90889537861179725553, -0.49151450544890296079, 0.95180903084537338277, 0.31231202672612079496, -0.78416614637393700082, 0.4534081611517823962, -1.1711369929499528819, -1.1228952128467266647, 1.7833321983277987677, -0.05543814773678283625, -0.42779461349253811164, 0.021352229303511102015, 0.007531901115204664085, 0.033244696218130601051, 0.14543534382436593133, 0.0037956069961920194805, 0.8473147453077168878, -0.044854732714249959113, 1.5853682337831724869, 0.054480061579266131355, -0.38616534110945410774, 0.14497807394687750593, -2.2653864188032963867, -0.10147073278861845624, 1.9430514052120930746, -0.14850072666747962669, 2.8843894925937085816, 0.33098715709405579499, -5.1548937962780287947, 0.011396952652503542641, 0.087945848734329423735, -0.065952557774967432436, 0.64935218850878217989, -0.23655843353990058109, 0.90262481725902277141, -0.044372232611305732763, 0.23939481976571783117, 0.37009197410777977533, -1.0588087616813195435, -0.33957241343679639423, 0.13426223409097867711, -1.0193888969785738219, 1.5733219045695456817, 0.74691289987499476233, -1.4520157873552757, 1.0969502242749886722, -2.1629612193760392458, -2.3264786688505232348, 3.5372496286723378311, -0.062415510749811636826, -0.48163620876963536555, 0.8195140136919921714, 0.045981988292849676481, 0.88170239584467990923, -0.36155327574779005939, 0.19875523391830787756, -0.098276866020166997462, -0.93084557008965973512, 0.66449081424484612857, 0.14207954819710574834, -0.38575918922177282466, 1.418831177364036078, -1.467509312217160522, -1.2937127610296201841, 1.1548650229305499337, -1.9279955842607379157, 1.7067654635554521114, 3.232004184432778704, -3.3827058656451867158, -0.047797409383925140713, -0.36883400885657852131, -0.021262964105923369551, -0.0031022854611233788291, 0.1460681949195489493, 0.060436933823290558965, 0.85348373794725573838, 0.015696770625561979468, 1.5689066026927753761, -0.10905135306422376884, -0.39035761984884714826, 0.065894018981400556689, -2.2504521949512743539, 0.2449549909100549594, 1.9251468021185453861, -0.19161744080459083839, 2.8577824618961185088, -0.28309810920621092389, -5.1294237100882460467, 0.56511845971327800964, 0.0085901166188240788563, 0.066286587283785933233, -0.14931374206792483172, -0.18258953057237148343, -0.11261589846568037521, -0.15823359174408363481, -0.0011429154130191262681, -0.0010551192149562264085, 0.30156489541842562696, 0.17464289155956300159, 0.93257469826065064744, -0.24979099176207356092, 1.0795318316732362973, -0.62202008893514815213, -0.89266942187285236443, 0.42343196160757057278, -1.3343479845023715757, 0.62052301130682563368, 2.1155524024387766246, -1.4614021376163455201, -0.055370175087794709645, -0.42727009501042717554, -0.045179413406039932444, -0.055067758936182993612, -0.032853445083453579334, -0.047225270074522207597, 0.0013235626049733512782, -0.00019451554100623699175, 0.025957829199430799971, 0.051789330864583066338, -0.059352795367343585964, -0.074783156665720870726, 0.19867211632366271745, -0.18558562156573668589, 1.4877431595022336808, 0.12613921140813655342, 1.2014365403948221722, 0.18483406256944329149, -2.1966417328137768372, -0.43610504124242488455, -0.016624243563923207095, -0.1282828186071544585, -0.10472621487286955244, -0.1276780375015148794, -0.076361719159604879437, -0.10957926874689910557, 0.0027849647992298789088, -0.00047204001118300933926, 0.069387562012853995497, 0.1202268016798509892, -0.15722127080697423374, -0.17348334021941591576, -0.34750993698157911505, -0.4306340234217196361, 0.25592930937433366889, 0.29272786696227376391, 0.89803989341652912248, 0.42894253042841035128, 0.80764101265733667656, -1.0119267694495412968, -0.038557109538814519911, -0.29753021062070239555, -0.052405524507834276571, -0.063890551260129033184, -0.038210563318028127611, -0.054833362353974436643, 0.0013952838636999886825, -0.00023608614675063352537, 0.034667393120659889538, 0.060161039317539917459, -0.078558784282471219584, -0.086811135096279259948, -0.17052577031441601418, -0.21548879873646650807, 0.10741142530502149899, 0.14648050866337228304, 0.14986173697025292895, 0.21464206783358963371, -0.2791130852403586049, -0.50636714208926458802, 0.98070595851787800701, -0.14888461024604163208, ]).reshape((20, 11, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=4 +knots=np.array([-2500, -150, 300, 1500.0000000000000000, ]) +absorb_cons=TRUE +output=np.array([0.026705483244849264474, 0.029839625165101336945, 0.025137490946490849419, 0.032188537945938233698, 0.021607394654091297004, 0.037467894551815809911, 0.013655036980899055293, 0.049314030316796791942, -0.004274510570643489521, 0.07576300788030972122, -0.044664576703176542272, 0.1337724526334178321, -0.13422281221596993328, 0.251582066127820414, -0.31121876398729647617, 0.43612872129651875097, -0.47985225176217655152, 0.49291724756068344693, -0.081762536217311512776, -0.57008353784816034882, 0.10575886843256800118, 0.098523720643000009534, 0.10937645918695998448, 0.093097559739294566405, 0.11751580252413190708, 0.080890140328454290808, 0.13582591101899046948, 0.053438242334149517465, 0.17698108482519578355, -0.0081682818617542177903, 0.26907668054096511856, -0.14499960251139776268, 0.47046169477357585587, -0.43311804519238522593, 0.8566919676788534721, -0.94615480020651354653, 1.1710825622951557268, -1.4966789629626817693, 0.019850657594207062745, -0.7294516591807701511, -0.065495278981390098183, -0.065538150305470069257, -0.065472788689835886844, -0.065568482416232795607, -0.065419575517949940524, -0.065631137544391218719, -0.065286317209239316806, -0.065744866169428622937, -0.064914403751873434034, -0.065874953263984459273, -0.063671751390664124703, -0.065668915889071088898, -0.058354957302844213951, -0.064207225531959205567, -0.028319888642541334034, -0.061612158154530236032, 0.15860060924423530215, -0.060152247616144620401, 0.96974734313860999624, -0.071414854005294861605, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=5 +knots=np.array([-400, -50, 10, 50, 100, ]) +absorb_cons=TRUE +output=np.array([0.21482323419002713472, 0.24750397604597326739, 0.19883614002139288202, 0.27258973708238182221, 0.16379621347999451242, 0.33062932586024107451, 0.090229192760086424085, 0.46740970723200020442, -0.043673571594035724697, 0.78496238070321600055, -0.14225997541844798144, 1.352022453322457185, 0.3403195391608931919, 1.6947780812699095865, 1.6168904854104195756, -0.12774151466578054226, 4.4891751144718545774, -5.4563586958095688928, 10.951815529860082776, -17.445747353383097789, 0.78661625540292257064, 0.77643763922916775311, 0.79017886797586167624, 0.76625062041079372577, 0.79428060270008205013, 0.73589687070232667754, 0.78216715039058581915, 0.63518798334179016329, 0.65550344333732102342, 0.30392043723920803, 0.19412499069407199159, -0.42254129005404528208, -0.4561535986725677172, -1.1523051841355156366, -1.7794911913869626563, -0.26332862233794968043, -4.7570007749943510333, 2.9350973501194954629, -11.456397338110976492, 10.131555788148743247, 0.21540397689706236584, 0.19368025263260429947, 0.22641495625607274689, 0.1776489056064568528, 0.25155233513796670941, 0.14240007942952948028, 0.30993541465339075058, 0.067271686044363815382, 0.44245515455816608608, -0.080352654001592846433, 0.58572719290272645676, -0.30336068837952584465, 0.016951242449324648714, -0.3319833812262538153, -1.5163892893085060276, 0.9143206895602743467, -4.9664054857636248386, 4.3390336686705470726, -12.728941927787642996, 12.044637871668662399, -0.24478425848794690967, -0.24574753349402200797, -0.24311234670203171748, -0.24447893336440842948, -0.23629987575155153579, -0.23582487990744877004, -0.20434545124769434854, -0.19103328802457081315, -0.055793360625630179783, -0.0080996580588084746144, 0.39680666612040660368, 0.39418417396254185059, 1.016323619403686207, 0.62129681239849587904, 2.2740869262794469741, -0.76498115062552785037, 5.1040543667499091995, -4.782338947138994989, 11.471481107808449096, -13.821393989294298521, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cs +nb_knots=7 +knots=np.array([-1000, -500, -250, 0, 250, 500, 1000, ]) +absorb_cons=TRUE +output=np.array([0.18906235677058036426, 0.18778525841872689695, 0.18966313099776943574, 0.18676205783172145081, 0.19092371457093507137, 0.18426214279619892999, 0.19330747373751991369, 0.17770329603139525809, 0.19648166130871616564, 0.15897921699813499785, 0.19369977803300092445, 0.10544719310340035234, 0.15040730339948449323, 0.026126087939682636485, 0.014566423626603465513, 0.71038417591713942656, -0.0044258520659356658661, 0.37477303749040830061, 0.11191608928948779123, -3.5378245461949706652, -0.1717114269621455025, -0.1641796852631927095, -0.1753614922544594612, -0.15832977440814030579, -0.18329458477753993173, -0.14455385888762556368, -0.19975455127362412577, -0.11060689494904693553, -0.23004851008792162603, -0.021054716326888309186, -0.26742505651389464338, 0.22697177040482915955, -0.233733177660145508, 0.79112685520733139199, 0.0087978598061598800584, 0.36982567289124945731, -0.019154626403592486805, -0.30951045809435018263, -0.039292263384108856716, 1.0312889189371063914, 0.550395590305010729, 0.54949597448884435202, 0.55072323934346578689, 0.54860843215917232119, 0.55116651719216569472, 0.54595839995564021674, 0.5507105841767095944, 0.53682026836985941021, 0.54272290221675423272, 0.50167044456244525019, 0.49401178725604522057, 0.36566698512261336385, 0.28011631034896739001, -0.03551586186561946773, -0.15096545178713224877, 0.063629989613431983675, 0.133595751562454651, -0.72836523541381203994, -0.59095728594899554764, -5.2594893416580195122, -0.095090409079557833283, -0.1030766681400390461, -0.090988045895585706324, -0.10887508452680887128, -0.081496719465270400784, -0.12133034539926186579, -0.058865730473533696421, -0.14644031510302549237, -0.0020110794198277630838, -0.18907748512879404834, 0.15000794369741921042, -0.22502359947941463769, 0.5462684746707909822, -0.11817275982033918769, 0.95064928964895001329, 0.052430922211166117175, -0.40184197213040517838, -0.16340199015776293856, 1.0056597912908593617, -0.79932421729955860368, 0.03971313277885706039, 0.041414831889495302975, 0.038837883046586599289, 0.042648161751521966589, 0.036811186605924875459, 0.045290364726222026581, 0.031978640736114505305, 0.050580394866669355081, 0.019931365400903504337, 0.059364669508446515911, -0.010779243096346216579, 0.065589985310555209974, -0.071477633391997127954, 0.036649613012278252355, 0.13265213083724519683, -0.017297782300268411959, 1.1319824969476413035, 0.066678235503076957458, -2.1076119483122943699, 0.36704351417936742497, -0.098246537944137943277, -0.098542071754031859698, -0.098088618240313230068, -0.098745945231101361905, -0.097708943948828105852, -0.099149563571540588747, -0.096734808676916902992, -0.099784603436978008828, -0.093975228815392539139, -0.099897241328297553542, -0.085336692453571283412, -0.094243446676616243751, -0.058668216352278305947, -0.060228845196453252575, -0.018756415239227899883, 0.03177289587597233872, 0.19240899911984374326, -0.16120768980326213859, 2.2227564852817449648, -0.98762351160861328037, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=4 +knots=None +absorb_cons=FALSE +output=np.array([-0.00011851815295720334641, -0.00012663567739435794201, -0.00010982693555193819436, -0.00012486657068400786952, -7.8574573747497574675e-05, -9.7456835655811038625e-05, 5.4155250158153698734e-05, 7.2018696214385270055e-05, 0.00068058583050101088829, 0.00094879940917660596233, 0.0037183147633434721069, 0.0053485055580019882915, 0.0183840295424396033, 0.02677749980087675008, 0.086329741280370991818, 0.12474145818684392872, 0.3626441834851739654, 0.49882426586368627808, 1, 0.99999999999999977796, 0.35563445619191813574, 0.46362413648379807718, 0.30171426160013936624, 0.54469854427884600856, 0.18065455579032740907, 0.72714127654712401583, -0.089788280381099649929, 1.1356676987661198375, -0.68581279037676712296, 2.0358855654123400036, -1.9635811732571735178, 3.963516193961472478, -4.5268166706294525881, 7.818994828526680152, -8.8143777554827753562, 14.211587381298102173, -12.092085343347227067, 18.821721967074164894, 0, 1.1102230246251565404e-16, 0.64448406196103913413, 0.53650249919359616069, 0.69839556533541258254, 0.45542632229183804826, 0.81942401878342008281, 0.27295618028853169124, 1.0897341251309387022, -0.13573971746233581825, 1.685132204546259338, -1.0368343648215159192, 2.9598628584938277974, -2.9688646995194716283, 5.5084326410870145807, -6.8457723283275555559, 9.7280480142024003953, -13.336328839484941966, 12.72944115986205027, -18.320546232937854114, -5.5511151231257827021e-17, 1.1102230246251565404e-16, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=7 +knots=None +absorb_cons=FALSE +output=np.array([7.6647956129152551405e-07, -1.1550595444117308123e-07, 1.9331333022628060142e-06, 7.0074370880358996831e-07, 4.276544862176869743e-06, 3.9889844050692401989e-06, -8.8286906818606534835e-06, -1.1748087754222518581e-05, -0.00018052779655174404014, -0.00026002337472508241234, -0.00087512057847980513799, -0.0012887090681721327309, 0.0010150616469118238505, 0.0015068191039899082179, 0.047197284048099072407, 0.069183314412051222231, 0.31391535501834866295, 0.43677277426050831188, 1, 1, 0.00010414066623386542833, -0.00015235200709813872134, 0.00016280595673724983273, -0.00043421191677436572591, 0.00016730985750816495974, -0.00096382547591343699107, -9.0113367500726122014e-05, 0.0019506005877063976872, -0.00042706768120516621842, 0.042844970995241649092, -5.2132124969551940641e-05, 0.27943748664501288914, -0.00082303187571104372, 1.1480003233353344161, -0.045428857401670741378, 2.6726262314060083014, -0.26572750370216563498, 3.4985477308433670096, 2.2204460492503130808e-16, 0, -0.031639925468625686167, 0.046730544589411379675, -0.049698223025307776413, 0.14261932064706925316, -0.051804308700160631163, 0.44426741959012128191, 0.029985561329029603028, 1.2694922528331589184, 0.18639387492323189477, 2.6501418567322971853, 0.29516026175368154094, 3.4280258862936845432, -0.075791571757795037079, -0.87883069340180242079, -0.70490461473281773586, -10.07981330853315427, -0.24791206297674328596, -16.148116252431378825, -1.7763568394002504647e-15, 0, 0.9404004428081522704, 1.0229943455861092438, 0.84837282177641593073, 0.99419676362025177774, 0.5526597738396983317, 0.71315928497606728698, -0.26997136265236038044, -0.36417829458474493265, -1.6835610275209540454, -2.2695939445331143602, -2.6912296816355203433, -3.6212526616197560081, 0.7249087759092099903, 0.96643128272326350725, 8.270877054240102666, 10.639570935701080145, 13.016842606390081727, 14.65915427188926401, 0, 0, 0.091455790248830992617, -0.06982269652782702174, 0.20182330529950023856, -0.13687095276618752027, 0.50015399051603726122, -0.15701950364285152673, 1.2380162944797474811, 0.093052186884682086543, 2.454295887293517886, 0.57831424352675386835, 3.117018133244208844, 0.91526479748152955729, -0.79779073451863469213, -0.23433512959673663545, -9.2728475980951614588, -2.148398325632811634, -15.512250940383852438, -0.55028191775469181835, -3.5527136788005009294e-15, 0, -0.00032121473415268157747, 0.00025027386535885344336, -0.00066264314064781932364, 0.00048837967193203002999, -0.0011810420579453353648, 0.00055263556817129462322, 0.0020684489017660893928, -0.00030499763304578722534, 0.043478860781959838278, -0.001447103346453879405, 0.27997853934107919116, -0.00018679973229867273543, 1.1484815005960040679, -0.0027726021640539499913, 2.7051067319414512369, -0.15316884735317959354, 3.6951325456543355763, -0.89607660680706602285, 4.4408920985006261617e-16, 0, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=10 +knots=None +absorb_cons=FALSE +output=np.array([1.7052675937596968357e-07, 2.1554130872244172271e-07, -1.8766481785820174288e-07, -2.5625876315796275659e-07, -1.3028476697477565147e-06, -1.8631355726629473538e-06, 3.6693095004218680534e-06, 5.3764688723538902118e-06, 6.0796641288638842218e-05, 8.9528552951850039502e-05, -0.00012887069103758740009, -0.00019001548651089925079, -0.0035275680979317425995, -0.0052024266625657657193, 0.0035256702065387685724, 0.0051982990643293265631, 0.2362999429577772037, 0.33323526570676581526, 0.99999999999999988898, 1, -1.5536971506019493448e-06, -3.7723308315471718504e-06, 1.0498525832867015351e-06, 6.1264614941971342081e-06, 3.3796481270836038393e-06, 5.4203738638415076344e-05, -3.5129100336125819986e-06, -0.0001705894910869632658, -3.7468155003797335172e-05, -0.0028884082386604389286, 6.8182896976374759469e-05, 0.0061884953395126701681, 0.0018130647206160395782, 0.21325100724817980247, -0.0017981230343969457908, 1.0927529255884664838, -0.10407530163420519731, 1.8409714784490120998, 0, -2.2204460492503130808e-16, 9.8228540403516947542e-05, 0.00024501849587308256306, -6.3993936608566740908e-05, -0.0004010047866267046901, -0.00018304683587852169481, -0.0035611604429654220016, 0.00011419029847733929632, 0.011357234442518585049, 0.00050617348630547251507, 0.25226492984599047098, -0.00032188615231765204967, 1.1982978420717516066, -0.0052489266241784434189, 2.0211806750240537411, 0.004422931600446426692, -0.32320182404955488664, 0.24763812678503760445, -3.5956683328958609636, 2.2204460492503130808e-16, 0, -0.0066286721449819972773, -0.016550854830837284648, 0.0043124327641686751103, 0.027487867638282981186, 0.012275008624007566552, 0.3281445173550811556, -0.0074331317422015865878, 1.2933290334062270688, -0.029450751586844299557, 1.9518047804513476429, 0.011641882663420602406, -0.66721597637483753829, 0.077812573766972065181, -4.01958848618877429, -0.02237250215454568425, 0.74181768967199701592, -0.70957277332229884426, 8.2779135644074397504, -8.8817841970012523234e-16, -1.7763568394002504647e-15, 0.14341792272585895951, 0.77593418511036460483, -0.090433414170275921995, 1.1259556534302141984, -0.25737004638880062179, 1.110930597939268516, 0.15569410127086877327, -0.56800026419801152855, 0.61436360579663806813, -2.2407355088743035054, -0.23716773295804302601, 0.86370268070518285697, -1.4404805919834702266, 5.2118285879993342391, 0.2780344963834942007, -0.97074031271066019144, 3.8024793557257794419, -11.342987956092152046, 0, 0, 0.88922860214889154484, 0.26150593343291061998, 1.0527176310249597435, -0.16739004844301930142, 0.90250111388972187321, -0.47638677331480472343, -0.44192413673958003129, 0.28819070120487033648, -1.7434322051050550328, 1.1372558503535050711, 0.67215428910723273859, -0.43917237872741754501, 4.0596131096953849138, -2.6712549469068491703, -0.75992694414757844257, 0.51959152341465042468, -9.0955055761811927084, 7.3255691971501466497, 0, 0, -0.026500878677340050649, -0.021443321240789712384, 0.033955530529363592285, 0.01455399094161052842, 0.34654945272048409688, 0.041426545282572141415, 1.2822017995143766278, -0.025084826033741181028, 1.9080047293712101286, -0.099372016748206934422, -0.65055242209998476177, 0.039244657655196912849, -3.9247579397546936697, 0.26136174203674272798, 0.7301169577862545168, -0.074258542407508620897, 8.480299193362036192, -2.3225008358095564631, -8.8817841970012523234e-16, -1.7763568394002504647e-15, 0.00039214456274060853838, 0.00031751196529807511858, -0.00049656870424369891313, -0.0002157937723172946836, -0.0038324354523821676718, -0.00061725037261922916041, 0.011518730827296382035, 0.00038505493185519946639, 0.25286023990754330493, 0.0017067621188927551389, 1.1981634895781139161, -0.0010852069418095661169, 2.0228506259066678652, -0.017693728679951309379, -0.32609759852778003042, 0.014908398163377523105, -3.7765166040071465048, 0.83470297192668896358, 4.4408920985006261617e-16, 0, -5.9639851815191078669e-06, -4.9161432965675507926e-06, 7.5203048707079762948e-06, 3.4647891244179194819e-06, 5.7876642390457017258e-05, 1.1182950401982235801e-05, -0.00017170982870512408684, -1.1720731503335203019e-05, -0.0028751203560827250441, -0.0001259174615164541705, 0.0061430676556425214963, 0.00022990175893332354118, 0.21192565237063318295, 0.0061175761298287428119, 1.0940951118875659187, -0.0060681567350964193963, 1.9189536363142121189, -0.35123535284248763588, 0, -4.4408920985006261617e-16, ]).reshape((20, 9, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=12 +knots=None +absorb_cons=FALSE +output=np.array([-3.5802310279784754585e-08, -4.6262647978685225562e-08, 8.4108204760015214405e-08, 1.1691317515513621075e-07, 1.3383585568882782416e-07, 1.9334920179260735574e-07, -4.203667662871902566e-06, -6.1443325945584099136e-06, 8.870740522791627539e-06, 1.2991653852666520431e-05, 0.00025968489610813934136, 0.00038043548035123880531, -0.001538951033558028092, -0.002254678726504918268, -0.011894389332899407696, -0.017426311105119260403, 0.16787692522771835435, 0.2391755401848442153, 1, 1, 1.5979133269021421162e-07, 4.7768854385179628339e-07, -1.9425098428285929911e-07, -1.661723207394062299e-06, -1.2068855552733148196e-07, -3.2055922738442340194e-06, 1.9511133954906500148e-06, 0.00010616629891630242227, -3.4565252886977172405e-06, -0.00022600512710102375891, -9.8259384682155117077e-05, -0.0066248710130454744813, 0.00057889080026267934753, 0.040648127270414641243, 0.0044706215223907566636, 0.59368709533766184094, -0.057610288739808043768, 1.4572996890794969183, 0, 2.2204460492503130808e-16, -5.5109923531389489217e-06, -1.7294660575127571221e-05, 6.1519217837447675384e-06, 6.0756378562884462338e-05, 2.7216035102121806338e-06, 0.00011763795929723115457, -1.6476765274556428198e-05, -0.0038995592960682475339, 9.9827397529189624958e-06, 0.0083454262915318017102, 0.00018240275250513114397, 0.34605772709145571353, -0.00095280597828643811414, 1.3922985845928645965, -0.007230442437518780005, 1.0497271498165361425, 0.092837834238923916397, -1.6519805635559703383, 0, -4.4408920985006261617e-16, 0.00023261122232546074806, 0.00073160846398710190595, -0.00025857850183971374958, -0.0025712720147247018071, -0.00011201881409144995674, -0.0049793706065786738982, 0.00059472548275806631952, 0.20119309669405308072, -0.00020482161298259401474, 1.1583114626193435903, -0.0013424798341694420094, 1.5703649598779465535, 0.0025261771262702131455, -1.2014100351887648799, 0.013860165507571235721, -1.7597171609627610955, -0.16373073924917352917, 2.8753824912917806955, 0, 4.4408920985006261617e-16, -0.009603671354393113202, -0.030208220454698501978, 0.010673917274214628215, 0.11304566492258458221, 0.0046199850162510491813, 0.84717578954956962445, -0.024382491288093402493, 1.620889030714223189, 0.0080875614382544102482, -0.43741011526471584858, 0.044600501680212630007, -2.3916675588781384221, -0.040106814398597687155, 2.0236045109652547325, -0.076082896664545401899, 2.9650152140638748044, 0.36507708741878691638, -4.859029716718211489, 0, 0, 0.10357736791963742529, 0.85603579089397319191, -0.11294862650356479739, 1.0800085662880150039, -0.048885819171624864121, 0.24015822941969325321, 0.25794065020098305707, -1.2534166511355830931, -0.085429974450229081984, 0.41506987095643310681, -0.46751914821604279027, 2.269740510670964273, 0.39810586745371900896, -1.921845360279117898, 0.60183408291126982981, -2.8261756066203411741, -1.2434080193894079258, 4.7739148511542310871, 0, 0, 0.94933899366841034695, 0.20425903192036259926, 0.97636197471447405682, -0.22571398353340010878, 0.19529869420992360118, -0.097692387302149769068, -1.0167283962036961498, 0.5154656778185841004, 0.33669612032614604225, -0.17072771898201555274, 1.8413288872915176686, -0.93446780726201750245, -1.5601117305432461446, 0.7966817961552830063, -2.3016241440126483653, 1.2113186062078835636, 3.9901615392586013975, -2.5959908523544878989, -4.4408920985006261617e-16, -8.8817841970012523234e-16, -0.044595107940631317778, -0.031547859459583466046, 0.12905624158450940131, 0.036024366939322927106, 0.85410524864504355769, 0.015592380256197772501, 1.5843319897343188796, -0.082289673658138620671, -0.42531415373425501825, 0.02729325191154396979, -2.3258032067945428878, 0.15046179406667054002, 1.9695869973481714421, -0.13497763436486276412, 2.8983680069011104052, -0.25382247697616189264, -4.9233259421066879469, 1.1940247607627194615, 4.4408920985006261617e-16, 0, 0.0010800130290116449761, 0.00076408094461186495429, -0.0029589630116448285488, -0.00087264995012978460905, -0.0051470914118511394697, -0.00037804019106299111778, 0.20207527387121515527, 0.0020070544765826729347, 1.1580252366043886081, -0.00069118022426611653436, 1.5689665948166240383, -0.0045290910522769603844, -1.2012679739112754884, 0.0085164006815267589978, -1.7671162635968691301, 0.046706182018272840439, 2.9931065266471703623, -0.55166786071240503375, 0, 0, -2.5513815072961419693e-05, -1.8078345013767598096e-05, 6.9882718216176479414e-05, 2.0732787925975703258e-05, 0.00012154373149783886249, 9.1724360658872410822e-06, -0.0039185795650754015607, -5.5540121878291909925e-05, 0.0083483300512910106617, 3.366784700094217677e-05, 0.34597774598037167593, 0.00061544857656690001111, 1.3929650741667591873, -0.0032153965723222335815, 1.0550792027144637597, -0.024400898124765986463, -1.7214890573288510467, 0.31330563624629470532, 0, 0, 6.9427404324062452156e-07, 5.092710402106320213e-07, -1.8900533691006157141e-06, -6.37008124488906817e-07, -3.2769559589167800075e-06, -3.9927796023670766917e-07, 0.00010555708713181393625, 6.542541903472452638e-06, -0.00022369557760034113753, -1.1651681607648470274e-05, -0.0065527231879012725474, -0.00033154755847665279712, 0.040215268969781864383, 0.0019536854662268524074, 0.59033605648767484286, 0.015088206344919037616, 1.5005041340227291968, -0.19443397537829132382, -1.1102230246251565404e-16, 0, ]).reshape((20, 11, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=4 +knots=np.array([-2500, -150, 300, 1500.0000000000000000, ]) +absorb_cons=FALSE +output=np.array([-0.03303972668455883166, -0.032723631630874550069, -0.033194598680918049882, -0.032481019964223409313, -0.033535293013993730527, -0.031917861017270607316, -0.03426231263902488472, -0.030563998358814094963, -0.035695429397679306893, -0.027087023457207957261, -0.037865492526216820712, -0.017178820311233713308, -0.037086543898716496648, 0.014593291596970280055, -0.0029879266785189512179, 0.12551122978070125558, 0.23922654623041611499, 0.49782433286763683178, 0.98768627515810170081, 1.0869145050394330987, 0.66601437778113736776, 0.67187778857060287407, 0.663080503426190071, 0.67627141867934648101, 0.65647421427937902028, 0.68614414294517134252, 0.64158611076564242559, 0.70828643005086278084, 0.60798624557560698722, 0.7576791553065401752, 0.5320956270640739838, 0.865894348010412096, 0.36241579174811910935, 1.0862902782459773476, 0.015083764342983273232, 1.4407803230899152158, -0.4134231048981120149, 1.6325959428355898417, -0.025636829423459156496, 0.35643164379996317148, 0.36702534890342142226, 0.36084584306027167599, 0.37011409525472788173, 0.35620960128487694218, 0.37706107873461469637, 0.34577371807209933419, 0.39267620187338242443, 0.32227756830795128984, 0.42770918382207229191, 0.26940786815066769533, 0.50576986546214286466, 0.15128447230082164854, 0.6746707521505973526, -0.10088356984294755136, 0.98790416233553579595, -0.56629155287061583302, 1.1741965586676958999, -1.1304202757032262294, 0.037950554265357511197, -0.44334614883939615915, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=5 +knots=np.array([-400, -50, 10, 50, 100, ]) +absorb_cons=FALSE +output=np.array([0.015162953484350691347, 0.017003239050418700318, 0.01389317445221215086, 0.01781864311343593632, 0.010107471620559638215, 0.018108516505766211746, -0.0037108407090391832411, 0.013008750547323907898, -0.048928829481261350287, -0.0040236561643654800147, 0.092210640717886122042, 0.1378672467189187012, 1.5241189647343453828, 1.1908052000719462349, 1.3336312280306561462, 0.1631244792608173011, 1.8059790376981266213, -0.013880364847569600512, 0.0084813946159772030109, 1.4226717441894676242, 0.085563268199896264088, 0.11668451836115162346, 0.071115177265946433183, 0.14186260471454884002, 0.041497176936461224739, 0.20374514230967810668, -0.0090968367480324351104, 0.36464078885855299994, -0.046829263271134111135, 0.78133519562325359775, 0.0086505068072265829671, 1.4941773335338757178, 0.083794480856750619413, 1.5469438185966697397, 1.4536819883528222519, 0.01009019548322653316, 0.24373154263518609364, -0.026484165693594415025, 0.45865093019281244491, 1.3856971378298170716, 1.0470804297077640488, 1.0403159202859915133, 1.0474228585236060596, 1.0301709677530419551, 1.0403805448593048677, 0.99263889345454958679, 0.98179764669852209735, 0.84465069052528973792, 0.662325916413059268, 0.31424672127915465047, -0.11097382584830663144, -0.73780817614306393182, 0.10634636847011158522, -1.0591219159940026273, -0.97302313835893716742, -0.14685901225266156933, 0.065659678129581511286, 0.92642956346749238961, 0.738106497929031935, -0.90865791610827972846, -0.14780665139201115688, -0.17400367769756186487, -0.13243121024176468525, -0.18985221558102688411, -0.091985193416325716775, -0.21449255226999386359, 0.031010030758549505386, -0.22230022993116671515, 0.43343217633933617261, -0.091558260738042823723, 1.0101126783231939577, 0.10576359589026917973, -0.71425981406120730988, -0.67862710267461334723, -0.81429007802454078657, 0.97364433750861778538, -1.115370258462895503, 0.11393496707367145593, -0.20523882273782165231, -0.89971096591100430118, ]).reshape((20, 4, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=7 +knots=np.array([-1000, -500, -250, 0, 250, 500, 1000, ]) +absorb_cons=FALSE +output=np.array([1.0865454545429926135e-06, 2.4398181818138797716e-06, 5.4730227272719212013e-06, 1.2258383522732035908e-05, 2.7392640980115554039e-05, 6.0996505637431891467e-05, 0.0001350924767677991363, 0.00029670296713464952565, 0.00064309569467692253436, 0.0013643251258789318436, 0.0027908209016161266564, 0.0053380236469475778743, 0.0088335867924326759437, 0.0091533086384256254903, -0.014306039442788853755, -0.041433352007441685838, 0.31405170261824960631, 0.99790444618953877409, 0.027724626841434521496, 0.0068039590138881103284, 0.00064727402371540310524, -0.00098920483399211889264, 0.0014426438433794426357, -0.0022558485342761974701, 0.0031770096755419320253, -0.0052223605999905525765, 0.0068053308523184398438, -0.012426118572852515309, 0.013644913148864869917, -0.030618365664116811709, 0.023048059495840829414, -0.073679585582029943902, 0.022074755528899835111, -0.091195081533291866283, -0.0002259526328000187323, 0.78626962637629815855, -0.10027585488170688566, 0.03440373467483604647, 1.0473889505746853956, -0.065646799659779347946, -0.003108653786561336313, 0.0047444954940711828867, -0.0069334472845849707406, 0.010810919925889327445, -0.015293474668169363198, 0.024997761679919142108, -0.03288173605395704191, 0.059489869048364188431, -0.066524536226034367004, 0.14842140322069641289, -0.11509599902262178384, 0.38653940175293038939, -0.12009256540661154833, 0.89487060989842726055, 0.023974235745902267025, 0.30753674660261021145, 0.028225509751146779513, -0.016286171465612203635, -0.087188251557721807572, 0.95672514836045408071, 0.99996516654545464231, 0.99992170981818173647, 0.99982413427272720519, 0.99960527135227272844, 0.99911513172301125163, 0.99802008661061780703, 0.99558245566310810126, 0.99018628040560352499, 0.9783435545897927188, 0.95270542773753197352, 0.89842166335737938532, 0.7877650145033745499, 0.57753870046138200411, 0.23531461121027275052, -0.101438596654484528, -0.076220798157655950122, 0.080593293321039760624, 0.00045998670001021375875, 0.022032291428807804223, 0.12976646713984618664, 0.0031521796047431342204, -0.0046466867667984135259, 0.0071530971936759326843, -0.010318124209980239492, 0.01639748407299900651, -0.022529876245437452376, 0.03838002020499131639, -0.047302525716890531093, 0.093325747193657035417, -0.090212229951197098199, 0.23900090287817127299, -0.13160022708072441344, 0.61322255928469093789, -0.056958752001294875311, 0.958298331738895115, 0.012677886126789952859, -0.35059868303530600242, 0.01444622466557134513, -0.00094091415750929829898, -0.032059943389195363905, -0.00065705293280633844839, 0.00096724647035571764686, -0.0014919010479248961606, 0.0021455230825716264942, -0.0034235434443629607359, 0.0046733920492536690228, -0.008021163143228648984, 0.0097557918686406452924, -0.019432774400957149308, 0.018339439531206425116, -0.048165447610385929422, 0.025637372759501717012, -0.10157703666079390126, 0.0088153037874612247271, 0.13369802124527602194, 0.011169891059399323502, 1.0280040322265766584, -0.030928220764344298982, -0.0090167031296965738374, 0.004411168534786328102, ]).reshape((20, 6, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=4 +knots=None +absorb_cons=TRUE +output=np.array([0.19511874223105002413, 0.19328136140945711974, 0.19603076753463616333, 0.19189278126562986371, 0.19806475922765381936, 0.18874078982063985377, 0.20253543882853958236, 0.18155709647843842891, 0.21199988818367701549, 0.16514182390533327371, 0.23031856584684334832, 0.12705798198206638694, 0.25709528872115156028, 0.036195691844765578993, 0.25138520448010354125, -0.18708237186262471896, -0.013972372776853255599, -0.70106203022920721146, -0.96214970344564842986, -0.96214970344564820781, 0.68403334135296989249, 0.60311193997153489388, 0.72443479807328026165, 0.54235372240853074732, 0.81513433908152477247, 0.40561204773518105826, 1.0177088251859824908, 0.099342480096702004411, 1.4639211866974952692, -0.57590399808120096292, 2.4193104627273829266, -2.0236042389889199455, 4.3297301577097133674, -4.928177533945309996, 7.4943452610127803126, -9.7886574066511276015, 9.753529003891806326, -13.510350272896850754, 0.23706294230926167055, 0.23706294230926180933, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=7 +knots=None +absorb_cons=TRUE +output=np.array([-0.09996264143545301184, -0.11347888802625775984, -0.085118834474127241796, -0.10911447157987791412, -0.0376192915747680795, -0.064440162552667323848, 0.093968376147604365523, 0.11142321074687944193, 0.31776266530375074648, 0.45570604000055198179, 0.46380277431584160386, 0.89300636651257359055, -0.14510213799700033555, 0.96333821295332311418, -1.5132894536153895793, 0.82432258344543585249, -2.5988714669036583338, 0.92635413953045664393, -0.14134351039860873489, -0.14134351039860867938, 0.23834091756376188376, 0.35248629179932566835, 0.18039220953514537027, 0.43583938337484684489, 0.050144193047881382985, 0.61552699880967853829, -0.2237848683809608441, 0.97413442320198884161, -0.67208413897185625974, 1.5362399491838241161, -0.95632335803874857216, 1.7726129713790426123, 0.31347441526077174379, -0.38061109255151409636, 3.2553930274666940115, -5.093077784759170612, 6.0469258529758489473, -9.2083208514013143997, 0.38134573025237739063, 0.38134573025237838984, 0.36086943997122683525, 0.36667024194421360406, 0.35446911502732253441, 0.36478130178265055772, 0.33382084885464979873, 0.34553973621188488474, 0.27476295985860993421, 0.26982601949673939989, 0.15921647742368139067, 0.1214671481463027447, -0.0048407176404455702981, -0.067803846828875705133, -0.11067535403631012514, -0.10302868958722773141, -0.2301530127015978533, -0.064773144847515770617, -0.49542622407015213248, -0.23755670608026469015, -0.81858279646244769268, -0.81858279646244602734, 0.36026977248710895241, 0.23461157027634554906, 0.43091928395041323441, 0.1550818089508944897, 0.60166186948369282383, 0.013499889397706944794, 0.98534266394190206384, -0.20102910227880538274, 1.5995282267915371666, -0.53077336516331363736, 1.8709434423002264669, -0.7329934007992182643, -0.41020716027288028904, 0.26173115951276498814, -5.3296664149739436667, 2.8167844608879319956, -9.2446193976201840314, 6.3595195952585372723, 0.3796975489346396393, 0.37969754893464241485, -0.09342094101113124216, -0.10518600840242132988, -0.080006629364737152921, -0.10062511887211006423, -0.036336786815554571184, -0.058504221090871715016, 0.089578204326735660912, 0.10154568474713222825, 0.33951493212221051099, 0.38266890106103862434, 0.7115379830932434535, 0.57066292250314121226, 1.0142476918808467357, -0.17457778635418924607, 1.3394445526441309813, -1.8727860878377164955, 1.5244315420174636699, -3.2891836324660186364, -0.13150260109059599967, -0.13150260109059619396, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=10 +knots=None +absorb_cons=TRUE +output=np.array([-0.010422589164110178037, 0.0456424386898241774, -0.037865479111961315717, 0.067665213698612183824, -0.082737354894918610504, 0.028116719037984471558, -0.13142165397961641515, -0.22684145450558812485, -0.14183761903259869963, -0.4397636102098926858, 0.038753040222973357543, 0.16687260126443773101, 0.24596836576748323799, 1.1496535841573791714, -0.11141233683909176899, 0.852150817442395625, -0.69719802631935023918, -0.16780336922215680073, -0.27375964350090231658, -0.27375964350090231658, 0.00075686991514895495502, -0.0026399619145559983374, 0.002329286728553797009, -0.0046772664281081481261, 0.0050464211301084280908, -0.0053347974019967861828, 0.0084202195193733477691, 0.025683527700154588219, 0.0094683775407149051856, 0.27987678132954318944, -0.0027668876775316930683, 1.1881421141921484352, -0.020680289816708941064, 1.9619971627400687453, 0.011350885804312933758, -0.30799503353642232462, 0.28512530049421225264, -3.4687076070237505832, 0.017302448352367463119, 0.017302448352367227197, -0.031423668563904168238, 0.092056168183617143042, -0.085784223470207240925, 0.18847060597276241167, -0.18459182127963985609, 0.39491427056812172802, -0.32011917407772511046, 0.75400611255752592044, -0.36683893574186782205, 0.9123381072270769776, 0.10368560537272084043, -0.284896787114018335, 0.65873659367957215771, -1.7915854614656305799, -0.28317998595666565853, 0.16934785893573317539, -2.1208025768458700355, 3.4983918640596205485, -0.65136227602061025355, -0.65136227602061058661, 0.15390547566386716949, 0.72999661431747953078, -0.052325183145307693766, 1.0578646982284642952, -0.17410117772396246916, 1.0826889596002884364, 0.28795108435587113416, -0.33988255901594949249, 0.75706886705991383035, -1.8010717324191700683, -0.27609951573452540252, 0.70199292810649616126, -1.6861943363558831166, 4.2694489532922874631, 0.3883483777323971653, -0.72860244126989648361, 4.3993879828572435287, -9.3213910982477266032, 0.27550705134905656424, 0.27550705134905634219, 0.88473558816481134848, 0.28118622960754013906, 1.0363915332292370497, -0.13821893333931381531, 0.86682756892064050103, -0.46428766146855998675, -0.49858487332948592252, 0.19046189397427254475, -1.804569129824072693, 0.94889775503965156922, 0.68883320796217106796, -0.36989366480027330297, 4.1648803055867107403, -2.2675263648363670477, -0.80718694983894612172, 0.41585628137205921107, -9.3512295591515375293, 6.4594889011881138075, -0.11803106422832626565, -0.11803106422832615463, -0.04700419996957900387, 0.068365309897369067049, -0.04054662542658848956, 0.14767281664377382433, 0.18375758144525122795, 0.096639366434089990499, 1.0236374391375679949, -0.47105831760443933609, 1.6290138304390200386, -0.95892121020674836451, -0.57444021027476643848, 0.35538961856435591358, -3.4443839310068100623, 2.1037278825342364819, 0.51445168623435322264, -0.5476416666229180219, 7.3133339883682770832, -6.2747526284605275038, -0.5386203650629584061, -0.53862036506295885019, -0.00033055953514735743511, 0.0034830998631877898263, -0.0031226317036678898596, 0.0044763982618290778723, -0.0095705473805210890259, 0.0013288993039827501352, 0.0024048160547256620945, -0.015334684583203243846, 0.24302632748633656856, -0.02859075483432030676, 1.2008463040646732978, 0.01005831734477347951, 2.0397829199332155881, 0.047246265215163486817, -0.33369939987991892316, -0.0017774801323981149429, -3.8176499659498723815, 0.69539341686864553083, -0.018985370198741847308, -0.01898537019874227405, -0.0098485472403549607912, 0.043107558972873410985, -0.035757108373310586558, 0.063906922484069789148, -0.078090074289757671622, 0.026516000447580879984, -0.12429507538278902756, -0.2141005094608952608, -0.13680420974781898336, -0.41275099307476753596, 0.042680600816607877634, 0.15199473312943939662, 0.44252834874998403514, 0.8905421952388906659, 0.99056537832665858545, -0.23331489131404251069, 1.3587540460951703647, -2.2485068612054024406, -0.25856375708606771369, -0.25856375708606793573, ]).reshape((20, 8, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=12 +knots=None +absorb_cons=TRUE +output=np.array([-0.07766833740489995086, -0.10190625722373891637, -0.060810191651491825315, -0.095843436838280671175, -0.026956945198949221199, -0.02140480076346930674, -0.0044354303173668322216, 0.068142865158757101596, -0.10242235056407339444, -0.134962672377622106, -0.17923996606808398346, -0.32198261136183764508, 0.061769798735937714307, 0.22368036323142082011, 0.1062350870161039712, 0.86684951229524320748, -0.41431550373346520688, 0.82628193491032586593, -0.30550552892225468771, -0.30550552892225446566, -0.046843894383066776721, -0.061472670935691822725, -0.036665627178526026542, -0.057737114955866711274, -0.016253728913666141281, -0.012788703169830750381, -0.0026924622704371371611, 0.037130318979860681139, -0.061754253708923484423, -0.072908208132761248566, -0.10784991719446739011, 0.15587963325803569359, 0.035948683163131246732, 1.5026771080647596257, 0.054139137539069064065, 1.2144591386571002012, -0.12227506507632453225, -2.0325190387816292059, -0.18423666748038231011, -0.1842366674803827542, -0.10253186808225246696, -0.1341028859441055765, -0.080717296578839040078, -0.12938111733003612724, -0.035779041281597902258, -0.033296176820796892504, -0.0052764476269259964411, 0.29121358356235121922, -0.13571696227220694797, 0.9800391391797497187, -0.23836784885271891654, 1.1531098931327661283, 0.083488884262169646422, -0.95923704223174655059, 0.14850642088377782879, -1.3982914277816191895, -0.63569333679288853034, 2.040472414748102814, -0.40421944208659177367, -0.40421944208659132958, -0.014736324481430123495, -0.036942635828954392685, 0.0066553430184999587058, 0.1067120469886325973, 0.0028385673937536314362, 0.84576148428624664533, -0.024675731668667714308, 1.6253851750682712929, 0.0013193004864854235899, -0.44631406733607736914, 0.032762082318650569135, -2.4125076929166153761, -0.03606306801106605453, 2.0357000324722602791, -0.069357883037490283828, 2.9830669079191580728, 0.34150454252272821609, -4.9007299602670126859, -0.020189059463686463008, -0.020189059463686463008, -0.012482766482938594671, 0.70375642696389684172, -0.20381708316356489386, 0.93679207951689691392, -0.089167436412632875009, 0.2081777984642331214, 0.25130986547048167479, -1.1517493252694694927, -0.23847465841613846305, 0.21373269726886048869, -0.73521082895311973271, 1.7985010371260992112, 0.48954351921215394361, -1.6483400566813448673, 0.75390085346775681518, -2.4179886586261010173, -1.7764330770220631006, 3.8309842164304526158, -0.45651730144672891809, -0.45651730144672891809, 0.86855075539761661396, 0.098258969106073332234, 0.91310939823129155801, -0.32540547292490512588, 0.16725908432707276008, -0.11995362876401588492, -1.021344015679647832, 0.58623523352093998007, 0.23016332628828412021, -0.31087640693906454237, 1.6549915252178080127, -1.2624926460002787731, -1.4964629433416147819, 0.98706595992626866565, -2.1957720652086201163, 1.4954532454044999756, 3.619128405599101761, -3.2523549448400173034, -0.31777688966039602247, -0.31777688966039646656, -0.068946719872015810315, -0.063498950974957252269, 0.10999032024314105149, 0.0059748385118500793589, 0.84565340326272575577, 0.0088822808061620184272, 1.5829407256504981483, -0.060957945254261673707, -0.45742582387218383433, -0.014951096212291247606, -2.381969985853732652, 0.051586837169672689063, 1.9887723465897544362, -0.077591047241966609738, 2.9302744923046657455, -0.16817713282609225711, -5.0351646834625327642, 0.99618007435765298929, -0.095785966663044092018, -0.095785966663044536107, -0.092425948063627971774, -0.12192256208017497598, -0.076168790113220086191, -0.11625762092899732947, -0.037600709993932460162, -0.026143656852116337053, 0.19673306138614868321, 0.083917187234610293722, 1.0347219995539065351, -0.16290214117344051226, 1.3532959167438192161, -0.38419175563061558343, -1.1275995644118568251, 0.22887092989596394266, -1.6446009002954922185, 0.37556943100676937197, 2.5636651809434143345, -1.3113571002380715047, -0.36780147849154309903, -0.36780147849154309903, -0.052133443997911740886, -0.06838748447056271218, -0.040727650559123369789, -0.064279681235506633263, -0.017963836831353656442, -0.014349195077656596783, -0.0068956265034833194583, 0.045590399764175990049, -0.060364684525170013429, -0.090361397122777853408, 0.22579126263553786491, -0.21095860924503515021, 1.4340181609862545642, 0.11958124964793707956, 1.1233531600390498362, 0.15886424366674492537, -1.9608032079784090129, -0.11004527519600627861, -0.20496419199835186342, -0.20496419199835186342, -0.074397287283336693831, -0.097615070510572624074, -0.058251260498594206738, -0.091806644267701589812, -0.02582498595211388942, -0.020500802148151781035, -0.0041449721977959343849, 0.065178307797134571455, -0.098329868155822383602, -0.12907473963965984676, -0.17815101427258792088, -0.30240999889208236562, 0.098829510321402941342, 0.17727868088912610012, 0.68781535762400658474, 0.27674812243204571782, 1.1588192944220654379, -0.7988804231889805596, -0.29264110323919079182, -0.2926411032391906808, ]).reshape((20, 10, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=4 +knots=np.array([-2500, -150, 300, 1500.0000000000000000, ]) +absorb_cons=TRUE +output=np.array([0.12313452571054940565, 0.12624926449090670411, 0.12157389196350212868, 0.12857954187334583174, 0.11805461329003080762, 0.13380425540627891023, 0.11009731641023581816, 0.14546384037961754276, 0.092005873745000077424, 0.17117971635322848378, 0.050459076159657625937, 0.22605161337519041886, -0.04604552699950949235, 0.33036931836460758927, -0.26444093870479618014, 0.45978406857873022062, -0.66227507648797157014, 0.32946799433163242998, -0.92301557680450230237, -0.77049779143573060569, 0.15656827198639958199, 0.14932319431509266661, 0.16018937960169490897, 0.14388705697943621198, 0.1683330978621291607, 0.13164928933754893592, 0.18663507205881160744, 0.10408933274661898161, 0.22768017116328620464, 0.042040878816280137509, 0.31905484877266732102, -0.096761998947504118673, 0.51632342198274205902, -0.39392983963941236025, 0.87954141557829357279, -0.94659228313998333704, 1.0777246444382655444, -1.6356011142349877741, -0.30993435496630139525, -0.88022048471107694478, ]).reshape((20, 2, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=5 +knots=np.array([-400, -50, 10, 50, 100, ]) +absorb_cons=TRUE +output=np.array([-0.16508056690578271075, -0.14355192166054722702, -0.17398515944924686227, -0.12432844320614395983, -0.18919890928728577695, -0.072282554700368567557, -0.19674137112973341668, 0.081531091765042931763, -0.099155660656600808078, 0.52456028958996936407, 0.059704023721638257993, 1.2036951770569246367, -0.95698314791898375642, 0.59171921208541256032, 0.40429183055884826414, 0.021134682418438101997, -1.035862596202561825, -0.18547278101676506479, 0.17821896181573629314, 0.27778784312200943685, 0.84139218015539352091, 0.82675559954147825881, 0.84628382311749461575, 0.8117240601311839221, 0.85106220741071658686, 0.76611964233460772, 0.82780911632526033017, 0.61231966988832331467, 0.61938480406110207888, 0.10352707230517528558, -0.069077289581256251516, -0.9761893286926568436, -0.74775693930080122662, -1.843017028194991358, -1.8341942282567624822, -0.13779546922177127177, -0.98442590823258591115, 0.79595721424418131029, 0.50797292743971100837, -1.8178521254738027046, -0.057675412235671304206, -0.080422948680625480633, -0.044293406826563193335, -0.094130216309427472421, -0.0090271421596601793269, -0.11523330512953809668, 0.098486792744760950913, -0.12049430358370501193, 0.45224868955998115405, 0.00077770457813844623505, 0.99175389147792825106, 0.21022065027995529007, -0.33999735782244788762, -0.33512941632144105375, -0.43693056610772496029, 0.96967275251871798414, -0.65522965575463965049, 0.17110709302995569248, -0.10439580460326271238, -0.50130803865473083647, ]).reshape((20, 3, ), order="F") +--END TEST CASE-- +--BEGIN TEST CASE-- +spline_type=cc +nb_knots=7 +knots=np.array([-1000, -500, -250, 0, 250, 500, 1000, ]) +absorb_cons=TRUE +output=np.array([-0.10421720382140421679, -0.10591736328552885105, -0.10337614089781445303, -0.10720759929942245969, -0.10150561917996400729, -0.11015275422250632442, -0.097405901413871925909, -0.11694382088021060273, -0.088713078413449955595, -0.13250065888393972036, -0.07161679548265666162, -0.1625759820148384438, -0.043015722854652924112, -0.13320201735142009336, 0.0004329669515455780238, 0.78255062519422247114, -0.15088551365188454523, -0.085517465675143913839, 1.0298684606084522741, -0.098098415425510815391, -0.16366514384894217948, -0.15590949502662956871, -0.16741997729436150499, -0.14987919244601818902, -0.17557153836450387074, -0.13565965107884025986, -0.1924380512291224421, -0.10053567798805967959, -0.22324338128005483117, -0.0075691069598905688642, -0.26003599357502127365, 0.25043141090853648922, -0.21975165836638141381, 0.83055439613540549271, 0.024983098021001227257, 0.30184263751436557488, -0.049262209087217581627, -0.19989579226301767978, -0.11401362112954462058, 0.90703894735829693197, 0.15993324209937159752, 0.15937966275042819708, 0.16015824098241202011, 0.15887423467611411221, 0.16053993466300625625, 0.15746013438548811525, 0.16078344852210443849, 0.15293225108971789106, 0.15839019763395165152, 0.13656272051085360797, 0.14009527925573453389, 0.075647694069404219919, 0.05612209740148604159, -0.10118796678857061577, -0.096160226916063087921, -0.10601238997400461161, -0.32482262945752882199, -0.96018597065328126217, -0.11831810372893719618, -0.13019185052168549821, -0.080994950879331353844, -0.088844916921682309807, -0.07695736745600667561, -0.094535285708752150868, -0.067603724064711254171, -0.10672989998407718393, -0.045242921897107997442, -0.13117139070034619652, 0.011189913886947294372, -0.17196634533664997835, 0.16303832653371333472, -0.20293397921406119977, 0.56099155513187193289, -0.090666668944769990279, 0.95882707315240156554, 0.0096936222066400009462, -0.39120974264100472073, -0.081782976118326314308, -0.015000002474441720413, -0.058100318570304822219, -0.06971270937892765085, -0.068130345111184043017, -0.070517467540312656071, -0.066967604576931502591, -0.072359448172744492145, -0.064425671443484225365, -0.076646642438798442964, -0.059071504956647494233, -0.086837852317636618493, -0.048752380149832678924, -0.11050441917873819742, -0.032902936957473871704, -0.1444406050066643632, -0.018847223960927635827, 0.13413193485813351691, 0.0087208437439542339786, 0.9946764147081772478, -0.10989907326032234691, -0.020554346388292375064, -0.016958962471346181872, ]).reshape((20, 5, ), order="F") +--END TEST CASE-- +""" +R_crs_num_tests = 42 diff --git a/venv/lib/python3.10/site-packages/patsy/test_state.py b/venv/lib/python3.10/site-packages/patsy/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..2c5a8e850d15379d9674ae0bd06b7c322327f8e4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/test_state.py @@ -0,0 +1,207 @@ +# This file is part of Patsy +# Copyright (C) 2012-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +import numpy as np + +from patsy.state import Center, Standardize, center +from patsy.util import atleast_2d_column_default + + +def check_stateful(cls, accepts_multicolumn, input, output, *args, **kwargs): + input = np.asarray(input) + output = np.asarray(output) + test_cases = [ + # List input, one chunk + ([input], output), + # Scalar input, many chunks + (input, output), + # List input, many chunks: + ([[n] for n in input], output), + # 0-d array input, many chunks: + ([np.array(n) for n in input], output), + # 1-d array input, one chunk: + ([np.array(input)], output), + # 1-d array input, many chunks: + ([np.array([n]) for n in input], output), + # 2-d but 1 column input, one chunk: + ([np.array(input)[:, None]], atleast_2d_column_default(output)), + # 2-d but 1 column input, many chunks: + ([np.array([[n]]) for n in input], atleast_2d_column_default(output)), + ] + if accepts_multicolumn: + # 2-d array input, one chunk: + test_cases += [ + ( + [np.column_stack((input, input[::-1]))], + np.column_stack((output, output[::-1])), + ), + # 2-d array input, many chunks: + ( + [np.array([[input[i], input[-i - 1]]]) for i in range(len(input))], + np.column_stack((output, output[::-1])), + ), + ] + from patsy.util import have_pandas + + if have_pandas: + import pandas + + pandas_type = (pandas.Series, pandas.DataFrame) + pandas_index = np.linspace(0, 1, num=len(input)) + # 1d and 2d here refer to the dimensionality of the input + if output.ndim == 1: + output_1d = pandas.Series(output, index=pandas_index) + else: + output_1d = pandas.DataFrame(output, index=pandas_index) + test_cases += [ + # Series input, one chunk + ([pandas.Series(input, index=pandas_index)], output_1d), + # Series input, many chunks + ( + [ + pandas.Series([x], index=[idx]) + for (x, idx) in zip(input, pandas_index) + ], + output_1d, + ), + ] + if accepts_multicolumn: + input_2d_2col = np.column_stack((input, input[::-1])) + output_2d_2col = np.column_stack((output, output[::-1])) + output_2col_dataframe = pandas.DataFrame(output_2d_2col, index=pandas_index) + test_cases += [ + # DataFrame input, one chunk + ( + [pandas.DataFrame(input_2d_2col, index=pandas_index)], + output_2col_dataframe, + ), + # DataFrame input, many chunks + ( + [ + pandas.DataFrame([input_2d_2col[i, :]], index=[pandas_index[i]]) + for i in range(len(input)) + ], + output_2col_dataframe, + ), + ] + for input_obj, output_obj in test_cases: + print(input_obj) + t = cls() + for input_chunk in input_obj: + t.memorize_chunk(input_chunk, *args, **kwargs) + t.memorize_finish() + all_outputs = [] + for input_chunk in input_obj: + output_chunk = t.transform(input_chunk, *args, **kwargs) + if input.ndim == output.ndim: + assert output_chunk.ndim == np.asarray(input_chunk).ndim + all_outputs.append(output_chunk) + if have_pandas and isinstance(all_outputs[0], pandas_type): + all_output1 = pandas.concat(all_outputs) + assert np.array_equal(all_output1.index, pandas_index) + elif all_outputs[0].ndim == 0: + all_output1 = np.array(all_outputs) + elif all_outputs[0].ndim == 1: + all_output1 = np.concatenate(all_outputs) + else: + all_output1 = np.vstack(all_outputs) + assert all_output1.shape[0] == len(input) + # output_obj_reshaped = np.asarray(output_obj).reshape(all_output1.shape) + # assert np.allclose(all_output1, output_obj_reshaped) + assert np.allclose(all_output1, output_obj) + if np.asarray(input_obj[0]).ndim == 0: + all_input = np.array(input_obj) + elif have_pandas and isinstance(input_obj[0], pandas_type): + # handles both Series and DataFrames + all_input = pandas.concat(input_obj) + elif np.asarray(input_obj[0]).ndim == 1: + # Don't use vstack, because that would turn this into a 1xn + # matrix: + all_input = np.concatenate(input_obj) + else: + all_input = np.vstack(input_obj) + all_output2 = t.transform(all_input, *args, **kwargs) + if have_pandas and isinstance(input_obj[0], pandas_type): + assert np.array_equal(all_output2.index, pandas_index) + if input.ndim == output.ndim: + assert all_output2.ndim == all_input.ndim + assert np.allclose(all_output2, output_obj) + + +def test_Center(): + check_stateful(Center, True, [1, 2, 3], [-1, 0, 1]) + check_stateful(Center, True, [1, 2, 1, 2], [-0.5, 0.5, -0.5, 0.5]) + check_stateful(Center, True, [1.3, -10.1, 7.0, 12.0], [-1.25, -12.65, 4.45, 9.45]) + + +def test_stateful_transform_wrapper(): + assert np.allclose(center([1, 2, 3]), [-1, 0, 1]) + assert np.allclose(center([1, 2, 1, 2]), [-0.5, 0.5, -0.5, 0.5]) + assert center([1.0, 2.0, 3.0]).dtype == np.dtype(float) + assert center(np.array([1.0, 2.0, 3.0], dtype=np.float32)).dtype == np.dtype( + np.float32 + ) + assert center([1, 2, 3]).dtype == np.dtype(float) + + from patsy.util import have_pandas + + if have_pandas: + import pandas + + s = pandas.Series([1, 2, 3], index=["a", "b", "c"]) + df = pandas.DataFrame( + [[1, 2], [2, 4], [3, 6]], columns=["x1", "x2"], index=[10, 20, 30] + ) + s_c = center(s) + assert isinstance(s_c, pandas.Series) + assert np.array_equal(s_c.index, ["a", "b", "c"]) + assert np.allclose(s_c, [-1, 0, 1]) + df_c = center(df) + assert isinstance(df_c, pandas.DataFrame) + assert np.array_equal(df_c.index, [10, 20, 30]) + assert np.array_equal(df_c.columns, ["x1", "x2"]) + assert np.allclose(df_c, [[-1, -2], [0, 0], [1, 2]]) + + +def test_Standardize(): + check_stateful(Standardize, True, [1, -1], [1, -1]) + check_stateful(Standardize, True, [12, 10], [1, -1]) + check_stateful( + Standardize, True, [12, 11, 10], [np.sqrt(3.0 / 2), 0, -np.sqrt(3.0 / 2)] + ) + + check_stateful( + Standardize, True, [12.0, 11.0, 10.0], [np.sqrt(3.0 / 2), 0, -np.sqrt(3.0 / 2)] + ) + + # XX: see the comment in Standardize.transform about why this doesn't + # work: + # check_stateful(Standardize, + # [12.0+0j, 11.0+0j, 10.0], + # [np.sqrt(3./2)+0j, 0, -np.sqrt(3./2)]) + + r20 = list(range(20)) + + check_stateful( + Standardize, True, [1, -1], [np.sqrt(2) / 2, -np.sqrt(2) / 2], ddof=1 + ) + + check_stateful( + Standardize, True, r20, list((np.arange(20) - 9.5) / 5.7662812973353983), ddof=0 + ) + check_stateful( + Standardize, True, r20, list((np.arange(20) - 9.5) / 5.9160797830996161), ddof=1 + ) + check_stateful( + Standardize, True, r20, list((np.arange(20) - 9.5)), rescale=False, ddof=1 + ) + check_stateful( + Standardize, + True, + r20, + list(np.arange(20) / 5.9160797830996161), + center=False, + ddof=1, + ) + check_stateful(Standardize, True, r20, r20, center=False, rescale=False, ddof=1) diff --git a/venv/lib/python3.10/site-packages/patsy/tokens.py b/venv/lib/python3.10/site-packages/patsy/tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..9cc500cb02fc1d743ca2f95ef8747a947fbef48e --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/tokens.py @@ -0,0 +1,203 @@ +# This file is part of Patsy +# Copyright (C) 2011 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Utilities for dealing with Python code at the token level. +# +# Includes: +# a "pretty printer" that converts a sequence of tokens back into a +# readable, white-space normalized string. +# a utility function to replace calls to global functions with calls to +# other functions + +from io import StringIO + +import tokenize + +from patsy import PatsyError +from patsy.origin import Origin + +__all__ = ["python_tokenize", "pretty_untokenize", "normalize_token_spacing"] + + +# A convenience wrapper around tokenize.generate_tokens. yields tuples +# (tokenize type, token string, origin object) +def python_tokenize(code): + # Since formulas can only contain Python expressions, and Python + # expressions cannot meaningfully contain newlines, we'll just remove all + # the newlines up front to avoid any complications: + code = code.replace("\n", " ").strip() + it = tokenize.generate_tokens(StringIO(code).readline) + try: + for pytype, string, (_, start), (_, end), code in it: + if pytype == tokenize.ENDMARKER: + break + if pytype in (tokenize.NL, tokenize.NEWLINE): + assert string == "" + continue + origin = Origin(code, start, end) + if pytype == tokenize.ERRORTOKEN: + raise PatsyError( + "error tokenizing input " "(maybe an unclosed string?)", origin + ) + if pytype == tokenize.COMMENT: + raise PatsyError("comments are not allowed", origin) + yield (pytype, string, origin) + else: # pragma: no cover + raise ValueError("stream ended without ENDMARKER?!?") + except tokenize.TokenError as e: + # TokenError is raised iff the tokenizer thinks that there is + # some sort of multi-line construct in progress (e.g., an + # unclosed parentheses, which in Python lets a virtual line + # continue past the end of the physical line), and it hits the + # end of the source text. We have our own error handling for + # such cases, so just treat this as an end-of-stream. + # + if "unterminated string literal" in e.args[0]: + raise PatsyError( + "error tokenizing input ({})".format(e.args[0]), + Origin(code, 0, len(code)), + ) + + # Just in case someone adds some other error case: + assert "EOF in multi-line" in e.args[0] + return + + +def test_python_tokenize(): + code = "a + (foo * -1)" + tokens = list(python_tokenize(code)) + expected = [ + (tokenize.NAME, "a", Origin(code, 0, 1)), + (tokenize.OP, "+", Origin(code, 2, 3)), + (tokenize.OP, "(", Origin(code, 4, 5)), + (tokenize.NAME, "foo", Origin(code, 5, 8)), + (tokenize.OP, "*", Origin(code, 9, 10)), + (tokenize.OP, "-", Origin(code, 11, 12)), + (tokenize.NUMBER, "1", Origin(code, 12, 13)), + (tokenize.OP, ")", Origin(code, 13, 14)), + ] + assert tokens == expected + + code2 = "a + (b" + tokens2 = list(python_tokenize(code2)) + expected2 = [ + (tokenize.NAME, "a", Origin(code2, 0, 1)), + (tokenize.OP, "+", Origin(code2, 2, 3)), + (tokenize.OP, "(", Origin(code2, 4, 5)), + (tokenize.NAME, "b", Origin(code2, 5, 6)), + ] + assert tokens2 == expected2 + + import pytest + + pytest.raises(PatsyError, list, python_tokenize("a b # c")) + + import pytest + + pytest.raises(PatsyError, list, python_tokenize('a b "c')) + + +_python_space_both = list("+-*/%&^|<>") + [ + "==", + "<>", + "!=", + "<=", + ">=", + "<<", + ">>", + "**", + "//", +] +_python_space_before = _python_space_both + ["!", "~"] +_python_space_after = _python_space_both + [",", ":"] + + +def pretty_untokenize(typed_tokens): + text = [] + prev_was_space_delim = False + prev_wants_space = False + prev_was_open_paren_or_comma = False + prev_was_object_like = False + brackets = [] + for token_type, token in typed_tokens: + assert token_type not in (tokenize.INDENT, tokenize.DEDENT, tokenize.NL) + if token_type == tokenize.NEWLINE: + continue + if token_type == tokenize.ENDMARKER: + continue + if token_type in (tokenize.NAME, tokenize.NUMBER, tokenize.STRING): + if prev_wants_space or prev_was_space_delim: + text.append(" ") + text.append(token) + prev_wants_space = False + prev_was_space_delim = True + else: + if token in ("(", "[", "{"): + brackets.append(token) + elif brackets and token in (")", "]", "}"): + brackets.pop() + this_wants_space_before = token in _python_space_before + this_wants_space_after = token in _python_space_after + # Special case for slice syntax: foo[:10] + # Otherwise ":" is spaced after, like: "{1: ...}", "if a: ..." + if token == ":" and brackets and brackets[-1] == "[": + this_wants_space_after = False + # Special case for foo(*args), foo(a, *args): + if token in ("*", "**") and prev_was_open_paren_or_comma: + this_wants_space_before = False + this_wants_space_after = False + # Special case for "a = foo(b=1)": + if token == "=" and not brackets: + this_wants_space_before = True + this_wants_space_after = True + # Special case for unary -, +. Our heuristic is that if we see the + # + or - after something that looks like an object (a NAME, + # NUMBER, STRING, or close paren) then it is probably binary, + # otherwise it is probably unary. + if token in ("+", "-") and not prev_was_object_like: + this_wants_space_before = False + this_wants_space_after = False + if prev_wants_space or this_wants_space_before: + text.append(" ") + text.append(token) + prev_wants_space = this_wants_space_after + prev_was_space_delim = False + if ( + token_type in (tokenize.NAME, tokenize.NUMBER, tokenize.STRING) + or token == ")" + ): + prev_was_object_like = True + else: + prev_was_object_like = False + prev_was_open_paren_or_comma = token in ("(", ",") + return "".join(text) + + +def normalize_token_spacing(code): + tokens = [(t[0], t[1]) for t in tokenize.generate_tokens(StringIO(code).readline)] + return pretty_untokenize(tokens) + + +def test_pretty_untokenize_and_normalize_token_spacing(): + assert normalize_token_spacing("1 + 1") == "1 + 1" + assert normalize_token_spacing("1+1") == "1 + 1" + assert normalize_token_spacing("1*(2+3**2)") == "1 * (2 + 3 ** 2)" + assert normalize_token_spacing("a and b") == "a and b" + assert normalize_token_spacing("foo(a=bar.baz[1:])") == "foo(a=bar.baz[1:])" + assert normalize_token_spacing("""{"hi":foo[:]}""") == """{"hi": foo[:]}""" + assert normalize_token_spacing("""'a' "b" 'c'""") == """'a' "b" 'c'""" + assert normalize_token_spacing('"""a""" is 1 or 2==3') == '"""a""" is 1 or 2 == 3' + assert normalize_token_spacing("foo ( * args )") == "foo(*args)" + assert normalize_token_spacing("foo ( a * args )") == "foo(a * args)" + assert normalize_token_spacing("foo ( ** args )") == "foo(**args)" + assert normalize_token_spacing("foo ( a ** args )") == "foo(a ** args)" + assert normalize_token_spacing("foo (1, * args )") == "foo(1, *args)" + assert normalize_token_spacing("foo (1, a * args )") == "foo(1, a * args)" + assert normalize_token_spacing("foo (1, ** args )") == "foo(1, **args)" + assert normalize_token_spacing("foo (1, a ** args )") == "foo(1, a ** args)" + + assert normalize_token_spacing("a=foo(b = 1)") == "a = foo(b=1)" + + assert normalize_token_spacing("foo(+ 10, bar = - 1)") == "foo(+10, bar=-1)" + assert normalize_token_spacing("1 + +10 + -1 - 5") == "1 + +10 + -1 - 5" diff --git a/venv/lib/python3.10/site-packages/patsy/user_util.py b/venv/lib/python3.10/site-packages/patsy/user_util.py new file mode 100644 index 0000000000000000000000000000000000000000..080af84a76df62361652a82c392b5a9bcb8237ef --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/user_util.py @@ -0,0 +1,286 @@ +# This file is part of Patsy +# Copyright (C) 2012 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Miscellaneous utilities that are useful to users (as compared to +# patsy.util, which is misc. utilities useful for implementing patsy). + +# These are made available in the patsy.* namespace +__all__ = ["balanced", "demo_data", "LookupFactor"] + +import itertools +import numpy as np +from patsy import PatsyError +from patsy.categorical import C +from patsy.util import no_pickling, assert_no_pickling + + +def balanced(**kwargs): + """balanced(factor_name=num_levels, [factor_name=num_levels, ..., repeat=1]) + + Create simple balanced factorial designs for testing. + + Given some factor names and the number of desired levels for each, + generates a balanced factorial design in the form of a data + dictionary. For example: + + .. ipython:: + + In [1]: balanced(a=2, b=3) + Out[1]: + {'a': ['a1', 'a1', 'a1', 'a2', 'a2', 'a2'], + 'b': ['b1', 'b2', 'b3', 'b1', 'b2', 'b3']} + + By default it produces exactly one instance of each combination of levels, + but if you want multiple replicates this can be accomplished via the + `repeat` argument: + + .. ipython:: + + In [2]: balanced(a=2, b=2, repeat=2) + Out[2]: + {'a': ['a1', 'a1', 'a2', 'a2', 'a1', 'a1', 'a2', 'a2'], + 'b': ['b1', 'b2', 'b1', 'b2', 'b1', 'b2', 'b1', 'b2']} + """ + repeat = kwargs.pop("repeat", 1) + levels = [] + names = sorted(kwargs) + for name in names: + level_count = kwargs[name] + levels.append(["%s%s" % (name, i) for i in range(1, level_count + 1)]) + # zip(*...) does an "unzip" + values = zip(*itertools.product(*levels)) + data = {} + for name, value in zip(names, values): + data[name] = list(value) * repeat + return data + + +def test_balanced(): + data = balanced(a=2, b=3) + assert data["a"] == ["a1", "a1", "a1", "a2", "a2", "a2"] + assert data["b"] == ["b1", "b2", "b3", "b1", "b2", "b3"] + data = balanced(a=2, b=3, repeat=2) + assert data["a"] == [ + "a1", + "a1", + "a1", + "a2", + "a2", + "a2", + "a1", + "a1", + "a1", + "a2", + "a2", + "a2", + ] + assert data["b"] == [ + "b1", + "b2", + "b3", + "b1", + "b2", + "b3", + "b1", + "b2", + "b3", + "b1", + "b2", + "b3", + ] + + +def demo_data(*names, **kwargs): + """demo_data(*names, nlevels=2, min_rows=5) + + Create simple categorical/numerical demo data. + + Pass in a set of variable names, and this function will return a simple + data set using those variable names. + + Names whose first letter falls in the range "a" through "m" will be made + categorical (with `nlevels` levels). Those that start with a "p" through + "z" are numerical. + + We attempt to produce a balanced design on the categorical variables, + repeating as necessary to generate at least `min_rows` data + points. Categorical variables are returned as a list of strings. + + Numerical data is generated by sampling from a normal distribution. A + fixed random seed is used, so that identical calls to demo_data() will + produce identical results. Numerical data is returned in a numpy array. + + Example: + + .. ipython: + + In [1]: patsy.demo_data("a", "b", "x", "y") + Out[1]: + {'a': ['a1', 'a1', 'a2', 'a2', 'a1', 'a1', 'a2', 'a2'], + 'b': ['b1', 'b2', 'b1', 'b2', 'b1', 'b2', 'b1', 'b2'], + 'x': array([ 1.76405235, 0.40015721, 0.97873798, 2.2408932 , + 1.86755799, -0.97727788, 0.95008842, -0.15135721]), + 'y': array([-0.10321885, 0.4105985 , 0.14404357, 1.45427351, + 0.76103773, 0.12167502, 0.44386323, 0.33367433])} + """ + nlevels = kwargs.pop("nlevels", 2) + min_rows = kwargs.pop("min_rows", 5) + if kwargs: + raise TypeError("unexpected keyword arguments %r" % (kwargs,)) + numerical = set() + categorical = {} + for name in names: + if name[0] in "abcdefghijklmn": + categorical[name] = nlevels + elif name[0] in "pqrstuvwxyz": + numerical.add(name) + else: + raise PatsyError("bad name %r" % (name,)) + balanced_design_size = np.prod(list(categorical.values()), dtype=int) + repeat = int(np.ceil(min_rows * 1.0 / balanced_design_size)) + num_rows = repeat * balanced_design_size + data = balanced(repeat=repeat, **categorical) + r = np.random.RandomState(0) + for name in sorted(numerical): + data[name] = r.normal(size=num_rows) + return data + + +def test_demo_data(): + d1 = demo_data("a", "b", "x") + assert sorted(d1.keys()) == ["a", "b", "x"] + assert d1["a"] == ["a1", "a1", "a2", "a2", "a1", "a1", "a2", "a2"] + assert d1["b"] == ["b1", "b2", "b1", "b2", "b1", "b2", "b1", "b2"] + assert d1["x"].dtype == np.dtype(float) + assert d1["x"].shape == (8,) + + d2 = demo_data("x", "y") + assert sorted(d2.keys()) == ["x", "y"] + assert len(d2["x"]) == len(d2["y"]) == 5 + + assert len(demo_data("x", min_rows=10)["x"]) == 10 + assert len(demo_data("a", "b", "x", min_rows=10)["x"]) == 12 + assert len(demo_data("a", "b", "x", min_rows=10, nlevels=3)["x"]) == 18 + + import pytest + + pytest.raises(PatsyError, demo_data, "a", "b", "__123") + pytest.raises(TypeError, demo_data, "a", "b", asdfasdf=123) + + +class LookupFactor(object): + """A simple factor class that simply looks up a named entry in the given + data. + + Useful for programatically constructing formulas, and as a simple example + of the factor protocol. For details see + :ref:`expert-model-specification`. + + Example:: + + dmatrix(ModelDesc([], [Term([LookupFactor("x")])]), {"x": [1, 2, 3]}) + + :arg varname: The name of this variable; used as a lookup key in the + passed in data dictionary/DataFrame/whatever. + :arg force_categorical: If True, then treat this factor as + categorical. (Equivalent to using :func:`C` in a regular formula, but + of course you can't do that with a :class:`LookupFactor`. + :arg contrast: If given, the contrast to use; see :func:`C`. (Requires + ``force_categorical=True``.) + :arg levels: If given, the categorical levels; see :func:`C`. (Requires + ``force_categorical=True``.) + :arg origin: Either ``None``, or the :class:`Origin` of this factor for use + in error reporting. + + .. versionadded:: 0.2.0 + The ``force_categorical`` and related arguments. + """ + + def __init__( + self, varname, force_categorical=False, contrast=None, levels=None, origin=None + ): + self._varname = varname + self._force_categorical = force_categorical + self._contrast = contrast + self._levels = levels + self.origin = origin + if not self._force_categorical: + if contrast is not None: + raise ValueError("contrast= requires force_categorical=True") + if levels is not None: + raise ValueError("levels= requires force_categorical=True") + + def name(self): + return self._varname + + def __repr__(self): + return "%s(%r)" % (self.__class__.__name__, self._varname) + + def __eq__(self, other): + return ( + isinstance(other, LookupFactor) + and self._varname == other._varname + and self._force_categorical == other._force_categorical + and self._contrast == other._contrast + and self._levels == other._levels + ) + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash( + ( + LookupFactor, + self._varname, + self._force_categorical, + self._contrast, + self._levels, + ) + ) + + def memorize_passes_needed(self, state, eval_env): + return 0 + + def memorize_chunk(self, state, which_pass, data): # pragma: no cover + assert False + + def memorize_finish(self, state, which_pass): # pragma: no cover + assert False + + def eval(self, memorize_state, data): + value = data[self._varname] + if self._force_categorical: + value = C(value, contrast=self._contrast, levels=self._levels) + return value + + __getstate__ = no_pickling + + +def test_LookupFactor(): + l_a = LookupFactor("a") + assert l_a.name() == "a" + assert l_a == LookupFactor("a") + assert l_a != LookupFactor("b") + assert hash(l_a) == hash(LookupFactor("a")) + assert hash(l_a) != hash(LookupFactor("b")) + assert l_a.eval({}, {"a": 1}) == 1 + assert l_a.eval({}, {"a": 2}) == 2 + assert repr(l_a) == "LookupFactor('a')" + assert l_a.origin is None + l_with_origin = LookupFactor("b", origin="asdf") + assert l_with_origin.origin == "asdf" + + l_c = LookupFactor("c", force_categorical=True, contrast="CONTRAST", levels=(1, 2)) + box = l_c.eval({}, {"c": [1, 1, 2]}) + assert box.data == [1, 1, 2] + assert box.contrast == "CONTRAST" + assert box.levels == (1, 2) + + import pytest + + pytest.raises(ValueError, LookupFactor, "nc", contrast="CONTRAST") + pytest.raises(ValueError, LookupFactor, "nc", levels=(1, 2)) + + assert_no_pickling(LookupFactor("a")) diff --git a/venv/lib/python3.10/site-packages/patsy/util.py b/venv/lib/python3.10/site-packages/patsy/util.py new file mode 100644 index 0000000000000000000000000000000000000000..2c1c19d09eceebeac0f13a4f8dd68036f8e7202a --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/util.py @@ -0,0 +1,848 @@ +# This file is part of Patsy +# Copyright (C) 2011-2013 Nathaniel Smith +# See file LICENSE.txt for license information. + +# Some generic utilities. + +__all__ = [ + "atleast_2d_column_default", + "uniqueify_list", + "widest_float", + "widest_complex", + "wide_dtype_for", + "widen", + "repr_pretty_delegate", + "repr_pretty_impl", + "SortAnythingKey", + "safe_scalar_isnan", + "safe_isnan", + "iterable", + "have_pandas", + "have_pandas_categorical", + "have_pandas_categorical_dtype", + "pandas_Categorical_from_codes", + "pandas_Categorical_categories", + "pandas_Categorical_codes", + "safe_is_pandas_categorical_dtype", + "safe_is_pandas_categorical", + "safe_issubdtype", + "no_pickling", + "assert_no_pickling", + "safe_string_eq", +] + +import sys +from io import StringIO +import numpy as np + +from .compat import optional_dep_ok + +try: + import pandas +except ImportError: + have_pandas = False +else: + have_pandas = True + +# Pandas versions < 0.9.0 don't have Categorical +# Can drop this guard whenever we drop support for such older versions of +# pandas. +have_pandas_categorical = have_pandas and hasattr(pandas, "Categorical") +if not have_pandas: + _pandas_is_categorical_dtype = None +else: + if hasattr(pandas, "CategoricalDtype"): # pandas >= 0.25 + _pandas_is_categorical_dtype = lambda x: isinstance( + getattr(x, "dtype", x), pandas.CategoricalDtype + ) + elif hasattr(pandas, "api"): # pandas >= 0.19 + _pandas_is_categorical_dtype = getattr( + pandas.api.types, "is_categorical_dtype", None + ) + else: # pandas <=0.18 + _pandas_is_categorical_dtype = getattr( + pandas.core.common, "is_categorical_dtype", None + ) +have_pandas_categorical_dtype = _pandas_is_categorical_dtype is not None + +# The handling of the `copy` keyword has been changed since numpy>=2. +# https://numpy.org/devdocs/numpy_2_0_migration_guide.html#adapting-to-changes-in-the-copy-keyword +# If numpy<2 support is dropped, this try-clause can be removed. +try: + np.array([1]).__array__(copy=None) + copy_if_needed = None +except TypeError: + copy_if_needed = False + + +# Passes through Series and DataFrames, call np.asarray() on everything else +def asarray_or_pandas(a, copy=copy_if_needed, dtype=None, subok=False): + if have_pandas: + if isinstance(a, (pandas.Series, pandas.DataFrame)): + # The .name attribute on Series is discarded when passing through + # the constructor: + # https://github.com/pydata/pandas/issues/1578 + extra_args = {} + if hasattr(a, "name"): + extra_args["name"] = a.name + return a.__class__(a, copy=copy, dtype=dtype, **extra_args) + return np.array(a, copy=copy, dtype=dtype, subok=subok) + + +def test_asarray_or_pandas(): + import warnings + + assert type(asarray_or_pandas([1, 2, 3])) is np.ndarray + with warnings.catch_warnings() as w: + warnings.filterwarnings( + "ignore", "the matrix subclass", PendingDeprecationWarning + ) + assert type(asarray_or_pandas(np.matrix([[1, 2, 3]]))) is np.ndarray + assert type(asarray_or_pandas(np.matrix([[1, 2, 3]]), subok=True)) is np.matrix + assert w is None + a = np.array([1, 2, 3]) + assert asarray_or_pandas(a) is a + a_copy = asarray_or_pandas(a, copy=True) + assert np.array_equal(a, a_copy) + a_copy[0] = 100 + assert not np.array_equal(a, a_copy) + assert np.allclose(asarray_or_pandas([1, 2, 3], dtype=float), [1.0, 2.0, 3.0]) + assert asarray_or_pandas([1, 2, 3], dtype=float).dtype == np.dtype(float) + a_view = asarray_or_pandas(a, dtype=a.dtype) + a_view[0] = 99 + assert a[0] == 99 + global have_pandas + if have_pandas: + s = pandas.Series([1, 2, 3], name="A", index=[10, 20, 30]) + s_view1 = asarray_or_pandas(s) + assert s_view1.name == "A" + assert np.array_equal(s_view1.index, [10, 20, 30]) + s_view1[10] = 101 + assert s[10] == 101 + s_copy = asarray_or_pandas(s, copy=True) + assert s_copy.name == "A" + assert np.array_equal(s_copy.index, [10, 20, 30]) + assert np.array_equal(s_copy, s) + s_copy[10] = 100 + assert not np.array_equal(s_copy, s) + assert asarray_or_pandas(s, dtype=float).dtype == np.dtype(float) + s_view2 = asarray_or_pandas(s, dtype=s.dtype) + assert s_view2.name == "A" + assert np.array_equal(s_view2.index, [10, 20, 30]) + s_view2[10] = 99 + assert s[10] == 99 + + df = pandas.DataFrame([[1, 2, 3]], columns=["A", "B", "C"], index=[10]) + df_view1 = asarray_or_pandas(df) + df_view1.loc[10, "A"] = 101 + assert np.array_equal(df_view1.columns, ["A", "B", "C"]) + assert np.array_equal(df_view1.index, [10]) + assert df.loc[10, "A"] == 101 + df_copy = asarray_or_pandas(df, copy=True) + assert np.array_equal(df_copy, df) + assert np.array_equal(df_copy.columns, ["A", "B", "C"]) + assert np.array_equal(df_copy.index, [10]) + df_copy.loc[10, "A"] = 100 + assert not np.array_equal(df_copy, df) + df_converted = asarray_or_pandas(df, dtype=float) + assert df_converted["A"].dtype == np.dtype(float) + assert np.allclose(df_converted, df) + assert np.array_equal(df_converted.columns, ["A", "B", "C"]) + assert np.array_equal(df_converted.index, [10]) + df_view2 = asarray_or_pandas(df, dtype=df["A"].dtype) + assert np.array_equal(df_view2.columns, ["A", "B", "C"]) + assert np.array_equal(df_view2.index, [10]) + # This actually makes a copy, not a view, because of a pandas bug: + # https://github.com/pydata/pandas/issues/1572 + assert np.array_equal(df, df_view2) + # df_view2[0][0] = 99 + # assert df[0][0] == 99 + + had_pandas = have_pandas + try: + have_pandas = False + assert type(asarray_or_pandas(pandas.Series([1, 2, 3]))) is np.ndarray + assert type(asarray_or_pandas(pandas.DataFrame([[1, 2, 3]]))) is np.ndarray + finally: + have_pandas = had_pandas + + +# Like np.atleast_2d, but this converts lower-dimensional arrays into columns, +# instead of rows. It also converts ndarray subclasses into basic ndarrays, +# which makes it easier to guarantee correctness. However, there are many +# places in the code where we want to preserve pandas indexing information if +# present, so there is also an option +def atleast_2d_column_default(a, preserve_pandas=False): + if preserve_pandas and have_pandas: + if isinstance(a, pandas.Series): + return pandas.DataFrame(a) + elif isinstance(a, pandas.DataFrame): + return a + # fall through + a = np.asarray(a) + a = np.atleast_1d(a) + if a.ndim <= 1: + a = a.reshape((-1, 1)) + assert a.ndim >= 2 + return a + + +def test_atleast_2d_column_default(): + import warnings + + assert np.all(atleast_2d_column_default([1, 2, 3]) == [[1], [2], [3]]) + + assert atleast_2d_column_default(1).shape == (1, 1) + assert atleast_2d_column_default([1]).shape == (1, 1) + assert atleast_2d_column_default([[1]]).shape == (1, 1) + assert atleast_2d_column_default([[[1]]]).shape == (1, 1, 1) + + assert atleast_2d_column_default([1, 2, 3]).shape == (3, 1) + assert atleast_2d_column_default([[1], [2], [3]]).shape == (3, 1) + + with warnings.catch_warnings() as w: + warnings.filterwarnings( + "ignore", "the matrix subclass", PendingDeprecationWarning + ) + assert type(atleast_2d_column_default(np.matrix(1))) == np.ndarray + assert w is None + + global have_pandas + if have_pandas: + assert type(atleast_2d_column_default(pandas.Series([1, 2]))) == np.ndarray + assert ( + type(atleast_2d_column_default(pandas.DataFrame([[1], [2]]))) == np.ndarray + ) + assert ( + type(atleast_2d_column_default(pandas.Series([1, 2]), preserve_pandas=True)) + == pandas.DataFrame + ) + assert ( + type( + atleast_2d_column_default( + pandas.DataFrame([[1], [2]]), preserve_pandas=True + ) + ) + == pandas.DataFrame + ) + s = pandas.Series([10, 11, 12], name="hi", index=["a", "b", "c"]) + df = atleast_2d_column_default(s, preserve_pandas=True) + assert isinstance(df, pandas.DataFrame) + assert np.all(df.columns == ["hi"]) + assert np.all(df.index == ["a", "b", "c"]) + with warnings.catch_warnings() as w: + warnings.filterwarnings( + "ignore", "the matrix subclass", PendingDeprecationWarning + ) + assert ( + type(atleast_2d_column_default(np.matrix(1), preserve_pandas=True)) + == np.ndarray + ) + assert w is None + assert ( + type(atleast_2d_column_default([1, 2, 3], preserve_pandas=True)) == np.ndarray + ) + + if have_pandas: + had_pandas = have_pandas + try: + have_pandas = False + assert ( + type( + atleast_2d_column_default( + pandas.Series([1, 2]), preserve_pandas=True + ) + ) + == np.ndarray + ) + assert ( + type( + atleast_2d_column_default( + pandas.DataFrame([[1], [2]]), preserve_pandas=True + ) + ) + == np.ndarray + ) + finally: + have_pandas = had_pandas + + +# A version of .reshape() that knows how to down-convert a 1-column +# pandas.DataFrame into a pandas.Series. Useful for code that wants to be +# agnostic between 1d and 2d data, with the pattern: +# new_a = atleast_2d_column_default(a, preserve_pandas=True) +# # do stuff to new_a, which can assume it's always 2 dimensional +# return pandas_friendly_reshape(new_a, a.shape) +def pandas_friendly_reshape(a, new_shape): + if not have_pandas: + return a.reshape(new_shape) + if not isinstance(a, pandas.DataFrame): + return a.reshape(new_shape) + # we have a DataFrame. Only supported reshapes are no-op, and + # single-column DataFrame -> Series. + if new_shape == a.shape: + return a + if len(new_shape) == 1 and a.shape[1] == 1: + if new_shape[0] != a.shape[0]: + raise ValueError("arrays have incompatible sizes") + return a[a.columns[0]] + raise ValueError( + "cannot reshape a DataFrame with shape %s to shape %s" % (a.shape, new_shape) + ) + + +def test_pandas_friendly_reshape(): + import pytest + + global have_pandas + assert np.allclose( + pandas_friendly_reshape(np.arange(10).reshape(5, 2), (2, 5)), + np.arange(10).reshape(2, 5), + ) + if have_pandas: + df = pandas.DataFrame({"x": [1, 2, 3]}, index=["a", "b", "c"]) + noop = pandas_friendly_reshape(df, (3, 1)) + assert isinstance(noop, pandas.DataFrame) + assert np.array_equal(noop.index, ["a", "b", "c"]) + assert np.array_equal(noop.columns, ["x"]) + squozen = pandas_friendly_reshape(df, (3,)) + assert isinstance(squozen, pandas.Series) + assert np.array_equal(squozen.index, ["a", "b", "c"]) + assert squozen.name == "x" + + pytest.raises(ValueError, pandas_friendly_reshape, df, (4,)) + pytest.raises(ValueError, pandas_friendly_reshape, df, (1, 3)) + pytest.raises(ValueError, pandas_friendly_reshape, df, (3, 3)) + + had_pandas = have_pandas + try: + have_pandas = False + # this will try to do a reshape directly, and DataFrames *have* no + # reshape method + pytest.raises(AttributeError, pandas_friendly_reshape, df, (3,)) + finally: + have_pandas = had_pandas + + +def uniqueify_list(seq): + seq_new = [] + seen = set() + for obj in seq: + if obj not in seen: + seq_new.append(obj) + seen.add(obj) + return seq_new + + +def test_to_uniqueify_list(): + assert uniqueify_list([1, 2, 3]) == [1, 2, 3] + assert uniqueify_list([1, 3, 3, 2, 3, 1]) == [1, 3, 2] + assert uniqueify_list([3, 2, 1, 4, 1, 2, 3]) == [3, 2, 1, 4] + + +for float_type in ("float128", "float96", "float64"): + if hasattr(np, float_type): + widest_float = getattr(np, float_type) + break +else: # pragma: no cover + assert False +for complex_type in ("complex256", "complex196", "complex128"): + if hasattr(np, complex_type): + widest_complex = getattr(np, complex_type) + break +else: # pragma: no cover + assert False + + +def wide_dtype_for(arr): + arr = np.asarray(arr) + if safe_issubdtype(arr.dtype, np.integer) or safe_issubdtype( + arr.dtype, np.floating + ): + return widest_float + elif safe_issubdtype(arr.dtype, np.complexfloating): + return widest_complex + raise ValueError("cannot widen a non-numeric type %r" % (arr.dtype,)) + + +def widen(arr): + return np.asarray(arr, dtype=wide_dtype_for(arr)) + + +def test_wide_dtype_for_and_widen(): + assert np.allclose(widen([1, 2, 3]), [1, 2, 3]) + assert widen([1, 2, 3]).dtype == widest_float + assert np.allclose(widen([1.0, 2.0, 3.0]), [1, 2, 3]) + assert widen([1.0, 2.0, 3.0]).dtype == widest_float + assert np.allclose(widen([1 + 0j, 2, 3]), [1, 2, 3]) + assert widen([1 + 0j, 2, 3]).dtype == widest_complex + import pytest + + pytest.raises(ValueError, widen, ["hi"]) + + +class PushbackAdapter(object): + def __init__(self, it): + self._it = it + self._pushed = [] + + def __iter__(self): + return self + + def push_back(self, obj): + self._pushed.append(obj) + + def next(self): + if self._pushed: + return self._pushed.pop() + else: + # May raise StopIteration + return next(self._it) + + __next__ = next + + def peek(self): + try: + obj = next(self) + except StopIteration: + raise ValueError("no more data") + self.push_back(obj) + return obj + + def has_more(self): + try: + self.peek() + except ValueError: + return False + else: + return True + + +def test_PushbackAdapter(): + it = PushbackAdapter(iter([1, 2, 3, 4])) + assert it.has_more() + assert next(it) == 1 + it.push_back(0) + assert next(it) == 0 + assert next(it) == 2 + assert it.peek() == 3 + it.push_back(10) + assert it.peek() == 10 + it.push_back(20) + assert it.peek() == 20 + assert it.has_more() + assert list(it) == [20, 10, 3, 4] + assert not it.has_more() + + +# The IPython pretty-printer gives very nice output that is difficult to get +# otherwise, e.g., look how much more readable this is than if it were all +# smooshed onto one line: +# +# ModelDesc(input_code='y ~ x*asdf', +# lhs_terms=[Term([EvalFactor('y')])], +# rhs_terms=[Term([]), +# Term([EvalFactor('x')]), +# Term([EvalFactor('asdf')]), +# Term([EvalFactor('x'), EvalFactor('asdf')])], +# ) +# +# But, we don't want to assume it always exists; nor do we want to be +# re-writing every repr function twice, once for regular repr and once for +# the pretty printer. So, here's an ugly fallback implementation that can be +# used unconditionally to implement __repr__ in terms of _pretty_repr_. +# +# Pretty printer docs: +# http://ipython.org/ipython-doc/dev/api/generated/IPython.lib.pretty.html + + +class _MiniPPrinter(object): + def __init__(self): + self._out = StringIO() + self.indentation = 0 + + def text(self, text): + self._out.write(text) + + def breakable(self, sep=" "): + self._out.write(sep) + + def begin_group(self, _, text): + self.text(text) + + def end_group(self, _, text): + self.text(text) + + def pretty(self, obj): + if hasattr(obj, "_repr_pretty_"): + obj._repr_pretty_(self, False) + else: + self.text(repr(obj)) + + def getvalue(self): + return self._out.getvalue() + + +def _mini_pretty(obj): + printer = _MiniPPrinter() + printer.pretty(obj) + return printer.getvalue() + + +def repr_pretty_delegate(obj): + # If IPython is already loaded, then might as well use it. (Most commonly + # this will occur if we are in an IPython session, but somehow someone has + # called repr() directly. This can happen for example if printing an + # container like a namedtuple that IPython lacks special code for + # pretty-printing.) But, if IPython is not already imported, we do not + # attempt to import it. This makes patsy itself faster to import (as of + # Nov. 2012 I measured the extra overhead from loading IPython as ~4 + # seconds on a cold cache), it prevents IPython from automatically + # spawning a bunch of child processes (!) which may not be what you want + # if you are not otherwise using IPython, and it avoids annoying the + # pandas people who have some hack to tell whether you are using IPython + # in their test suite (see patsy bug #12). + if optional_dep_ok and "IPython" in sys.modules: + from IPython.lib.pretty import pretty + + return pretty(obj) + else: + return _mini_pretty(obj) + + +def repr_pretty_impl(p, obj, args, kwargs=[]): + name = obj.__class__.__name__ + p.begin_group(len(name) + 1, "%s(" % (name,)) + started = [False] + + def new_item(): + if started[0]: + p.text(",") + p.breakable() + started[0] = True + + for arg in args: + new_item() + p.pretty(arg) + for label, value in kwargs: + new_item() + p.begin_group(len(label) + 1, "%s=" % (label,)) + p.pretty(value) + p.end_group(len(label) + 1, "") + p.end_group(len(name) + 1, ")") + + +def test_repr_pretty(): + assert repr_pretty_delegate("asdf") == "'asdf'" + printer = _MiniPPrinter() + + class MyClass(object): + pass + + repr_pretty_impl(printer, MyClass(), ["a", 1], [("foo", "bar"), ("asdf", "asdf")]) + assert printer.getvalue() == "MyClass('a', 1, foo='bar', asdf='asdf')" + + +# In Python 3, objects of different types are not generally comparable, so a +# list of heterogeneous types cannot be sorted. This implements a Python 2 +# style comparison for arbitrary types. (It works on Python 2 too, but just +# gives you the built-in ordering.) To understand why this is tricky, consider +# this example: +# a = 1 # type 'int' +# b = 1.5 # type 'float' +# class gggg: +# pass +# c = gggg() +# sorted([a, b, c]) +# The fallback ordering sorts by class name, so according to the fallback +# ordering, we have b < c < a. But, of course, a and b are comparable (even +# though they're of different types), so we also have a < b. This is +# inconsistent. There is no general solution to this problem (which I guess is +# why Python 3 stopped trying), but the worst offender is all the different +# "numeric" classes (int, float, complex, decimal, rational...), so as a +# special-case, we sort all numeric objects to the start of the list. +# (In Python 2, there is also a similar special case for str and unicode, but +# we don't have to worry about that for Python 3.) +class SortAnythingKey(object): + def __init__(self, obj): + self.obj = obj + + def _python_lt(self, other_obj): + # On Py2, < never raises an error, so this is just <. (Actually it + # does raise a TypeError for comparing complex to numeric, but not for + # comparisons of complex to other types. Sigh. Whatever.) + # On Py3, this returns a bool if available, and otherwise returns + # NotImplemented + try: + return self.obj < other_obj + except TypeError: + return NotImplemented + + def __lt__(self, other): + assert isinstance(other, SortAnythingKey) + result = self._python_lt(other.obj) + if result is not NotImplemented: + return result + # Okay, that didn't work, time to fall back. + # If one of these is a number, then it is smaller. + if self._python_lt(0) is not NotImplemented: + return True + if other._python_lt(0) is not NotImplemented: + return False + # Also check ==, since it may well be defined for otherwise + # unorderable objects, and if so then we should be consistent with + # it: + if self.obj == other.obj: + return False + # Otherwise, we break ties based on class name and memory position + return (self.obj.__class__.__name__, id(self.obj)) < ( + other.obj.__class__.__name__, + id(other.obj), + ) + + +def test_SortAnythingKey(): + assert sorted([20, 10, 0, 15], key=SortAnythingKey) == [0, 10, 15, 20] + assert sorted([10, -1.5], key=SortAnythingKey) == [-1.5, 10] + assert sorted([10, "a", 20.5, "b"], key=SortAnythingKey) == [10, 20.5, "a", "b"] + + class a(object): + pass + + class b(object): + pass + + class z(object): + pass + + a_obj = a() + b_obj = b() + z_obj = z() + o_obj = object() + assert sorted([z_obj, a_obj, 1, b_obj, o_obj], key=SortAnythingKey) == [ + 1, + a_obj, + b_obj, + o_obj, + z_obj, + ] + + +# NaN checking functions that work on arbitrary objects, on old Python +# versions (math.isnan is only in 2.6+), etc. +def safe_scalar_isnan(x): + try: + return np.isnan(float(x)) + except (TypeError, ValueError, NotImplementedError): + return False + + +safe_isnan = np.vectorize(safe_scalar_isnan, otypes=[bool]) + + +def test_safe_scalar_isnan(): + assert not safe_scalar_isnan(True) + assert not safe_scalar_isnan(None) + assert not safe_scalar_isnan("sadf") + assert not safe_scalar_isnan((1, 2, 3)) + assert not safe_scalar_isnan(np.asarray([1, 2, 3])) + assert not safe_scalar_isnan([np.nan]) + assert safe_scalar_isnan(np.nan) + assert safe_scalar_isnan(np.float32(np.nan)) + assert safe_scalar_isnan(float(np.nan)) + + +def test_safe_isnan(): + assert np.array_equal( + safe_isnan([1, True, None, np.nan, "asdf"]), [False, False, False, True, False] + ) + assert safe_isnan(np.nan).ndim == 0 + assert safe_isnan(np.nan) + assert not safe_isnan(None) + # raw isnan raises a *different* error for strings than for objects: + assert not safe_isnan("asdf") + + +def iterable(obj): + try: + iter(obj) + except Exception: + return False + return True + + +def test_iterable(): + assert iterable("asdf") + assert iterable([]) + assert iterable({"a": 1}) + assert not iterable(1) + assert not iterable(iterable) + + +##### Handling Pandas's categorical stuff is horrible and hateful + +# Basically they decided that they didn't like how numpy does things, so their +# categorical stuff is *kinda* like how numpy would do it (e.g. they have a +# special ".dtype" attribute to mark categorical data), so by default you'll +# find yourself using the same code paths to handle pandas categorical data +# and other non-categorical data. BUT, all the idioms for detecting +# categorical data blow up with errors if you try them with real numpy dtypes, +# and all numpy's idioms for detecting non-categorical types blow up with +# errors if you try them with pandas categorical stuff. So basically they have +# just poisoned all code that touches dtypes; the old numpy stuff is unsafe, +# and you must use special code like below. +# +# Also there are hoops to jump through to handle both the old style +# (Categorical objects) and new-style (Series with dtype="category"). + + +# Needed to support pandas < 0.15 +def pandas_Categorical_from_codes(codes, categories): + assert have_pandas_categorical + + # Old versions of pandas sometimes fail to coerce this to an array and + # just return it directly from .labels (?!). + codes = np.asarray(codes) + if hasattr(pandas.Categorical, "from_codes"): + return pandas.Categorical.from_codes(codes, categories) + else: + return pandas.Categorical(codes, categories) + + +def test_pandas_Categorical_from_codes(): + if not have_pandas_categorical: + return + c = pandas_Categorical_from_codes([1, 1, 0, -1], ["a", "b"]) + assert np.all(np.asarray(c)[:-1] == ["b", "b", "a"]) + assert np.isnan(np.asarray(c)[-1]) + + +# Needed to support pandas < 0.15 +def pandas_Categorical_categories(cat): + # In 0.15+, a categorical Series has a .cat attribute which is similar to + # a Categorical object, and Categorical objects are what have .categories + # and .codes attributes. + if hasattr(cat, "cat"): + cat = cat.cat + if hasattr(cat, "categories"): + return cat.categories + else: + return cat.levels + + +# Needed to support pandas < 0.15 +def pandas_Categorical_codes(cat): + # In 0.15+, a categorical Series has a .cat attribute which is a + # Categorical object, and Categorical objects are what have .categories / + # .codes attributes. + if hasattr(cat, "cat"): + cat = cat.cat + if hasattr(cat, "codes"): + return cat.codes + else: + return cat.labels + + +def test_pandas_Categorical_accessors(): + if not have_pandas_categorical: + return + c = pandas_Categorical_from_codes([1, 1, 0, -1], ["a", "b"]) + assert np.all(pandas_Categorical_categories(c) == ["a", "b"]) + assert np.all(pandas_Categorical_codes(c) == [1, 1, 0, -1]) + + if have_pandas_categorical_dtype: + s = pandas.Series(c) + assert np.all(pandas_Categorical_categories(s) == ["a", "b"]) + assert np.all(pandas_Categorical_codes(s) == [1, 1, 0, -1]) + + +# Needed to support pandas >= 0.15 (!) +def safe_is_pandas_categorical_dtype(dt): + if not have_pandas_categorical_dtype: + return False + return _pandas_is_categorical_dtype(dt) + + +# Needed to support pandas >= 0.15 (!) +def safe_is_pandas_categorical(data): + if not have_pandas_categorical: + return False + if isinstance(data, pandas.Categorical): + return True + if hasattr(data, "dtype"): + return safe_is_pandas_categorical_dtype(data.dtype) + return False + + +def test_safe_is_pandas_categorical(): + assert not safe_is_pandas_categorical(np.arange(10)) + + if have_pandas_categorical: + c_obj = pandas.Categorical(["a", "b"]) + assert safe_is_pandas_categorical(c_obj) + + if have_pandas_categorical_dtype: + s_obj = pandas.Series(["a", "b"], dtype="category") + assert safe_is_pandas_categorical(s_obj) + + +# Needed to support pandas >= 0.15 (!) +# Calling np.issubdtype on a pandas categorical will blow up -- the officially +# recommended solution is to replace every piece of code like +# np.issubdtype(foo.dtype, bool) +# with code like +# isinstance(foo.dtype, np.dtype) and np.issubdtype(foo.dtype, bool) +# or +# not pandas.is_categorical_dtype(foo.dtype) and issubdtype(foo.dtype, bool) +# We do the latter (with extra hoops) because the isinstance check is not +# safe. See +# https://github.com/pydata/pandas/issues/9581 +# https://github.com/pydata/pandas/issues/9581#issuecomment-77099564 +def safe_issubdtype(dt1, dt2): + if safe_is_pandas_categorical_dtype(dt1): + return False + return np.issubdtype(dt1, dt2) + + +def test_safe_issubdtype(): + assert safe_issubdtype(int, np.integer) + assert safe_issubdtype(np.dtype(float), np.floating) + assert not safe_issubdtype(int, np.floating) + assert not safe_issubdtype(np.dtype(float), np.integer) + + if have_pandas_categorical_dtype: + bad_dtype = pandas.Series(["a", "b"], dtype="category") + assert not safe_issubdtype(bad_dtype, np.integer) + + +def no_pickling(*args, **kwargs): + raise NotImplementedError( + "Sorry, pickling not yet supported. " + "See https://github.com/pydata/patsy/issues/26 if you want to " + "help." + ) + + +def assert_no_pickling(obj): + import pickle + import pytest + + pytest.raises(NotImplementedError, pickle.dumps, obj) + + +# Use like: +# if safe_string_eq(constraints, "center"): +# ... +# where 'constraints' might be a string or an array. (If it's an array, then +# we can't use == becaues it might broadcast and ugh.) +def safe_string_eq(obj, value): + if isinstance(obj, str): + return obj == value + else: + return False + + +def test_safe_string_eq(): + assert safe_string_eq("foo", "foo") + assert not safe_string_eq("foo", "bar") + assert not safe_string_eq(np.empty((2, 2)), "foo") diff --git a/venv/lib/python3.10/site-packages/patsy/version.py b/venv/lib/python3.10/site-packages/patsy/version.py new file mode 100644 index 0000000000000000000000000000000000000000..c16a1becd5dee399f66d2280fb7d55e73ee9c152 --- /dev/null +++ b/venv/lib/python3.10/site-packages/patsy/version.py @@ -0,0 +1,20 @@ +# This file is part of Patsy +# Copyright (C) 2011-2014 Nathaniel Smith +# See file LICENSE.txt for license information. + +# This file must be kept very simple, because it is consumed from several +# places -- it is imported by patsy/__init__.py, execfile'd by setup.py, etc. + +# We use a simple scheme: +# 1.0.1 -> 1.0.1+dev -> 1.1.0 -> 1.1.0+dev +# where the +dev versions are never released into the wild, they're just what +# we stick into the VCS in between releases. +# +# This is compatible with PEP 440: +# http://legacy.python.org/dev/peps/pep-0440/ +# via the use of the "local suffix" "+dev", which is disallowed on index +# servers and causes 1.0.1+dev to sort after plain 1.0.1, which is what we +# want. (Contrast with the special suffix 1.0.1.dev, which sorts *before* +# 1.0.1.) + +__version__ = "1.0.1" diff --git a/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ea8c3fd5005b0470c94be125ad04c6eb0a6739fc --- /dev/null +++ b/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/METADATA @@ -0,0 +1,177 @@ +Metadata-Version: 2.4 +Name: pillow +Version: 11.3.0 +Summary: Python Imaging Library (Fork) +Author-email: "Jeffrey A. Clark" +License-Expression: MIT-CMU +Project-URL: Changelog, https://github.com/python-pillow/Pillow/releases +Project-URL: Documentation, https://pillow.readthedocs.io +Project-URL: Funding, https://tidelift.com/subscription/pkg/pypi-pillow?utm_source=pypi-pillow&utm_medium=pypi +Project-URL: Homepage, https://python-pillow.github.io +Project-URL: Mastodon, https://fosstodon.org/@pillow +Project-URL: Release notes, https://pillow.readthedocs.io/en/stable/releasenotes/index.html +Project-URL: Source, https://github.com/python-pillow/Pillow +Keywords: Imaging +Classifier: Development Status :: 6 - Mature +Classifier: Programming Language :: Python :: 3 :: Only +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: Topic :: Multimedia :: Graphics +Classifier: Topic :: Multimedia :: Graphics :: Capture :: Digital Camera +Classifier: Topic :: Multimedia :: Graphics :: Capture :: Screen Capture +Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion +Classifier: Topic :: Multimedia :: Graphics :: Viewers +Classifier: Typing :: Typed +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +Provides-Extra: docs +Requires-Dist: furo; extra == "docs" +Requires-Dist: olefile; extra == "docs" +Requires-Dist: sphinx>=8.2; extra == "docs" +Requires-Dist: sphinx-autobuild; extra == "docs" +Requires-Dist: sphinx-copybutton; extra == "docs" +Requires-Dist: sphinx-inline-tabs; extra == "docs" +Requires-Dist: sphinxext-opengraph; extra == "docs" +Provides-Extra: fpx +Requires-Dist: olefile; extra == "fpx" +Provides-Extra: mic +Requires-Dist: olefile; extra == "mic" +Provides-Extra: test-arrow +Requires-Dist: pyarrow; extra == "test-arrow" +Provides-Extra: tests +Requires-Dist: check-manifest; extra == "tests" +Requires-Dist: coverage>=7.4.2; extra == "tests" +Requires-Dist: defusedxml; extra == "tests" +Requires-Dist: markdown2; extra == "tests" +Requires-Dist: olefile; extra == "tests" +Requires-Dist: packaging; extra == "tests" +Requires-Dist: pyroma; extra == "tests" +Requires-Dist: pytest; extra == "tests" +Requires-Dist: pytest-cov; extra == "tests" +Requires-Dist: pytest-timeout; extra == "tests" +Requires-Dist: pytest-xdist; extra == "tests" +Requires-Dist: trove-classifiers>=2024.10.12; extra == "tests" +Provides-Extra: typing +Requires-Dist: typing-extensions; python_version < "3.10" and extra == "typing" +Provides-Extra: xmp +Requires-Dist: defusedxml; extra == "xmp" +Dynamic: license-file + +

+ Pillow logo +

+ +# Pillow + +## Python Imaging Library (Fork) + +Pillow is the friendly PIL fork by [Jeffrey A. Clark and +contributors](https://github.com/python-pillow/Pillow/graphs/contributors). +PIL is the Python Imaging Library by Fredrik Lundh and contributors. +As of 2019, Pillow development is +[supported by Tidelift](https://tidelift.com/subscription/pkg/pypi-pillow?utm_source=pypi-pillow&utm_medium=readme&utm_campaign=enterprise). + + + + + + + + + + + + + + + + + + +
docs + Documentation Status +
tests + GitHub Actions build status (Lint) + GitHub Actions build status (Test Linux and macOS) + GitHub Actions build status (Test Windows) + GitHub Actions build status (Test MinGW) + GitHub Actions build status (Test Cygwin) + GitHub Actions build status (Test Docker) + GitHub Actions build status (Wheels) + Code coverage + Fuzzing Status +
package + Zenodo + Tidelift + Newest PyPI version + Number of PyPI downloads + OpenSSF Best Practices +
social + Join the chat at https://gitter.im/python-pillow/Pillow + Follow on https://fosstodon.org/@pillow +
+ +## Overview + +The Python Imaging Library adds image processing capabilities to your Python interpreter. + +This library provides extensive file format support, an efficient internal representation, and fairly powerful image processing capabilities. + +The core image library is designed for fast access to data stored in a few basic pixel formats. It should provide a solid foundation for a general image processing tool. + +## More information + +- [Documentation](https://pillow.readthedocs.io/) + - [Installation](https://pillow.readthedocs.io/en/latest/installation/basic-installation.html) + - [Handbook](https://pillow.readthedocs.io/en/latest/handbook/index.html) +- [Contribute](https://github.com/python-pillow/Pillow/blob/main/.github/CONTRIBUTING.md) + - [Issues](https://github.com/python-pillow/Pillow/issues) + - [Pull requests](https://github.com/python-pillow/Pillow/pulls) +- [Release notes](https://pillow.readthedocs.io/en/stable/releasenotes/index.html) +- [Changelog](https://github.com/python-pillow/Pillow/releases) + - [Pre-fork](https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst#pre-fork) + +## Report a vulnerability + +To report a security vulnerability, please follow the procedure described in the [Tidelift security policy](https://tidelift.com/docs/security). diff --git a/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..c4281a2bbe02b244fe243d2744e7c51e3dbebe56 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/RECORD @@ -0,0 +1,233 @@ +PIL/AvifImagePlugin.py,sha256=5IiDMvMZQXLnS3t25XJjlwgNWmeVSNaGfReWAp-V5lo,8994 +PIL/BdfFontFile.py,sha256=PhlZfIRmEfmorbhZZeSM5eebGo1Ei7fL-lR9XlfTZZA,3285 +PIL/BlpImagePlugin.py,sha256=Ub4vVKBEniiNBEgNizxScEpO1VKbC1w6iecWUU7T-Vs,16533 +PIL/BmpImagePlugin.py,sha256=-SNdj2godmaKYAc08dEng6z3mRPbYYHezjveIR5e-tU,19855 +PIL/BufrStubImagePlugin.py,sha256=JSqDhkPNPnFw0Qcz-gQJl-D_iSCFdtcLvPynshKJ4WM,1730 +PIL/ContainerIO.py,sha256=wkBqL2GDAb5fh3wrtfTGUfqioJipCl-lg2GxbjQrTZw,4604 +PIL/CurImagePlugin.py,sha256=bICiwXZrzSONWBu4bKtshxZSNFj8su0lbDojYntEUYs,1797 +PIL/DcxImagePlugin.py,sha256=DhqsmW7MjmnUSTGZ-Skv9hz1XeX3XoQQoAl9GWLAEEY,2145 +PIL/DdsImagePlugin.py,sha256=fjdfZK_eQtUp_-bjoRmt-5wgOT5GTmvg6aI-itch4mo,18906 +PIL/EpsImagePlugin.py,sha256=ROWwCv08bC_B41eMf2AFe8UW6ZH4_XQ18x12KB_aQLM,16389 +PIL/ExifTags.py,sha256=zW6kVikCosiyoCo7J7R62evD3hoxjKPchnVh8po7CZc,9931 +PIL/FitsImagePlugin.py,sha256=-oDJnAH113CK5qPvwz9lL81fkV1gla_tNfqLcq8zKgo,4644 +PIL/FliImagePlugin.py,sha256=DaWuH8f-9GihS0VVZqF1bT3uDv1Vb0VBl0chnNd82Ow,4786 +PIL/FontFile.py,sha256=St7MxO5Q-oakCLWn3ZrgrtaT3wSsmAarxm8AU-G8Moc,3577 +PIL/FpxImagePlugin.py,sha256=aXfg0YdvNeJhxqh-f-f22D1NobQ8tSVCj-tpLE2PKfE,7293 +PIL/FtexImagePlugin.py,sha256=v2I5YkdfNA3iW35JzKnWry9v6Rgvr0oezGVOuArREac,3535 +PIL/GbrImagePlugin.py,sha256=5t0UfLubTPQcuDDbafwC78OLR7IsD5hjpvhUZ5g8z4A,3006 +PIL/GdImageFile.py,sha256=LP4Uxv3Y2ivGZIyOVuGJarDDVS7zK6F1Q6SNl4wyGuQ,2788 +PIL/GifImagePlugin.py,sha256=SkXboZwxTolq0uteXYX0ncrZiUxyASywqAurOcVAi3U,42201 +PIL/GimpGradientFile.py,sha256=Z_4TUYMdPyUsiP40KSIpMJ5yLGMnBaIKOAkHyiQGEWE,3906 +PIL/GimpPaletteFile.py,sha256=YHEhKThsEVlXVjFQUnGvhDgNsJcfFqUAN0O0ucG9G-Q,1815 +PIL/GribStubImagePlugin.py,sha256=degHg344X3JXL8u-x8NWn08BsmM9wRh-Jg08HHrvfOc,1738 +PIL/Hdf5StubImagePlugin.py,sha256=OuEQijGqVwTTSG4dB2vAyQzmN-NYT22tiuZHFH0Q0Sw,1741 +PIL/IcnsImagePlugin.py,sha256=qvi-OP0g8CRlNlJE--5_rPlfyxLFLlSOil66Fw4TMwU,12949 +PIL/IcoImagePlugin.py,sha256=QCo29Toh08UX8vEcdCAaIeuidSolbPiZlCnQ4rUu2SQ,12491 +PIL/ImImagePlugin.py,sha256=wo5OL2PAcQW2MwRkJnS-N16toZzXWL95jx9FBM7l9ok,11567 +PIL/Image.py,sha256=95Jefi2QFIfZYOyfHNBRTwBtwrnNZsn5oCsLQsBLdK8,148332 +PIL/ImageChops.py,sha256=GEjlymcoDtA5OOeIxQVIX96BD-s6AXhb7TmSLYn2tUg,7946 +PIL/ImageCms.py,sha256=A5ZVaTjjxR6AeDNNvK-hmu0QqKOMTscou6BUBTLob0g,41934 +PIL/ImageColor.py,sha256=IGA9C2umeED_EzS2Cvj6KsU0VutC9RstWIYPe8uDsVk,9441 +PIL/ImageDraw.py,sha256=Enr0ctBHKBnSHVBDlqcIbIAyHgVj5ZbLL-swVb8s8Vo,42845 +PIL/ImageDraw2.py,sha256=pdVMW7bVw3KwhXvRZh28Md4y-2xFfuo5fHcDnaYqVK4,7227 +PIL/ImageEnhance.py,sha256=4Elhz_lyyxLmx0GkSHrwOAmNJ2TkqVQPHejzGihZUMI,3627 +PIL/ImageFile.py,sha256=HLgKqn6K9J4HlnyiPFZUTAfcqxXYjE06fZeKO6V-haw,29334 +PIL/ImageFilter.py,sha256=MiTowY9micg1dSfwZkExXSBNPr2b_11kDCGreP6W8x4,18671 +PIL/ImageFont.py,sha256=rVQm3zwnTFZ1HSp4OeA5THKjTezhE8HMrnOhHzmqfEM,64292 +PIL/ImageGrab.py,sha256=I9PHpsQf2VyNX4T8QL-8awFNotyAzB1mGxTt_I5FbTE,6471 +PIL/ImageMath.py,sha256=XasMsgjaD9p2OZa7naOdpEACq3yJl-Q2RGTf4xo7CgM,11919 +PIL/ImageMode.py,sha256=5yOxODAZ7jG03DsUFrt7eQayTtIpWPgvfyhlXDWwcv8,2681 +PIL/ImageMorph.py,sha256=TowXnk1Q2wX9AXVBDWRRQhCfAbFOUWGMo00vq4yn-fU,8563 +PIL/ImageOps.py,sha256=A69qjt-mxDI99387z_4cHI-wtH85SLL_ENTI9EeOQGI,25525 +PIL/ImagePalette.py,sha256=M5tYUgadWR7mxUEByyVl7IV9QFFzAGiKKmAhCZtdG0w,9009 +PIL/ImagePath.py,sha256=5yUG5XCUil1KKTTA_8PgGhcmg-mnue-GK0FwTBlhjw4,371 +PIL/ImageQt.py,sha256=dQbadF2Lg59OJVjiNVcbz3wvymqEpL-uEZG32b8E-bg,6841 +PIL/ImageSequence.py,sha256=gx2EvywPBEjxNJujCqdpbfAm2BpyNV2_f1IaO3niubw,2200 +PIL/ImageShow.py,sha256=Ju0_Db2B4_n3yKJV9sDsF7_HAgciEdXlq6I1Eiw1YTo,10106 +PIL/ImageStat.py,sha256=S43FZ89r_u4hKCj59lVuWpyVJfhbUy3igXkp9DwaMgM,5325 +PIL/ImageTk.py,sha256=b5SntckGXs0ECsI2MmdJg3CSX6AtELsWh0Ohxu41u_k,8132 +PIL/ImageTransform.py,sha256=-qek7P3lzLddcXt9cWt5w_L11JGp2yY3AJtOfmJAkDc,3916 +PIL/ImageWin.py,sha256=LT05w8_vTfRrC3n9S9pM0TNbXrzZLEJHlCJil7Xv80k,8085 +PIL/ImtImagePlugin.py,sha256=SL5IrsHcblltxtX4v_HVFhYnR6haJ0AOd2NHhZKMImY,2665 +PIL/IptcImagePlugin.py,sha256=3BVI_oEbFEJC-yn6zmp5Joqf8edCJLKH9N5FQanyaV8,6719 +PIL/Jpeg2KImagePlugin.py,sha256=k9UoU7-Hq8vAWi9ZoosA4bfufNJsctBd4ttM1RFxwnk,13865 +PIL/JpegImagePlugin.py,sha256=WaCZTpdmzuCM5mi44bNyN4p1EXOsnKz63qv4XEbm8Ns,31786 +PIL/JpegPresets.py,sha256=lnqWHo4DLIHIulcdHp0NJ7CWexHt8T3w51kIKlLfkIA,12379 +PIL/McIdasImagePlugin.py,sha256=baOIkD-CIIeCgBFTf8kos928PKBuCUqYYa38u3WES_8,1877 +PIL/MicImagePlugin.py,sha256=aoIwkWVyr_X-dPvB6ldZOJF3a9kd_OeuEW3say5Y0QM,2564 +PIL/MpegImagePlugin.py,sha256=g7BZd93kWpFi41SG_wKFoi0yEPsioI4kj45b2F-3Vrw,2010 +PIL/MpoImagePlugin.py,sha256=S45qt7OcY7rBjYlwEk0nUmEj5IOu5z8KVLo066V1RBE,6722 +PIL/MspImagePlugin.py,sha256=oxk_MLUDvzJ4JDuOZCHkmqOPXniG42PHOyNGwe60slY,5892 +PIL/PSDraw.py,sha256=KMBGj3vXaFpblaIcA9KjFFTpdal41AQggY-UgzqoMkQ,6918 +PIL/PaletteFile.py,sha256=suDdAL6VMljXw4oEn1vhTt4DQ4vbpIHGd3A4oxOgE6s,1216 +PIL/PalmImagePlugin.py,sha256=WJ1b8I1xTSAXYDJhIpkVFCLu2LlpbiBD5d1Hr-m2l08,8748 +PIL/PcdImagePlugin.py,sha256=VweZ108HBHeNEfsoE26EOR4ktxqNGSOWOnd58DhS8Fo,1601 +PIL/PcfFontFile.py,sha256=NPZQ0XkbGB8uTlGqgmIPGkwuLMYBdykDeVuvFgIC7JU,7147 +PIL/PcxImagePlugin.py,sha256=2dqnjRjSLbjm8Opub4sZRhOIdYLdn3y7Q_ETV8EmiOQ,6224 +PIL/PdfImagePlugin.py,sha256=AbJA2f4qzH8G1olfmk18SzQlcx3WsipUYDc5bcR8Wvk,9349 +PIL/PdfParser.py,sha256=LnmX0Cm7ZQwGkB1uYP4rvXZUkERmURzmYo78zjeq6VI,37987 +PIL/PixarImagePlugin.py,sha256=l_4GwBd0mATnIXYJbwmmODU2vP7wewLu6BRviHCB2EI,1758 +PIL/PngImagePlugin.py,sha256=jPBNqZ50txFHWIsDikcdkeeBfLNY1PxT5wzcPMcmcmQ,51117 +PIL/PpmImagePlugin.py,sha256=QJM-V-odV7w-prA7B5bLRQcykdC4d7OJ5BBbCvPPIzY,12370 +PIL/PsdImagePlugin.py,sha256=ImnNRG4VANs2GATXVEB5Q-yy1Jskc6XRVRtZYi2fALg,8685 +PIL/QoiImagePlugin.py,sha256=RPO63QsgHAsyPpcxh7ymeMYlnjVu5gT5ELolkvJt0vc,8572 +PIL/SgiImagePlugin.py,sha256=3Ql89s8vycNWjcxJwMw28iksV9Yj2xWoKBQ6c5DHXBg,6389 +PIL/SpiderImagePlugin.py,sha256=Bsg6pfZMctas1xYx__oL-ZZseUReZdnLy5a-aKEJhpE,10249 +PIL/SunImagePlugin.py,sha256=Hdxkhk0pxpBGxYhPJfCDLwsYcO1KjxjtplNMFYibIvk,4589 +PIL/TarIO.py,sha256=BqYUChCBb9F7Sh-uZ86iz1Dtoy2D0obNwGm65z1rdc0,1442 +PIL/TgaImagePlugin.py,sha256=2vDsFTcBUBHw1V80wpVv4tgpLDbPr6yVHi6Fvaqf0HY,6980 +PIL/TiffImagePlugin.py,sha256=IK7Ur131NNyJET-wk50tzLkSyd7TI1lwSES4N_txy5w,85029 +PIL/TiffTags.py,sha256=-gbXLZ5rlHD6crwtY6TkafDm2tamlc5v8e7FjS8PcIg,17082 +PIL/WalImageFile.py,sha256=Lfuq_WZ_V_onwucfUc6GWfvY7z_K4s-5EdaQGu_2DD4,5704 +PIL/WebPImagePlugin.py,sha256=YFWo6_FYBSrzAf6XMbmrF4YRtR4x7tYecCWF7EA13WQ,10010 +PIL/WmfImagePlugin.py,sha256=Z1hzGuHGt08tBLsxgBV7ZVOLdQPykDMYd4RGkw1J8rw,5243 +PIL/XVThumbImagePlugin.py,sha256=cJSapkBasFt11O6XYXxqcyA-njxA5BD3wHhNj6VC7Fk,2115 +PIL/XbmImagePlugin.py,sha256=Fd6GVDEo73nyFICA3Z3w4LjkwoZWvhHB6rKCm5yVrho,2669 +PIL/XpmImagePlugin.py,sha256=jtUKavJCYwIAsJaJwSx8vJsx1oTbCywfDxePENmA93w,4400 +PIL/__init__.py,sha256=Q4KOEpR7S_Xsj30fvOsvR94xEpX4KUsVeUwaVP1fU80,2031 +PIL/__main__.py,sha256=Lpj4vef8mI7jA1sRCUAoVYaeePD_Uc898xF5c7XLx1A,133 +PIL/__pycache__/AvifImagePlugin.cpython-310.pyc,, +PIL/__pycache__/BdfFontFile.cpython-310.pyc,, +PIL/__pycache__/BlpImagePlugin.cpython-310.pyc,, +PIL/__pycache__/BmpImagePlugin.cpython-310.pyc,, +PIL/__pycache__/BufrStubImagePlugin.cpython-310.pyc,, +PIL/__pycache__/ContainerIO.cpython-310.pyc,, +PIL/__pycache__/CurImagePlugin.cpython-310.pyc,, +PIL/__pycache__/DcxImagePlugin.cpython-310.pyc,, +PIL/__pycache__/DdsImagePlugin.cpython-310.pyc,, +PIL/__pycache__/EpsImagePlugin.cpython-310.pyc,, +PIL/__pycache__/ExifTags.cpython-310.pyc,, +PIL/__pycache__/FitsImagePlugin.cpython-310.pyc,, +PIL/__pycache__/FliImagePlugin.cpython-310.pyc,, +PIL/__pycache__/FontFile.cpython-310.pyc,, +PIL/__pycache__/FpxImagePlugin.cpython-310.pyc,, +PIL/__pycache__/FtexImagePlugin.cpython-310.pyc,, +PIL/__pycache__/GbrImagePlugin.cpython-310.pyc,, +PIL/__pycache__/GdImageFile.cpython-310.pyc,, +PIL/__pycache__/GifImagePlugin.cpython-310.pyc,, +PIL/__pycache__/GimpGradientFile.cpython-310.pyc,, +PIL/__pycache__/GimpPaletteFile.cpython-310.pyc,, +PIL/__pycache__/GribStubImagePlugin.cpython-310.pyc,, +PIL/__pycache__/Hdf5StubImagePlugin.cpython-310.pyc,, +PIL/__pycache__/IcnsImagePlugin.cpython-310.pyc,, +PIL/__pycache__/IcoImagePlugin.cpython-310.pyc,, +PIL/__pycache__/ImImagePlugin.cpython-310.pyc,, +PIL/__pycache__/Image.cpython-310.pyc,, +PIL/__pycache__/ImageChops.cpython-310.pyc,, +PIL/__pycache__/ImageCms.cpython-310.pyc,, +PIL/__pycache__/ImageColor.cpython-310.pyc,, +PIL/__pycache__/ImageDraw.cpython-310.pyc,, +PIL/__pycache__/ImageDraw2.cpython-310.pyc,, +PIL/__pycache__/ImageEnhance.cpython-310.pyc,, +PIL/__pycache__/ImageFile.cpython-310.pyc,, +PIL/__pycache__/ImageFilter.cpython-310.pyc,, +PIL/__pycache__/ImageFont.cpython-310.pyc,, +PIL/__pycache__/ImageGrab.cpython-310.pyc,, +PIL/__pycache__/ImageMath.cpython-310.pyc,, +PIL/__pycache__/ImageMode.cpython-310.pyc,, +PIL/__pycache__/ImageMorph.cpython-310.pyc,, +PIL/__pycache__/ImageOps.cpython-310.pyc,, +PIL/__pycache__/ImagePalette.cpython-310.pyc,, +PIL/__pycache__/ImagePath.cpython-310.pyc,, +PIL/__pycache__/ImageQt.cpython-310.pyc,, +PIL/__pycache__/ImageSequence.cpython-310.pyc,, +PIL/__pycache__/ImageShow.cpython-310.pyc,, +PIL/__pycache__/ImageStat.cpython-310.pyc,, +PIL/__pycache__/ImageTk.cpython-310.pyc,, +PIL/__pycache__/ImageTransform.cpython-310.pyc,, +PIL/__pycache__/ImageWin.cpython-310.pyc,, +PIL/__pycache__/ImtImagePlugin.cpython-310.pyc,, +PIL/__pycache__/IptcImagePlugin.cpython-310.pyc,, +PIL/__pycache__/Jpeg2KImagePlugin.cpython-310.pyc,, +PIL/__pycache__/JpegImagePlugin.cpython-310.pyc,, +PIL/__pycache__/JpegPresets.cpython-310.pyc,, +PIL/__pycache__/McIdasImagePlugin.cpython-310.pyc,, +PIL/__pycache__/MicImagePlugin.cpython-310.pyc,, +PIL/__pycache__/MpegImagePlugin.cpython-310.pyc,, +PIL/__pycache__/MpoImagePlugin.cpython-310.pyc,, +PIL/__pycache__/MspImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PSDraw.cpython-310.pyc,, +PIL/__pycache__/PaletteFile.cpython-310.pyc,, +PIL/__pycache__/PalmImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PcdImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PcfFontFile.cpython-310.pyc,, +PIL/__pycache__/PcxImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PdfImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PdfParser.cpython-310.pyc,, +PIL/__pycache__/PixarImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PngImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PpmImagePlugin.cpython-310.pyc,, +PIL/__pycache__/PsdImagePlugin.cpython-310.pyc,, +PIL/__pycache__/QoiImagePlugin.cpython-310.pyc,, +PIL/__pycache__/SgiImagePlugin.cpython-310.pyc,, +PIL/__pycache__/SpiderImagePlugin.cpython-310.pyc,, +PIL/__pycache__/SunImagePlugin.cpython-310.pyc,, +PIL/__pycache__/TarIO.cpython-310.pyc,, +PIL/__pycache__/TgaImagePlugin.cpython-310.pyc,, +PIL/__pycache__/TiffImagePlugin.cpython-310.pyc,, +PIL/__pycache__/TiffTags.cpython-310.pyc,, +PIL/__pycache__/WalImageFile.cpython-310.pyc,, +PIL/__pycache__/WebPImagePlugin.cpython-310.pyc,, +PIL/__pycache__/WmfImagePlugin.cpython-310.pyc,, +PIL/__pycache__/XVThumbImagePlugin.cpython-310.pyc,, +PIL/__pycache__/XbmImagePlugin.cpython-310.pyc,, +PIL/__pycache__/XpmImagePlugin.cpython-310.pyc,, +PIL/__pycache__/__init__.cpython-310.pyc,, +PIL/__pycache__/__main__.cpython-310.pyc,, +PIL/__pycache__/_binary.cpython-310.pyc,, +PIL/__pycache__/_deprecate.cpython-310.pyc,, +PIL/__pycache__/_tkinter_finder.cpython-310.pyc,, +PIL/__pycache__/_typing.cpython-310.pyc,, +PIL/__pycache__/_util.cpython-310.pyc,, +PIL/__pycache__/_version.cpython-310.pyc,, +PIL/__pycache__/features.cpython-310.pyc,, +PIL/__pycache__/report.cpython-310.pyc,, +PIL/_avif.cpython-310-x86_64-linux-gnu.so,sha256=_OLlpUW_hDaovCG426O3dKcytzna0bnEftAStUhyLi4,87889 +PIL/_avif.pyi,sha256=3fBxcSppJr6EOEcUojvflG3Eegg7lv2Qp0dNQQILrP4,63 +PIL/_binary.py,sha256=pcM6AL04GxgmGeLfcH1V1BZHENwIrQH0uxhJ7r0HIL0,2550 +PIL/_deprecate.py,sha256=JYJfJgemvedcdHMH6_RFTDBLNp4vSJqd-o32e3WzNlM,2034 +PIL/_imaging.cpython-310-x86_64-linux-gnu.so,sha256=qYpamZqYqAtfyYPF0efDuQi7e7L9Y-lY95jzN_MYhEw,3345225 +PIL/_imaging.pyi,sha256=StMbXUZS32AegATP1sUHfs5P05A3TD_BiQKsDHQBW40,868 +PIL/_imagingcms.cpython-310-x86_64-linux-gnu.so,sha256=bTOjqVzQAuPoQvyz_HRsMnacDYct0pHYt4i48Gc_r3o,141369 +PIL/_imagingcms.pyi,sha256=brpjxRoiY_2ItyfTrjhKeGEsExe4GPG-25q9AQP8Jp8,4389 +PIL/_imagingft.cpython-310-x86_64-linux-gnu.so,sha256=7b17Tr2yVmWPrudhRvRLujsBEjvoDEI-2BK-UxRGtF4,298297 +PIL/_imagingft.pyi,sha256=IYdFGfApwsqYiJVoD5AVOvgMvnO1eP1J3cMA6L0YZJ0,1806 +PIL/_imagingmath.cpython-310-x86_64-linux-gnu.so,sha256=czXmZlP6DXHYPPzB7NeHNW2aoCYEbPA_i82jGxwz52Y,161896 +PIL/_imagingmath.pyi,sha256=3fBxcSppJr6EOEcUojvflG3Eegg7lv2Qp0dNQQILrP4,63 +PIL/_imagingmorph.cpython-310-x86_64-linux-gnu.so,sha256=Yj96EhgQp4hrO-zx1kpcBPovsltfh5rLOz6RXl4IZAA,35896 +PIL/_imagingmorph.pyi,sha256=3fBxcSppJr6EOEcUojvflG3Eegg7lv2Qp0dNQQILrP4,63 +PIL/_imagingtk.cpython-310-x86_64-linux-gnu.so,sha256=djXYcrWZQG3sMZ7DDmze_lpF_N5Cn3IRvq_zT0EKjVM,45560 +PIL/_imagingtk.pyi,sha256=3fBxcSppJr6EOEcUojvflG3Eegg7lv2Qp0dNQQILrP4,63 +PIL/_tkinter_finder.py,sha256=GIZ4stmFhUosmHKSrdxcjStiocDNfyJn7RBie2SWxU0,538 +PIL/_typing.py,sha256=1NAWJ7Z59TP98cFv9qGpBMgSHbyR4CAByLjMRRbSZxY,1251 +PIL/_util.py,sha256=E76J1WLAe6Xg5yNWYztQwYzxUT_sR_VQxFJu7IZ3S3k,635 +PIL/_version.py,sha256=Zwv2LKWt6v32STL5K9uN7PdcJmZhDlokKTLkDA7Ky1w,87 +PIL/_webp.cpython-310-x86_64-linux-gnu.so,sha256=85GawQF0nCwVzqEFfFOItf3CWRTKTsAuTr_F0hwbt64,84193 +PIL/_webp.pyi,sha256=3fBxcSppJr6EOEcUojvflG3Eegg7lv2Qp0dNQQILrP4,63 +PIL/features.py,sha256=FfyYObVJbzYQUXf8KuRuqY6kvA8md2LorE81k3EuQrw,11479 +PIL/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +PIL/report.py,sha256=4JY6-IU7sH1RKuRbOvy1fUt0dAoi79FX4tYJN3p1DT0,100 +pillow-11.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pillow-11.3.0.dist-info/METADATA,sha256=1T1NePio7-GCOWcR73aEA4bSukzNrUIfWMwAw7NAH3M,9023 +pillow-11.3.0.dist-info/RECORD,, +pillow-11.3.0.dist-info/WHEEL,sha256=Obtqci3x5vy5ZivY2BiOH9GHO8-xQ0d4HFhTOtXMNhw,152 +pillow-11.3.0.dist-info/licenses/LICENSE,sha256=LECn2IlBJv96mTp1JQW5FWlKr-emIIie82isv1S4cUQ,66498 +pillow-11.3.0.dist-info/top_level.txt,sha256=riZqrk-hyZqh5f1Z0Zwii3dKfxEsByhu9cU9IODF-NY,4 +pillow-11.3.0.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +pillow.libs/libXau-154567c4.so.6.0.0,sha256=BUhNJL94y47QMWnxywZyBNgpy3ryHeiCBADSnRFeQyA,22081 +pillow.libs/libavif-01e67780.so.16.3.0,sha256=xCXlA8_rggzsCA_EsWKFzgqPBmT1ihpZCo3iMyvD1P0,5142057 +pillow.libs/libbrotlicommon-c55a5f7a.so.1.1.0,sha256=HaLbMm3YehX759wgF7ZU0kVwhdgX4ukfvQNKytoarw8,144425 +pillow.libs/libbrotlidec-2ced2f3a.so.1.1.0,sha256=BOwekVTiRipkYusnBXmzGGhiPsBwBI6DDWPLkvxAbRE,62337 +pillow.libs/libfreetype-083ff72c.so.6.20.2,sha256=nR7Qj8vHmYmFqPKudV_uWIjG3NoY3ZEIGqySuB3Fxi0,1430825 +pillow.libs/libharfbuzz-fe5b8f8d.so.0.61121.0,sha256=7BYYYjM0M0rNxEo1d1yqqSoOGLCcbs-Jqi1KWqxvomM,908081 +pillow.libs/libjpeg-8a13c6e0.so.62.4.0,sha256=L9LNO3lhekD_kggV6DrgsleI_gXfl3EfWwApiRwxy9k,832177 +pillow.libs/liblcms2-cc10e42f.so.2.0.17,sha256=5JMjEDVKMwxcinhbQl6qhRLaezAiQFYEPSz-KultHe0,519073 +pillow.libs/liblzma-64b7ab39.so.5.8.1,sha256=hN2B2RPEM6wOgvER_g43fNjbNQ_SsrenX2wlAfHW-nA,266369 +pillow.libs/libopenjp2-56811f71.so.2.5.3,sha256=aG9iy-0yE3nj44vnrpTFZBHUNFvejVTlV7QEctmnaTo,585849 +pillow.libs/libpng16-d00bd151.so.16.49.0,sha256=VYiCiAoDB6dnWllbcSpOu9DrHKQ3Th4tepiWdhdg_mw,278001 +pillow.libs/libsharpyuv-60a7c00b.so.0.1.1,sha256=jySHi3I26NspkZW9eAaQsPCDwB8_D_Guh7g5d-ROCAQ,46113 +pillow.libs/libtiff-13a02c81.so.6.1.0,sha256=AH827ZKX4f_-DpYv66BELczkhkVdbNmLLFile8vRVgU,746233 +pillow.libs/libwebp-5f0275c0.so.7.1.10,sha256=s6N3iSclHhrkhSaM_cFqk7IAZrWe1pgGmwJk-wzhSYk,731185 +pillow.libs/libwebpdemux-efaed568.so.2.0.16,sha256=q8bcLAXcqize_gg5VszKAHNQ-nBcDU7VVyFKytD1J68,30217 +pillow.libs/libwebpmux-6f2b1ad9.so.3.1.1,sha256=Amxlm7OxjsJWAu9Q-bI59RnoZ9GiZS6FKb2bGccAPUw,58617 +pillow.libs/libxcb-64009ff3.so.1.1.0,sha256=t0N-0WuuesRJgEn9FOENG9HD59FdDl6rHS6tQqg6SdE,251425 diff --git a/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12e67ca29ff180ca4133d9ec4769226edb266ce4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pillow-11.3.0.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_27_x86_64 +Tag: cp310-cp310-manylinux_2_28_x86_64 + diff --git a/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8df788bc8d91ef4df6c3cd21aa4bdc4d3d883f6f --- /dev/null +++ b/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/licenses/LICENSE @@ -0,0 +1,1487 @@ +The Python Imaging Library (PIL) is + + Copyright © 1997-2011 by Secret Labs AB + Copyright © 1995-2011 by Fredrik Lundh and contributors + +Pillow is the friendly PIL fork. It is + + Copyright © 2010 by Jeffrey A. Clark and contributors + +Like PIL, Pillow is licensed under the open source MIT-CMU License: + +By obtaining, using, and/or copying this software and/or its associated +documentation, you agree that you have read, understood, and will comply +with the following terms and conditions: + +Permission to use, copy, modify and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appears in all copies, and that +both that copyright notice and this permission notice appear in supporting +documentation, and that the name of Secret Labs AB or the author not be +used in advertising or publicity pertaining to distribution of the software +without specific, written prior permission. + +SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, +INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + + +---- + +AOM + +Copyright (c) 2016, Alliance for Open Media. 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. + + +---- + +BROTLI + +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. + +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. + + +---- + +BZIP2 + + +-------------------------------------------------------------------------- + +This program, "bzip2", the associated library "libbzip2", and all +documentation, are copyright (C) 1996-2019 Julian R Seward. 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. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + +3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + +4. 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. + +Julian Seward, jseward@acm.org +bzip2/libbzip2 version 1.0.8 of 13 July 2019 + +-------------------------------------------------------------------------- + + +---- + +DAV1D + +Copyright © 2018-2019, VideoLAN and dav1d authors +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 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. + + +---- + +FREETYPE2 + +The FreeType 2 font engine is copyrighted work and cannot be used +legally without a software license. In order to make this project +usable to a vast majority of developers, we distribute it under two +mutually exclusive open-source licenses. + +This means that *you* must choose *one* of the two licenses described +below, then obey all its terms and conditions when using FreeType 2 in +any of your projects or products. + + - The FreeType License, found in the file `docs/FTL.TXT`, which is + similar to the original BSD license *with* an advertising clause + that forces you to explicitly cite the FreeType project in your + product's documentation. All details are in the license file. + This license is suited to products which don't use the GNU General + Public License. + + Note that this license is compatible to the GNU General Public + License version 3, but not version 2. + + - The GNU General Public License version 2, found in + `docs/GPLv2.TXT` (any later version can be used also), for + programs which already use the GPL. Note that the FTL is + incompatible with GPLv2 due to its advertisement clause. + +The contributed BDF and PCF drivers come with a license similar to +that of the X Window System. It is compatible to the above two +licenses (see files `src/bdf/README` and `src/pcf/README`). The same +holds for the source code files `src/base/fthash.c` and +`include/freetype/internal/fthash.h`; they were part of the BDF driver +in earlier FreeType versions. + +The gzip module uses the zlib license (see `src/gzip/zlib.h`) which +too is compatible to the above two licenses. + +The files `src/autofit/ft-hb.c` and `src/autofit/ft-hb.h` contain code +taken almost verbatim from the HarfBuzz file `hb-ft.cc`, which uses +the 'Old MIT' license, compatible to the above two licenses. + +The MD5 checksum support (only used for debugging in development +builds) is in the public domain. + +-------------------------------------------------------------------------- + + The FreeType Project LICENSE + ---------------------------- + + 2006-Jan-27 + + Copyright 1996-2002, 2006 by + David Turner, Robert Wilhelm, and Werner Lemberg + + + +Introduction +============ + + The FreeType Project is distributed in several archive packages; + some of them may contain, in addition to the FreeType font engine, + various tools and contributions which rely on, or relate to, the + FreeType Project. + + This license applies to all files found in such packages, and + which do not fall under their own explicit license. The license + affects thus the FreeType font engine, the test programs, + documentation and makefiles, at the very least. + + This license was inspired by the BSD, Artistic, and IJG + (Independent JPEG Group) licenses, which all encourage inclusion + and use of free software in commercial and freeware products + alike. As a consequence, its main points are that: + + o We don't promise that this software works. However, we will be + interested in any kind of bug reports. (`as is' distribution) + + o You can use this software for whatever you want, in parts or + full form, without having to pay us. (`royalty-free' usage) + + o You may not pretend that you wrote this software. If you use + it, or only parts of it, in a program, you must acknowledge + somewhere in your documentation that you have used the + FreeType code. (`credits') + + We specifically permit and encourage the inclusion of this + software, with or without modifications, in commercial products. + We disclaim all warranties covering The FreeType Project and + assume no liability related to The FreeType Project. + + + Finally, many people asked us for a preferred form for a + credit/disclaimer to use in compliance with this license. We thus + encourage you to use the following text: + + """ + Portions of this software are copyright © The FreeType + Project (www.freetype.org). All rights reserved. + """ + + Please replace with the value from the FreeType version you + actually use. + + +Legal Terms +=========== + +0. Definitions +-------------- + + Throughout this license, the terms `package', `FreeType Project', + and `FreeType archive' refer to the set of files originally + distributed by the authors (David Turner, Robert Wilhelm, and + Werner Lemberg) as the `FreeType Project', be they named as alpha, + beta or final release. + + `You' refers to the licensee, or person using the project, where + `using' is a generic term including compiling the project's source + code as well as linking it to form a `program' or `executable'. + This program is referred to as `a program using the FreeType + engine'. + + This license applies to all files distributed in the original + FreeType Project, including all source code, binaries and + documentation, unless otherwise stated in the file in its + original, unmodified form as distributed in the original archive. + If you are unsure whether or not a particular file is covered by + this license, you must contact us to verify this. + + The FreeType Project is copyright (C) 1996-2000 by David Turner, + Robert Wilhelm, and Werner Lemberg. All rights reserved except as + specified below. + +1. No Warranty +-------------- + + THE FREETYPE PROJECT IS PROVIDED `AS IS' WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE. IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY DAMAGES CAUSED BY THE USE OR THE INABILITY TO + USE, OF THE FREETYPE PROJECT. + +2. Redistribution +----------------- + + This license grants a worldwide, royalty-free, perpetual and + irrevocable right and license to use, execute, perform, compile, + display, copy, create derivative works of, distribute and + sublicense the FreeType Project (in both source and object code + forms) and derivative works thereof for any purpose; and to + authorize others to exercise some or all of the rights granted + herein, subject to the following conditions: + + o Redistribution of source code must retain this license file + (`FTL.TXT') unaltered; any additions, deletions or changes to + the original files must be clearly indicated in accompanying + documentation. The copyright notices of the unaltered, + original files must be preserved in all copies of source + files. + + o Redistribution in binary form must provide a disclaimer that + states that the software is based in part of the work of the + FreeType Team, in the distribution documentation. We also + encourage you to put an URL to the FreeType web page in your + documentation, though this isn't mandatory. + + These conditions apply to any software derived from or based on + the FreeType Project, not just the unmodified files. If you use + our work, you must acknowledge us. However, no fee need be paid + to us. + +3. Advertising +-------------- + + Neither the FreeType authors and contributors nor you shall use + the name of the other for commercial, advertising, or promotional + purposes without specific prior written permission. + + We suggest, but do not require, that you use one or more of the + following phrases to refer to this software in your documentation + or advertising materials: `FreeType Project', `FreeType Engine', + `FreeType library', or `FreeType Distribution'. + + As you have not signed this license, you are not required to + accept it. However, as the FreeType Project is copyrighted + material, only this license, or another one contracted with the + authors, grants you the right to use, distribute, and modify it. + Therefore, by using, distributing, or modifying the FreeType + Project, you indicate that you understand and accept all the terms + of this license. + +4. Contacts +----------- + + There are two mailing lists related to FreeType: + + o freetype@nongnu.org + + Discusses general use and applications of FreeType, as well as + future and wanted additions to the library and distribution. + If you are looking for support, start in this list if you + haven't found anything to help you in the documentation. + + o freetype-devel@nongnu.org + + Discusses bugs, as well as engine internals, design issues, + specific licenses, porting, etc. + + Our home page can be found at + + https://www.freetype.org + + +--- end of FTL.TXT --- + +The following license details are part of `src/bdf/README`: + +``` +License +******* + +Copyright (C) 2001-2002 by Francesco Zappa Nardelli + +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. + +*** Portions of the driver (that is, bdflib.c and bdf.h): + +Copyright 2000 Computing Research Labs, New Mexico State University +Copyright 2001-2002, 2011 Francesco Zappa Nardelli + +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 COMPUTING RESEARCH LAB OR NEW MEXICO STATE UNIVERSITY 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. + + +Credits +******* + +This driver is based on excellent Mark Leisher's bdf library. If you +find something good in this driver you should probably thank him, not +me. +``` + +The following license details are part of `src/pcf/README`: + +``` +License +******* + +Copyright (C) 2000 by Francesco Zappa Nardelli + +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. + + +Credits +******* + +Keith Packard wrote the pcf driver found in XFree86. His work is at +the same time the specification and the sample implementation of the +PCF format. Undoubtedly, this driver is inspired from his work. +``` + + +---- + +HARFBUZZ + +HarfBuzz is licensed under the so-called "Old MIT" license. Details follow. +For parts of HarfBuzz that are licensed under different licenses see individual +files names COPYING in subdirectories where applicable. + +Copyright © 2010-2022 Google, Inc. +Copyright © 2015-2020 Ebrahim Byagowi +Copyright © 2019,2020 Facebook, Inc. +Copyright © 2012,2015 Mozilla Foundation +Copyright © 2011 Codethink Limited +Copyright © 2008,2010 Nokia Corporation and/or its subsidiary(-ies) +Copyright © 2009 Keith Stribley +Copyright © 2011 Martin Hosken and SIL International +Copyright © 2007 Chris Wilson +Copyright © 2005,2006,2020,2021,2022,2023 Behdad Esfahbod +Copyright © 2004,2007,2008,2009,2010,2013,2021,2022,2023 Red Hat, Inc. +Copyright © 1998-2005 David Turner and Werner Lemberg +Copyright © 2016 Igalia S.L. +Copyright © 2022 Matthias Clasen +Copyright © 2018,2021 Khaled Hosny +Copyright © 2018,2019,2020 Adobe, Inc +Copyright © 2013-2015 Alexei Podtelezhnikov + +For full copyright notices consult the individual files in the package. + + +Permission is hereby granted, without written agreement and without +license or royalty fees, to use, copy, modify, and distribute this +software and its documentation for any purpose, provided that the +above copyright notice and the following two paragraphs appear in +all copies of this software. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR +DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN +IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGE. + +THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, +BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS +ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO +PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + + +---- + +LCMS2 + +Little CMS +Copyright (c) 1998-2020 Marti Maria Saguer + +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. + + +---- + +LIBAVIF + +Copyright 2019 Joe Drago. 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. + +------------------------------------------------------------------------------ + +Files: src/obu.c + +Copyright © 2018-2019, VideoLAN and dav1d authors +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 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. + +------------------------------------------------------------------------------ + +Files: third_party/iccjpeg/* + +In plain English: + +1. We don't promise that this software works. (But if you find any bugs, + please let us know!) +2. You can use this software for whatever you want. You don't have to pay us. +3. You may not pretend that you wrote this software. If you use it in a + program, you must acknowledge somewhere in your documentation that + you've used the IJG code. + +In legalese: + +The authors make NO WARRANTY or representation, either express or implied, +with respect to this software, its quality, accuracy, merchantability, or +fitness for a particular purpose. This software is provided "AS IS", and you, +its user, assume the entire risk as to its quality and accuracy. + +This software is copyright (C) 1991-2013, Thomas G. Lane, Guido Vollbeding. +All Rights Reserved except as specified below. + +Permission is hereby granted to use, copy, modify, and distribute this +software (or portions thereof) for any purpose, without fee, subject to these +conditions: +(1) If any part of the source code for this software is distributed, then this +README file must be included, with this copyright and no-warranty notice +unaltered; and any additions, deletions, or changes to the original files +must be clearly indicated in accompanying documentation. +(2) If only executable code is distributed, then the accompanying +documentation must state that "this software is based in part on the work of +the Independent JPEG Group". +(3) Permission for use of this software is granted only if the user accepts +full responsibility for any undesirable consequences; the authors accept +NO LIABILITY for damages of any kind. + +These conditions apply to any software derived from or based on the IJG code, +not just to the unmodified library. If you use our work, you ought to +acknowledge us. + +Permission is NOT granted for the use of any IJG author's name or company name +in advertising or publicity relating to this software or products derived from +it. This software may be referred to only as "the Independent JPEG Group's +software". + +We specifically permit and encourage the use of this software as the basis of +commercial products, provided that all warranty or liability claims are +assumed by the product vendor. + + +The Unix configuration script "configure" was produced with GNU Autoconf. +It is copyright by the Free Software Foundation but is freely distributable. +The same holds for its supporting scripts (config.guess, config.sub, +ltmain.sh). Another support script, install-sh, is copyright by X Consortium +but is also freely distributable. + +The IJG distribution formerly included code to read and write GIF files. +To avoid entanglement with the Unisys LZW patent, GIF reading support has +been removed altogether, and the GIF writer has been simplified to produce +"uncompressed GIFs". This technique does not use the LZW algorithm; the +resulting GIF files are larger than usual, but are readable by all standard +GIF decoders. + +We are required to state that + "The Graphics Interchange Format(c) is the Copyright property of + CompuServe Incorporated. GIF(sm) is a Service Mark property of + CompuServe Incorporated." + +------------------------------------------------------------------------------ + +Files: contrib/gdk-pixbuf/* + +Copyright 2020 Emmanuel Gil Peyrot. 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. + +------------------------------------------------------------------------------ + +Files: android_jni/gradlew* + + + 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. + +------------------------------------------------------------------------------ + +Files: third_party/libyuv/* + +Copyright 2011 The LibYuv Project Authors. 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 Google 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. + + +---- + +LIBJPEG + +1. We don't promise that this software works. (But if you find any bugs, + please let us know!) +2. You can use this software for whatever you want. You don't have to pay us. +3. You may not pretend that you wrote this software. If you use it in a + program, you must acknowledge somewhere in your documentation that + you've used the IJG code. + +In legalese: + +The authors make NO WARRANTY or representation, either express or implied, +with respect to this software, its quality, accuracy, merchantability, or +fitness for a particular purpose. This software is provided "AS IS", and you, +its user, assume the entire risk as to its quality and accuracy. + +This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. +All Rights Reserved except as specified below. + +Permission is hereby granted to use, copy, modify, and distribute this +software (or portions thereof) for any purpose, without fee, subject to these +conditions: +(1) If any part of the source code for this software is distributed, then this +README file must be included, with this copyright and no-warranty notice +unaltered; and any additions, deletions, or changes to the original files +must be clearly indicated in accompanying documentation. +(2) If only executable code is distributed, then the accompanying +documentation must state that "this software is based in part on the work of +the Independent JPEG Group". +(3) Permission for use of this software is granted only if the user accepts +full responsibility for any undesirable consequences; the authors accept +NO LIABILITY for damages of any kind. + +These conditions apply to any software derived from or based on the IJG code, +not just to the unmodified library. If you use our work, you ought to +acknowledge us. + +Permission is NOT granted for the use of any IJG author's name or company name +in advertising or publicity relating to this software or products derived from +it. This software may be referred to only as "the Independent JPEG Group's +software". + +We specifically permit and encourage the use of this software as the basis of +commercial products, provided that all warranty or liability claims are +assumed by the product vendor. + + +---- + +LIBLZMA + +XZ Utils Licensing +================== + + Different licenses apply to different files in this package. Here + is a rough summary of which licenses apply to which parts of this + package (but check the individual files to be sure!): + + - liblzma is in the public domain. + + - xz, xzdec, and lzmadec command line tools are in the public + domain unless GNU getopt_long had to be compiled and linked + in from the lib directory. The getopt_long code is under + GNU LGPLv2.1+. + + - The scripts to grep, diff, and view compressed files have been + adapted from gzip. These scripts and their documentation are + under GNU GPLv2+. + + - All the documentation in the doc directory and most of the + XZ Utils specific documentation files in other directories + are in the public domain. + + - Translated messages are in the public domain. + + - The build system contains public domain files, and files that + are under GNU GPLv2+ or GNU GPLv3+. None of these files end up + in the binaries being built. + + - Test files and test code in the tests directory, and debugging + utilities in the debug directory are in the public domain. + + - The extra directory may contain public domain files, and files + that are under various free software licenses. + + You can do whatever you want with the files that have been put into + the public domain. If you find public domain legally problematic, + take the previous sentence as a license grant. If you still find + the lack of copyright legally problematic, you have too many + lawyers. + + As usual, this software is provided "as is", without any warranty. + + If you copy significant amounts of public domain code from XZ Utils + into your project, acknowledging this somewhere in your software is + polite (especially if it is proprietary, non-free software), but + naturally it is not legally required. Here is an example of a good + notice to put into "about box" or into documentation: + + This software includes code from XZ Utils . + + The following license texts are included in the following files: + - COPYING.LGPLv2.1: GNU Lesser General Public License version 2.1 + - COPYING.GPLv2: GNU General Public License version 2 + - COPYING.GPLv3: GNU General Public License version 3 + + Note that the toolchain (compiler, linker etc.) may add some code + pieces that are copyrighted. Thus, it is possible that e.g. liblzma + binary wouldn't actually be in the public domain in its entirety + even though it contains no copyrighted code from the XZ Utils source + package. + + If you have questions, don't hesitate to ask the author(s) for more + information. + + +---- + +LIBPNG + +COPYRIGHT NOTICE, DISCLAIMER, and LICENSE +========================================= + +PNG Reference Library License version 2 +--------------------------------------- + + * Copyright (c) 1995-2022 The PNG Reference Library Authors. + * Copyright (c) 2018-2022 Cosmin Truta. + * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson. + * Copyright (c) 1996-1997 Andreas Dilger. + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. + +The software is supplied "as is", without warranty of any kind, +express or implied, including, without limitation, the warranties +of merchantability, fitness for a particular purpose, title, and +non-infringement. In no event shall the Copyright owners, 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, even if advised of the possibility +of such damage. + +Permission is hereby granted to use, copy, modify, and distribute +this software, or portions hereof, for any purpose, without fee, +subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you + use this software in a product, an acknowledgment in the product + documentation would be appreciated, but is not required. + + 2. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 3. This Copyright notice may not be removed or altered from any + source or altered source distribution. + + +PNG Reference Library License version 1 (for libpng 0.5 through 1.6.35) +----------------------------------------------------------------------- + +libpng versions 1.0.7, July 1, 2000, through 1.6.35, July 15, 2018 are +Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson, are +derived from libpng-1.0.6, and are distributed according to the same +disclaimer and license as libpng-1.0.6 with the following individuals +added to the list of Contributing Authors: + + Simon-Pierre Cadieux + Eric S. Raymond + Mans Rullgard + Cosmin Truta + Gilles Vollant + James Yu + Mandar Sahastrabuddhe + Google Inc. + Vadim Barkov + +and with the following additions to the disclaimer: + + There is no warranty against interference with your enjoyment of + the library or against infringement. There is no warranty that our + efforts or the library will fulfill any of your particular purposes + or needs. This library is provided with all faults, and the entire + risk of satisfactory quality, performance, accuracy, and effort is + with the user. + +Some files in the "contrib" directory and some configure-generated +files that are distributed with libpng have other copyright owners, and +are released under other open source licenses. + +libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are +Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from +libpng-0.96, and are distributed according to the same disclaimer and +license as libpng-0.96, with the following individuals added to the +list of Contributing Authors: + + Tom Lane + Glenn Randers-Pehrson + Willem van Schaik + +libpng versions 0.89, June 1996, through 0.96, May 1997, are +Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88, +and are distributed according to the same disclaimer and license as +libpng-0.88, with the following individuals added to the list of +Contributing Authors: + + John Bowler + Kevin Bracey + Sam Bushell + Magnus Holmgren + Greg Roelofs + Tom Tanner + +Some files in the "scripts" directory have other copyright owners, +but are released under this license. + +libpng versions 0.5, May 1995, through 0.88, January 1996, are +Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. + +For the purposes of this copyright and license, "Contributing Authors" +is defined as the following set of individuals: + + Andreas Dilger + Dave Martindale + Guy Eric Schalnat + Paul Schmidt + Tim Wegner + +The PNG Reference Library is supplied "AS IS". The Contributing +Authors and Group 42, Inc. disclaim all warranties, expressed or +implied, including, without limitation, the warranties of +merchantability and of fitness for any purpose. The Contributing +Authors and Group 42, Inc. assume no liability for direct, indirect, +incidental, special, exemplary, or consequential damages, which may +result from the use of the PNG Reference Library, even if advised of +the possibility of such damage. + +Permission is hereby granted to use, copy, modify, and distribute this +source code, or portions hereof, for any purpose, without fee, subject +to the following restrictions: + + 1. The origin of this source code must not be misrepresented. + + 2. Altered versions must be plainly marked as such and must not + be misrepresented as being the original source. + + 3. This Copyright notice may not be removed or altered from any + source or altered source distribution. + +The Contributing Authors and Group 42, Inc. specifically permit, +without fee, and encourage the use of this source code as a component +to supporting the PNG file format in commercial products. If you use +this source code in a product, acknowledgment is not required but would +be appreciated. + + +---- + +LIBTIFF + +Copyright (c) 1988-1997 Sam Leffler +Copyright (c) 1991-1997 Silicon Graphics, Inc. + +Permission to use, copy, modify, distribute, and sell this software and +its documentation for any purpose is hereby granted without fee, provided +that (i) the above copyright notices and this permission notice appear in +all copies of the software and related documentation, and (ii) the names of +Sam Leffler and Silicon Graphics may not be used in any advertising or +publicity relating to the software without the specific, prior written +permission of Sam Leffler and Silicon Graphics. + +THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, +EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY +WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR +ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF +LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE +OF THIS SOFTWARE. + + +---- + +LIBWEBP + +Copyright (c) 2010, Google 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 Google 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. + + +---- + +LIBYUV + +Copyright 2011 The LibYuv Project Authors. 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 Google 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. + + +---- + +OPENJPEG + +* + * The copyright in this software is being made available under the 2-clauses + * BSD License, included below. This software may be subject to other third + * party and contributor rights, including patent rights, and no such rights + * are granted under this license. + * + * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium + * Copyright (c) 2002-2014, Professor Benoit Macq + * Copyright (c) 2003-2014, Antonin Descampe + * Copyright (c) 2003-2009, Francois-Olivier Devaux + * Copyright (c) 2005, Herve Drolon, FreeImage Team + * Copyright (c) 2002-2003, Yannick Verschueren + * Copyright (c) 2001-2003, David Janssens + * Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France + * Copyright (c) 2012, CS Systemes d'Information, France + * + * 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 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. + */ + + +---- + +RAQM + +The MIT License (MIT) + +Copyright © 2015 Information Technology Authority (ITA) +Copyright © 2016 Khaled Hosny + +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. + + +---- + +XAU + +Copyright 1988, 1993, 1994, 1998 The Open Group + +Permission to use, copy, modify, distribute, and sell this software and its +documentation for any purpose is hereby granted without fee, provided that +the above copyright notice appear in all copies and that both that +copyright notice and this permission notice appear in supporting +documentation. + +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 +OPEN GROUP 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. + +Except as contained in this notice, the name of The Open Group shall not be +used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization from The Open Group. + + +---- + +XCB + +Copyright (C) 2001-2006 Bart Massey, Jamey Sharp, and Josh Triplett. +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 +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. + +Except as contained in this notice, the names of the authors +or their institutions shall not be used in advertising or +otherwise to promote the sale, use or other dealings in this +Software without prior written authorization from the +authors. + + +---- + +XDMCP + +Copyright 1989, 1998 The Open Group + +Permission to use, copy, modify, distribute, and sell this software and its +documentation for any purpose is hereby granted without fee, provided that +the above copyright notice appear in all copies and that both that +copyright notice and this permission notice appear in supporting +documentation. + +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 +OPEN GROUP 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. + +Except as contained in this notice, the name of The Open Group shall not be +used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization from The Open Group. + +Author: Keith Packard, MIT X Consortium + + +---- + +ZLIB + + (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. diff --git a/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..b338169ce0c740c335bfe82912227ae8637bd492 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/top_level.txt @@ -0,0 +1 @@ +PIL diff --git a/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/zip-safe b/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/venv/lib/python3.10/site-packages/pillow-11.3.0.dist-info/zip-safe @@ -0,0 +1 @@ + diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__init__.py b/venv/lib/python3.10/site-packages/prometheus_client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..84a7ba82b045dbdd6a255faa6719597951452b2c --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/__init__.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python + +from . import ( + exposition, gc_collector, metrics, metrics_core, platform_collector, + process_collector, registry, +) +from .exposition import ( + CONTENT_TYPE_LATEST, delete_from_gateway, generate_latest, + instance_ip_grouping_key, make_asgi_app, make_wsgi_app, MetricsHandler, + push_to_gateway, pushadd_to_gateway, start_http_server, start_wsgi_server, + write_to_textfile, +) +from .gc_collector import GC_COLLECTOR, GCCollector +from .metrics import ( + Counter, disable_created_metrics, enable_created_metrics, Enum, Gauge, + Histogram, Info, Summary, +) +from .metrics_core import Metric +from .platform_collector import PLATFORM_COLLECTOR, PlatformCollector +from .process_collector import PROCESS_COLLECTOR, ProcessCollector +from .registry import CollectorRegistry, REGISTRY + +__all__ = ( + 'CollectorRegistry', + 'REGISTRY', + 'Metric', + 'Counter', + 'Gauge', + 'Summary', + 'Histogram', + 'Info', + 'Enum', + 'enable_created_metrics', + 'disable_created_metrics', + 'CONTENT_TYPE_LATEST', + 'generate_latest', + 'MetricsHandler', + 'make_wsgi_app', + 'make_asgi_app', + 'start_http_server', + 'start_wsgi_server', + 'write_to_textfile', + 'push_to_gateway', + 'pushadd_to_gateway', + 'delete_from_gateway', + 'instance_ip_grouping_key', + 'ProcessCollector', + 'PROCESS_COLLECTOR', + 'PlatformCollector', + 'PLATFORM_COLLECTOR', + 'GCCollector', + 'GC_COLLECTOR', +) + +if __name__ == '__main__': + c = Counter('cc', 'A counter') + c.inc() + + g = Gauge('gg', 'A gauge') + g.set(17) + + s = Summary('ss', 'A summary', ['a', 'b']) + s.labels('c', 'd').observe(17) + + h = Histogram('hh', 'A histogram') + h.observe(.6) + + start_http_server(8000) + import time + + while True: + time.sleep(1) diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1afad733fbaf8d19a2c0f1843053db731cd41ede Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/asgi.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/asgi.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46021556bf5f6107903bb9a67eb2595e19347d44 Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/asgi.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/context_managers.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/context_managers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6340bf01d335a6d3f0746814a513f27fb0a58ae4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/context_managers.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/core.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb19f0b47be637a180d141ab30b70076bbea2d0c Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/core.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/decorator.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/decorator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..064f2ad49c4468a5d4ee760dab9d344e7a4a3b0c Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/decorator.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/exposition.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/exposition.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af66e4eddbf08d27d04f7cb5f1bf429288717805 Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/exposition.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/gc_collector.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/gc_collector.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9de6535c1eb8f03f76511799f206d6c9e110f62a Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/gc_collector.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/metrics.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/metrics.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7994010a03010c265ad0f05634d1ecfa8191e2f9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/metrics.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/metrics_core.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/metrics_core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fe82cab6b24f66d6fc4a4591b2c890791feee21 Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/metrics_core.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/mmap_dict.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/mmap_dict.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01edff3f1123dea690cecc4d30c7b0c11d290614 Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/mmap_dict.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/multiprocess.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/multiprocess.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05482e02634259d7a0cb5826c0b171cd35597e43 Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/multiprocess.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/parser.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/parser.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cab61be35016b3ca47791b8486b8f91a6fbf37c Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/parser.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/platform_collector.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/platform_collector.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b59b3f440a41d70140cfbb1d3b949b55e7bac090 Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/platform_collector.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/process_collector.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/process_collector.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e0425038d9ef517621c40391886409e40d02b5d Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/process_collector.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/samples.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/samples.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f1d4b90f9cef3e27196ecd735cb4c0b679843f7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/__pycache__/samples.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/asgi.py b/venv/lib/python3.10/site-packages/prometheus_client/asgi.py new file mode 100644 index 0000000000000000000000000000000000000000..e1864b8b9f55a09af34d08b48bef16a6a651caf3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/asgi.py @@ -0,0 +1,40 @@ +from typing import Callable +from urllib.parse import parse_qs + +from .exposition import _bake_output +from .registry import CollectorRegistry, REGISTRY + + +def make_asgi_app(registry: CollectorRegistry = REGISTRY, disable_compression: bool = False) -> Callable: + """Create a ASGI app which serves the metrics from a registry.""" + + async def prometheus_app(scope, receive, send): + assert scope.get("type") == "http" + # Prepare parameters + params = parse_qs(scope.get('query_string', b'')) + accept_header = ",".join([ + value.decode("utf8") for (name, value) in scope.get('headers') + if name.decode("utf8").lower() == 'accept' + ]) + accept_encoding_header = ",".join([ + value.decode("utf8") for (name, value) in scope.get('headers') + if name.decode("utf8").lower() == 'accept-encoding' + ]) + # Bake output + status, headers, output = _bake_output(registry, accept_header, accept_encoding_header, params, disable_compression) + formatted_headers = [] + for header in headers: + formatted_headers.append(tuple(x.encode('utf8') for x in header)) + # Return output + payload = await receive() + if payload.get("type") == "http.request": + await send( + { + "type": "http.response.start", + "status": int(status.split(' ')[0]), + "headers": formatted_headers, + } + ) + await send({"type": "http.response.body", "body": output}) + + return prometheus_app diff --git a/venv/lib/python3.10/site-packages/prometheus_client/bridge/__init__.py b/venv/lib/python3.10/site-packages/prometheus_client/bridge/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/prometheus_client/bridge/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/bridge/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd2d706383e42e8defe1b404700384c46b959fc0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/bridge/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/bridge/__pycache__/graphite.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/bridge/__pycache__/graphite.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3cb5ead6444b98cacbd394067b64c0c0f5d6225 Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/bridge/__pycache__/graphite.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/bridge/graphite.py b/venv/lib/python3.10/site-packages/prometheus_client/bridge/graphite.py new file mode 100644 index 0000000000000000000000000000000000000000..8cadbedc53f7b45521af7fcc8c88e2fcfa7ec042 --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/bridge/graphite.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python + +import logging +import re +import socket +import threading +import time +from timeit import default_timer +from typing import Callable, Tuple + +from ..registry import CollectorRegistry, REGISTRY + +# Roughly, have to keep to what works as a file name. +# We also remove periods, so labels can be distinguished. + +_INVALID_GRAPHITE_CHARS = re.compile(r"[^a-zA-Z0-9_-]") + + +def _sanitize(s): + return _INVALID_GRAPHITE_CHARS.sub('_', s) + + +class _RegularPush(threading.Thread): + def __init__(self, pusher, interval, prefix): + super().__init__() + self._pusher = pusher + self._interval = interval + self._prefix = prefix + + def run(self): + wait_until = default_timer() + while True: + while True: + now = default_timer() + if now >= wait_until: + # May need to skip some pushes. + while wait_until < now: + wait_until += self._interval + break + # time.sleep can return early. + time.sleep(wait_until - now) + try: + self._pusher.push(prefix=self._prefix) + except OSError: + logging.exception("Push failed") + + +class GraphiteBridge: + def __init__(self, + address: Tuple[str, int], + registry: CollectorRegistry = REGISTRY, + timeout_seconds: float = 30, + _timer: Callable[[], float] = time.time, + tags: bool = False, + ): + self._address = address + self._registry = registry + self._tags = tags + self._timeout = timeout_seconds + self._timer = _timer + + def push(self, prefix: str = '') -> None: + now = int(self._timer()) + output = [] + + prefixstr = '' + if prefix: + prefixstr = prefix + '.' + + for metric in self._registry.collect(): + for s in metric.samples: + if s.labels: + if self._tags: + sep = ';' + fmt = '{0}={1}' + else: + sep = '.' + fmt = '{0}.{1}' + labelstr = sep + sep.join( + [fmt.format( + _sanitize(k), _sanitize(v)) + for k, v in sorted(s.labels.items())]) + else: + labelstr = '' + output.append(f'{prefixstr}{_sanitize(s.name)}{labelstr} {float(s.value)} {now}\n') + + conn = socket.create_connection(self._address, self._timeout) + conn.sendall(''.join(output).encode('ascii')) + conn.close() + + def start(self, interval: float = 60.0, prefix: str = '') -> None: + t = _RegularPush(self, interval, prefix) + t.daemon = True + t.start() diff --git a/venv/lib/python3.10/site-packages/prometheus_client/context_managers.py b/venv/lib/python3.10/site-packages/prometheus_client/context_managers.py new file mode 100644 index 0000000000000000000000000000000000000000..3988ec22218e96a7bee77971d7ee59fdfc6effcb --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/context_managers.py @@ -0,0 +1,82 @@ +from timeit import default_timer +from types import TracebackType +from typing import ( + Any, Callable, Literal, Optional, Tuple, Type, TYPE_CHECKING, TypeVar, + Union, +) + +from .decorator import decorate + +if TYPE_CHECKING: + from . import Counter + F = TypeVar("F", bound=Callable[..., Any]) + + +class ExceptionCounter: + def __init__(self, counter: "Counter", exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]]) -> None: + self._counter = counter + self._exception = exception + + def __enter__(self) -> None: + pass + + def __exit__(self, typ: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType]) -> Literal[False]: + if isinstance(value, self._exception): + self._counter.inc() + return False + + def __call__(self, f: "F") -> "F": + def wrapped(func, *args, **kwargs): + with self: + return func(*args, **kwargs) + + return decorate(f, wrapped) + + +class InprogressTracker: + def __init__(self, gauge): + self._gauge = gauge + + def __enter__(self): + self._gauge.inc() + + def __exit__(self, typ, value, traceback): + self._gauge.dec() + + def __call__(self, f: "F") -> "F": + def wrapped(func, *args, **kwargs): + with self: + return func(*args, **kwargs) + + return decorate(f, wrapped) + + +class Timer: + def __init__(self, metric, callback_name): + self._metric = metric + self._callback_name = callback_name + + def _new_timer(self): + return self.__class__(self._metric, self._callback_name) + + def __enter__(self): + self._start = default_timer() + return self + + def __exit__(self, typ, value, traceback): + # Time can go backwards. + duration = max(default_timer() - self._start, 0) + callback = getattr(self._metric, self._callback_name) + callback(duration) + + def labels(self, *args, **kw): + self._metric = self._metric.labels(*args, **kw) + + def __call__(self, f: "F") -> "F": + def wrapped(func, *args, **kwargs): + # Obtaining new instance of timer every time + # ensures thread safety and reentrancy. + with self._new_timer(): + return func(*args, **kwargs) + + return decorate(f, wrapped) diff --git a/venv/lib/python3.10/site-packages/prometheus_client/core.py b/venv/lib/python3.10/site-packages/prometheus_client/core.py new file mode 100644 index 0000000000000000000000000000000000000000..60f93ce10cb3daef95b843bdf5aa064a1863c1be --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/core.py @@ -0,0 +1,34 @@ +from .metrics import Counter, Enum, Gauge, Histogram, Info, Summary +from .metrics_core import ( + CounterMetricFamily, GaugeHistogramMetricFamily, GaugeMetricFamily, + HistogramMetricFamily, InfoMetricFamily, Metric, StateSetMetricFamily, + SummaryMetricFamily, UnknownMetricFamily, UntypedMetricFamily, +) +from .registry import CollectorRegistry, REGISTRY +from .samples import BucketSpan, Exemplar, NativeHistogram, Sample, Timestamp + +__all__ = ( + 'BucketSpan', + 'CollectorRegistry', + 'Counter', + 'CounterMetricFamily', + 'Enum', + 'Exemplar', + 'Gauge', + 'GaugeHistogramMetricFamily', + 'GaugeMetricFamily', + 'Histogram', + 'HistogramMetricFamily', + 'Info', + 'InfoMetricFamily', + 'Metric', + 'NativeHistogram', + 'REGISTRY', + 'Sample', + 'StateSetMetricFamily', + 'Summary', + 'SummaryMetricFamily', + 'Timestamp', + 'UnknownMetricFamily', + 'UntypedMetricFamily', +) diff --git a/venv/lib/python3.10/site-packages/prometheus_client/decorator.py b/venv/lib/python3.10/site-packages/prometheus_client/decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..1ad2c9770ec1272587e8ff8d512d53ea68eac3d8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/decorator.py @@ -0,0 +1,427 @@ +# ######################### LICENSE ############################ # + +# Copyright (c) 2005-2016, Michele Simionato +# 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 bytecode 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 +# 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. + +""" +Decorator module, see http://pypi.python.org/pypi/decorator +for the documentation. +""" +from __future__ import print_function + +import collections +import inspect +import itertools +import operator +import re +import sys + +__version__ = '4.0.10' + +if sys.version_info >= (3,): + from inspect import getfullargspec + + + def get_init(cls): + return cls.__init__ +else: + class getfullargspec(object): + "A quick and dirty replacement for getfullargspec for Python 2.X" + + def __init__(self, f): + self.args, self.varargs, self.varkw, self.defaults = \ + inspect.getargspec(f) + self.kwonlyargs = [] + self.kwonlydefaults = None + + def __iter__(self): + yield self.args + yield self.varargs + yield self.varkw + yield self.defaults + + getargspec = inspect.getargspec + + + def get_init(cls): + return cls.__init__.__func__ + +# getargspec has been deprecated in Python 3.5 +ArgSpec = collections.namedtuple( + 'ArgSpec', 'args varargs varkw defaults') + + +def getargspec(f): + """A replacement for inspect.getargspec""" + spec = getfullargspec(f) + return ArgSpec(spec.args, spec.varargs, spec.varkw, spec.defaults) + + +DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(') + + +# basic functionality +class FunctionMaker(object): + """ + An object with the ability to create functions with a given signature. + It has attributes name, doc, module, signature, defaults, dict and + methods update and make. + """ + + # Atomic get-and-increment provided by the GIL + _compile_count = itertools.count() + + def __init__(self, func=None, name=None, signature=None, + defaults=None, doc=None, module=None, funcdict=None): + self.shortsignature = signature + if func: + # func can be a class or a callable, but not an instance method + self.name = func.__name__ + if self.name == '': # small hack for lambda functions + self.name = '_lambda_' + self.doc = func.__doc__ + self.module = func.__module__ + if inspect.isfunction(func): + argspec = getfullargspec(func) + self.annotations = getattr(func, '__annotations__', {}) + for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs', + 'kwonlydefaults'): + setattr(self, a, getattr(argspec, a)) + for i, arg in enumerate(self.args): + setattr(self, 'arg%d' % i, arg) + if sys.version_info < (3,): # easy way + self.shortsignature = self.signature = ( + inspect.formatargspec( + formatvalue=lambda val: "", *argspec)[1:-1]) + else: # Python 3 way + allargs = list(self.args) + allshortargs = list(self.args) + if self.varargs: + allargs.append('*' + self.varargs) + allshortargs.append('*' + self.varargs) + elif self.kwonlyargs: + allargs.append('*') # single star syntax + for a in self.kwonlyargs: + allargs.append('%s=None' % a) + allshortargs.append('%s=%s' % (a, a)) + if self.varkw: + allargs.append('**' + self.varkw) + allshortargs.append('**' + self.varkw) + self.signature = ', '.join(allargs) + self.shortsignature = ', '.join(allshortargs) + self.dict = func.__dict__.copy() + # func=None happens when decorating a caller + if name: + self.name = name + if signature is not None: + self.signature = signature + if defaults: + self.defaults = defaults + if doc: + self.doc = doc + if module: + self.module = module + if funcdict: + self.dict = funcdict + # check existence required attributes + assert hasattr(self, 'name') + if not hasattr(self, 'signature'): + raise TypeError('You are decorating a non function: %s' % func) + + def update(self, func, **kw): + "Update the signature of func with the data in self" + func.__name__ = self.name + func.__doc__ = getattr(self, 'doc', None) + func.__dict__ = getattr(self, 'dict', {}) + func.__defaults__ = getattr(self, 'defaults', ()) + func.__kwdefaults__ = getattr(self, 'kwonlydefaults', None) + func.__annotations__ = getattr(self, 'annotations', None) + try: + frame = sys._getframe(3) + except AttributeError: # for IronPython and similar implementations + callermodule = '?' + else: + callermodule = frame.f_globals.get('__name__', '?') + func.__module__ = getattr(self, 'module', callermodule) + func.__dict__.update(kw) + + def make(self, src_templ, evaldict=None, addsource=False, **attrs): + "Make a new function from a given template and update the signature" + src = src_templ % vars(self) # expand name and signature + evaldict = evaldict or {} + mo = DEF.match(src) + if mo is None: + raise SyntaxError('not a valid function template\n%s' % src) + name = mo.group(1) # extract the function name + names = set([name] + [arg.strip(' *') for arg in + self.shortsignature.split(',')]) + for n in names: + if n in ('_func_', '_call_'): + raise NameError('%s is overridden in\n%s' % (n, src)) + + if not src.endswith('\n'): # add a newline for old Pythons + src += '\n' + + # Ensure each generated function has a unique filename for profilers + # (such as cProfile) that depend on the tuple of (, + # , ) being unique. + filename = '' % (next(self._compile_count),) + try: + code = compile(src, filename, 'single') + exec(code, evaldict) + except: + print('Error in generated code:', file=sys.stderr) + print(src, file=sys.stderr) + raise + func = evaldict[name] + if addsource: + attrs['__source__'] = src + self.update(func, **attrs) + return func + + @classmethod + def create(cls, obj, body, evaldict, defaults=None, + doc=None, module=None, addsource=True, **attrs): + """ + Create a function from the strings name, signature and body. + evaldict is the evaluation dictionary. If addsource is true an + attribute __source__ is added to the result. The attributes attrs + are added, if any. + """ + if isinstance(obj, str): # "name(signature)" + name, rest = obj.strip().split('(', 1) + signature = rest[:-1] # strip a right parens + func = None + else: # a function + name = None + signature = None + func = obj + self = cls(func, name, signature, defaults, doc, module) + ibody = '\n'.join(' ' + line for line in body.splitlines()) + return self.make('def %(name)s(%(signature)s):\n' + ibody, + evaldict, addsource, **attrs) + + +def decorate(func, caller): + """ + decorate(func, caller) decorates a function using a caller. + """ + evaldict = dict(_call_=caller, _func_=func) + fun = FunctionMaker.create( + func, "return _call_(_func_, %(shortsignature)s)", + evaldict, __wrapped__=func) + if hasattr(func, '__qualname__'): + fun.__qualname__ = func.__qualname__ + return fun + + +def decorator(caller, _func=None): + """decorator(caller) converts a caller function into a decorator""" + if _func is not None: # return a decorated function + # this is obsolete behavior; you should use decorate instead + return decorate(_func, caller) + # else return a decorator function + if inspect.isclass(caller): + name = caller.__name__.lower() + doc = 'decorator(%s) converts functions/generators into ' \ + 'factories of %s objects' % (caller.__name__, caller.__name__) + elif inspect.isfunction(caller): + if caller.__name__ == '': + name = '_lambda_' + else: + name = caller.__name__ + doc = caller.__doc__ + else: # assume caller is an object with a __call__ method + name = caller.__class__.__name__.lower() + doc = caller.__call__.__doc__ + evaldict = dict(_call_=caller, _decorate_=decorate) + return FunctionMaker.create( + '%s(func)' % name, 'return _decorate_(func, _call_)', + evaldict, doc=doc, module=caller.__module__, + __wrapped__=caller) + + +# ####################### contextmanager ####################### # + +try: # Python >= 3.2 + from contextlib import _GeneratorContextManager +except ImportError: # Python >= 2.5 + from contextlib import GeneratorContextManager as _GeneratorContextManager + + +class ContextManager(_GeneratorContextManager): + def __call__(self, func): + """Context manager decorator""" + return FunctionMaker.create( + func, "with _self_: return _func_(%(shortsignature)s)", + dict(_self_=self, _func_=func), __wrapped__=func) + + +init = getfullargspec(_GeneratorContextManager.__init__) +n_args = len(init.args) +if n_args == 2 and not init.varargs: # (self, genobj) Python 2.7 + def __init__(self, g, *a, **k): + return _GeneratorContextManager.__init__(self, g(*a, **k)) + + + ContextManager.__init__ = __init__ +elif n_args == 2 and init.varargs: # (self, gen, *a, **k) Python 3.4 + pass +elif n_args == 4: # (self, gen, args, kwds) Python 3.5 + def __init__(self, g, *a, **k): + return _GeneratorContextManager.__init__(self, g, a, k) + + + ContextManager.__init__ = __init__ + +contextmanager = decorator(ContextManager) + + +# ############################ dispatch_on ############################ # + +def append(a, vancestors): + """ + Append ``a`` to the list of the virtual ancestors, unless it is already + included. + """ + add = True + for j, va in enumerate(vancestors): + if issubclass(va, a): + add = False + break + if issubclass(a, va): + vancestors[j] = a + add = False + if add: + vancestors.append(a) + + +# inspired from simplegeneric by P.J. Eby and functools.singledispatch +def dispatch_on(*dispatch_args): + """ + Factory of decorators turning a function into a generic function + dispatching on the given arguments. + """ + assert dispatch_args, 'No dispatch args passed' + dispatch_str = '(%s,)' % ', '.join(dispatch_args) + + def check(arguments, wrong=operator.ne, msg=''): + """Make sure one passes the expected number of arguments""" + if wrong(len(arguments), len(dispatch_args)): + raise TypeError('Expected %d arguments, got %d%s' % + (len(dispatch_args), len(arguments), msg)) + + def gen_func_dec(func): + """Decorator turning a function into a generic function""" + + # first check the dispatch arguments + argset = set(getfullargspec(func).args) + if not set(dispatch_args) <= argset: + raise NameError('Unknown dispatch arguments %s' % dispatch_str) + + typemap = {} + + def vancestors(*types): + """ + Get a list of sets of virtual ancestors for the given types + """ + check(types) + ras = [[] for _ in range(len(dispatch_args))] + for types_ in typemap: + for t, type_, ra in zip(types, types_, ras): + if issubclass(t, type_) and type_ not in t.__mro__: + append(type_, ra) + return [set(ra) for ra in ras] + + def ancestors(*types): + """ + Get a list of virtual MROs, one for each type + """ + check(types) + lists = [] + for t, vas in zip(types, vancestors(*types)): + n_vas = len(vas) + if n_vas > 1: + raise RuntimeError( + 'Ambiguous dispatch for %s: %s' % (t, vas)) + elif n_vas == 1: + va, = vas + mro = type('t', (t, va), {}).__mro__[1:] + else: + mro = t.__mro__ + lists.append(mro[:-1]) # discard t and object + return lists + + def register(*types): + """ + Decorator to register an implementation for the given types + """ + check(types) + + def dec(f): + check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__) + typemap[types] = f + return f + + return dec + + def dispatch_info(*types): + """ + An utility to introspect the dispatch algorithm + """ + check(types) + lst = [] + for anc in itertools.product(*ancestors(*types)): + lst.append(tuple(a.__name__ for a in anc)) + return lst + + def _dispatch(dispatch_args, *args, **kw): + types = tuple(type(arg) for arg in dispatch_args) + try: # fast path + f = typemap[types] + except KeyError: + pass + else: + return f(*args, **kw) + combinations = itertools.product(*ancestors(*types)) + next(combinations) # the first one has been already tried + for types_ in combinations: + f = typemap.get(types_) + if f is not None: + return f(*args, **kw) + + # else call the default implementation + return func(*args, **kw) + + return FunctionMaker.create( + func, 'return _f_(%s, %%(shortsignature)s)' % dispatch_str, + dict(_f_=_dispatch), register=register, default=func, + typemap=typemap, vancestors=vancestors, ancestors=ancestors, + dispatch_info=dispatch_info, __wrapped__=func) + + gen_func_dec.__name__ = 'dispatch_on' + dispatch_str + return gen_func_dec diff --git a/venv/lib/python3.10/site-packages/prometheus_client/exposition.py b/venv/lib/python3.10/site-packages/prometheus_client/exposition.py new file mode 100644 index 0000000000000000000000000000000000000000..0bc3632e442029fd11887affddcaaa824ccec03e --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/exposition.py @@ -0,0 +1,679 @@ +import base64 +from contextlib import closing +import gzip +from http.server import BaseHTTPRequestHandler +import os +import socket +from socketserver import ThreadingMixIn +import ssl +import sys +import threading +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from urllib.error import HTTPError +from urllib.parse import parse_qs, quote_plus, urlparse +from urllib.request import ( + BaseHandler, build_opener, HTTPHandler, HTTPRedirectHandler, HTTPSHandler, + Request, +) +from wsgiref.simple_server import make_server, WSGIRequestHandler, WSGIServer + +from .openmetrics import exposition as openmetrics +from .registry import CollectorRegistry, REGISTRY +from .utils import floatToGoString +from .validation import _is_valid_legacy_metric_name + +__all__ = ( + 'CONTENT_TYPE_LATEST', + 'delete_from_gateway', + 'generate_latest', + 'instance_ip_grouping_key', + 'make_asgi_app', + 'make_wsgi_app', + 'MetricsHandler', + 'push_to_gateway', + 'pushadd_to_gateway', + 'start_http_server', + 'start_wsgi_server', + 'write_to_textfile', +) + +CONTENT_TYPE_LATEST = 'text/plain; version=0.0.4; charset=utf-8' +"""Content type of the latest text format""" + + +class _PrometheusRedirectHandler(HTTPRedirectHandler): + """ + Allow additional methods (e.g. PUT) and data forwarding in redirects. + + Use of this class constitute a user's explicit agreement to the + redirect responses the Prometheus client will receive when using it. + You should only use this class if you control or otherwise trust the + redirect behavior involved and are certain it is safe to full transfer + the original request (method and data) to the redirected URL. For + example, if you know there is a cosmetic URL redirect in front of a + local deployment of a Prometheus server, and all redirects are safe, + this is the class to use to handle redirects in that case. + + The standard HTTPRedirectHandler does not forward request data nor + does it allow redirected PUT requests (which Prometheus uses for some + operations, for example `push_to_gateway`) because these cannot + generically guarantee no violations of HTTP RFC 2616 requirements for + the user to explicitly confirm redirects that could have unexpected + side effects (such as rendering a PUT request non-idempotent or + creating multiple resources not named in the original request). + """ + + def redirect_request(self, req, fp, code, msg, headers, newurl): + """ + Apply redirect logic to a request. + + See parent HTTPRedirectHandler.redirect_request for parameter info. + + If the redirect is disallowed, this raises the corresponding HTTP error. + If the redirect can't be determined, return None to allow other handlers + to try. If the redirect is allowed, return the new request. + + This method specialized for the case when (a) the user knows that the + redirect will not cause unacceptable side effects for any request method, + and (b) the user knows that any request data should be passed through to + the redirect. If either condition is not met, this should not be used. + """ + # note that requests being provided by a handler will use get_method to + # indicate the method, by monkeypatching this, instead of setting the + # Request object's method attribute. + m = getattr(req, "method", req.get_method()) + if not (code in (301, 302, 303, 307) and m in ("GET", "HEAD") + or code in (301, 302, 303) and m in ("POST", "PUT")): + raise HTTPError(req.full_url, code, msg, headers, fp) + new_request = Request( + newurl.replace(' ', '%20'), # space escaping in new url if needed. + headers=req.headers, + origin_req_host=req.origin_req_host, + unverifiable=True, + data=req.data, + ) + new_request.method = m + return new_request + + +def _bake_output(registry, accept_header, accept_encoding_header, params, disable_compression): + """Bake output for metrics output.""" + # Choose the correct plain text format of the output. + encoder, content_type = choose_encoder(accept_header) + if 'name[]' in params: + registry = registry.restricted_registry(params['name[]']) + output = encoder(registry) + headers = [('Content-Type', content_type)] + # If gzip encoding required, gzip the output. + if not disable_compression and gzip_accepted(accept_encoding_header): + output = gzip.compress(output) + headers.append(('Content-Encoding', 'gzip')) + return '200 OK', headers, output + + +def make_wsgi_app(registry: CollectorRegistry = REGISTRY, disable_compression: bool = False) -> Callable: + """Create a WSGI app which serves the metrics from a registry.""" + + def prometheus_app(environ, start_response): + # Prepare parameters + accept_header = environ.get('HTTP_ACCEPT') + accept_encoding_header = environ.get('HTTP_ACCEPT_ENCODING') + params = parse_qs(environ.get('QUERY_STRING', '')) + method = environ['REQUEST_METHOD'] + + if method == 'OPTIONS': + status = '200 OK' + headers = [('Allow', 'OPTIONS,GET')] + output = b'' + elif method != 'GET': + status = '405 Method Not Allowed' + headers = [('Allow', 'OPTIONS,GET')] + output = '# HTTP {}: {}; use OPTIONS or GET\n'.format(status, method).encode() + elif environ['PATH_INFO'] == '/favicon.ico': + # Serve empty response for browsers + status = '200 OK' + headers = [] + output = b'' + else: + # Note: For backwards compatibility, the URI path for GET is not + # constrained to the documented /metrics, but any path is allowed. + # Bake output + status, headers, output = _bake_output(registry, accept_header, accept_encoding_header, params, disable_compression) + # Return output + start_response(status, headers) + return [output] + + return prometheus_app + + +class _SilentHandler(WSGIRequestHandler): + """WSGI handler that does not log requests.""" + + def log_message(self, format, *args): + """Log nothing.""" + + +class ThreadingWSGIServer(ThreadingMixIn, WSGIServer): + """Thread per request HTTP server.""" + # Make worker threads "fire and forget". Beginning with Python 3.7 this + # prevents a memory leak because ``ThreadingMixIn`` starts to gather all + # non-daemon threads in a list in order to join on them at server close. + daemon_threads = True + + +def _get_best_family(address, port): + """Automatically select address family depending on address""" + # HTTPServer defaults to AF_INET, which will not start properly if + # binding an ipv6 address is requested. + # This function is based on what upstream python did for http.server + # in https://github.com/python/cpython/pull/11767 + infos = socket.getaddrinfo(address, port, type=socket.SOCK_STREAM, flags=socket.AI_PASSIVE) + family, _, _, _, sockaddr = next(iter(infos)) + return family, sockaddr[0] + + +def _get_ssl_ctx( + certfile: str, + keyfile: str, + protocol: int, + cafile: Optional[str] = None, + capath: Optional[str] = None, + client_auth_required: bool = False, +) -> ssl.SSLContext: + """Load context supports SSL.""" + ssl_cxt = ssl.SSLContext(protocol=protocol) + + if cafile is not None or capath is not None: + try: + ssl_cxt.load_verify_locations(cafile, capath) + except IOError as exc: + exc_type = type(exc) + msg = str(exc) + raise exc_type(f"Cannot load CA certificate chain from file " + f"{cafile!r} or directory {capath!r}: {msg}") + else: + try: + ssl_cxt.load_default_certs(purpose=ssl.Purpose.CLIENT_AUTH) + except IOError as exc: + exc_type = type(exc) + msg = str(exc) + raise exc_type(f"Cannot load default CA certificate chain: {msg}") + + if client_auth_required: + ssl_cxt.verify_mode = ssl.CERT_REQUIRED + + try: + ssl_cxt.load_cert_chain(certfile=certfile, keyfile=keyfile) + except IOError as exc: + exc_type = type(exc) + msg = str(exc) + raise exc_type(f"Cannot load server certificate file {certfile!r} or " + f"its private key file {keyfile!r}: {msg}") + + return ssl_cxt + + +def start_wsgi_server( + port: int, + addr: str = '0.0.0.0', + registry: CollectorRegistry = REGISTRY, + certfile: Optional[str] = None, + keyfile: Optional[str] = None, + client_cafile: Optional[str] = None, + client_capath: Optional[str] = None, + protocol: int = ssl.PROTOCOL_TLS_SERVER, + client_auth_required: bool = False, +) -> Tuple[WSGIServer, threading.Thread]: + """Starts a WSGI server for prometheus metrics as a daemon thread.""" + + class TmpServer(ThreadingWSGIServer): + """Copy of ThreadingWSGIServer to update address_family locally""" + + TmpServer.address_family, addr = _get_best_family(addr, port) + app = make_wsgi_app(registry) + httpd = make_server(addr, port, app, TmpServer, handler_class=_SilentHandler) + if certfile and keyfile: + context = _get_ssl_ctx(certfile, keyfile, protocol, client_cafile, client_capath, client_auth_required) + httpd.socket = context.wrap_socket(httpd.socket, server_side=True) + t = threading.Thread(target=httpd.serve_forever) + t.daemon = True + t.start() + + return httpd, t + + +start_http_server = start_wsgi_server + + +def generate_latest(registry: CollectorRegistry = REGISTRY) -> bytes: + """Returns the metrics from the registry in latest text format as a string.""" + + def sample_line(samples): + if samples.labels: + labelstr = '{0}'.format(','.join( + ['{}="{}"'.format( + openmetrics.escape_label_name(k), openmetrics._escape(v)) + for k, v in sorted(samples.labels.items())])) + else: + labelstr = '' + timestamp = '' + if samples.timestamp is not None: + # Convert to milliseconds. + timestamp = f' {int(float(samples.timestamp) * 1000):d}' + if _is_valid_legacy_metric_name(samples.name): + if labelstr: + labelstr = '{{{0}}}'.format(labelstr) + return f'{samples.name}{labelstr} {floatToGoString(samples.value)}{timestamp}\n' + maybe_comma = '' + if labelstr: + maybe_comma = ',' + return f'{{{openmetrics.escape_metric_name(samples.name)}{maybe_comma}{labelstr}}} {floatToGoString(samples.value)}{timestamp}\n' + + output = [] + for metric in registry.collect(): + try: + mname = metric.name + mtype = metric.type + # Munging from OpenMetrics into Prometheus format. + if mtype == 'counter': + mname = mname + '_total' + elif mtype == 'info': + mname = mname + '_info' + mtype = 'gauge' + elif mtype == 'stateset': + mtype = 'gauge' + elif mtype == 'gaugehistogram': + # A gauge histogram is really a gauge, + # but this captures the structure better. + mtype = 'histogram' + elif mtype == 'unknown': + mtype = 'untyped' + + output.append('# HELP {} {}\n'.format( + openmetrics.escape_metric_name(mname), metric.documentation.replace('\\', r'\\').replace('\n', r'\n'))) + output.append(f'# TYPE {openmetrics.escape_metric_name(mname)} {mtype}\n') + + om_samples: Dict[str, List[str]] = {} + for s in metric.samples: + for suffix in ['_created', '_gsum', '_gcount']: + if s.name == metric.name + suffix: + # OpenMetrics specific sample, put in a gauge at the end. + om_samples.setdefault(suffix, []).append(sample_line(s)) + break + else: + output.append(sample_line(s)) + except Exception as exception: + exception.args = (exception.args or ('',)) + (metric,) + raise + + for suffix, lines in sorted(om_samples.items()): + output.append('# HELP {} {}\n'.format(openmetrics.escape_metric_name(metric.name + suffix), + metric.documentation.replace('\\', r'\\').replace('\n', r'\n'))) + output.append(f'# TYPE {openmetrics.escape_metric_name(metric.name + suffix)} gauge\n') + output.extend(lines) + return ''.join(output).encode('utf-8') + + +def choose_encoder(accept_header: str) -> Tuple[Callable[[CollectorRegistry], bytes], str]: + accept_header = accept_header or '' + for accepted in accept_header.split(','): + if accepted.split(';')[0].strip() == 'application/openmetrics-text': + return (openmetrics.generate_latest, + openmetrics.CONTENT_TYPE_LATEST) + return generate_latest, CONTENT_TYPE_LATEST + + +def gzip_accepted(accept_encoding_header: str) -> bool: + accept_encoding_header = accept_encoding_header or '' + for accepted in accept_encoding_header.split(','): + if accepted.split(';')[0].strip().lower() == 'gzip': + return True + return False + + +class MetricsHandler(BaseHTTPRequestHandler): + """HTTP handler that gives metrics from ``REGISTRY``.""" + registry: CollectorRegistry = REGISTRY + + def do_GET(self) -> None: + # Prepare parameters + registry = self.registry + accept_header = self.headers.get('Accept') + accept_encoding_header = self.headers.get('Accept-Encoding') + params = parse_qs(urlparse(self.path).query) + # Bake output + status, headers, output = _bake_output(registry, accept_header, accept_encoding_header, params, False) + # Return output + self.send_response(int(status.split(' ')[0])) + for header in headers: + self.send_header(*header) + self.end_headers() + self.wfile.write(output) + + def log_message(self, format: str, *args: Any) -> None: + """Log nothing.""" + + @classmethod + def factory(cls, registry: CollectorRegistry) -> type: + """Returns a dynamic MetricsHandler class tied + to the passed registry. + """ + # This implementation relies on MetricsHandler.registry + # (defined above and defaulted to REGISTRY). + + # As we have unicode_literals, we need to create a str() + # object for type(). + cls_name = str(cls.__name__) + MyMetricsHandler = type(cls_name, (cls, object), + {"registry": registry}) + return MyMetricsHandler + + +def write_to_textfile(path: str, registry: CollectorRegistry) -> None: + """Write metrics to the given path. + + This is intended for use with the Node exporter textfile collector. + The path must end in .prom for the textfile collector to process it.""" + tmppath = f'{path}.{os.getpid()}.{threading.current_thread().ident}' + try: + with open(tmppath, 'wb') as f: + f.write(generate_latest(registry)) + + # rename(2) is atomic but fails on Windows if the destination file exists + if os.name == 'nt': + os.replace(tmppath, path) + else: + os.rename(tmppath, path) + except Exception: + if os.path.exists(tmppath): + os.remove(tmppath) + raise + + +def _make_handler( + url: str, + method: str, + timeout: Optional[float], + headers: Sequence[Tuple[str, str]], + data: bytes, + base_handler: Union[BaseHandler, type], +) -> Callable[[], None]: + def handle() -> None: + request = Request(url, data=data) + request.get_method = lambda: method # type: ignore + for k, v in headers: + request.add_header(k, v) + resp = build_opener(base_handler).open(request, timeout=timeout) + if resp.code >= 400: + raise OSError(f"error talking to pushgateway: {resp.code} {resp.msg}") + + return handle + + +def default_handler( + url: str, + method: str, + timeout: Optional[float], + headers: List[Tuple[str, str]], + data: bytes, +) -> Callable[[], None]: + """Default handler that implements HTTP/HTTPS connections. + + Used by the push_to_gateway functions. Can be re-used by other handlers.""" + + return _make_handler(url, method, timeout, headers, data, HTTPHandler) + + +def passthrough_redirect_handler( + url: str, + method: str, + timeout: Optional[float], + headers: List[Tuple[str, str]], + data: bytes, +) -> Callable[[], None]: + """ + Handler that automatically trusts redirect responses for all HTTP methods. + + Augments standard HTTPRedirectHandler capability by permitting PUT requests, + preserving the method upon redirect, and passing through all headers and + data from the original request. Only use this handler if you control or + trust the source of redirect responses you encounter when making requests + via the Prometheus client. This handler will simply repeat the identical + request, including same method and data, to the new redirect URL.""" + + return _make_handler(url, method, timeout, headers, data, _PrometheusRedirectHandler) + + +def basic_auth_handler( + url: str, + method: str, + timeout: Optional[float], + headers: List[Tuple[str, str]], + data: bytes, + username: Optional[str] = None, + password: Optional[str] = None, +) -> Callable[[], None]: + """Handler that implements HTTP/HTTPS connections with Basic Auth. + + Sets auth headers using supplied 'username' and 'password', if set. + Used by the push_to_gateway functions. Can be re-used by other handlers.""" + + def handle(): + """Handler that implements HTTP Basic Auth. + """ + if username is not None and password is not None: + auth_value = f'{username}:{password}'.encode() + auth_token = base64.b64encode(auth_value) + auth_header = b'Basic ' + auth_token + headers.append(('Authorization', auth_header)) + default_handler(url, method, timeout, headers, data)() + + return handle + + +def tls_auth_handler( + url: str, + method: str, + timeout: Optional[float], + headers: List[Tuple[str, str]], + data: bytes, + certfile: str, + keyfile: str, + cafile: Optional[str] = None, + protocol: int = ssl.PROTOCOL_TLS_CLIENT, + insecure_skip_verify: bool = False, +) -> Callable[[], None]: + """Handler that implements an HTTPS connection with TLS Auth. + + The default protocol (ssl.PROTOCOL_TLS_CLIENT) will also enable + ssl.CERT_REQUIRED and SSLContext.check_hostname by default. This can be + disabled by setting insecure_skip_verify to True. + + Both this handler and the TLS feature on pushgateay are experimental.""" + context = ssl.SSLContext(protocol=protocol) + if cafile is not None: + context.load_verify_locations(cafile) + else: + context.load_default_certs() + + if insecure_skip_verify: + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + + context.load_cert_chain(certfile=certfile, keyfile=keyfile) + handler = HTTPSHandler(context=context) + return _make_handler(url, method, timeout, headers, data, handler) + + +def push_to_gateway( + gateway: str, + job: str, + registry: CollectorRegistry, + grouping_key: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = 30, + handler: Callable = default_handler, +) -> None: + """Push metrics to the given pushgateway. + + `gateway` the url for your push gateway. Either of the form + 'http://pushgateway.local', or 'pushgateway.local'. + Scheme defaults to 'http' if none is provided + `job` is the job label to be attached to all pushed metrics + `registry` is an instance of CollectorRegistry + `grouping_key` please see the pushgateway documentation for details. + Defaults to None + `timeout` is how long push will attempt to connect before giving up. + Defaults to 30s, can be set to None for no timeout. + `handler` is an optional function which can be provided to perform + requests to the 'gateway'. + Defaults to None, in which case an http or https request + will be carried out by a default handler. + If not None, the argument must be a function which accepts + the following arguments: + url, method, timeout, headers, and content + May be used to implement additional functionality not + supported by the built-in default handler (such as SSL + client certicates, and HTTP authentication mechanisms). + 'url' is the URL for the request, the 'gateway' argument + described earlier will form the basis of this URL. + 'method' is the HTTP method which should be used when + carrying out the request. + 'timeout' requests not successfully completed after this + many seconds should be aborted. If timeout is None, then + the handler should not set a timeout. + 'headers' is a list of ("header-name","header-value") tuples + which must be passed to the pushgateway in the form of HTTP + request headers. + The function should raise an exception (e.g. IOError) on + failure. + 'content' is the data which should be used to form the HTTP + Message Body. + + This overwrites all metrics with the same job and grouping_key. + This uses the PUT HTTP method.""" + _use_gateway('PUT', gateway, job, registry, grouping_key, timeout, handler) + + +def pushadd_to_gateway( + gateway: str, + job: str, + registry: Optional[CollectorRegistry], + grouping_key: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = 30, + handler: Callable = default_handler, +) -> None: + """PushAdd metrics to the given pushgateway. + + `gateway` the url for your push gateway. Either of the form + 'http://pushgateway.local', or 'pushgateway.local'. + Scheme defaults to 'http' if none is provided + `job` is the job label to be attached to all pushed metrics + `registry` is an instance of CollectorRegistry + `grouping_key` please see the pushgateway documentation for details. + Defaults to None + `timeout` is how long push will attempt to connect before giving up. + Defaults to 30s, can be set to None for no timeout. + `handler` is an optional function which can be provided to perform + requests to the 'gateway'. + Defaults to None, in which case an http or https request + will be carried out by a default handler. + See the 'prometheus_client.push_to_gateway' documentation + for implementation requirements. + + This replaces metrics with the same name, job and grouping_key. + This uses the POST HTTP method.""" + _use_gateway('POST', gateway, job, registry, grouping_key, timeout, handler) + + +def delete_from_gateway( + gateway: str, + job: str, + grouping_key: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = 30, + handler: Callable = default_handler, +) -> None: + """Delete metrics from the given pushgateway. + + `gateway` the url for your push gateway. Either of the form + 'http://pushgateway.local', or 'pushgateway.local'. + Scheme defaults to 'http' if none is provided + `job` is the job label to be attached to all pushed metrics + `grouping_key` please see the pushgateway documentation for details. + Defaults to None + `timeout` is how long delete will attempt to connect before giving up. + Defaults to 30s, can be set to None for no timeout. + `handler` is an optional function which can be provided to perform + requests to the 'gateway'. + Defaults to None, in which case an http or https request + will be carried out by a default handler. + See the 'prometheus_client.push_to_gateway' documentation + for implementation requirements. + + This deletes metrics with the given job and grouping_key. + This uses the DELETE HTTP method.""" + _use_gateway('DELETE', gateway, job, None, grouping_key, timeout, handler) + + +def _use_gateway( + method: str, + gateway: str, + job: str, + registry: Optional[CollectorRegistry], + grouping_key: Optional[Dict[str, Any]], + timeout: Optional[float], + handler: Callable, +) -> None: + gateway_url = urlparse(gateway) + # See https://bugs.python.org/issue27657 for details on urlparse in py>=3.7.6. + if not gateway_url.scheme or gateway_url.scheme not in ['http', 'https']: + gateway = f'http://{gateway}' + + gateway = gateway.rstrip('/') + url = '{}/metrics/{}/{}'.format(gateway, *_escape_grouping_key("job", job)) + + data = b'' + if method != 'DELETE': + if registry is None: + registry = REGISTRY + data = generate_latest(registry) + + if grouping_key is None: + grouping_key = {} + url += ''.join( + '/{}/{}'.format(*_escape_grouping_key(str(k), str(v))) + for k, v in sorted(grouping_key.items())) + + handler( + url=url, method=method, timeout=timeout, + headers=[('Content-Type', CONTENT_TYPE_LATEST)], data=data, + )() + + +def _escape_grouping_key(k, v): + if v == "": + # Per https://github.com/prometheus/pushgateway/pull/346. + return k + "@base64", "=" + elif '/' in v: + # Added in Pushgateway 0.9.0. + return k + "@base64", base64.urlsafe_b64encode(v.encode("utf-8")).decode("utf-8") + else: + return k, quote_plus(v) + + +def instance_ip_grouping_key() -> Dict[str, Any]: + """Grouping key with instance set to the IP Address of this host.""" + with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as s: + if sys.platform == 'darwin': + # This check is done this way only on MacOS devices + # it is done this way because the localhost method does + # not work. + # This method was adapted from this StackOverflow answer: + # https://stackoverflow.com/a/28950776 + s.connect(('10.255.255.255', 1)) + else: + s.connect(('localhost', 0)) + + return {'instance': s.getsockname()[0]} + + +from .asgi import make_asgi_app # noqa diff --git a/venv/lib/python3.10/site-packages/prometheus_client/gc_collector.py b/venv/lib/python3.10/site-packages/prometheus_client/gc_collector.py new file mode 100644 index 0000000000000000000000000000000000000000..06e52dfc3c8f4238d9d9bccbbb0a606530405a1d --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/gc_collector.py @@ -0,0 +1,45 @@ +import gc +import platform +from typing import Iterable + +from .metrics_core import CounterMetricFamily, Metric +from .registry import Collector, CollectorRegistry, REGISTRY + + +class GCCollector(Collector): + """Collector for Garbage collection statistics.""" + + def __init__(self, registry: CollectorRegistry = REGISTRY): + if not hasattr(gc, 'get_stats') or platform.python_implementation() != 'CPython': + return + registry.register(self) + + def collect(self) -> Iterable[Metric]: + collected = CounterMetricFamily( + 'python_gc_objects_collected', + 'Objects collected during gc', + labels=['generation'], + ) + uncollectable = CounterMetricFamily( + 'python_gc_objects_uncollectable', + 'Uncollectable objects found during GC', + labels=['generation'], + ) + + collections = CounterMetricFamily( + 'python_gc_collections', + 'Number of times this generation was collected', + labels=['generation'], + ) + + for gen, stat in enumerate(gc.get_stats()): + generation = str(gen) + collected.add_metric([generation], value=stat['collected']) + uncollectable.add_metric([generation], value=stat['uncollectable']) + collections.add_metric([generation], value=stat['collections']) + + return [collected, uncollectable, collections] + + +GC_COLLECTOR = GCCollector() +"""Default GCCollector in default Registry REGISTRY.""" diff --git a/venv/lib/python3.10/site-packages/prometheus_client/metrics.py b/venv/lib/python3.10/site-packages/prometheus_client/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..b9f25ffc2e6ded98b9d74fa7cd6aa266c379d14c --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/metrics.py @@ -0,0 +1,753 @@ +import os +from threading import Lock +import time +import types +from typing import ( + Any, Callable, Dict, Iterable, List, Literal, Optional, Sequence, Tuple, + Type, TypeVar, Union, +) +import warnings + +from . import values # retain this import style for testability +from .context_managers import ExceptionCounter, InprogressTracker, Timer +from .metrics_core import Metric +from .registry import Collector, CollectorRegistry, REGISTRY +from .samples import Exemplar, Sample +from .utils import floatToGoString, INF +from .validation import ( + _validate_exemplar, _validate_labelnames, _validate_metric_name, +) + +T = TypeVar('T', bound='MetricWrapperBase') +F = TypeVar("F", bound=Callable[..., Any]) + + +def _build_full_name(metric_type, name, namespace, subsystem, unit): + if not name: + raise ValueError('Metric name should not be empty') + full_name = '' + if namespace: + full_name += namespace + '_' + if subsystem: + full_name += subsystem + '_' + full_name += name + if metric_type == 'counter' and full_name.endswith('_total'): + full_name = full_name[:-6] # Munge to OpenMetrics. + if unit and not full_name.endswith("_" + unit): + full_name += "_" + unit + if unit and metric_type in ('info', 'stateset'): + raise ValueError('Metric name is of a type that cannot have a unit: ' + full_name) + return full_name + + + +def _get_use_created() -> bool: + return os.environ.get("PROMETHEUS_DISABLE_CREATED_SERIES", 'False').lower() not in ('true', '1', 't') + + +_use_created = _get_use_created() + + +def disable_created_metrics(): + """Disable exporting _created metrics on counters, histograms, and summaries.""" + global _use_created + _use_created = False + + +def enable_created_metrics(): + """Enable exporting _created metrics on counters, histograms, and summaries.""" + global _use_created + _use_created = True + + +class MetricWrapperBase(Collector): + _type: Optional[str] = None + _reserved_labelnames: Sequence[str] = () + + def _is_observable(self): + # Whether this metric is observable, i.e. + # * a metric without label names and values, or + # * the child of a labelled metric. + return not self._labelnames or (self._labelnames and self._labelvalues) + + def _raise_if_not_observable(self): + # Functions that mutate the state of the metric, for example incrementing + # a counter, will fail if the metric is not observable, because only if a + # metric is observable will the value be initialized. + if not self._is_observable(): + raise ValueError('%s metric is missing label values' % str(self._type)) + + def _is_parent(self): + return self._labelnames and not self._labelvalues + + def _get_metric(self): + return Metric(self._name, self._documentation, self._type, self._unit) + + def describe(self) -> Iterable[Metric]: + return [self._get_metric()] + + def collect(self) -> Iterable[Metric]: + metric = self._get_metric() + for suffix, labels, value, timestamp, exemplar, native_histogram_value in self._samples(): + metric.add_sample(self._name + suffix, labels, value, timestamp, exemplar, native_histogram_value) + return [metric] + + def __str__(self) -> str: + return f"{self._type}:{self._name}" + + def __repr__(self) -> str: + metric_type = type(self) + return f"{metric_type.__module__}.{metric_type.__name__}({self._name})" + + def __init__(self: T, + name: str, + documentation: str, + labelnames: Iterable[str] = (), + namespace: str = '', + subsystem: str = '', + unit: str = '', + registry: Optional[CollectorRegistry] = REGISTRY, + _labelvalues: Optional[Sequence[str]] = None, + ) -> None: + self._name = _build_full_name(self._type, name, namespace, subsystem, unit) + self._labelnames = _validate_labelnames(self, labelnames) + self._labelvalues = tuple(_labelvalues or ()) + self._kwargs: Dict[str, Any] = {} + self._documentation = documentation + self._unit = unit + + _validate_metric_name(self._name) + + if self._is_parent(): + # Prepare the fields needed for child metrics. + self._lock = Lock() + self._metrics: Dict[Sequence[str], T] = {} + + if self._is_observable(): + self._metric_init() + + if not self._labelvalues: + # Register the multi-wrapper parent metric, or if a label-less metric, the whole shebang. + if registry: + registry.register(self) + + def labels(self: T, *labelvalues: Any, **labelkwargs: Any) -> T: + """Return the child for the given labelset. + + All metrics can have labels, allowing grouping of related time series. + Taking a counter as an example: + + from prometheus_client import Counter + + c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) + c.labels('get', '/').inc() + c.labels('post', '/submit').inc() + + Labels can also be provided as keyword arguments: + + from prometheus_client import Counter + + c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) + c.labels(method='get', endpoint='/').inc() + c.labels(method='post', endpoint='/submit').inc() + + See the best practices on [naming](http://prometheus.io/docs/practices/naming/) + and [labels](http://prometheus.io/docs/practices/instrumentation/#use-labels). + """ + if not self._labelnames: + raise ValueError('No label names were set when constructing %s' % self) + + if self._labelvalues: + raise ValueError('{} already has labels set ({}); can not chain calls to .labels()'.format( + self, + dict(zip(self._labelnames, self._labelvalues)) + )) + + if labelvalues and labelkwargs: + raise ValueError("Can't pass both *args and **kwargs") + + if labelkwargs: + if sorted(labelkwargs) != sorted(self._labelnames): + raise ValueError('Incorrect label names') + labelvalues = tuple(str(labelkwargs[l]) for l in self._labelnames) + else: + if len(labelvalues) != len(self._labelnames): + raise ValueError('Incorrect label count') + labelvalues = tuple(str(l) for l in labelvalues) + with self._lock: + if labelvalues not in self._metrics: + self._metrics[labelvalues] = self.__class__( + self._name, + documentation=self._documentation, + labelnames=self._labelnames, + unit=self._unit, + _labelvalues=labelvalues, + **self._kwargs + ) + return self._metrics[labelvalues] + + def remove(self, *labelvalues: Any) -> None: + if 'prometheus_multiproc_dir' in os.environ or 'PROMETHEUS_MULTIPROC_DIR' in os.environ: + warnings.warn( + "Removal of labels has not been implemented in multi-process mode yet.", + UserWarning) + + if not self._labelnames: + raise ValueError('No label names were set when constructing %s' % self) + + """Remove the given labelset from the metric.""" + if len(labelvalues) != len(self._labelnames): + raise ValueError('Incorrect label count (expected %d, got %s)' % (len(self._labelnames), labelvalues)) + labelvalues = tuple(str(l) for l in labelvalues) + with self._lock: + if labelvalues in self._metrics: + del self._metrics[labelvalues] + + def clear(self) -> None: + """Remove all labelsets from the metric""" + if 'prometheus_multiproc_dir' in os.environ or 'PROMETHEUS_MULTIPROC_DIR' in os.environ: + warnings.warn( + "Clearing labels has not been implemented in multi-process mode yet", + UserWarning) + with self._lock: + self._metrics = {} + + def _samples(self) -> Iterable[Sample]: + if self._is_parent(): + return self._multi_samples() + else: + return self._child_samples() + + def _multi_samples(self) -> Iterable[Sample]: + with self._lock: + metrics = self._metrics.copy() + for labels, metric in metrics.items(): + series_labels = list(zip(self._labelnames, labels)) + for suffix, sample_labels, value, timestamp, exemplar, native_histogram_value in metric._samples(): + yield Sample(suffix, dict(series_labels + list(sample_labels.items())), value, timestamp, exemplar, native_histogram_value) + + def _child_samples(self) -> Iterable[Sample]: # pragma: no cover + raise NotImplementedError('_child_samples() must be implemented by %r' % self) + + def _metric_init(self): # pragma: no cover + """ + Initialize the metric object as a child, i.e. when it has labels (if any) set. + + This is factored as a separate function to allow for deferred initialization. + """ + raise NotImplementedError('_metric_init() must be implemented by %r' % self) + + +class Counter(MetricWrapperBase): + """A Counter tracks counts of events or running totals. + + Example use cases for Counters: + - Number of requests processed + - Number of items that were inserted into a queue + - Total amount of data that a system has processed + + Counters can only go up (and be reset when the process restarts). If your use case can go down, + you should use a Gauge instead. + + An example for a Counter: + + from prometheus_client import Counter + + c = Counter('my_failures_total', 'Description of counter') + c.inc() # Increment by 1 + c.inc(1.6) # Increment by given value + + There are utilities to count exceptions raised: + + @c.count_exceptions() + def f(): + pass + + with c.count_exceptions(): + pass + + # Count only one type of exception + with c.count_exceptions(ValueError): + pass + + You can also reset the counter to zero in case your logical "process" restarts + without restarting the actual python process. + + c.reset() + + """ + _type = 'counter' + + def _metric_init(self) -> None: + self._value = values.ValueClass(self._type, self._name, self._name + '_total', self._labelnames, + self._labelvalues, self._documentation) + self._created = time.time() + + def inc(self, amount: float = 1, exemplar: Optional[Dict[str, str]] = None) -> None: + """Increment counter by the given amount.""" + self._raise_if_not_observable() + if amount < 0: + raise ValueError('Counters can only be incremented by non-negative amounts.') + self._value.inc(amount) + if exemplar: + _validate_exemplar(exemplar) + self._value.set_exemplar(Exemplar(exemplar, amount, time.time())) + + def reset(self) -> None: + """Reset the counter to zero. Use this when a logical process restarts without restarting the actual python process.""" + self._value.set(0) + self._created = time.time() + + def count_exceptions(self, exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]] = Exception) -> ExceptionCounter: + """Count exceptions in a block of code or function. + + Can be used as a function decorator or context manager. + Increments the counter when an exception of the given + type is raised up out of the code. + """ + self._raise_if_not_observable() + return ExceptionCounter(self, exception) + + def _child_samples(self) -> Iterable[Sample]: + sample = Sample('_total', {}, self._value.get(), None, self._value.get_exemplar()) + if _use_created: + return ( + sample, + Sample('_created', {}, self._created, None, None) + ) + return (sample,) + + +class Gauge(MetricWrapperBase): + """Gauge metric, to report instantaneous values. + + Examples of Gauges include: + - Inprogress requests + - Number of items in a queue + - Free memory + - Total memory + - Temperature + + Gauges can go both up and down. + + from prometheus_client import Gauge + + g = Gauge('my_inprogress_requests', 'Description of gauge') + g.inc() # Increment by 1 + g.dec(10) # Decrement by given value + g.set(4.2) # Set to a given value + + There are utilities for common use cases: + + g.set_to_current_time() # Set to current unixtime + + # Increment when entered, decrement when exited. + @g.track_inprogress() + def f(): + pass + + with g.track_inprogress(): + pass + + A Gauge can also take its value from a callback: + + d = Gauge('data_objects', 'Number of objects') + my_dict = {} + d.set_function(lambda: len(my_dict)) + """ + _type = 'gauge' + _MULTIPROC_MODES = frozenset(('all', 'liveall', 'min', 'livemin', 'max', 'livemax', 'sum', 'livesum', 'mostrecent', 'livemostrecent')) + _MOST_RECENT_MODES = frozenset(('mostrecent', 'livemostrecent')) + + def __init__(self, + name: str, + documentation: str, + labelnames: Iterable[str] = (), + namespace: str = '', + subsystem: str = '', + unit: str = '', + registry: Optional[CollectorRegistry] = REGISTRY, + _labelvalues: Optional[Sequence[str]] = None, + multiprocess_mode: Literal['all', 'liveall', 'min', 'livemin', 'max', 'livemax', 'sum', 'livesum', 'mostrecent', 'livemostrecent'] = 'all', + ): + self._multiprocess_mode = multiprocess_mode + if multiprocess_mode not in self._MULTIPROC_MODES: + raise ValueError('Invalid multiprocess mode: ' + multiprocess_mode) + super().__init__( + name=name, + documentation=documentation, + labelnames=labelnames, + namespace=namespace, + subsystem=subsystem, + unit=unit, + registry=registry, + _labelvalues=_labelvalues, + ) + self._kwargs['multiprocess_mode'] = self._multiprocess_mode + self._is_most_recent = self._multiprocess_mode in self._MOST_RECENT_MODES + + def _metric_init(self) -> None: + self._value = values.ValueClass( + self._type, self._name, self._name, self._labelnames, self._labelvalues, + self._documentation, multiprocess_mode=self._multiprocess_mode + ) + + def inc(self, amount: float = 1) -> None: + """Increment gauge by the given amount.""" + if self._is_most_recent: + raise RuntimeError("inc must not be used with the mostrecent mode") + self._raise_if_not_observable() + self._value.inc(amount) + + def dec(self, amount: float = 1) -> None: + """Decrement gauge by the given amount.""" + if self._is_most_recent: + raise RuntimeError("dec must not be used with the mostrecent mode") + self._raise_if_not_observable() + self._value.inc(-amount) + + def set(self, value: float) -> None: + """Set gauge to the given value.""" + self._raise_if_not_observable() + if self._is_most_recent: + self._value.set(float(value), timestamp=time.time()) + else: + self._value.set(float(value)) + + def set_to_current_time(self) -> None: + """Set gauge to the current unixtime.""" + self.set(time.time()) + + def track_inprogress(self) -> InprogressTracker: + """Track inprogress blocks of code or functions. + + Can be used as a function decorator or context manager. + Increments the gauge when the code is entered, + and decrements when it is exited. + """ + self._raise_if_not_observable() + return InprogressTracker(self) + + def time(self) -> Timer: + """Time a block of code or function, and set the duration in seconds. + + Can be used as a function decorator or context manager. + """ + return Timer(self, 'set') + + def set_function(self, f: Callable[[], float]) -> None: + """Call the provided function to return the Gauge value. + + The function must return a float, and may be called from + multiple threads. All other methods of the Gauge become NOOPs. + """ + + self._raise_if_not_observable() + + def samples(_: Gauge) -> Iterable[Sample]: + return (Sample('', {}, float(f()), None, None),) + + self._child_samples = types.MethodType(samples, self) # type: ignore + + def _child_samples(self) -> Iterable[Sample]: + return (Sample('', {}, self._value.get(), None, None),) + + +class Summary(MetricWrapperBase): + """A Summary tracks the size and number of events. + + Example use cases for Summaries: + - Response latency + - Request size + + Example for a Summary: + + from prometheus_client import Summary + + s = Summary('request_size_bytes', 'Request size (bytes)') + s.observe(512) # Observe 512 (bytes) + + Example for a Summary using time: + + from prometheus_client import Summary + + REQUEST_TIME = Summary('response_latency_seconds', 'Response latency (seconds)') + + @REQUEST_TIME.time() + def create_response(request): + '''A dummy function''' + time.sleep(1) + + Example for using the same Summary object as a context manager: + + with REQUEST_TIME.time(): + pass # Logic to be timed + """ + _type = 'summary' + _reserved_labelnames = ['quantile'] + + def _metric_init(self) -> None: + self._count = values.ValueClass(self._type, self._name, self._name + '_count', self._labelnames, + self._labelvalues, self._documentation) + self._sum = values.ValueClass(self._type, self._name, self._name + '_sum', self._labelnames, self._labelvalues, self._documentation) + self._created = time.time() + + def observe(self, amount: float) -> None: + """Observe the given amount. + + The amount is usually positive or zero. Negative values are + accepted but prevent current versions of Prometheus from + properly detecting counter resets in the sum of + observations. See + https://prometheus.io/docs/practices/histograms/#count-and-sum-of-observations + for details. + """ + self._raise_if_not_observable() + self._count.inc(1) + self._sum.inc(amount) + + def time(self) -> Timer: + """Time a block of code or function, and observe the duration in seconds. + + Can be used as a function decorator or context manager. + """ + return Timer(self, 'observe') + + def _child_samples(self) -> Iterable[Sample]: + samples = [ + Sample('_count', {}, self._count.get(), None, None), + Sample('_sum', {}, self._sum.get(), None, None), + ] + if _use_created: + samples.append(Sample('_created', {}, self._created, None, None)) + return tuple(samples) + + +class Histogram(MetricWrapperBase): + """A Histogram tracks the size and number of events in buckets. + + You can use Histograms for aggregatable calculation of quantiles. + + Example use cases: + - Response latency + - Request size + + Example for a Histogram: + + from prometheus_client import Histogram + + h = Histogram('request_size_bytes', 'Request size (bytes)') + h.observe(512) # Observe 512 (bytes) + + Example for a Histogram using time: + + from prometheus_client import Histogram + + REQUEST_TIME = Histogram('response_latency_seconds', 'Response latency (seconds)') + + @REQUEST_TIME.time() + def create_response(request): + '''A dummy function''' + time.sleep(1) + + Example of using the same Histogram object as a context manager: + + with REQUEST_TIME.time(): + pass # Logic to be timed + + The default buckets are intended to cover a typical web/rpc request from milliseconds to seconds. + They can be overridden by passing `buckets` keyword argument to `Histogram`. + """ + _type = 'histogram' + _reserved_labelnames = ['le'] + DEFAULT_BUCKETS = (.005, .01, .025, .05, .075, .1, .25, .5, .75, 1.0, 2.5, 5.0, 7.5, 10.0, INF) + + def __init__(self, + name: str, + documentation: str, + labelnames: Iterable[str] = (), + namespace: str = '', + subsystem: str = '', + unit: str = '', + registry: Optional[CollectorRegistry] = REGISTRY, + _labelvalues: Optional[Sequence[str]] = None, + buckets: Sequence[Union[float, str]] = DEFAULT_BUCKETS, + ): + self._prepare_buckets(buckets) + super().__init__( + name=name, + documentation=documentation, + labelnames=labelnames, + namespace=namespace, + subsystem=subsystem, + unit=unit, + registry=registry, + _labelvalues=_labelvalues, + ) + self._kwargs['buckets'] = buckets + + def _prepare_buckets(self, source_buckets: Sequence[Union[float, str]]) -> None: + buckets = [float(b) for b in source_buckets] + if buckets != sorted(buckets): + # This is probably an error on the part of the user, + # so raise rather than sorting for them. + raise ValueError('Buckets not in sorted order') + if buckets and buckets[-1] != INF: + buckets.append(INF) + if len(buckets) < 2: + raise ValueError('Must have at least two buckets') + self._upper_bounds = buckets + + def _metric_init(self) -> None: + self._buckets: List[values.ValueClass] = [] + self._created = time.time() + bucket_labelnames = self._labelnames + ('le',) + self._sum = values.ValueClass(self._type, self._name, self._name + '_sum', self._labelnames, self._labelvalues, self._documentation) + for b in self._upper_bounds: + self._buckets.append(values.ValueClass( + self._type, + self._name, + self._name + '_bucket', + bucket_labelnames, + self._labelvalues + (floatToGoString(b),), + self._documentation) + ) + + def observe(self, amount: float, exemplar: Optional[Dict[str, str]] = None) -> None: + """Observe the given amount. + + The amount is usually positive or zero. Negative values are + accepted but prevent current versions of Prometheus from + properly detecting counter resets in the sum of + observations. See + https://prometheus.io/docs/practices/histograms/#count-and-sum-of-observations + for details. + """ + self._raise_if_not_observable() + self._sum.inc(amount) + for i, bound in enumerate(self._upper_bounds): + if amount <= bound: + self._buckets[i].inc(1) + if exemplar: + _validate_exemplar(exemplar) + self._buckets[i].set_exemplar(Exemplar(exemplar, amount, time.time())) + break + + def time(self) -> Timer: + """Time a block of code or function, and observe the duration in seconds. + + Can be used as a function decorator or context manager. + """ + return Timer(self, 'observe') + + def _child_samples(self) -> Iterable[Sample]: + samples = [] + acc = 0.0 + for i, bound in enumerate(self._upper_bounds): + acc += self._buckets[i].get() + samples.append(Sample('_bucket', {'le': floatToGoString(bound)}, acc, None, self._buckets[i].get_exemplar())) + samples.append(Sample('_count', {}, acc, None, None)) + if self._upper_bounds[0] >= 0: + samples.append(Sample('_sum', {}, self._sum.get(), None, None)) + if _use_created: + samples.append(Sample('_created', {}, self._created, None, None)) + return tuple(samples) + + +class Info(MetricWrapperBase): + """Info metric, key-value pairs. + + Examples of Info include: + - Build information + - Version information + - Potential target metadata + + Example usage: + from prometheus_client import Info + + i = Info('my_build', 'Description of info') + i.info({'version': '1.2.3', 'buildhost': 'foo@bar'}) + + Info metrics do not work in multiprocess mode. + """ + _type = 'info' + + def _metric_init(self): + self._labelname_set = set(self._labelnames) + self._lock = Lock() + self._value = {} + + def info(self, val: Dict[str, str]) -> None: + """Set info metric.""" + if self._labelname_set.intersection(val.keys()): + raise ValueError('Overlapping labels for Info metric, metric: {} child: {}'.format( + self._labelnames, val)) + if any(i is None for i in val.values()): + raise ValueError('Label value cannot be None') + with self._lock: + self._value = dict(val) + + def _child_samples(self) -> Iterable[Sample]: + with self._lock: + return (Sample('_info', self._value, 1.0, None, None),) + + +class Enum(MetricWrapperBase): + """Enum metric, which of a set of states is true. + + Example usage: + from prometheus_client import Enum + + e = Enum('task_state', 'Description of enum', + states=['starting', 'running', 'stopped']) + e.state('running') + + The first listed state will be the default. + Enum metrics do not work in multiprocess mode. + """ + _type = 'stateset' + + def __init__(self, + name: str, + documentation: str, + labelnames: Sequence[str] = (), + namespace: str = '', + subsystem: str = '', + unit: str = '', + registry: Optional[CollectorRegistry] = REGISTRY, + _labelvalues: Optional[Sequence[str]] = None, + states: Optional[Sequence[str]] = None, + ): + super().__init__( + name=name, + documentation=documentation, + labelnames=labelnames, + namespace=namespace, + subsystem=subsystem, + unit=unit, + registry=registry, + _labelvalues=_labelvalues, + ) + if name in labelnames: + raise ValueError(f'Overlapping labels for Enum metric: {name}') + if not states: + raise ValueError(f'No states provided for Enum metric: {name}') + self._kwargs['states'] = self._states = states + + def _metric_init(self) -> None: + self._value = 0 + self._lock = Lock() + + def state(self, state: str) -> None: + """Set enum metric state.""" + self._raise_if_not_observable() + with self._lock: + self._value = self._states.index(state) + + def _child_samples(self) -> Iterable[Sample]: + with self._lock: + return [ + Sample('', {self._name: s}, 1 if i == self._value else 0, None, None) + for i, s + in enumerate(self._states) + ] diff --git a/venv/lib/python3.10/site-packages/prometheus_client/metrics_core.py b/venv/lib/python3.10/site-packages/prometheus_client/metrics_core.py new file mode 100644 index 0000000000000000000000000000000000000000..27d1712ddaa7d4e4573ed7c13a20974a32e198ea --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/metrics_core.py @@ -0,0 +1,415 @@ +from typing import Dict, List, Optional, Sequence, Tuple, Union + +from .samples import Exemplar, NativeHistogram, Sample, Timestamp +from .validation import _validate_metric_name + +METRIC_TYPES = ( + 'counter', 'gauge', 'summary', 'histogram', + 'gaugehistogram', 'unknown', 'info', 'stateset', +) + + +class Metric: + """A single metric family and its samples. + + This is intended only for internal use by the instrumentation client. + + Custom collectors should use GaugeMetricFamily, CounterMetricFamily + and SummaryMetricFamily instead. + """ + + def __init__(self, name: str, documentation: str, typ: str, unit: str = ''): + if unit and not name.endswith("_" + unit): + name += "_" + unit + _validate_metric_name(name) + self.name: str = name + self.documentation: str = documentation + self.unit: str = unit + if typ == 'untyped': + typ = 'unknown' + if typ not in METRIC_TYPES: + raise ValueError('Invalid metric type: ' + typ) + self.type: str = typ + self.samples: List[Sample] = [] + + def add_sample(self, name: str, labels: Dict[str, str], value: float, timestamp: Optional[Union[Timestamp, float]] = None, exemplar: Optional[Exemplar] = None, native_histogram: Optional[NativeHistogram] = None) -> None: + """Add a sample to the metric. + + Internal-only, do not use.""" + self.samples.append(Sample(name, labels, value, timestamp, exemplar, native_histogram)) + + def __eq__(self, other: object) -> bool: + return (isinstance(other, Metric) + and self.name == other.name + and self.documentation == other.documentation + and self.type == other.type + and self.unit == other.unit + and self.samples == other.samples) + + def __repr__(self) -> str: + return "Metric({}, {}, {}, {}, {})".format( + self.name, + self.documentation, + self.type, + self.unit, + self.samples, + ) + + def _restricted_metric(self, names): + """Build a snapshot of a metric with samples restricted to a given set of names.""" + samples = [s for s in self.samples if s[0] in names] + if samples: + m = Metric(self.name, self.documentation, self.type) + m.samples = samples + return m + return None + + +class UnknownMetricFamily(Metric): + """A single unknown metric and its samples. + For use by custom collectors. + """ + + def __init__(self, + name: str, + documentation: str, + value: Optional[float] = None, + labels: Optional[Sequence[str]] = None, + unit: str = '', + ): + Metric.__init__(self, name, documentation, 'unknown', unit) + if labels is not None and value is not None: + raise ValueError('Can only specify at most one of value and labels.') + if labels is None: + labels = [] + self._labelnames = tuple(labels) + if value is not None: + self.add_metric([], value) + + def add_metric(self, labels: Sequence[str], value: float, timestamp: Optional[Union[Timestamp, float]] = None) -> None: + """Add a metric to the metric family. + Args: + labels: A list of label values + value: The value of the metric. + """ + self.samples.append(Sample(self.name, dict(zip(self._labelnames, labels)), value, timestamp)) + + +# For backward compatibility. +UntypedMetricFamily = UnknownMetricFamily + + +class CounterMetricFamily(Metric): + """A single counter and its samples. + + For use by custom collectors. + """ + + def __init__(self, + name: str, + documentation: str, + value: Optional[float] = None, + labels: Optional[Sequence[str]] = None, + created: Optional[float] = None, + unit: str = '', + exemplar: Optional[Exemplar] = None, + ): + # Glue code for pre-OpenMetrics metrics. + if name.endswith('_total'): + name = name[:-6] + Metric.__init__(self, name, documentation, 'counter', unit) + if labels is not None and value is not None: + raise ValueError('Can only specify at most one of value and labels.') + if labels is None: + labels = [] + self._labelnames = tuple(labels) + if value is not None: + self.add_metric([], value, created, exemplar=exemplar) + + def add_metric(self, + labels: Sequence[str], + value: float, + created: Optional[float] = None, + timestamp: Optional[Union[Timestamp, float]] = None, + exemplar: Optional[Exemplar] = None, + ) -> None: + """Add a metric to the metric family. + + Args: + labels: A list of label values + value: The value of the metric + created: Optional unix timestamp the child was created at. + """ + self.samples.append(Sample(self.name + '_total', dict(zip(self._labelnames, labels)), value, timestamp, exemplar)) + if created is not None: + self.samples.append(Sample(self.name + '_created', dict(zip(self._labelnames, labels)), created, timestamp)) + + +class GaugeMetricFamily(Metric): + """A single gauge and its samples. + + For use by custom collectors. + """ + + def __init__(self, + name: str, + documentation: str, + value: Optional[float] = None, + labels: Optional[Sequence[str]] = None, + unit: str = '', + ): + Metric.__init__(self, name, documentation, 'gauge', unit) + if labels is not None and value is not None: + raise ValueError('Can only specify at most one of value and labels.') + if labels is None: + labels = [] + self._labelnames = tuple(labels) + if value is not None: + self.add_metric([], value) + + def add_metric(self, labels: Sequence[str], value: float, timestamp: Optional[Union[Timestamp, float]] = None) -> None: + """Add a metric to the metric family. + + Args: + labels: A list of label values + value: A float + """ + self.samples.append(Sample(self.name, dict(zip(self._labelnames, labels)), value, timestamp)) + + +class SummaryMetricFamily(Metric): + """A single summary and its samples. + + For use by custom collectors. + """ + + def __init__(self, + name: str, + documentation: str, + count_value: Optional[int] = None, + sum_value: Optional[float] = None, + labels: Optional[Sequence[str]] = None, + unit: str = '', + ): + Metric.__init__(self, name, documentation, 'summary', unit) + if (sum_value is None) != (count_value is None): + raise ValueError('count_value and sum_value must be provided together.') + if labels is not None and count_value is not None: + raise ValueError('Can only specify at most one of value and labels.') + if labels is None: + labels = [] + self._labelnames = tuple(labels) + # The and clause is necessary only for typing, the above ValueError will raise if only one is set. + if count_value is not None and sum_value is not None: + self.add_metric([], count_value, sum_value) + + def add_metric(self, + labels: Sequence[str], + count_value: int, + sum_value: float, + timestamp: + Optional[Union[float, Timestamp]] = None + ) -> None: + """Add a metric to the metric family. + + Args: + labels: A list of label values + count_value: The count value of the metric. + sum_value: The sum value of the metric. + """ + self.samples.append(Sample(self.name + '_count', dict(zip(self._labelnames, labels)), count_value, timestamp)) + self.samples.append(Sample(self.name + '_sum', dict(zip(self._labelnames, labels)), sum_value, timestamp)) + + +class HistogramMetricFamily(Metric): + """A single histogram and its samples. + + For use by custom collectors. + """ + + def __init__(self, + name: str, + documentation: str, + buckets: Optional[Sequence[Union[Tuple[str, float], Tuple[str, float, Exemplar]]]] = None, + sum_value: Optional[float] = None, + labels: Optional[Sequence[str]] = None, + unit: str = '', + ): + Metric.__init__(self, name, documentation, 'histogram', unit) + if sum_value is not None and buckets is None: + raise ValueError('sum value cannot be provided without buckets.') + if labels is not None and buckets is not None: + raise ValueError('Can only specify at most one of buckets and labels.') + if labels is None: + labels = [] + self._labelnames = tuple(labels) + if buckets is not None: + self.add_metric([], buckets, sum_value) + + def add_metric(self, + labels: Sequence[str], + buckets: Sequence[Union[Tuple[str, float], Tuple[str, float, Exemplar]]], + sum_value: Optional[float], + timestamp: Optional[Union[Timestamp, float]] = None) -> None: + """Add a metric to the metric family. + + Args: + labels: A list of label values + buckets: A list of lists. + Each inner list can be a pair of bucket name and value, + or a triple of bucket name, value, and exemplar. + The buckets must be sorted, and +Inf present. + sum_value: The sum value of the metric. + """ + for b in buckets: + bucket, value = b[:2] + exemplar = None + if len(b) == 3: + exemplar = b[2] # type: ignore + self.samples.append(Sample( + self.name + '_bucket', + dict(list(zip(self._labelnames, labels)) + [('le', bucket)]), + value, + timestamp, + exemplar, + )) + # Don't include sum and thus count if there's negative buckets. + if float(buckets[0][0]) >= 0 and sum_value is not None: + # +Inf is last and provides the count value. + self.samples.append( + Sample(self.name + '_count', dict(zip(self._labelnames, labels)), buckets[-1][1], timestamp)) + self.samples.append( + Sample(self.name + '_sum', dict(zip(self._labelnames, labels)), sum_value, timestamp)) + + +class GaugeHistogramMetricFamily(Metric): + """A single gauge histogram and its samples. + + For use by custom collectors. + """ + + def __init__(self, + name: str, + documentation: str, + buckets: Optional[Sequence[Tuple[str, float]]] = None, + gsum_value: Optional[float] = None, + labels: Optional[Sequence[str]] = None, + unit: str = '', + ): + Metric.__init__(self, name, documentation, 'gaugehistogram', unit) + if labels is not None and buckets is not None: + raise ValueError('Can only specify at most one of buckets and labels.') + if labels is None: + labels = [] + self._labelnames = tuple(labels) + if buckets is not None: + self.add_metric([], buckets, gsum_value) + + def add_metric(self, + labels: Sequence[str], + buckets: Sequence[Tuple[str, float]], + gsum_value: Optional[float], + timestamp: Optional[Union[float, Timestamp]] = None, + ) -> None: + """Add a metric to the metric family. + + Args: + labels: A list of label values + buckets: A list of pairs of bucket names and values. + The buckets must be sorted, and +Inf present. + gsum_value: The sum value of the metric. + """ + for bucket, value in buckets: + self.samples.append(Sample( + self.name + '_bucket', + dict(list(zip(self._labelnames, labels)) + [('le', bucket)]), + value, timestamp)) + # +Inf is last and provides the count value. + self.samples.extend([ + Sample(self.name + '_gcount', dict(zip(self._labelnames, labels)), buckets[-1][1], timestamp), + # TODO: Handle None gsum_value correctly. Currently a None will fail exposition but is allowed here. + Sample(self.name + '_gsum', dict(zip(self._labelnames, labels)), gsum_value, timestamp), # type: ignore + ]) + + +class InfoMetricFamily(Metric): + """A single info and its samples. + + For use by custom collectors. + """ + + def __init__(self, + name: str, + documentation: str, + value: Optional[Dict[str, str]] = None, + labels: Optional[Sequence[str]] = None, + ): + Metric.__init__(self, name, documentation, 'info') + if labels is not None and value is not None: + raise ValueError('Can only specify at most one of value and labels.') + if labels is None: + labels = [] + self._labelnames = tuple(labels) + if value is not None: + self.add_metric([], value) + + def add_metric(self, + labels: Sequence[str], + value: Dict[str, str], + timestamp: Optional[Union[Timestamp, float]] = None, + ) -> None: + """Add a metric to the metric family. + + Args: + labels: A list of label values + value: A dict of labels + """ + self.samples.append(Sample( + self.name + '_info', + dict(dict(zip(self._labelnames, labels)), **value), + 1, + timestamp, + )) + + +class StateSetMetricFamily(Metric): + """A single stateset and its samples. + + For use by custom collectors. + """ + + def __init__(self, + name: str, + documentation: str, + value: Optional[Dict[str, bool]] = None, + labels: Optional[Sequence[str]] = None, + ): + Metric.__init__(self, name, documentation, 'stateset') + if labels is not None and value is not None: + raise ValueError('Can only specify at most one of value and labels.') + if labels is None: + labels = [] + self._labelnames = tuple(labels) + if value is not None: + self.add_metric([], value) + + def add_metric(self, + labels: Sequence[str], + value: Dict[str, bool], + timestamp: Optional[Union[Timestamp, float]] = None, + ) -> None: + """Add a metric to the metric family. + + Args: + labels: A list of label values + value: A dict of string state names to booleans + """ + labels = tuple(labels) + for state, enabled in sorted(value.items()): + v = (1 if enabled else 0) + self.samples.append(Sample( + self.name, + dict(zip(self._labelnames + (self.name,), labels + (state,))), + v, + timestamp, + )) diff --git a/venv/lib/python3.10/site-packages/prometheus_client/mmap_dict.py b/venv/lib/python3.10/site-packages/prometheus_client/mmap_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..edd895cda9d492b3874597d0613d9eee1f5f48f1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/mmap_dict.py @@ -0,0 +1,145 @@ +import json +import mmap +import os +import struct +from typing import List + +_INITIAL_MMAP_SIZE = 1 << 16 +_pack_integer_func = struct.Struct(b'i').pack +_pack_two_doubles_func = struct.Struct(b'dd').pack +_unpack_integer = struct.Struct(b'i').unpack_from +_unpack_two_doubles = struct.Struct(b'dd').unpack_from + + +# struct.pack_into has atomicity issues because it will temporarily write 0 into +# the mmap, resulting in false reads to 0 when experiencing a lot of writes. +# Using direct assignment solves this issue. + + +def _pack_two_doubles(data, pos, value, timestamp): + data[pos:pos + 16] = _pack_two_doubles_func(value, timestamp) + + +def _pack_integer(data, pos, value): + data[pos:pos + 4] = _pack_integer_func(value) + + +def _read_all_values(data, used=0): + """Yield (key, value, timestamp, pos). No locking is performed.""" + + if used <= 0: + # If not valid `used` value is passed in, read it from the file. + used = _unpack_integer(data, 0)[0] + + pos = 8 + + while pos < used: + encoded_len = _unpack_integer(data, pos)[0] + # check we are not reading beyond bounds + if encoded_len + pos > used: + raise RuntimeError('Read beyond file size detected, file is corrupted.') + pos += 4 + encoded_key = data[pos:pos + encoded_len] + padded_len = encoded_len + (8 - (encoded_len + 4) % 8) + pos += padded_len + value, timestamp = _unpack_two_doubles(data, pos) + yield encoded_key.decode('utf-8'), value, timestamp, pos + pos += 16 + + +class MmapedDict: + """A dict of doubles, backed by an mmapped file. + + The file starts with a 4 byte int, indicating how much of it is used. + Then 4 bytes of padding. + There's then a number of entries, consisting of a 4 byte int which is the + size of the next field, a utf-8 encoded string key, padding to a 8 byte + alignment, and then a 8 byte float which is the value and a 8 byte float + which is a UNIX timestamp in seconds. + + Not thread safe. + """ + + def __init__(self, filename, read_mode=False): + self._f = open(filename, 'rb' if read_mode else 'a+b') + self._fname = filename + capacity = os.fstat(self._f.fileno()).st_size + if capacity == 0: + self._f.truncate(_INITIAL_MMAP_SIZE) + capacity = _INITIAL_MMAP_SIZE + self._capacity = capacity + self._m = mmap.mmap(self._f.fileno(), self._capacity, + access=mmap.ACCESS_READ if read_mode else mmap.ACCESS_WRITE) + + self._positions = {} + self._used = _unpack_integer(self._m, 0)[0] + if self._used == 0: + self._used = 8 + _pack_integer(self._m, 0, self._used) + else: + if not read_mode: + for key, _, _, pos in self._read_all_values(): + self._positions[key] = pos + + @staticmethod + def read_all_values_from_file(filename): + with open(filename, 'rb') as infp: + # Read the first block of data, including the first 4 bytes which tell us + # how much of the file (which is preallocated to _INITIAL_MMAP_SIZE bytes) is occupied. + data = infp.read(mmap.PAGESIZE) + used = _unpack_integer(data, 0)[0] + if used > len(data): # Then read in the rest, if needed. + data += infp.read(used - len(data)) + return _read_all_values(data, used) + + def _init_value(self, key): + """Initialize a value. Lock must be held by caller.""" + encoded = key.encode('utf-8') + # Pad to be 8-byte aligned. + padded = encoded + (b' ' * (8 - (len(encoded) + 4) % 8)) + value = struct.pack(f'i{len(padded)}sdd'.encode(), len(encoded), padded, 0.0, 0.0) + while self._used + len(value) > self._capacity: + self._capacity *= 2 + self._f.truncate(self._capacity) + self._m = mmap.mmap(self._f.fileno(), self._capacity) + self._m[self._used:self._used + len(value)] = value + + # Update how much space we've used. + self._used += len(value) + _pack_integer(self._m, 0, self._used) + self._positions[key] = self._used - 16 + + def _read_all_values(self): + """Yield (key, value, pos). No locking is performed.""" + return _read_all_values(data=self._m, used=self._used) + + def read_all_values(self): + """Yield (key, value, timestamp). No locking is performed.""" + for k, v, ts, _ in self._read_all_values(): + yield k, v, ts + + def read_value(self, key): + if key not in self._positions: + self._init_value(key) + pos = self._positions[key] + return _unpack_two_doubles(self._m, pos) + + def write_value(self, key, value, timestamp): + if key not in self._positions: + self._init_value(key) + pos = self._positions[key] + _pack_two_doubles(self._m, pos, value, timestamp) + + def close(self): + if self._f: + self._m.close() + self._m = None + self._f.close() + self._f = None + + +def mmap_key(metric_name: str, name: str, labelnames: List[str], labelvalues: List[str], help_text: str) -> str: + """Format a key for use in the mmap file.""" + # ensure labels are in consistent order for identity + labels = dict(zip(labelnames, labelvalues)) + return json.dumps([metric_name, name, labels, help_text], sort_keys=True) diff --git a/venv/lib/python3.10/site-packages/prometheus_client/multiprocess.py b/venv/lib/python3.10/site-packages/prometheus_client/multiprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..2682190a4901c18db3360699bc38bf20b4ddabad --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/multiprocess.py @@ -0,0 +1,170 @@ +from collections import defaultdict +import glob +import json +import os +import warnings + +from .metrics import Gauge +from .metrics_core import Metric +from .mmap_dict import MmapedDict +from .samples import Sample +from .utils import floatToGoString + +try: # Python3 + FileNotFoundError +except NameError: # Python >= 2.5 + FileNotFoundError = IOError + + +class MultiProcessCollector: + """Collector for files for multi-process mode.""" + + def __init__(self, registry, path=None): + if path is None: + # This deprecation warning can go away in a few releases when removing the compatibility + if 'prometheus_multiproc_dir' in os.environ and 'PROMETHEUS_MULTIPROC_DIR' not in os.environ: + os.environ['PROMETHEUS_MULTIPROC_DIR'] = os.environ['prometheus_multiproc_dir'] + warnings.warn("prometheus_multiproc_dir variable has been deprecated in favor of the upper case naming PROMETHEUS_MULTIPROC_DIR", DeprecationWarning) + path = os.environ.get('PROMETHEUS_MULTIPROC_DIR') + if not path or not os.path.isdir(path): + raise ValueError('env PROMETHEUS_MULTIPROC_DIR is not set or not a directory') + self._path = path + if registry: + registry.register(self) + + @staticmethod + def merge(files, accumulate=True): + """Merge metrics from given mmap files. + + By default, histograms are accumulated, as per prometheus wire format. + But if writing the merged data back to mmap files, use + accumulate=False to avoid compound accumulation. + """ + metrics = MultiProcessCollector._read_metrics(files) + return MultiProcessCollector._accumulate_metrics(metrics, accumulate) + + @staticmethod + def _read_metrics(files): + metrics = {} + key_cache = {} + + def _parse_key(key): + val = key_cache.get(key) + if not val: + metric_name, name, labels, help_text = json.loads(key) + labels_key = tuple(sorted(labels.items())) + val = key_cache[key] = (metric_name, name, labels, labels_key, help_text) + return val + + for f in files: + parts = os.path.basename(f).split('_') + typ = parts[0] + try: + file_values = MmapedDict.read_all_values_from_file(f) + except FileNotFoundError: + if typ == 'gauge' and parts[1].startswith('live'): + # Files for 'live*' gauges can be deleted between the glob of collect + # and now (via a mark_process_dead call) so don't fail if + # the file is missing + continue + raise + for key, value, timestamp, _ in file_values: + metric_name, name, labels, labels_key, help_text = _parse_key(key) + + metric = metrics.get(metric_name) + if metric is None: + metric = Metric(metric_name, help_text, typ) + metrics[metric_name] = metric + + if typ == 'gauge': + pid = parts[2][:-3] + metric._multiprocess_mode = parts[1] + metric.add_sample(name, labels_key + (('pid', pid),), value, timestamp) + else: + # The duplicates and labels are fixed in the next for. + metric.add_sample(name, labels_key, value) + return metrics + + @staticmethod + def _accumulate_metrics(metrics, accumulate): + for metric in metrics.values(): + samples = defaultdict(float) + sample_timestamps = defaultdict(float) + buckets = defaultdict(lambda: defaultdict(float)) + samples_setdefault = samples.setdefault + for s in metric.samples: + name, labels, value, timestamp, exemplar, native_histogram_value = s + if metric.type == 'gauge': + without_pid_key = (name, tuple(l for l in labels if l[0] != 'pid')) + if metric._multiprocess_mode in ('min', 'livemin'): + current = samples_setdefault(without_pid_key, value) + if value < current: + samples[without_pid_key] = value + elif metric._multiprocess_mode in ('max', 'livemax'): + current = samples_setdefault(without_pid_key, value) + if value > current: + samples[without_pid_key] = value + elif metric._multiprocess_mode in ('sum', 'livesum'): + samples[without_pid_key] += value + elif metric._multiprocess_mode in ('mostrecent', 'livemostrecent'): + current_timestamp = sample_timestamps[without_pid_key] + timestamp = float(timestamp or 0) + if current_timestamp < timestamp: + samples[without_pid_key] = value + sample_timestamps[without_pid_key] = timestamp + else: # all/liveall + samples[(name, labels)] = value + + elif metric.type == 'histogram': + # A for loop with early exit is faster than a genexpr + # or a listcomp that ends up building unnecessary things + for l in labels: + if l[0] == 'le': + bucket_value = float(l[1]) + # _bucket + without_le = tuple(l for l in labels if l[0] != 'le') + buckets[without_le][bucket_value] += value + break + else: # did not find the `le` key + # _sum/_count + samples[(name, labels)] += value + else: + # Counter and Summary. + samples[(name, labels)] += value + + # Accumulate bucket values. + if metric.type == 'histogram': + for labels, values in buckets.items(): + acc = 0.0 + for bucket, value in sorted(values.items()): + sample_key = ( + metric.name + '_bucket', + labels + (('le', floatToGoString(bucket)),), + ) + if accumulate: + acc += value + samples[sample_key] = acc + else: + samples[sample_key] = value + if accumulate: + samples[(metric.name + '_count', labels)] = acc + + # Convert to correct sample format. + metric.samples = [Sample(name_, dict(labels), value) for (name_, labels), value in samples.items()] + return metrics.values() + + def collect(self): + files = glob.glob(os.path.join(self._path, '*.db')) + return self.merge(files, accumulate=True) + + +_LIVE_GAUGE_MULTIPROCESS_MODES = {m for m in Gauge._MULTIPROC_MODES if m.startswith('live')} + + +def mark_process_dead(pid, path=None): + """Do bookkeeping for when one process dies in a multi-process setup.""" + if path is None: + path = os.environ.get('PROMETHEUS_MULTIPROC_DIR', os.environ.get('prometheus_multiproc_dir')) + for mode in _LIVE_GAUGE_MULTIPROCESS_MODES: + for f in glob.glob(os.path.join(path, f'gauge_{mode}_{pid}.db')): + os.remove(f) diff --git a/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/__init__.py b/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..078ef0ae5e3bbfa608d9fdc1e6ed5caf894a1d76 Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/__pycache__/exposition.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/__pycache__/exposition.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a53c77af4581efad0235200e9965319dc9c070be Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/__pycache__/exposition.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/__pycache__/parser.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/__pycache__/parser.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bda5cc1036f8d2342b3cc1d19c44b26f44d119e5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/__pycache__/parser.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/exposition.py b/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/exposition.py new file mode 100644 index 0000000000000000000000000000000000000000..84600605e57abef36a1a2a095197ac7cff2f907d --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/exposition.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python + + +from ..utils import floatToGoString +from ..validation import ( + _is_valid_legacy_labelname, _is_valid_legacy_metric_name, +) + +CONTENT_TYPE_LATEST = 'application/openmetrics-text; version=1.0.0; charset=utf-8' +"""Content type of the latest OpenMetrics text format""" + + +def _is_valid_exemplar_metric(metric, sample): + if metric.type == 'counter' and sample.name.endswith('_total'): + return True + if metric.type in ('gaugehistogram') and sample.name.endswith('_bucket'): + return True + if metric.type in ('histogram') and sample.name.endswith('_bucket') or sample.name == metric.name: + return True + return False + + +def generate_latest(registry): + '''Returns the metrics from the registry in latest text format as a string.''' + output = [] + for metric in registry.collect(): + try: + mname = metric.name + output.append('# HELP {} {}\n'.format( + escape_metric_name(mname), _escape(metric.documentation))) + output.append(f'# TYPE {escape_metric_name(mname)} {metric.type}\n') + if metric.unit: + output.append(f'# UNIT {escape_metric_name(mname)} {metric.unit}\n') + for s in metric.samples: + if not _is_valid_legacy_metric_name(s.name): + labelstr = escape_metric_name(s.name) + if s.labels: + labelstr += ', ' + else: + labelstr = '' + + if s.labels: + items = sorted(s.labels.items()) + labelstr += ','.join( + ['{}="{}"'.format( + escape_label_name(k), _escape(v)) + for k, v in items]) + if labelstr: + labelstr = "{" + labelstr + "}" + + if s.exemplar: + if not _is_valid_exemplar_metric(metric, s): + raise ValueError(f"Metric {metric.name} has exemplars, but is not a histogram bucket or counter") + labels = '{{{0}}}'.format(','.join( + ['{}="{}"'.format( + k, v.replace('\\', r'\\').replace('\n', r'\n').replace('"', r'\"')) + for k, v in sorted(s.exemplar.labels.items())])) + if s.exemplar.timestamp is not None: + exemplarstr = ' # {} {} {}'.format( + labels, + floatToGoString(s.exemplar.value), + s.exemplar.timestamp, + ) + else: + exemplarstr = ' # {} {}'.format( + labels, + floatToGoString(s.exemplar.value), + ) + else: + exemplarstr = '' + timestamp = '' + if s.timestamp is not None: + timestamp = f' {s.timestamp}' + if _is_valid_legacy_metric_name(s.name): + output.append('{}{} {}{}{}\n'.format( + s.name, + labelstr, + floatToGoString(s.value), + timestamp, + exemplarstr, + )) + else: + output.append('{} {}{}{}\n'.format( + labelstr, + floatToGoString(s.value), + timestamp, + exemplarstr, + )) + except Exception as exception: + exception.args = (exception.args or ('',)) + (metric,) + raise + + output.append('# EOF\n') + return ''.join(output).encode('utf-8') + + +def escape_metric_name(s: str) -> str: + """Escapes the metric name and puts it in quotes iff the name does not + conform to the legacy Prometheus character set. + """ + if _is_valid_legacy_metric_name(s): + return s + return '"{}"'.format(_escape(s)) + + +def escape_label_name(s: str) -> str: + """Escapes the label name and puts it in quotes iff the name does not + conform to the legacy Prometheus character set. + """ + if _is_valid_legacy_labelname(s): + return s + return '"{}"'.format(_escape(s)) + + +def _escape(s: str) -> str: + """Performs backslash escaping on backslash, newline, and double-quote characters.""" + return s.replace('\\', r'\\').replace('\n', r'\n').replace('"', r'\"') diff --git a/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/parser.py b/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..d967e83b93bae5683449e5527c24566efb05ddf8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/openmetrics/parser.py @@ -0,0 +1,653 @@ +#!/usr/bin/env python + + +import io as StringIO +import math +import re + +from ..metrics_core import Metric +from ..parser import ( + _last_unquoted_char, _next_unquoted_char, _parse_value, _split_quoted, + _unquote_unescape, parse_labels, +) +from ..samples import BucketSpan, Exemplar, NativeHistogram, Sample, Timestamp +from ..utils import floatToGoString +from ..validation import _is_valid_legacy_metric_name, _validate_metric_name + + +def text_string_to_metric_families(text): + """Parse Openmetrics text format from a unicode string. + + See text_fd_to_metric_families. + """ + yield from text_fd_to_metric_families(StringIO.StringIO(text)) + + +_CANONICAL_NUMBERS = {float("inf")} + + +def _isUncanonicalNumber(s): + f = float(s) + if f not in _CANONICAL_NUMBERS: + return False # Only the canonical numbers are required to be canonical. + return s != floatToGoString(f) + + +ESCAPE_SEQUENCES = { + '\\\\': '\\', + '\\n': '\n', + '\\"': '"', +} + + +def _replace_escape_sequence(match): + return ESCAPE_SEQUENCES[match.group(0)] + + +ESCAPING_RE = re.compile(r'\\[\\n"]') + + +def _replace_escaping(s): + return ESCAPING_RE.sub(_replace_escape_sequence, s) + + +def _unescape_help(text): + result = [] + slash = False + + for char in text: + if slash: + if char == '\\': + result.append('\\') + elif char == '"': + result.append('"') + elif char == 'n': + result.append('\n') + else: + result.append('\\' + char) + slash = False + else: + if char == '\\': + slash = True + else: + result.append(char) + + if slash: + result.append('\\') + + return ''.join(result) + + +def _parse_timestamp(timestamp): + timestamp = ''.join(timestamp) + if not timestamp: + return None + if timestamp != timestamp.strip() or '_' in timestamp: + raise ValueError(f"Invalid timestamp: {timestamp!r}") + try: + # Simple int. + return Timestamp(int(timestamp), 0) + except ValueError: + try: + # aaaa.bbbb. Nanosecond resolution supported. + parts = timestamp.split('.', 1) + return Timestamp(int(parts[0]), int(parts[1][:9].ljust(9, "0"))) + except ValueError: + # Float. + ts = float(timestamp) + if math.isnan(ts) or math.isinf(ts): + raise ValueError(f"Invalid timestamp: {timestamp!r}") + return ts + + +def _is_character_escaped(s, charpos): + num_bslashes = 0 + while (charpos > num_bslashes + and s[charpos - 1 - num_bslashes] == '\\'): + num_bslashes += 1 + return num_bslashes % 2 == 1 + + +def _parse_sample(text): + separator = " # " + # Detect the labels in the text + label_start = _next_unquoted_char(text, '{') + if label_start == -1 or separator in text[:label_start]: + # We don't have labels, but there could be an exemplar. + name_end = _next_unquoted_char(text, ' ') + name = text[:name_end] + if not _is_valid_legacy_metric_name(name): + raise ValueError("invalid metric name:" + text) + # Parse the remaining text after the name + remaining_text = text[name_end + 1:] + value, timestamp, exemplar = _parse_remaining_text(remaining_text) + return Sample(name, {}, value, timestamp, exemplar) + name = text[:label_start] + label_end = _next_unquoted_char(text, '}') + labels = parse_labels(text[label_start + 1:label_end], True) + if not name: + # Name might be in the labels + if '__name__' not in labels: + raise ValueError + name = labels['__name__'] + del labels['__name__'] + elif '__name__' in labels: + raise ValueError("metric name specified more than once") + # Parsing labels succeeded, continue parsing the remaining text + remaining_text = text[label_end + 2:] + value, timestamp, exemplar = _parse_remaining_text(remaining_text) + return Sample(name, labels, value, timestamp, exemplar) + + +def _parse_remaining_text(text): + split_text = text.split(" ", 1) + val = _parse_value(split_text[0]) + if len(split_text) == 1: + # We don't have timestamp or exemplar + return val, None, None + + timestamp = [] + exemplar_value = [] + exemplar_timestamp = [] + exemplar_labels = None + + state = 'timestamp' + text = split_text[1] + + it = iter(text) + in_quotes = False + for char in it: + if char == '"': + in_quotes = not in_quotes + if in_quotes: + continue + if state == 'timestamp': + if char == '#' and not timestamp: + state = 'exemplarspace' + elif char == ' ': + state = 'exemplarhash' + else: + timestamp.append(char) + elif state == 'exemplarhash': + if char == '#': + state = 'exemplarspace' + else: + raise ValueError("Invalid line: " + text) + elif state == 'exemplarspace': + if char == ' ': + state = 'exemplarstartoflabels' + else: + raise ValueError("Invalid line: " + text) + elif state == 'exemplarstartoflabels': + if char == '{': + label_start = _next_unquoted_char(text, '{') + label_end = _last_unquoted_char(text, '}') + exemplar_labels = parse_labels(text[label_start + 1:label_end], True) + state = 'exemplarparsedlabels' + else: + raise ValueError("Invalid line: " + text) + elif state == 'exemplarparsedlabels': + if char == '}': + state = 'exemplarvaluespace' + elif state == 'exemplarvaluespace': + if char == ' ': + state = 'exemplarvalue' + else: + raise ValueError("Invalid line: " + text) + elif state == 'exemplarvalue': + if char == ' ' and not exemplar_value: + raise ValueError("Invalid line: " + text) + elif char == ' ': + state = 'exemplartimestamp' + else: + exemplar_value.append(char) + elif state == 'exemplartimestamp': + exemplar_timestamp.append(char) + + # Trailing space after value. + if state == 'timestamp' and not timestamp: + raise ValueError("Invalid line: " + text) + + # Trailing space after value. + if state == 'exemplartimestamp' and not exemplar_timestamp: + raise ValueError("Invalid line: " + text) + + # Incomplete exemplar. + if state in ['exemplarhash', 'exemplarspace', 'exemplarstartoflabels', 'exemplarparsedlabels']: + raise ValueError("Invalid line: " + text) + + ts = _parse_timestamp(timestamp) + exemplar = None + if exemplar_labels is not None: + exemplar_length = sum(len(k) + len(v) for k, v in exemplar_labels.items()) + if exemplar_length > 128: + raise ValueError("Exemplar labels are too long: " + text) + exemplar = Exemplar( + exemplar_labels, + _parse_value(exemplar_value), + _parse_timestamp(exemplar_timestamp), + ) + + return val, ts, exemplar + + +def _parse_nh_sample(text, suffixes): + """Determines if the line has a native histogram sample, and parses it if so.""" + labels_start = _next_unquoted_char(text, '{') + labels_end = -1 + + # Finding a native histogram sample requires careful parsing of + # possibly-quoted text, which can appear in metric names, label names, and + # values. + # + # First, we need to determine if there are metric labels. Find the space + # between the metric definition and the rest of the line. Look for unquoted + # space or {. + i = 0 + has_metric_labels = False + i = _next_unquoted_char(text, ' {') + if i == -1: + return + + # If the first unquoted char was a {, then that is the metric labels (which + # could contain a UTF-8 metric name). + if text[i] == '{': + has_metric_labels = True + # Consume the labels -- jump ahead to the close bracket. + labels_end = i = _next_unquoted_char(text, '}', i) + if labels_end == -1: + raise ValueError + + # If there is no subsequent unquoted {, then it's definitely not a nh. + nh_value_start = _next_unquoted_char(text, '{', i + 1) + if nh_value_start == -1: + return + + # Edge case: if there is an unquoted # between the metric definition and the {, + # then this is actually an exemplar + exemplar = _next_unquoted_char(text, '#', i + 1) + if exemplar != -1 and exemplar < nh_value_start: + return + + nh_value_end = _next_unquoted_char(text, '}', nh_value_start) + if nh_value_end == -1: + raise ValueError + + if has_metric_labels: + labelstext = text[labels_start + 1:labels_end] + labels = parse_labels(labelstext, True) + name_end = labels_start + name = text[:name_end] + if name.endswith(suffixes): + raise ValueError("the sample name of a native histogram with labels should have no suffixes", name) + if not name: + # Name might be in the labels + if '__name__' not in labels: + raise ValueError + name = labels['__name__'] + del labels['__name__'] + # Edge case: the only "label" is the name definition. + if not labels: + labels = None + + nh_value = text[nh_value_start:] + nat_hist_value = _parse_nh_struct(nh_value) + return Sample(name, labels, None, None, None, nat_hist_value) + # check if it's a native histogram + else: + nh_value = text[nh_value_start:] + name_end = nh_value_start - 1 + name = text[:name_end] + if name.endswith(suffixes): + raise ValueError("the sample name of a native histogram should have no suffixes", name) + # Not possible for UTF-8 name here, that would have been caught as having a labelset. + nat_hist_value = _parse_nh_struct(nh_value) + return Sample(name, None, None, None, None, nat_hist_value) + + +def _parse_nh_struct(text): + pattern = r'(\w+):\s*([^,}]+)' + re_spans = re.compile(r'(positive_spans|negative_spans):\[(\d+:\d+(,\d+:\d+)*)\]') + re_deltas = re.compile(r'(positive_deltas|negative_deltas):\[(-?\d+(?:,-?\d+)*)\]') + + items = dict(re.findall(pattern, text)) + span_matches = re_spans.findall(text) + deltas = dict(re_deltas.findall(text)) + + count_value = int(items['count']) + sum_value = int(items['sum']) + schema = int(items['schema']) + zero_threshold = float(items['zero_threshold']) + zero_count = int(items['zero_count']) + + pos_spans = _compose_spans(span_matches, 'positive_spans') + neg_spans = _compose_spans(span_matches, 'negative_spans') + pos_deltas = _compose_deltas(deltas, 'positive_deltas') + neg_deltas = _compose_deltas(deltas, 'negative_deltas') + + return NativeHistogram( + count_value=count_value, + sum_value=sum_value, + schema=schema, + zero_threshold=zero_threshold, + zero_count=zero_count, + pos_spans=pos_spans, + neg_spans=neg_spans, + pos_deltas=pos_deltas, + neg_deltas=neg_deltas + ) + + +def _compose_spans(span_matches, spans_name): + """Takes a list of span matches (expected to be a list of tuples) and a string + (the expected span list name) and processes the list so that the values extracted + from the span matches can be used to compose a tuple of BucketSpan objects""" + spans = {} + for match in span_matches: + # Extract the key from the match (first element of the tuple). + key = match[0] + # Extract the value from the match (second element of the tuple). + # Split the value string by commas to get individual pairs, + # split each pair by ':' to get start and end, and convert them to integers. + value = [tuple(map(int, pair.split(':'))) for pair in match[1].split(',')] + # Store the processed value in the spans dictionary with the key. + spans[key] = value + if spans_name not in spans: + return None + out_spans = [] + # Iterate over each start and end tuple in the list of tuples for the specified spans_name. + for start, end in spans[spans_name]: + # Compose a BucketSpan object with the start and end values + # and append it to the out_spans list. + out_spans.append(BucketSpan(start, end)) + # Convert to tuple + out_spans_tuple = tuple(out_spans) + return out_spans_tuple + + +def _compose_deltas(deltas, deltas_name): + """Takes a list of deltas matches (a dictionary) and a string (the expected delta list name), + and processes its elements to compose a tuple of integers representing the deltas""" + if deltas_name not in deltas: + return None + out_deltas = deltas.get(deltas_name) + if out_deltas is not None and out_deltas.strip(): + elems = out_deltas.split(',') + # Convert each element in the list elems to an integer + # after stripping whitespace and create a tuple from these integers. + out_deltas_tuple = tuple(int(x.strip()) for x in elems) + return out_deltas_tuple + + +def _group_for_sample(sample, name, typ): + if typ == 'info': + # We can't distinguish between groups for info metrics. + return {} + if typ == 'summary' and sample.name == name: + d = sample.labels.copy() + del d['quantile'] + return d + if typ == 'stateset': + d = sample.labels.copy() + del d[name] + return d + if typ in ['histogram', 'gaugehistogram'] and sample.name == name + '_bucket': + d = sample.labels.copy() + del d['le'] + return d + return sample.labels + + +def _check_histogram(samples, name): + group = None + timestamp = None + + def do_checks(): + if bucket != float('+Inf'): + raise ValueError("+Inf bucket missing: " + name) + if count is not None and value != count: + raise ValueError("Count does not match +Inf value: " + name) + if has_sum and count is None: + raise ValueError("_count must be present if _sum is present: " + name) + if has_gsum and count is None: + raise ValueError("_gcount must be present if _gsum is present: " + name) + if not (has_sum or has_gsum) and count is not None: + raise ValueError("_sum/_gsum must be present if _count is present: " + name) + if has_negative_buckets and has_sum: + raise ValueError("Cannot have _sum with negative buckets: " + name) + if not has_negative_buckets and has_negative_gsum: + raise ValueError("Cannot have negative _gsum with non-negative buckets: " + name) + + for s in samples: + suffix = s.name[len(name):] + g = _group_for_sample(s, name, 'histogram') + if len(suffix) == 0: + continue + if g != group or s.timestamp != timestamp: + if group is not None: + do_checks() + count = None + bucket = None + has_negative_buckets = False + has_sum = False + has_gsum = False + has_negative_gsum = False + value = 0 + group = g + timestamp = s.timestamp + + if suffix == '_bucket': + b = float(s.labels['le']) + if b < 0: + has_negative_buckets = True + if bucket is not None and b <= bucket: + raise ValueError("Buckets out of order: " + name) + if s.value < value: + raise ValueError("Bucket values out of order: " + name) + bucket = b + value = s.value + elif suffix in ['_count', '_gcount']: + count = s.value + elif suffix in ['_sum']: + has_sum = True + elif suffix in ['_gsum']: + has_gsum = True + if s.value < 0: + has_negative_gsum = True + + if group is not None: + do_checks() + + +def text_fd_to_metric_families(fd): + """Parse Prometheus text format from a file descriptor. + + This is a laxer parser than the main Go parser, + so successful parsing does not imply that the parsed + text meets the specification. + + Yields Metric's. + """ + name = None + allowed_names = [] + eof = False + + seen_names = set() + type_suffixes = { + 'counter': ['_total', '_created'], + 'summary': ['', '_count', '_sum', '_created'], + 'histogram': ['_count', '_sum', '_bucket', '_created'], + 'gaugehistogram': ['_gcount', '_gsum', '_bucket'], + 'info': ['_info'], + } + + def build_metric(name, documentation, typ, unit, samples): + if typ is None: + typ = 'unknown' + for suffix in set(type_suffixes.get(typ, []) + [""]): + if name + suffix in seen_names: + raise ValueError("Clashing name: " + name + suffix) + seen_names.add(name + suffix) + if documentation is None: + documentation = '' + if unit is None: + unit = '' + if unit and not name.endswith("_" + unit): + raise ValueError("Unit does not match metric name: " + name) + if unit and typ in ['info', 'stateset']: + raise ValueError("Units not allowed for this metric type: " + name) + if typ in ['histogram', 'gaugehistogram']: + _check_histogram(samples, name) + _validate_metric_name(name) + metric = Metric(name, documentation, typ, unit) + # TODO: check labelvalues are valid utf8 + metric.samples = samples + return metric + + is_nh = False + typ = None + for line in fd: + if line[-1] == '\n': + line = line[:-1] + + if eof: + raise ValueError("Received line after # EOF: " + line) + + if not line: + raise ValueError("Received blank line") + + if line == '# EOF': + eof = True + elif line.startswith('#'): + parts = _split_quoted(line, ' ', 3) + if len(parts) < 4: + raise ValueError("Invalid line: " + line) + candidate_name, quoted = _unquote_unescape(parts[2]) + if not quoted and not _is_valid_legacy_metric_name(candidate_name): + raise ValueError + if candidate_name == name and samples: + raise ValueError("Received metadata after samples: " + line) + if candidate_name != name: + if name is not None: + yield build_metric(name, documentation, typ, unit, samples) + # New metric + name = candidate_name + unit = None + typ = None + documentation = None + group = None + seen_groups = set() + group_timestamp = None + group_timestamp_samples = set() + samples = [] + allowed_names = [candidate_name] + + if parts[1] == 'HELP': + if documentation is not None: + raise ValueError("More than one HELP for metric: " + line) + documentation = _unescape_help(parts[3]) + elif parts[1] == 'TYPE': + if typ is not None: + raise ValueError("More than one TYPE for metric: " + line) + typ = parts[3] + if typ == 'untyped': + raise ValueError("Invalid TYPE for metric: " + line) + allowed_names = [name + n for n in type_suffixes.get(typ, [''])] + elif parts[1] == 'UNIT': + if unit is not None: + raise ValueError("More than one UNIT for metric: " + line) + unit = parts[3] + else: + raise ValueError("Invalid line: " + line) + else: + if typ == 'histogram': + # set to true to account for native histograms naming exceptions/sanitizing differences + is_nh = True + sample = _parse_nh_sample(line, tuple(type_suffixes['histogram'])) + # It's not a native histogram + if sample is None: + is_nh = False + sample = _parse_sample(line) + else: + is_nh = False + sample = _parse_sample(line) + if sample.name not in allowed_names and not is_nh: + if name is not None: + yield build_metric(name, documentation, typ, unit, samples) + # Start an unknown metric. + candidate_name, quoted = _unquote_unescape(sample.name) + if not quoted and not _is_valid_legacy_metric_name(candidate_name): + raise ValueError + name = candidate_name + documentation = None + unit = None + typ = 'unknown' + samples = [] + group = None + group_timestamp = None + group_timestamp_samples = set() + seen_groups = set() + allowed_names = [sample.name] + + if typ == 'stateset' and name not in sample.labels: + raise ValueError("Stateset missing label: " + line) + if (name + '_bucket' == sample.name + and (sample.labels.get('le', "NaN") == "NaN" + or _isUncanonicalNumber(sample.labels['le']))): + raise ValueError("Invalid le label: " + line) + if (name + '_bucket' == sample.name + and (not isinstance(sample.value, int) and not sample.value.is_integer())): + raise ValueError("Bucket value must be an integer: " + line) + if ((name + '_count' == sample.name or name + '_gcount' == sample.name) + and (not isinstance(sample.value, int) and not sample.value.is_integer())): + raise ValueError("Count value must be an integer: " + line) + if (typ == 'summary' and name == sample.name + and (not (0 <= float(sample.labels.get('quantile', -1)) <= 1) + or _isUncanonicalNumber(sample.labels['quantile']))): + raise ValueError("Invalid quantile label: " + line) + + if not is_nh: + g = tuple(sorted(_group_for_sample(sample, name, typ).items())) + if group is not None and g != group and g in seen_groups: + raise ValueError("Invalid metric grouping: " + line) + if group is not None and g == group: + if (sample.timestamp is None) != (group_timestamp is None): + raise ValueError("Mix of timestamp presence within a group: " + line) + if group_timestamp is not None and group_timestamp > sample.timestamp and typ != 'info': + raise ValueError("Timestamps went backwards within a group: " + line) + else: + group_timestamp_samples = set() + + series_id = (sample.name, tuple(sorted(sample.labels.items()))) + if sample.timestamp != group_timestamp or series_id not in group_timestamp_samples: + # Not a duplicate due to timestamp truncation. + samples.append(sample) + group_timestamp_samples.add(series_id) + + group = g + group_timestamp = sample.timestamp + seen_groups.add(g) + else: + samples.append(sample) + + if typ == 'stateset' and sample.value not in [0, 1]: + raise ValueError("Stateset samples can only have values zero and one: " + line) + if typ == 'info' and sample.value != 1: + raise ValueError("Info samples can only have value one: " + line) + if typ == 'summary' and name == sample.name and sample.value < 0: + raise ValueError("Quantile values cannot be negative: " + line) + if sample.name[len(name):] in ['_total', '_sum', '_count', '_bucket', '_gcount', '_gsum'] and math.isnan( + sample.value): + raise ValueError("Counter-like samples cannot be NaN: " + line) + if sample.name[len(name):] in ['_total', '_sum', '_count', '_bucket', '_gcount'] and sample.value < 0: + raise ValueError("Counter-like samples cannot be negative: " + line) + if sample.exemplar and not ( + (typ in ['histogram', 'gaugehistogram'] and sample.name.endswith('_bucket')) + or (typ in ['counter'] and sample.name.endswith('_total'))): + raise ValueError("Invalid line only histogram/gaugehistogram buckets and counters can have exemplars: " + line) + + if name is not None: + yield build_metric(name, documentation, typ, unit, samples) + + if not eof: + raise ValueError("Missing # EOF at end") diff --git a/venv/lib/python3.10/site-packages/prometheus_client/parser.py b/venv/lib/python3.10/site-packages/prometheus_client/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..0434edf7d6e2a16afcead14ab799c10a09eb32c4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/parser.py @@ -0,0 +1,367 @@ +import io as StringIO +import re +import string +from typing import Dict, Iterable, List, Match, Optional, TextIO, Tuple + +from .metrics_core import Metric +from .samples import Sample +from .validation import ( + _is_valid_legacy_metric_name, _validate_labelname, _validate_metric_name, +) + + +def text_string_to_metric_families(text: str) -> Iterable[Metric]: + """Parse Prometheus text format from a unicode string. + + See text_fd_to_metric_families. + """ + yield from text_fd_to_metric_families(StringIO.StringIO(text)) + + +ESCAPE_SEQUENCES = { + '\\\\': '\\', + '\\n': '\n', + '\\"': '"', +} + + +def replace_escape_sequence(match: Match[str]) -> str: + return ESCAPE_SEQUENCES[match.group(0)] + + +HELP_ESCAPING_RE = re.compile(r'\\[\\n]') +ESCAPING_RE = re.compile(r'\\[\\n"]') + + +def _replace_help_escaping(s: str) -> str: + return HELP_ESCAPING_RE.sub(replace_escape_sequence, s) + + +def _replace_escaping(s: str) -> str: + return ESCAPING_RE.sub(replace_escape_sequence, s) + + +def _is_character_escaped(s: str, charpos: int) -> bool: + num_bslashes = 0 + while (charpos > num_bslashes + and s[charpos - 1 - num_bslashes] == '\\'): + num_bslashes += 1 + return num_bslashes % 2 == 1 + + +def parse_labels(labels_string: str, openmetrics: bool = False) -> Dict[str, str]: + labels: Dict[str, str] = {} + + # Copy original labels + sub_labels = labels_string.strip() + if openmetrics and sub_labels and sub_labels[0] == ',': + raise ValueError("leading comma: " + labels_string) + try: + # Process one label at a time + while sub_labels: + # The label name is before the equal, or if there's no equal, that's the + # metric name. + + term, sub_labels = _next_term(sub_labels, openmetrics) + if not term: + if openmetrics: + raise ValueError("empty term in line: " + labels_string) + continue + + quoted_name = False + operator_pos = _next_unquoted_char(term, '=') + if operator_pos == -1: + quoted_name = True + label_name = "__name__" + else: + value_start = _next_unquoted_char(term, '=') + label_name, quoted_name = _unquote_unescape(term[:value_start]) + term = term[value_start + 1:] + + if not quoted_name and not _is_valid_legacy_metric_name(label_name): + raise ValueError("unquoted UTF-8 metric name") + + # Check for missing quotes + term = term.strip() + if not term or term[0] != '"': + raise ValueError + + # The first quote is guaranteed to be after the equal. + # Find the last unescaped quote. + i = 1 + while i < len(term): + i = term.index('"', i) + if not _is_character_escaped(term[:i], i): + break + i += 1 + + # The label value is between the first and last quote + quote_end = i + 1 + if quote_end != len(term): + raise ValueError("unexpected text after quote: " + labels_string) + label_value, _ = _unquote_unescape(term[:quote_end]) + if label_name == '__name__': + _validate_metric_name(label_name) + else: + _validate_labelname(label_name) + if label_name in labels: + raise ValueError("invalid line, duplicate label name: " + labels_string) + labels[label_name] = label_value + return labels + except ValueError: + raise ValueError("Invalid labels: " + labels_string) + + +def _next_term(text: str, openmetrics: bool) -> Tuple[str, str]: + """Extract the next comma-separated label term from the text. + + Returns the stripped term and the stripped remainder of the string, + including the comma. + + Raises ValueError if the term is empty and we're in openmetrics mode. + """ + + # There may be a leading comma, which is fine here. + if text[0] == ',': + text = text[1:] + if not text: + return "", "" + if text[0] == ',': + raise ValueError("multiple commas") + splitpos = _next_unquoted_char(text, ',}') + if splitpos == -1: + splitpos = len(text) + term = text[:splitpos] + if not term and openmetrics: + raise ValueError("empty term:", term) + + sublabels = text[splitpos:] + return term.strip(), sublabels.strip() + + +def _next_unquoted_char(text: str, chs: str, startidx: int = 0) -> int: + """Return position of next unquoted character in tuple, or -1 if not found. + + It is always assumed that the first character being checked is not already + inside quotes. + """ + i = startidx + in_quotes = False + if chs is None: + chs = string.whitespace + while i < len(text): + if text[i] == '"' and not _is_character_escaped(text, i): + in_quotes = not in_quotes + if not in_quotes: + if text[i] in chs: + return i + i += 1 + return -1 + + +def _last_unquoted_char(text: str, chs: str) -> int: + """Return position of last unquoted character in list, or -1 if not found.""" + i = len(text) - 1 + in_quotes = False + if chs is None: + chs = string.whitespace + while i > 0: + if text[i] == '"' and not _is_character_escaped(text, i): + in_quotes = not in_quotes + + if not in_quotes: + if text[i] in chs: + return i + i -= 1 + return -1 + + +def _split_quoted(text, separator, maxsplit=0): + """Splits on split_ch similarly to strings.split, skipping separators if + they are inside quotes. + """ + + tokens = [''] + x = 0 + while x < len(text): + split_pos = _next_unquoted_char(text, separator, x) + if split_pos == -1: + tokens[-1] = text[x:] + x = len(text) + continue + if maxsplit > 0 and len(tokens) > maxsplit: + tokens[-1] = text[x:] + break + tokens[-1] = text[x:split_pos] + x = split_pos + 1 + tokens.append('') + return tokens + + +def _unquote_unescape(text): + """Returns the string, and true if it was quoted.""" + if not text: + return text, False + quoted = False + text = text.strip() + if text[0] == '"': + if len(text) == 1 or text[-1] != '"': + raise ValueError("missing close quote") + text = text[1:-1] + quoted = True + if "\\" in text: + text = _replace_escaping(text) + return text, quoted + + +# If we have multiple values only consider the first +def _parse_value_and_timestamp(s: str) -> Tuple[float, Optional[float]]: + s = s.lstrip() + separator = " " + if separator not in s: + separator = "\t" + values = [value.strip() for value in s.split(separator) if value.strip()] + if not values: + return float(s), None + value = _parse_value(values[0]) + timestamp = (_parse_value(values[-1]) / 1000) if len(values) > 1 else None + return value, timestamp + + +def _parse_value(value): + value = ''.join(value) + if value != value.strip() or '_' in value: + raise ValueError(f"Invalid value: {value!r}") + try: + return int(value) + except ValueError: + return float(value) + + +def _parse_sample(text): + separator = " # " + # Detect the labels in the text + label_start = _next_unquoted_char(text, '{') + if label_start == -1 or separator in text[:label_start]: + # We don't have labels, but there could be an exemplar. + name_end = _next_unquoted_char(text, ' \t') + name = text[:name_end].strip() + if not _is_valid_legacy_metric_name(name): + raise ValueError("invalid metric name:" + text) + # Parse the remaining text after the name + remaining_text = text[name_end + 1:] + value, timestamp = _parse_value_and_timestamp(remaining_text) + return Sample(name, {}, value, timestamp) + name = text[:label_start].strip() + label_end = _next_unquoted_char(text, '}') + labels = parse_labels(text[label_start + 1:label_end], False) + if not name: + # Name might be in the labels + if '__name__' not in labels: + raise ValueError + name = labels['__name__'] + del labels['__name__'] + elif '__name__' in labels: + raise ValueError("metric name specified more than once") + # Parsing labels succeeded, continue parsing the remaining text + remaining_text = text[label_end + 1:] + value, timestamp = _parse_value_and_timestamp(remaining_text) + return Sample(name, labels, value, timestamp) + + +def text_fd_to_metric_families(fd: TextIO) -> Iterable[Metric]: + """Parse Prometheus text format from a file descriptor. + + This is a laxer parser than the main Go parser, + so successful parsing does not imply that the parsed + text meets the specification. + + Yields Metric's. + """ + name = '' + documentation = '' + typ = 'untyped' + samples: List[Sample] = [] + allowed_names = [] + + def build_metric(name: str, documentation: str, typ: str, samples: List[Sample]) -> Metric: + # Munge counters into OpenMetrics representation + # used internally. + if typ == 'counter': + if name.endswith('_total'): + name = name[:-6] + else: + new_samples = [] + for s in samples: + new_samples.append(Sample(s[0] + '_total', *s[1:])) + samples = new_samples + metric = Metric(name, documentation, typ) + metric.samples = samples + return metric + + for line in fd: + line = line.strip() + + if line.startswith('#'): + parts = _split_quoted(line, None, 3) + if len(parts) < 2: + continue + candidate_name, quoted = '', False + if len(parts) > 2: + # Ignore comment tokens + if parts[1] != 'TYPE' and parts[1] != 'HELP': + continue + candidate_name, quoted = _unquote_unescape(parts[2]) + if not quoted and not _is_valid_legacy_metric_name(candidate_name): + raise ValueError + if parts[1] == 'HELP': + if candidate_name != name: + if name != '': + yield build_metric(name, documentation, typ, samples) + # New metric + name = candidate_name + typ = 'untyped' + samples = [] + allowed_names = [candidate_name] + if len(parts) == 4: + documentation = _replace_help_escaping(parts[3]) + else: + documentation = '' + elif parts[1] == 'TYPE': + if len(parts) < 4: + raise ValueError + if candidate_name != name: + if name != '': + yield build_metric(name, documentation, typ, samples) + # New metric + name = candidate_name + documentation = '' + samples = [] + typ = parts[3] + allowed_names = { + 'counter': [''], + 'gauge': [''], + 'summary': ['_count', '_sum', ''], + 'histogram': ['_count', '_sum', '_bucket'], + }.get(typ, ['']) + allowed_names = [name + n for n in allowed_names] + elif line == '': + # Ignore blank lines + pass + else: + sample = _parse_sample(line) + if sample.name not in allowed_names: + if name != '': + yield build_metric(name, documentation, typ, samples) + # New metric, yield immediately as untyped singleton + name = '' + documentation = '' + typ = 'untyped' + samples = [] + allowed_names = [] + yield build_metric(sample[0], documentation, typ, [sample]) + else: + samples.append(sample) + + if name != '': + yield build_metric(name, documentation, typ, samples) diff --git a/venv/lib/python3.10/site-packages/prometheus_client/platform_collector.py b/venv/lib/python3.10/site-packages/prometheus_client/platform_collector.py new file mode 100644 index 0000000000000000000000000000000000000000..6040fcce622ad229dafdd00ea2c0692504294041 --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/platform_collector.py @@ -0,0 +1,59 @@ +import platform as pf +from typing import Any, Iterable, Optional + +from .metrics_core import GaugeMetricFamily, Metric +from .registry import Collector, CollectorRegistry, REGISTRY + + +class PlatformCollector(Collector): + """Collector for python platform information""" + + def __init__(self, + registry: Optional[CollectorRegistry] = REGISTRY, + platform: Optional[Any] = None, + ): + self._platform = pf if platform is None else platform + info = self._info() + system = self._platform.system() + if system == "Java": + info.update(self._java()) + self._metrics = [ + self._add_metric("python_info", "Python platform information", info) + ] + if registry: + registry.register(self) + + def collect(self) -> Iterable[Metric]: + return self._metrics + + @staticmethod + def _add_metric(name, documentation, data): + labels = data.keys() + values = [data[k] for k in labels] + g = GaugeMetricFamily(name, documentation, labels=labels) + g.add_metric(values, 1) + return g + + def _info(self): + major, minor, patchlevel = self._platform.python_version_tuple() + return { + "version": self._platform.python_version(), + "implementation": self._platform.python_implementation(), + "major": major, + "minor": minor, + "patchlevel": patchlevel + } + + def _java(self): + java_version, _, vminfo, osinfo = self._platform.java_ver() + vm_name, vm_release, vm_vendor = vminfo + return { + "jvm_version": java_version, + "jvm_release": vm_release, + "jvm_vendor": vm_vendor, + "jvm_name": vm_name + } + + +PLATFORM_COLLECTOR = PlatformCollector() +"""PlatformCollector in default Registry REGISTRY""" diff --git a/venv/lib/python3.10/site-packages/prometheus_client/process_collector.py b/venv/lib/python3.10/site-packages/prometheus_client/process_collector.py new file mode 100644 index 0000000000000000000000000000000000000000..2894e8745020201e9e6e7ffc01466c11b2e096b3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/process_collector.py @@ -0,0 +1,101 @@ +import os +from typing import Callable, Iterable, Optional, Union + +from .metrics_core import CounterMetricFamily, GaugeMetricFamily, Metric +from .registry import Collector, CollectorRegistry, REGISTRY + +try: + import resource + + _PAGESIZE = resource.getpagesize() +except ImportError: + # Not Unix + _PAGESIZE = 4096 + + +class ProcessCollector(Collector): + """Collector for Standard Exports such as cpu and memory.""" + + def __init__(self, + namespace: str = '', + pid: Callable[[], Union[int, str]] = lambda: 'self', + proc: str = '/proc', + registry: Optional[CollectorRegistry] = REGISTRY): + self._namespace = namespace + self._pid = pid + self._proc = proc + if namespace: + self._prefix = namespace + '_process_' + else: + self._prefix = 'process_' + self._ticks = 100.0 + try: + self._ticks = os.sysconf('SC_CLK_TCK') + except (ValueError, TypeError, AttributeError, OSError): + pass + + self._pagesize = _PAGESIZE + + # This is used to test if we can access /proc. + self._btime = 0 + try: + self._btime = self._boot_time() + except OSError: + pass + if registry: + registry.register(self) + + def _boot_time(self): + with open(os.path.join(self._proc, 'stat'), 'rb') as stat: + for line in stat: + if line.startswith(b'btime '): + return float(line.split()[1]) + + def collect(self) -> Iterable[Metric]: + if not self._btime: + return [] + + pid = os.path.join(self._proc, str(self._pid()).strip()) + + result = [] + try: + with open(os.path.join(pid, 'stat'), 'rb') as stat: + parts = (stat.read().split(b')')[-1].split()) + + vmem = GaugeMetricFamily(self._prefix + 'virtual_memory_bytes', + 'Virtual memory size in bytes.', value=float(parts[20])) + rss = GaugeMetricFamily(self._prefix + 'resident_memory_bytes', 'Resident memory size in bytes.', + value=float(parts[21]) * self._pagesize) + start_time_secs = float(parts[19]) / self._ticks + start_time = GaugeMetricFamily(self._prefix + 'start_time_seconds', + 'Start time of the process since unix epoch in seconds.', + value=start_time_secs + self._btime) + utime = float(parts[11]) / self._ticks + stime = float(parts[12]) / self._ticks + cpu = CounterMetricFamily(self._prefix + 'cpu_seconds_total', + 'Total user and system CPU time spent in seconds.', + value=utime + stime) + result.extend([vmem, rss, start_time, cpu]) + except OSError: + pass + + try: + with open(os.path.join(pid, 'limits'), 'rb') as limits: + for line in limits: + if line.startswith(b'Max open file'): + max_fds = GaugeMetricFamily(self._prefix + 'max_fds', + 'Maximum number of open file descriptors.', + value=float(line.split()[3])) + break + open_fds = GaugeMetricFamily(self._prefix + 'open_fds', + 'Number of open file descriptors.', + len(os.listdir(os.path.join(pid, 'fd')))) + result.extend([open_fds, max_fds]) + except OSError: + pass + + return result + + +PROCESS_COLLECTOR = ProcessCollector() +"""Default ProcessCollector in default Registry REGISTRY.""" diff --git a/venv/lib/python3.10/site-packages/prometheus_client/py.typed b/venv/lib/python3.10/site-packages/prometheus_client/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/prometheus_client/registry.py b/venv/lib/python3.10/site-packages/prometheus_client/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..694e4bd87f5fe83cfe4ab380a24b7730adb9285d --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/registry.py @@ -0,0 +1,168 @@ +from abc import ABC, abstractmethod +import copy +from threading import Lock +from typing import Dict, Iterable, List, Optional + +from .metrics_core import Metric + + +# Ideally this would be a Protocol, but Protocols are only available in Python >= 3.8. +class Collector(ABC): + @abstractmethod + def collect(self) -> Iterable[Metric]: + pass + + +class _EmptyCollector(Collector): + def collect(self) -> Iterable[Metric]: + return [] + + +class CollectorRegistry(Collector): + """Metric collector registry. + + Collectors must have a no-argument method 'collect' that returns a list of + Metric objects. The returned metrics should be consistent with the Prometheus + exposition formats. + """ + + def __init__(self, auto_describe: bool = False, target_info: Optional[Dict[str, str]] = None): + self._collector_to_names: Dict[Collector, List[str]] = {} + self._names_to_collectors: Dict[str, Collector] = {} + self._auto_describe = auto_describe + self._lock = Lock() + self._target_info: Optional[Dict[str, str]] = {} + self.set_target_info(target_info) + + def register(self, collector: Collector) -> None: + """Add a collector to the registry.""" + with self._lock: + names = self._get_names(collector) + duplicates = set(self._names_to_collectors).intersection(names) + if duplicates: + raise ValueError( + 'Duplicated timeseries in CollectorRegistry: {}'.format( + duplicates)) + for name in names: + self._names_to_collectors[name] = collector + self._collector_to_names[collector] = names + + def unregister(self, collector: Collector) -> None: + """Remove a collector from the registry.""" + with self._lock: + for name in self._collector_to_names[collector]: + del self._names_to_collectors[name] + del self._collector_to_names[collector] + + def _get_names(self, collector): + """Get names of timeseries the collector produces and clashes with.""" + desc_func = None + # If there's a describe function, use it. + try: + desc_func = collector.describe + except AttributeError: + pass + # Otherwise, if auto describe is enabled use the collect function. + if not desc_func and self._auto_describe: + desc_func = collector.collect + + if not desc_func: + return [] + + result = [] + type_suffixes = { + 'counter': ['_total', '_created'], + 'summary': ['_sum', '_count', '_created'], + 'histogram': ['_bucket', '_sum', '_count', '_created'], + 'gaugehistogram': ['_bucket', '_gsum', '_gcount'], + 'info': ['_info'], + } + for metric in desc_func(): + result.append(metric.name) + for suffix in type_suffixes.get(metric.type, []): + result.append(metric.name + suffix) + return result + + def collect(self) -> Iterable[Metric]: + """Yields metrics from the collectors in the registry.""" + collectors = None + ti = None + with self._lock: + collectors = copy.copy(self._collector_to_names) + if self._target_info: + ti = self._target_info_metric() + if ti: + yield ti + for collector in collectors: + yield from collector.collect() + + def restricted_registry(self, names: Iterable[str]) -> "RestrictedRegistry": + """Returns object that only collects some metrics. + + Returns an object which upon collect() will return + only samples with the given names. + + Intended usage is: + generate_latest(REGISTRY.restricted_registry(['a_timeseries'])) + + Experimental.""" + names = set(names) + return RestrictedRegistry(names, self) + + def set_target_info(self, labels: Optional[Dict[str, str]]) -> None: + with self._lock: + if labels: + if not self._target_info and 'target_info' in self._names_to_collectors: + raise ValueError('CollectorRegistry already contains a target_info metric') + self._names_to_collectors['target_info'] = _EmptyCollector() + elif self._target_info: + self._names_to_collectors.pop('target_info', None) + self._target_info = labels + + def get_target_info(self) -> Optional[Dict[str, str]]: + with self._lock: + return self._target_info + + def _target_info_metric(self): + m = Metric('target', 'Target metadata', 'info') + m.add_sample('target_info', self._target_info, 1) + return m + + def get_sample_value(self, name: str, labels: Optional[Dict[str, str]] = None) -> Optional[float]: + """Returns the sample value, or None if not found. + + This is inefficient, and intended only for use in unittests. + """ + if labels is None: + labels = {} + for metric in self.collect(): + for s in metric.samples: + if s.name == name and s.labels == labels: + return s.value + return None + + +class RestrictedRegistry: + def __init__(self, names: Iterable[str], registry: CollectorRegistry): + self._name_set = set(names) + self._registry = registry + + def collect(self) -> Iterable[Metric]: + collectors = set() + target_info_metric = None + with self._registry._lock: + if 'target_info' in self._name_set and self._registry._target_info: + target_info_metric = self._registry._target_info_metric() + for name in self._name_set: + if name != 'target_info' and name in self._registry._names_to_collectors: + collectors.add(self._registry._names_to_collectors[name]) + if target_info_metric: + yield target_info_metric + for collector in collectors: + for metric in collector.collect(): + m = metric._restricted_metric(self._name_set) + if m: + yield m + + +REGISTRY = CollectorRegistry(auto_describe=True) diff --git a/venv/lib/python3.10/site-packages/prometheus_client/samples.py b/venv/lib/python3.10/site-packages/prometheus_client/samples.py new file mode 100644 index 0000000000000000000000000000000000000000..16e03c0479278b88e08aa75971c4a3d58b931ebc --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/samples.py @@ -0,0 +1,73 @@ +from typing import Dict, NamedTuple, Optional, Sequence, Union + + +class Timestamp: + """A nanosecond-resolution timestamp.""" + + def __init__(self, sec: float, nsec: float) -> None: + if nsec < 0 or nsec >= 1e9: + raise ValueError(f"Invalid value for nanoseconds in Timestamp: {nsec}") + if sec < 0: + nsec = -nsec + self.sec: int = int(sec) + self.nsec: int = int(nsec) + + def __str__(self) -> str: + return f"{self.sec}.{self.nsec:09d}" + + def __repr__(self) -> str: + return f"Timestamp({self.sec}, {self.nsec})" + + def __float__(self) -> float: + return float(self.sec) + float(self.nsec) / 1e9 + + def __eq__(self, other: object) -> bool: + return isinstance(other, Timestamp) and self.sec == other.sec and self.nsec == other.nsec + + def __ne__(self, other: object) -> bool: + return not self == other + + def __gt__(self, other: "Timestamp") -> bool: + return self.nsec > other.nsec if self.sec == other.sec else self.sec > other.sec + + def __lt__(self, other: "Timestamp") -> bool: + return self.nsec < other.nsec if self.sec == other.sec else self.sec < other.sec + + +# BucketSpan is experimental and subject to change at any time. +class BucketSpan(NamedTuple): + offset: int + length: int + + +# NativeHistogram is experimental and subject to change at any time. +class NativeHistogram(NamedTuple): + count_value: float + sum_value: float + schema: int + zero_threshold: float + zero_count: float + pos_spans: Optional[Sequence[BucketSpan]] = None + neg_spans: Optional[Sequence[BucketSpan]] = None + pos_deltas: Optional[Sequence[int]] = None + neg_deltas: Optional[Sequence[int]] = None + + +# Timestamp and exemplar are optional. +# Value can be an int or a float. +# Timestamp can be a float containing a unixtime in seconds, +# a Timestamp object, or None. +# Exemplar can be an Exemplar object, or None. +class Exemplar(NamedTuple): + labels: Dict[str, str] + value: float + timestamp: Optional[Union[float, Timestamp]] = None + + +class Sample(NamedTuple): + name: str + labels: Dict[str, str] + value: float + timestamp: Optional[Union[float, Timestamp]] = None + exemplar: Optional[Exemplar] = None + native_histogram: Optional[NativeHistogram] = None diff --git a/venv/lib/python3.10/site-packages/prometheus_client/twisted/__init__.py b/venv/lib/python3.10/site-packages/prometheus_client/twisted/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..87e0b8a6b90dd3841077ebefb650ad8c0b4ae33a --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/twisted/__init__.py @@ -0,0 +1,3 @@ +from ._exposition import MetricsResource + +__all__ = ['MetricsResource'] diff --git a/venv/lib/python3.10/site-packages/prometheus_client/twisted/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/twisted/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f31804d8a1428e318cbe3f1b24fca6ee98053db6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/twisted/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/twisted/__pycache__/_exposition.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_client/twisted/__pycache__/_exposition.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4929b8667c948dc99b032bdf40eba22dbccc830b Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_client/twisted/__pycache__/_exposition.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/prometheus_client/twisted/_exposition.py b/venv/lib/python3.10/site-packages/prometheus_client/twisted/_exposition.py new file mode 100644 index 0000000000000000000000000000000000000000..202a7d3bbde9325fce3bdc5c143e76cb66359380 --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/twisted/_exposition.py @@ -0,0 +1,8 @@ +from twisted.internet import reactor +from twisted.web.wsgi import WSGIResource + +from .. import exposition, REGISTRY + +MetricsResource = lambda registry=REGISTRY: WSGIResource( + reactor, reactor.getThreadPool(), exposition.make_wsgi_app(registry) +) diff --git a/venv/lib/python3.10/site-packages/prometheus_client/utils.py b/venv/lib/python3.10/site-packages/prometheus_client/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0d2b09487c515e07bde1086b358861eefa2cb187 --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/utils.py @@ -0,0 +1,24 @@ +import math + +INF = float("inf") +MINUS_INF = float("-inf") +NaN = float("NaN") + + +def floatToGoString(d): + d = float(d) + if d == INF: + return '+Inf' + elif d == MINUS_INF: + return '-Inf' + elif math.isnan(d): + return 'NaN' + else: + s = repr(d) + dot = s.find('.') + # Go switches to exponents sooner than Python. + # We only need to care about positive values for le/quantile. + if d > 0 and dot > 6: + mantissa = f'{s[0]}.{s[1:dot]}{s[dot + 1:]}'.rstrip('0.') + return f'{mantissa}e+0{dot - 1}' + return s diff --git a/venv/lib/python3.10/site-packages/prometheus_client/validation.py b/venv/lib/python3.10/site-packages/prometheus_client/validation.py new file mode 100644 index 0000000000000000000000000000000000000000..bf19fc75608066dd3feef2ce0763bbd63742c5ce --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/validation.py @@ -0,0 +1,123 @@ +import os +import re + +METRIC_NAME_RE = re.compile(r'^[a-zA-Z_:][a-zA-Z0-9_:]*$') +METRIC_LABEL_NAME_RE = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$') +RESERVED_METRIC_LABEL_NAME_RE = re.compile(r'^__.*$') + + +def _init_legacy_validation() -> bool: + """Retrieve name validation setting from environment.""" + return os.environ.get("PROMETHEUS_LEGACY_NAME_VALIDATION", 'False').lower() in ('true', '1', 't') + + +_legacy_validation = _init_legacy_validation() + + +def get_legacy_validation() -> bool: + """Return the current status of the legacy validation setting.""" + global _legacy_validation + return _legacy_validation + + +def disable_legacy_validation(): + """Disable legacy name validation, instead allowing all UTF8 characters.""" + global _legacy_validation + _legacy_validation = False + + +def enable_legacy_validation(): + """Enable legacy name validation instead of allowing all UTF8 characters.""" + global _legacy_validation + _legacy_validation = True + + +def _validate_metric_name(name: str) -> None: + """Raises ValueError if the provided name is not a valid metric name. + + This check uses the global legacy validation setting to determine the validation scheme. + """ + if not name: + raise ValueError("metric name cannot be empty") + global _legacy_validation + if _legacy_validation: + if not METRIC_NAME_RE.match(name): + raise ValueError("invalid metric name " + name) + try: + name.encode('utf-8') + except UnicodeDecodeError: + raise ValueError("invalid metric name " + name) + + +def _is_valid_legacy_metric_name(name: str) -> bool: + """Returns true if the provided metric name conforms to the legacy validation scheme.""" + return METRIC_NAME_RE.match(name) is not None + + +def _validate_metric_label_name_token(tok: str) -> None: + """Raises ValueError if a parsed label name token is invalid. + + UTF-8 names must be quoted. + """ + if not tok: + raise ValueError("invalid label name token " + tok) + global _legacy_validation + quoted = tok[0] == '"' and tok[-1] == '"' + if not quoted or _legacy_validation: + if not METRIC_LABEL_NAME_RE.match(tok): + raise ValueError("invalid label name token " + tok) + return + try: + tok.encode('utf-8') + except UnicodeDecodeError: + raise ValueError("invalid label name token " + tok) + + +def _validate_labelname(l): + """Raises ValueError if the provided name is not a valid label name. + + This check uses the global legacy validation setting to determine the validation scheme. + """ + if get_legacy_validation(): + if not METRIC_LABEL_NAME_RE.match(l): + raise ValueError('Invalid label metric name: ' + l) + if RESERVED_METRIC_LABEL_NAME_RE.match(l): + raise ValueError('Reserved label metric name: ' + l) + else: + try: + l.encode('utf-8') + except UnicodeDecodeError: + raise ValueError('Invalid label metric name: ' + l) + if RESERVED_METRIC_LABEL_NAME_RE.match(l): + raise ValueError('Reserved label metric name: ' + l) + + +def _is_valid_legacy_labelname(l: str) -> bool: + """Returns true if the provided label name conforms to the legacy validation scheme.""" + if METRIC_LABEL_NAME_RE.match(l) is None: + return False + return RESERVED_METRIC_LABEL_NAME_RE.match(l) is None + + +def _validate_labelnames(cls, labelnames): + """Raises ValueError if any of the provided names is not a valid label name. + + This check uses the global legacy validation setting to determine the validation scheme. + """ + labelnames = tuple(labelnames) + for l in labelnames: + _validate_labelname(l) + if l in cls._reserved_labelnames: + raise ValueError('Reserved label methe fric name: ' + l) + return labelnames + + +def _validate_exemplar(exemplar): + """Raises ValueError if the exemplar is invalid.""" + runes = 0 + for k, v in exemplar.items(): + _validate_labelname(k) + runes += len(k) + runes += len(v) + if runes > 128: + raise ValueError('Exemplar labels have %d UTF-8 characters, exceeding the limit of 128') diff --git a/venv/lib/python3.10/site-packages/prometheus_client/values.py b/venv/lib/python3.10/site-packages/prometheus_client/values.py new file mode 100644 index 0000000000000000000000000000000000000000..6ff85e3b4c95fa4fdca91f64b3e4bd044d94638a --- /dev/null +++ b/venv/lib/python3.10/site-packages/prometheus_client/values.py @@ -0,0 +1,139 @@ +import os +from threading import Lock +import warnings + +from .mmap_dict import mmap_key, MmapedDict + + +class MutexValue: + """A float protected by a mutex.""" + + _multiprocess = False + + def __init__(self, typ, metric_name, name, labelnames, labelvalues, help_text, **kwargs): + self._value = 0.0 + self._exemplar = None + self._lock = Lock() + + def inc(self, amount): + with self._lock: + self._value += amount + + def set(self, value, timestamp=None): + with self._lock: + self._value = value + + def set_exemplar(self, exemplar): + with self._lock: + self._exemplar = exemplar + + def get(self): + with self._lock: + return self._value + + def get_exemplar(self): + with self._lock: + return self._exemplar + + +def MultiProcessValue(process_identifier=os.getpid): + """Returns a MmapedValue class based on a process_identifier function. + + The 'process_identifier' function MUST comply with this simple rule: + when called in simultaneously running processes it MUST return distinct values. + + Using a different function than the default 'os.getpid' is at your own risk. + """ + files = {} + values = [] + pid = {'value': process_identifier()} + # Use a single global lock when in multi-processing mode + # as we presume this means there is no threading going on. + # This avoids the need to also have mutexes in __MmapDict. + lock = Lock() + + class MmapedValue: + """A float protected by a mutex backed by a per-process mmaped file.""" + + _multiprocess = True + + def __init__(self, typ, metric_name, name, labelnames, labelvalues, help_text, multiprocess_mode='', **kwargs): + self._params = typ, metric_name, name, labelnames, labelvalues, help_text, multiprocess_mode + # This deprecation warning can go away in a few releases when removing the compatibility + if 'prometheus_multiproc_dir' in os.environ and 'PROMETHEUS_MULTIPROC_DIR' not in os.environ: + os.environ['PROMETHEUS_MULTIPROC_DIR'] = os.environ['prometheus_multiproc_dir'] + warnings.warn("prometheus_multiproc_dir variable has been deprecated in favor of the upper case naming PROMETHEUS_MULTIPROC_DIR", DeprecationWarning) + with lock: + self.__check_for_pid_change() + self.__reset() + values.append(self) + + def __reset(self): + typ, metric_name, name, labelnames, labelvalues, help_text, multiprocess_mode = self._params + if typ == 'gauge': + file_prefix = typ + '_' + multiprocess_mode + else: + file_prefix = typ + if file_prefix not in files: + filename = os.path.join( + os.environ.get('PROMETHEUS_MULTIPROC_DIR'), + '{}_{}.db'.format(file_prefix, pid['value'])) + + files[file_prefix] = MmapedDict(filename) + self._file = files[file_prefix] + self._key = mmap_key(metric_name, name, labelnames, labelvalues, help_text) + self._value, self._timestamp = self._file.read_value(self._key) + + def __check_for_pid_change(self): + actual_pid = process_identifier() + if pid['value'] != actual_pid: + pid['value'] = actual_pid + # There has been a fork(), reset all the values. + for f in files.values(): + f.close() + files.clear() + for value in values: + value.__reset() + + def inc(self, amount): + with lock: + self.__check_for_pid_change() + self._value += amount + self._timestamp = 0.0 + self._file.write_value(self._key, self._value, self._timestamp) + + def set(self, value, timestamp=None): + with lock: + self.__check_for_pid_change() + self._value = value + self._timestamp = timestamp or 0.0 + self._file.write_value(self._key, self._value, self._timestamp) + + def set_exemplar(self, exemplar): + # TODO: Implement exemplars for multiprocess mode. + return + + def get(self): + with lock: + self.__check_for_pid_change() + return self._value + + def get_exemplar(self): + # TODO: Implement exemplars for multiprocess mode. + return None + + return MmapedValue + + +def get_value_class(): + # Should we enable multi-process mode? + # This needs to be chosen before the first metric is constructed, + # and as that may be in some arbitrary library the user/admin has + # no control over we use an environment variable. + if 'prometheus_multiproc_dir' in os.environ or 'PROMETHEUS_MULTIPROC_DIR' in os.environ: + return MultiProcessValue() + else: + return MutexValue + + +ValueClass = get_value_class() diff --git a/venv/lib/python3.10/site-packages/pydevd_plugins/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/pydevd_plugins/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0eb803d54635ea8c1934477422c58474bcdb979 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pydevd_plugins/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pydevd_plugins/extensions/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/pydevd_plugins/extensions/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..817d09f2a67df24aa02f73a388cfac7d38388534 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pydevd_plugins/extensions/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pydevd_plugins/extensions/__pycache__/pydevd_plugin_omegaconf.cpython-310.pyc b/venv/lib/python3.10/site-packages/pydevd_plugins/extensions/__pycache__/pydevd_plugin_omegaconf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f09f6125232043b618e62744a0d7e9ed7ca3ff8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pydevd_plugins/extensions/__pycache__/pydevd_plugin_omegaconf.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pydevd_plugins/extensions/pydevd_plugin_omegaconf.py b/venv/lib/python3.10/site-packages/pydevd_plugins/extensions/pydevd_plugin_omegaconf.py new file mode 100644 index 0000000000000000000000000000000000000000..3dc3ce157b5de32df787e4925fd9251a65fa01d2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pydevd_plugins/extensions/pydevd_plugin_omegaconf.py @@ -0,0 +1,126 @@ +# based on https://github.com/fabioz/PyDev.Debugger/tree/main/pydevd_plugins/extensions +import os +import sys +from typing import Any, Dict + +from _pydevd_bundle.pydevd_extension_api import ( # type: ignore + StrPresentationProvider, + TypeResolveProvider, +) + +DEBUG = False + + +def print_debug(msg: str) -> None: # pragma: no cover + if DEBUG: + print(msg) + + +def find_mod_attr(mod_name: str, attr: str) -> Any: + mod = sys.modules.get(mod_name) + return getattr(mod, attr, None) + + +class OmegaConfDeveloperResolver(object): + def can_provide(self, type_object: Any, type_name: str) -> bool: + Node = find_mod_attr("omegaconf", "Node") + return Node is not None and issubclass(type_object, Node) + + def resolve(self, obj: Any, attribute: str) -> Any: + return getattr(obj, attribute) + + def get_dictionary(self, obj: Any) -> Any: + return obj.__dict__ + + +class OmegaConfUserResolver(StrPresentationProvider): # type: ignore + def __init__(self) -> None: + self.Node = find_mod_attr("omegaconf", "Node") + self.ValueNode = find_mod_attr("omegaconf", "ValueNode") + self.ListConfig = find_mod_attr("omegaconf", "ListConfig") + self.DictConfig = find_mod_attr("omegaconf", "DictConfig") + self.InterpolationResolutionError = find_mod_attr( + "omegaconf.errors", "InterpolationResolutionError" + ) + + def can_provide(self, type_object: Any, type_name: str) -> bool: + return self.Node is not None and issubclass(type_object, self.Node) + + def resolve(self, obj: Any, attribute: Any) -> Any: + if isinstance(obj, self.ListConfig) and isinstance(attribute, str): + attribute = int(attribute) + + if isinstance(obj, self.Node): + obj = obj._dereference_node() + + val = obj.__dict__["_content"][attribute] + + print_debug( + f"resolving {obj} ({type(obj).__name__}), {attribute} -> {val} ({type(val).__name__})" + ) + + return val + + def _is_simple_value(self, val: Any) -> bool: + return ( + isinstance(val, self.ValueNode) + and not val._is_none() + and not val._is_missing() + and not val._is_interpolation() + ) + + def get_dictionary(self, obj: Any) -> Dict[str, Any]: + d = self._get_dictionary(obj) + print_debug(f"get_dictionary {obj}, ({type(obj).__name__}) -> {d}") + return d + + def _get_dictionary(self, obj: Any) -> Dict[str, Any]: + if isinstance(obj, self.Node): + obj = obj._maybe_dereference_node() + if obj is None or obj._is_none() or obj._is_missing(): + return {} + + if isinstance(obj, self.DictConfig): + d = {} + for k, v in obj.__dict__["_content"].items(): + if self._is_simple_value(v): + v = v._value() + d[k] = v + elif isinstance(obj, self.ListConfig): + d = {} + for idx, v in enumerate(obj.__dict__["_content"]): + if self._is_simple_value(v): + v = v._value() + d[str(idx)] = v + else: + d = {} + + return d + + def get_str(self, val: Any) -> str: + if val._is_missing(): + return "??? " + if val._is_interpolation(): + try: + dr = val._dereference_node() + except self.InterpolationResolutionError as e: + dr = f"ERR: {e}" + return f"{val._value()} -> {dr}" + else: + return f"{val}" + + +# OC_PYDEVD_RESOLVER env can take: +# DISABLE: Do not install a pydevd resolver +# USER: Install a resolver for OmegaConf users (default) +# DEV: Install a resolver for OmegaConf developers. Shows underlying data-model in the debugger. +resolver = os.environ.get("OC_PYDEVD_RESOLVER", "USER").upper() +if resolver != "DISABLE": # pragma: no cover + if resolver == "USER": + TypeResolveProvider.register(OmegaConfUserResolver) + elif resolver == "DEV": + TypeResolveProvider.register(OmegaConfDeveloperResolver) + else: + sys.stderr.write( + f"OmegaConf pydev plugin: Not installing. Unknown mode {resolver}. Supported one of [USER, DEV, DISABLE]\n" + ) diff --git a/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/LICENSE b/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..90eaf67e3489741ca5d093f43675aae792d0beb0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/LICENSE @@ -0,0 +1,9 @@ +Copyright (c) 2011, Zakaria Zajac and the python-json-logger 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: + +* 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 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/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..3f8fbd88a9b6250f098e63e8ebf79c656cd84fac --- /dev/null +++ b/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/METADATA @@ -0,0 +1,80 @@ +Metadata-Version: 2.2 +Name: python-json-logger +Version: 3.3.0 +Summary: JSON Log Formatter for the Python Logging Package +Author-email: Zakaria Zajac , Nicholas Hairs +Maintainer-email: Nicholas Hairs +License: BSD-2-Clause License +Project-URL: Homepage, https://nhairs.github.io/python-json-logger +Project-URL: GitHub, https://github.com/nhairs/python-json-logger +Classifier: Development Status :: 6 - Mature +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +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: Topic :: System :: Logging +Classifier: Typing :: Typed +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +License-File: LICENSE +License-File: NOTICE +Requires-Dist: typing_extensions; python_version < "3.10" +Provides-Extra: dev +Requires-Dist: orjson; implementation_name != "pypy" and extra == "dev" +Requires-Dist: msgspec; implementation_name != "pypy" and extra == "dev" +Requires-Dist: validate-pyproject[all]; extra == "dev" +Requires-Dist: black; extra == "dev" +Requires-Dist: pylint; extra == "dev" +Requires-Dist: mypy; extra == "dev" +Requires-Dist: pytest; extra == "dev" +Requires-Dist: freezegun; extra == "dev" +Requires-Dist: backports.zoneinfo; python_version < "3.9" and extra == "dev" +Requires-Dist: tzdata; extra == "dev" +Requires-Dist: build; extra == "dev" +Requires-Dist: mkdocs; extra == "dev" +Requires-Dist: mkdocs-material>=8.5; extra == "dev" +Requires-Dist: mkdocs-awesome-pages-plugin; extra == "dev" +Requires-Dist: mdx_truly_sane_lists; extra == "dev" +Requires-Dist: mkdocstrings[python]; extra == "dev" +Requires-Dist: mkdocs-gen-files; extra == "dev" +Requires-Dist: mkdocs-literate-nav; extra == "dev" +Requires-Dist: mike; extra == "dev" + +[![PyPi](https://img.shields.io/pypi/v/python-json-logger.svg)](https://pypi.python.org/pypi/python-json-logger/) +[![PyPI - Status](https://img.shields.io/pypi/status/python-json-logger)](https://pypi.python.org/pypi/python-json-logger/) +[![PyPI - Downloads](https://img.shields.io/pypi/dm/python-json-logger)](https://pypi.python.org/pypi/python-json-logger/) +[![Python Versions](https://img.shields.io/pypi/pyversions/python-json-logger.svg)](https://github.com/nhairs/python-json-logger) +[![License](https://img.shields.io/github/license/nhairs/python-json-logger.svg)](https://github.com/nhairs/python-json-logger) +![Build Status](https://github.com/nhairs/python-json-logger/actions/workflows/test-suite.yml/badge.svg) +# +# Python JSON Logger + +Python JSON Logger enables you produce JSON logs when using Python's `logging` package. + +JSON logs are machine readable allowing for much easier parsing and ingestion into log aggregation tools. + + +## Documentation + +- [Documentation](https://nhairs.github.io/python-json-logger/latest/) +- [Quickstart Guide](https://nhairs.github.io/python-json-logger/latest/quickstart/) +- [Change Log](https://nhairs.github.io/python-json-logger/latest/changelog/) +- [Contributing](https://nhairs.github.io/python-json-logger/latest/contributing/) + +## License + +This project is licensed under the BSD 2 Clause License - see [`LICENSE`](https://github.com/nhairs/python-json-logger/blob/main/LICENSE) + +## Authors and Maintainers + +This project was originally authored by [Zakaria Zajac](https://github.com/madzak) and our wonderful [contributors](https://github.com/nhairs/python-json-logger/graphs/contributors) + +It is currently maintained by: + +- [Nicholas Hairs](https://github.com/nhairs) - [nicholashairs.com](https://www.nicholashairs.com) diff --git a/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/NOTICE b/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..cfa67dd0dee09c81ca76e2a298c99d095af14c77 --- /dev/null +++ b/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/NOTICE @@ -0,0 +1,5 @@ +This software includes the following licenced software: + - mkdocstrings-python + Copyright (c) 2021, Timothée Mazzucotelli + Licenced under ISC Licence + Source: https://github.com/mkdocstrings/python diff --git a/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..3859c7dd7a1f385a1bf9f7853ae11f0e80f18324 --- /dev/null +++ b/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/RECORD @@ -0,0 +1,26 @@ +python_json_logger-3.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +python_json_logger-3.3.0.dist-info/LICENSE,sha256=GOqVF546Xg4k62zhbED7--IxM8JQKTOi91-KPhoFW1Q,1329 +python_json_logger-3.3.0.dist-info/METADATA,sha256=XfdvZal_i2ckXHh-fNw0pcFtVbF2dqvtZjwOkFc_m20,3969 +python_json_logger-3.3.0.dist-info/NOTICE,sha256=uRQnFcGZCwuIBR2AIHVvhKi9w1KkiI_vAyralfxCsk4,209 +python_json_logger-3.3.0.dist-info/RECORD,, +python_json_logger-3.3.0.dist-info/WHEEL,sha256=jB7zZ3N9hIM9adW7qlTAyycLYW9npaWKLRzaoVcLKcM,91 +python_json_logger-3.3.0.dist-info/top_level.txt,sha256=9G-OsTkbwPgM8t-bXKPmWDBRZv9cbzLIiEDE5EnGk2I,17 +pythonjsonlogger/__init__.py,sha256=2QcveuId10CyXff_BtJ_6kXIarHT5oq66XHHMFiaE8s,419 +pythonjsonlogger/__pycache__/__init__.cpython-310.pyc,, +pythonjsonlogger/__pycache__/core.cpython-310.pyc,, +pythonjsonlogger/__pycache__/defaults.cpython-310.pyc,, +pythonjsonlogger/__pycache__/exception.cpython-310.pyc,, +pythonjsonlogger/__pycache__/json.cpython-310.pyc,, +pythonjsonlogger/__pycache__/jsonlogger.cpython-310.pyc,, +pythonjsonlogger/__pycache__/msgspec.cpython-310.pyc,, +pythonjsonlogger/__pycache__/orjson.cpython-310.pyc,, +pythonjsonlogger/__pycache__/utils.cpython-310.pyc,, +pythonjsonlogger/core.py,sha256=pnKRSExv0WHbyNoSXE-JrzhHN3Bp1gctK_oGQSDY__s,14589 +pythonjsonlogger/defaults.py,sha256=-XgxIj8ioq7CsnBBMsQhTRpU-lKbLrpQLJTCaT3iH38,6577 +pythonjsonlogger/exception.py,sha256=r3DXDk7TThscnMVNPpVRaRSFHTnY-ygea6nn-FgjwsI,804 +pythonjsonlogger/json.py,sha256=TsKD_1-TDjaeMUg6la_aVzIWd7GBxgAntY6zWzVe7lU,4165 +pythonjsonlogger/jsonlogger.py,sha256=sfltkYGwRhRvqcpT-kxlPfcMuOc4ngEa4W4NVTiBpMI,417 +pythonjsonlogger/msgspec.py,sha256=M5kiIX4RLr1PwvWKx21N8sgk05LCFymBAWM4cRR3VNA,2161 +pythonjsonlogger/orjson.py,sha256=HVhIHo7CrTwj9pZuZzUmj1qsW0coNdVmDKSDycDs-pM,2357 +pythonjsonlogger/py.typed,sha256=4RLptUHQuSqzK6CDbigff8uvWQjwPPQMxikWPkV4OtA,80 +pythonjsonlogger/utils.py,sha256=qr04nb61TkVw7cJTXAtLBfyH_NBvyYUlR_mehH76-RM,1126 diff --git a/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ec2f44ecd4dd7988bf337cd4fd9d4c64d40c2aa2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.8.2) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..2f881809fa73b749139686496fd6a31b94904cf8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/python_json_logger-3.3.0.dist-info/top_level.txt @@ -0,0 +1 @@ +pythonjsonlogger diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/__init__.py b/venv/lib/python3.10/site-packages/pythonjsonlogger/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..298a3feb0623e8fbf909457116cda9b2e37553d3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pythonjsonlogger/__init__.py @@ -0,0 +1,17 @@ +### IMPORTS +### ============================================================================ +## Future + +## Standard Library +import warnings + +## Installed + +## Application +from . import json +from . import utils + +### CONSTANTS +### ============================================================================ +ORJSON_AVAILABLE = utils.package_is_available("orjson") +MSGSPEC_AVAILABLE = utils.package_is_available("msgspec") diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f648fd61d337310131e5deca824ab641b55c7b60 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/core.cpython-310.pyc b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5dd6f58a98169469c4852639e98c95d8de663ed9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/core.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/defaults.cpython-310.pyc b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/defaults.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c7ceef09248dd0d0f3f5c9d661f54bf7b6b2739 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/defaults.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/exception.cpython-310.pyc b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/exception.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfb74c63738338cd83e8d4ceb7d416bf79ef4dea Binary files /dev/null and b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/exception.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/json.cpython-310.pyc b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/json.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..547eb20496c3daddaa39f792a622115a2471e13c Binary files /dev/null and b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/json.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/jsonlogger.cpython-310.pyc b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/jsonlogger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b8d345bc0a36e18ccfcea3653073d395620162b Binary files /dev/null and b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/jsonlogger.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/msgspec.cpython-310.pyc b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/msgspec.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..164dabe618bdf35c728de1ca640caea5e239a76e Binary files /dev/null and b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/msgspec.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/orjson.cpython-310.pyc b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/orjson.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afe09becd9668b4fce12978ceb04fcccc6dc7c95 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/orjson.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba006271446813d203836d5d34a7bbcd47f050e3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pythonjsonlogger/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/core.py b/venv/lib/python3.10/site-packages/pythonjsonlogger/core.py new file mode 100644 index 0000000000000000000000000000000000000000..1a4dee382b9f37059d32a99004613a2869f64798 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pythonjsonlogger/core.py @@ -0,0 +1,394 @@ +"""Core functionality shared by all JSON loggers""" + +### IMPORTS +### ============================================================================ +## Future +from __future__ import annotations + +## Standard Library +from datetime import datetime, timezone +import importlib +import logging +import re +import sys +from typing import Optional, Union, Callable, List, Dict, Container, Any, Sequence + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +## Installed + +## Application + + +### CONSTANTS +### ============================================================================ +RESERVED_ATTRS: List[str] = [ + "args", + "asctime", + "created", + "exc_info", + "exc_text", + "filename", + "funcName", + "levelname", + "levelno", + "lineno", + "module", + "msecs", + "message", + "msg", + "name", + "pathname", + "process", + "processName", + "relativeCreated", + "stack_info", + "thread", + "threadName", +] +"""Default reserved attributes. + +These come from the [default attributes of `LogRecord` objects](http://docs.python.org/library/logging.html#logrecord-attributes). + +Note: + Although considered a constant, this list is dependent on the Python version due to + different `LogRecord` objects having different attributes in different Python versions. + +*Changed in 3.0*: `RESERVED_ATTRS` is now `list[str]` instead of `tuple[str, ...]`. +""" + +if sys.version_info >= (3, 12): + # taskName added in python 3.12 + RESERVED_ATTRS.append("taskName") + RESERVED_ATTRS.sort() + + +STYLE_STRING_TEMPLATE_REGEX = re.compile(r"\$\{(.+?)\}", re.IGNORECASE) # $ style +STYLE_STRING_FORMAT_REGEX = re.compile(r"\{(.+?)\}", re.IGNORECASE) # { style +STYLE_PERCENT_REGEX = re.compile(r"%\((.+?)\)", re.IGNORECASE) # % style + +## Type Aliases +## ----------------------------------------------------------------------------- +OptionalCallableOrStr: TypeAlias = Optional[Union[Callable, str]] +"""Type alias""" + +LogRecord: TypeAlias = Dict[str, Any] +"""Type alias""" + + +### FUNCTIONS +### ============================================================================ +def str_to_object(obj: Any) -> Any: + """Import strings to an object, leaving non-strings as-is. + + Args: + obj: the object or string to process + + *New in 3.1* + """ + + if not isinstance(obj, str): + return obj + + module_name, attribute_name = obj.rsplit(".", 1) + return getattr(importlib.import_module(module_name), attribute_name) + + +def merge_record_extra( + record: logging.LogRecord, + target: Dict, + reserved: Container[str], + rename_fields: Optional[Dict[str, str]] = None, +) -> Dict: + """ + Merges extra attributes from LogRecord object into target dictionary + + Args: + record: logging.LogRecord + target: dict to update + reserved: dict or list with reserved keys to skip + rename_fields: an optional dict, used to rename field names in the output. + e.g. Rename `levelname` to `log.level`: `{'levelname': 'log.level'}` + + *Changed in 3.1*: `reserved` is now `Container[str]`. + """ + if rename_fields is None: + rename_fields = {} + for key, value in record.__dict__.items(): + # this allows to have numeric keys + if key not in reserved and not (hasattr(key, "startswith") and key.startswith("_")): + target[rename_fields.get(key, key)] = value + return target + + +### CLASSES +### ============================================================================ +class BaseJsonFormatter(logging.Formatter): + """Base class for all formatters + + Must not be used directly. + + *New in 3.1* + + *Changed in 3.2*: `defaults` argument is no longer ignored. + + *Added in UNRELEASED*: `exc_info_as_array` and `stack_info_as_array` options are added. + """ + + _style: Union[logging.PercentStyle, str] # type: ignore[assignment] + + ## Parent Methods + ## ------------------------------------------------------------------------- + # pylint: disable=too-many-arguments,super-init-not-called + def __init__( + self, + fmt: Optional[str] = None, + datefmt: Optional[str] = None, + style: str = "%", + validate: bool = True, + *, + prefix: str = "", + rename_fields: Optional[Dict[str, str]] = None, + rename_fields_keep_missing: bool = False, + static_fields: Optional[Dict[str, Any]] = None, + reserved_attrs: Optional[Sequence[str]] = None, + timestamp: Union[bool, str] = False, + defaults: Optional[Dict[str, Any]] = None, + exc_info_as_array: bool = False, + stack_info_as_array: bool = False, + ) -> None: + """ + Args: + fmt: string representing fields to log + datefmt: format to use when formatting `asctime` field + style: how to extract log fields from `fmt` + validate: validate `fmt` against style, if implementing a custom `style` you + must set this to `False`. + defaults: a dictionary containing default fields that are added before all other fields and + may be overridden. The supplied fields are still subject to `rename_fields`. + prefix: an optional string prefix added at the beginning of + the formatted string + rename_fields: an optional dict, used to rename field names in the output. + Rename `message` to `@message`: `{'message': '@message'}` + rename_fields_keep_missing: When renaming fields, include missing fields in the output. + static_fields: an optional dict, used to add fields with static values to all logs + reserved_attrs: an optional list of fields that will be skipped when + outputting json log record. Defaults to [all log record attributes][pythonjsonlogger.core.RESERVED_ATTRS]. + timestamp: an optional string/boolean field to add a timestamp when + outputting the json log record. If string is passed, timestamp will be added + to log record using string as key. If True boolean is passed, timestamp key + will be "timestamp". Defaults to False/off. + exc_info_as_array: break the exc_info into a list of lines based on line breaks. + stack_info_as_array: break the stack_info into a list of lines based on line breaks. + + *Changed in 3.1*: + + - you can now use custom values for style by setting validate to `False`. + The value is stored in `self._style` as a string. The `parse` method will need to be + overridden in order to support the new style. + - Renaming fields now preserves the order that fields were added in and avoids adding + missing fields. The original behaviour, missing fields have a value of `None`, is still + available by setting `rename_fields_keep_missing` to `True`. + """ + ## logging.Formatter compatibility + ## --------------------------------------------------------------------- + # Note: validate added in 3.8, defaults added in 3.10 + if style in logging._STYLES: + _style = logging._STYLES[style][0](fmt) # type: ignore[operator] + if validate: + _style.validate() + self._style = _style + self._fmt = _style._fmt + + elif not validate: + self._style = style + self._fmt = fmt + + else: + raise ValueError(f"Style must be one of: {','.join(logging._STYLES.keys())}") + + self.datefmt = datefmt + + ## JSON Logging specific + ## --------------------------------------------------------------------- + self.prefix = prefix + self.rename_fields = rename_fields if rename_fields is not None else {} + self.rename_fields_keep_missing = rename_fields_keep_missing + self.static_fields = static_fields if static_fields is not None else {} + self.reserved_attrs = set(reserved_attrs if reserved_attrs is not None else RESERVED_ATTRS) + self.timestamp = timestamp + + self._required_fields = self.parse() + self._skip_fields = set(self._required_fields) + self._skip_fields.update(self.reserved_attrs) + self.defaults = defaults if defaults is not None else {} + self.exc_info_as_array = exc_info_as_array + self.stack_info_as_array = stack_info_as_array + return + + def format(self, record: logging.LogRecord) -> str: + """Formats a log record and serializes to json + + Args: + record: the record to format + """ + message_dict: Dict[str, Any] = {} + # TODO: logging.LogRecord.msg and logging.LogRecord.message in typeshed + # are always type of str. We shouldn't need to override that. + if isinstance(record.msg, dict): + message_dict = record.msg + record.message = "" + else: + record.message = record.getMessage() + + # only format time if needed + if "asctime" in self._required_fields: + record.asctime = self.formatTime(record, self.datefmt) + + # Display formatted exception, but allow overriding it in the + # user-supplied dict. + if record.exc_info and not message_dict.get("exc_info"): + message_dict["exc_info"] = self.formatException(record.exc_info) + if not message_dict.get("exc_info") and record.exc_text: + message_dict["exc_info"] = record.exc_text + + # Display formatted record of stack frames + # default format is a string returned from :func:`traceback.print_stack` + if record.stack_info and not message_dict.get("stack_info"): + message_dict["stack_info"] = self.formatStack(record.stack_info) + + log_record: LogRecord = {} + self.add_fields(log_record, record, message_dict) + log_record = self.process_log_record(log_record) + + return self.serialize_log_record(log_record) + + ## JSON Formatter Specific Methods + ## ------------------------------------------------------------------------- + def parse(self) -> List[str]: + """Parses format string looking for substitutions + + This method is responsible for returning a list of fields (as strings) + to include in all log messages. + + You can support custom styles by overriding this method. + + Returns: + list of fields to be extracted and serialized + """ + if isinstance(self._style, logging.StringTemplateStyle): + formatter_style_pattern = STYLE_STRING_TEMPLATE_REGEX + + elif isinstance(self._style, logging.StrFormatStyle): + formatter_style_pattern = STYLE_STRING_FORMAT_REGEX + + elif isinstance(self._style, logging.PercentStyle): + # PercentStyle is parent class of StringTemplateStyle and StrFormatStyle + # so it must be checked last. + formatter_style_pattern = STYLE_PERCENT_REGEX + + else: + raise ValueError(f"Style {self._style!r} is not supported") + + if self._fmt: + return formatter_style_pattern.findall(self._fmt) + + return [] + + def serialize_log_record(self, log_record: LogRecord) -> str: + """Returns the final representation of the log record. + + Args: + log_record: the log record + """ + return self.prefix + self.jsonify_log_record(log_record) + + def add_fields( + self, + log_record: Dict[str, Any], + record: logging.LogRecord, + message_dict: Dict[str, Any], + ) -> None: + """Extract fields from a LogRecord for logging + + This method can be overridden to implement custom logic for adding fields. + + Args: + log_record: data that will be logged + record: the record to extract data from + message_dict: dictionary that was logged instead of a message. e.g + `logger.info({"is_this_message_dict": True})` + """ + for field in self.defaults: + log_record[self._get_rename(field)] = self.defaults[field] + + for field in self._required_fields: + log_record[self._get_rename(field)] = record.__dict__.get(field) + + for data_dict in [self.static_fields, message_dict]: + for key, value in data_dict.items(): + log_record[self._get_rename(key)] = value + + merge_record_extra( + record, + log_record, + reserved=self._skip_fields, + rename_fields=self.rename_fields, + ) + + if self.timestamp: + key = self.timestamp if isinstance(self.timestamp, str) else "timestamp" + log_record[self._get_rename(key)] = datetime.fromtimestamp( + record.created, tz=timezone.utc + ) + + if self.rename_fields_keep_missing: + for field in self.rename_fields.values(): + if field not in log_record: + log_record[field] = None + return + + def _get_rename(self, key: str) -> str: + return self.rename_fields.get(key, key) + + # Child Methods + # .......................................................................... + def jsonify_log_record(self, log_record: LogRecord) -> str: + """Convert this log record into a JSON string. + + Child classes MUST override this method. + + Args: + log_record: the data to serialize + """ + raise NotImplementedError() + + def process_log_record(self, log_record: LogRecord) -> LogRecord: + """Custom processing of the log record. + + Child classes can override this method to alter the log record before it + is serialized. + + Args: + log_record: incoming data + """ + return log_record + + def formatException(self, ei) -> Union[str, list[str]]: # type: ignore + """Format and return the specified exception information. + + If exc_info_as_array is set to True, This method returns an array of strings. + """ + exception_info_str = super().formatException(ei) + return exception_info_str.splitlines() if self.exc_info_as_array else exception_info_str + + def formatStack(self, stack_info) -> Union[str, list[str]]: # type: ignore + """Format and return the specified stack information. + + If stack_info_as_array is set to True, This method returns an array of strings. + """ + stack_info_str = super().formatStack(stack_info) + return stack_info_str.splitlines() if self.stack_info_as_array else stack_info_str diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/defaults.py b/venv/lib/python3.10/site-packages/pythonjsonlogger/defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..0a002a90fdfe8d77e2a5664cd6bcb7a4ec48c919 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pythonjsonlogger/defaults.py @@ -0,0 +1,241 @@ +"""Collection of functions for building custom `json_default` functions. + +In general functions come in pairs of `use_x_default` and `x_default`, where the former is used +to determine if you should call the latter. + +Most `use_x_default` functions also act as a [`TypeGuard`](https://mypy.readthedocs.io/en/stable/type_narrowing.html#user-defined-type-guards). +""" + +### IMPORTS +### ============================================================================ +## Future +from __future__ import annotations + +## Standard Library +import base64 +import dataclasses +import datetime +import enum +import sys +from types import TracebackType +from typing import Any +import traceback +import uuid + +if sys.version_info >= (3, 10): + from typing import TypeGuard +else: + from typing_extensions import TypeGuard + +## Installed + +## Application + + +### FUNCTIONS +### ============================================================================ +def unknown_default(obj: Any) -> str: + """Backup default function for any object type. + + Will attempt to use `str` or `repr`. If both functions error will return + the string `"__could_not_encode__"`. + + Args: + obj: object to handle + """ + try: + return str(obj) + except Exception: # pylint: disable=broad-exception-caught + pass + try: + return repr(obj) + except Exception: # pylint: disable=broad-exception-caught + pass + return "__could_not_encode__" + + +## Types +## ----------------------------------------------------------------------------- +def use_type_default(obj: Any) -> TypeGuard[type]: + """Default check function for `type` objects (aka classes).""" + return isinstance(obj, type) + + +def type_default(obj: type) -> str: + """Default function for `type` objects. + + Args: + obj: object to handle + """ + return obj.__name__ + + +## Dataclasses +## ----------------------------------------------------------------------------- +def use_dataclass_default(obj: Any) -> bool: + """Default check function for dataclass instances""" + return dataclasses.is_dataclass(obj) and not isinstance(obj, type) + + +def dataclass_default(obj) -> dict[str, Any]: + """Default function for dataclass instances + + Args: + obj: object to handle + """ + return dataclasses.asdict(obj) + + +## Dates and Times +## ----------------------------------------------------------------------------- +def use_time_default(obj: Any) -> TypeGuard[datetime.time]: + """Default check function for `datetime.time` instances""" + return isinstance(obj, datetime.time) + + +def time_default(obj: datetime.time) -> str: + """Default function for `datetime.time` instances + + Args: + obj: object to handle + """ + return obj.isoformat() + + +def use_date_default(obj: Any) -> TypeGuard[datetime.date]: + """Default check function for `datetime.date` instances""" + return isinstance(obj, datetime.date) + + +def date_default(obj: datetime.date) -> str: + """Default function for `datetime.date` instances + + Args: + obj: object to handle + """ + return obj.isoformat() + + +def use_datetime_default(obj: Any) -> TypeGuard[datetime.datetime]: + """Default check function for `datetime.datetime` instances""" + return isinstance(obj, datetime.datetime) + + +def datetime_default(obj: datetime.datetime) -> str: + """Default function for `datetime.datetime` instances + + Args: + obj: object to handle + """ + return obj.isoformat() + + +def use_datetime_any(obj: Any) -> TypeGuard[datetime.time | datetime.date | datetime.datetime]: + """Default check function for `datetime` related instances""" + return isinstance(obj, (datetime.time, datetime.date, datetime.datetime)) + + +def datetime_any(obj: datetime.time | datetime.date | datetime.date) -> str: + """Default function for `datetime` related instances + + Args: + obj: object to handle + """ + return obj.isoformat() + + +## Exception and Tracebacks +## ----------------------------------------------------------------------------- +def use_exception_default(obj: Any) -> TypeGuard[BaseException]: + """Default check function for exception instances. + + Exception classes are not treated specially and should be handled by the + `[use_]type_default` functions. + """ + return isinstance(obj, BaseException) + + +def exception_default(obj: BaseException) -> str: + """Default function for exception instances + + Args: + obj: object to handle + """ + return f"{obj.__class__.__name__}: {obj}" + + +def use_traceback_default(obj: Any) -> TypeGuard[TracebackType]: + """Default check function for tracebacks""" + return isinstance(obj, TracebackType) + + +def traceback_default(obj: TracebackType) -> str: + """Default function for tracebacks + + Args: + obj: object to handle + """ + return "".join(traceback.format_tb(obj)).strip() + + +## Enums +## ----------------------------------------------------------------------------- +def use_enum_default(obj: Any) -> TypeGuard[enum.Enum | enum.EnumMeta]: + """Default check function for enums. + + Supports both enum classes and enum values. + """ + return isinstance(obj, (enum.Enum, enum.EnumMeta)) + + +def enum_default(obj: enum.Enum | enum.EnumMeta) -> Any | list[Any]: + """Default function for enums. + + Supports both enum classes and enum values. + + Args: + obj: object to handle + """ + if isinstance(obj, enum.Enum): + return obj.value + return [e.value for e in obj] # type: ignore[var-annotated] + + +## UUIDs +## ----------------------------------------------------------------------------- +def use_uuid_default(obj: Any) -> TypeGuard[uuid.UUID]: + """Default check function for `uuid.UUID` instances""" + return isinstance(obj, uuid.UUID) + + +def uuid_default(obj: uuid.UUID) -> str: + """Default function for `uuid.UUID` instances + + Formats the UUID using "hyphen" format. + + Args: + obj: object to handle + """ + return str(obj) + + +## Bytes +## ----------------------------------------------------------------------------- +def use_bytes_default(obj: Any) -> TypeGuard[bytes | bytearray]: + """Default check function for bytes""" + return isinstance(obj, (bytes, bytearray)) + + +def bytes_default(obj: bytes | bytearray, url_safe: bool = True) -> str: + """Default function for bytes + + Args: + obj: object to handle + url_safe: use URL safe base 64 character set. + + Returns: + The byte data as a base 64 string. + """ + if url_safe: + return base64.urlsafe_b64encode(obj).decode("utf8") + return base64.b64encode(obj).decode("utf8") diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/exception.py b/venv/lib/python3.10/site-packages/pythonjsonlogger/exception.py new file mode 100644 index 0000000000000000000000000000000000000000..1233f1ab5a6b3021b0f3e5568a4da118b52a74a7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pythonjsonlogger/exception.py @@ -0,0 +1,27 @@ +### IMPORTS +### ============================================================================ +## Future +from __future__ import annotations + +## Standard Library + +## Installed + +## Application + + +### CLASSES +### ============================================================================ +class PythonJsonLoggerError(Exception): + "Generic base clas for all Python JSON Logger exceptions" + + +class MissingPackageError(ImportError, PythonJsonLoggerError): + "A required package is missing" + + def __init__(self, name: str, extras_name: str | None = None) -> None: + msg = f"The {name!r} package is required but could not be found." + if extras_name is not None: + msg += f" It can be installed using 'python-json-logger[{extras_name}]'." + super().__init__(msg) + return diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/json.py b/venv/lib/python3.10/site-packages/pythonjsonlogger/json.py new file mode 100644 index 0000000000000000000000000000000000000000..21e78d0fa92e80a2a6fc35d584045be2cef52435 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pythonjsonlogger/json.py @@ -0,0 +1,119 @@ +"""JSON formatter using the standard library's `json` for encoding. + +Module contains the `JsonFormatter` and a custom `JsonEncoder` which supports a greater +variety of types. +""" + +### IMPORTS +### ============================================================================ +## Future +from __future__ import annotations + +## Standard Library +import datetime +import json +from typing import Any, Callable, Optional, Union +import warnings + +## Application +from . import core +from . import defaults as d + + +### CLASSES +### ============================================================================ +class JsonEncoder(json.JSONEncoder): + """A custom encoder extending [json.JSONEncoder](https://docs.python.org/3/library/json.html#json.JSONEncoder)""" + + def default(self, o: Any) -> Any: + if d.use_datetime_any(o): + return self.format_datetime_obj(o) + + if d.use_exception_default(o): + return d.exception_default(o) + + if d.use_traceback_default(o): + return d.traceback_default(o) + + if d.use_enum_default(o): + return d.enum_default(o) + + if d.use_bytes_default(o): + return d.bytes_default(o) + + if d.use_dataclass_default(o): + return d.dataclass_default(o) + + if d.use_type_default(o): + return d.type_default(o) + + try: + return super().default(o) + except TypeError: + return d.unknown_default(o) + + def format_datetime_obj(self, o: datetime.time | datetime.date | datetime.datetime) -> str: + """Format datetime objects found in `self.default` + + This allows subclasses to change the datetime format without understanding the + internals of the default method. + """ + return d.datetime_any(o) + + +class JsonFormatter(core.BaseJsonFormatter): + """JSON formatter using the standard library's [`json`](https://docs.python.org/3/library/json.html) for encoding""" + + def __init__( + self, + *args, + json_default: core.OptionalCallableOrStr = None, + json_encoder: core.OptionalCallableOrStr = None, + json_serializer: Union[Callable, str] = json.dumps, + json_indent: Optional[Union[int, str]] = None, + json_ensure_ascii: bool = True, + **kwargs, + ) -> None: + """ + Args: + args: see [BaseJsonFormatter][pythonjsonlogger.core.BaseJsonFormatter] + json_default: a function for encoding non-standard objects + json_encoder: custom JSON encoder + json_serializer: a [`json.dumps`](https://docs.python.org/3/library/json.html#json.dumps)-compatible callable + that will be used to serialize the log record. + json_indent: indent parameter for the `json_serializer` + json_ensure_ascii: `ensure_ascii` parameter for the `json_serializer` + kwargs: see [BaseJsonFormatter][pythonjsonlogger.core.BaseJsonFormatter] + """ + super().__init__(*args, **kwargs) + + self.json_default = core.str_to_object(json_default) + self.json_encoder = core.str_to_object(json_encoder) + self.json_serializer = core.str_to_object(json_serializer) + self.json_indent = json_indent + self.json_ensure_ascii = json_ensure_ascii + if not self.json_encoder and not self.json_default: + self.json_encoder = JsonEncoder + return + + def jsonify_log_record(self, log_record: core.LogRecord) -> str: + """Returns a json string of the log record.""" + return self.json_serializer( + log_record, + default=self.json_default, + cls=self.json_encoder, + indent=self.json_indent, + ensure_ascii=self.json_ensure_ascii, + ) + + +### DEPRECATED COMPATIBILITY +### ============================================================================ +def __getattr__(name: str): + if name == "RESERVED_ATTRS": + warnings.warn( + "RESERVED_ATTRS has been moved to pythonjsonlogger.core", + DeprecationWarning, + ) + return core.RESERVED_ATTRS + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/jsonlogger.py b/venv/lib/python3.10/site-packages/pythonjsonlogger/jsonlogger.py new file mode 100644 index 0000000000000000000000000000000000000000..0b283b2dbff4c944c9b5724010b96183471a504a --- /dev/null +++ b/venv/lib/python3.10/site-packages/pythonjsonlogger/jsonlogger.py @@ -0,0 +1,18 @@ +"""Stub module retained for compatibility. + +It retains access to old names whilst sending deprecation warnings. +""" + +# pylint: disable=wrong-import-position,unused-import + +import warnings + +## Throw warning +warnings.warn( + "pythonjsonlogger.jsonlogger has been moved to pythonjsonlogger.json", + DeprecationWarning, +) + +## Import names +from .json import JsonFormatter, JsonEncoder +from .core import RESERVED_ATTRS diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/msgspec.py b/venv/lib/python3.10/site-packages/pythonjsonlogger/msgspec.py new file mode 100644 index 0000000000000000000000000000000000000000..8646f85d772000c71703a314fada486e7026e859 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pythonjsonlogger/msgspec.py @@ -0,0 +1,63 @@ +"""JSON Formatter using [`msgspec`](https://github.com/jcrist/msgspec)""" + +### IMPORTS +### ============================================================================ +## Future +from __future__ import annotations + +## Standard Library +from typing import Any + +## Installed + +## Application +from . import core +from . import defaults as d +from .utils import package_is_available + +# We import msgspec after checking it is available +package_is_available("msgspec", throw_error=True) +import msgspec.json # pylint: disable=wrong-import-position,wrong-import-order + + +### FUNCTIONS +### ============================================================================ +def msgspec_default(obj: Any) -> Any: + """msgspec default encoder function for non-standard types""" + if d.use_exception_default(obj): + return d.exception_default(obj) + if d.use_traceback_default(obj): + return d.traceback_default(obj) + if d.use_enum_default(obj): + return d.enum_default(obj) + if d.use_type_default(obj): + return d.type_default(obj) + return d.unknown_default(obj) + + +### CLASSES +### ============================================================================ +class MsgspecFormatter(core.BaseJsonFormatter): + """JSON formatter using [`msgspec.json.Encoder`](https://jcristharif.com/msgspec/api.html#msgspec.json.Encoder) for encoding.""" + + def __init__( + self, + *args, + json_default: core.OptionalCallableOrStr = msgspec_default, + **kwargs, + ) -> None: + """ + Args: + args: see [BaseJsonFormatter][pythonjsonlogger.core.BaseJsonFormatter] + json_default: a function for encoding non-standard objects + kwargs: see [BaseJsonFormatter][pythonjsonlogger.core.BaseJsonFormatter] + """ + super().__init__(*args, **kwargs) + + self.json_default = core.str_to_object(json_default) + self._encoder = msgspec.json.Encoder(enc_hook=self.json_default) + return + + def jsonify_log_record(self, log_record: core.LogRecord) -> str: + """Returns a json string of the log record.""" + return self._encoder.encode(log_record).decode("utf8") diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/orjson.py b/venv/lib/python3.10/site-packages/pythonjsonlogger/orjson.py new file mode 100644 index 0000000000000000000000000000000000000000..16db8426dfa86fe70040a410088e64cebba475da --- /dev/null +++ b/venv/lib/python3.10/site-packages/pythonjsonlogger/orjson.py @@ -0,0 +1,71 @@ +"""JSON Formatter using [orjson](https://github.com/ijl/orjson)""" + +### IMPORTS +### ============================================================================ +## Future +from __future__ import annotations + +## Standard Library +from typing import Any + +## Installed + +## Application +from . import core +from . import defaults as d +from .utils import package_is_available + +# We import msgspec after checking it is available +package_is_available("orjson", throw_error=True) +import orjson # pylint: disable=wrong-import-position,wrong-import-order + + +### FUNCTIONS +### ============================================================================ +def orjson_default(obj: Any) -> Any: + """orjson default encoder function for non-standard types""" + if d.use_exception_default(obj): + return d.exception_default(obj) + if d.use_traceback_default(obj): + return d.traceback_default(obj) + if d.use_bytes_default(obj): + return d.bytes_default(obj) + if d.use_enum_default(obj): + return d.enum_default(obj) + if d.use_type_default(obj): + return d.type_default(obj) + return d.unknown_default(obj) + + +### CLASSES +### ============================================================================ +class OrjsonFormatter(core.BaseJsonFormatter): + """JSON formatter using [orjson](https://github.com/ijl/orjson) for encoding.""" + + def __init__( + self, + *args, + json_default: core.OptionalCallableOrStr = orjson_default, + json_indent: bool = False, + **kwargs, + ) -> None: + """ + Args: + args: see [BaseJsonFormatter][pythonjsonlogger.core.BaseJsonFormatter] + json_default: a function for encoding non-standard objects + json_indent: indent output with 2 spaces. + kwargs: see [BaseJsonFormatter][pythonjsonlogger.core.BaseJsonFormatter] + """ + super().__init__(*args, **kwargs) + + self.json_default = core.str_to_object(json_default) + self.json_indent = json_indent + return + + def jsonify_log_record(self, log_record: core.LogRecord) -> str: + """Returns a json string of the log record.""" + opt = orjson.OPT_NON_STR_KEYS + if self.json_indent: + opt |= orjson.OPT_INDENT_2 + + return orjson.dumps(log_record, default=self.json_default, option=opt).decode("utf8") diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/py.typed b/venv/lib/python3.10/site-packages/pythonjsonlogger/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..89afa56db54469a094f2314e66df9e4219568623 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pythonjsonlogger/py.typed @@ -0,0 +1 @@ +# PEP-561 marker. https://mypy.readthedocs.io/en/latest/installed_packages.html diff --git a/venv/lib/python3.10/site-packages/pythonjsonlogger/utils.py b/venv/lib/python3.10/site-packages/pythonjsonlogger/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d810a13086ec5b2b36ff8b790ad2afc698dd7783 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pythonjsonlogger/utils.py @@ -0,0 +1,40 @@ +"""Utilities for Python JSON Logger""" + +### IMPORTS +### ============================================================================ +## Future +from __future__ import annotations + +## Standard Library +import importlib.util + +## Installed + +## Application +from .exception import MissingPackageError + + +### FUNCTIONS +### ============================================================================ +def package_is_available( + name: str, *, throw_error: bool = False, extras_name: str | None = None +) -> bool: + """Determine if the given package is available for import. + + Args: + name: Import name of the package to check. + throw_error: Throw an error if the package is unavailable. + extras_name: Extra dependency name to use in `throw_error`'s message. + + Raises: + MissingPackageError: When `throw_error` is `True` and the return value would be `False` + + Returns: + If the package is available for import. + """ + available = importlib.util.find_spec(name) is not None + + if not available and throw_error: + raise MissingPackageError(name, extras_name) + + return available diff --git a/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/LICENSE b/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..bd0f1972f91538217f3cf9f9c7cbac6f70333756 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Christophe Van Gysel + +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. \ No newline at end of file diff --git a/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/METADATA b/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..9747ec5fb03b5ebd0ec00e1857457cd9ac5cd5cf --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/METADATA @@ -0,0 +1,23 @@ +Metadata-Version: 2.1 +Name: pytrec-eval +Version: 0.5 +Summary: Provides Python bindings for popular Information Retrieval measures implemented within trec_eval. +Home-page: https://github.com/cvangysel/pytrec_eval +Author: Christophe Van Gysel +Author-email: cvangysel@uva.nl +License: UNKNOWN +Download-URL: https://github.com/cvangysel/pytrec_eval/tarball/0.5 +Keywords: trec_eval,information retrieval,evaluation,ranking +Platform: UNKNOWN +Classifier: Development Status :: 3 - Alpha +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python +Classifier: Programming Language :: C++ +Classifier: Intended Audience :: Science/Research +Classifier: Operating System :: POSIX :: Linux +Classifier: Topic :: Text Processing :: General +Requires-Python: >=3 +License-File: LICENSE + +UNKNOWN + diff --git a/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/RECORD b/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..810e43e9a27da2f64bc022b3a87ea97eb612b4b2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/RECORD @@ -0,0 +1,10 @@ +pytrec_eval-0.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pytrec_eval-0.5.dist-info/LICENSE,sha256=jul1y04B4xdQkK4TNyS29CzHf05s3YszmoL-YGNT4oE,1086 +pytrec_eval-0.5.dist-info/METADATA,sha256=MB-JpA7_7pvNr5diyiRjj7r3oSGvlJ8ZDU3S7pmM4Xg,811 +pytrec_eval-0.5.dist-info/RECORD,, +pytrec_eval-0.5.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pytrec_eval-0.5.dist-info/WHEEL,sha256=ajFZpXEWjoF3CE-pJ2B52cATZBlVc3sJLvDIL5I6Tak,105 +pytrec_eval-0.5.dist-info/top_level.txt,sha256=A0p5dmQFCEMc4etKus3pSkji8P6X_9NsKAv4TAXy89A,28 +pytrec_eval/__init__.py,sha256=Qido9a2fYTi26KFs0UlqsUqMQPJRnlQFFfaNKPdTcDA,3442 +pytrec_eval/__pycache__/__init__.cpython-310.pyc,, +pytrec_eval_ext.cpython-310-x86_64-linux-gnu.so,sha256=69k4RWPX3g2Fw-tPBp-nGkgeALzhvTxt1qhLpzW-XpQ,909160 diff --git a/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/REQUESTED b/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/WHEEL b/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d277b161656396d81ebf2f7aeb6a42d499cc0b6e --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.45.1) +Root-Is-Purelib: false +Tag: cp310-cp310-linux_x86_64 + diff --git a/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..c08b5cab18097ef7a7f8cbca485b747907314dff --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytrec_eval-0.5.dist-info/top_level.txt @@ -0,0 +1,2 @@ +pytrec_eval +pytrec_eval_ext diff --git a/venv/lib/python3.10/site-packages/pytrec_eval/__init__.py b/venv/lib/python3.10/site-packages/pytrec_eval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b1e2e4adc1171250109d9971c94f37cff078fe7b --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytrec_eval/__init__.py @@ -0,0 +1,104 @@ +"""Module pytrec_eval.""" + +import re +import collections +import numpy as np + +from pytrec_eval_ext import RelevanceEvaluator as _RelevanceEvaluator +from pytrec_eval_ext import supported_measures, supported_nicknames + +__all__ = [ + 'parse_run', + 'parse_qrel', + 'supported_measures', + 'supported_nicknames', + 'RelevanceEvaluator', +] + + +def parse_run(f_run): + run = collections.defaultdict(dict) + + for line in f_run: + query_id, _, object_id, ranking, score, _ = line.strip().split() + + assert object_id not in run[query_id] + run[query_id][object_id] = float(score) + + return run + + +def parse_qrel(f_qrel): + qrel = collections.defaultdict(dict) + + for line in f_qrel: + query_id, _, object_id, relevance = line.strip().split() + + assert object_id not in qrel[query_id] + qrel[query_id][object_id] = int(relevance) + + return qrel + + +def compute_aggregated_measure(measure, values): + if measure.startswith('num_'): + agg_fun = np.sum + elif measure.startswith('gm_'): + def agg_fun(values): + return np.exp(np.sum(values) / len(values)) + else: + agg_fun = np.mean + + return agg_fun(values) + + +class RelevanceEvaluator(_RelevanceEvaluator): + def __init__(self, query_relevance, measures, relevance_level=1): + measures = self._expand_nicknames(measures) + measures = self._combine_measures(measures) + super().__init__(query_relevance=query_relevance, measures=measures, relevance_level=relevance_level) + + def evaluate(self, scores): + if not scores: + return {} + return super().evaluate(scores) + + def _expand_nicknames(self, measures): + # Expand nicknames (e.g., official, all_trec) + result = set() + for measure in measures: + if measure in supported_nicknames: + result.update(supported_nicknames[measure]) + else: + result.add(measure) + return result + + def _combine_measures(self, measures): + RE_BASE = r'{}[\._]([0-9]+(\.[0-9]+)?(,[0-9]+(\.[0-9]+)?)*)' + + # break apart measures in any of the following formats and combine + # 1) meas -> {meas: {}} # either non-parameterized measure or use default params + # 2) meas.p1 -> {meas: {p1}} + # 3) meas_p1 -> {meas: {p1}} + # 4) meas.p1,p2,p3 -> {meas: {p1, p2, p3}} + # 5) meas_p1,p2,p3 -> {meas: {p1, p2, p3}} + param_meas = collections.defaultdict(set) + for measure in measures: + if measure not in supported_measures and measure not in supported_nicknames: + matches = ((m, re.match(RE_BASE.format(re.escape(m)), measure)) for m in supported_measures) + match = next(filter(lambda x: x[1] is not None, matches), None) + if match is None: + raise ValueError('unsupported measure {}'.format(measure)) + base_meas, meas_args = match[0], match[1].group(1) + param_meas[base_meas].update(meas_args.split(',')) + elif measure not in param_meas: + param_meas[measure] = set() + + # re-construct in meas.p1,p2,p3 format for trec_eval + fmt_meas = set() + for meas, meas_args in param_meas.items(): + if meas_args: + meas = '{}.{}'.format(meas, ','.join(sorted(meas_args))) + fmt_meas.add(meas) + + return fmt_meas diff --git a/venv/lib/python3.10/site-packages/pytrec_eval/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytrec_eval/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e85e92ebb05fb7f7f55afbc82d3e4cadf9a479fd Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytrec_eval/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/referencing-0.36.2.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/referencing-0.36.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/referencing-0.36.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/referencing-0.36.2.dist-info/METADATA b/venv/lib/python3.10/site-packages/referencing-0.36.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..78cde34ad1f681da6482410e949c877f2ab71b77 --- /dev/null +++ b/venv/lib/python3.10/site-packages/referencing-0.36.2.dist-info/METADATA @@ -0,0 +1,64 @@ +Metadata-Version: 2.4 +Name: referencing +Version: 0.36.2 +Summary: JSON Referencing + Python +Project-URL: Documentation, https://referencing.readthedocs.io/ +Project-URL: Homepage, https://github.com/python-jsonschema/referencing +Project-URL: Issues, https://github.com/python-jsonschema/referencing/issues/ +Project-URL: Funding, https://github.com/sponsors/Julian +Project-URL: Tidelift, https://tidelift.com/subscription/pkg/pypi-referencing?utm_source=pypi-referencing&utm_medium=referral&utm_campaign=pypi-link +Project-URL: Changelog, https://referencing.readthedocs.io/en/stable/changes/ +Project-URL: Source, https://github.com/python-jsonschema/referencing +Author-email: Julian Berman +License-Expression: MIT +License-File: COPYING +Keywords: asyncapi,json,jsonschema,openapi,referencing +Classifier: Development Status :: 3 - Alpha +Classifier: Intended Audience :: Developers +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 :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: File Formats :: JSON +Classifier: Topic :: File Formats :: JSON :: JSON Schema +Requires-Python: >=3.9 +Requires-Dist: attrs>=22.2.0 +Requires-Dist: rpds-py>=0.7.0 +Requires-Dist: typing-extensions>=4.4.0; python_version < '3.13' +Description-Content-Type: text/x-rst + +=============== +``referencing`` +=============== + +|PyPI| |Pythons| |CI| |ReadTheDocs| |pre-commit| + +.. |PyPI| image:: https://img.shields.io/pypi/v/referencing.svg + :alt: PyPI version + :target: https://pypi.org/project/referencing/ + +.. |Pythons| image:: https://img.shields.io/pypi/pyversions/referencing.svg + :alt: Supported Python versions + :target: https://pypi.org/project/referencing/ + +.. |CI| image:: https://github.com/python-jsonschema/referencing/workflows/CI/badge.svg + :alt: Build status + :target: https://github.com/python-jsonschema/referencing/actions?query=workflow%3ACI + +.. |ReadTheDocs| image:: https://readthedocs.org/projects/referencing/badge/?version=stable&style=flat + :alt: ReadTheDocs status + :target: https://referencing.readthedocs.io/en/stable/ + +.. |pre-commit| image:: https://results.pre-commit.ci/badge/github/python-jsonschema/referencing/main.svg + :alt: pre-commit.ci status + :target: https://results.pre-commit.ci/latest/github/python-jsonschema/referencing/main + + +An implementation-agnostic implementation of JSON reference resolution. + +See `the documentation `_ for more details. diff --git a/venv/lib/python3.10/site-packages/referencing-0.36.2.dist-info/RECORD b/venv/lib/python3.10/site-packages/referencing-0.36.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..b42f48d203a690b6c036d38c8c2288faa81c0f92 --- /dev/null +++ b/venv/lib/python3.10/site-packages/referencing-0.36.2.dist-info/RECORD @@ -0,0 +1,33 @@ +referencing-0.36.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +referencing-0.36.2.dist-info/METADATA,sha256=8eyM93pT0UngPkNw0ZxSgXU8d_JKvDRo0nxhSwW9cgY,2843 +referencing-0.36.2.dist-info/RECORD,, +referencing-0.36.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +referencing-0.36.2.dist-info/licenses/COPYING,sha256=QtzWNJX4e063x3V6-jebtVpT-Ur9el9lfZrfVyNuUVw,1057 +referencing/__init__.py,sha256=5IZKXaAH_FWyCJRkaTn1XcptLfg9cveLb9u5nYUxJKs,207 +referencing/__pycache__/__init__.cpython-310.pyc,, +referencing/__pycache__/_attrs.cpython-310.pyc,, +referencing/__pycache__/_core.cpython-310.pyc,, +referencing/__pycache__/exceptions.cpython-310.pyc,, +referencing/__pycache__/jsonschema.cpython-310.pyc,, +referencing/__pycache__/retrieval.cpython-310.pyc,, +referencing/__pycache__/typing.cpython-310.pyc,, +referencing/_attrs.py,sha256=bgT-KMhDVLeGtWxM_SGKYeLaZBFzT2kUVFdAkOcXi8g,791 +referencing/_attrs.pyi,sha256=J6StMUKqixO4H7Eii9-TXNfCOfS8aHm-1ewimOA-8oo,559 +referencing/_core.py,sha256=0SJfZW68dOrLMaFdhMyuyYzb0Bi9d0BcPjGwijesf9E,24830 +referencing/exceptions.py,sha256=zFgaEg6WiKeT58MQuKNsgGDnHszp26c4oReC6sF9gHM,4176 +referencing/jsonschema.py,sha256=jFURIFOnuxtE4doPL1xSDeuQ4OhdxNzSn8MRRbTeVyk,18628 +referencing/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +referencing/retrieval.py,sha256=QYlOvhiQeDI12XKwezhZ3XOUzqBTFE8b5TpfATamA7I,2697 +referencing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +referencing/tests/__pycache__/__init__.cpython-310.pyc,, +referencing/tests/__pycache__/test_core.cpython-310.pyc,, +referencing/tests/__pycache__/test_exceptions.cpython-310.pyc,, +referencing/tests/__pycache__/test_jsonschema.cpython-310.pyc,, +referencing/tests/__pycache__/test_referencing_suite.cpython-310.pyc,, +referencing/tests/__pycache__/test_retrieval.cpython-310.pyc,, +referencing/tests/test_core.py,sha256=eap0CAaI23vjMIbVyEj92qLddp3iHH3AxC55CKUN4LU,37854 +referencing/tests/test_exceptions.py,sha256=7eOdHyobXMt7-h5AnnH7u8iw2uHPaH7U4Bs9JhLgjWo,934 +referencing/tests/test_jsonschema.py,sha256=4QnjUWOAMAn5yeA8ZtldJkhI54vwKWJWB0LDzNdx5xc,11687 +referencing/tests/test_referencing_suite.py,sha256=wD6veMfLsUu0s4MLjm7pS8cg4cIfL7FMBENngk73zCI,2335 +referencing/tests/test_retrieval.py,sha256=vcbnfA4TqVeqUzW073wO-nLeqVIv0rQZWNWv0z9km48,3719 +referencing/typing.py,sha256=WjUbnZ6jPAd31cnCFAaeWIVENzyHtHdJyOlelv1GY70,1445 diff --git a/venv/lib/python3.10/site-packages/referencing-0.36.2.dist-info/WHEEL b/venv/lib/python3.10/site-packages/referencing-0.36.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/referencing-0.36.2.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/venv/lib/python3.10/site-packages/referencing-0.36.2.dist-info/licenses/COPYING b/venv/lib/python3.10/site-packages/referencing-0.36.2.dist-info/licenses/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..a9f853e43069b8e3f8a156a4af2b1198a004230d --- /dev/null +++ b/venv/lib/python3.10/site-packages/referencing-0.36.2.dist-info/licenses/COPYING @@ -0,0 +1,19 @@ +Copyright (c) 2022 Julian Berman + +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/venv/lib/python3.10/site-packages/rpds/__init__.py b/venv/lib/python3.10/site-packages/rpds/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..257da6a7bd439c46cb2409e77531dc4a4dc6295c --- /dev/null +++ b/venv/lib/python3.10/site-packages/rpds/__init__.py @@ -0,0 +1,5 @@ +from .rpds import * + +__doc__ = rpds.__doc__ +if hasattr(rpds, "__all__"): + __all__ = rpds.__all__ \ No newline at end of file diff --git a/venv/lib/python3.10/site-packages/rpds/__init__.pyi b/venv/lib/python3.10/site-packages/rpds/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5af0e323c1d6d4182d0d373e216a86e520affc87 --- /dev/null +++ b/venv/lib/python3.10/site-packages/rpds/__init__.pyi @@ -0,0 +1,77 @@ +from typing import ( + ItemsView, + Iterable, + Iterator, + KeysView, + Mapping, + TypeVar, + ValuesView, +) + +_T = TypeVar("_T") +_KT_co = TypeVar("_KT_co", covariant=True) +_VT_co = TypeVar("_VT_co", covariant=True) +_KU_co = TypeVar("_KU_co", covariant=True) +_VU_co = TypeVar("_VU_co", covariant=True) + +class HashTrieMap(Mapping[_KT_co, _VT_co]): + def __init__( + self, + value: Mapping[_KT_co, _VT_co] | Iterable[tuple[_KT_co, _VT_co]] = {}, + **kwds: Mapping[_KT_co, _VT_co], + ): ... + def __getitem__(self, key: _KT_co) -> _VT_co: ... + def __iter__(self) -> Iterator[_KT_co]: ... + def __len__(self) -> int: ... + def discard(self, key: _KT_co) -> HashTrieMap[_KT_co, _VT_co]: ... + def items(self) -> ItemsView[_KT_co, _VT_co]: ... + def keys(self) -> KeysView[_KT_co]: ... + def values(self) -> ValuesView[_VT_co]: ... + def remove(self, key: _KT_co) -> HashTrieMap[_KT_co, _VT_co]: ... + def insert( + self, + key: _KT_co, + val: _VT_co, + ) -> HashTrieMap[_KT_co, _VT_co]: ... + def update( + self, + *args: Mapping[_KU_co, _VU_co] | Iterable[tuple[_KU_co, _VU_co]], + ) -> HashTrieMap[_KT_co | _KU_co, _VT_co | _VU_co]: ... + @classmethod + def convert( + cls, + value: Mapping[_KT_co, _VT_co] | Iterable[tuple[_KT_co, _VT_co]], + ) -> HashTrieMap[_KT_co, _VT_co]: ... + @classmethod + def fromkeys( + cls, + keys: Iterable[_KT_co], + value: _VT_co = None, + ) -> HashTrieMap[_KT_co, _VT_co]: ... + +class HashTrieSet(frozenset[_T]): + def __init__(self, value: Iterable[_T] = ()): ... + def __iter__(self) -> Iterator[_T]: ... + def __len__(self) -> int: ... + def discard(self, value: _T) -> HashTrieSet[_T]: ... + def remove(self, value: _T) -> HashTrieSet[_T]: ... + def insert(self, value: _T) -> HashTrieSet[_T]: ... + def update(self, *args: Iterable[_T]) -> HashTrieSet[_T]: ... + +class List(Iterable[_T]): + def __init__(self, value: Iterable[_T] = (), *more: _T): ... + def __iter__(self) -> Iterator[_T]: ... + def __len__(self) -> int: ... + def push_front(self, value: _T) -> List[_T]: ... + def drop_first(self) -> List[_T]: ... + +class Queue(Iterable[_T]): + def __init__(self, value: Iterable[_T] = (), *more: _T): ... + def __iter__(self) -> Iterator[_T]: ... + def __len__(self) -> int: ... + def enqueue(self, value: _T) -> Queue[_T]: ... + def dequeue(self, value: _T) -> Queue[_T]: ... + @property + def is_empty(self) -> _T: ... + @property + def peek(self) -> _T: ... diff --git a/venv/lib/python3.10/site-packages/rpds/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/rpds/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b1a6d51019c064c884bb82f5f365b37e4e11c86 Binary files /dev/null and b/venv/lib/python3.10/site-packages/rpds/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/rpds/py.typed b/venv/lib/python3.10/site-packages/rpds/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/LICENSE b/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..67589cbb8600ecbd6589f3374ccb724320c82617 --- /dev/null +++ b/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/LICENSE @@ -0,0 +1,13 @@ +Copyright 2011 Sybren A. Stüvel + +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 + + https://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. diff --git a/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/METADATA b/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..76959d84154d83f823a4b66b2a21f52e48ec0a6d --- /dev/null +++ b/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/METADATA @@ -0,0 +1,140 @@ +Metadata-Version: 2.3 +Name: rsa +Version: 4.9.1 +Summary: Pure-Python RSA implementation +License: Apache-2.0 +Author: Sybren A. Stüvel +Author-email: sybren@stuvel.eu +Requires-Python: >=3.6,<4 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Information Technology +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +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.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Security :: Cryptography +Requires-Dist: pyasn1 (>=0.1.3) +Project-URL: Homepage, https://stuvel.eu/rsa +Project-URL: Repository, https://github.com/sybrenstuvel/python-rsa +Description-Content-Type: text/markdown + +# Python-RSA has been archived + +Hi folks, + +I'm Sybren, one of the original authors and the maintainer of this project. +Unfortunately I don't have the time and brain space left to properly maintain +Python-RSA. As you can see from the lack of activity on the open issues, and the +lack of commits, that has been the case for a while now. + +As Python-RSA is included as a dependency in quite a few high-profile projects, +I don't feel comfortable handing over the project to someone else. It's just too +big of a risk. + +Thanks for having used this little library for so long, and in so many projects. +I truely didn't expect that when I started working on it. Also big thanks to all +the people helping out and improving the project. + +There are improvements that haven't made it into a new release. As I said, I +don't have the time and the brain space to really investigate and oversee the +security impact of all those changes. It's not a decision I've made lightly. + +So that's it. If you want to keep the project alive, please fork it. Give it the +love it deserves, investigate those yet-unreleased improvements, and have a +project that's then already better than how I left this one. + +Cheers, +Sybren + + +--------------------------------------------- + +# Pure Python RSA implementation + +[![PyPI](https://img.shields.io/pypi/v/rsa.svg)](https://pypi.org/project/rsa/) +[![Build Status](https://travis-ci.org/sybrenstuvel/python-rsa.svg?branch=master)](https://travis-ci.org/sybrenstuvel/python-rsa) +[![Coverage Status](https://coveralls.io/repos/github/sybrenstuvel/python-rsa/badge.svg?branch=master)](https://coveralls.io/github/sybrenstuvel/python-rsa?branch=master) +[![Code Climate](https://api.codeclimate.com/v1/badges/a99a88d28ad37a79dbf6/maintainability)](https://codeclimate.com/github/codeclimate/codeclimate/maintainability) + +[Python-RSA](https://stuvel.eu/rsa) is a pure-Python RSA implementation. It supports +encryption and decryption, signing and verifying signatures, and key +generation according to PKCS#1 version 1.5. It can be used as a Python +library as well as on the commandline. The code was mostly written by +Sybren A. Stüvel. + +Documentation can be found at the [Python-RSA homepage](https://stuvel.eu/rsa). For all changes, check [the changelog](https://github.com/sybrenstuvel/python-rsa/blob/master/CHANGELOG.md). + +Download and install using: + + pip install rsa + +or download it from the [Python Package Index](https://pypi.org/project/rsa/). + +The source code is maintained at [GitHub](https://github.com/sybrenstuvel/python-rsa/) and is +licensed under the [Apache License, version 2.0](https://www.apache.org/licenses/LICENSE-2.0) + +## Security + +Because of how Python internally stores numbers, it is very hard (if not impossible) to make a pure-Python program secure against timing attacks. This library is no exception, so use it with care. See https://securitypitfalls.wordpress.com/2018/08/03/constant-time-compare-in-python/ for more info. + +## Setup of Development Environment + +``` +python3 -m venv .venv +. ./.venv/bin/activate +pip install poetry +poetry install +``` + +## Publishing a New Release + +Since this project is considered critical on the Python Package Index, +two-factor authentication is required. For uploading packages to PyPi, an API +key is required; username+password will not work. + +First, generate an API token at https://pypi.org/manage/account/token/. Then, +use this token when publishing instead of your username and password. + +As username, use `__token__`. +As password, use the token itself, including the `pypi-` prefix. + +See https://pypi.org/help/#apitoken for help using API tokens to publish. This +is what I have in `~/.pypirc`: + +``` +[distutils] +index-servers = + rsa + +# Use `twine upload -r rsa` to upload with this token. +[rsa] + repository = https://upload.pypi.org/legacy/ + username = __token__ + password = pypi-token +``` + +``` +. ./.venv/bin/activate +pip install twine + +poetry build +twine check dist/rsa-4.9.1.tar.gz dist/rsa-4.9.1-*.whl +twine upload -r rsa dist/rsa-4.9.1.tar.gz dist/rsa-4.9.1-*.whl +``` + +The `pip install twine` is necessary as Python-RSA requires Python >= 3.6, and +Twine requires at least version 3.7. This means Poetry refuses to add it as +dependency. + diff --git a/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/RECORD b/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..bfabd03f4b93caa911d10a36b91d20a74e35f7c7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/RECORD @@ -0,0 +1,41 @@ +../../../bin/pyrsa-decrypt,sha256=LceCXy4Jk_sf88XdmdGd1OFkgaduejn85Ip_7ZB0iO8,282 +../../../bin/pyrsa-encrypt,sha256=zUij06pZJv14d-ooxYVKKSR1Yhtv07UV7FCRvfemqT0,282 +../../../bin/pyrsa-keygen,sha256=zPEthtYeTfpQfR8yfTIxvahGPsIFtVSKNRSOjw0e1SM,280 +../../../bin/pyrsa-priv2pub,sha256=IJeok83ZipoDV_-SbGxGvn3ZlEOCay7AdT8_CS_oW7Q,303 +../../../bin/pyrsa-sign,sha256=yN0WAvgF20GTykgpDXndJdbKNr0WVV398sLYdSTKzNc,276 +../../../bin/pyrsa-verify,sha256=-Wob9t3Bjl7lFd92oe6K8unQE9XVb7JKVTgmwMq2cG4,280 +rsa-4.9.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +rsa-4.9.1.dist-info/LICENSE,sha256=Bz8ot9OJyP509gfhfCf4HqpazmntxDqITyP0G0HFxyY,577 +rsa-4.9.1.dist-info/METADATA,sha256=dlNfSHIPYbcprUNaXLdI_h220MlG7Wa5kzbjPjqpd4k,5590 +rsa-4.9.1.dist-info/RECORD,, +rsa-4.9.1.dist-info/WHEEL,sha256=fGIA9gx4Qxk2KDKeNJCbOEwSrmLtjWCwzBz351GyrPQ,88 +rsa-4.9.1.dist-info/entry_points.txt,sha256=p0nVsezmPSjm5x4GDMD4a9Sshc9ukdfw1kkmOmpaAu0,201 +rsa/__init__.py,sha256=F_HYsjAm4fNMky56VN6BraayH4wmWQuhuduc_iJdG1Y,1607 +rsa/__pycache__/__init__.cpython-310.pyc,, +rsa/__pycache__/asn1.cpython-310.pyc,, +rsa/__pycache__/cli.cpython-310.pyc,, +rsa/__pycache__/common.cpython-310.pyc,, +rsa/__pycache__/core.cpython-310.pyc,, +rsa/__pycache__/key.cpython-310.pyc,, +rsa/__pycache__/parallel.cpython-310.pyc,, +rsa/__pycache__/pem.cpython-310.pyc,, +rsa/__pycache__/pkcs1.cpython-310.pyc,, +rsa/__pycache__/pkcs1_v2.cpython-310.pyc,, +rsa/__pycache__/prime.cpython-310.pyc,, +rsa/__pycache__/randnum.cpython-310.pyc,, +rsa/__pycache__/transform.cpython-310.pyc,, +rsa/__pycache__/util.cpython-310.pyc,, +rsa/asn1.py,sha256=fZPoHdVV-8ERZacGM6Wa2pW2l3F31HghGfqT9qIfs9Y,1740 +rsa/cli.py,sha256=K4tCTgNaY1h8H9c9UVRiSgeyvHsyi6Mxkgj8m55bnvI,9862 +rsa/common.py,sha256=w0UuV5HNvkFC4sBMjMDO8JTUJCoXvsLzcoJrAuqzLpA,4679 +rsa/core.py,sha256=yAj0Lg2G0HNxsa6xHMI-RF-OcIlE7GHzoBgWO7_2z5g,1661 +rsa/key.py,sha256=MgSlCEeWnEROLrr_FDCSqvC-_CbWbdjlkcO4kgh4sjw,27427 +rsa/parallel.py,sha256=lp8ln5nEw5mWbBr9yoegvHEcawbR96GVkgCKjwPHYbk,2309 +rsa/pem.py,sha256=7eZt4U9im0hLuCMQOAMaPHi2FexxQ-a7FVXyzbJS_HM,3989 +rsa/pkcs1.py,sha256=iRUFVeMf_5QwZHP_CudyMaDbD-RhzDKwjgoisMOnsbE,16205 +rsa/pkcs1_v2.py,sha256=pY22h-EJHV7jaeeNjqjlen0CbMgl-UP7d9CsQceHpek,3449 +rsa/prime.py,sha256=OFpVIF3JjXzeMWdYeGEnXt1Fy3cYnHQystcltgpfoR0,5106 +rsa/py.typed,sha256=bzd2a8c8TpHiUMxJz1pUd7d9LKFo71w1NxpG1fR73JA,63 +rsa/randnum.py,sha256=23l2gOUY9Vv9f67md_16tANrbBDpUP7dW1EuDdEklUs,2657 +rsa/transform.py,sha256=n44DPrO1CZLgKXYtJkTkvhwyFTcIt1hrbD_jM0KRBu0,2200 +rsa/util.py,sha256=DC27D6LR5E9pOPvxMwlTA1Y46Irx30Yh5gW3tCyp43E,2993 diff --git a/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/WHEEL b/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..5b4f9fcb0f00b8a9bd531ba1586141e1dcfd2786 --- /dev/null +++ b/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: poetry-core 2.1.2 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/entry_points.txt b/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..bf058e3ebda1b5bda76eefdf3e7c188ae20bb911 --- /dev/null +++ b/venv/lib/python3.10/site-packages/rsa-4.9.1.dist-info/entry_points.txt @@ -0,0 +1,8 @@ +[console_scripts] +pyrsa-decrypt=rsa.cli:decrypt +pyrsa-encrypt=rsa.cli:encrypt +pyrsa-keygen=rsa.cli:keygen +pyrsa-priv2pub=rsa.util:private_to_public +pyrsa-sign=rsa.cli:sign +pyrsa-verify=rsa.cli:verify + diff --git a/venv/lib/python3.10/site-packages/s3transfer/__init__.py b/venv/lib/python3.10/site-packages/s3transfer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..19ef3a6feff71d9964fcec34832f6c4ba072d7c2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/__init__.py @@ -0,0 +1,877 @@ +# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +"""Abstractions over S3's upload/download operations. + +This module provides high level abstractions for efficient +uploads/downloads. It handles several things for the user: + +* Automatically switching to multipart transfers when + a file is over a specific size threshold +* Uploading/downloading a file in parallel +* Throttling based on max bandwidth +* Progress callbacks to monitor transfers +* Retries. While botocore handles retries for streaming uploads, + it is not possible for it to handle retries for streaming + downloads. This module handles retries for both cases so + you don't need to implement any retry logic yourself. + +This module has a reasonable set of defaults. It also allows you +to configure many aspects of the transfer process including: + +* Multipart threshold size +* Max parallel downloads +* Max bandwidth +* Socket timeouts +* Retry amounts + +There is no support for s3->s3 multipart copies at this +time. + + +.. _ref_s3transfer_usage: + +Usage +===== + +The simplest way to use this module is: + +.. code-block:: python + + client = boto3.client('s3', 'us-west-2') + transfer = S3Transfer(client) + # Upload /tmp/myfile to s3://bucket/key + transfer.upload_file('/tmp/myfile', 'bucket', 'key') + + # Download s3://bucket/key to /tmp/myfile + transfer.download_file('bucket', 'key', '/tmp/myfile') + +The ``upload_file`` and ``download_file`` methods also accept +``**kwargs``, which will be forwarded through to the corresponding +client operation. Here are a few examples using ``upload_file``:: + + # Making the object public + transfer.upload_file('/tmp/myfile', 'bucket', 'key', + extra_args={'ACL': 'public-read'}) + + # Setting metadata + transfer.upload_file('/tmp/myfile', 'bucket', 'key', + extra_args={'Metadata': {'a': 'b', 'c': 'd'}}) + + # Setting content type + transfer.upload_file('/tmp/myfile.json', 'bucket', 'key', + extra_args={'ContentType': "application/json"}) + + +The ``S3Transfer`` class also supports progress callbacks so you can +provide transfer progress to users. Both the ``upload_file`` and +``download_file`` methods take an optional ``callback`` parameter. +Here's an example of how to print a simple progress percentage +to the user: + +.. code-block:: python + + class ProgressPercentage(object): + def __init__(self, filename): + self._filename = filename + self._size = float(os.path.getsize(filename)) + self._seen_so_far = 0 + self._lock = threading.Lock() + + def __call__(self, bytes_amount): + # To simplify we'll assume this is hooked up + # to a single filename. + with self._lock: + self._seen_so_far += bytes_amount + percentage = (self._seen_so_far / self._size) * 100 + sys.stdout.write( + "\r%s %s / %s (%.2f%%)" % (self._filename, self._seen_so_far, + self._size, percentage)) + sys.stdout.flush() + + + transfer = S3Transfer(boto3.client('s3', 'us-west-2')) + # Upload /tmp/myfile to s3://bucket/key and print upload progress. + transfer.upload_file('/tmp/myfile', 'bucket', 'key', + callback=ProgressPercentage('/tmp/myfile')) + + + +You can also provide a TransferConfig object to the S3Transfer +object that gives you more fine grained control over the +transfer. For example: + +.. code-block:: python + + client = boto3.client('s3', 'us-west-2') + config = TransferConfig( + multipart_threshold=8 * 1024 * 1024, + max_concurrency=10, + num_download_attempts=10, + ) + transfer = S3Transfer(client, config) + transfer.upload_file('/tmp/foo', 'bucket', 'key') + + +""" + +import concurrent.futures +import functools +import logging +import math +import os +import queue +import random +import socket +import string +import threading + +from botocore.compat import six # noqa: F401 +from botocore.exceptions import IncompleteReadError, ResponseStreamingError +from botocore.vendored.requests.packages.urllib3.exceptions import ( + ReadTimeoutError, +) + +import s3transfer.compat +from s3transfer.exceptions import RetriesExceededError, S3UploadFailedError + +__author__ = 'Amazon Web Services' +__version__ = '0.10.4' + + +class NullHandler(logging.Handler): + def emit(self, record): + pass + + +logger = logging.getLogger(__name__) +logger.addHandler(NullHandler()) + +MB = 1024 * 1024 +SHUTDOWN_SENTINEL = object() + + +def random_file_extension(num_digits=8): + return ''.join(random.choice(string.hexdigits) for _ in range(num_digits)) + + +def disable_upload_callbacks(request, operation_name, **kwargs): + if operation_name in ['PutObject', 'UploadPart'] and hasattr( + request.body, 'disable_callback' + ): + request.body.disable_callback() + + +def enable_upload_callbacks(request, operation_name, **kwargs): + if operation_name in ['PutObject', 'UploadPart'] and hasattr( + request.body, 'enable_callback' + ): + request.body.enable_callback() + + +class QueueShutdownError(Exception): + pass + + +class ReadFileChunk: + def __init__( + self, + fileobj, + start_byte, + chunk_size, + full_file_size, + callback=None, + enable_callback=True, + ): + """ + + Given a file object shown below: + + |___________________________________________________| + 0 | | full_file_size + |----chunk_size---| + start_byte + + :type fileobj: file + :param fileobj: File like object + + :type start_byte: int + :param start_byte: The first byte from which to start reading. + + :type chunk_size: int + :param chunk_size: The max chunk size to read. Trying to read + pass the end of the chunk size will behave like you've + reached the end of the file. + + :type full_file_size: int + :param full_file_size: The entire content length associated + with ``fileobj``. + + :type callback: function(amount_read) + :param callback: Called whenever data is read from this object. + + """ + self._fileobj = fileobj + self._start_byte = start_byte + self._size = self._calculate_file_size( + self._fileobj, + requested_size=chunk_size, + start_byte=start_byte, + actual_file_size=full_file_size, + ) + self._fileobj.seek(self._start_byte) + self._amount_read = 0 + self._callback = callback + self._callback_enabled = enable_callback + + @classmethod + def from_filename( + cls, + filename, + start_byte, + chunk_size, + callback=None, + enable_callback=True, + ): + """Convenience factory function to create from a filename. + + :type start_byte: int + :param start_byte: The first byte from which to start reading. + + :type chunk_size: int + :param chunk_size: The max chunk size to read. Trying to read + pass the end of the chunk size will behave like you've + reached the end of the file. + + :type full_file_size: int + :param full_file_size: The entire content length associated + with ``fileobj``. + + :type callback: function(amount_read) + :param callback: Called whenever data is read from this object. + + :type enable_callback: bool + :param enable_callback: Indicate whether to invoke callback + during read() calls. + + :rtype: ``ReadFileChunk`` + :return: A new instance of ``ReadFileChunk`` + + """ + f = open(filename, 'rb') + file_size = os.fstat(f.fileno()).st_size + return cls( + f, start_byte, chunk_size, file_size, callback, enable_callback + ) + + def _calculate_file_size( + self, fileobj, requested_size, start_byte, actual_file_size + ): + max_chunk_size = actual_file_size - start_byte + return min(max_chunk_size, requested_size) + + def read(self, amount=None): + if amount is None: + amount_to_read = self._size - self._amount_read + else: + amount_to_read = min(self._size - self._amount_read, amount) + data = self._fileobj.read(amount_to_read) + self._amount_read += len(data) + if self._callback is not None and self._callback_enabled: + self._callback(len(data)) + return data + + def enable_callback(self): + self._callback_enabled = True + + def disable_callback(self): + self._callback_enabled = False + + def seek(self, where): + self._fileobj.seek(self._start_byte + where) + if self._callback is not None and self._callback_enabled: + # To also rewind the callback() for an accurate progress report + self._callback(where - self._amount_read) + self._amount_read = where + + def close(self): + self._fileobj.close() + + def tell(self): + return self._amount_read + + def __len__(self): + # __len__ is defined because requests will try to determine the length + # of the stream to set a content length. In the normal case + # of the file it will just stat the file, but we need to change that + # behavior. By providing a __len__, requests will use that instead + # of stat'ing the file. + return self._size + + def __enter__(self): + return self + + def __exit__(self, *args, **kwargs): + self.close() + + def __iter__(self): + # This is a workaround for http://bugs.python.org/issue17575 + # Basically httplib will try to iterate over the contents, even + # if its a file like object. This wasn't noticed because we've + # already exhausted the stream so iterating over the file immediately + # stops, which is what we're simulating here. + return iter([]) + + +class StreamReaderProgress: + """Wrapper for a read only stream that adds progress callbacks.""" + + def __init__(self, stream, callback=None): + self._stream = stream + self._callback = callback + + def read(self, *args, **kwargs): + value = self._stream.read(*args, **kwargs) + if self._callback is not None: + self._callback(len(value)) + return value + + +class OSUtils: + def get_file_size(self, filename): + return os.path.getsize(filename) + + def open_file_chunk_reader(self, filename, start_byte, size, callback): + return ReadFileChunk.from_filename( + filename, start_byte, size, callback, enable_callback=False + ) + + def open(self, filename, mode): + return open(filename, mode) + + def remove_file(self, filename): + """Remove a file, noop if file does not exist.""" + # Unlike os.remove, if the file does not exist, + # then this method does nothing. + try: + os.remove(filename) + except OSError: + pass + + def rename_file(self, current_filename, new_filename): + s3transfer.compat.rename_file(current_filename, new_filename) + + +class MultipartUploader: + # These are the extra_args that need to be forwarded onto + # subsequent upload_parts. + UPLOAD_PART_ARGS = [ + 'SSECustomerKey', + 'SSECustomerAlgorithm', + 'SSECustomerKeyMD5', + 'RequestPayer', + ] + + def __init__( + self, + client, + config, + osutil, + executor_cls=concurrent.futures.ThreadPoolExecutor, + ): + self._client = client + self._config = config + self._os = osutil + self._executor_cls = executor_cls + + def _extra_upload_part_args(self, extra_args): + # Only the args in UPLOAD_PART_ARGS actually need to be passed + # onto the upload_part calls. + upload_parts_args = {} + for key, value in extra_args.items(): + if key in self.UPLOAD_PART_ARGS: + upload_parts_args[key] = value + return upload_parts_args + + def upload_file(self, filename, bucket, key, callback, extra_args): + response = self._client.create_multipart_upload( + Bucket=bucket, Key=key, **extra_args + ) + upload_id = response['UploadId'] + try: + parts = self._upload_parts( + upload_id, filename, bucket, key, callback, extra_args + ) + except Exception as e: + logger.debug( + "Exception raised while uploading parts, " + "aborting multipart upload.", + exc_info=True, + ) + self._client.abort_multipart_upload( + Bucket=bucket, Key=key, UploadId=upload_id + ) + raise S3UploadFailedError( + "Failed to upload {} to {}: {}".format( + filename, '/'.join([bucket, key]), e + ) + ) + self._client.complete_multipart_upload( + Bucket=bucket, + Key=key, + UploadId=upload_id, + MultipartUpload={'Parts': parts}, + ) + + def _upload_parts( + self, upload_id, filename, bucket, key, callback, extra_args + ): + upload_parts_extra_args = self._extra_upload_part_args(extra_args) + parts = [] + part_size = self._config.multipart_chunksize + num_parts = int( + math.ceil(self._os.get_file_size(filename) / float(part_size)) + ) + max_workers = self._config.max_concurrency + with self._executor_cls(max_workers=max_workers) as executor: + upload_partial = functools.partial( + self._upload_one_part, + filename, + bucket, + key, + upload_id, + part_size, + upload_parts_extra_args, + callback, + ) + for part in executor.map(upload_partial, range(1, num_parts + 1)): + parts.append(part) + return parts + + def _upload_one_part( + self, + filename, + bucket, + key, + upload_id, + part_size, + extra_args, + callback, + part_number, + ): + open_chunk_reader = self._os.open_file_chunk_reader + with open_chunk_reader( + filename, part_size * (part_number - 1), part_size, callback + ) as body: + response = self._client.upload_part( + Bucket=bucket, + Key=key, + UploadId=upload_id, + PartNumber=part_number, + Body=body, + **extra_args, + ) + etag = response['ETag'] + return {'ETag': etag, 'PartNumber': part_number} + + +class ShutdownQueue(queue.Queue): + """A queue implementation that can be shutdown. + + Shutting down a queue means that this class adds a + trigger_shutdown method that will trigger all subsequent + calls to put() to fail with a ``QueueShutdownError``. + + It purposefully deviates from queue.Queue, and is *not* meant + to be a drop in replacement for ``queue.Queue``. + + """ + + def _init(self, maxsize): + self._shutdown = False + self._shutdown_lock = threading.Lock() + # queue.Queue is an old style class so we don't use super(). + return queue.Queue._init(self, maxsize) + + def trigger_shutdown(self): + with self._shutdown_lock: + self._shutdown = True + logger.debug("The IO queue is now shutdown.") + + def put(self, item): + # Note: this is not sufficient, it's still possible to deadlock! + # Need to hook into the condition vars used by this class. + with self._shutdown_lock: + if self._shutdown: + raise QueueShutdownError( + "Cannot put item to queue when " "queue has been shutdown." + ) + return queue.Queue.put(self, item) + + +class MultipartDownloader: + def __init__( + self, + client, + config, + osutil, + executor_cls=concurrent.futures.ThreadPoolExecutor, + ): + self._client = client + self._config = config + self._os = osutil + self._executor_cls = executor_cls + self._ioqueue = ShutdownQueue(self._config.max_io_queue) + + def download_file( + self, bucket, key, filename, object_size, extra_args, callback=None + ): + with self._executor_cls(max_workers=2) as controller: + # 1 thread for the future that manages the uploading of files + # 1 thread for the future that manages IO writes. + download_parts_handler = functools.partial( + self._download_file_as_future, + bucket, + key, + filename, + object_size, + callback, + ) + parts_future = controller.submit(download_parts_handler) + + io_writes_handler = functools.partial( + self._perform_io_writes, filename + ) + io_future = controller.submit(io_writes_handler) + results = concurrent.futures.wait( + [parts_future, io_future], + return_when=concurrent.futures.FIRST_EXCEPTION, + ) + self._process_future_results(results) + + def _process_future_results(self, futures): + finished, unfinished = futures + for future in finished: + future.result() + + def _download_file_as_future( + self, bucket, key, filename, object_size, callback + ): + part_size = self._config.multipart_chunksize + num_parts = int(math.ceil(object_size / float(part_size))) + max_workers = self._config.max_concurrency + download_partial = functools.partial( + self._download_range, + bucket, + key, + filename, + part_size, + num_parts, + callback, + ) + try: + with self._executor_cls(max_workers=max_workers) as executor: + list(executor.map(download_partial, range(num_parts))) + finally: + self._ioqueue.put(SHUTDOWN_SENTINEL) + + def _calculate_range_param(self, part_size, part_index, num_parts): + start_range = part_index * part_size + if part_index == num_parts - 1: + end_range = '' + else: + end_range = start_range + part_size - 1 + range_param = f'bytes={start_range}-{end_range}' + return range_param + + def _download_range( + self, bucket, key, filename, part_size, num_parts, callback, part_index + ): + try: + range_param = self._calculate_range_param( + part_size, part_index, num_parts + ) + + max_attempts = self._config.num_download_attempts + last_exception = None + for i in range(max_attempts): + try: + logger.debug("Making get_object call.") + response = self._client.get_object( + Bucket=bucket, Key=key, Range=range_param + ) + streaming_body = StreamReaderProgress( + response['Body'], callback + ) + buffer_size = 1024 * 16 + current_index = part_size * part_index + for chunk in iter( + lambda: streaming_body.read(buffer_size), b'' + ): + self._ioqueue.put((current_index, chunk)) + current_index += len(chunk) + return + except ( + socket.timeout, + OSError, + ReadTimeoutError, + IncompleteReadError, + ResponseStreamingError, + ) as e: + logger.debug( + "Retrying exception caught (%s), " + "retrying request, (attempt %s / %s)", + e, + i, + max_attempts, + exc_info=True, + ) + last_exception = e + continue + raise RetriesExceededError(last_exception) + finally: + logger.debug("EXITING _download_range for part: %s", part_index) + + def _perform_io_writes(self, filename): + with self._os.open(filename, 'wb') as f: + while True: + task = self._ioqueue.get() + if task is SHUTDOWN_SENTINEL: + logger.debug( + "Shutdown sentinel received in IO handler, " + "shutting down IO handler." + ) + return + else: + try: + offset, data = task + f.seek(offset) + f.write(data) + except Exception as e: + logger.debug( + "Caught exception in IO thread: %s", + e, + exc_info=True, + ) + self._ioqueue.trigger_shutdown() + raise + + +class TransferConfig: + def __init__( + self, + multipart_threshold=8 * MB, + max_concurrency=10, + multipart_chunksize=8 * MB, + num_download_attempts=5, + max_io_queue=100, + ): + self.multipart_threshold = multipart_threshold + self.max_concurrency = max_concurrency + self.multipart_chunksize = multipart_chunksize + self.num_download_attempts = num_download_attempts + self.max_io_queue = max_io_queue + + +class S3Transfer: + ALLOWED_DOWNLOAD_ARGS = [ + 'VersionId', + 'SSECustomerAlgorithm', + 'SSECustomerKey', + 'SSECustomerKeyMD5', + 'RequestPayer', + ] + + ALLOWED_UPLOAD_ARGS = [ + 'ACL', + 'CacheControl', + 'ContentDisposition', + 'ContentEncoding', + 'ContentLanguage', + 'ContentType', + 'Expires', + 'GrantFullControl', + 'GrantRead', + 'GrantReadACP', + 'GrantWriteACL', + 'Metadata', + 'RequestPayer', + 'ServerSideEncryption', + 'StorageClass', + 'SSECustomerAlgorithm', + 'SSECustomerKey', + 'SSECustomerKeyMD5', + 'SSEKMSKeyId', + 'SSEKMSEncryptionContext', + 'Tagging', + ] + + def __init__(self, client, config=None, osutil=None): + self._client = client + if config is None: + config = TransferConfig() + self._config = config + if osutil is None: + osutil = OSUtils() + self._osutil = osutil + + def upload_file( + self, filename, bucket, key, callback=None, extra_args=None + ): + """Upload a file to an S3 object. + + Variants have also been injected into S3 client, Bucket and Object. + You don't have to use S3Transfer.upload_file() directly. + """ + if extra_args is None: + extra_args = {} + self._validate_all_known_args(extra_args, self.ALLOWED_UPLOAD_ARGS) + events = self._client.meta.events + events.register_first( + 'request-created.s3', + disable_upload_callbacks, + unique_id='s3upload-callback-disable', + ) + events.register_last( + 'request-created.s3', + enable_upload_callbacks, + unique_id='s3upload-callback-enable', + ) + if ( + self._osutil.get_file_size(filename) + >= self._config.multipart_threshold + ): + self._multipart_upload(filename, bucket, key, callback, extra_args) + else: + self._put_object(filename, bucket, key, callback, extra_args) + + def _put_object(self, filename, bucket, key, callback, extra_args): + # We're using open_file_chunk_reader so we can take advantage of the + # progress callback functionality. + open_chunk_reader = self._osutil.open_file_chunk_reader + with open_chunk_reader( + filename, + 0, + self._osutil.get_file_size(filename), + callback=callback, + ) as body: + self._client.put_object( + Bucket=bucket, Key=key, Body=body, **extra_args + ) + + def download_file( + self, bucket, key, filename, extra_args=None, callback=None + ): + """Download an S3 object to a file. + + Variants have also been injected into S3 client, Bucket and Object. + You don't have to use S3Transfer.download_file() directly. + """ + # This method will issue a ``head_object`` request to determine + # the size of the S3 object. This is used to determine if the + # object is downloaded in parallel. + if extra_args is None: + extra_args = {} + self._validate_all_known_args(extra_args, self.ALLOWED_DOWNLOAD_ARGS) + object_size = self._object_size(bucket, key, extra_args) + temp_filename = filename + os.extsep + random_file_extension() + try: + self._download_file( + bucket, key, temp_filename, object_size, extra_args, callback + ) + except Exception: + logger.debug( + "Exception caught in download_file, removing partial " + "file: %s", + temp_filename, + exc_info=True, + ) + self._osutil.remove_file(temp_filename) + raise + else: + self._osutil.rename_file(temp_filename, filename) + + def _download_file( + self, bucket, key, filename, object_size, extra_args, callback + ): + if object_size >= self._config.multipart_threshold: + self._ranged_download( + bucket, key, filename, object_size, extra_args, callback + ) + else: + self._get_object(bucket, key, filename, extra_args, callback) + + def _validate_all_known_args(self, actual, allowed): + for kwarg in actual: + if kwarg not in allowed: + raise ValueError( + f"Invalid extra_args key '{kwarg}', " + f"must be one of: {', '.join(allowed)}" + ) + + def _ranged_download( + self, bucket, key, filename, object_size, extra_args, callback + ): + downloader = MultipartDownloader( + self._client, self._config, self._osutil + ) + downloader.download_file( + bucket, key, filename, object_size, extra_args, callback + ) + + def _get_object(self, bucket, key, filename, extra_args, callback): + # precondition: num_download_attempts > 0 + max_attempts = self._config.num_download_attempts + last_exception = None + for i in range(max_attempts): + try: + return self._do_get_object( + bucket, key, filename, extra_args, callback + ) + except ( + socket.timeout, + OSError, + ReadTimeoutError, + IncompleteReadError, + ResponseStreamingError, + ) as e: + # TODO: we need a way to reset the callback if the + # download failed. + logger.debug( + "Retrying exception caught (%s), " + "retrying request, (attempt %s / %s)", + e, + i, + max_attempts, + exc_info=True, + ) + last_exception = e + continue + raise RetriesExceededError(last_exception) + + def _do_get_object(self, bucket, key, filename, extra_args, callback): + response = self._client.get_object( + Bucket=bucket, Key=key, **extra_args + ) + streaming_body = StreamReaderProgress(response['Body'], callback) + with self._osutil.open(filename, 'wb') as f: + for chunk in iter(lambda: streaming_body.read(8192), b''): + f.write(chunk) + + def _object_size(self, bucket, key, extra_args): + return self._client.head_object(Bucket=bucket, Key=key, **extra_args)[ + 'ContentLength' + ] + + def _multipart_upload(self, filename, bucket, key, callback, extra_args): + uploader = MultipartUploader(self._client, self._config, self._osutil) + uploader.upload_file(filename, bucket, key, callback, extra_args) diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7ae640ab030d0389e193f8c7a864282535f1278 Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/bandwidth.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/bandwidth.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6cb429cd9f8c4aeb97bf0f8527ec3df6fab7eb5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/bandwidth.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/compat.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/compat.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe4ad28018b4cf711fdb5c2dc9ab85f2f2a9fd59 Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/compat.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/constants.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/constants.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4fd5d74a1aa5fd7466beed87eddb3fab883a8ed Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/constants.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/copies.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/copies.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2f30bd988daa4a9cda535e92c7985f6c1fa0d6d Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/copies.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/crt.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/crt.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca93abe5b59cdd00eefeb21b6934504a35f9cf2a Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/crt.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/delete.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/delete.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..313c93658f37cc624da298dabc7ff1578e8e1de4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/delete.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/download.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/download.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6369c63989e58d714bc1a18fe9c4e4e5d79522fd Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/download.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/exceptions.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40f2add4aed20341ed575ff0560ec977d5867c58 Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/exceptions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/futures.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/futures.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70d30560a46586f6a5eefb7258f5e89f1b9c12ff Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/futures.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/manager.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/manager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72e1f8733ce8bd06d5797a5d789380be07929958 Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/manager.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/processpool.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/processpool.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0932d3d8a52bffb692ea87722c5ba76dc845b8e0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/processpool.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/subscribers.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/subscribers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..882752f9b5146a7c90df38b65cd08b784ebbf91a Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/subscribers.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/tasks.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/tasks.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfffee1a48bd1a3644046d643bc4adeee95b468b Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/tasks.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/upload.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/upload.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12ab794b76b8072ee89da206ffd7b143dee6a575 Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/upload.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5b101c90b1778c92585904779585510fa222db5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/s3transfer/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/s3transfer/bandwidth.py b/venv/lib/python3.10/site-packages/s3transfer/bandwidth.py new file mode 100644 index 0000000000000000000000000000000000000000..9301c8e3b9d1a9c9f7a13137fd23c93f196b4d2a --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/bandwidth.py @@ -0,0 +1,437 @@ +# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +import threading +import time + + +class RequestExceededException(Exception): + def __init__(self, requested_amt, retry_time): + """Error when requested amount exceeds what is allowed + + The request that raised this error should be retried after waiting + the time specified by ``retry_time``. + + :type requested_amt: int + :param requested_amt: The originally requested byte amount + + :type retry_time: float + :param retry_time: The length in time to wait to retry for the + requested amount + """ + self.requested_amt = requested_amt + self.retry_time = retry_time + msg = f'Request amount {requested_amt} exceeded the amount available. Retry in {retry_time}' + super().__init__(msg) + + +class RequestToken: + """A token to pass as an identifier when consuming from the LeakyBucket""" + + pass + + +class TimeUtils: + def time(self): + """Get the current time back + + :rtype: float + :returns: The current time in seconds + """ + return time.time() + + def sleep(self, value): + """Sleep for a designated time + + :type value: float + :param value: The time to sleep for in seconds + """ + return time.sleep(value) + + +class BandwidthLimiter: + def __init__(self, leaky_bucket, time_utils=None): + """Limits bandwidth for shared S3 transfers + + :type leaky_bucket: LeakyBucket + :param leaky_bucket: The leaky bucket to use limit bandwidth + + :type time_utils: TimeUtils + :param time_utils: Time utility to use for interacting with time. + """ + self._leaky_bucket = leaky_bucket + self._time_utils = time_utils + if time_utils is None: + self._time_utils = TimeUtils() + + def get_bandwith_limited_stream( + self, fileobj, transfer_coordinator, enabled=True + ): + """Wraps a fileobj in a bandwidth limited stream wrapper + + :type fileobj: file-like obj + :param fileobj: The file-like obj to wrap + + :type transfer_coordinator: s3transfer.futures.TransferCoordinator + param transfer_coordinator: The coordinator for the general transfer + that the wrapped stream is a part of + + :type enabled: boolean + :param enabled: Whether bandwidth limiting should be enabled to start + """ + stream = BandwidthLimitedStream( + fileobj, self._leaky_bucket, transfer_coordinator, self._time_utils + ) + if not enabled: + stream.disable_bandwidth_limiting() + return stream + + +class BandwidthLimitedStream: + def __init__( + self, + fileobj, + leaky_bucket, + transfer_coordinator, + time_utils=None, + bytes_threshold=256 * 1024, + ): + """Limits bandwidth for reads on a wrapped stream + + :type fileobj: file-like object + :param fileobj: The file like object to wrap + + :type leaky_bucket: LeakyBucket + :param leaky_bucket: The leaky bucket to use to throttle reads on + the stream + + :type transfer_coordinator: s3transfer.futures.TransferCoordinator + param transfer_coordinator: The coordinator for the general transfer + that the wrapped stream is a part of + + :type time_utils: TimeUtils + :param time_utils: The time utility to use for interacting with time + """ + self._fileobj = fileobj + self._leaky_bucket = leaky_bucket + self._transfer_coordinator = transfer_coordinator + self._time_utils = time_utils + if time_utils is None: + self._time_utils = TimeUtils() + self._bandwidth_limiting_enabled = True + self._request_token = RequestToken() + self._bytes_seen = 0 + self._bytes_threshold = bytes_threshold + + def enable_bandwidth_limiting(self): + """Enable bandwidth limiting on reads to the stream""" + self._bandwidth_limiting_enabled = True + + def disable_bandwidth_limiting(self): + """Disable bandwidth limiting on reads to the stream""" + self._bandwidth_limiting_enabled = False + + def read(self, amount): + """Read a specified amount + + Reads will only be throttled if bandwidth limiting is enabled. + """ + if not self._bandwidth_limiting_enabled: + return self._fileobj.read(amount) + + # We do not want to be calling consume on every read as the read + # amounts can be small causing the lock of the leaky bucket to + # introduce noticeable overhead. So instead we keep track of + # how many bytes we have seen and only call consume once we pass a + # certain threshold. + self._bytes_seen += amount + if self._bytes_seen < self._bytes_threshold: + return self._fileobj.read(amount) + + self._consume_through_leaky_bucket() + return self._fileobj.read(amount) + + def _consume_through_leaky_bucket(self): + # NOTE: If the read amount on the stream are high, it will result + # in large bursty behavior as there is not an interface for partial + # reads. However given the read's on this abstraction are at most 256KB + # (via downloads), it reduces the burstiness to be small KB bursts at + # worst. + while not self._transfer_coordinator.exception: + try: + self._leaky_bucket.consume( + self._bytes_seen, self._request_token + ) + self._bytes_seen = 0 + return + except RequestExceededException as e: + self._time_utils.sleep(e.retry_time) + else: + raise self._transfer_coordinator.exception + + def signal_transferring(self): + """Signal that data being read is being transferred to S3""" + self.enable_bandwidth_limiting() + + def signal_not_transferring(self): + """Signal that data being read is not being transferred to S3""" + self.disable_bandwidth_limiting() + + def seek(self, where, whence=0): + self._fileobj.seek(where, whence) + + def tell(self): + return self._fileobj.tell() + + def close(self): + if self._bandwidth_limiting_enabled and self._bytes_seen: + # This handles the case where the file is small enough to never + # trigger the threshold and thus is never subjugated to the + # leaky bucket on read(). This specifically happens for small + # uploads. So instead to account for those bytes, have + # it go through the leaky bucket when the file gets closed. + self._consume_through_leaky_bucket() + self._fileobj.close() + + def __enter__(self): + return self + + def __exit__(self, *args, **kwargs): + self.close() + + +class LeakyBucket: + def __init__( + self, + max_rate, + time_utils=None, + rate_tracker=None, + consumption_scheduler=None, + ): + """A leaky bucket abstraction to limit bandwidth consumption + + :type rate: int + :type rate: The maximum rate to allow. This rate is in terms of + bytes per second. + + :type time_utils: TimeUtils + :param time_utils: The time utility to use for interacting with time + + :type rate_tracker: BandwidthRateTracker + :param rate_tracker: Tracks bandwidth consumption + + :type consumption_scheduler: ConsumptionScheduler + :param consumption_scheduler: Schedules consumption retries when + necessary + """ + self._max_rate = float(max_rate) + self._time_utils = time_utils + if time_utils is None: + self._time_utils = TimeUtils() + self._lock = threading.Lock() + self._rate_tracker = rate_tracker + if rate_tracker is None: + self._rate_tracker = BandwidthRateTracker() + self._consumption_scheduler = consumption_scheduler + if consumption_scheduler is None: + self._consumption_scheduler = ConsumptionScheduler() + + def consume(self, amt, request_token): + """Consume an a requested amount + + :type amt: int + :param amt: The amount of bytes to request to consume + + :type request_token: RequestToken + :param request_token: The token associated to the consumption + request that is used to identify the request. So if a + RequestExceededException is raised the token should be used + in subsequent retry consume() request. + + :raises RequestExceededException: If the consumption amount would + exceed the maximum allocated bandwidth + + :rtype: int + :returns: The amount consumed + """ + with self._lock: + time_now = self._time_utils.time() + if self._consumption_scheduler.is_scheduled(request_token): + return self._release_requested_amt_for_scheduled_request( + amt, request_token, time_now + ) + elif self._projected_to_exceed_max_rate(amt, time_now): + self._raise_request_exceeded_exception( + amt, request_token, time_now + ) + else: + return self._release_requested_amt(amt, time_now) + + def _projected_to_exceed_max_rate(self, amt, time_now): + projected_rate = self._rate_tracker.get_projected_rate(amt, time_now) + return projected_rate > self._max_rate + + def _release_requested_amt_for_scheduled_request( + self, amt, request_token, time_now + ): + self._consumption_scheduler.process_scheduled_consumption( + request_token + ) + return self._release_requested_amt(amt, time_now) + + def _raise_request_exceeded_exception(self, amt, request_token, time_now): + allocated_time = amt / float(self._max_rate) + retry_time = self._consumption_scheduler.schedule_consumption( + amt, request_token, allocated_time + ) + raise RequestExceededException( + requested_amt=amt, retry_time=retry_time + ) + + def _release_requested_amt(self, amt, time_now): + self._rate_tracker.record_consumption_rate(amt, time_now) + return amt + + +class ConsumptionScheduler: + def __init__(self): + """Schedules when to consume a desired amount""" + self._tokens_to_scheduled_consumption = {} + self._total_wait = 0 + + def is_scheduled(self, token): + """Indicates if a consumption request has been scheduled + + :type token: RequestToken + :param token: The token associated to the consumption + request that is used to identify the request. + """ + return token in self._tokens_to_scheduled_consumption + + def schedule_consumption(self, amt, token, time_to_consume): + """Schedules a wait time to be able to consume an amount + + :type amt: int + :param amt: The amount of bytes scheduled to be consumed + + :type token: RequestToken + :param token: The token associated to the consumption + request that is used to identify the request. + + :type time_to_consume: float + :param time_to_consume: The desired time it should take for that + specific request amount to be consumed in regardless of previously + scheduled consumption requests + + :rtype: float + :returns: The amount of time to wait for the specific request before + actually consuming the specified amount. + """ + self._total_wait += time_to_consume + self._tokens_to_scheduled_consumption[token] = { + 'wait_duration': self._total_wait, + 'time_to_consume': time_to_consume, + } + return self._total_wait + + def process_scheduled_consumption(self, token): + """Processes a scheduled consumption request that has completed + + :type token: RequestToken + :param token: The token associated to the consumption + request that is used to identify the request. + """ + scheduled_retry = self._tokens_to_scheduled_consumption.pop(token) + self._total_wait = max( + self._total_wait - scheduled_retry['time_to_consume'], 0 + ) + + +class BandwidthRateTracker: + def __init__(self, alpha=0.8): + """Tracks the rate of bandwidth consumption + + :type a: float + :param a: The constant to use in calculating the exponentional moving + average of the bandwidth rate. Specifically it is used in the + following calculation: + + current_rate = alpha * new_rate + (1 - alpha) * current_rate + + This value of this constant should be between 0 and 1. + """ + self._alpha = alpha + self._last_time = None + self._current_rate = None + + @property + def current_rate(self): + """The current transfer rate + + :rtype: float + :returns: The current tracked transfer rate + """ + if self._last_time is None: + return 0.0 + return self._current_rate + + def get_projected_rate(self, amt, time_at_consumption): + """Get the projected rate using a provided amount and time + + :type amt: int + :param amt: The proposed amount to consume + + :type time_at_consumption: float + :param time_at_consumption: The proposed time to consume at + + :rtype: float + :returns: The consumption rate if that amt and time were consumed + """ + if self._last_time is None: + return 0.0 + return self._calculate_exponential_moving_average_rate( + amt, time_at_consumption + ) + + def record_consumption_rate(self, amt, time_at_consumption): + """Record the consumption rate based off amount and time point + + :type amt: int + :param amt: The amount that got consumed + + :type time_at_consumption: float + :param time_at_consumption: The time at which the amount was consumed + """ + if self._last_time is None: + self._last_time = time_at_consumption + self._current_rate = 0.0 + return + self._current_rate = self._calculate_exponential_moving_average_rate( + amt, time_at_consumption + ) + self._last_time = time_at_consumption + + def _calculate_rate(self, amt, time_at_consumption): + time_delta = time_at_consumption - self._last_time + if time_delta <= 0: + # While it is really unlikely to see this in an actual transfer, + # we do not want to be returning back a negative rate or try to + # divide the amount by zero. So instead return back an infinite + # rate as the time delta is infinitesimally small. + return float('inf') + return amt / (time_delta) + + def _calculate_exponential_moving_average_rate( + self, amt, time_at_consumption + ): + new_rate = self._calculate_rate(amt, time_at_consumption) + return self._alpha * new_rate + (1 - self._alpha) * self._current_rate diff --git a/venv/lib/python3.10/site-packages/s3transfer/compat.py b/venv/lib/python3.10/site-packages/s3transfer/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..68267ad0e2689c6c88fd2fda3bf397f16f97cc90 --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/compat.py @@ -0,0 +1,94 @@ +# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +import errno +import inspect +import os +import socket +import sys + +from botocore.compat import six + +if sys.platform.startswith('win'): + def rename_file(current_filename, new_filename): + try: + os.remove(new_filename) + except OSError as e: + if not e.errno == errno.ENOENT: + # We only want to a ignore trying to remove + # a file that does not exist. If it fails + # for any other reason we should be propagating + # that exception. + raise + os.rename(current_filename, new_filename) +else: + rename_file = os.rename + + +def accepts_kwargs(func): + return inspect.getfullargspec(func)[2] + + +# In python 3, socket.error is OSError, which is too general +# for what we want (i.e FileNotFoundError is a subclass of OSError). +# In python 3, all the socket related errors are in a newly created +# ConnectionError. +SOCKET_ERROR = ConnectionError +MAXINT = None + + +def seekable(fileobj): + """Backwards compat function to determine if a fileobj is seekable + + :param fileobj: The file-like object to determine if seekable + + :returns: True, if seekable. False, otherwise. + """ + # If the fileobj has a seekable attr, try calling the seekable() + # method on it. + if hasattr(fileobj, 'seekable'): + return fileobj.seekable() + # If there is no seekable attr, check if the object can be seeked + # or telled. If it can, try to seek to the current position. + elif hasattr(fileobj, 'seek') and hasattr(fileobj, 'tell'): + try: + fileobj.seek(0, 1) + return True + except OSError: + # If an io related error was thrown then it is not seekable. + return False + # Else, the fileobj is not seekable + return False + + +def readable(fileobj): + """Determines whether or not a file-like object is readable. + + :param fileobj: The file-like object to determine if readable + + :returns: True, if readable. False otherwise. + """ + if hasattr(fileobj, 'readable'): + return fileobj.readable() + + return hasattr(fileobj, 'read') + + +def fallocate(fileobj, size): + if hasattr(os, 'posix_fallocate'): + os.posix_fallocate(fileobj.fileno(), 0, size) + else: + fileobj.truncate(size) + + +# Import at end of file to avoid circular dependencies +from multiprocessing.managers import BaseManager # noqa: F401,E402 diff --git a/venv/lib/python3.10/site-packages/s3transfer/constants.py b/venv/lib/python3.10/site-packages/s3transfer/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..b07b1d471635f414b6fe8d21a4c5a32348bf050c --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/constants.py @@ -0,0 +1,30 @@ +# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +import s3transfer + +KB = 1024 +MB = KB * KB +GB = MB * KB + +ALLOWED_DOWNLOAD_ARGS = [ + 'ChecksumMode', + 'VersionId', + 'SSECustomerAlgorithm', + 'SSECustomerKey', + 'SSECustomerKeyMD5', + 'RequestPayer', + 'ExpectedBucketOwner', +] + +USER_AGENT = f's3transfer/{s3transfer.__version__}' +PROCESS_USER_AGENT = f'{USER_AGENT} processpool' diff --git a/venv/lib/python3.10/site-packages/s3transfer/copies.py b/venv/lib/python3.10/site-packages/s3transfer/copies.py new file mode 100644 index 0000000000000000000000000000000000000000..c2ae9ce0ca5a0461c6deb4c56efdefe4427b97a8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/copies.py @@ -0,0 +1,388 @@ +# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +import copy +import math + +from s3transfer.tasks import ( + CompleteMultipartUploadTask, + CreateMultipartUploadTask, + SubmissionTask, + Task, +) +from s3transfer.utils import ( + ChunksizeAdjuster, + calculate_range_parameter, + get_callbacks, + get_filtered_dict, +) + + +class CopySubmissionTask(SubmissionTask): + """Task for submitting tasks to execute a copy""" + + EXTRA_ARGS_TO_HEAD_ARGS_MAPPING = { + 'CopySourceIfMatch': 'IfMatch', + 'CopySourceIfModifiedSince': 'IfModifiedSince', + 'CopySourceIfNoneMatch': 'IfNoneMatch', + 'CopySourceIfUnmodifiedSince': 'IfUnmodifiedSince', + 'CopySourceSSECustomerKey': 'SSECustomerKey', + 'CopySourceSSECustomerAlgorithm': 'SSECustomerAlgorithm', + 'CopySourceSSECustomerKeyMD5': 'SSECustomerKeyMD5', + 'RequestPayer': 'RequestPayer', + 'ExpectedBucketOwner': 'ExpectedBucketOwner', + } + + UPLOAD_PART_COPY_ARGS = [ + 'CopySourceIfMatch', + 'CopySourceIfModifiedSince', + 'CopySourceIfNoneMatch', + 'CopySourceIfUnmodifiedSince', + 'CopySourceSSECustomerKey', + 'CopySourceSSECustomerAlgorithm', + 'CopySourceSSECustomerKeyMD5', + 'SSECustomerKey', + 'SSECustomerAlgorithm', + 'SSECustomerKeyMD5', + 'RequestPayer', + 'ExpectedBucketOwner', + ] + + CREATE_MULTIPART_ARGS_BLACKLIST = [ + 'CopySourceIfMatch', + 'CopySourceIfModifiedSince', + 'CopySourceIfNoneMatch', + 'CopySourceIfUnmodifiedSince', + 'CopySourceSSECustomerKey', + 'CopySourceSSECustomerAlgorithm', + 'CopySourceSSECustomerKeyMD5', + 'MetadataDirective', + 'TaggingDirective', + ] + + COMPLETE_MULTIPART_ARGS = [ + 'SSECustomerKey', + 'SSECustomerAlgorithm', + 'SSECustomerKeyMD5', + 'RequestPayer', + 'ExpectedBucketOwner', + ] + + def _submit( + self, client, config, osutil, request_executor, transfer_future + ): + """ + :param client: The client associated with the transfer manager + + :type config: s3transfer.manager.TransferConfig + :param config: The transfer config associated with the transfer + manager + + :type osutil: s3transfer.utils.OSUtil + :param osutil: The os utility associated to the transfer manager + + :type request_executor: s3transfer.futures.BoundedExecutor + :param request_executor: The request executor associated with the + transfer manager + + :type transfer_future: s3transfer.futures.TransferFuture + :param transfer_future: The transfer future associated with the + transfer request that tasks are being submitted for + """ + # Determine the size if it was not provided + if transfer_future.meta.size is None: + # If a size was not provided figure out the size for the + # user. Note that we will only use the client provided to + # the TransferManager. If the object is outside of the region + # of the client, they may have to provide the file size themselves + # with a completely new client. + call_args = transfer_future.meta.call_args + head_object_request = ( + self._get_head_object_request_from_copy_source( + call_args.copy_source + ) + ) + extra_args = call_args.extra_args + + # Map any values that may be used in the head object that is + # used in the copy object + for param, value in extra_args.items(): + if param in self.EXTRA_ARGS_TO_HEAD_ARGS_MAPPING: + head_object_request[ + self.EXTRA_ARGS_TO_HEAD_ARGS_MAPPING[param] + ] = value + + response = call_args.source_client.head_object( + **head_object_request + ) + transfer_future.meta.provide_transfer_size( + response['ContentLength'] + ) + + # If it is greater than threshold do a multipart copy, otherwise + # do a regular copy object. + if transfer_future.meta.size < config.multipart_threshold: + self._submit_copy_request( + client, config, osutil, request_executor, transfer_future + ) + else: + self._submit_multipart_request( + client, config, osutil, request_executor, transfer_future + ) + + def _submit_copy_request( + self, client, config, osutil, request_executor, transfer_future + ): + call_args = transfer_future.meta.call_args + + # Get the needed progress callbacks for the task + progress_callbacks = get_callbacks(transfer_future, 'progress') + + # Submit the request of a single copy. + self._transfer_coordinator.submit( + request_executor, + CopyObjectTask( + transfer_coordinator=self._transfer_coordinator, + main_kwargs={ + 'client': client, + 'copy_source': call_args.copy_source, + 'bucket': call_args.bucket, + 'key': call_args.key, + 'extra_args': call_args.extra_args, + 'callbacks': progress_callbacks, + 'size': transfer_future.meta.size, + }, + is_final=True, + ), + ) + + def _submit_multipart_request( + self, client, config, osutil, request_executor, transfer_future + ): + call_args = transfer_future.meta.call_args + + # Submit the request to create a multipart upload and make sure it + # does not include any of the arguments used for copy part. + create_multipart_extra_args = {} + for param, val in call_args.extra_args.items(): + if param not in self.CREATE_MULTIPART_ARGS_BLACKLIST: + create_multipart_extra_args[param] = val + + create_multipart_future = self._transfer_coordinator.submit( + request_executor, + CreateMultipartUploadTask( + transfer_coordinator=self._transfer_coordinator, + main_kwargs={ + 'client': client, + 'bucket': call_args.bucket, + 'key': call_args.key, + 'extra_args': create_multipart_extra_args, + }, + ), + ) + + # Determine how many parts are needed based on filesize and + # desired chunksize. + part_size = config.multipart_chunksize + adjuster = ChunksizeAdjuster() + part_size = adjuster.adjust_chunksize( + part_size, transfer_future.meta.size + ) + num_parts = int( + math.ceil(transfer_future.meta.size / float(part_size)) + ) + + # Submit requests to upload the parts of the file. + part_futures = [] + progress_callbacks = get_callbacks(transfer_future, 'progress') + + for part_number in range(1, num_parts + 1): + extra_part_args = self._extra_upload_part_args( + call_args.extra_args + ) + # The part number for upload part starts at 1 while the + # range parameter starts at zero, so just subtract 1 off of + # the part number + extra_part_args['CopySourceRange'] = calculate_range_parameter( + part_size, + part_number - 1, + num_parts, + transfer_future.meta.size, + ) + # Get the size of the part copy as well for the progress + # callbacks. + size = self._get_transfer_size( + part_size, + part_number - 1, + num_parts, + transfer_future.meta.size, + ) + # Get the checksum algorithm of the multipart request. + checksum_algorithm = call_args.extra_args.get("ChecksumAlgorithm") + part_futures.append( + self._transfer_coordinator.submit( + request_executor, + CopyPartTask( + transfer_coordinator=self._transfer_coordinator, + main_kwargs={ + 'client': client, + 'copy_source': call_args.copy_source, + 'bucket': call_args.bucket, + 'key': call_args.key, + 'part_number': part_number, + 'extra_args': extra_part_args, + 'callbacks': progress_callbacks, + 'size': size, + 'checksum_algorithm': checksum_algorithm, + }, + pending_main_kwargs={ + 'upload_id': create_multipart_future + }, + ), + ) + ) + + complete_multipart_extra_args = self._extra_complete_multipart_args( + call_args.extra_args + ) + # Submit the request to complete the multipart upload. + self._transfer_coordinator.submit( + request_executor, + CompleteMultipartUploadTask( + transfer_coordinator=self._transfer_coordinator, + main_kwargs={ + 'client': client, + 'bucket': call_args.bucket, + 'key': call_args.key, + 'extra_args': complete_multipart_extra_args, + }, + pending_main_kwargs={ + 'upload_id': create_multipart_future, + 'parts': part_futures, + }, + is_final=True, + ), + ) + + def _get_head_object_request_from_copy_source(self, copy_source): + if isinstance(copy_source, dict): + return copy.copy(copy_source) + else: + raise TypeError( + 'Expecting dictionary formatted: ' + '{"Bucket": bucket_name, "Key": key} ' + f'but got {copy_source} or type {type(copy_source)}.' + ) + + def _extra_upload_part_args(self, extra_args): + # Only the args in COPY_PART_ARGS actually need to be passed + # onto the upload_part_copy calls. + return get_filtered_dict(extra_args, self.UPLOAD_PART_COPY_ARGS) + + def _extra_complete_multipart_args(self, extra_args): + return get_filtered_dict(extra_args, self.COMPLETE_MULTIPART_ARGS) + + def _get_transfer_size( + self, part_size, part_index, num_parts, total_transfer_size + ): + if part_index == num_parts - 1: + # The last part may be different in size then the rest of the + # parts. + return total_transfer_size - (part_index * part_size) + return part_size + + +class CopyObjectTask(Task): + """Task to do a nonmultipart copy""" + + def _main( + self, client, copy_source, bucket, key, extra_args, callbacks, size + ): + """ + :param client: The client to use when calling PutObject + :param copy_source: The CopySource parameter to use + :param bucket: The name of the bucket to copy to + :param key: The name of the key to copy to + :param extra_args: A dictionary of any extra arguments that may be + used in the upload. + :param callbacks: List of callbacks to call after copy + :param size: The size of the transfer. This value is passed into + the callbacks + + """ + client.copy_object( + CopySource=copy_source, Bucket=bucket, Key=key, **extra_args + ) + for callback in callbacks: + callback(bytes_transferred=size) + + +class CopyPartTask(Task): + """Task to upload a part in a multipart copy""" + + def _main( + self, + client, + copy_source, + bucket, + key, + upload_id, + part_number, + extra_args, + callbacks, + size, + checksum_algorithm=None, + ): + """ + :param client: The client to use when calling PutObject + :param copy_source: The CopySource parameter to use + :param bucket: The name of the bucket to upload to + :param key: The name of the key to upload to + :param upload_id: The id of the upload + :param part_number: The number representing the part of the multipart + upload + :param extra_args: A dictionary of any extra arguments that may be + used in the upload. + :param callbacks: List of callbacks to call after copy part + :param size: The size of the transfer. This value is passed into + the callbacks + :param checksum_algorithm: The algorithm that was used to create the multipart + upload + + :rtype: dict + :returns: A dictionary representing a part:: + + {'Etag': etag_value, 'PartNumber': part_number} + + This value can be appended to a list to be used to complete + the multipart upload. If a checksum is in the response, + it will also be included. + """ + response = client.upload_part_copy( + CopySource=copy_source, + Bucket=bucket, + Key=key, + UploadId=upload_id, + PartNumber=part_number, + **extra_args, + ) + for callback in callbacks: + callback(bytes_transferred=size) + etag = response['CopyPartResult']['ETag'] + part_metadata = {'ETag': etag, 'PartNumber': part_number} + if checksum_algorithm: + checksum_member = f'Checksum{checksum_algorithm.upper()}' + if checksum_member in response['CopyPartResult']: + part_metadata[checksum_member] = response['CopyPartResult'][ + checksum_member + ] + return part_metadata diff --git a/venv/lib/python3.10/site-packages/s3transfer/crt.py b/venv/lib/python3.10/site-packages/s3transfer/crt.py new file mode 100644 index 0000000000000000000000000000000000000000..df7eb26d9102ec58bf2a1a88ccb1e9244809fc0f --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/crt.py @@ -0,0 +1,970 @@ +# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +import logging +import re +import threading +from io import BytesIO + +import awscrt.http +import awscrt.s3 +import botocore.awsrequest +import botocore.session +from awscrt.auth import ( + AwsCredentials, + AwsCredentialsProvider, + AwsSigningAlgorithm, + AwsSigningConfig, +) +from awscrt.io import ( + ClientBootstrap, + ClientTlsContext, + DefaultHostResolver, + EventLoopGroup, + TlsContextOptions, +) +from awscrt.s3 import S3Client, S3RequestTlsMode, S3RequestType +from botocore import UNSIGNED +from botocore.compat import urlsplit +from botocore.config import Config +from botocore.exceptions import NoCredentialsError +from botocore.utils import ArnParser, InvalidArnException + +from s3transfer.constants import MB +from s3transfer.exceptions import TransferNotDoneError +from s3transfer.futures import BaseTransferFuture, BaseTransferMeta +from s3transfer.manager import TransferManager +from s3transfer.utils import ( + CallArgs, + OSUtils, + get_callbacks, + is_s3express_bucket, +) + +logger = logging.getLogger(__name__) + +CRT_S3_PROCESS_LOCK = None + + +def acquire_crt_s3_process_lock(name): + # Currently, the CRT S3 client performs best when there is only one + # instance of it running on a host. This lock allows an application to + # signal across processes whether there is another process of the same + # application using the CRT S3 client and prevent spawning more than one + # CRT S3 clients running on the system for that application. + # + # NOTE: When acquiring the CRT process lock, the lock automatically is + # released when the lock object is garbage collected. So, the CRT process + # lock is set as a global so that it is not unintentionally garbage + # collected/released if reference of the lock is lost. + global CRT_S3_PROCESS_LOCK + if CRT_S3_PROCESS_LOCK is None: + crt_lock = awscrt.s3.CrossProcessLock(name) + try: + crt_lock.acquire() + except RuntimeError: + # If there is another process that is holding the lock, the CRT + # returns a RuntimeError. We return None here to signal that our + # current process was not able to acquire the lock. + return None + CRT_S3_PROCESS_LOCK = crt_lock + return CRT_S3_PROCESS_LOCK + + +def create_s3_crt_client( + region, + crt_credentials_provider=None, + num_threads=None, + target_throughput=None, + part_size=8 * MB, + use_ssl=True, + verify=None, +): + """ + :type region: str + :param region: The region used for signing + + :type crt_credentials_provider: + Optional[awscrt.auth.AwsCredentialsProvider] + :param crt_credentials_provider: CRT AWS credentials provider + to use to sign requests. If not set, requests will not be signed. + + :type num_threads: Optional[int] + :param num_threads: Number of worker threads generated. Default + is the number of processors in the machine. + + :type target_throughput: Optional[int] + :param target_throughput: Throughput target in bytes per second. + By default, CRT will automatically attempt to choose a target + throughput that matches the system's maximum network throughput. + Currently, if CRT is unable to determine the maximum network + throughput, a fallback target throughput of ``1_250_000_000`` bytes + per second (which translates to 10 gigabits per second, or 1.16 + gibibytes per second) is used. To set a specific target + throughput, set a value for this parameter. + + :type part_size: Optional[int] + :param part_size: Size, in Bytes, of parts that files will be downloaded + or uploaded in. + + :type use_ssl: boolean + :param use_ssl: Whether or not to use SSL. By default, SSL is used. + Note that not all services support non-ssl connections. + + :type verify: Optional[boolean/string] + :param verify: Whether or not to verify SSL certificates. + By default SSL certificates are verified. You can provide the + following values: + + * False - do not validate SSL certificates. SSL will still be + used (unless use_ssl is False), but SSL certificates + will not be verified. + * path/to/cert/bundle.pem - A filename of the CA cert bundle to + use. Specify this argument if you want to use a custom CA cert + bundle instead of the default one on your system. + """ + event_loop_group = EventLoopGroup(num_threads) + host_resolver = DefaultHostResolver(event_loop_group) + bootstrap = ClientBootstrap(event_loop_group, host_resolver) + tls_connection_options = None + + tls_mode = ( + S3RequestTlsMode.ENABLED if use_ssl else S3RequestTlsMode.DISABLED + ) + if verify is not None: + tls_ctx_options = TlsContextOptions() + if verify: + tls_ctx_options.override_default_trust_store_from_path( + ca_filepath=verify + ) + else: + tls_ctx_options.verify_peer = False + client_tls_option = ClientTlsContext(tls_ctx_options) + tls_connection_options = client_tls_option.new_connection_options() + target_gbps = _get_crt_throughput_target_gbps( + provided_throughput_target_bytes=target_throughput + ) + return S3Client( + bootstrap=bootstrap, + region=region, + credential_provider=crt_credentials_provider, + part_size=part_size, + tls_mode=tls_mode, + tls_connection_options=tls_connection_options, + throughput_target_gbps=target_gbps, + enable_s3express=True, + ) + + +def _get_crt_throughput_target_gbps(provided_throughput_target_bytes=None): + if provided_throughput_target_bytes is None: + target_gbps = awscrt.s3.get_recommended_throughput_target_gbps() + logger.debug( + 'Recommended CRT throughput target in gbps: %s', target_gbps + ) + if target_gbps is None: + target_gbps = 10.0 + else: + # NOTE: The GB constant in s3transfer is technically a gibibyte. The + # GB constant is not used here because the CRT interprets gigabits + # for networking as a base power of 10 + # (i.e. 1000 ** 3 instead of 1024 ** 3). + target_gbps = provided_throughput_target_bytes * 8 / 1_000_000_000 + logger.debug('Using CRT throughput target in gbps: %s', target_gbps) + return target_gbps + + +class CRTTransferManager: + ALLOWED_DOWNLOAD_ARGS = TransferManager.ALLOWED_DOWNLOAD_ARGS + ALLOWED_UPLOAD_ARGS = TransferManager.ALLOWED_UPLOAD_ARGS + ALLOWED_DELETE_ARGS = TransferManager.ALLOWED_DELETE_ARGS + + VALIDATE_SUPPORTED_BUCKET_VALUES = True + + _UNSUPPORTED_BUCKET_PATTERNS = TransferManager._UNSUPPORTED_BUCKET_PATTERNS + + def __init__(self, crt_s3_client, crt_request_serializer, osutil=None): + """A transfer manager interface for Amazon S3 on CRT s3 client. + + :type crt_s3_client: awscrt.s3.S3Client + :param crt_s3_client: The CRT s3 client, handling all the + HTTP requests and functions under then hood + + :type crt_request_serializer: s3transfer.crt.BaseCRTRequestSerializer + :param crt_request_serializer: Serializer, generates unsigned crt HTTP + request. + + :type osutil: s3transfer.utils.OSUtils + :param osutil: OSUtils object to use for os-related behavior when + using with transfer manager. + """ + if osutil is None: + self._osutil = OSUtils() + self._crt_s3_client = crt_s3_client + self._s3_args_creator = S3ClientArgsCreator( + crt_request_serializer, self._osutil + ) + self._crt_exception_translator = ( + crt_request_serializer.translate_crt_exception + ) + self._future_coordinators = [] + self._semaphore = threading.Semaphore(128) # not configurable + # A counter to create unique id's for each transfer submitted. + self._id_counter = 0 + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, *args): + cancel = False + if exc_type: + cancel = True + self._shutdown(cancel) + + def download( + self, bucket, key, fileobj, extra_args=None, subscribers=None + ): + if extra_args is None: + extra_args = {} + if subscribers is None: + subscribers = {} + self._validate_all_known_args(extra_args, self.ALLOWED_DOWNLOAD_ARGS) + self._validate_if_bucket_supported(bucket) + callargs = CallArgs( + bucket=bucket, + key=key, + fileobj=fileobj, + extra_args=extra_args, + subscribers=subscribers, + ) + return self._submit_transfer("get_object", callargs) + + def upload(self, fileobj, bucket, key, extra_args=None, subscribers=None): + if extra_args is None: + extra_args = {} + if subscribers is None: + subscribers = {} + self._validate_all_known_args(extra_args, self.ALLOWED_UPLOAD_ARGS) + self._validate_if_bucket_supported(bucket) + self._validate_checksum_algorithm_supported(extra_args) + callargs = CallArgs( + bucket=bucket, + key=key, + fileobj=fileobj, + extra_args=extra_args, + subscribers=subscribers, + ) + return self._submit_transfer("put_object", callargs) + + def delete(self, bucket, key, extra_args=None, subscribers=None): + if extra_args is None: + extra_args = {} + if subscribers is None: + subscribers = {} + self._validate_all_known_args(extra_args, self.ALLOWED_DELETE_ARGS) + self._validate_if_bucket_supported(bucket) + callargs = CallArgs( + bucket=bucket, + key=key, + extra_args=extra_args, + subscribers=subscribers, + ) + return self._submit_transfer("delete_object", callargs) + + def shutdown(self, cancel=False): + self._shutdown(cancel) + + def _validate_if_bucket_supported(self, bucket): + # s3 high level operations don't support some resources + # (eg. S3 Object Lambda) only direct API calls are available + # for such resources + if self.VALIDATE_SUPPORTED_BUCKET_VALUES: + for resource, pattern in self._UNSUPPORTED_BUCKET_PATTERNS.items(): + match = pattern.match(bucket) + if match: + raise ValueError( + f'TransferManager methods do not support {resource} ' + 'resource. Use direct client calls instead.' + ) + + def _validate_all_known_args(self, actual, allowed): + for kwarg in actual: + if kwarg not in allowed: + raise ValueError( + f"Invalid extra_args key '{kwarg}', " + f"must be one of: {', '.join(allowed)}" + ) + + def _validate_checksum_algorithm_supported(self, extra_args): + checksum_algorithm = extra_args.get('ChecksumAlgorithm') + if checksum_algorithm is None: + return + supported_algorithms = list(awscrt.s3.S3ChecksumAlgorithm.__members__) + if checksum_algorithm.upper() not in supported_algorithms: + raise ValueError( + f'ChecksumAlgorithm: {checksum_algorithm} not supported. ' + f'Supported algorithms are: {supported_algorithms}' + ) + + def _cancel_transfers(self): + for coordinator in self._future_coordinators: + if not coordinator.done(): + coordinator.cancel() + + def _finish_transfers(self): + for coordinator in self._future_coordinators: + coordinator.result() + + def _wait_transfers_done(self): + for coordinator in self._future_coordinators: + coordinator.wait_until_on_done_callbacks_complete() + + def _shutdown(self, cancel=False): + if cancel: + self._cancel_transfers() + try: + self._finish_transfers() + + except KeyboardInterrupt: + self._cancel_transfers() + except Exception: + pass + finally: + self._wait_transfers_done() + + def _release_semaphore(self, **kwargs): + self._semaphore.release() + + def _submit_transfer(self, request_type, call_args): + on_done_after_calls = [self._release_semaphore] + coordinator = CRTTransferCoordinator( + transfer_id=self._id_counter, + exception_translator=self._crt_exception_translator, + ) + components = { + 'meta': CRTTransferMeta(self._id_counter, call_args), + 'coordinator': coordinator, + } + future = CRTTransferFuture(**components) + afterdone = AfterDoneHandler(coordinator) + on_done_after_calls.append(afterdone) + + try: + self._semaphore.acquire() + on_queued = self._s3_args_creator.get_crt_callback( + future, 'queued' + ) + on_queued() + crt_callargs = self._s3_args_creator.get_make_request_args( + request_type, + call_args, + coordinator, + future, + on_done_after_calls, + ) + crt_s3_request = self._crt_s3_client.make_request(**crt_callargs) + except Exception as e: + coordinator.set_exception(e, True) + on_done = self._s3_args_creator.get_crt_callback( + future, 'done', after_subscribers=on_done_after_calls + ) + on_done(error=e) + else: + coordinator.set_s3_request(crt_s3_request) + self._future_coordinators.append(coordinator) + + self._id_counter += 1 + return future + + +class CRTTransferMeta(BaseTransferMeta): + """Holds metadata about the CRTTransferFuture""" + + def __init__(self, transfer_id=None, call_args=None): + self._transfer_id = transfer_id + self._call_args = call_args + self._user_context = {} + + @property + def call_args(self): + return self._call_args + + @property + def transfer_id(self): + return self._transfer_id + + @property + def user_context(self): + return self._user_context + + +class CRTTransferFuture(BaseTransferFuture): + def __init__(self, meta=None, coordinator=None): + """The future associated to a submitted transfer request via CRT S3 client + + :type meta: s3transfer.crt.CRTTransferMeta + :param meta: The metadata associated to the transfer future. + + :type coordinator: s3transfer.crt.CRTTransferCoordinator + :param coordinator: The coordinator associated to the transfer future. + """ + self._meta = meta + if meta is None: + self._meta = CRTTransferMeta() + self._coordinator = coordinator + + @property + def meta(self): + return self._meta + + def done(self): + return self._coordinator.done() + + def result(self, timeout=None): + self._coordinator.result(timeout) + + def cancel(self): + self._coordinator.cancel() + + def set_exception(self, exception): + """Sets the exception on the future.""" + if not self.done(): + raise TransferNotDoneError( + 'set_exception can only be called once the transfer is ' + 'complete.' + ) + self._coordinator.set_exception(exception, override=True) + + +class BaseCRTRequestSerializer: + def serialize_http_request(self, transfer_type, future): + """Serialize CRT HTTP requests. + + :type transfer_type: string + :param transfer_type: the type of transfer made, + e.g 'put_object', 'get_object', 'delete_object' + + :type future: s3transfer.crt.CRTTransferFuture + + :rtype: awscrt.http.HttpRequest + :returns: An unsigned HTTP request to be used for the CRT S3 client + """ + raise NotImplementedError('serialize_http_request()') + + def translate_crt_exception(self, exception): + raise NotImplementedError('translate_crt_exception()') + + +class BotocoreCRTRequestSerializer(BaseCRTRequestSerializer): + def __init__(self, session, client_kwargs=None): + """Serialize CRT HTTP request using botocore logic + It also takes into account configuration from both the session + and any keyword arguments that could be passed to + `Session.create_client()` when serializing the request. + + :type session: botocore.session.Session + + :type client_kwargs: Optional[Dict[str, str]]) + :param client_kwargs: The kwargs for the botocore + s3 client initialization. + """ + self._session = session + if client_kwargs is None: + client_kwargs = {} + self._resolve_client_config(session, client_kwargs) + self._client = session.create_client(**client_kwargs) + self._client.meta.events.register( + 'request-created.s3.*', self._capture_http_request + ) + self._client.meta.events.register( + 'after-call.s3.*', self._change_response_to_serialized_http_request + ) + self._client.meta.events.register( + 'before-send.s3.*', self._make_fake_http_response + ) + + def _resolve_client_config(self, session, client_kwargs): + user_provided_config = None + if session.get_default_client_config(): + user_provided_config = session.get_default_client_config() + if 'config' in client_kwargs: + user_provided_config = client_kwargs['config'] + + client_config = Config(signature_version=UNSIGNED) + if user_provided_config: + client_config = user_provided_config.merge(client_config) + client_kwargs['config'] = client_config + client_kwargs["service_name"] = "s3" + + def _crt_request_from_aws_request(self, aws_request): + url_parts = urlsplit(aws_request.url) + crt_path = url_parts.path + if url_parts.query: + crt_path = f'{crt_path}?{url_parts.query}' + headers_list = [] + for name, value in aws_request.headers.items(): + if isinstance(value, str): + headers_list.append((name, value)) + else: + headers_list.append((name, str(value, 'utf-8'))) + + crt_headers = awscrt.http.HttpHeaders(headers_list) + + crt_request = awscrt.http.HttpRequest( + method=aws_request.method, + path=crt_path, + headers=crt_headers, + body_stream=aws_request.body, + ) + return crt_request + + def _convert_to_crt_http_request(self, botocore_http_request): + # Logic that does CRTUtils.crt_request_from_aws_request + crt_request = self._crt_request_from_aws_request(botocore_http_request) + if crt_request.headers.get("host") is None: + # If host is not set, set it for the request before using CRT s3 + url_parts = urlsplit(botocore_http_request.url) + crt_request.headers.set("host", url_parts.netloc) + if crt_request.headers.get('Content-MD5') is not None: + crt_request.headers.remove("Content-MD5") + + # In general, the CRT S3 client expects a content length header. It + # only expects a missing content length header if the body is not + # seekable. However, botocore does not set the content length header + # for GetObject API requests and so we set the content length to zero + # to meet the CRT S3 client's expectation that the content length + # header is set even if there is no body. + if crt_request.headers.get('Content-Length') is None: + if botocore_http_request.body is None: + crt_request.headers.add('Content-Length', "0") + + # Botocore sets the Transfer-Encoding header when it cannot determine + # the content length of the request body (e.g. it's not seekable). + # However, CRT does not support this header, but it supports + # non-seekable bodies. So we remove this header to not cause issues + # in the downstream CRT S3 request. + if crt_request.headers.get('Transfer-Encoding') is not None: + crt_request.headers.remove('Transfer-Encoding') + + return crt_request + + def _capture_http_request(self, request, **kwargs): + request.context['http_request'] = request + + def _change_response_to_serialized_http_request( + self, context, parsed, **kwargs + ): + request = context['http_request'] + parsed['HTTPRequest'] = request.prepare() + + def _make_fake_http_response(self, request, **kwargs): + return botocore.awsrequest.AWSResponse( + None, + 200, + {}, + FakeRawResponse(b""), + ) + + def _get_botocore_http_request(self, client_method, call_args): + return getattr(self._client, client_method)( + Bucket=call_args.bucket, Key=call_args.key, **call_args.extra_args + )['HTTPRequest'] + + def serialize_http_request(self, transfer_type, future): + botocore_http_request = self._get_botocore_http_request( + transfer_type, future.meta.call_args + ) + crt_request = self._convert_to_crt_http_request(botocore_http_request) + return crt_request + + def translate_crt_exception(self, exception): + if isinstance(exception, awscrt.s3.S3ResponseError): + return self._translate_crt_s3_response_error(exception) + else: + return None + + def _translate_crt_s3_response_error(self, s3_response_error): + status_code = s3_response_error.status_code + if status_code < 301: + # Botocore's exception parsing only + # runs on status codes >= 301 + return None + + headers = {k: v for k, v in s3_response_error.headers} + operation_name = s3_response_error.operation_name + if operation_name is not None: + service_model = self._client.meta.service_model + shape = service_model.operation_model(operation_name).output_shape + else: + shape = None + + response_dict = { + 'headers': botocore.awsrequest.HeadersDict(headers), + 'status_code': status_code, + 'body': s3_response_error.body, + } + parsed_response = self._client._response_parser.parse( + response_dict, shape=shape + ) + + error_code = parsed_response.get("Error", {}).get("Code") + error_class = self._client.exceptions.from_code(error_code) + return error_class(parsed_response, operation_name=operation_name) + + +class FakeRawResponse(BytesIO): + def stream(self, amt=1024, decode_content=None): + while True: + chunk = self.read(amt) + if not chunk: + break + yield chunk + + +class BotocoreCRTCredentialsWrapper: + def __init__(self, resolved_botocore_credentials): + self._resolved_credentials = resolved_botocore_credentials + + def __call__(self): + credentials = self._get_credentials().get_frozen_credentials() + return AwsCredentials( + credentials.access_key, credentials.secret_key, credentials.token + ) + + def to_crt_credentials_provider(self): + return AwsCredentialsProvider.new_delegate(self) + + def _get_credentials(self): + if self._resolved_credentials is None: + raise NoCredentialsError() + return self._resolved_credentials + + +class CRTTransferCoordinator: + """A helper class for managing CRTTransferFuture""" + + def __init__( + self, transfer_id=None, s3_request=None, exception_translator=None + ): + self.transfer_id = transfer_id + self._exception_translator = exception_translator + self._s3_request = s3_request + self._lock = threading.Lock() + self._exception = None + self._crt_future = None + self._done_event = threading.Event() + + @property + def s3_request(self): + return self._s3_request + + def set_done_callbacks_complete(self): + self._done_event.set() + + def wait_until_on_done_callbacks_complete(self, timeout=None): + self._done_event.wait(timeout) + + def set_exception(self, exception, override=False): + with self._lock: + if not self.done() or override: + self._exception = exception + + def cancel(self): + if self._s3_request: + self._s3_request.cancel() + + def result(self, timeout=None): + if self._exception: + raise self._exception + try: + self._crt_future.result(timeout) + except KeyboardInterrupt: + self.cancel() + self._crt_future.result(timeout) + raise + except Exception as e: + self.handle_exception(e) + finally: + if self._s3_request: + self._s3_request = None + + def handle_exception(self, exc): + translated_exc = None + if self._exception_translator: + try: + translated_exc = self._exception_translator(exc) + except Exception as e: + # Bail out if we hit an issue translating + # and raise the original error. + logger.debug("Unable to translate exception.", exc_info=e) + pass + if translated_exc is not None: + raise translated_exc from exc + else: + raise exc + + def done(self): + if self._crt_future is None: + return False + return self._crt_future.done() + + def set_s3_request(self, s3_request): + self._s3_request = s3_request + self._crt_future = self._s3_request.finished_future + + +class S3ClientArgsCreator: + def __init__(self, crt_request_serializer, os_utils): + self._request_serializer = crt_request_serializer + self._os_utils = os_utils + + def get_make_request_args( + self, request_type, call_args, coordinator, future, on_done_after_calls + ): + request_args_handler = getattr( + self, + f'_get_make_request_args_{request_type}', + self._default_get_make_request_args, + ) + return request_args_handler( + request_type=request_type, + call_args=call_args, + coordinator=coordinator, + future=future, + on_done_before_calls=[], + on_done_after_calls=on_done_after_calls, + ) + + def get_crt_callback( + self, + future, + callback_type, + before_subscribers=None, + after_subscribers=None, + ): + def invoke_all_callbacks(*args, **kwargs): + callbacks_list = [] + if before_subscribers is not None: + callbacks_list += before_subscribers + callbacks_list += get_callbacks(future, callback_type) + if after_subscribers is not None: + callbacks_list += after_subscribers + for callback in callbacks_list: + # The get_callbacks helper will set the first augment + # by keyword, the other augments need to be set by keyword + # as well + if callback_type == "progress": + callback(bytes_transferred=args[0]) + else: + callback(*args, **kwargs) + + return invoke_all_callbacks + + def _get_make_request_args_put_object( + self, + request_type, + call_args, + coordinator, + future, + on_done_before_calls, + on_done_after_calls, + ): + send_filepath = None + if isinstance(call_args.fileobj, str): + send_filepath = call_args.fileobj + data_len = self._os_utils.get_file_size(send_filepath) + call_args.extra_args["ContentLength"] = data_len + else: + call_args.extra_args["Body"] = call_args.fileobj + + checksum_algorithm = call_args.extra_args.pop( + 'ChecksumAlgorithm', 'CRC32' + ).upper() + checksum_config = awscrt.s3.S3ChecksumConfig( + algorithm=awscrt.s3.S3ChecksumAlgorithm[checksum_algorithm], + location=awscrt.s3.S3ChecksumLocation.TRAILER, + ) + # Suppress botocore's automatic MD5 calculation by setting an override + # value that will get deleted in the BotocoreCRTRequestSerializer. + # As part of the CRT S3 request, we request the CRT S3 client to + # automatically add trailing checksums to its uploads. + call_args.extra_args["ContentMD5"] = "override-to-be-removed" + + make_request_args = self._default_get_make_request_args( + request_type=request_type, + call_args=call_args, + coordinator=coordinator, + future=future, + on_done_before_calls=on_done_before_calls, + on_done_after_calls=on_done_after_calls, + ) + make_request_args['send_filepath'] = send_filepath + make_request_args['checksum_config'] = checksum_config + return make_request_args + + def _get_make_request_args_get_object( + self, + request_type, + call_args, + coordinator, + future, + on_done_before_calls, + on_done_after_calls, + ): + recv_filepath = None + on_body = None + checksum_config = awscrt.s3.S3ChecksumConfig(validate_response=True) + if isinstance(call_args.fileobj, str): + final_filepath = call_args.fileobj + recv_filepath = self._os_utils.get_temp_filename(final_filepath) + on_done_before_calls.append( + RenameTempFileHandler( + coordinator, final_filepath, recv_filepath, self._os_utils + ) + ) + else: + on_body = OnBodyFileObjWriter(call_args.fileobj) + + make_request_args = self._default_get_make_request_args( + request_type=request_type, + call_args=call_args, + coordinator=coordinator, + future=future, + on_done_before_calls=on_done_before_calls, + on_done_after_calls=on_done_after_calls, + ) + make_request_args['recv_filepath'] = recv_filepath + make_request_args['on_body'] = on_body + make_request_args['checksum_config'] = checksum_config + return make_request_args + + def _default_get_make_request_args( + self, + request_type, + call_args, + coordinator, + future, + on_done_before_calls, + on_done_after_calls, + ): + make_request_args = { + 'request': self._request_serializer.serialize_http_request( + request_type, future + ), + 'type': getattr( + S3RequestType, request_type.upper(), S3RequestType.DEFAULT + ), + 'on_done': self.get_crt_callback( + future, 'done', on_done_before_calls, on_done_after_calls + ), + 'on_progress': self.get_crt_callback(future, 'progress'), + } + + # For DEFAULT requests, CRT requires the official S3 operation name. + # So transform string like "delete_object" -> "DeleteObject". + if make_request_args['type'] == S3RequestType.DEFAULT: + make_request_args['operation_name'] = ''.join( + x.title() for x in request_type.split('_') + ) + + arn_handler = _S3ArnParamHandler() + if ( + accesspoint_arn_details := arn_handler.handle_arn(call_args.bucket) + ) and accesspoint_arn_details['region'] == "": + # Configure our region to `*` to propogate in `x-amz-region-set` + # for multi-region support in MRAP accesspoints. + make_request_args['signing_config'] = AwsSigningConfig( + algorithm=AwsSigningAlgorithm.V4_ASYMMETRIC, + region="*", + ) + call_args.bucket = accesspoint_arn_details['resource_name'] + elif is_s3express_bucket(call_args.bucket): + make_request_args['signing_config'] = AwsSigningConfig( + algorithm=AwsSigningAlgorithm.V4_S3EXPRESS + ) + return make_request_args + + +class RenameTempFileHandler: + def __init__(self, coordinator, final_filename, temp_filename, osutil): + self._coordinator = coordinator + self._final_filename = final_filename + self._temp_filename = temp_filename + self._osutil = osutil + + def __call__(self, **kwargs): + error = kwargs['error'] + if error: + self._osutil.remove_file(self._temp_filename) + else: + try: + self._osutil.rename_file( + self._temp_filename, self._final_filename + ) + except Exception as e: + self._osutil.remove_file(self._temp_filename) + # the CRT future has done already at this point + self._coordinator.set_exception(e) + + +class AfterDoneHandler: + def __init__(self, coordinator): + self._coordinator = coordinator + + def __call__(self, **kwargs): + self._coordinator.set_done_callbacks_complete() + + +class OnBodyFileObjWriter: + def __init__(self, fileobj): + self._fileobj = fileobj + + def __call__(self, chunk, **kwargs): + self._fileobj.write(chunk) + + +class _S3ArnParamHandler: + """Partial port of S3ArnParamHandler from botocore. + + This is used to make a determination on MRAP accesspoints for signing + purposes. This should be safe to remove once we properly integrate auth + resolution from Botocore into the CRT transfer integration. + """ + + _RESOURCE_REGEX = re.compile( + r'^(?Paccesspoint|outpost)[/:](?P.+)$' + ) + + def __init__(self): + self._arn_parser = ArnParser() + + def handle_arn(self, bucket): + arn_details = self._get_arn_details_from_bucket(bucket) + if arn_details is None: + return + if arn_details['resource_type'] == 'accesspoint': + return arn_details + + def _get_arn_details_from_bucket(self, bucket): + try: + arn_details = self._arn_parser.parse_arn(bucket) + self._add_resource_type_and_name(arn_details) + return arn_details + except InvalidArnException: + pass + return None + + def _add_resource_type_and_name(self, arn_details): + match = self._RESOURCE_REGEX.match(arn_details['resource']) + if match: + arn_details['resource_type'] = match.group('resource_type') + arn_details['resource_name'] = match.group('resource_name') diff --git a/venv/lib/python3.10/site-packages/s3transfer/delete.py b/venv/lib/python3.10/site-packages/s3transfer/delete.py new file mode 100644 index 0000000000000000000000000000000000000000..74084d312a7d603c3016fb424940e775ee2f9333 --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/delete.py @@ -0,0 +1,71 @@ +# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +from s3transfer.tasks import SubmissionTask, Task + + +class DeleteSubmissionTask(SubmissionTask): + """Task for submitting tasks to execute an object deletion.""" + + def _submit(self, client, request_executor, transfer_future, **kwargs): + """ + :param client: The client associated with the transfer manager + + :type config: s3transfer.manager.TransferConfig + :param config: The transfer config associated with the transfer + manager + + :type osutil: s3transfer.utils.OSUtil + :param osutil: The os utility associated to the transfer manager + + :type request_executor: s3transfer.futures.BoundedExecutor + :param request_executor: The request executor associated with the + transfer manager + + :type transfer_future: s3transfer.futures.TransferFuture + :param transfer_future: The transfer future associated with the + transfer request that tasks are being submitted for + """ + call_args = transfer_future.meta.call_args + + self._transfer_coordinator.submit( + request_executor, + DeleteObjectTask( + transfer_coordinator=self._transfer_coordinator, + main_kwargs={ + 'client': client, + 'bucket': call_args.bucket, + 'key': call_args.key, + 'extra_args': call_args.extra_args, + }, + is_final=True, + ), + ) + + +class DeleteObjectTask(Task): + def _main(self, client, bucket, key, extra_args): + """ + + :param client: The S3 client to use when calling DeleteObject + + :type bucket: str + :param bucket: The name of the bucket. + + :type key: str + :param key: The name of the object to delete. + + :type extra_args: dict + :param extra_args: Extra arguments to pass to the DeleteObject call. + + """ + client.delete_object(Bucket=bucket, Key=key, **extra_args) diff --git a/venv/lib/python3.10/site-packages/s3transfer/download.py b/venv/lib/python3.10/site-packages/s3transfer/download.py new file mode 100644 index 0000000000000000000000000000000000000000..e1a9cf0e9af97db7c36070f2e1cf4dafeec6d18c --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/download.py @@ -0,0 +1,788 @@ +# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +import heapq +import logging +import threading + +from s3transfer.compat import seekable +from s3transfer.exceptions import RetriesExceededError +from s3transfer.futures import IN_MEMORY_DOWNLOAD_TAG +from s3transfer.tasks import SubmissionTask, Task +from s3transfer.utils import ( + S3_RETRYABLE_DOWNLOAD_ERRORS, + CountCallbackInvoker, + DeferredOpenFile, + FunctionContainer, + StreamReaderProgress, + calculate_num_parts, + calculate_range_parameter, + get_callbacks, + invoke_progress_callbacks, +) + +logger = logging.getLogger(__name__) + + +class DownloadOutputManager: + """Base manager class for handling various types of files for downloads + + This class is typically used for the DownloadSubmissionTask class to help + determine the following: + + * Provides the fileobj to write to downloads to + * Get a task to complete once everything downloaded has been written + + The answers/implementations differ for the various types of file outputs + that may be accepted. All implementations must subclass and override + public methods from this class. + """ + + def __init__(self, osutil, transfer_coordinator, io_executor): + self._osutil = osutil + self._transfer_coordinator = transfer_coordinator + self._io_executor = io_executor + + @classmethod + def is_compatible(cls, download_target, osutil): + """Determines if the target for the download is compatible with manager + + :param download_target: The target for which the upload will write + data to. + + :param osutil: The os utility to be used for the transfer + + :returns: True if the manager can handle the type of target specified + otherwise returns False. + """ + raise NotImplementedError('must implement is_compatible()') + + def get_download_task_tag(self): + """Get the tag (if any) to associate all GetObjectTasks + + :rtype: s3transfer.futures.TaskTag + :returns: The tag to associate all GetObjectTasks with + """ + return None + + def get_fileobj_for_io_writes(self, transfer_future): + """Get file-like object to use for io writes in the io executor + + :type transfer_future: s3transfer.futures.TransferFuture + :param transfer_future: The future associated with upload request + + returns: A file-like object to write to + """ + raise NotImplementedError('must implement get_fileobj_for_io_writes()') + + def queue_file_io_task(self, fileobj, data, offset): + """Queue IO write for submission to the IO executor. + + This method accepts an IO executor and information about the + downloaded data, and handles submitting this to the IO executor. + + This method may defer submission to the IO executor if necessary. + + """ + self._transfer_coordinator.submit( + self._io_executor, self.get_io_write_task(fileobj, data, offset) + ) + + def get_io_write_task(self, fileobj, data, offset): + """Get an IO write task for the requested set of data + + This task can be ran immediately or be submitted to the IO executor + for it to run. + + :type fileobj: file-like object + :param fileobj: The file-like object to write to + + :type data: bytes + :param data: The data to write out + + :type offset: integer + :param offset: The offset to write the data to in the file-like object + + :returns: An IO task to be used to write data to a file-like object + """ + return IOWriteTask( + self._transfer_coordinator, + main_kwargs={ + 'fileobj': fileobj, + 'data': data, + 'offset': offset, + }, + ) + + def get_final_io_task(self): + """Get the final io task to complete the download + + This is needed because based on the architecture of the TransferManager + the final tasks will be sent to the IO executor, but the executor + needs a final task for it to signal that the transfer is done and + all done callbacks can be run. + + :rtype: s3transfer.tasks.Task + :returns: A final task to completed in the io executor + """ + raise NotImplementedError('must implement get_final_io_task()') + + def _get_fileobj_from_filename(self, filename): + f = DeferredOpenFile( + filename, mode='wb', open_function=self._osutil.open + ) + # Make sure the file gets closed and we remove the temporary file + # if anything goes wrong during the process. + self._transfer_coordinator.add_failure_cleanup(f.close) + return f + + +class DownloadFilenameOutputManager(DownloadOutputManager): + def __init__(self, osutil, transfer_coordinator, io_executor): + super().__init__(osutil, transfer_coordinator, io_executor) + self._final_filename = None + self._temp_filename = None + self._temp_fileobj = None + + @classmethod + def is_compatible(cls, download_target, osutil): + return isinstance(download_target, str) + + def get_fileobj_for_io_writes(self, transfer_future): + fileobj = transfer_future.meta.call_args.fileobj + self._final_filename = fileobj + self._temp_filename = self._osutil.get_temp_filename(fileobj) + self._temp_fileobj = self._get_temp_fileobj() + return self._temp_fileobj + + def get_final_io_task(self): + # A task to rename the file from the temporary file to its final + # location is needed. This should be the last task needed to complete + # the download. + return IORenameFileTask( + transfer_coordinator=self._transfer_coordinator, + main_kwargs={ + 'fileobj': self._temp_fileobj, + 'final_filename': self._final_filename, + 'osutil': self._osutil, + }, + is_final=True, + ) + + def _get_temp_fileobj(self): + f = self._get_fileobj_from_filename(self._temp_filename) + self._transfer_coordinator.add_failure_cleanup( + self._osutil.remove_file, self._temp_filename + ) + return f + + +class DownloadSeekableOutputManager(DownloadOutputManager): + @classmethod + def is_compatible(cls, download_target, osutil): + return seekable(download_target) + + def get_fileobj_for_io_writes(self, transfer_future): + # Return the fileobj provided to the future. + return transfer_future.meta.call_args.fileobj + + def get_final_io_task(self): + # This task will serve the purpose of signaling when all of the io + # writes have finished so done callbacks can be called. + return CompleteDownloadNOOPTask( + transfer_coordinator=self._transfer_coordinator + ) + + +class DownloadNonSeekableOutputManager(DownloadOutputManager): + def __init__( + self, osutil, transfer_coordinator, io_executor, defer_queue=None + ): + super().__init__(osutil, transfer_coordinator, io_executor) + if defer_queue is None: + defer_queue = DeferQueue() + self._defer_queue = defer_queue + self._io_submit_lock = threading.Lock() + + @classmethod + def is_compatible(cls, download_target, osutil): + return hasattr(download_target, 'write') + + def get_download_task_tag(self): + return IN_MEMORY_DOWNLOAD_TAG + + def get_fileobj_for_io_writes(self, transfer_future): + return transfer_future.meta.call_args.fileobj + + def get_final_io_task(self): + return CompleteDownloadNOOPTask( + transfer_coordinator=self._transfer_coordinator + ) + + def queue_file_io_task(self, fileobj, data, offset): + with self._io_submit_lock: + writes = self._defer_queue.request_writes(offset, data) + for write in writes: + data = write['data'] + logger.debug( + "Queueing IO offset %s for fileobj: %s", + write['offset'], + fileobj, + ) + super().queue_file_io_task(fileobj, data, offset) + + def get_io_write_task(self, fileobj, data, offset): + return IOStreamingWriteTask( + self._transfer_coordinator, + main_kwargs={ + 'fileobj': fileobj, + 'data': data, + }, + ) + + +class DownloadSpecialFilenameOutputManager(DownloadNonSeekableOutputManager): + def __init__( + self, osutil, transfer_coordinator, io_executor, defer_queue=None + ): + super().__init__( + osutil, transfer_coordinator, io_executor, defer_queue + ) + self._fileobj = None + + @classmethod + def is_compatible(cls, download_target, osutil): + return isinstance(download_target, str) and osutil.is_special_file( + download_target + ) + + def get_fileobj_for_io_writes(self, transfer_future): + filename = transfer_future.meta.call_args.fileobj + self._fileobj = self._get_fileobj_from_filename(filename) + return self._fileobj + + def get_final_io_task(self): + # Make sure the file gets closed once the transfer is done. + return IOCloseTask( + transfer_coordinator=self._transfer_coordinator, + is_final=True, + main_kwargs={'fileobj': self._fileobj}, + ) + + +class DownloadSubmissionTask(SubmissionTask): + """Task for submitting tasks to execute a download""" + + def _get_download_output_manager_cls(self, transfer_future, osutil): + """Retrieves a class for managing output for a download + + :type transfer_future: s3transfer.futures.TransferFuture + :param transfer_future: The transfer future for the request + + :type osutil: s3transfer.utils.OSUtils + :param osutil: The os utility associated to the transfer + + :rtype: class of DownloadOutputManager + :returns: The appropriate class to use for managing a specific type of + input for downloads. + """ + download_manager_resolver_chain = [ + DownloadSpecialFilenameOutputManager, + DownloadFilenameOutputManager, + DownloadSeekableOutputManager, + DownloadNonSeekableOutputManager, + ] + + fileobj = transfer_future.meta.call_args.fileobj + for download_manager_cls in download_manager_resolver_chain: + if download_manager_cls.is_compatible(fileobj, osutil): + return download_manager_cls + raise RuntimeError( + f'Output {fileobj} of type: {type(fileobj)} is not supported.' + ) + + def _submit( + self, + client, + config, + osutil, + request_executor, + io_executor, + transfer_future, + bandwidth_limiter=None, + ): + """ + :param client: The client associated with the transfer manager + + :type config: s3transfer.manager.TransferConfig + :param config: The transfer config associated with the transfer + manager + + :type osutil: s3transfer.utils.OSUtil + :param osutil: The os utility associated to the transfer manager + + :type request_executor: s3transfer.futures.BoundedExecutor + :param request_executor: The request executor associated with the + transfer manager + + :type io_executor: s3transfer.futures.BoundedExecutor + :param io_executor: The io executor associated with the + transfer manager + + :type transfer_future: s3transfer.futures.TransferFuture + :param transfer_future: The transfer future associated with the + transfer request that tasks are being submitted for + + :type bandwidth_limiter: s3transfer.bandwidth.BandwidthLimiter + :param bandwidth_limiter: The bandwidth limiter to use when + downloading streams + """ + if transfer_future.meta.size is None: + # If a size was not provided figure out the size for the + # user. + response = client.head_object( + Bucket=transfer_future.meta.call_args.bucket, + Key=transfer_future.meta.call_args.key, + **transfer_future.meta.call_args.extra_args, + ) + transfer_future.meta.provide_transfer_size( + response['ContentLength'] + ) + + download_output_manager = self._get_download_output_manager_cls( + transfer_future, osutil + )(osutil, self._transfer_coordinator, io_executor) + + # If it is greater than threshold do a ranged download, otherwise + # do a regular GetObject download. + if transfer_future.meta.size < config.multipart_threshold: + self._submit_download_request( + client, + config, + osutil, + request_executor, + io_executor, + download_output_manager, + transfer_future, + bandwidth_limiter, + ) + else: + self._submit_ranged_download_request( + client, + config, + osutil, + request_executor, + io_executor, + download_output_manager, + transfer_future, + bandwidth_limiter, + ) + + def _submit_download_request( + self, + client, + config, + osutil, + request_executor, + io_executor, + download_output_manager, + transfer_future, + bandwidth_limiter, + ): + call_args = transfer_future.meta.call_args + + # Get a handle to the file that will be used for writing downloaded + # contents + fileobj = download_output_manager.get_fileobj_for_io_writes( + transfer_future + ) + + # Get the needed callbacks for the task + progress_callbacks = get_callbacks(transfer_future, 'progress') + + # Get any associated tags for the get object task. + get_object_tag = download_output_manager.get_download_task_tag() + + # Get the final io task to run once the download is complete. + final_task = download_output_manager.get_final_io_task() + + # Submit the task to download the object. + self._transfer_coordinator.submit( + request_executor, + ImmediatelyWriteIOGetObjectTask( + transfer_coordinator=self._transfer_coordinator, + main_kwargs={ + 'client': client, + 'bucket': call_args.bucket, + 'key': call_args.key, + 'fileobj': fileobj, + 'extra_args': call_args.extra_args, + 'callbacks': progress_callbacks, + 'max_attempts': config.num_download_attempts, + 'download_output_manager': download_output_manager, + 'io_chunksize': config.io_chunksize, + 'bandwidth_limiter': bandwidth_limiter, + }, + done_callbacks=[final_task], + ), + tag=get_object_tag, + ) + + def _submit_ranged_download_request( + self, + client, + config, + osutil, + request_executor, + io_executor, + download_output_manager, + transfer_future, + bandwidth_limiter, + ): + call_args = transfer_future.meta.call_args + + # Get the needed progress callbacks for the task + progress_callbacks = get_callbacks(transfer_future, 'progress') + + # Get a handle to the file that will be used for writing downloaded + # contents + fileobj = download_output_manager.get_fileobj_for_io_writes( + transfer_future + ) + + # Determine the number of parts + part_size = config.multipart_chunksize + num_parts = calculate_num_parts(transfer_future.meta.size, part_size) + + # Get any associated tags for the get object task. + get_object_tag = download_output_manager.get_download_task_tag() + + # Callback invoker to submit the final io task once all downloads + # are complete. + finalize_download_invoker = CountCallbackInvoker( + self._get_final_io_task_submission_callback( + download_output_manager, io_executor + ) + ) + for i in range(num_parts): + # Calculate the range parameter + range_parameter = calculate_range_parameter( + part_size, i, num_parts + ) + + # Inject the Range parameter to the parameters to be passed in + # as extra args + extra_args = {'Range': range_parameter} + extra_args.update(call_args.extra_args) + finalize_download_invoker.increment() + # Submit the ranged downloads + self._transfer_coordinator.submit( + request_executor, + GetObjectTask( + transfer_coordinator=self._transfer_coordinator, + main_kwargs={ + 'client': client, + 'bucket': call_args.bucket, + 'key': call_args.key, + 'fileobj': fileobj, + 'extra_args': extra_args, + 'callbacks': progress_callbacks, + 'max_attempts': config.num_download_attempts, + 'start_index': i * part_size, + 'download_output_manager': download_output_manager, + 'io_chunksize': config.io_chunksize, + 'bandwidth_limiter': bandwidth_limiter, + }, + done_callbacks=[finalize_download_invoker.decrement], + ), + tag=get_object_tag, + ) + finalize_download_invoker.finalize() + + def _get_final_io_task_submission_callback( + self, download_manager, io_executor + ): + final_task = download_manager.get_final_io_task() + return FunctionContainer( + self._transfer_coordinator.submit, io_executor, final_task + ) + + def _calculate_range_param(self, part_size, part_index, num_parts): + # Used to calculate the Range parameter + start_range = part_index * part_size + if part_index == num_parts - 1: + end_range = '' + else: + end_range = start_range + part_size - 1 + range_param = f'bytes={start_range}-{end_range}' + return range_param + + +class GetObjectTask(Task): + def _main( + self, + client, + bucket, + key, + fileobj, + extra_args, + callbacks, + max_attempts, + download_output_manager, + io_chunksize, + start_index=0, + bandwidth_limiter=None, + ): + """Downloads an object and places content into io queue + + :param client: The client to use when calling GetObject + :param bucket: The bucket to download from + :param key: The key to download from + :param fileobj: The file handle to write content to + :param exta_args: Any extra arguments to include in GetObject request + :param callbacks: List of progress callbacks to invoke on download + :param max_attempts: The number of retries to do when downloading + :param download_output_manager: The download output manager associated + with the current download. + :param io_chunksize: The size of each io chunk to read from the + download stream and queue in the io queue. + :param start_index: The location in the file to start writing the + content of the key to. + :param bandwidth_limiter: The bandwidth limiter to use when throttling + the downloading of data in streams. + """ + last_exception = None + for i in range(max_attempts): + try: + current_index = start_index + response = client.get_object( + Bucket=bucket, Key=key, **extra_args + ) + streaming_body = StreamReaderProgress( + response['Body'], callbacks + ) + if bandwidth_limiter: + streaming_body = ( + bandwidth_limiter.get_bandwith_limited_stream( + streaming_body, self._transfer_coordinator + ) + ) + + chunks = DownloadChunkIterator(streaming_body, io_chunksize) + for chunk in chunks: + # If the transfer is done because of a cancellation + # or error somewhere else, stop trying to submit more + # data to be written and break out of the download. + if not self._transfer_coordinator.done(): + self._handle_io( + download_output_manager, + fileobj, + chunk, + current_index, + ) + current_index += len(chunk) + else: + return + return + except S3_RETRYABLE_DOWNLOAD_ERRORS as e: + logger.debug( + "Retrying exception caught (%s), " + "retrying request, (attempt %s / %s)", + e, + i, + max_attempts, + exc_info=True, + ) + last_exception = e + # Also invoke the progress callbacks to indicate that we + # are trying to download the stream again and all progress + # for this GetObject has been lost. + invoke_progress_callbacks( + callbacks, start_index - current_index + ) + continue + raise RetriesExceededError(last_exception) + + def _handle_io(self, download_output_manager, fileobj, chunk, index): + download_output_manager.queue_file_io_task(fileobj, chunk, index) + + +class ImmediatelyWriteIOGetObjectTask(GetObjectTask): + """GetObjectTask that immediately writes to the provided file object + + This is useful for downloads where it is known only one thread is + downloading the object so there is no reason to go through the + overhead of using an IO queue and executor. + """ + + def _handle_io(self, download_output_manager, fileobj, chunk, index): + task = download_output_manager.get_io_write_task(fileobj, chunk, index) + task() + + +class IOWriteTask(Task): + def _main(self, fileobj, data, offset): + """Pulls off an io queue to write contents to a file + + :param fileobj: The file handle to write content to + :param data: The data to write + :param offset: The offset to write the data to. + """ + fileobj.seek(offset) + fileobj.write(data) + + +class IOStreamingWriteTask(Task): + """Task for writing data to a non-seekable stream.""" + + def _main(self, fileobj, data): + """Write data to a fileobj. + + Data will be written directly to the fileobj without + any prior seeking. + + :param fileobj: The fileobj to write content to + :param data: The data to write + + """ + fileobj.write(data) + + +class IORenameFileTask(Task): + """A task to rename a temporary file to its final filename + + :param fileobj: The file handle that content was written to. + :param final_filename: The final name of the file to rename to + upon completion of writing the contents. + :param osutil: OS utility + """ + + def _main(self, fileobj, final_filename, osutil): + fileobj.close() + osutil.rename_file(fileobj.name, final_filename) + + +class IOCloseTask(Task): + """A task to close out a file once the download is complete. + + :param fileobj: The fileobj to close. + """ + + def _main(self, fileobj): + fileobj.close() + + +class CompleteDownloadNOOPTask(Task): + """A NOOP task to serve as an indicator that the download is complete + + Note that the default for is_final is set to True because this should + always be the last task. + """ + + def __init__( + self, + transfer_coordinator, + main_kwargs=None, + pending_main_kwargs=None, + done_callbacks=None, + is_final=True, + ): + super().__init__( + transfer_coordinator=transfer_coordinator, + main_kwargs=main_kwargs, + pending_main_kwargs=pending_main_kwargs, + done_callbacks=done_callbacks, + is_final=is_final, + ) + + def _main(self): + pass + + +class DownloadChunkIterator: + def __init__(self, body, chunksize): + """Iterator to chunk out a downloaded S3 stream + + :param body: A readable file-like object + :param chunksize: The amount to read each time + """ + self._body = body + self._chunksize = chunksize + self._num_reads = 0 + + def __iter__(self): + return self + + def __next__(self): + chunk = self._body.read(self._chunksize) + self._num_reads += 1 + if chunk: + return chunk + elif self._num_reads == 1: + # Even though the response may have not had any + # content, we still want to account for an empty object's + # existence so return the empty chunk for that initial + # read. + return chunk + raise StopIteration() + + next = __next__ + + +class DeferQueue: + """IO queue that defers write requests until they are queued sequentially. + + This class is used to track IO data for a *single* fileobj. + + You can send data to this queue, and it will defer any IO write requests + until it has the next contiguous block available (starting at 0). + + """ + + def __init__(self): + self._writes = [] + self._pending_offsets = set() + self._next_offset = 0 + + def request_writes(self, offset, data): + """Request any available writes given new incoming data. + + You call this method by providing new data along with the + offset associated with the data. If that new data unlocks + any contiguous writes that can now be submitted, this + method will return all applicable writes. + + This is done with 1 method call so you don't have to + make two method calls (put(), get()) which acquires a lock + each method call. + + """ + if offset < self._next_offset: + # This is a request for a write that we've already + # seen. This can happen in the event of a retry + # where if we retry at at offset N/2, we'll requeue + # offsets 0-N/2 again. + return [] + writes = [] + if offset in self._pending_offsets: + # We've already queued this offset so this request is + # a duplicate. In this case we should ignore + # this request and prefer what's already queued. + return [] + heapq.heappush(self._writes, (offset, data)) + self._pending_offsets.add(offset) + while self._writes and self._writes[0][0] == self._next_offset: + next_write = heapq.heappop(self._writes) + writes.append({'offset': next_write[0], 'data': next_write[1]}) + self._pending_offsets.remove(next_write[0]) + self._next_offset += len(next_write[1]) + return writes diff --git a/venv/lib/python3.10/site-packages/s3transfer/exceptions.py b/venv/lib/python3.10/site-packages/s3transfer/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..6150fe650daf99e5d12341ba128e6dec30b8e953 --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/exceptions.py @@ -0,0 +1,37 @@ +# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +from concurrent.futures import CancelledError + + +class RetriesExceededError(Exception): + def __init__(self, last_exception, msg='Max Retries Exceeded'): + super().__init__(msg) + self.last_exception = last_exception + + +class S3UploadFailedError(Exception): + pass + + +class InvalidSubscriberMethodError(Exception): + pass + + +class TransferNotDoneError(Exception): + pass + + +class FatalError(CancelledError): + """A CancelledError raised from an error in the TransferManager""" + + pass diff --git a/venv/lib/python3.10/site-packages/s3transfer/futures.py b/venv/lib/python3.10/site-packages/s3transfer/futures.py new file mode 100644 index 0000000000000000000000000000000000000000..68775d04e93d51dbc571d9d093eb3092962946f1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/futures.py @@ -0,0 +1,603 @@ +# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +import copy +import logging +import sys +import threading +from collections import namedtuple +from concurrent import futures + +from s3transfer.compat import MAXINT +from s3transfer.exceptions import CancelledError, TransferNotDoneError +from s3transfer.utils import FunctionContainer, TaskSemaphore + +logger = logging.getLogger(__name__) + + +class BaseTransferFuture: + @property + def meta(self): + """The metadata associated to the TransferFuture""" + raise NotImplementedError('meta') + + def done(self): + """Determines if a TransferFuture has completed + + :returns: True if completed. False, otherwise. + """ + raise NotImplementedError('done()') + + def result(self): + """Waits until TransferFuture is done and returns the result + + If the TransferFuture succeeded, it will return the result. If the + TransferFuture failed, it will raise the exception associated to the + failure. + """ + raise NotImplementedError('result()') + + def cancel(self): + """Cancels the request associated with the TransferFuture""" + raise NotImplementedError('cancel()') + + +class BaseTransferMeta: + @property + def call_args(self): + """The call args used in the transfer request""" + raise NotImplementedError('call_args') + + @property + def transfer_id(self): + """The unique id of the transfer""" + raise NotImplementedError('transfer_id') + + @property + def user_context(self): + """A dictionary that requesters can store data in""" + raise NotImplementedError('user_context') + + +class TransferFuture(BaseTransferFuture): + def __init__(self, meta=None, coordinator=None): + """The future associated to a submitted transfer request + + :type meta: TransferMeta + :param meta: The metadata associated to the request. This object + is visible to the requester. + + :type coordinator: TransferCoordinator + :param coordinator: The coordinator associated to the request. This + object is not visible to the requester. + """ + self._meta = meta + if meta is None: + self._meta = TransferMeta() + + self._coordinator = coordinator + if coordinator is None: + self._coordinator = TransferCoordinator() + + @property + def meta(self): + return self._meta + + def done(self): + return self._coordinator.done() + + def result(self): + try: + # Usually the result() method blocks until the transfer is done, + # however if a KeyboardInterrupt is raised we want want to exit + # out of this and propagate the exception. + return self._coordinator.result() + except KeyboardInterrupt as e: + self.cancel() + raise e + + def cancel(self): + self._coordinator.cancel() + + def set_exception(self, exception): + """Sets the exception on the future.""" + if not self.done(): + raise TransferNotDoneError( + 'set_exception can only be called once the transfer is ' + 'complete.' + ) + self._coordinator.set_exception(exception, override=True) + + +class TransferMeta(BaseTransferMeta): + """Holds metadata about the TransferFuture""" + + def __init__(self, call_args=None, transfer_id=None): + self._call_args = call_args + self._transfer_id = transfer_id + self._size = None + self._user_context = {} + + @property + def call_args(self): + """The call args used in the transfer request""" + return self._call_args + + @property + def transfer_id(self): + """The unique id of the transfer""" + return self._transfer_id + + @property + def size(self): + """The size of the transfer request if known""" + return self._size + + @property + def user_context(self): + """A dictionary that requesters can store data in""" + return self._user_context + + def provide_transfer_size(self, size): + """A method to provide the size of a transfer request + + By providing this value, the TransferManager will not try to + call HeadObject or use the use OS to determine the size of the + transfer. + """ + self._size = size + + +class TransferCoordinator: + """A helper class for managing TransferFuture""" + + def __init__(self, transfer_id=None): + self.transfer_id = transfer_id + self._status = 'not-started' + self._result = None + self._exception = None + self._associated_futures = set() + self._failure_cleanups = [] + self._done_callbacks = [] + self._done_event = threading.Event() + self._lock = threading.Lock() + self._associated_futures_lock = threading.Lock() + self._done_callbacks_lock = threading.Lock() + self._failure_cleanups_lock = threading.Lock() + + def __repr__(self): + return f'{self.__class__.__name__}(transfer_id={self.transfer_id})' + + @property + def exception(self): + return self._exception + + @property + def associated_futures(self): + """The list of futures associated to the inprogress TransferFuture + + Once the transfer finishes this list becomes empty as the transfer + is considered done and there should be no running futures left. + """ + with self._associated_futures_lock: + # We return a copy of the list because we do not want to + # processing the returned list while another thread is adding + # more futures to the actual list. + return copy.copy(self._associated_futures) + + @property + def failure_cleanups(self): + """The list of callbacks to call when the TransferFuture fails""" + return self._failure_cleanups + + @property + def status(self): + """The status of the TransferFuture + + The currently supported states are: + * not-started - Has yet to start. If in this state, a transfer + can be canceled immediately and nothing will happen. + * queued - SubmissionTask is about to submit tasks + * running - Is inprogress. In-progress as of now means that + the SubmissionTask that runs the transfer is being executed. So + there is no guarantee any transfer requests had been made to + S3 if this state is reached. + * cancelled - Was cancelled + * failed - An exception other than CancelledError was thrown + * success - No exceptions were thrown and is done. + """ + return self._status + + def set_result(self, result): + """Set a result for the TransferFuture + + Implies that the TransferFuture succeeded. This will always set a + result because it is invoked on the final task where there is only + ever one final task and it is ran at the very end of a transfer + process. So if a result is being set for this final task, the transfer + succeeded even if something came a long and canceled the transfer + on the final task. + """ + with self._lock: + self._exception = None + self._result = result + self._status = 'success' + + def set_exception(self, exception, override=False): + """Set an exception for the TransferFuture + + Implies the TransferFuture failed. + + :param exception: The exception that cause the transfer to fail. + :param override: If True, override any existing state. + """ + with self._lock: + if not self.done() or override: + self._exception = exception + self._status = 'failed' + + def result(self): + """Waits until TransferFuture is done and returns the result + + If the TransferFuture succeeded, it will return the result. If the + TransferFuture failed, it will raise the exception associated to the + failure. + """ + # Doing a wait() with no timeout cannot be interrupted in python2 but + # can be interrupted in python3 so we just wait with the largest + # possible value integer value, which is on the scale of billions of + # years... + self._done_event.wait(MAXINT) + + # Once done waiting, raise an exception if present or return the + # final result. + if self._exception: + raise self._exception + return self._result + + def cancel(self, msg='', exc_type=CancelledError): + """Cancels the TransferFuture + + :param msg: The message to attach to the cancellation + :param exc_type: The type of exception to set for the cancellation + """ + with self._lock: + if not self.done(): + should_announce_done = False + logger.debug('%s cancel(%s) called', self, msg) + self._exception = exc_type(msg) + if self._status == 'not-started': + should_announce_done = True + self._status = 'cancelled' + if should_announce_done: + self.announce_done() + + def set_status_to_queued(self): + """Sets the TransferFutrue's status to running""" + self._transition_to_non_done_state('queued') + + def set_status_to_running(self): + """Sets the TransferFuture's status to running""" + self._transition_to_non_done_state('running') + + def _transition_to_non_done_state(self, desired_state): + with self._lock: + if self.done(): + raise RuntimeError( + f'Unable to transition from done state {self.status} to non-done ' + f'state {desired_state}.' + ) + self._status = desired_state + + def submit(self, executor, task, tag=None): + """Submits a task to a provided executor + + :type executor: s3transfer.futures.BoundedExecutor + :param executor: The executor to submit the callable to + + :type task: s3transfer.tasks.Task + :param task: The task to submit to the executor + + :type tag: s3transfer.futures.TaskTag + :param tag: A tag to associate to the submitted task + + :rtype: concurrent.futures.Future + :returns: A future representing the submitted task + """ + logger.debug( + f"Submitting task {task} to executor {executor} for transfer request: {self.transfer_id}." + ) + future = executor.submit(task, tag=tag) + # Add this created future to the list of associated future just + # in case it is needed during cleanups. + self.add_associated_future(future) + future.add_done_callback( + FunctionContainer(self.remove_associated_future, future) + ) + return future + + def done(self): + """Determines if a TransferFuture has completed + + :returns: False if status is equal to 'failed', 'cancelled', or + 'success'. True, otherwise + """ + return self.status in ['failed', 'cancelled', 'success'] + + def add_associated_future(self, future): + """Adds a future to be associated with the TransferFuture""" + with self._associated_futures_lock: + self._associated_futures.add(future) + + def remove_associated_future(self, future): + """Removes a future's association to the TransferFuture""" + with self._associated_futures_lock: + self._associated_futures.remove(future) + + def add_done_callback(self, function, *args, **kwargs): + """Add a done callback to be invoked when transfer is done""" + with self._done_callbacks_lock: + self._done_callbacks.append( + FunctionContainer(function, *args, **kwargs) + ) + + def add_failure_cleanup(self, function, *args, **kwargs): + """Adds a callback to call upon failure""" + with self._failure_cleanups_lock: + self._failure_cleanups.append( + FunctionContainer(function, *args, **kwargs) + ) + + def announce_done(self): + """Announce that future is done running and run associated callbacks + + This will run any failure cleanups if the transfer failed if not + they have not been run, allows the result() to be unblocked, and will + run any done callbacks associated to the TransferFuture if they have + not already been ran. + """ + if self.status != 'success': + self._run_failure_cleanups() + self._done_event.set() + self._run_done_callbacks() + + def _run_done_callbacks(self): + # Run the callbacks and remove the callbacks from the internal + # list so they do not get ran again if done is announced more than + # once. + with self._done_callbacks_lock: + self._run_callbacks(self._done_callbacks) + self._done_callbacks = [] + + def _run_failure_cleanups(self): + # Run the cleanup callbacks and remove the callbacks from the internal + # list so they do not get ran again if done is announced more than + # once. + with self._failure_cleanups_lock: + self._run_callbacks(self.failure_cleanups) + self._failure_cleanups = [] + + def _run_callbacks(self, callbacks): + for callback in callbacks: + self._run_callback(callback) + + def _run_callback(self, callback): + try: + callback() + # We do not want a callback interrupting the process, especially + # in the failure cleanups. So log and catch, the exception. + except Exception: + logger.debug(f"Exception raised in {callback}.", exc_info=True) + + +class BoundedExecutor: + EXECUTOR_CLS = futures.ThreadPoolExecutor + + def __init__( + self, max_size, max_num_threads, tag_semaphores=None, executor_cls=None + ): + """An executor implementation that has a maximum queued up tasks + + The executor will block if the number of tasks that have been + submitted and is currently working on is past its maximum. + + :params max_size: The maximum number of inflight futures. An inflight + future means that the task is either queued up or is currently + being executed. A size of None or 0 means that the executor will + have no bound in terms of the number of inflight futures. + + :params max_num_threads: The maximum number of threads the executor + uses. + + :type tag_semaphores: dict + :params tag_semaphores: A dictionary where the key is the name of the + tag and the value is the semaphore to use when limiting the + number of tasks the executor is processing at a time. + + :type executor_cls: BaseExecutor + :param underlying_executor_cls: The executor class that + get bounded by this executor. If None is provided, the + concurrent.futures.ThreadPoolExecutor class is used. + """ + self._max_num_threads = max_num_threads + if executor_cls is None: + executor_cls = self.EXECUTOR_CLS + self._executor = executor_cls(max_workers=self._max_num_threads) + self._semaphore = TaskSemaphore(max_size) + self._tag_semaphores = tag_semaphores + + def submit(self, task, tag=None, block=True): + """Submit a task to complete + + :type task: s3transfer.tasks.Task + :param task: The task to run __call__ on + + + :type tag: s3transfer.futures.TaskTag + :param tag: An optional tag to associate to the task. This + is used to override which semaphore to use. + + :type block: boolean + :param block: True if to wait till it is possible to submit a task. + False, if not to wait and raise an error if not able to submit + a task. + + :returns: The future associated to the submitted task + """ + semaphore = self._semaphore + # If a tag was provided, use the semaphore associated to that + # tag. + if tag: + semaphore = self._tag_semaphores[tag] + + # Call acquire on the semaphore. + acquire_token = semaphore.acquire(task.transfer_id, block) + # Create a callback to invoke when task is done in order to call + # release on the semaphore. + release_callback = FunctionContainer( + semaphore.release, task.transfer_id, acquire_token + ) + # Submit the task to the underlying executor. + future = ExecutorFuture(self._executor.submit(task)) + # Add the Semaphore.release() callback to the future such that + # it is invoked once the future completes. + future.add_done_callback(release_callback) + return future + + def shutdown(self, wait=True): + self._executor.shutdown(wait) + + +class ExecutorFuture: + def __init__(self, future): + """A future returned from the executor + + Currently, it is just a wrapper around a concurrent.futures.Future. + However, this can eventually grow to implement the needed functionality + of concurrent.futures.Future if we move off of the library and not + affect the rest of the codebase. + + :type future: concurrent.futures.Future + :param future: The underlying future + """ + self._future = future + + def result(self): + return self._future.result() + + def add_done_callback(self, fn): + """Adds a callback to be completed once future is done + + :param fn: A callable that takes no arguments. Note that is different + than concurrent.futures.Future.add_done_callback that requires + a single argument for the future. + """ + + # The done callback for concurrent.futures.Future will always pass a + # the future in as the only argument. So we need to create the + # proper signature wrapper that will invoke the callback provided. + def done_callback(future_passed_to_callback): + return fn() + + self._future.add_done_callback(done_callback) + + def done(self): + return self._future.done() + + +class BaseExecutor: + """Base Executor class implementation needed to work with s3transfer""" + + def __init__(self, max_workers=None): + pass + + def submit(self, fn, *args, **kwargs): + raise NotImplementedError('submit()') + + def shutdown(self, wait=True): + raise NotImplementedError('shutdown()') + + +class NonThreadedExecutor(BaseExecutor): + """A drop-in replacement non-threaded version of ThreadPoolExecutor""" + + def submit(self, fn, *args, **kwargs): + future = NonThreadedExecutorFuture() + try: + result = fn(*args, **kwargs) + future.set_result(result) + except Exception: + e, tb = sys.exc_info()[1:] + logger.debug( + 'Setting exception for %s to %s with traceback %s', + future, + e, + tb, + ) + future.set_exception_info(e, tb) + return future + + def shutdown(self, wait=True): + pass + + +class NonThreadedExecutorFuture: + """The Future returned from NonThreadedExecutor + + Note that this future is **not** thread-safe as it is being used + from the context of a non-threaded environment. + """ + + def __init__(self): + self._result = None + self._exception = None + self._traceback = None + self._done = False + self._done_callbacks = [] + + def set_result(self, result): + self._result = result + self._set_done() + + def set_exception_info(self, exception, traceback): + self._exception = exception + self._traceback = traceback + self._set_done() + + def result(self, timeout=None): + if self._exception: + raise self._exception.with_traceback(self._traceback) + return self._result + + def _set_done(self): + self._done = True + for done_callback in self._done_callbacks: + self._invoke_done_callback(done_callback) + self._done_callbacks = [] + + def _invoke_done_callback(self, done_callback): + return done_callback(self) + + def done(self): + return self._done + + def add_done_callback(self, fn): + if self._done: + self._invoke_done_callback(fn) + else: + self._done_callbacks.append(fn) + + +TaskTag = namedtuple('TaskTag', ['name']) + +IN_MEMORY_UPLOAD_TAG = TaskTag('in_memory_upload') +IN_MEMORY_DOWNLOAD_TAG = TaskTag('in_memory_download') diff --git a/venv/lib/python3.10/site-packages/s3transfer/manager.py b/venv/lib/python3.10/site-packages/s3transfer/manager.py new file mode 100644 index 0000000000000000000000000000000000000000..8db9a411a460380d2be5cfe804860b61f48c28cf --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/manager.py @@ -0,0 +1,736 @@ +# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +import copy +import logging +import re +import threading + +from s3transfer.bandwidth import BandwidthLimiter, LeakyBucket +from s3transfer.constants import ALLOWED_DOWNLOAD_ARGS, KB, MB +from s3transfer.copies import CopySubmissionTask +from s3transfer.delete import DeleteSubmissionTask +from s3transfer.download import DownloadSubmissionTask +from s3transfer.exceptions import CancelledError, FatalError +from s3transfer.futures import ( + IN_MEMORY_DOWNLOAD_TAG, + IN_MEMORY_UPLOAD_TAG, + BoundedExecutor, + TransferCoordinator, + TransferFuture, + TransferMeta, +) +from s3transfer.upload import UploadSubmissionTask +from s3transfer.utils import ( + CallArgs, + OSUtils, + SlidingWindowSemaphore, + TaskSemaphore, + add_s3express_defaults, + get_callbacks, + signal_not_transferring, + signal_transferring, +) + +logger = logging.getLogger(__name__) + + +class TransferConfig: + def __init__( + self, + multipart_threshold=8 * MB, + multipart_chunksize=8 * MB, + max_request_concurrency=10, + max_submission_concurrency=5, + max_request_queue_size=1000, + max_submission_queue_size=1000, + max_io_queue_size=1000, + io_chunksize=256 * KB, + num_download_attempts=5, + max_in_memory_upload_chunks=10, + max_in_memory_download_chunks=10, + max_bandwidth=None, + ): + """Configurations for the transfer manager + + :param multipart_threshold: The threshold for which multipart + transfers occur. + + :param max_request_concurrency: The maximum number of S3 API + transfer-related requests that can happen at a time. + + :param max_submission_concurrency: The maximum number of threads + processing a call to a TransferManager method. Processing a + call usually entails determining which S3 API requests that need + to be enqueued, but does **not** entail making any of the + S3 API data transferring requests needed to perform the transfer. + The threads controlled by ``max_request_concurrency`` is + responsible for that. + + :param multipart_chunksize: The size of each transfer if a request + becomes a multipart transfer. + + :param max_request_queue_size: The maximum amount of S3 API requests + that can be queued at a time. + + :param max_submission_queue_size: The maximum amount of + TransferManager method calls that can be queued at a time. + + :param max_io_queue_size: The maximum amount of read parts that + can be queued to be written to disk per download. The default + size for each elementin this queue is 8 KB. + + :param io_chunksize: The max size of each chunk in the io queue. + Currently, this is size used when reading from the downloaded + stream as well. + + :param num_download_attempts: The number of download attempts that + will be tried upon errors with downloading an object in S3. Note + that these retries account for errors that occur when streaming + down the data from s3 (i.e. socket errors and read timeouts that + occur after receiving an OK response from s3). + Other retryable exceptions such as throttling errors and 5xx errors + are already retried by botocore (this default is 5). The + ``num_download_attempts`` does not take into account the + number of exceptions retried by botocore. + + :param max_in_memory_upload_chunks: The number of chunks that can + be stored in memory at a time for all ongoing upload requests. + This pertains to chunks of data that need to be stored in memory + during an upload if the data is sourced from a file-like object. + The total maximum memory footprint due to a in-memory upload + chunks is roughly equal to: + + max_in_memory_upload_chunks * multipart_chunksize + + max_submission_concurrency * multipart_chunksize + + ``max_submission_concurrency`` has an affect on this value because + for each thread pulling data off of a file-like object, they may + be waiting with a single read chunk to be submitted for upload + because the ``max_in_memory_upload_chunks`` value has been reached + by the threads making the upload request. + + :param max_in_memory_download_chunks: The number of chunks that can + be buffered in memory and **not** in the io queue at a time for all + ongoing download requests. This pertains specifically to file-like + objects that cannot be seeked. The total maximum memory footprint + due to a in-memory download chunks is roughly equal to: + + max_in_memory_download_chunks * multipart_chunksize + + :param max_bandwidth: The maximum bandwidth that will be consumed + in uploading and downloading file content. The value is in terms of + bytes per second. + """ + self.multipart_threshold = multipart_threshold + self.multipart_chunksize = multipart_chunksize + self.max_request_concurrency = max_request_concurrency + self.max_submission_concurrency = max_submission_concurrency + self.max_request_queue_size = max_request_queue_size + self.max_submission_queue_size = max_submission_queue_size + self.max_io_queue_size = max_io_queue_size + self.io_chunksize = io_chunksize + self.num_download_attempts = num_download_attempts + self.max_in_memory_upload_chunks = max_in_memory_upload_chunks + self.max_in_memory_download_chunks = max_in_memory_download_chunks + self.max_bandwidth = max_bandwidth + self._validate_attrs_are_nonzero() + + def _validate_attrs_are_nonzero(self): + for attr, attr_val in self.__dict__.items(): + if attr_val is not None and attr_val <= 0: + raise ValueError( + f'Provided parameter {attr} of value {attr_val} must ' + 'be greater than 0.' + ) + + +class TransferManager: + ALLOWED_DOWNLOAD_ARGS = ALLOWED_DOWNLOAD_ARGS + + ALLOWED_UPLOAD_ARGS = [ + 'ACL', + 'CacheControl', + 'ChecksumAlgorithm', + 'ContentDisposition', + 'ContentEncoding', + 'ContentLanguage', + 'ContentType', + 'ExpectedBucketOwner', + 'Expires', + 'GrantFullControl', + 'GrantRead', + 'GrantReadACP', + 'GrantWriteACP', + 'Metadata', + 'ObjectLockLegalHoldStatus', + 'ObjectLockMode', + 'ObjectLockRetainUntilDate', + 'RequestPayer', + 'ServerSideEncryption', + 'StorageClass', + 'SSECustomerAlgorithm', + 'SSECustomerKey', + 'SSECustomerKeyMD5', + 'SSEKMSKeyId', + 'SSEKMSEncryptionContext', + 'Tagging', + 'WebsiteRedirectLocation', + ] + + ALLOWED_COPY_ARGS = ALLOWED_UPLOAD_ARGS + [ + 'CopySourceIfMatch', + 'CopySourceIfModifiedSince', + 'CopySourceIfNoneMatch', + 'CopySourceIfUnmodifiedSince', + 'CopySourceSSECustomerAlgorithm', + 'CopySourceSSECustomerKey', + 'CopySourceSSECustomerKeyMD5', + 'MetadataDirective', + 'TaggingDirective', + ] + + ALLOWED_DELETE_ARGS = [ + 'MFA', + 'VersionId', + 'RequestPayer', + 'ExpectedBucketOwner', + ] + + VALIDATE_SUPPORTED_BUCKET_VALUES = True + + _UNSUPPORTED_BUCKET_PATTERNS = { + 'S3 Object Lambda': re.compile( + r'^arn:(aws).*:s3-object-lambda:[a-z\-0-9]+:[0-9]{12}:' + r'accesspoint[/:][a-zA-Z0-9\-]{1,63}' + ), + } + + def __init__(self, client, config=None, osutil=None, executor_cls=None): + """A transfer manager interface for Amazon S3 + + :param client: Client to be used by the manager + :param config: TransferConfig to associate specific configurations + :param osutil: OSUtils object to use for os-related behavior when + using with transfer manager. + + :type executor_cls: s3transfer.futures.BaseExecutor + :param executor_cls: The class of executor to use with the transfer + manager. By default, concurrent.futures.ThreadPoolExecutor is used. + """ + self._client = client + self._config = config + if config is None: + self._config = TransferConfig() + self._osutil = osutil + if osutil is None: + self._osutil = OSUtils() + self._coordinator_controller = TransferCoordinatorController() + # A counter to create unique id's for each transfer submitted. + self._id_counter = 0 + + # The executor responsible for making S3 API transfer requests + self._request_executor = BoundedExecutor( + max_size=self._config.max_request_queue_size, + max_num_threads=self._config.max_request_concurrency, + tag_semaphores={ + IN_MEMORY_UPLOAD_TAG: TaskSemaphore( + self._config.max_in_memory_upload_chunks + ), + IN_MEMORY_DOWNLOAD_TAG: SlidingWindowSemaphore( + self._config.max_in_memory_download_chunks + ), + }, + executor_cls=executor_cls, + ) + + # The executor responsible for submitting the necessary tasks to + # perform the desired transfer + self._submission_executor = BoundedExecutor( + max_size=self._config.max_submission_queue_size, + max_num_threads=self._config.max_submission_concurrency, + executor_cls=executor_cls, + ) + + # There is one thread available for writing to disk. It will handle + # downloads for all files. + self._io_executor = BoundedExecutor( + max_size=self._config.max_io_queue_size, + max_num_threads=1, + executor_cls=executor_cls, + ) + + # The component responsible for limiting bandwidth usage if it + # is configured. + self._bandwidth_limiter = None + if self._config.max_bandwidth is not None: + logger.debug( + 'Setting max_bandwidth to %s', self._config.max_bandwidth + ) + leaky_bucket = LeakyBucket(self._config.max_bandwidth) + self._bandwidth_limiter = BandwidthLimiter(leaky_bucket) + + self._register_handlers() + + @property + def client(self): + return self._client + + @property + def config(self): + return self._config + + def upload(self, fileobj, bucket, key, extra_args=None, subscribers=None): + """Uploads a file to S3 + + :type fileobj: str or seekable file-like object + :param fileobj: The name of a file to upload or a seekable file-like + object to upload. It is recommended to use a filename because + file-like objects may result in higher memory usage. + + :type bucket: str + :param bucket: The name of the bucket to upload to + + :type key: str + :param key: The name of the key to upload to + + :type extra_args: dict + :param extra_args: Extra arguments that may be passed to the + client operation + + :type subscribers: list(s3transfer.subscribers.BaseSubscriber) + :param subscribers: The list of subscribers to be invoked in the + order provided based on the event emit during the process of + the transfer request. + + :rtype: s3transfer.futures.TransferFuture + :returns: Transfer future representing the upload + """ + if extra_args is None: + extra_args = {} + if subscribers is None: + subscribers = [] + self._validate_all_known_args(extra_args, self.ALLOWED_UPLOAD_ARGS) + self._validate_if_bucket_supported(bucket) + self._add_operation_defaults(bucket, extra_args) + call_args = CallArgs( + fileobj=fileobj, + bucket=bucket, + key=key, + extra_args=extra_args, + subscribers=subscribers, + ) + extra_main_kwargs = {} + if self._bandwidth_limiter: + extra_main_kwargs['bandwidth_limiter'] = self._bandwidth_limiter + return self._submit_transfer( + call_args, UploadSubmissionTask, extra_main_kwargs + ) + + def download( + self, bucket, key, fileobj, extra_args=None, subscribers=None + ): + """Downloads a file from S3 + + :type bucket: str + :param bucket: The name of the bucket to download from + + :type key: str + :param key: The name of the key to download from + + :type fileobj: str or seekable file-like object + :param fileobj: The name of a file to download or a seekable file-like + object to download. It is recommended to use a filename because + file-like objects may result in higher memory usage. + + :type extra_args: dict + :param extra_args: Extra arguments that may be passed to the + client operation + + :type subscribers: list(s3transfer.subscribers.BaseSubscriber) + :param subscribers: The list of subscribers to be invoked in the + order provided based on the event emit during the process of + the transfer request. + + :rtype: s3transfer.futures.TransferFuture + :returns: Transfer future representing the download + """ + if extra_args is None: + extra_args = {} + if subscribers is None: + subscribers = [] + self._validate_all_known_args(extra_args, self.ALLOWED_DOWNLOAD_ARGS) + self._validate_if_bucket_supported(bucket) + call_args = CallArgs( + bucket=bucket, + key=key, + fileobj=fileobj, + extra_args=extra_args, + subscribers=subscribers, + ) + extra_main_kwargs = {'io_executor': self._io_executor} + if self._bandwidth_limiter: + extra_main_kwargs['bandwidth_limiter'] = self._bandwidth_limiter + return self._submit_transfer( + call_args, DownloadSubmissionTask, extra_main_kwargs + ) + + def copy( + self, + copy_source, + bucket, + key, + extra_args=None, + subscribers=None, + source_client=None, + ): + """Copies a file in S3 + + :type copy_source: dict + :param copy_source: The name of the source bucket, key name of the + source object, and optional version ID of the source object. The + dictionary format is: + ``{'Bucket': 'bucket', 'Key': 'key', 'VersionId': 'id'}``. Note + that the ``VersionId`` key is optional and may be omitted. + + :type bucket: str + :param bucket: The name of the bucket to copy to + + :type key: str + :param key: The name of the key to copy to + + :type extra_args: dict + :param extra_args: Extra arguments that may be passed to the + client operation + + :type subscribers: a list of subscribers + :param subscribers: The list of subscribers to be invoked in the + order provided based on the event emit during the process of + the transfer request. + + :type source_client: botocore or boto3 Client + :param source_client: The client to be used for operation that + may happen at the source object. For example, this client is + used for the head_object that determines the size of the copy. + If no client is provided, the transfer manager's client is used + as the client for the source object. + + :rtype: s3transfer.futures.TransferFuture + :returns: Transfer future representing the copy + """ + if extra_args is None: + extra_args = {} + if subscribers is None: + subscribers = [] + if source_client is None: + source_client = self._client + self._validate_all_known_args(extra_args, self.ALLOWED_COPY_ARGS) + if isinstance(copy_source, dict): + self._validate_if_bucket_supported(copy_source.get('Bucket')) + self._validate_if_bucket_supported(bucket) + call_args = CallArgs( + copy_source=copy_source, + bucket=bucket, + key=key, + extra_args=extra_args, + subscribers=subscribers, + source_client=source_client, + ) + return self._submit_transfer(call_args, CopySubmissionTask) + + def delete(self, bucket, key, extra_args=None, subscribers=None): + """Delete an S3 object. + + :type bucket: str + :param bucket: The name of the bucket. + + :type key: str + :param key: The name of the S3 object to delete. + + :type extra_args: dict + :param extra_args: Extra arguments that may be passed to the + DeleteObject call. + + :type subscribers: list + :param subscribers: A list of subscribers to be invoked during the + process of the transfer request. Note that the ``on_progress`` + callback is not invoked during object deletion. + + :rtype: s3transfer.futures.TransferFuture + :return: Transfer future representing the deletion. + + """ + if extra_args is None: + extra_args = {} + if subscribers is None: + subscribers = [] + self._validate_all_known_args(extra_args, self.ALLOWED_DELETE_ARGS) + self._validate_if_bucket_supported(bucket) + call_args = CallArgs( + bucket=bucket, + key=key, + extra_args=extra_args, + subscribers=subscribers, + ) + return self._submit_transfer(call_args, DeleteSubmissionTask) + + def _validate_if_bucket_supported(self, bucket): + # s3 high level operations don't support some resources + # (eg. S3 Object Lambda) only direct API calls are available + # for such resources + if self.VALIDATE_SUPPORTED_BUCKET_VALUES: + for resource, pattern in self._UNSUPPORTED_BUCKET_PATTERNS.items(): + match = pattern.match(bucket) + if match: + raise ValueError( + f'TransferManager methods do not support {resource} ' + 'resource. Use direct client calls instead.' + ) + + def _validate_all_known_args(self, actual, allowed): + for kwarg in actual: + if kwarg not in allowed: + raise ValueError( + "Invalid extra_args key '{}', " + "must be one of: {}".format(kwarg, ', '.join(allowed)) + ) + + def _add_operation_defaults(self, bucket, extra_args): + add_s3express_defaults(bucket, extra_args) + + def _submit_transfer( + self, call_args, submission_task_cls, extra_main_kwargs=None + ): + if not extra_main_kwargs: + extra_main_kwargs = {} + + # Create a TransferFuture to return back to the user + transfer_future, components = self._get_future_with_components( + call_args + ) + + # Add any provided done callbacks to the created transfer future + # to be invoked on the transfer future being complete. + for callback in get_callbacks(transfer_future, 'done'): + components['coordinator'].add_done_callback(callback) + + # Get the main kwargs needed to instantiate the submission task + main_kwargs = self._get_submission_task_main_kwargs( + transfer_future, extra_main_kwargs + ) + + # Submit a SubmissionTask that will submit all of the necessary + # tasks needed to complete the S3 transfer. + self._submission_executor.submit( + submission_task_cls( + transfer_coordinator=components['coordinator'], + main_kwargs=main_kwargs, + ) + ) + + # Increment the unique id counter for future transfer requests + self._id_counter += 1 + + return transfer_future + + def _get_future_with_components(self, call_args): + transfer_id = self._id_counter + # Creates a new transfer future along with its components + transfer_coordinator = TransferCoordinator(transfer_id=transfer_id) + # Track the transfer coordinator for transfers to manage. + self._coordinator_controller.add_transfer_coordinator( + transfer_coordinator + ) + # Also make sure that the transfer coordinator is removed once + # the transfer completes so it does not stick around in memory. + transfer_coordinator.add_done_callback( + self._coordinator_controller.remove_transfer_coordinator, + transfer_coordinator, + ) + components = { + 'meta': TransferMeta(call_args, transfer_id=transfer_id), + 'coordinator': transfer_coordinator, + } + transfer_future = TransferFuture(**components) + return transfer_future, components + + def _get_submission_task_main_kwargs( + self, transfer_future, extra_main_kwargs + ): + main_kwargs = { + 'client': self._client, + 'config': self._config, + 'osutil': self._osutil, + 'request_executor': self._request_executor, + 'transfer_future': transfer_future, + } + main_kwargs.update(extra_main_kwargs) + return main_kwargs + + def _register_handlers(self): + # Register handlers to enable/disable callbacks on uploads. + event_name = 'request-created.s3' + self._client.meta.events.register_first( + event_name, + signal_not_transferring, + unique_id='s3upload-not-transferring', + ) + self._client.meta.events.register_last( + event_name, signal_transferring, unique_id='s3upload-transferring' + ) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, *args): + cancel = False + cancel_msg = '' + cancel_exc_type = FatalError + # If a exception was raised in the context handler, signal to cancel + # all of the inprogress futures in the shutdown. + if exc_type: + cancel = True + cancel_msg = str(exc_value) + if not cancel_msg: + cancel_msg = repr(exc_value) + # If it was a KeyboardInterrupt, the cancellation was initiated + # by the user. + if isinstance(exc_value, KeyboardInterrupt): + cancel_exc_type = CancelledError + self._shutdown(cancel, cancel_msg, cancel_exc_type) + + def shutdown(self, cancel=False, cancel_msg=''): + """Shutdown the TransferManager + + It will wait till all transfers complete before it completely shuts + down. + + :type cancel: boolean + :param cancel: If True, calls TransferFuture.cancel() for + all in-progress in transfers. This is useful if you want the + shutdown to happen quicker. + + :type cancel_msg: str + :param cancel_msg: The message to specify if canceling all in-progress + transfers. + """ + self._shutdown(cancel, cancel, cancel_msg) + + def _shutdown(self, cancel, cancel_msg, exc_type=CancelledError): + if cancel: + # Cancel all in-flight transfers if requested, before waiting + # for them to complete. + self._coordinator_controller.cancel(cancel_msg, exc_type) + try: + # Wait until there are no more in-progress transfers. This is + # wrapped in a try statement because this can be interrupted + # with a KeyboardInterrupt that needs to be caught. + self._coordinator_controller.wait() + except KeyboardInterrupt: + # If not errors were raised in the try block, the cancel should + # have no coordinators it needs to run cancel on. If there was + # an error raised in the try statement we want to cancel all of + # the inflight transfers before shutting down to speed that + # process up. + self._coordinator_controller.cancel('KeyboardInterrupt()') + raise + finally: + # Shutdown all of the executors. + self._submission_executor.shutdown() + self._request_executor.shutdown() + self._io_executor.shutdown() + + +class TransferCoordinatorController: + def __init__(self): + """Abstraction to control all transfer coordinators + + This abstraction allows the manager to wait for inprogress transfers + to complete and cancel all inprogress transfers. + """ + self._lock = threading.Lock() + self._tracked_transfer_coordinators = set() + + @property + def tracked_transfer_coordinators(self): + """The set of transfer coordinators being tracked""" + with self._lock: + # We return a copy because the set is mutable and if you were to + # iterate over the set, it may be changing in length due to + # additions and removals of transfer coordinators. + return copy.copy(self._tracked_transfer_coordinators) + + def add_transfer_coordinator(self, transfer_coordinator): + """Adds a transfer coordinator of a transfer to be canceled if needed + + :type transfer_coordinator: s3transfer.futures.TransferCoordinator + :param transfer_coordinator: The transfer coordinator for the + particular transfer + """ + with self._lock: + self._tracked_transfer_coordinators.add(transfer_coordinator) + + def remove_transfer_coordinator(self, transfer_coordinator): + """Remove a transfer coordinator from cancellation consideration + + Typically, this method is invoked by the transfer coordinator itself + to remove its self when it completes its transfer. + + :type transfer_coordinator: s3transfer.futures.TransferCoordinator + :param transfer_coordinator: The transfer coordinator for the + particular transfer + """ + with self._lock: + self._tracked_transfer_coordinators.remove(transfer_coordinator) + + def cancel(self, msg='', exc_type=CancelledError): + """Cancels all inprogress transfers + + This cancels the inprogress transfers by calling cancel() on all + tracked transfer coordinators. + + :param msg: The message to pass on to each transfer coordinator that + gets cancelled. + + :param exc_type: The type of exception to set for the cancellation + """ + for transfer_coordinator in self.tracked_transfer_coordinators: + transfer_coordinator.cancel(msg, exc_type) + + def wait(self): + """Wait until there are no more inprogress transfers + + This will not stop when failures are encountered and not propagate any + of these errors from failed transfers, but it can be interrupted with + a KeyboardInterrupt. + """ + try: + transfer_coordinator = None + for transfer_coordinator in self.tracked_transfer_coordinators: + transfer_coordinator.result() + except KeyboardInterrupt: + logger.debug('Received KeyboardInterrupt in wait()') + # If Keyboard interrupt is raised while waiting for + # the result, then exit out of the wait and raise the + # exception + if transfer_coordinator: + logger.debug( + 'On KeyboardInterrupt was waiting for %s', + transfer_coordinator, + ) + raise + except Exception: + # A general exception could have been thrown because + # of result(). We just want to ignore this and continue + # because we at least know that the transfer coordinator + # has completed. + pass diff --git a/venv/lib/python3.10/site-packages/s3transfer/processpool.py b/venv/lib/python3.10/site-packages/s3transfer/processpool.py new file mode 100644 index 0000000000000000000000000000000000000000..318f1e7f0ec44a38d6a7eb9883542ef43d918e3b --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/processpool.py @@ -0,0 +1,1009 @@ +# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +"""Speeds up S3 throughput by using processes + +Getting Started +=============== + +The :class:`ProcessPoolDownloader` can be used to download a single file by +calling :meth:`ProcessPoolDownloader.download_file`: + +.. code:: python + + from s3transfer.processpool import ProcessPoolDownloader + + with ProcessPoolDownloader() as downloader: + downloader.download_file('mybucket', 'mykey', 'myfile') + + +This snippet downloads the S3 object located in the bucket ``mybucket`` at the +key ``mykey`` to the local file ``myfile``. Any errors encountered during the +transfer are not propagated. To determine if a transfer succeeded or +failed, use the `Futures`_ interface. + + +The :class:`ProcessPoolDownloader` can be used to download multiple files as +well: + +.. code:: python + + from s3transfer.processpool import ProcessPoolDownloader + + with ProcessPoolDownloader() as downloader: + downloader.download_file('mybucket', 'mykey', 'myfile') + downloader.download_file('mybucket', 'myotherkey', 'myotherfile') + + +When running this snippet, the downloading of ``mykey`` and ``myotherkey`` +happen in parallel. The first ``download_file`` call does not block the +second ``download_file`` call. The snippet blocks when exiting +the context manager and blocks until both downloads are complete. + +Alternatively, the ``ProcessPoolDownloader`` can be instantiated +and explicitly be shutdown using :meth:`ProcessPoolDownloader.shutdown`: + +.. code:: python + + from s3transfer.processpool import ProcessPoolDownloader + + downloader = ProcessPoolDownloader() + downloader.download_file('mybucket', 'mykey', 'myfile') + downloader.download_file('mybucket', 'myotherkey', 'myotherfile') + downloader.shutdown() + + +For this code snippet, the call to ``shutdown`` blocks until both +downloads are complete. + + +Additional Parameters +===================== + +Additional parameters can be provided to the ``download_file`` method: + +* ``extra_args``: A dictionary containing any additional client arguments + to include in the + `GetObject `_ + API request. For example: + + .. code:: python + + from s3transfer.processpool import ProcessPoolDownloader + + with ProcessPoolDownloader() as downloader: + downloader.download_file( + 'mybucket', 'mykey', 'myfile', + extra_args={'VersionId': 'myversion'}) + + +* ``expected_size``: By default, the downloader will make a HeadObject + call to determine the size of the object. To opt-out of this additional + API call, you can provide the size of the object in bytes: + + .. code:: python + + from s3transfer.processpool import ProcessPoolDownloader + + MB = 1024 * 1024 + with ProcessPoolDownloader() as downloader: + downloader.download_file( + 'mybucket', 'mykey', 'myfile', expected_size=2 * MB) + + +Futures +======= + +When ``download_file`` is called, it immediately returns a +:class:`ProcessPoolTransferFuture`. The future can be used to poll the state +of a particular transfer. To get the result of the download, +call :meth:`ProcessPoolTransferFuture.result`. The method blocks +until the transfer completes, whether it succeeds or fails. For example: + +.. code:: python + + from s3transfer.processpool import ProcessPoolDownloader + + with ProcessPoolDownloader() as downloader: + future = downloader.download_file('mybucket', 'mykey', 'myfile') + print(future.result()) + + +If the download succeeds, the future returns ``None``: + +.. code:: python + + None + + +If the download fails, the exception causing the failure is raised. For +example, if ``mykey`` did not exist, the following error would be raised + + +.. code:: python + + botocore.exceptions.ClientError: An error occurred (404) when calling the HeadObject operation: Not Found + + +.. note:: + + :meth:`ProcessPoolTransferFuture.result` can only be called while the + ``ProcessPoolDownloader`` is running (e.g. before calling ``shutdown`` or + inside the context manager). + + +Process Pool Configuration +========================== + +By default, the downloader has the following configuration options: + +* ``multipart_threshold``: The threshold size for performing ranged downloads + in bytes. By default, ranged downloads happen for S3 objects that are + greater than or equal to 8 MB in size. + +* ``multipart_chunksize``: The size of each ranged download in bytes. By + default, the size of each ranged download is 8 MB. + +* ``max_request_processes``: The maximum number of processes used to download + S3 objects. By default, the maximum is 10 processes. + + +To change the default configuration, use the :class:`ProcessTransferConfig`: + +.. code:: python + + from s3transfer.processpool import ProcessPoolDownloader + from s3transfer.processpool import ProcessTransferConfig + + config = ProcessTransferConfig( + multipart_threshold=64 * 1024 * 1024, # 64 MB + max_request_processes=50 + ) + downloader = ProcessPoolDownloader(config=config) + + +Client Configuration +==================== + +The process pool downloader creates ``botocore`` clients on your behalf. In +order to affect how the client is created, pass the keyword arguments +that would have been used in the :meth:`botocore.Session.create_client` call: + +.. code:: python + + + from s3transfer.processpool import ProcessPoolDownloader + from s3transfer.processpool import ProcessTransferConfig + + downloader = ProcessPoolDownloader( + client_kwargs={'region_name': 'us-west-2'}) + + +This snippet ensures that all clients created by the ``ProcessPoolDownloader`` +are using ``us-west-2`` as their region. + +""" + +import collections +import contextlib +import logging +import multiprocessing +import signal +import threading +from copy import deepcopy + +import botocore.session +from botocore.config import Config + +from s3transfer.compat import MAXINT, BaseManager +from s3transfer.constants import ALLOWED_DOWNLOAD_ARGS, MB, PROCESS_USER_AGENT +from s3transfer.exceptions import CancelledError, RetriesExceededError +from s3transfer.futures import BaseTransferFuture, BaseTransferMeta +from s3transfer.utils import ( + S3_RETRYABLE_DOWNLOAD_ERRORS, + CallArgs, + OSUtils, + calculate_num_parts, + calculate_range_parameter, +) + +logger = logging.getLogger(__name__) + +SHUTDOWN_SIGNAL = 'SHUTDOWN' + +# The DownloadFileRequest tuple is submitted from the ProcessPoolDownloader +# to the GetObjectSubmitter in order for the submitter to begin submitting +# GetObjectJobs to the GetObjectWorkers. +DownloadFileRequest = collections.namedtuple( + 'DownloadFileRequest', + [ + 'transfer_id', # The unique id for the transfer + 'bucket', # The bucket to download the object from + 'key', # The key to download the object from + 'filename', # The user-requested download location + 'extra_args', # Extra arguments to provide to client calls + 'expected_size', # The user-provided expected size of the download + ], +) + +# The GetObjectJob tuple is submitted from the GetObjectSubmitter +# to the GetObjectWorkers to download the file or parts of the file. +GetObjectJob = collections.namedtuple( + 'GetObjectJob', + [ + 'transfer_id', # The unique id for the transfer + 'bucket', # The bucket to download the object from + 'key', # The key to download the object from + 'temp_filename', # The temporary file to write the content to via + # completed GetObject calls. + 'extra_args', # Extra arguments to provide to the GetObject call + 'offset', # The offset to write the content for the temp file. + 'filename', # The user-requested download location. The worker + # of final GetObjectJob will move the file located at + # temp_filename to the location of filename. + ], +) + + +@contextlib.contextmanager +def ignore_ctrl_c(): + original_handler = _add_ignore_handler_for_interrupts() + yield + signal.signal(signal.SIGINT, original_handler) + + +def _add_ignore_handler_for_interrupts(): + # Windows is unable to pickle signal.signal directly so it needs to + # be wrapped in a function defined at the module level + return signal.signal(signal.SIGINT, signal.SIG_IGN) + + +class ProcessTransferConfig: + def __init__( + self, + multipart_threshold=8 * MB, + multipart_chunksize=8 * MB, + max_request_processes=10, + ): + """Configuration for the ProcessPoolDownloader + + :param multipart_threshold: The threshold for which ranged downloads + occur. + + :param multipart_chunksize: The chunk size of each ranged download. + + :param max_request_processes: The maximum number of processes that + will be making S3 API transfer-related requests at a time. + """ + self.multipart_threshold = multipart_threshold + self.multipart_chunksize = multipart_chunksize + self.max_request_processes = max_request_processes + + +class ProcessPoolDownloader: + def __init__(self, client_kwargs=None, config=None): + """Downloads S3 objects using process pools + + :type client_kwargs: dict + :param client_kwargs: The keyword arguments to provide when + instantiating S3 clients. The arguments must match the keyword + arguments provided to the + `botocore.session.Session.create_client()` method. + + :type config: ProcessTransferConfig + :param config: Configuration for the downloader + """ + if client_kwargs is None: + client_kwargs = {} + self._client_factory = ClientFactory(client_kwargs) + + self._transfer_config = config + if config is None: + self._transfer_config = ProcessTransferConfig() + + self._download_request_queue = multiprocessing.Queue(1000) + self._worker_queue = multiprocessing.Queue(1000) + self._osutil = OSUtils() + + self._started = False + self._start_lock = threading.Lock() + + # These below are initialized in the start() method + self._manager = None + self._transfer_monitor = None + self._submitter = None + self._workers = [] + + def download_file( + self, bucket, key, filename, extra_args=None, expected_size=None + ): + """Downloads the object's contents to a file + + :type bucket: str + :param bucket: The name of the bucket to download from + + :type key: str + :param key: The name of the key to download from + + :type filename: str + :param filename: The name of a file to download to. + + :type extra_args: dict + :param extra_args: Extra arguments that may be passed to the + client operation + + :type expected_size: int + :param expected_size: The expected size in bytes of the download. If + provided, the downloader will not call HeadObject to determine the + object's size and use the provided value instead. The size is + needed to determine whether to do a multipart download. + + :rtype: s3transfer.futures.TransferFuture + :returns: Transfer future representing the download + """ + self._start_if_needed() + if extra_args is None: + extra_args = {} + self._validate_all_known_args(extra_args) + transfer_id = self._transfer_monitor.notify_new_transfer() + download_file_request = DownloadFileRequest( + transfer_id=transfer_id, + bucket=bucket, + key=key, + filename=filename, + extra_args=extra_args, + expected_size=expected_size, + ) + logger.debug( + 'Submitting download file request: %s.', download_file_request + ) + self._download_request_queue.put(download_file_request) + call_args = CallArgs( + bucket=bucket, + key=key, + filename=filename, + extra_args=extra_args, + expected_size=expected_size, + ) + future = self._get_transfer_future(transfer_id, call_args) + return future + + def shutdown(self): + """Shutdown the downloader + + It will wait till all downloads are complete before returning. + """ + self._shutdown_if_needed() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, *args): + if isinstance(exc_value, KeyboardInterrupt): + if self._transfer_monitor is not None: + self._transfer_monitor.notify_cancel_all_in_progress() + self.shutdown() + + def _start_if_needed(self): + with self._start_lock: + if not self._started: + self._start() + + def _start(self): + self._start_transfer_monitor_manager() + self._start_submitter() + self._start_get_object_workers() + self._started = True + + def _validate_all_known_args(self, provided): + for kwarg in provided: + if kwarg not in ALLOWED_DOWNLOAD_ARGS: + download_args = ', '.join(ALLOWED_DOWNLOAD_ARGS) + raise ValueError( + f"Invalid extra_args key '{kwarg}', " + f"must be one of: {download_args}" + ) + + def _get_transfer_future(self, transfer_id, call_args): + meta = ProcessPoolTransferMeta( + call_args=call_args, transfer_id=transfer_id + ) + future = ProcessPoolTransferFuture( + monitor=self._transfer_monitor, meta=meta + ) + return future + + def _start_transfer_monitor_manager(self): + logger.debug('Starting the TransferMonitorManager.') + self._manager = TransferMonitorManager() + # We do not want Ctrl-C's to cause the manager to shutdown immediately + # as worker processes will still need to communicate with it when they + # are shutting down. So instead we ignore Ctrl-C and let the manager + # be explicitly shutdown when shutting down the downloader. + self._manager.start(_add_ignore_handler_for_interrupts) + self._transfer_monitor = self._manager.TransferMonitor() + + def _start_submitter(self): + logger.debug('Starting the GetObjectSubmitter.') + self._submitter = GetObjectSubmitter( + transfer_config=self._transfer_config, + client_factory=self._client_factory, + transfer_monitor=self._transfer_monitor, + osutil=self._osutil, + download_request_queue=self._download_request_queue, + worker_queue=self._worker_queue, + ) + self._submitter.start() + + def _start_get_object_workers(self): + logger.debug( + 'Starting %s GetObjectWorkers.', + self._transfer_config.max_request_processes, + ) + for _ in range(self._transfer_config.max_request_processes): + worker = GetObjectWorker( + queue=self._worker_queue, + client_factory=self._client_factory, + transfer_monitor=self._transfer_monitor, + osutil=self._osutil, + ) + worker.start() + self._workers.append(worker) + + def _shutdown_if_needed(self): + with self._start_lock: + if self._started: + self._shutdown() + + def _shutdown(self): + self._shutdown_submitter() + self._shutdown_get_object_workers() + self._shutdown_transfer_monitor_manager() + self._started = False + + def _shutdown_transfer_monitor_manager(self): + logger.debug('Shutting down the TransferMonitorManager.') + self._manager.shutdown() + + def _shutdown_submitter(self): + logger.debug('Shutting down the GetObjectSubmitter.') + self._download_request_queue.put(SHUTDOWN_SIGNAL) + self._submitter.join() + + def _shutdown_get_object_workers(self): + logger.debug('Shutting down the GetObjectWorkers.') + for _ in self._workers: + self._worker_queue.put(SHUTDOWN_SIGNAL) + for worker in self._workers: + worker.join() + + +class ProcessPoolTransferFuture(BaseTransferFuture): + def __init__(self, monitor, meta): + """The future associated to a submitted process pool transfer request + + :type monitor: TransferMonitor + :param monitor: The monitor associated to the process pool downloader + + :type meta: ProcessPoolTransferMeta + :param meta: The metadata associated to the request. This object + is visible to the requester. + """ + self._monitor = monitor + self._meta = meta + + @property + def meta(self): + return self._meta + + def done(self): + return self._monitor.is_done(self._meta.transfer_id) + + def result(self): + try: + return self._monitor.poll_for_result(self._meta.transfer_id) + except KeyboardInterrupt: + # For the multiprocessing Manager, a thread is given a single + # connection to reuse in communicating between the thread in the + # main process and the Manager's process. If a Ctrl-C happens when + # polling for the result, it will make the main thread stop trying + # to receive from the connection, but the Manager process will not + # know that the main process has stopped trying to receive and + # will not close the connection. As a result if another message is + # sent to the Manager process, the listener in the Manager + # processes will not process the new message as it is still trying + # trying to process the previous message (that was Ctrl-C'd) and + # thus cause the thread in the main process to hang on its send. + # The only way around this is to create a new connection and send + # messages from that new connection instead. + self._monitor._connect() + self.cancel() + raise + + def cancel(self): + self._monitor.notify_exception( + self._meta.transfer_id, CancelledError() + ) + + +class ProcessPoolTransferMeta(BaseTransferMeta): + """Holds metadata about the ProcessPoolTransferFuture""" + + def __init__(self, transfer_id, call_args): + self._transfer_id = transfer_id + self._call_args = call_args + self._user_context = {} + + @property + def call_args(self): + return self._call_args + + @property + def transfer_id(self): + return self._transfer_id + + @property + def user_context(self): + return self._user_context + + +class ClientFactory: + def __init__(self, client_kwargs=None): + """Creates S3 clients for processes + + Botocore sessions and clients are not pickleable so they cannot be + inherited across Process boundaries. Instead, they must be instantiated + once a process is running. + """ + self._client_kwargs = client_kwargs + if self._client_kwargs is None: + self._client_kwargs = {} + + client_config = deepcopy(self._client_kwargs.get('config', Config())) + if not client_config.user_agent_extra: + client_config.user_agent_extra = PROCESS_USER_AGENT + else: + client_config.user_agent_extra += " " + PROCESS_USER_AGENT + self._client_kwargs['config'] = client_config + + def create_client(self): + """Create a botocore S3 client""" + return botocore.session.Session().create_client( + 's3', **self._client_kwargs + ) + + +class TransferMonitor: + def __init__(self): + """Monitors transfers for cross-process communication + + Notifications can be sent to the monitor and information can be + retrieved from the monitor for a particular transfer. This abstraction + is ran in a ``multiprocessing.managers.BaseManager`` in order to be + shared across processes. + """ + # TODO: Add logic that removes the TransferState if the transfer is + # marked as done and the reference to the future is no longer being + # held onto. Without this logic, this dictionary will continue to + # grow in size with no limit. + self._transfer_states = {} + self._id_count = 0 + self._init_lock = threading.Lock() + + def notify_new_transfer(self): + with self._init_lock: + transfer_id = self._id_count + self._transfer_states[transfer_id] = TransferState() + self._id_count += 1 + return transfer_id + + def is_done(self, transfer_id): + """Determine a particular transfer is complete + + :param transfer_id: Unique identifier for the transfer + :return: True, if done. False, otherwise. + """ + return self._transfer_states[transfer_id].done + + def notify_done(self, transfer_id): + """Notify a particular transfer is complete + + :param transfer_id: Unique identifier for the transfer + """ + self._transfer_states[transfer_id].set_done() + + def poll_for_result(self, transfer_id): + """Poll for the result of a transfer + + :param transfer_id: Unique identifier for the transfer + :return: If the transfer succeeded, it will return the result. If the + transfer failed, it will raise the exception associated to the + failure. + """ + self._transfer_states[transfer_id].wait_till_done() + exception = self._transfer_states[transfer_id].exception + if exception: + raise exception + return None + + def notify_exception(self, transfer_id, exception): + """Notify an exception was encountered for a transfer + + :param transfer_id: Unique identifier for the transfer + :param exception: The exception encountered for that transfer + """ + # TODO: Not all exceptions are pickleable so if we are running + # this in a multiprocessing.BaseManager we will want to + # make sure to update this signature to ensure pickleability of the + # arguments or have the ProxyObject do the serialization. + self._transfer_states[transfer_id].exception = exception + + def notify_cancel_all_in_progress(self): + for transfer_state in self._transfer_states.values(): + if not transfer_state.done: + transfer_state.exception = CancelledError() + + def get_exception(self, transfer_id): + """Retrieve the exception encountered for the transfer + + :param transfer_id: Unique identifier for the transfer + :return: The exception encountered for that transfer. Otherwise + if there were no exceptions, returns None. + """ + return self._transfer_states[transfer_id].exception + + def notify_expected_jobs_to_complete(self, transfer_id, num_jobs): + """Notify the amount of jobs expected for a transfer + + :param transfer_id: Unique identifier for the transfer + :param num_jobs: The number of jobs to complete the transfer + """ + self._transfer_states[transfer_id].jobs_to_complete = num_jobs + + def notify_job_complete(self, transfer_id): + """Notify that a single job is completed for a transfer + + :param transfer_id: Unique identifier for the transfer + :return: The number of jobs remaining to complete the transfer + """ + return self._transfer_states[transfer_id].decrement_jobs_to_complete() + + +class TransferState: + """Represents the current state of an individual transfer""" + + # NOTE: Ideally the TransferState object would be used directly by the + # various different abstractions in the ProcessPoolDownloader and remove + # the need for the TransferMonitor. However, it would then impose the + # constraint that two hops are required to make or get any changes in the + # state of a transfer across processes: one hop to get a proxy object for + # the TransferState and then a second hop to communicate calling the + # specific TransferState method. + def __init__(self): + self._exception = None + self._done_event = threading.Event() + self._job_lock = threading.Lock() + self._jobs_to_complete = 0 + + @property + def done(self): + return self._done_event.is_set() + + def set_done(self): + self._done_event.set() + + def wait_till_done(self): + self._done_event.wait(MAXINT) + + @property + def exception(self): + return self._exception + + @exception.setter + def exception(self, val): + self._exception = val + + @property + def jobs_to_complete(self): + return self._jobs_to_complete + + @jobs_to_complete.setter + def jobs_to_complete(self, val): + self._jobs_to_complete = val + + def decrement_jobs_to_complete(self): + with self._job_lock: + self._jobs_to_complete -= 1 + return self._jobs_to_complete + + +class TransferMonitorManager(BaseManager): + pass + + +TransferMonitorManager.register('TransferMonitor', TransferMonitor) + + +class BaseS3TransferProcess(multiprocessing.Process): + def __init__(self, client_factory): + super().__init__() + self._client_factory = client_factory + self._client = None + + def run(self): + # Clients are not pickleable so their instantiation cannot happen + # in the __init__ for processes that are created under the + # spawn method. + self._client = self._client_factory.create_client() + with ignore_ctrl_c(): + # By default these processes are ran as child processes to the + # main process. Any Ctrl-c encountered in the main process is + # propagated to the child process and interrupt it at any time. + # To avoid any potentially bad states caused from an interrupt + # (i.e. a transfer failing to notify its done or making the + # communication protocol become out of sync with the + # TransferMonitor), we ignore all Ctrl-C's and allow the main + # process to notify these child processes when to stop processing + # jobs. + self._do_run() + + def _do_run(self): + raise NotImplementedError('_do_run()') + + +class GetObjectSubmitter(BaseS3TransferProcess): + def __init__( + self, + transfer_config, + client_factory, + transfer_monitor, + osutil, + download_request_queue, + worker_queue, + ): + """Submit GetObjectJobs to fulfill a download file request + + :param transfer_config: Configuration for transfers. + :param client_factory: ClientFactory for creating S3 clients. + :param transfer_monitor: Monitor for notifying and retrieving state + of transfer. + :param osutil: OSUtils object to use for os-related behavior when + performing the transfer. + :param download_request_queue: Queue to retrieve download file + requests. + :param worker_queue: Queue to submit GetObjectJobs for workers + to perform. + """ + super().__init__(client_factory) + self._transfer_config = transfer_config + self._transfer_monitor = transfer_monitor + self._osutil = osutil + self._download_request_queue = download_request_queue + self._worker_queue = worker_queue + + def _do_run(self): + while True: + download_file_request = self._download_request_queue.get() + if download_file_request == SHUTDOWN_SIGNAL: + logger.debug('Submitter shutdown signal received.') + return + try: + self._submit_get_object_jobs(download_file_request) + except Exception as e: + logger.debug( + 'Exception caught when submitting jobs for ' + 'download file request %s: %s', + download_file_request, + e, + exc_info=True, + ) + self._transfer_monitor.notify_exception( + download_file_request.transfer_id, e + ) + self._transfer_monitor.notify_done( + download_file_request.transfer_id + ) + + def _submit_get_object_jobs(self, download_file_request): + size = self._get_size(download_file_request) + temp_filename = self._allocate_temp_file(download_file_request, size) + if size < self._transfer_config.multipart_threshold: + self._submit_single_get_object_job( + download_file_request, temp_filename + ) + else: + self._submit_ranged_get_object_jobs( + download_file_request, temp_filename, size + ) + + def _get_size(self, download_file_request): + expected_size = download_file_request.expected_size + if expected_size is None: + expected_size = self._client.head_object( + Bucket=download_file_request.bucket, + Key=download_file_request.key, + **download_file_request.extra_args, + )['ContentLength'] + return expected_size + + def _allocate_temp_file(self, download_file_request, size): + temp_filename = self._osutil.get_temp_filename( + download_file_request.filename + ) + self._osutil.allocate(temp_filename, size) + return temp_filename + + def _submit_single_get_object_job( + self, download_file_request, temp_filename + ): + self._notify_jobs_to_complete(download_file_request.transfer_id, 1) + self._submit_get_object_job( + transfer_id=download_file_request.transfer_id, + bucket=download_file_request.bucket, + key=download_file_request.key, + temp_filename=temp_filename, + offset=0, + extra_args=download_file_request.extra_args, + filename=download_file_request.filename, + ) + + def _submit_ranged_get_object_jobs( + self, download_file_request, temp_filename, size + ): + part_size = self._transfer_config.multipart_chunksize + num_parts = calculate_num_parts(size, part_size) + self._notify_jobs_to_complete( + download_file_request.transfer_id, num_parts + ) + for i in range(num_parts): + offset = i * part_size + range_parameter = calculate_range_parameter( + part_size, i, num_parts + ) + get_object_kwargs = {'Range': range_parameter} + get_object_kwargs.update(download_file_request.extra_args) + self._submit_get_object_job( + transfer_id=download_file_request.transfer_id, + bucket=download_file_request.bucket, + key=download_file_request.key, + temp_filename=temp_filename, + offset=offset, + extra_args=get_object_kwargs, + filename=download_file_request.filename, + ) + + def _submit_get_object_job(self, **get_object_job_kwargs): + self._worker_queue.put(GetObjectJob(**get_object_job_kwargs)) + + def _notify_jobs_to_complete(self, transfer_id, jobs_to_complete): + logger.debug( + 'Notifying %s job(s) to complete for transfer_id %s.', + jobs_to_complete, + transfer_id, + ) + self._transfer_monitor.notify_expected_jobs_to_complete( + transfer_id, jobs_to_complete + ) + + +class GetObjectWorker(BaseS3TransferProcess): + # TODO: It may make sense to expose these class variables as configuration + # options if users want to tweak them. + _MAX_ATTEMPTS = 5 + _IO_CHUNKSIZE = 2 * MB + + def __init__(self, queue, client_factory, transfer_monitor, osutil): + """Fulfills GetObjectJobs + + Downloads the S3 object, writes it to the specified file, and + renames the file to its final location if it completes the final + job for a particular transfer. + + :param queue: Queue for retrieving GetObjectJob's + :param client_factory: ClientFactory for creating S3 clients + :param transfer_monitor: Monitor for notifying + :param osutil: OSUtils object to use for os-related behavior when + performing the transfer. + """ + super().__init__(client_factory) + self._queue = queue + self._client_factory = client_factory + self._transfer_monitor = transfer_monitor + self._osutil = osutil + + def _do_run(self): + while True: + job = self._queue.get() + if job == SHUTDOWN_SIGNAL: + logger.debug('Worker shutdown signal received.') + return + if not self._transfer_monitor.get_exception(job.transfer_id): + self._run_get_object_job(job) + else: + logger.debug( + 'Skipping get object job %s because there was a previous ' + 'exception.', + job, + ) + remaining = self._transfer_monitor.notify_job_complete( + job.transfer_id + ) + logger.debug( + '%s jobs remaining for transfer_id %s.', + remaining, + job.transfer_id, + ) + if not remaining: + self._finalize_download( + job.transfer_id, job.temp_filename, job.filename + ) + + def _run_get_object_job(self, job): + try: + self._do_get_object( + bucket=job.bucket, + key=job.key, + temp_filename=job.temp_filename, + extra_args=job.extra_args, + offset=job.offset, + ) + except Exception as e: + logger.debug( + 'Exception caught when downloading object for ' + 'get object job %s: %s', + job, + e, + exc_info=True, + ) + self._transfer_monitor.notify_exception(job.transfer_id, e) + + def _do_get_object(self, bucket, key, extra_args, temp_filename, offset): + last_exception = None + for i in range(self._MAX_ATTEMPTS): + try: + response = self._client.get_object( + Bucket=bucket, Key=key, **extra_args + ) + self._write_to_file(temp_filename, offset, response['Body']) + return + except S3_RETRYABLE_DOWNLOAD_ERRORS as e: + logger.debug( + 'Retrying exception caught (%s), ' + 'retrying request, (attempt %s / %s)', + e, + i + 1, + self._MAX_ATTEMPTS, + exc_info=True, + ) + last_exception = e + raise RetriesExceededError(last_exception) + + def _write_to_file(self, filename, offset, body): + with open(filename, 'rb+') as f: + f.seek(offset) + chunks = iter(lambda: body.read(self._IO_CHUNKSIZE), b'') + for chunk in chunks: + f.write(chunk) + + def _finalize_download(self, transfer_id, temp_filename, filename): + if self._transfer_monitor.get_exception(transfer_id): + self._osutil.remove_file(temp_filename) + else: + self._do_file_rename(transfer_id, temp_filename, filename) + self._transfer_monitor.notify_done(transfer_id) + + def _do_file_rename(self, transfer_id, temp_filename, filename): + try: + self._osutil.rename_file(temp_filename, filename) + except Exception as e: + self._transfer_monitor.notify_exception(transfer_id, e) + self._osutil.remove_file(temp_filename) diff --git a/venv/lib/python3.10/site-packages/s3transfer/subscribers.py b/venv/lib/python3.10/site-packages/s3transfer/subscribers.py new file mode 100644 index 0000000000000000000000000000000000000000..fe773233bb3816f1edd869222b9c3db75d2afa86 --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/subscribers.py @@ -0,0 +1,94 @@ +# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +from functools import lru_cache + +from s3transfer.compat import accepts_kwargs +from s3transfer.exceptions import InvalidSubscriberMethodError + + +class BaseSubscriber: + """The base subscriber class + + It is recommended that all subscriber implementations subclass and then + override the subscription methods (i.e. on_{subsribe_type}() methods). + """ + + VALID_SUBSCRIBER_TYPES = ['queued', 'progress', 'done'] + + def __new__(cls, *args, **kwargs): + cls._validate_subscriber_methods() + return super().__new__(cls) + + @classmethod + @lru_cache + def _validate_subscriber_methods(cls): + for subscriber_type in cls.VALID_SUBSCRIBER_TYPES: + subscriber_method = getattr(cls, 'on_' + subscriber_type) + if not callable(subscriber_method): + raise InvalidSubscriberMethodError( + f'Subscriber method {subscriber_method} must be callable.' + ) + + if not accepts_kwargs(subscriber_method): + raise InvalidSubscriberMethodError( + f'Subscriber method {subscriber_method} must accept keyword ' + 'arguments (**kwargs)' + ) + + def on_queued(self, future, **kwargs): + """Callback to be invoked when transfer request gets queued + + This callback can be useful for: + + * Keeping track of how many transfers have been requested + * Providing the expected transfer size through + future.meta.provide_transfer_size() so a HeadObject would not + need to be made for copies and downloads. + + :type future: s3transfer.futures.TransferFuture + :param future: The TransferFuture representing the requested transfer. + """ + pass + + def on_progress(self, future, bytes_transferred, **kwargs): + """Callback to be invoked when progress is made on transfer + + This callback can be useful for: + + * Recording and displaying progress + + :type future: s3transfer.futures.TransferFuture + :param future: The TransferFuture representing the requested transfer. + + :type bytes_transferred: int + :param bytes_transferred: The number of bytes transferred for that + invocation of the callback. Note that a negative amount can be + provided, which usually indicates that an in-progress request + needed to be retried and thus progress was rewound. + """ + pass + + def on_done(self, future, **kwargs): + """Callback to be invoked once a transfer is done + + This callback can be useful for: + + * Recording and displaying whether the transfer succeeded or + failed using future.result() + * Running some task after the transfer completed like changing + the last modified time of a downloaded file. + + :type future: s3transfer.futures.TransferFuture + :param future: The TransferFuture representing the requested transfer. + """ + pass diff --git a/venv/lib/python3.10/site-packages/s3transfer/tasks.py b/venv/lib/python3.10/site-packages/s3transfer/tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..4183715a900860558359860839c43d6634bd94ae --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/tasks.py @@ -0,0 +1,383 @@ +# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +import copy +import logging + +from s3transfer.utils import get_callbacks + +logger = logging.getLogger(__name__) + + +class Task: + """A task associated to a TransferFuture request + + This is a base class for other classes to subclass from. All subclassed + classes must implement the main() method. + """ + + def __init__( + self, + transfer_coordinator, + main_kwargs=None, + pending_main_kwargs=None, + done_callbacks=None, + is_final=False, + ): + """ + :type transfer_coordinator: s3transfer.futures.TransferCoordinator + :param transfer_coordinator: The context associated to the + TransferFuture for which this Task is associated with. + + :type main_kwargs: dict + :param main_kwargs: The keyword args that can be immediately supplied + to the _main() method of the task + + :type pending_main_kwargs: dict + :param pending_main_kwargs: The keyword args that are depended upon + by the result from a dependent future(s). The result returned by + the future(s) will be used as the value for the keyword argument + when _main() is called. The values for each key can be: + * a single future - Once completed, its value will be the + result of that single future + * a list of futures - Once all of the futures complete, the + value used will be a list of each completed future result + value in order of when they were originally supplied. + + :type done_callbacks: list of callbacks + :param done_callbacks: A list of callbacks to call once the task is + done completing. Each callback will be called with no arguments + and will be called no matter if the task succeeds or an exception + is raised. + + :type is_final: boolean + :param is_final: True, to indicate that this task is the final task + for the TransferFuture request. By setting this value to True, it + will set the result of the entire TransferFuture to the result + returned by this task's main() method. + """ + self._transfer_coordinator = transfer_coordinator + + self._main_kwargs = main_kwargs + if self._main_kwargs is None: + self._main_kwargs = {} + + self._pending_main_kwargs = pending_main_kwargs + if pending_main_kwargs is None: + self._pending_main_kwargs = {} + + self._done_callbacks = done_callbacks + if self._done_callbacks is None: + self._done_callbacks = [] + + self._is_final = is_final + + def __repr__(self): + # These are the general main_kwarg parameters that we want to + # display in the repr. + params_to_display = [ + 'bucket', + 'key', + 'part_number', + 'final_filename', + 'transfer_future', + 'offset', + 'extra_args', + ] + main_kwargs_to_display = self._get_kwargs_with_params_to_include( + self._main_kwargs, params_to_display + ) + return f'{self.__class__.__name__}(transfer_id={self._transfer_coordinator.transfer_id}, {main_kwargs_to_display})' + + @property + def transfer_id(self): + """The id for the transfer request that the task belongs to""" + return self._transfer_coordinator.transfer_id + + def _get_kwargs_with_params_to_include(self, kwargs, include): + filtered_kwargs = {} + for param in include: + if param in kwargs: + filtered_kwargs[param] = kwargs[param] + return filtered_kwargs + + def _get_kwargs_with_params_to_exclude(self, kwargs, exclude): + filtered_kwargs = {} + for param, value in kwargs.items(): + if param in exclude: + continue + filtered_kwargs[param] = value + return filtered_kwargs + + def __call__(self): + """The callable to use when submitting a Task to an executor""" + try: + # Wait for all of futures this task depends on. + self._wait_on_dependent_futures() + # Gather up all of the main keyword arguments for main(). + # This includes the immediately provided main_kwargs and + # the values for pending_main_kwargs that source from the return + # values from the task's dependent futures. + kwargs = self._get_all_main_kwargs() + # If the task is not done (really only if some other related + # task to the TransferFuture had failed) then execute the task's + # main() method. + if not self._transfer_coordinator.done(): + return self._execute_main(kwargs) + except Exception as e: + self._log_and_set_exception(e) + finally: + # Run any done callbacks associated to the task no matter what. + for done_callback in self._done_callbacks: + done_callback() + + if self._is_final: + # If this is the final task announce that it is done if results + # are waiting on its completion. + self._transfer_coordinator.announce_done() + + def _execute_main(self, kwargs): + # Do not display keyword args that should not be printed, especially + # if they are going to make the logs hard to follow. + params_to_exclude = ['data'] + kwargs_to_display = self._get_kwargs_with_params_to_exclude( + kwargs, params_to_exclude + ) + # Log what is about to be executed. + logger.debug(f"Executing task {self} with kwargs {kwargs_to_display}") + + return_value = self._main(**kwargs) + # If the task is the final task, then set the TransferFuture's + # value to the return value from main(). + if self._is_final: + self._transfer_coordinator.set_result(return_value) + return return_value + + def _log_and_set_exception(self, exception): + # If an exception is ever thrown than set the exception for the + # entire TransferFuture. + logger.debug("Exception raised.", exc_info=True) + self._transfer_coordinator.set_exception(exception) + + def _main(self, **kwargs): + """The method that will be ran in the executor + + This method must be implemented by subclasses from Task. main() can + be implemented with any arguments decided upon by the subclass. + """ + raise NotImplementedError('_main() must be implemented') + + def _wait_on_dependent_futures(self): + # Gather all of the futures into that main() depends on. + futures_to_wait_on = [] + for _, future in self._pending_main_kwargs.items(): + # If the pending main keyword arg is a list then extend the list. + if isinstance(future, list): + futures_to_wait_on.extend(future) + # If the pending main keyword arg is a future append it to the list. + else: + futures_to_wait_on.append(future) + # Now wait for all of the futures to complete. + self._wait_until_all_complete(futures_to_wait_on) + + def _wait_until_all_complete(self, futures): + # This is a basic implementation of the concurrent.futures.wait() + # + # concurrent.futures.wait() is not used instead because of this + # reported issue: https://bugs.python.org/issue20319. + # The issue would occasionally cause multipart uploads to hang + # when wait() was called. With this approach, it avoids the + # concurrency bug by removing any association with concurrent.futures + # implementation of waiters. + logger.debug( + '%s about to wait for the following futures %s', self, futures + ) + for future in futures: + try: + logger.debug('%s about to wait for %s', self, future) + future.result() + except Exception: + # result() can also produce exceptions. We want to ignore + # these to be deferred to error handling down the road. + pass + logger.debug('%s done waiting for dependent futures', self) + + def _get_all_main_kwargs(self): + # Copy over all of the kwargs that we know is available. + kwargs = copy.copy(self._main_kwargs) + + # Iterate through the kwargs whose values are pending on the result + # of a future. + for key, pending_value in self._pending_main_kwargs.items(): + # If the value is a list of futures, iterate though the list + # appending on the result from each future. + if isinstance(pending_value, list): + result = [] + for future in pending_value: + result.append(future.result()) + # Otherwise if the pending_value is a future, just wait for it. + else: + result = pending_value.result() + # Add the retrieved value to the kwargs to be sent to the + # main() call. + kwargs[key] = result + return kwargs + + +class SubmissionTask(Task): + """A base class for any submission task + + Submission tasks are the top-level task used to submit a series of tasks + to execute a particular transfer. + """ + + def _main(self, transfer_future, **kwargs): + """ + :type transfer_future: s3transfer.futures.TransferFuture + :param transfer_future: The transfer future associated with the + transfer request that tasks are being submitted for + + :param kwargs: Any additional kwargs that you may want to pass + to the _submit() method + """ + try: + self._transfer_coordinator.set_status_to_queued() + + # Before submitting any tasks, run all of the on_queued callbacks + on_queued_callbacks = get_callbacks(transfer_future, 'queued') + for on_queued_callback in on_queued_callbacks: + on_queued_callback() + + # Once callbacks have been ran set the status to running. + self._transfer_coordinator.set_status_to_running() + + # Call the submit method to start submitting tasks to execute the + # transfer. + self._submit(transfer_future=transfer_future, **kwargs) + except BaseException as e: + # If there was an exception raised during the submission of task + # there is a chance that the final task that signals if a transfer + # is done and too run the cleanup may never have been submitted in + # the first place so we need to account accordingly. + # + # Note that BaseException is caught, instead of Exception, because + # for some implementations of executors, specifically the serial + # implementation, the SubmissionTask is directly exposed to + # KeyboardInterupts and so needs to cleanup and signal done + # for those as well. + + # Set the exception, that caused the process to fail. + self._log_and_set_exception(e) + + # Wait for all possibly associated futures that may have spawned + # from this submission task have finished before we announce the + # transfer done. + self._wait_for_all_submitted_futures_to_complete() + + # Announce the transfer as done, which will run any cleanups + # and done callbacks as well. + self._transfer_coordinator.announce_done() + + def _submit(self, transfer_future, **kwargs): + """The submission method to be implemented + + :type transfer_future: s3transfer.futures.TransferFuture + :param transfer_future: The transfer future associated with the + transfer request that tasks are being submitted for + + :param kwargs: Any additional keyword arguments you want to be passed + in + """ + raise NotImplementedError('_submit() must be implemented') + + def _wait_for_all_submitted_futures_to_complete(self): + # We want to wait for all futures that were submitted to + # complete as we do not want the cleanup callbacks or done callbacks + # to be called to early. The main problem is any task that was + # submitted may have submitted even more during its process and so + # we need to account accordingly. + + # First get all of the futures that were submitted up to this point. + submitted_futures = self._transfer_coordinator.associated_futures + while submitted_futures: + # Wait for those futures to complete. + self._wait_until_all_complete(submitted_futures) + # However, more futures may have been submitted as we waited so + # we need to check again for any more associated futures. + possibly_more_submitted_futures = ( + self._transfer_coordinator.associated_futures + ) + # If the current list of submitted futures is equal to the + # the list of associated futures for when after the wait completes, + # we can ensure no more futures were submitted in waiting on + # the current list of futures to complete ultimately meaning all + # futures that may have spawned from the original submission task + # have completed. + if submitted_futures == possibly_more_submitted_futures: + break + submitted_futures = possibly_more_submitted_futures + + +class CreateMultipartUploadTask(Task): + """Task to initiate a multipart upload""" + + def _main(self, client, bucket, key, extra_args): + """ + :param client: The client to use when calling CreateMultipartUpload + :param bucket: The name of the bucket to upload to + :param key: The name of the key to upload to + :param extra_args: A dictionary of any extra arguments that may be + used in the initialization. + + :returns: The upload id of the multipart upload + """ + # Create the multipart upload. + response = client.create_multipart_upload( + Bucket=bucket, Key=key, **extra_args + ) + upload_id = response['UploadId'] + + # Add a cleanup if the multipart upload fails at any point. + self._transfer_coordinator.add_failure_cleanup( + client.abort_multipart_upload, + Bucket=bucket, + Key=key, + UploadId=upload_id, + ) + return upload_id + + +class CompleteMultipartUploadTask(Task): + """Task to complete a multipart upload""" + + def _main(self, client, bucket, key, upload_id, parts, extra_args): + """ + :param client: The client to use when calling CompleteMultipartUpload + :param bucket: The name of the bucket to upload to + :param key: The name of the key to upload to + :param upload_id: The id of the upload + :param parts: A list of parts to use to complete the multipart upload:: + + [{'Etag': etag_value, 'PartNumber': part_number}, ...] + + Each element in the list consists of a return value from + ``UploadPartTask.main()``. + :param extra_args: A dictionary of any extra arguments that may be + used in completing the multipart transfer. + """ + client.complete_multipart_upload( + Bucket=bucket, + Key=key, + UploadId=upload_id, + MultipartUpload={'Parts': parts}, + **extra_args, + ) diff --git a/venv/lib/python3.10/site-packages/s3transfer/upload.py b/venv/lib/python3.10/site-packages/s3transfer/upload.py new file mode 100644 index 0000000000000000000000000000000000000000..0347857b5d20c7bd4faf41eb5ceef07c0ccf1b10 --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/upload.py @@ -0,0 +1,806 @@ +# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +import math +from io import BytesIO + +from s3transfer.compat import readable, seekable +from s3transfer.futures import IN_MEMORY_UPLOAD_TAG +from s3transfer.tasks import ( + CompleteMultipartUploadTask, + CreateMultipartUploadTask, + SubmissionTask, + Task, +) +from s3transfer.utils import ( + ChunksizeAdjuster, + DeferredOpenFile, + get_callbacks, + get_filtered_dict, +) + + +class AggregatedProgressCallback: + def __init__(self, callbacks, threshold=1024 * 256): + """Aggregates progress updates for every provided progress callback + + :type callbacks: A list of functions that accepts bytes_transferred + as a single argument + :param callbacks: The callbacks to invoke when threshold is reached + + :type threshold: int + :param threshold: The progress threshold in which to take the + aggregated progress and invoke the progress callback with that + aggregated progress total + """ + self._callbacks = callbacks + self._threshold = threshold + self._bytes_seen = 0 + + def __call__(self, bytes_transferred): + self._bytes_seen += bytes_transferred + if self._bytes_seen >= self._threshold: + self._trigger_callbacks() + + def flush(self): + """Flushes out any progress that has not been sent to its callbacks""" + if self._bytes_seen > 0: + self._trigger_callbacks() + + def _trigger_callbacks(self): + for callback in self._callbacks: + callback(bytes_transferred=self._bytes_seen) + self._bytes_seen = 0 + + +class InterruptReader: + """Wrapper that can interrupt reading using an error + + It uses a transfer coordinator to propagate an error if it notices + that a read is being made while the file is being read from. + + :type fileobj: file-like obj + :param fileobj: The file-like object to read from + + :type transfer_coordinator: s3transfer.futures.TransferCoordinator + :param transfer_coordinator: The transfer coordinator to use if the + reader needs to be interrupted. + """ + + def __init__(self, fileobj, transfer_coordinator): + self._fileobj = fileobj + self._transfer_coordinator = transfer_coordinator + + def read(self, amount=None): + # If there is an exception, then raise the exception. + # We raise an error instead of returning no bytes because for + # requests where the content length and md5 was sent, it will + # cause md5 mismatches and retries as there was no indication that + # the stream being read from encountered any issues. + if self._transfer_coordinator.exception: + raise self._transfer_coordinator.exception + return self._fileobj.read(amount) + + def seek(self, where, whence=0): + self._fileobj.seek(where, whence) + + def tell(self): + return self._fileobj.tell() + + def close(self): + self._fileobj.close() + + def __enter__(self): + return self + + def __exit__(self, *args, **kwargs): + self.close() + + +class UploadInputManager: + """Base manager class for handling various types of files for uploads + + This class is typically used for the UploadSubmissionTask class to help + determine the following: + + * How to determine the size of the file + * How to determine if a multipart upload is required + * How to retrieve the body for a PutObject + * How to retrieve the bodies for a set of UploadParts + + The answers/implementations differ for the various types of file inputs + that may be accepted. All implementations must subclass and override + public methods from this class. + """ + + def __init__(self, osutil, transfer_coordinator, bandwidth_limiter=None): + self._osutil = osutil + self._transfer_coordinator = transfer_coordinator + self._bandwidth_limiter = bandwidth_limiter + + @classmethod + def is_compatible(cls, upload_source): + """Determines if the source for the upload is compatible with manager + + :param upload_source: The source for which the upload will pull data + from. + + :returns: True if the manager can handle the type of source specified + otherwise returns False. + """ + raise NotImplementedError('must implement _is_compatible()') + + def stores_body_in_memory(self, operation_name): + """Whether the body it provides are stored in-memory + + :type operation_name: str + :param operation_name: The name of the client operation that the body + is being used for. Valid operation_names are ``put_object`` and + ``upload_part``. + + :rtype: boolean + :returns: True if the body returned by the manager will be stored in + memory. False if the manager will not directly store the body in + memory. + """ + raise NotImplementedError('must implement store_body_in_memory()') + + def provide_transfer_size(self, transfer_future): + """Provides the transfer size of an upload + + :type transfer_future: s3transfer.futures.TransferFuture + :param transfer_future: The future associated with upload request + """ + raise NotImplementedError('must implement provide_transfer_size()') + + def requires_multipart_upload(self, transfer_future, config): + """Determines where a multipart upload is required + + :type transfer_future: s3transfer.futures.TransferFuture + :param transfer_future: The future associated with upload request + + :type config: s3transfer.manager.TransferConfig + :param config: The config associated to the transfer manager + + :rtype: boolean + :returns: True, if the upload should be multipart based on + configuration and size. False, otherwise. + """ + raise NotImplementedError('must implement requires_multipart_upload()') + + def get_put_object_body(self, transfer_future): + """Returns the body to use for PutObject + + :type transfer_future: s3transfer.futures.TransferFuture + :param transfer_future: The future associated with upload request + + :type config: s3transfer.manager.TransferConfig + :param config: The config associated to the transfer manager + + :rtype: s3transfer.utils.ReadFileChunk + :returns: A ReadFileChunk including all progress callbacks + associated with the transfer future. + """ + raise NotImplementedError('must implement get_put_object_body()') + + def yield_upload_part_bodies(self, transfer_future, chunksize): + """Yields the part number and body to use for each UploadPart + + :type transfer_future: s3transfer.futures.TransferFuture + :param transfer_future: The future associated with upload request + + :type chunksize: int + :param chunksize: The chunksize to use for this upload. + + :rtype: int, s3transfer.utils.ReadFileChunk + :returns: Yields the part number and the ReadFileChunk including all + progress callbacks associated with the transfer future for that + specific yielded part. + """ + raise NotImplementedError('must implement yield_upload_part_bodies()') + + def _wrap_fileobj(self, fileobj): + fileobj = InterruptReader(fileobj, self._transfer_coordinator) + if self._bandwidth_limiter: + fileobj = self._bandwidth_limiter.get_bandwith_limited_stream( + fileobj, self._transfer_coordinator, enabled=False + ) + return fileobj + + def _get_progress_callbacks(self, transfer_future): + callbacks = get_callbacks(transfer_future, 'progress') + # We only want to be wrapping the callbacks if there are callbacks to + # invoke because we do not want to be doing any unnecessary work if + # there are no callbacks to invoke. + if callbacks: + return [AggregatedProgressCallback(callbacks)] + return [] + + def _get_close_callbacks(self, aggregated_progress_callbacks): + return [callback.flush for callback in aggregated_progress_callbacks] + + +class UploadFilenameInputManager(UploadInputManager): + """Upload utility for filenames""" + + @classmethod + def is_compatible(cls, upload_source): + return isinstance(upload_source, str) + + def stores_body_in_memory(self, operation_name): + return False + + def provide_transfer_size(self, transfer_future): + transfer_future.meta.provide_transfer_size( + self._osutil.get_file_size(transfer_future.meta.call_args.fileobj) + ) + + def requires_multipart_upload(self, transfer_future, config): + return transfer_future.meta.size >= config.multipart_threshold + + def get_put_object_body(self, transfer_future): + # Get a file-like object for the given input + fileobj, full_size = self._get_put_object_fileobj_with_full_size( + transfer_future + ) + + # Wrap fileobj with interrupt reader that will quickly cancel + # uploads if needed instead of having to wait for the socket + # to completely read all of the data. + fileobj = self._wrap_fileobj(fileobj) + + callbacks = self._get_progress_callbacks(transfer_future) + close_callbacks = self._get_close_callbacks(callbacks) + size = transfer_future.meta.size + # Return the file-like object wrapped into a ReadFileChunk to get + # progress. + return self._osutil.open_file_chunk_reader_from_fileobj( + fileobj=fileobj, + chunk_size=size, + full_file_size=full_size, + callbacks=callbacks, + close_callbacks=close_callbacks, + ) + + def yield_upload_part_bodies(self, transfer_future, chunksize): + full_file_size = transfer_future.meta.size + num_parts = self._get_num_parts(transfer_future, chunksize) + for part_number in range(1, num_parts + 1): + callbacks = self._get_progress_callbacks(transfer_future) + close_callbacks = self._get_close_callbacks(callbacks) + start_byte = chunksize * (part_number - 1) + # Get a file-like object for that part and the size of the full + # file size for the associated file-like object for that part. + fileobj, full_size = self._get_upload_part_fileobj_with_full_size( + transfer_future.meta.call_args.fileobj, + start_byte=start_byte, + part_size=chunksize, + full_file_size=full_file_size, + ) + + # Wrap fileobj with interrupt reader that will quickly cancel + # uploads if needed instead of having to wait for the socket + # to completely read all of the data. + fileobj = self._wrap_fileobj(fileobj) + + # Wrap the file-like object into a ReadFileChunk to get progress. + read_file_chunk = self._osutil.open_file_chunk_reader_from_fileobj( + fileobj=fileobj, + chunk_size=chunksize, + full_file_size=full_size, + callbacks=callbacks, + close_callbacks=close_callbacks, + ) + yield part_number, read_file_chunk + + def _get_deferred_open_file(self, fileobj, start_byte): + fileobj = DeferredOpenFile( + fileobj, start_byte, open_function=self._osutil.open + ) + return fileobj + + def _get_put_object_fileobj_with_full_size(self, transfer_future): + fileobj = transfer_future.meta.call_args.fileobj + size = transfer_future.meta.size + return self._get_deferred_open_file(fileobj, 0), size + + def _get_upload_part_fileobj_with_full_size(self, fileobj, **kwargs): + start_byte = kwargs['start_byte'] + full_size = kwargs['full_file_size'] + return self._get_deferred_open_file(fileobj, start_byte), full_size + + def _get_num_parts(self, transfer_future, part_size): + return int(math.ceil(transfer_future.meta.size / float(part_size))) + + +class UploadSeekableInputManager(UploadFilenameInputManager): + """Upload utility for an open file object""" + + @classmethod + def is_compatible(cls, upload_source): + return readable(upload_source) and seekable(upload_source) + + def stores_body_in_memory(self, operation_name): + if operation_name == 'put_object': + return False + else: + return True + + def provide_transfer_size(self, transfer_future): + fileobj = transfer_future.meta.call_args.fileobj + # To determine size, first determine the starting position + # Seek to the end and then find the difference in the length + # between the end and start positions. + start_position = fileobj.tell() + fileobj.seek(0, 2) + end_position = fileobj.tell() + fileobj.seek(start_position) + transfer_future.meta.provide_transfer_size( + end_position - start_position + ) + + def _get_upload_part_fileobj_with_full_size(self, fileobj, **kwargs): + # Note: It is unfortunate that in order to do a multithreaded + # multipart upload we cannot simply copy the filelike object + # since there is not really a mechanism in python (i.e. os.dup + # points to the same OS filehandle which causes concurrency + # issues). So instead we need to read from the fileobj and + # chunk the data out to separate file-like objects in memory. + data = fileobj.read(kwargs['part_size']) + # We return the length of the data instead of the full_file_size + # because we partitioned the data into separate BytesIO objects + # meaning the BytesIO object has no knowledge of its start position + # relative the input source nor access to the rest of the input + # source. So we must treat it as its own standalone file. + return BytesIO(data), len(data) + + def _get_put_object_fileobj_with_full_size(self, transfer_future): + fileobj = transfer_future.meta.call_args.fileobj + # The current position needs to be taken into account when retrieving + # the full size of the file. + size = fileobj.tell() + transfer_future.meta.size + return fileobj, size + + +class UploadNonSeekableInputManager(UploadInputManager): + """Upload utility for a file-like object that cannot seek.""" + + def __init__(self, osutil, transfer_coordinator, bandwidth_limiter=None): + super().__init__(osutil, transfer_coordinator, bandwidth_limiter) + self._initial_data = b'' + + @classmethod + def is_compatible(cls, upload_source): + return readable(upload_source) + + def stores_body_in_memory(self, operation_name): + return True + + def provide_transfer_size(self, transfer_future): + # No-op because there is no way to do this short of reading the entire + # body into memory. + return + + def requires_multipart_upload(self, transfer_future, config): + # If the user has set the size, we can use that. + if transfer_future.meta.size is not None: + return transfer_future.meta.size >= config.multipart_threshold + + # This is tricky to determine in this case because we can't know how + # large the input is. So to figure it out, we read data into memory + # up until the threshold and compare how much data was actually read + # against the threshold. + fileobj = transfer_future.meta.call_args.fileobj + threshold = config.multipart_threshold + self._initial_data = self._read(fileobj, threshold, False) + if len(self._initial_data) < threshold: + return False + else: + return True + + def get_put_object_body(self, transfer_future): + callbacks = self._get_progress_callbacks(transfer_future) + close_callbacks = self._get_close_callbacks(callbacks) + fileobj = transfer_future.meta.call_args.fileobj + + body = self._wrap_data( + self._initial_data + fileobj.read(), callbacks, close_callbacks + ) + + # Zero out the stored data so we don't have additional copies + # hanging around in memory. + self._initial_data = None + return body + + def yield_upload_part_bodies(self, transfer_future, chunksize): + file_object = transfer_future.meta.call_args.fileobj + part_number = 0 + + # Continue reading parts from the file-like object until it is empty. + while True: + callbacks = self._get_progress_callbacks(transfer_future) + close_callbacks = self._get_close_callbacks(callbacks) + part_number += 1 + part_content = self._read(file_object, chunksize) + if not part_content: + break + part_object = self._wrap_data( + part_content, callbacks, close_callbacks + ) + + # Zero out part_content to avoid hanging on to additional data. + part_content = None + yield part_number, part_object + + def _read(self, fileobj, amount, truncate=True): + """ + Reads a specific amount of data from a stream and returns it. If there + is any data in initial_data, that will be popped out first. + + :type fileobj: A file-like object that implements read + :param fileobj: The stream to read from. + + :type amount: int + :param amount: The number of bytes to read from the stream. + + :type truncate: bool + :param truncate: Whether or not to truncate initial_data after + reading from it. + + :return: Generator which generates part bodies from the initial data. + """ + # If the the initial data is empty, we simply read from the fileobj + if len(self._initial_data) == 0: + return fileobj.read(amount) + + # If the requested number of bytes is less than the amount of + # initial data, pull entirely from initial data. + if amount <= len(self._initial_data): + data = self._initial_data[:amount] + # Truncate initial data so we don't hang onto the data longer + # than we need. + if truncate: + self._initial_data = self._initial_data[amount:] + return data + + # At this point there is some initial data left, but not enough to + # satisfy the number of bytes requested. Pull out the remaining + # initial data and read the rest from the fileobj. + amount_to_read = amount - len(self._initial_data) + data = self._initial_data + fileobj.read(amount_to_read) + + # Zero out initial data so we don't hang onto the data any more. + if truncate: + self._initial_data = b'' + return data + + def _wrap_data(self, data, callbacks, close_callbacks): + """ + Wraps data with the interrupt reader and the file chunk reader. + + :type data: bytes + :param data: The data to wrap. + + :type callbacks: list + :param callbacks: The callbacks associated with the transfer future. + + :type close_callbacks: list + :param close_callbacks: The callbacks to be called when closing the + wrapper for the data. + + :return: Fully wrapped data. + """ + fileobj = self._wrap_fileobj(BytesIO(data)) + return self._osutil.open_file_chunk_reader_from_fileobj( + fileobj=fileobj, + chunk_size=len(data), + full_file_size=len(data), + callbacks=callbacks, + close_callbacks=close_callbacks, + ) + + +class UploadSubmissionTask(SubmissionTask): + """Task for submitting tasks to execute an upload""" + + UPLOAD_PART_ARGS = [ + 'ChecksumAlgorithm', + 'SSECustomerKey', + 'SSECustomerAlgorithm', + 'SSECustomerKeyMD5', + 'RequestPayer', + 'ExpectedBucketOwner', + ] + + COMPLETE_MULTIPART_ARGS = [ + 'SSECustomerKey', + 'SSECustomerAlgorithm', + 'SSECustomerKeyMD5', + 'RequestPayer', + 'ExpectedBucketOwner', + ] + + def _get_upload_input_manager_cls(self, transfer_future): + """Retrieves a class for managing input for an upload based on file type + + :type transfer_future: s3transfer.futures.TransferFuture + :param transfer_future: The transfer future for the request + + :rtype: class of UploadInputManager + :returns: The appropriate class to use for managing a specific type of + input for uploads. + """ + upload_manager_resolver_chain = [ + UploadFilenameInputManager, + UploadSeekableInputManager, + UploadNonSeekableInputManager, + ] + + fileobj = transfer_future.meta.call_args.fileobj + for upload_manager_cls in upload_manager_resolver_chain: + if upload_manager_cls.is_compatible(fileobj): + return upload_manager_cls + raise RuntimeError( + f'Input {fileobj} of type: {type(fileobj)} is not supported.' + ) + + def _submit( + self, + client, + config, + osutil, + request_executor, + transfer_future, + bandwidth_limiter=None, + ): + """ + :param client: The client associated with the transfer manager + + :type config: s3transfer.manager.TransferConfig + :param config: The transfer config associated with the transfer + manager + + :type osutil: s3transfer.utils.OSUtil + :param osutil: The os utility associated to the transfer manager + + :type request_executor: s3transfer.futures.BoundedExecutor + :param request_executor: The request executor associated with the + transfer manager + + :type transfer_future: s3transfer.futures.TransferFuture + :param transfer_future: The transfer future associated with the + transfer request that tasks are being submitted for + """ + upload_input_manager = self._get_upload_input_manager_cls( + transfer_future + )(osutil, self._transfer_coordinator, bandwidth_limiter) + + # Determine the size if it was not provided + if transfer_future.meta.size is None: + upload_input_manager.provide_transfer_size(transfer_future) + + # Do a multipart upload if needed, otherwise do a regular put object. + if not upload_input_manager.requires_multipart_upload( + transfer_future, config + ): + self._submit_upload_request( + client, + config, + osutil, + request_executor, + transfer_future, + upload_input_manager, + ) + else: + self._submit_multipart_request( + client, + config, + osutil, + request_executor, + transfer_future, + upload_input_manager, + ) + + def _submit_upload_request( + self, + client, + config, + osutil, + request_executor, + transfer_future, + upload_input_manager, + ): + call_args = transfer_future.meta.call_args + + # Get any tags that need to be associated to the put object task + put_object_tag = self._get_upload_task_tag( + upload_input_manager, 'put_object' + ) + + # Submit the request of a single upload. + self._transfer_coordinator.submit( + request_executor, + PutObjectTask( + transfer_coordinator=self._transfer_coordinator, + main_kwargs={ + 'client': client, + 'fileobj': upload_input_manager.get_put_object_body( + transfer_future + ), + 'bucket': call_args.bucket, + 'key': call_args.key, + 'extra_args': call_args.extra_args, + }, + is_final=True, + ), + tag=put_object_tag, + ) + + def _submit_multipart_request( + self, + client, + config, + osutil, + request_executor, + transfer_future, + upload_input_manager, + ): + call_args = transfer_future.meta.call_args + + # Submit the request to create a multipart upload. + create_multipart_future = self._transfer_coordinator.submit( + request_executor, + CreateMultipartUploadTask( + transfer_coordinator=self._transfer_coordinator, + main_kwargs={ + 'client': client, + 'bucket': call_args.bucket, + 'key': call_args.key, + 'extra_args': call_args.extra_args, + }, + ), + ) + + # Submit requests to upload the parts of the file. + part_futures = [] + extra_part_args = self._extra_upload_part_args(call_args.extra_args) + + # Get any tags that need to be associated to the submitted task + # for upload the data + upload_part_tag = self._get_upload_task_tag( + upload_input_manager, 'upload_part' + ) + + size = transfer_future.meta.size + adjuster = ChunksizeAdjuster() + chunksize = adjuster.adjust_chunksize(config.multipart_chunksize, size) + part_iterator = upload_input_manager.yield_upload_part_bodies( + transfer_future, chunksize + ) + + for part_number, fileobj in part_iterator: + part_futures.append( + self._transfer_coordinator.submit( + request_executor, + UploadPartTask( + transfer_coordinator=self._transfer_coordinator, + main_kwargs={ + 'client': client, + 'fileobj': fileobj, + 'bucket': call_args.bucket, + 'key': call_args.key, + 'part_number': part_number, + 'extra_args': extra_part_args, + }, + pending_main_kwargs={ + 'upload_id': create_multipart_future + }, + ), + tag=upload_part_tag, + ) + ) + + complete_multipart_extra_args = self._extra_complete_multipart_args( + call_args.extra_args + ) + # Submit the request to complete the multipart upload. + self._transfer_coordinator.submit( + request_executor, + CompleteMultipartUploadTask( + transfer_coordinator=self._transfer_coordinator, + main_kwargs={ + 'client': client, + 'bucket': call_args.bucket, + 'key': call_args.key, + 'extra_args': complete_multipart_extra_args, + }, + pending_main_kwargs={ + 'upload_id': create_multipart_future, + 'parts': part_futures, + }, + is_final=True, + ), + ) + + def _extra_upload_part_args(self, extra_args): + # Only the args in UPLOAD_PART_ARGS actually need to be passed + # onto the upload_part calls. + return get_filtered_dict(extra_args, self.UPLOAD_PART_ARGS) + + def _extra_complete_multipart_args(self, extra_args): + return get_filtered_dict(extra_args, self.COMPLETE_MULTIPART_ARGS) + + def _get_upload_task_tag(self, upload_input_manager, operation_name): + tag = None + if upload_input_manager.stores_body_in_memory(operation_name): + tag = IN_MEMORY_UPLOAD_TAG + return tag + + +class PutObjectTask(Task): + """Task to do a nonmultipart upload""" + + def _main(self, client, fileobj, bucket, key, extra_args): + """ + :param client: The client to use when calling PutObject + :param fileobj: The file to upload. + :param bucket: The name of the bucket to upload to + :param key: The name of the key to upload to + :param extra_args: A dictionary of any extra arguments that may be + used in the upload. + """ + with fileobj as body: + client.put_object(Bucket=bucket, Key=key, Body=body, **extra_args) + + +class UploadPartTask(Task): + """Task to upload a part in a multipart upload""" + + def _main( + self, client, fileobj, bucket, key, upload_id, part_number, extra_args + ): + """ + :param client: The client to use when calling PutObject + :param fileobj: The file to upload. + :param bucket: The name of the bucket to upload to + :param key: The name of the key to upload to + :param upload_id: The id of the upload + :param part_number: The number representing the part of the multipart + upload + :param extra_args: A dictionary of any extra arguments that may be + used in the upload. + + :rtype: dict + :returns: A dictionary representing a part:: + + {'Etag': etag_value, 'PartNumber': part_number} + + This value can be appended to a list to be used to complete + the multipart upload. + """ + with fileobj as body: + response = client.upload_part( + Bucket=bucket, + Key=key, + UploadId=upload_id, + PartNumber=part_number, + Body=body, + **extra_args, + ) + etag = response['ETag'] + part_metadata = {'ETag': etag, 'PartNumber': part_number} + if 'ChecksumAlgorithm' in extra_args: + algorithm_name = extra_args['ChecksumAlgorithm'].upper() + checksum_member = f'Checksum{algorithm_name}' + if checksum_member in response: + part_metadata[checksum_member] = response[checksum_member] + return part_metadata diff --git a/venv/lib/python3.10/site-packages/s3transfer/utils.py b/venv/lib/python3.10/site-packages/s3transfer/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9874223621776dd535a9ab73d135f27ec176e64d --- /dev/null +++ b/venv/lib/python3.10/site-packages/s3transfer/utils.py @@ -0,0 +1,814 @@ +# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. +import functools +import logging +import math +import os +import random +import socket +import stat +import string +import threading +from collections import defaultdict + +from botocore.exceptions import ( + IncompleteReadError, + ReadTimeoutError, + ResponseStreamingError, +) +from botocore.httpchecksum import AwsChunkedWrapper +from botocore.utils import is_s3express_bucket + +from s3transfer.compat import SOCKET_ERROR, fallocate, rename_file + +MAX_PARTS = 10000 +# The maximum file size you can upload via S3 per request. +# See: http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadingObjects.html +# and: http://docs.aws.amazon.com/AmazonS3/latest/dev/qfacts.html +MAX_SINGLE_UPLOAD_SIZE = 5 * (1024**3) +MIN_UPLOAD_CHUNKSIZE = 5 * (1024**2) +logger = logging.getLogger(__name__) + + +S3_RETRYABLE_DOWNLOAD_ERRORS = ( + socket.timeout, + SOCKET_ERROR, + ReadTimeoutError, + IncompleteReadError, + ResponseStreamingError, +) + + +def random_file_extension(num_digits=8): + return ''.join(random.choice(string.hexdigits) for _ in range(num_digits)) + + +def signal_not_transferring(request, operation_name, **kwargs): + if operation_name in ['PutObject', 'UploadPart'] and hasattr( + request.body, 'signal_not_transferring' + ): + request.body.signal_not_transferring() + + +def signal_transferring(request, operation_name, **kwargs): + if operation_name in ['PutObject', 'UploadPart']: + body = request.body + if isinstance(body, AwsChunkedWrapper): + body = getattr(body, '_raw', None) + if hasattr(body, 'signal_transferring'): + body.signal_transferring() + + +def calculate_num_parts(size, part_size): + return int(math.ceil(size / float(part_size))) + + +def calculate_range_parameter( + part_size, part_index, num_parts, total_size=None +): + """Calculate the range parameter for multipart downloads/copies + + :type part_size: int + :param part_size: The size of the part + + :type part_index: int + :param part_index: The index for which this parts starts. This index starts + at zero + + :type num_parts: int + :param num_parts: The total number of parts in the transfer + + :returns: The value to use for Range parameter on downloads or + the CopySourceRange parameter for copies + """ + # Used to calculate the Range parameter + start_range = part_index * part_size + if part_index == num_parts - 1: + end_range = '' + if total_size is not None: + end_range = str(total_size - 1) + else: + end_range = start_range + part_size - 1 + range_param = f'bytes={start_range}-{end_range}' + return range_param + + +def get_callbacks(transfer_future, callback_type): + """Retrieves callbacks from a subscriber + + :type transfer_future: s3transfer.futures.TransferFuture + :param transfer_future: The transfer future the subscriber is associated + to. + + :type callback_type: str + :param callback_type: The type of callback to retrieve from the subscriber. + Valid types include: + * 'queued' + * 'progress' + * 'done' + + :returns: A list of callbacks for the type specified. All callbacks are + preinjected with the transfer future. + """ + callbacks = [] + for subscriber in transfer_future.meta.call_args.subscribers: + callback_name = 'on_' + callback_type + if hasattr(subscriber, callback_name): + callbacks.append( + functools.partial( + getattr(subscriber, callback_name), future=transfer_future + ) + ) + return callbacks + + +def invoke_progress_callbacks(callbacks, bytes_transferred): + """Calls all progress callbacks + + :param callbacks: A list of progress callbacks to invoke + :param bytes_transferred: The number of bytes transferred. This is passed + to the callbacks. If no bytes were transferred the callbacks will not + be invoked because no progress was achieved. It is also possible + to receive a negative amount which comes from retrying a transfer + request. + """ + # Only invoke the callbacks if bytes were actually transferred. + if bytes_transferred: + for callback in callbacks: + callback(bytes_transferred=bytes_transferred) + + +def get_filtered_dict(original_dict, whitelisted_keys): + """Gets a dictionary filtered by whitelisted keys + + :param original_dict: The original dictionary of arguments to source keys + and values. + :param whitelisted_key: A list of keys to include in the filtered + dictionary. + + :returns: A dictionary containing key/values from the original dictionary + whose key was included in the whitelist + """ + filtered_dict = {} + for key, value in original_dict.items(): + if key in whitelisted_keys: + filtered_dict[key] = value + return filtered_dict + + +class CallArgs: + def __init__(self, **kwargs): + """A class that records call arguments + + The call arguments must be passed as keyword arguments. It will set + each keyword argument as an attribute of the object along with its + associated value. + """ + for arg, value in kwargs.items(): + setattr(self, arg, value) + + +class FunctionContainer: + """An object that contains a function and any args or kwargs to call it + + When called the provided function will be called with provided args + and kwargs. + """ + + def __init__(self, func, *args, **kwargs): + self._func = func + self._args = args + self._kwargs = kwargs + + def __repr__(self): + return f'Function: {self._func} with args {self._args} and kwargs {self._kwargs}' + + def __call__(self): + return self._func(*self._args, **self._kwargs) + + +class CountCallbackInvoker: + """An abstraction to invoke a callback when a shared count reaches zero + + :param callback: Callback invoke when finalized count reaches zero + """ + + def __init__(self, callback): + self._lock = threading.Lock() + self._callback = callback + self._count = 0 + self._is_finalized = False + + @property + def current_count(self): + with self._lock: + return self._count + + def increment(self): + """Increment the count by one""" + with self._lock: + if self._is_finalized: + raise RuntimeError( + 'Counter has been finalized it can no longer be ' + 'incremented.' + ) + self._count += 1 + + def decrement(self): + """Decrement the count by one""" + with self._lock: + if self._count == 0: + raise RuntimeError( + 'Counter is at zero. It cannot dip below zero' + ) + self._count -= 1 + if self._is_finalized and self._count == 0: + self._callback() + + def finalize(self): + """Finalize the counter + + Once finalized, the counter never be incremented and the callback + can be invoked once the count reaches zero + """ + with self._lock: + self._is_finalized = True + if self._count == 0: + self._callback() + + +class OSUtils: + _MAX_FILENAME_LEN = 255 + + def get_file_size(self, filename): + return os.path.getsize(filename) + + def open_file_chunk_reader(self, filename, start_byte, size, callbacks): + return ReadFileChunk.from_filename( + filename, start_byte, size, callbacks, enable_callbacks=False + ) + + def open_file_chunk_reader_from_fileobj( + self, + fileobj, + chunk_size, + full_file_size, + callbacks, + close_callbacks=None, + ): + return ReadFileChunk( + fileobj, + chunk_size, + full_file_size, + callbacks=callbacks, + enable_callbacks=False, + close_callbacks=close_callbacks, + ) + + def open(self, filename, mode): + return open(filename, mode) + + def remove_file(self, filename): + """Remove a file, noop if file does not exist.""" + # Unlike os.remove, if the file does not exist, + # then this method does nothing. + try: + os.remove(filename) + except OSError: + pass + + def rename_file(self, current_filename, new_filename): + rename_file(current_filename, new_filename) + + def is_special_file(cls, filename): + """Checks to see if a file is a special UNIX file. + + It checks if the file is a character special device, block special + device, FIFO, or socket. + + :param filename: Name of the file + + :returns: True if the file is a special file. False, if is not. + """ + # If it does not exist, it must be a new file so it cannot be + # a special file. + if not os.path.exists(filename): + return False + mode = os.stat(filename).st_mode + # Character special device. + if stat.S_ISCHR(mode): + return True + # Block special device + if stat.S_ISBLK(mode): + return True + # Named pipe / FIFO + if stat.S_ISFIFO(mode): + return True + # Socket. + if stat.S_ISSOCK(mode): + return True + return False + + def get_temp_filename(self, filename): + suffix = os.extsep + random_file_extension() + path = os.path.dirname(filename) + name = os.path.basename(filename) + temp_filename = name[: self._MAX_FILENAME_LEN - len(suffix)] + suffix + return os.path.join(path, temp_filename) + + def allocate(self, filename, size): + try: + with self.open(filename, 'wb') as f: + fallocate(f, size) + except OSError: + self.remove_file(filename) + raise + + +class DeferredOpenFile: + def __init__(self, filename, start_byte=0, mode='rb', open_function=open): + """A class that defers the opening of a file till needed + + This is useful for deferring opening of a file till it is needed + in a separate thread, as there is a limit of how many open files + there can be in a single thread for most operating systems. The + file gets opened in the following methods: ``read()``, ``seek()``, + and ``__enter__()`` + + :type filename: str + :param filename: The name of the file to open + + :type start_byte: int + :param start_byte: The byte to seek to when the file is opened. + + :type mode: str + :param mode: The mode to use to open the file + + :type open_function: function + :param open_function: The function to use to open the file + """ + self._filename = filename + self._fileobj = None + self._start_byte = start_byte + self._mode = mode + self._open_function = open_function + + def _open_if_needed(self): + if self._fileobj is None: + self._fileobj = self._open_function(self._filename, self._mode) + if self._start_byte != 0: + self._fileobj.seek(self._start_byte) + + @property + def name(self): + return self._filename + + def read(self, amount=None): + self._open_if_needed() + return self._fileobj.read(amount) + + def write(self, data): + self._open_if_needed() + self._fileobj.write(data) + + def seek(self, where, whence=0): + self._open_if_needed() + self._fileobj.seek(where, whence) + + def tell(self): + if self._fileobj is None: + return self._start_byte + return self._fileobj.tell() + + def close(self): + if self._fileobj: + self._fileobj.close() + + def __enter__(self): + self._open_if_needed() + return self + + def __exit__(self, *args, **kwargs): + self.close() + + +class ReadFileChunk: + def __init__( + self, + fileobj, + chunk_size, + full_file_size, + callbacks=None, + enable_callbacks=True, + close_callbacks=None, + ): + """ + + Given a file object shown below:: + + |___________________________________________________| + 0 | | full_file_size + |----chunk_size---| + f.tell() + + :type fileobj: file + :param fileobj: File like object + + :type chunk_size: int + :param chunk_size: The max chunk size to read. Trying to read + pass the end of the chunk size will behave like you've + reached the end of the file. + + :type full_file_size: int + :param full_file_size: The entire content length associated + with ``fileobj``. + + :type callbacks: A list of function(amount_read) + :param callbacks: Called whenever data is read from this object in the + order provided. + + :type enable_callbacks: boolean + :param enable_callbacks: True if to run callbacks. Otherwise, do not + run callbacks + + :type close_callbacks: A list of function() + :param close_callbacks: Called when close is called. The function + should take no arguments. + """ + self._fileobj = fileobj + self._start_byte = self._fileobj.tell() + self._size = self._calculate_file_size( + self._fileobj, + requested_size=chunk_size, + start_byte=self._start_byte, + actual_file_size=full_file_size, + ) + # _amount_read represents the position in the chunk and may exceed + # the chunk size, but won't allow reads out of bounds. + self._amount_read = 0 + self._callbacks = callbacks + if callbacks is None: + self._callbacks = [] + self._callbacks_enabled = enable_callbacks + self._close_callbacks = close_callbacks + if close_callbacks is None: + self._close_callbacks = close_callbacks + + @classmethod + def from_filename( + cls, + filename, + start_byte, + chunk_size, + callbacks=None, + enable_callbacks=True, + ): + """Convenience factory function to create from a filename. + + :type start_byte: int + :param start_byte: The first byte from which to start reading. + + :type chunk_size: int + :param chunk_size: The max chunk size to read. Trying to read + pass the end of the chunk size will behave like you've + reached the end of the file. + + :type full_file_size: int + :param full_file_size: The entire content length associated + with ``fileobj``. + + :type callbacks: function(amount_read) + :param callbacks: Called whenever data is read from this object. + + :type enable_callbacks: bool + :param enable_callbacks: Indicate whether to invoke callback + during read() calls. + + :rtype: ``ReadFileChunk`` + :return: A new instance of ``ReadFileChunk`` + + """ + f = open(filename, 'rb') + f.seek(start_byte) + file_size = os.fstat(f.fileno()).st_size + return cls(f, chunk_size, file_size, callbacks, enable_callbacks) + + def _calculate_file_size( + self, fileobj, requested_size, start_byte, actual_file_size + ): + max_chunk_size = actual_file_size - start_byte + return min(max_chunk_size, requested_size) + + def read(self, amount=None): + amount_left = max(self._size - self._amount_read, 0) + if amount is None: + amount_to_read = amount_left + else: + amount_to_read = min(amount_left, amount) + data = self._fileobj.read(amount_to_read) + self._amount_read += len(data) + if self._callbacks is not None and self._callbacks_enabled: + invoke_progress_callbacks(self._callbacks, len(data)) + return data + + def signal_transferring(self): + self.enable_callback() + if hasattr(self._fileobj, 'signal_transferring'): + self._fileobj.signal_transferring() + + def signal_not_transferring(self): + self.disable_callback() + if hasattr(self._fileobj, 'signal_not_transferring'): + self._fileobj.signal_not_transferring() + + def enable_callback(self): + self._callbacks_enabled = True + + def disable_callback(self): + self._callbacks_enabled = False + + def seek(self, where, whence=0): + if whence not in (0, 1, 2): + # Mimic io's error for invalid whence values + raise ValueError(f"invalid whence ({whence}, should be 0, 1 or 2)") + + # Recalculate where based on chunk attributes so seek from file + # start (whence=0) is always used + where += self._start_byte + if whence == 1: + where += self._amount_read + elif whence == 2: + where += self._size + + self._fileobj.seek(max(where, self._start_byte)) + if self._callbacks is not None and self._callbacks_enabled: + # To also rewind the callback() for an accurate progress report + bounded_where = max(min(where - self._start_byte, self._size), 0) + bounded_amount_read = min(self._amount_read, self._size) + amount = bounded_where - bounded_amount_read + invoke_progress_callbacks( + self._callbacks, bytes_transferred=amount + ) + self._amount_read = max(where - self._start_byte, 0) + + def close(self): + if self._close_callbacks is not None and self._callbacks_enabled: + for callback in self._close_callbacks: + callback() + self._fileobj.close() + + def tell(self): + return self._amount_read + + def __len__(self): + # __len__ is defined because requests will try to determine the length + # of the stream to set a content length. In the normal case + # of the file it will just stat the file, but we need to change that + # behavior. By providing a __len__, requests will use that instead + # of stat'ing the file. + return self._size + + def __enter__(self): + return self + + def __exit__(self, *args, **kwargs): + self.close() + + def __iter__(self): + # This is a workaround for http://bugs.python.org/issue17575 + # Basically httplib will try to iterate over the contents, even + # if its a file like object. This wasn't noticed because we've + # already exhausted the stream so iterating over the file immediately + # stops, which is what we're simulating here. + return iter([]) + + +class StreamReaderProgress: + """Wrapper for a read only stream that adds progress callbacks.""" + + def __init__(self, stream, callbacks=None): + self._stream = stream + self._callbacks = callbacks + if callbacks is None: + self._callbacks = [] + + def read(self, *args, **kwargs): + value = self._stream.read(*args, **kwargs) + invoke_progress_callbacks(self._callbacks, len(value)) + return value + + +class NoResourcesAvailable(Exception): + pass + + +class TaskSemaphore: + def __init__(self, count): + """A semaphore for the purpose of limiting the number of tasks + + :param count: The size of semaphore + """ + self._semaphore = threading.Semaphore(count) + + def acquire(self, tag, blocking=True): + """Acquire the semaphore + + :param tag: A tag identifying what is acquiring the semaphore. Note + that this is not really needed to directly use this class but is + needed for API compatibility with the SlidingWindowSemaphore + implementation. + :param block: If True, block until it can be acquired. If False, + do not block and raise an exception if cannot be acquired. + + :returns: A token (can be None) to use when releasing the semaphore + """ + logger.debug("Acquiring %s", tag) + if not self._semaphore.acquire(blocking): + raise NoResourcesAvailable(f"Cannot acquire tag '{tag}'") + + def release(self, tag, acquire_token): + """Release the semaphore + + :param tag: A tag identifying what is releasing the semaphore + :param acquire_token: The token returned from when the semaphore was + acquired. Note that this is not really needed to directly use this + class but is needed for API compatibility with the + SlidingWindowSemaphore implementation. + """ + logger.debug(f"Releasing acquire {tag}/{acquire_token}") + self._semaphore.release() + + +class SlidingWindowSemaphore(TaskSemaphore): + """A semaphore used to coordinate sequential resource access. + + This class is similar to the stdlib BoundedSemaphore: + + * It's initialized with a count. + * Each call to ``acquire()`` decrements the counter. + * If the count is at zero, then ``acquire()`` will either block until the + count increases, or if ``blocking=False``, then it will raise + a NoResourcesAvailable exception indicating that it failed to acquire the + semaphore. + + The main difference is that this semaphore is used to limit + access to a resource that requires sequential access. For example, + if I want to access resource R that has 20 subresources R_0 - R_19, + this semaphore can also enforce that you only have a max range of + 10 at any given point in time. You must also specify a tag name + when you acquire the semaphore. The sliding window semantics apply + on a per tag basis. The internal count will only be incremented + when the minimum sequence number for a tag is released. + + """ + + def __init__(self, count): + self._count = count + # Dict[tag, next_sequence_number]. + self._tag_sequences = defaultdict(int) + self._lowest_sequence = {} + self._lock = threading.Lock() + self._condition = threading.Condition(self._lock) + # Dict[tag, List[sequence_number]] + self._pending_release = {} + + def current_count(self): + with self._lock: + return self._count + + def acquire(self, tag, blocking=True): + logger.debug("Acquiring %s", tag) + self._condition.acquire() + try: + if self._count == 0: + if not blocking: + raise NoResourcesAvailable(f"Cannot acquire tag '{tag}'") + else: + while self._count == 0: + self._condition.wait() + # self._count is no longer zero. + # First, check if this is the first time we're seeing this tag. + sequence_number = self._tag_sequences[tag] + if sequence_number == 0: + # First time seeing the tag, so record we're at 0. + self._lowest_sequence[tag] = sequence_number + self._tag_sequences[tag] += 1 + self._count -= 1 + return sequence_number + finally: + self._condition.release() + + def release(self, tag, acquire_token): + sequence_number = acquire_token + logger.debug("Releasing acquire %s/%s", tag, sequence_number) + self._condition.acquire() + try: + if tag not in self._tag_sequences: + raise ValueError(f"Attempted to release unknown tag: {tag}") + max_sequence = self._tag_sequences[tag] + if self._lowest_sequence[tag] == sequence_number: + # We can immediately process this request and free up + # resources. + self._lowest_sequence[tag] += 1 + self._count += 1 + self._condition.notify() + queued = self._pending_release.get(tag, []) + while queued: + if self._lowest_sequence[tag] == queued[-1]: + queued.pop() + self._lowest_sequence[tag] += 1 + self._count += 1 + else: + break + elif self._lowest_sequence[tag] < sequence_number < max_sequence: + # We can't do anything right now because we're still waiting + # for the min sequence for the tag to be released. We have + # to queue this for pending release. + self._pending_release.setdefault(tag, []).append( + sequence_number + ) + self._pending_release[tag].sort(reverse=True) + else: + raise ValueError( + "Attempted to release unknown sequence number " + f"{sequence_number} for tag: {tag}" + ) + finally: + self._condition.release() + + +class ChunksizeAdjuster: + def __init__( + self, + max_size=MAX_SINGLE_UPLOAD_SIZE, + min_size=MIN_UPLOAD_CHUNKSIZE, + max_parts=MAX_PARTS, + ): + self.max_size = max_size + self.min_size = min_size + self.max_parts = max_parts + + def adjust_chunksize(self, current_chunksize, file_size=None): + """Get a chunksize close to current that fits within all S3 limits. + + :type current_chunksize: int + :param current_chunksize: The currently configured chunksize. + + :type file_size: int or None + :param file_size: The size of the file to upload. This might be None + if the object being transferred has an unknown size. + + :returns: A valid chunksize that fits within configured limits. + """ + chunksize = current_chunksize + if file_size is not None: + chunksize = self._adjust_for_max_parts(chunksize, file_size) + return self._adjust_for_chunksize_limits(chunksize) + + def _adjust_for_chunksize_limits(self, current_chunksize): + if current_chunksize > self.max_size: + logger.debug( + "Chunksize greater than maximum chunksize. " + f"Setting to {self.max_size} from {current_chunksize}." + ) + return self.max_size + elif current_chunksize < self.min_size: + logger.debug( + "Chunksize less than minimum chunksize. " + f"Setting to {self.min_size} from {current_chunksize}." + ) + return self.min_size + else: + return current_chunksize + + def _adjust_for_max_parts(self, current_chunksize, file_size): + chunksize = current_chunksize + num_parts = int(math.ceil(file_size / float(chunksize))) + + while num_parts > self.max_parts: + chunksize *= 2 + num_parts = int(math.ceil(file_size / float(chunksize))) + + if chunksize != current_chunksize: + logger.debug( + "Chunksize would result in the number of parts exceeding the " + f"maximum. Setting to {chunksize} from {current_chunksize}." + ) + + return chunksize + + +def add_s3express_defaults(bucket, extra_args): + if is_s3express_bucket(bucket) and "ChecksumAlgorithm" not in extra_args: + # Default Transfer Operations to S3Express to use CRC32 + extra_args["ChecksumAlgorithm"] = "crc32" diff --git a/venv/lib/python3.10/site-packages/sentencepiece/__init__.py b/venv/lib/python3.10/site-packages/sentencepiece/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..02379dd36dad021a82d4b3a85ad1598f01184758 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sentencepiece/__init__.py @@ -0,0 +1,1230 @@ +# This file was automatically generated by SWIG (https://www.swig.org). +# Version 4.3.0 +# +# Do not make changes to this file unless you know what you are doing - modify +# the SWIG interface file instead. + +from sys import version_info as _swig_python_version_info +# Import the low-level C/C++ module +if __package__ or "." in __name__: + from . import _sentencepiece +else: + import _sentencepiece + +try: + import builtins as __builtin__ +except ImportError: + import __builtin__ + +def _swig_repr(self): + try: + strthis = "proxy of " + self.this.__repr__() + except __builtin__.Exception: + strthis = "" + return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) + + +def _swig_setattr_nondynamic_instance_variable(set): + def set_instance_attr(self, name, value): + if name == "this": + set(self, name, value) + elif name == "thisown": + self.this.own(value) + elif hasattr(self, name) and isinstance(getattr(type(self), name), property): + set(self, name, value) + else: + raise AttributeError("You cannot add instance attributes to %s" % self) + return set_instance_attr + + +def _swig_setattr_nondynamic_class_variable(set): + def set_class_attr(cls, name, value): + if hasattr(cls, name) and not isinstance(getattr(cls, name), property): + set(cls, name, value) + else: + raise AttributeError("You cannot add class attributes to %s" % cls) + return set_class_attr + + +def _swig_add_metaclass(metaclass): + """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass""" + def wrapper(cls): + return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy()) + return wrapper + + +class _SwigNonDynamicMeta(type): + """Meta class to enforce nondynamic attributes (no new attributes) for a class""" + __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__) + + +class ImmutableSentencePieceText_ImmutableSentencePiece(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self): + _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece_swiginit(self, _sentencepiece.new_ImmutableSentencePieceText_ImmutableSentencePiece()) + __swig_destroy__ = _sentencepiece.delete_ImmutableSentencePieceText_ImmutableSentencePiece + + def _piece(self): + return _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece__piece(self) + + def _surface(self): + return _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece__surface(self) + + def _id(self): + return _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece__id(self) + + def _begin(self): + return _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece__begin(self) + + def _end(self): + return _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece__end(self) + + def _surface_as_bytes(self): + return _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece__surface_as_bytes(self) + + def _piece_as_bytes(self): + return _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece__piece_as_bytes(self) + + piece = property(_piece) + piece_as_bytes = property(_piece_as_bytes) + surface = property(_surface) + surface_as_bytes = property(_surface_as_bytes) + id = property(_id) + begin = property(_begin) + end = property(_end) + + def __str__(self): + return ('piece: \"{}\"\n' + 'id: {}\n' + 'surface: \"{}\"\n' + 'begin: {}\n' + 'end: {}\n').format(self.piece, self.id, self.surface, + self.begin, self.end) + + def __eq__(self, other): + return self.piece == other.piece and self.id == other.id and self.surface == other.surface and self.begin == other.begin and self.end == other.end + + def __hash__(self): + return hash(str(self)) + + __repr__ = __str__ + + +# Register ImmutableSentencePieceText_ImmutableSentencePiece in _sentencepiece: +_sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece_swigregister(ImmutableSentencePieceText_ImmutableSentencePiece) +class ImmutableSentencePieceText(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self): + _sentencepiece.ImmutableSentencePieceText_swiginit(self, _sentencepiece.new_ImmutableSentencePieceText()) + __swig_destroy__ = _sentencepiece.delete_ImmutableSentencePieceText + + def _pieces_size(self): + return _sentencepiece.ImmutableSentencePieceText__pieces_size(self) + + def _pieces(self, index): + return _sentencepiece.ImmutableSentencePieceText__pieces(self, index) + + def _text(self): + return _sentencepiece.ImmutableSentencePieceText__text(self) + + def _score(self): + return _sentencepiece.ImmutableSentencePieceText__score(self) + + def SerializeAsString(self): + return _sentencepiece.ImmutableSentencePieceText_SerializeAsString(self) + + def _text_as_bytes(self): + return _sentencepiece.ImmutableSentencePieceText__text_as_bytes(self) + + text = property(_text) + text_as_bytes = property(_text_as_bytes) + score = property(_score) + + class ImmutableSentencePieceIterator: + def __init__(self, proto): + self.proto = proto + self.len = self.proto._pieces_size() + + def __len__(self): + return self.len + + def __getitem__(self, index): + if isinstance(index, slice): + return [self.proto._pieces(i) for i in range(self.len)][index.start:index.stop:index.step] + if index < 0: + index = index + self.len + if index < 0 or index >= self.len: + raise IndexError('piece index is out of range') + return self.proto._pieces(index) + + def __str__(self): + return '\n'.join(['pieces {{\n{}}}'.format(str(x)) for x in self]) + + __repr__ = __str__ + + @property + def pieces(self): + return ImmutableSentencePieceText.ImmutableSentencePieceIterator(self) + + def __eq__(self, other): + return self.SerializeAsString() == other.SerializeAsString() + + def __hash__(self): + return hash(self.SerializeAsString()) + + def __str__(self): + return ('text: \"{}\"\n' + 'score: {}\n' + '{}').format(self.text, self.score, + '\n'.join(['pieces {{\n{}}}'.format(str(x)) for x in self.pieces])) + + __repr__ = __str__ + + +# Register ImmutableSentencePieceText in _sentencepiece: +_sentencepiece.ImmutableSentencePieceText_swigregister(ImmutableSentencePieceText) +class ImmutableNBestSentencePieceText(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self): + _sentencepiece.ImmutableNBestSentencePieceText_swiginit(self, _sentencepiece.new_ImmutableNBestSentencePieceText()) + __swig_destroy__ = _sentencepiece.delete_ImmutableNBestSentencePieceText + + def _nbests_size(self): + return _sentencepiece.ImmutableNBestSentencePieceText__nbests_size(self) + + def _nbests(self, index): + return _sentencepiece.ImmutableNBestSentencePieceText__nbests(self, index) + + def SerializeAsString(self): + return _sentencepiece.ImmutableNBestSentencePieceText_SerializeAsString(self) + + class ImmutableSentencePieceTextIterator: + def __init__(self, proto): + self.proto = proto + self.len = self.proto._nbests_size() + + def __len__(self): + return self.len + + def __getitem__(self, index): + if isinstance(index, slice): + return [self.proto._nbests(i) for i in range(self.len)][index.start:index.stop:index.step] + if index < 0: + index = index + self.len + if index < 0 or index >= self.len: + raise IndexError('nbests index is out of range') + return self.proto._nbests(index) + + def __str__(self): + return '\n'.join(['nbests {{\n{}}}'.format(str(x)) for x in self]) + + __repr__ = __str__ + + @property + def nbests(self): + return ImmutableNBestSentencePieceText.ImmutableSentencePieceTextIterator(self) + + def __eq__(self, other): + return self.SerializeAsString() == other.SerializeAsString() + + def __hash__(self): + return hash(self.SerializeAsString()) + + def __str__(self): + return '\n'.join(['nbests {{\n{}}}'.format(str(x)) for x in self.nbests]) + + __repr__ = __str__ + + +# Register ImmutableNBestSentencePieceText in _sentencepiece: +_sentencepiece.ImmutableNBestSentencePieceText_swigregister(ImmutableNBestSentencePieceText) +class SentencePieceProcessor(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self): + _sentencepiece.SentencePieceProcessor_swiginit(self, _sentencepiece.new_SentencePieceProcessor()) + __swig_destroy__ = _sentencepiece.delete_SentencePieceProcessor + + def LoadFromSerializedProto(self, serialized): + return _sentencepiece.SentencePieceProcessor_LoadFromSerializedProto(self, serialized) + + def SetEncodeExtraOptions(self, extra_option): + return _sentencepiece.SentencePieceProcessor_SetEncodeExtraOptions(self, extra_option) + + def SetDecodeExtraOptions(self, extra_option): + return _sentencepiece.SentencePieceProcessor_SetDecodeExtraOptions(self, extra_option) + + def SetVocabulary(self, valid_vocab): + return _sentencepiece.SentencePieceProcessor_SetVocabulary(self, valid_vocab) + + def ResetVocabulary(self): + return _sentencepiece.SentencePieceProcessor_ResetVocabulary(self) + + def LoadVocabulary(self, filename, threshold): + return _sentencepiece.SentencePieceProcessor_LoadVocabulary(self, filename, threshold) + + def CalculateEntropy(self, *args): + return _sentencepiece.SentencePieceProcessor_CalculateEntropy(self, *args) + + def GetPieceSize(self): + return _sentencepiece.SentencePieceProcessor_GetPieceSize(self) + + def PieceToId(self, piece): + return _sentencepiece.SentencePieceProcessor_PieceToId(self, piece) + + def IdToPiece(self, id): + return _sentencepiece.SentencePieceProcessor_IdToPiece(self, id) + + def GetScore(self, id): + return _sentencepiece.SentencePieceProcessor_GetScore(self, id) + + def IsUnknown(self, id): + return _sentencepiece.SentencePieceProcessor_IsUnknown(self, id) + + def IsControl(self, id): + return _sentencepiece.SentencePieceProcessor_IsControl(self, id) + + def IsUnused(self, id): + return _sentencepiece.SentencePieceProcessor_IsUnused(self, id) + + def IsByte(self, id): + return _sentencepiece.SentencePieceProcessor_IsByte(self, id) + + def unk_id(self): + return _sentencepiece.SentencePieceProcessor_unk_id(self) + + def bos_id(self): + return _sentencepiece.SentencePieceProcessor_bos_id(self) + + def eos_id(self): + return _sentencepiece.SentencePieceProcessor_eos_id(self) + + def pad_id(self): + return _sentencepiece.SentencePieceProcessor_pad_id(self) + + def serialized_model_proto(self): + return _sentencepiece.SentencePieceProcessor_serialized_model_proto(self) + + def LoadFromFile(self, arg): + return _sentencepiece.SentencePieceProcessor_LoadFromFile(self, arg) + + def _EncodeAsIds(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__EncodeAsIds(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece) + + def _EncodeAsPieces(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__EncodeAsPieces(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece) + + def _EncodeAsSerializedProto(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__EncodeAsSerializedProto(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece) + + def _EncodeAsImmutableProto(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__EncodeAsImmutableProto(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece) + + def _EncodeAsIdsBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__EncodeAsIdsBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece) + + def _EncodeAsPiecesBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__EncodeAsPiecesBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece) + + def _EncodeAsSerializedProtoBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__EncodeAsSerializedProtoBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece) + + def _EncodeAsImmutableProtoBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__EncodeAsImmutableProtoBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece) + + def _DecodeIds(self, ids): + return _sentencepiece.SentencePieceProcessor__DecodeIds(self, ids) + + def _DecodeIdsAsBytes(self, ids): + return _sentencepiece.SentencePieceProcessor__DecodeIdsAsBytes(self, ids) + + def _DecodePieces(self, pieces): + return _sentencepiece.SentencePieceProcessor__DecodePieces(self, pieces) + + def _DecodeIdsAsSerializedProto(self, ids): + return _sentencepiece.SentencePieceProcessor__DecodeIdsAsSerializedProto(self, ids) + + def _DecodePiecesAsSerializedProto(self, pieces): + return _sentencepiece.SentencePieceProcessor__DecodePiecesAsSerializedProto(self, pieces) + + def _DecodeIdsAsImmutableProto(self, ids): + return _sentencepiece.SentencePieceProcessor__DecodeIdsAsImmutableProto(self, ids) + + def _DecodePiecesAsImmutableProto(self, pieces): + return _sentencepiece.SentencePieceProcessor__DecodePiecesAsImmutableProto(self, pieces) + + def _DecodeIdsBatch(self, ins, num_threads): + return _sentencepiece.SentencePieceProcessor__DecodeIdsBatch(self, ins, num_threads) + + def _DecodeIdsAsBytesBatch(self, ins, num_threads): + return _sentencepiece.SentencePieceProcessor__DecodeIdsAsBytesBatch(self, ins, num_threads) + + def _DecodeIdsAsSerializedProtoBatch(self, ins, num_threads): + return _sentencepiece.SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch(self, ins, num_threads) + + def _DecodeIdsAsImmutableProtoBatch(self, ins, num_threads): + return _sentencepiece.SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch(self, ins, num_threads) + + def _DecodePiecesBatch(self, ins, num_threads): + return _sentencepiece.SentencePieceProcessor__DecodePiecesBatch(self, ins, num_threads) + + def _DecodePiecesAsSerializedProtoBatch(self, ins, num_threads): + return _sentencepiece.SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch(self, ins, num_threads) + + def _DecodePiecesAsImmutableProtoBatch(self, ins, num_threads): + return _sentencepiece.SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch(self, ins, num_threads) + + def _NBestEncodeAsIds(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__NBestEncodeAsIds(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece) + + def _NBestEncodeAsPieces(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__NBestEncodeAsPieces(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece) + + def _NBestEncodeAsSerializedProto(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__NBestEncodeAsSerializedProto(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece) + + def _NBestEncodeAsImmutableProto(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__NBestEncodeAsImmutableProto(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece) + + def _SampleEncodeAndScoreAsIds(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__SampleEncodeAndScoreAsIds(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece) + + def _SampleEncodeAndScoreAsPieces(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__SampleEncodeAndScoreAsPieces(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece) + + def _SampleEncodeAndScoreAsSerializedProto(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece) + + def _SampleEncodeAndScoreAsImmutableProto(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece): + return _sentencepiece.SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece) + + def _Normalize(self, text): + return _sentencepiece.SentencePieceProcessor__Normalize(self, text) + + def _NormalizeWithOffsets(self, text): + return _sentencepiece.SentencePieceProcessor__NormalizeWithOffsets(self, text) + + def _CalculateEntropy(self, text, alpha): + return _sentencepiece.SentencePieceProcessor__CalculateEntropy(self, text, alpha) + + def _CalculateEntropyBatch(self, ins, alpha, num_threads): + return _sentencepiece.SentencePieceProcessor__CalculateEntropyBatch(self, ins, alpha, num_threads) + + def _OverrideNormalizerSpec(self, args): + return _sentencepiece.SentencePieceProcessor__OverrideNormalizerSpec(self, args) + + def Init(self, + model_file=None, + model_proto=None, + out_type=int, + add_bos=False, + add_eos=False, + reverse=False, + emit_unk_piece=False, + enable_sampling=False, + nbest_size=-1, + alpha=0.1, + num_threads=-1): + """Initialzie sentencepieceProcessor. + + Args: + model_file: The sentencepiece model file path. + model_proto: The sentencepiece model serialized proto. + out_type: output type. int or str. + add_bos: Add to the result (Default = false) + add_eos: Add to the result (Default = false) / is added after + reversing (if enabled). + reverse: Reverses the tokenized sequence (Default = false) + emit_unk_piece: Emits the unk literal string (Default = false) + nbest_size: sampling parameters for unigram. Invalid in BPE-Dropout. + nbest_size = {0,1}: No sampling is performed. + nbest_size > 1: samples from the nbest_size results. + nbest_size < 0: assuming that nbest_size is infinite and samples + from the all hypothesis (lattice) using + forward-filtering-and-backward-sampling algorithm. + alpha: Soothing parameter for unigram sampling, and dropout probability of + merge operations for BPE-dropout. + num_threads: number of threads in batch processing (Default = -1, auto-detected) + """ + + _sentencepiece_processor_init_native(self) + self._out_type = out_type + self._add_bos = add_bos + self._add_eos = add_eos + self._reverse = reverse + self._emit_unk_piece = emit_unk_piece + self._enable_sampling = enable_sampling + self._nbest_size = nbest_size + self._alpha = alpha + self._num_threads = num_threads + if model_file or model_proto: + self.Load(model_file=model_file, model_proto=model_proto) + + + def Encode(self, + input, + out_type=None, + add_bos=None, + add_eos=None, + reverse=None, + emit_unk_piece=None, + enable_sampling=None, + nbest_size=None, + alpha=None, + num_threads=None): + """Encode text input to segmented ids or tokens. + + Args: + input: input string. accepsts list of string. + out_type: output type. int or str. + add_bos: Add to the result (Default = false) + add_eos: Add to the result (Default = false) / is added after + reversing (if enabled). + reverse: Reverses the tokenized sequence (Default = false) + emit_unk_piece: Emits the unk literal string (Default = false) + nbest_size: sampling parameters for unigram. Invalid in BPE-Dropout. + nbest_size = {0,1}: No sampling is performed. + nbest_size > 1: samples from the nbest_size results. + nbest_size < 0: assuming that nbest_size is infinite and samples + from the all hypothesis (lattice) using + forward-filtering-and-backward-sampling algorithm. + alpha: Soothing parameter for unigram sampling, and merge probability for + BPE-dropout (probablity 'p' in BPE-dropout paper). + num_threads: the number of threads used in the batch processing (Default = -1). + """ + + if out_type is None: + out_type = self._out_type + if add_bos is None: + add_bos = self._add_bos + if add_eos is None: + add_eos = self._add_eos + if reverse is None: + reverse = self._reverse + if emit_unk_piece is None: + emit_unk_piece = self._emit_unk_piece + if enable_sampling is None: + enable_sampling = self._enable_sampling + if nbest_size is None: + nbest_size = self._nbest_size + if alpha is None: + alpha = self._alpha + if num_threads is None: + num_threads = self._num_threads + + if enable_sampling == True and (nbest_size is None or nbest_size == 0 or + nbest_size == 1 or alpha is None): + raise RuntimeError( + 'When enable_sampling is True, We must specify "nbest_size > 1" or "nbest_size = -1", ' + 'and "alpha". "nbest_size" is enabled only on unigram mode ignored in BPE-dropout. ' + 'when "nbest_size = -1" , this method samples from all candidates on the lattice ' + 'instead of nbest segmentations.' + ) + + if num_threads is None or type(num_threads) is not int: + raise RuntimeError('num_threads must be int') + + if type(input) is list: + if out_type is int: + return self._EncodeAsIdsBatch(input, num_threads, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + if out_type is str: + return self._EncodeAsPiecesBatch(input, num_threads, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + if out_type == 'serialized_proto' or out_type == 'proto': + return self._EncodeAsSerializedProtoBatch(input, num_threads, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + if out_type == 'immutable_proto': + return self._EncodeAsImmutableProtoBatch(input, num_threads, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + + if out_type is int: + return self._EncodeAsIds(input, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + if out_type is str: + return self._EncodeAsPieces(input, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + if out_type == 'serialized_proto' or out_type == 'proto': + return self._EncodeAsSerializedProto(input, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + if out_type == 'immutable_proto': + return self._EncodeAsImmutableProto(input, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + + raise RuntimeError('unknown out_type={}'.format(out_type)) + return None + + + def EncodeAsPieces(self, input, **kwargs): + return self.Encode(input=input, out_type=str, **kwargs) + + + def EncodeAsIds(self, input, **kwargs): + return self.Encode(input=input, out_type=int, **kwargs) + + + def EncodeAsSerializedProto(self, input, **kwargs): + return self.Encode(input=input, out_type='serialized_proto', **kwargs) + + + def EncodeAsImmutableProto(self, input, **kwargs): + return self.Encode(input=input, out_type='immutable_proto', **kwargs) + + + def SampleEncodeAsPieces(self, input, nbest_size=None, alpha=None, **kwargs): + return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha, + out_type=str, enable_sampling=True, **kwargs) + + + def SampleEncodeAsIds(self, input, nbest_size=None, alpha=None,**kwargs): + return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha, + out_type=int, enable_sampling=True, **kwargs) + + + def SampleEncodeAsSerializedProto(self, input, nbest_size=None, alpha=None, **kwargs): + return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha, + out_type='serialized_proto', enable_sampling=True, **kwargs) + + + def SampleEncodeAsImmutableProto(self, input, nbest_size=None, alpha=None, **kwargs): + return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha, + out_type='immutable_proto', enable_sampling=True, **kwargs) + + + def NBestEncode(self, + input, + out_type=None, + add_bos=None, + add_eos=None, + reverse=None, + emit_unk_piece=None, + nbest_size=None): + """NBestEncode text input to segmented ids or tokens. + + Args: + input: input string. accepsts list of string. + out_type: output type. int or str. + add_bos: Add to the result (Default = false) + add_eos: Add to the result (Default = false) / is added after reversing (if enabled). + reverse: Reverses the tokenized sequence (Default = false) + emit_unk_piece: Emits the unk literal string (Default = false) + nbest_size: nbest size + """ + + if out_type is None: + out_type = self._out_type + if add_bos is None: + add_bos = self._add_bos + if add_eos is None: + add_eos = self._add_eos + if reverse is None: + reverse = self._reverse + if emit_unk_piece is None: + emit_unk_piece = self._emit_unk_piece + if nbest_size is None: + nbest_size = self._nbest_size + + if nbest_size <= 0: + nbest_size=1 + + def _encode(text): + if out_type is int: + return self._NBestEncodeAsIds(text, nbest_size, + add_bos, add_eos, reverse, emit_unk_piece) + if out_type is str: + return self._NBestEncodeAsPieces(text, nbest_size, + add_bos, add_eos, reverse, emit_unk_piece) + if out_type == 'serialized_proto' or out_type == 'proto': + return self._NBestEncodeAsSerializedProto(text, nbest_size, + add_bos, add_eos, reverse, emit_unk_piece) + if out_type == 'immutable_proto': + return self._NBestEncodeAsImmutableProto(text, nbest_size, + add_bos, add_eos, reverse, emit_unk_piece) + + raise RuntimeError('unknown out_type') + + if type(input) is list: + return [_encode(n) for n in input] + + return _encode(input) + + + def NBestEncodeAsPieces(self, input, nbest_size=None, **kwargs): + return self.NBestEncode(input=input, nbest_size=nbest_size, + out_type=str, **kwargs) + + + def NBestEncodeAsIds(self, input, nbest_size=None, **kwargs): + return self.NBestEncode(input=input, nbest_size=nbest_size, + out_type=int, **kwargs) + + + def NBestEncodeAsSerializedProto(self, input, nbest_size=None, **kwargs): + return self.NBestEncode(input=input, nbest_size=nbest_size, + out_type='serialized_proto', **kwargs) + + + def NBestEncodeAsImmutableProto(self, input, nbest_size=None, **kwargs): + return self.NBestEncode(input=input, nbest_size=nbest_size, + out_type='immutable_proto', **kwargs) + + + def SampleEncodeAndScore(self, + input, + out_type=None, + add_bos=None, + add_eos=None, + reverse=None, + emit_unk_piece=None, + num_samples=None, + alpha=None, + wor=None, + include_best=None): + """SampleEncodeAndScore text input to segmented ids or tokens. + + Args: + input: input string. accepsts list of string. + out_type: output type. int or str or 'serialized_proto' or 'immutable_proto' + add_bos: Add to the result (Default = false) + add_eos: Add to the result (Default = false) / is added after reversing (if enabled). + reverse: Reverses the tokenized sequence (Default = false) + emit_unk_piece: Emits the unk literal string (Default = false) + num_samples: How many samples to return (Default = 1) + alpha: inverse temperature for sampling + wor: whether to sample without replacement (Default = false) + include_best: whether to include the best tokenization, requires wor=True (Default = false) + """ + + if out_type is None: + out_type = self._out_type + if add_bos is None: + add_bos = self._add_bos + if add_eos is None: + add_eos = self._add_eos + if reverse is None: + reverse = self._reverse + if emit_unk_piece is None: + emit_unk_piece = self._emit_unk_piece + if num_samples is None: + num_samples = 1 + if alpha is None: + alpha = 1. + if wor is None: + wor = False + if include_best is None: + include_best = False + + if num_samples <= 0: + raise RuntimeError('num_examples must be positive') + + if include_best and not wor: + raise RuntimeError('When include_best is True, We must specify "wor = True".') + + + def _encode(text): + if out_type is int: + return self._SampleEncodeAndScoreAsIds(text, num_samples, alpha, wor, include_best, + add_bos, add_eos, reverse, emit_unk_piece) + if out_type is str: + return self._SampleEncodeAndScoreAsPieces(text, num_samples, alpha, wor, include_best, + add_bos, add_eos, reverse, emit_unk_piece) + + if out_type == 'serialized_proto' or out_type == 'proto': + return self._SampleEncodeAndScoreAsSerializedProto(text, num_samples, alpha, wor, include_best, + add_bos, add_eos, reverse, emit_unk_piece) + + if out_type == 'immutable_proto': + return self._SampleEncodeAndScoreAsImmutableProto(text, num_samples, alpha, wor, include_best, + add_bos, add_eos, reverse, emit_unk_piece) + + raise RuntimeError('unknown output type') + + + if type(input) is list: + return [_encode(n) for n in input] + + return _encode(input) + + + def SampleEncodeAndScoreAsPieces(self, input, num_samples=None, alpha=None, **kwargs): + return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha, + out_type=str, **kwargs) + + + def SampleEncodeAndScoreAsIds(self, input, num_samples=None, alpha=None, **kwargs): + return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha, + out_type=int, **kwargs) + + + def SampleEncodeAndScoreAsSerializedProto(self, input, num_samples=None, alpha=None, **kwargs): + return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha, + out_type='serialized_proto', **kwargs) + + + def SampleEncodeAndScoreAsImmutableProto(self, input, num_samples=None, alpha=None, **kwargs): + return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha, + out_type='immutable_proto', **kwargs) + + + def Decode(self, input, out_type=str, num_threads=None): + """Decode processed id or token sequences. + + Args: + out_type: output type. str, bytes or 'serialized_proto' or 'immutable_proto' (Default = str) + num_threads: the number of threads used in the batch processing (Default = -1). + """ + + if num_threads is None: + num_threads = self._num_threads + + if num_threads is None or type(num_threads) is not int: + raise RuntimeError('num_threads must be int') + + if not input: + return '' + + if out_type is str: + if type(input) is int: + return self._DecodeIds([input]) + if type(input) is str: + return self._DecodePieces([input]) + + if type(input) is list: + if len(input) == 0 or type(input[0]) is int: + return self._DecodeIds(input) + if type(input[0]) is str: + return self._DecodePieces(input) + + if type(input[0]) is list: + if len(input[0]) == 0 or type(input[0][0]) is int: + return self._DecodeIdsBatch(input, num_threads) + if type(input[0][0]) is str: + return self._DecodePiecesBatch(input, num_threads) + + if out_type is bytes: + if type(input) is int: + return self._DecodeIdsAsBytes([input]) + if type(input) is str: + return self._DecodePieces([input]) + + if type(input) is list: + if len(input) == 0 or type(input[0]) is int: + return self._DecodeIdsAsBytes(input) + if type(input[0]) is str: + return self._DecodePieces(input) + + if type(input[0]) is list: + if len(input[0]) == 0 or type(input[0][0]) is int: + return self._DecodeIdsAsBytesBatch(input, num_threads) + if type(input[0][0]) is str: + return self._DecodePiecesBatch(input, num_threads) + + if out_type == 'serialized_proto': + if type(input) is int: + return self._DecodeIdsAsSerializedProto([input]) + if type(input) is str: + return self._DecodePiecesAsSerializedProto([input]) + + if type(input) is list: + if len(input) == 0 or type(input[0]) is int: + return self._DecodeIdsAsSerializedProto(input) + if type(input[0]) is str: + return self._DecodePiecesAsSerializedProto(input) + + if type(input[0]) is list: + if len(input[0]) == 0 or type(input[0][0]) is int: + return self._DecodeIdsAsSerializedProtoBatch(input, num_threads) + if type(input[0][0]) is str: + return self._DecodePiecesAsSerializedProtoBatch(input, num_threads) + + + if out_type == 'immutable_proto': + if type(input) is int: + return self._DecodeIdsAsImmutableProto([input]) + if type(input) is str: + return self._DecodePiecesAsImmutableProto([input]) + + if type(input) is list: + if len(input) == 0 or type(input[0]) is int: + return self._DecodeIdsAsImmutableProto(input) + if type(input[0]) is str: + return self._DecodePiecesAsImmutableProto(input) + + if type(input[0]) is list: + if len(input[0]) == 0 or type(input[0][0]) is int: + return self._DecodeIdsAsImmutableProtoBatch(input, num_threads) + if type(input[0][0]) is str: + return self._DecodePiecesAsImmutableProtoBatch(input, num_threads) + + + raise RuntimeError('unknown output or input type') + return None + + + def DecodePieces(self, input, out_type=str, **kwargs): + return self.Decode(input=input, out_type=out_type, **kwargs) + + + def DecodeIds(self, input, out_type=str, **kwargs): + return self.Decode(input=input, out_type=out_type, **kwargs) + + + def DecodePiecesAsSerializedProto(self, input, out_type='serialized_proto', **kwargs): + return self.Decode(input=input, out_type=out_type, **kwargs) + + + def DecodeIdsAsSerializedProto(self, input, out_type='serialized_proto', **kwargs): + return self.Decode(input=input, out_type=out_type, **kwargs) + + + def DecodePiecesAsImmutableProto(self, input, out_type='immutable_proto', **kwargs): + return self.Decode(input=input, out_type=out_type, **kwargs) + + + def DecodeIdsAsImmutableProto(self, input, out_type='immutable_proto', **kwargs): + return self.Decode(input=input, out_type=out_type, **kwargs) + + + def CalculateEntropy(self, input, alpha, num_threads=None): + """Calculate sentence entropy""" + if type(input) is list: + if num_threads is None: + num_threads = self._num_threads + if num_threads is None or type(num_threads) is not int: + raise RuntimeError('num_threads must be int') + return self._CalculateEntropyBatch(input, alpha, num_threads) + + return self._CalculateEntropy(input, alpha) + + + def Normalize(self, input, with_offsets=None): + def _normalize(text): + if with_offsets: + return self._NormalizeWithOffsets(text) + return self._Normalize(text) + + if type(input) is list: + return [_normalize(x) for x in input] + return _normalize(input) + + def OverrideNormalizerSpec(self, **kwargs): + new_kwargs = {} + for key, value in kwargs.items(): + new_kwargs[key] = str(value) + return self._OverrideNormalizerSpec(new_kwargs) + + + def piece_size(self): + return self.GetPieceSize() + + + def vocab_size(self): + return self.GetPieceSize() + + + def __getstate__(self): + return self.serialized_model_proto() + + + def __setstate__(self, serialized_model_proto): + self.__init__() + self.LoadFromSerializedProto(serialized_model_proto) + + + def __len__(self): + return self.GetPieceSize() + + + def __getitem__(self, piece): + return self.PieceToId(piece) + + + def Load(self, model_file=None, model_proto=None): + """Overwride SentencePieceProcessor.Load to support both model_file and model_proto. + + Args: + model_file: The sentencepiece model file path. + model_proto: The sentencepiece model serialized proto. Either `model_file` + or `model_proto` must be set. + """ + if model_file and model_proto: + raise RuntimeError('model_file and model_proto must be exclusive.') + if model_proto: + return self.LoadFromSerializedProto(model_proto) + return self.LoadFromFile(model_file) + + +# Register SentencePieceProcessor in _sentencepiece: +_sentencepiece.SentencePieceProcessor_swigregister(SentencePieceProcessor) + +def SetRandomGeneratorSeed(seed): + return _sentencepiece.SetRandomGeneratorSeed(seed) + +def SetMinLogLevel(v): + return _sentencepiece.SetMinLogLevel(v) +class SentencePieceTrainer(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined") + __repr__ = _swig_repr + + @staticmethod + def _TrainFromString(arg): + return _sentencepiece.SentencePieceTrainer__TrainFromString(arg) + + @staticmethod + def _TrainFromMap(args): + return _sentencepiece.SentencePieceTrainer__TrainFromMap(args) + + @staticmethod + def _TrainFromMap2(args, iter): + return _sentencepiece.SentencePieceTrainer__TrainFromMap2(args, iter) + + @staticmethod + def _TrainFromMap3(args): + return _sentencepiece.SentencePieceTrainer__TrainFromMap3(args) + + @staticmethod + def _TrainFromMap4(args, iter): + return _sentencepiece.SentencePieceTrainer__TrainFromMap4(args, iter) + + @staticmethod + def _Train(arg=None, **kwargs): + """Train Sentencepiece model. Accept both kwargs and legacy string arg.""" + if arg is not None and type(arg) is str: + return SentencePieceTrainer._TrainFromString(arg) + + def _encode(value): + """Encode value to CSV..""" + if type(value) is list: + if sys.version_info[0] == 3: + f = StringIO() + else: + f = BytesIO() + writer = csv.writer(f, lineterminator='') + writer.writerow([str(v) for v in value]) + return f.getvalue() + else: + return str(value) + + sentence_iterator = None + model_writer = None + new_kwargs = {} + for key, value in kwargs.items(): + if key in ['sentence_iterator', 'sentence_reader']: + sentence_iterator = value + elif key in ['model_writer']: + model_writer = value + else: + new_kwargs[key] = _encode(value) + + if model_writer: + if sentence_iterator: + model_proto = SentencePieceTrainer._TrainFromMap4(new_kwargs, + sentence_iterator) + else: + model_proto = SentencePieceTrainer._TrainFromMap3(new_kwargs) + model_writer.write(model_proto) + else: + if sentence_iterator: + return SentencePieceTrainer._TrainFromMap2(new_kwargs, sentence_iterator) + else: + return SentencePieceTrainer._TrainFromMap(new_kwargs) + + return None + + @staticmethod + def Train(arg=None, logstream=None, **kwargs): + with _LogStream(ostream=logstream): + SentencePieceTrainer._Train(arg=arg, **kwargs) + + +# Register SentencePieceTrainer in _sentencepiece: +_sentencepiece.SentencePieceTrainer_swigregister(SentencePieceTrainer) +class SentencePieceNormalizer(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") + __repr__ = _swig_repr + + def __init__(self): + _sentencepiece.SentencePieceNormalizer_swiginit(self, _sentencepiece.new_SentencePieceNormalizer()) + __swig_destroy__ = _sentencepiece.delete_SentencePieceNormalizer + + def LoadFromSerializedProto(self, serialized): + return _sentencepiece.SentencePieceNormalizer_LoadFromSerializedProto(self, serialized) + + def LoadFromRuleTSV(self, filename): + return _sentencepiece.SentencePieceNormalizer_LoadFromRuleTSV(self, filename) + + def LoadFromRuleName(self, name): + return _sentencepiece.SentencePieceNormalizer_LoadFromRuleName(self, name) + + def serialized_model_proto(self): + return _sentencepiece.SentencePieceNormalizer_serialized_model_proto(self) + + def LoadFromFile(self, arg): + return _sentencepiece.SentencePieceNormalizer_LoadFromFile(self, arg) + + def _Normalize(self, text): + return _sentencepiece.SentencePieceNormalizer__Normalize(self, text) + + def _NormalizeWithOffsets(self, text): + return _sentencepiece.SentencePieceNormalizer__NormalizeWithOffsets(self, text) + + def _SetProtoField(self, name, value): + return _sentencepiece.SentencePieceNormalizer__SetProtoField(self, name, value) + + def Init(self, + model_file=None, + model_proto=None, + rule_tsv=None, + rule_name=None, + add_dummy_prefix=False, + escape_whitespaces=False, + remove_extra_whitespaces=False): + """Initialzie sentencePieceNormalizer. + + Args: + model_file: The sentencepiece model file path. + model_proto: The sentencepiece model serialized proto. + rule_tsv: The normalization rule file in TSV format. + rule_name: Pre-defined normalization name. + add_dummy_prefix: add dummy prefix. + escape_whitespaces: escape whitespaces. + remove_extra_whitespaces: remove extra whitespaces. + """ + + _sentencepiece_normalizer_init_native(self) + + if model_file: + status = self.LoadFromFile(model_file) + elif model_proto: + status = self.LoadFromSerializedProto(model_proto) + elif rule_tsv: + status = self.LoadFromRuleTSV(rule_tsv) + elif rule_name: + status = self.LoadFromRuleName(rule_name) + else: + raise RuntimeError('no model is specified') + + if status: + self._SetProtoField('add_dummy_prefix', add_dummy_prefix) + self._SetProtoField('escape_whitespaces', escape_whitespaces) + self._SetProtoField('remove_extra_whitespaces', remove_extra_whitespaces) + + def Normalize(self, input, with_offsets=None): + def _normalize(text): + if with_offsets: + return self._NormalizeWithOffsets(text) + return self._Normalize(text) + + if type(input) is list: + return [_normalize(x) for x in input] + return _normalize(input) + + + def __getstate__(self): + return self.serialized_model_proto() + + + def __setstate__(self, serialized_model_proto): + self.__init__() + self.LoadFromSerializedProto(serialized_model_proto) + + +# Register SentencePieceNormalizer in _sentencepiece: +_sentencepiece.SentencePieceNormalizer_swigregister(SentencePieceNormalizer) + +def SetDataDir(data_dir): + return _sentencepiece.SetDataDir(data_dir) + + +import re +import csv +import sys +import os +import importlib.resources +from io import StringIO +from io import BytesIO + + +def _add_snake_case(classname): + """Added snake_cased method from CammelCased method.""" + + snake_map = {} + for k, v in classname.__dict__.items(): + if re.match(r'^[A-Z]+', k): + snake = re.sub(r'(?= v.piece_size()): + raise IndexError('piece id is out of range.') + return func(v, n) + + def _batched_func(self, arg): + if type(arg) is list: + return [_func(self, n) for n in arg] + else: + return _func(self, arg) + + setattr(classname, name, _batched_func) + + +_sentencepiece_processor_init_native = SentencePieceProcessor.__init__ +_sentencepiece_normalizer_init_native = SentencePieceNormalizer.__init__ +setattr(SentencePieceProcessor, '__init__', SentencePieceProcessor.Init) +setattr(SentencePieceNormalizer, '__init__', SentencePieceNormalizer.Init) + +SentencePieceProcessor.Tokenize = SentencePieceProcessor.Encode +SentencePieceProcessor.Detokenize = SentencePieceProcessor.Decode + +for m in [ + 'PieceToId', 'IdToPiece', 'GetScore', 'IsUnknown', 'IsControl', 'IsUnused', + 'IsByte' +]: + _batchnize(SentencePieceProcessor, m) + +_add_snake_case(SentencePieceProcessor) +_add_snake_case(SentencePieceTrainer) +_add_snake_case(SentencePieceNormalizer) +set_random_generator_seed = SetRandomGeneratorSeed +set_min_log_level = SetMinLogLevel + +from ._version import __version__ + +SetDataDir(os.path.join(str(importlib.resources.files('sentencepiece')), 'package_data')) + +class _LogStream(object): + def __init__(self, ostream=None): + self.ostream = ostream + if self.ostream is not None: + self.orig_stream_fileno = sys.stderr.fileno() + + def __enter__(self): + if self.ostream is not None: + self.orig_stream_dup = os.dup(self.orig_stream_fileno) + os.dup2(self.ostream.fileno(), self.orig_stream_fileno) + + def __exit__(self, type, value, traceback): + if self.ostream is not None: + os.close(self.orig_stream_fileno) + os.dup2(self.orig_stream_dup, self.orig_stream_fileno) + os.close(self.orig_stream_dup) + self.ostream.close() + + diff --git a/venv/lib/python3.10/site-packages/sentencepiece/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/sentencepiece/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..992b6a4c4b474ee65b5d542b4f075363a1f31307 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sentencepiece/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sentencepiece/__pycache__/_version.cpython-310.pyc b/venv/lib/python3.10/site-packages/sentencepiece/__pycache__/_version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2800d1fea22f164992c32ff9d9e4fbcf72fe0ec2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sentencepiece/__pycache__/_version.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sentencepiece/__pycache__/sentencepiece_model_pb2.cpython-310.pyc b/venv/lib/python3.10/site-packages/sentencepiece/__pycache__/sentencepiece_model_pb2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8480249b5357be3a98809761488af40a904c87a Binary files /dev/null and b/venv/lib/python3.10/site-packages/sentencepiece/__pycache__/sentencepiece_model_pb2.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sentencepiece/__pycache__/sentencepiece_pb2.cpython-310.pyc b/venv/lib/python3.10/site-packages/sentencepiece/__pycache__/sentencepiece_pb2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ea473e919004d9d00cface2e08c11e45e5f2c91 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sentencepiece/__pycache__/sentencepiece_pb2.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sentencepiece/_version.py b/venv/lib/python3.10/site-packages/sentencepiece/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..fc79d63d5430b972ac6ec1c4bfea9af80922da4d --- /dev/null +++ b/venv/lib/python3.10/site-packages/sentencepiece/_version.py @@ -0,0 +1 @@ +__version__ = '0.2.1' diff --git a/venv/lib/python3.10/site-packages/sentencepiece/sentencepiece.i b/venv/lib/python3.10/site-packages/sentencepiece/sentencepiece.i new file mode 100644 index 0000000000000000000000000000000000000000..20944ea1ea2ade6d4a1b2debf4e90aa8e16d91d6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sentencepiece/sentencepiece.i @@ -0,0 +1,2013 @@ +%module sentencepiece +%include exception.i + +%{ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +PyObject* kUnicodeInput = reinterpret_cast(0x1); +PyObject* kByteInput = reinterpret_cast(0x2); + +using BytesArray = std::vector; + +inline void ReleaseResultObject(PyObject *obj) { + if (obj != nullptr && obj != kUnicodeInput && obj != kByteInput) { + Py_XDECREF(obj); + } +} + +class PyInputString { + public: + explicit PyInputString(PyObject* obj) { + if (PyUnicode_Check(obj)) { + str_ = const_cast(PyUnicode_AsUTF8AndSize(obj, &size_)); + input_type_ = kUnicodeInput; + } else if (PyBytes_Check(obj)) { + PyBytes_AsStringAndSize(obj, &str_, &size_); + input_type_ = kByteInput; + } else { + str_ = nullptr; + } + } + absl::string_view str() const { return absl::string_view(data(), size()); } + const char* data() const { return str_; } + Py_ssize_t size() const { return size_; } + bool IsAvalable() const { return str_ != nullptr; } + PyObject *input_type() const { return input_type_; } + + static bool IsUnicode(PyObject *resultobj) { + return (resultobj == nullptr || resultobj == kUnicodeInput); + } + + private: + PyObject* input_type_ = nullptr; + char* str_ = nullptr; + Py_ssize_t size_ = 0; +}; + +PyObject* MakePyOutputString(const std::string& output, + PyObject *resultobj) { + if (PyInputString::IsUnicode(resultobj)) { + return PyUnicode_FromStringAndSize(output.data(), output.size()); + } + return PyBytes_FromStringAndSize(output.data(), output.size()); +} + +PyObject* MakePyOutputBytes(const sentencepiece::util::bytes& output) { + return PyBytes_FromStringAndSize(output.data(), output.size()); +} + +int ToSwigError(sentencepiece::util::StatusCode code) { + switch (code) { + case sentencepiece::util::StatusCode::kNotFound: + return SWIG_IOError; + case sentencepiece::util::StatusCode::kOutOfRange: + return SWIG_IndexError; + case sentencepiece::util::StatusCode::kInvalidArgument: + return SWIG_SyntaxError; + default: + return SWIG_RuntimeError; + } + return SWIG_RuntimeError; +} + +class PySentenceIterator : public sentencepiece::SentenceIterator { + public: + PySentenceIterator(PyObject *iter) : iter_(iter) { + item_ = PyIter_Next(iter_); + CopyValue(); + } + + ~PySentenceIterator() { + // Py_XDECREF(iter_); + } + + bool done() const override { + return item_ == nullptr; + } + + void Next() override { + item_ = PyIter_Next(iter_); + CopyValue(); + } + + const std::string &value() const override { + return value_; + } + + sentencepiece::util::Status status() const override { + return status_; + } + + private: + void CopyValue() { + if (item_ == nullptr) return; + const PyInputString ustring(item_); + if (ustring.IsAvalable()) { + const char *data = ustring.data(); + size_t size = ustring.size(); + while (size > 0) { + if (data[size - 1] == '\r' || data[size - 1] == '\n') + --size; + else + break; + } + value_.assign(data, size); + } else { + status_ = sentencepiece::util::Status(sentencepiece::util::StatusCode::kInternal, + "Not a string."); + } + Py_XDECREF(item_); + } + PyObject *iter_ = nullptr; + PyObject *item_ = nullptr; + std::string value_; + sentencepiece::util::Status status_; +}; + +inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp, + std::vector *ids, + bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) { + if (!add_bos && !add_eos && !reverse) return; + if (reverse) std::reverse(ids->begin(), ids->end()); + if (add_bos) ids->insert(ids->begin(), sp.bos_id()); + if (add_eos) ids->push_back(sp.eos_id()); +} + +inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp, + std::vector *pieces, + bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) { + if (!add_bos && !add_eos && !reverse && !emit_unk_piece) return; + if (reverse) std::reverse(pieces->begin(), pieces->end()); + if (add_bos) pieces->insert(pieces->begin(), sp.IdToPiece(sp.bos_id())); + if (add_eos) pieces->push_back(sp.IdToPiece(sp.eos_id())); + if (emit_unk_piece) { + const auto &unk = sp.IdToPiece(sp.unk_id()); + for (auto &piece : *pieces) { + const int id = sp.PieceToId(piece); + if (id == sp.unk_id()) { + piece = unk; + } + } + } +} + +inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp, + sentencepiece::util::bytes *proto, + bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) { + if (add_bos || add_eos || reverse || emit_unk_piece) { + throw sentencepiece::util::Status( + sentencepiece::util::StatusCode::kUnimplemented, + "add_bos, add_eos, reverse, and emit_unk_piece is not supported in proto API"); + } +} + +inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp, + sentencepiece::ImmutableSentencePieceText *proto, + bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) { + if (add_bos || add_eos || reverse || emit_unk_piece) { + throw sentencepiece::util::Status( + sentencepiece::util::StatusCode::kUnimplemented, + "add_bos, add_eos, reverse, and emit_unk_piece is not supported in proto API"); + } +} + +inline void CheckIds(const std::vector &ids, int num_pieces) { + for (int id : ids) { + if (id < 0 || id >= num_pieces) { + throw sentencepiece::util::Status( + sentencepiece::util::StatusCode::kOutOfRange, + "piece id is out of range."); + } + } +} + +inline void CheckIds(const std::vector &ids, int num_pieces) {} + +inline void CheckIdsBatch(const std::vector> &ids, int num_pieces) { + for (const auto &v : ids) CheckIds(v, num_pieces); +} + +template +inline void ConvertToUnicodeSpans(T *proto) {} + +template <> +inline void ConvertToUnicodeSpans(sentencepiece::ImmutableSentencePieceText *proto) { + proto->ConvertToUnicodeSpans(); +} + +template <> +inline void ConvertToUnicodeSpans(sentencepiece::ImmutableNBestSentencePieceText *proto) { + proto->ConvertToUnicodeSpans(); +} + +class ThreadPool { + public: + explicit ThreadPool(size_t request_size) : + request_size_(request_size) {} + + virtual ~ThreadPool() { + for (auto &task : tasks_) { + task.join(); + } + } + + void Schedule(std::function closure) { + static constexpr size_t kMinThreadSize = 2; + if (request_size_ < kMinThreadSize) { + closure(); + } else { + tasks_.emplace_back(closure); + } + } + + private: + size_t request_size_ = 0; + std::vector tasks_; +}; + +template +inline void InitNumThreads(const std::vector &ins, int *num_threads) { + if (*num_threads < 0) { + *num_threads = std::thread::hardware_concurrency(); + } + *num_threads = std::max(1, + std::min({*num_threads, + static_cast(ins.size()), 256})); +} + +#define DEFINE_ENCODE_BATCH_FUNC_IMPL(FuncName, InType, OutType) \ + std::vector outs(ins.size()); \ + InitNumThreads(ins, &num_threads); \ + { \ + ThreadPool pool(ins.size()); \ + std::atomic index = 0; \ + for (int n = 0; n < num_threads; ++n) { \ + pool.Schedule([&]() { \ + size_t i = 0; \ + while ((i = std::atomic_fetch_add(&index, 1)) < outs.size()) { \ + auto out = enable_sampling ? \ + self->Sample##FuncName(ins[i], \ + nbest_size, alpha) : \ + self->FuncName(ins[i]); \ + RewriteIds(*self, &out, add_bos, add_eos, reverse, \ + emit_unk_piece); \ + ConvertToUnicodeSpans(&out); \ + outs[i] = std::move(out); \ + } \ + }); \ + } \ + } \ + return outs; + +#define DEFINE_DECODE_BATCH_FUNC_IMPL(FuncName, InType, OutType) \ + std::vector outs(ins.size()); \ + InitNumThreads(ins, &num_threads); \ + { \ + std::atomic index = 0; \ + ThreadPool pool(ins.size()); \ + for (int n = 0; n < num_threads; ++n) { \ + pool.Schedule([&]() { \ + size_t i = 0; \ + while ((i = std::atomic_fetch_add(&index, 1)) < outs.size()) { \ + auto out = self->FuncName(ins[i]); \ + ConvertToUnicodeSpans(&out); \ + outs[i] = std::move(out); \ + } \ + }); \ + } \ + } \ + return outs; + +} // namespace +%} + +%init %{ +#ifdef Py_GIL_DISABLED + PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED); +#endif +%} + +%exception { + try { + $action + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } +} + +%apply unsigned int { uint32_t } + +%ignore sentencepiece::util::Status; +%ignore sentencepiece::util::StatusCode; +%ignore absl::string_view; +%ignore std::string_view; +%ignore sentencepiece::SentencePieceText; +%ignore sentencepiece::NormalizerSpec; +%ignore sentencepiece::TrainerSpec; +%ignore sentencepiece::SentencePieceProcessor::status; +%ignore sentencepiece::ImmutableSentencePieceText::mutable_proto; +%ignore sentencepiece::ImmutableSentencePieceText::pieces() const; +%ignore sentencepiece::ImmutableSentencePieceText::ConvertToUnicodeSpans; +%ignore sentencepiece::ImmutableNBestSentencePieceText::mutable_proto; +%ignore sentencepiece::ImmutableNBestSentencePieceText::nbests() const; +%ignore sentencepiece::ImmutableNBestSentencePieceText::ConvertToUnicodeSpans; + +%ignore sentencepiece::SentencePieceProcessor::Encode; +%ignore sentencepiece::SentencePieceProcessor::SampleEncode; +%ignore sentencepiece::SentencePieceProcessor::NBestEncode; +%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAndScore; +%ignore sentencepiece::SentencePieceProcessor::Decode; + +%ignore sentencepiece::SentencePieceProcessor::EncodeAsPieces; +%ignore sentencepiece::SentencePieceProcessor::EncodeAsIds; +%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAsIds; +%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAsPieces; +%ignore sentencepiece::SentencePieceProcessor::NBestEncodeAsIds; +%ignore sentencepiece::SentencePieceProcessor::NBestEncodeAsPieces; +%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAndScoreAsIds; +%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAndScoreAsPieces; +%ignore sentencepiece::SentencePieceProcessor::DecodeIds; +%ignore sentencepiece::SentencePieceProcessor::DecodePieces; + +%ignore sentencepiece::SentencePieceProcessor::EncodeAsSerializedProto; +%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAsSerializedProto; +%ignore sentencepiece::SentencePieceProcessor::NBestEncodeAsSerializedProto; +%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAndScoreAsSerializedProto; +%ignore sentencepiece::SentencePieceProcessor::DecodePiecesAsSerializedProto; +%ignore sentencepiece::SentencePieceProcessor::DecodeIdsAsSerializedProto; + +%ignore sentencepiece::SentencePieceProcessor::EncodeAsImmutableProto; +%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAsImmutableProto; +%ignore sentencepiece::SentencePieceProcessor::NBestEncodeAsImmutableProto; +%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAndScoreAsImmutableProto; +%ignore sentencepiece::SentencePieceProcessor::DecodePiecesAsImmutableProto; +%ignore sentencepiece::SentencePieceProcessor::DecodeIdsAsImmutableProto; + +%ignore sentencepiece::SentencePieceProcessor::Normalize; +%ignore sentencepiece::SentencePieceProcessor::NormalizeWithOffsets; + +%ignore sentencepiece::SentencePieceProcessor::model_proto; +%ignore sentencepiece::SentencePieceProcessor::mutable_normalizer_spec; +%ignore sentencepiece::SentencePieceProcessor::Load; +%ignore sentencepiece::SentencePieceProcessor::LoadOrDie; +%ignore sentencepiece::SentencePieceProcessor::SetModel; +%ignore sentencepiece::SentencePieceProcessor::SetNormalizer; +%ignore sentencepiece::pretokenizer::PretokenizerForTrainingInterface; +%ignore sentencepiece::SentenceIterator; +%ignore sentencepiece::ConvertToUnicodeSpans; +%ignore sentencepiece::SentencePieceTrainer::Train; +%ignore sentencepiece::SentencePieceTrainer::GetNormalizerSpec; +%ignore sentencepiece::SentencePieceTrainer::PopulateNormalizerSpec; +%ignore sentencepiece::SentencePieceTrainer::MergeSpecsFromArgs; +%ignore sentencepiece::SentencePieceTrainer::SetProtoField; +%ignore sentencepiece::SentencePieceTrainer::PopulateModelTypeFromString; +%ignore sentencepiece::SentencePieceTrainer::PieceProcecssor; +%ignore sentencepiece::SentencePieceTrainer::SetPretokenizerForTraining; +%ignore sentencepiece::SentencePieceTrainer::GetPretokenizerForTraining; +%ignore sentencepiece::SentencePieceTrainer::SetDataDir; +%ignore sentencepiece::ConvertToUnicodeAlignment; + +%ignore sentencepiece::SentencePieceNormalizer::Load; +%ignore sentencepiece::SentencePieceNormalizer::Normalize; +%ignore sentencepiece::SentencePieceNormalizer::mutable_normalizer_spec; + +%ignore sentencepiece::io::LoadModelProto; +%ignore sentencepiece::io::SaveModelProto; + +%extend sentencepiece::SentencePieceProcessor { + sentencepiece::util::Status LoadFromFile(absl::string_view arg) { + return $self->Load(arg); + } + + ///////////////////////////////////////////////////////////////////////////// + // EncodeAs* (Single request) + std::vector _EncodeAsIds(absl::string_view text, + bool enable_sampling, + int nbest_size, float alpha, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + auto ids = enable_sampling ? + $self->SampleEncodeAsIds(text, nbest_size, alpha) : + $self->EncodeAsIds(text); + RewriteIds(*$self, &ids, add_bos, add_eos, reverse, emit_unk_piece); + return ids; + } + + std::vector _EncodeAsPieces(absl::string_view text, + bool enable_sampling, + int nbest_size, float alpha, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + auto pieces = enable_sampling ? + $self->SampleEncodeAsPieces(text, nbest_size, alpha) : + $self->EncodeAsPieces(text); + RewriteIds(*$self, &pieces, add_bos, add_eos, reverse, emit_unk_piece); + return pieces; + } + + sentencepiece::util::bytes _EncodeAsSerializedProto(absl::string_view text, + bool enable_sampling, + int nbest_size, float alpha, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + auto proto = enable_sampling ? + $self->SampleEncodeAsSerializedProto(text, nbest_size, alpha) : + $self->EncodeAsSerializedProto(text); + RewriteIds(*$self, &proto, add_bos, add_eos, reverse, emit_unk_piece); + return proto; + } + + sentencepiece::ImmutableSentencePieceText + _EncodeAsImmutableProto(absl::string_view text, + bool enable_sampling, + int nbest_size, float alpha, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + auto proto = enable_sampling ? + $self->SampleEncodeAsImmutableProto(text, nbest_size, alpha) : + $self->EncodeAsImmutableProto(text); + proto.ConvertToUnicodeSpans(); + RewriteIds(*$self, &proto, add_bos, add_eos, reverse, emit_unk_piece); + return proto; + } + + ///////////////////////////////////////////////////////////////////////////// + // EncodeAs* (Batch request) + std::vector> _EncodeAsIdsBatch( + const std::vector &ins, int num_threads, + bool enable_sampling, int nbest_size, float alpha, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsIds, + absl::string_view, std::vector); + } + + std::vector> _EncodeAsPiecesBatch( + const std::vector &ins, int num_threads, + bool enable_sampling, int nbest_size, float alpha, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsPieces, + absl::string_view, std::vector); + } + + BytesArray _EncodeAsSerializedProtoBatch( + const std::vector &ins, int num_threads, + bool enable_sampling, int nbest_size, float alpha, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsSerializedProto, + absl::string_view, + sentencepiece::util::bytes); + } + + std::vector + _EncodeAsImmutableProtoBatch( + const std::vector &ins, int num_threads, + bool enable_sampling, int nbest_size, float alpha, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsImmutableProto, + absl::string_view, + sentencepiece::ImmutableSentencePieceText); + } + + ///////////////////////////////////////////////////////////////////////////// + // DecodeAs* (Single request) + std::string _DecodeIds(const std::vector &ids) const { + CheckIds(ids, $self->GetPieceSize()); + return $self->DecodeIds(ids); + } + + sentencepiece::util::bytes _DecodeIdsAsBytes(const std::vector &ids) const { + CheckIds(ids, $self->GetPieceSize()); + return $self->DecodeIds(ids); + } + + std::string _DecodePieces(const std::vector &pieces) const { + return $self->DecodePieces(pieces); + } + + sentencepiece::util::bytes _DecodeIdsAsSerializedProto( + const std::vector &ids) const { + CheckIds(ids, $self->GetPieceSize()); + return $self->DecodeIdsAsSerializedProto(ids); + } + + sentencepiece::util::bytes _DecodePiecesAsSerializedProto( + const std::vector &pieces) const { + CheckIds(pieces, $self->GetPieceSize()); + return $self->DecodePiecesAsSerializedProto(pieces); + } + + sentencepiece::ImmutableSentencePieceText _DecodeIdsAsImmutableProto( + const std::vector &ids) const { + CheckIds(ids, $self->GetPieceSize()); + auto proto = $self->DecodeIdsAsImmutableProto(ids); + proto.ConvertToUnicodeSpans(); + return proto; + } + + sentencepiece::ImmutableSentencePieceText _DecodePiecesAsImmutableProto( + const std::vector &pieces) const { + CheckIds(pieces, $self->GetPieceSize()); + auto proto= $self->DecodePiecesAsImmutableProto(pieces); + proto.ConvertToUnicodeSpans(); + return proto; + } + + ///////////////////////////////////////////////////////////////////////////// + // DecodeAs* (Batch request) + std::vector _DecodeIdsBatch( + const std::vector> &ins, int num_threads) const { + CheckIdsBatch(ins, $self->GetPieceSize()); + DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIds, int, std::string); + } + + BytesArray _DecodeIdsAsBytesBatch( + const std::vector> &ins, int num_threads) const { + CheckIdsBatch(ins, $self->GetPieceSize()); + DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIds, int, std::string); + } + + BytesArray _DecodeIdsAsSerializedProtoBatch( + const std::vector> &ins, int num_threads) const { + CheckIdsBatch(ins, $self->GetPieceSize()); + DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIdsAsSerializedProto, int, + sentencepiece::util::bytes); + } + + std::vector + _DecodeIdsAsImmutableProtoBatch( + const std::vector> &ins, int num_threads) const { + CheckIdsBatch(ins, $self->GetPieceSize()); + DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIdsAsImmutableProto, int, + sentencepiece::ImmutableSentencePieceText); + } + + std::vector _DecodePiecesBatch( + const std::vector> &ins, int num_threads) const { + DEFINE_DECODE_BATCH_FUNC_IMPL(DecodePieces, std::string, std::string); + } + + BytesArray _DecodePiecesAsSerializedProtoBatch( + const std::vector> &ins, int num_threads) const { + DEFINE_DECODE_BATCH_FUNC_IMPL(DecodePiecesAsSerializedProto, std::string, + sentencepiece::util::bytes); + } + + std::vector + _DecodePiecesAsImmutableProtoBatch( + const std::vector> &ins, int num_threads) const { + DEFINE_DECODE_BATCH_FUNC_IMPL(DecodePiecesAsImmutableProto, std::string, + sentencepiece::ImmutableSentencePieceText); + } + + //////////////////////////////////////////////////////////////////////////// + // NBestEncodeAs* (Single request) + std::vector> + _NBestEncodeAsIds(absl::string_view text, + int nbest_size, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + auto idss = $self->NBestEncodeAsIds(text, nbest_size); + for (auto &ids : idss) { + RewriteIds(*$self, &ids, add_bos, add_eos, reverse, emit_unk_piece); + } + return idss; + } + + std::vector> + _NBestEncodeAsPieces(absl::string_view text, + int nbest_size, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + auto piecess = $self->NBestEncodeAsPieces(text, nbest_size); + for (auto &pieces : piecess) { + RewriteIds(*$self, &pieces, add_bos, add_eos, reverse, emit_unk_piece); + } + return piecess; + } + + sentencepiece::util::bytes + _NBestEncodeAsSerializedProto(absl::string_view text, + int nbest_size, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + RewriteIds(*$self, static_cast(nullptr), + add_bos, add_eos, reverse, emit_unk_piece); + return $self->NBestEncodeAsSerializedProto(text, nbest_size); + } + + sentencepiece::ImmutableNBestSentencePieceText + _NBestEncodeAsImmutableProto(absl::string_view text, + int nbest_size, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + RewriteIds(*$self, static_cast(nullptr), + add_bos, add_eos, reverse, emit_unk_piece); + auto proto = $self->NBestEncodeAsImmutableProto(text, nbest_size); + proto.ConvertToUnicodeSpans(); + return proto; + } + + + ///////////////////////////////////////////////////////////////////////////// + // SampleEncodeAndScoreAs* (Single request) + std::vector, float>> + _SampleEncodeAndScoreAsIds(absl::string_view text, + int num_samples, float alpha, bool wor, + bool include_best, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + auto idss = $self->SampleEncodeAndScoreAsIds(text, num_samples, + alpha, wor, include_best); + for (auto &ids : idss) { + RewriteIds(*$self, &ids.first, add_bos, add_eos, reverse, emit_unk_piece); + } + return idss; + } + + std::vector, float>> + _SampleEncodeAndScoreAsPieces(absl::string_view text, + int num_samples, float alpha, bool wor, + bool include_best, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + auto piecess = $self->SampleEncodeAndScoreAsPieces(text, num_samples, + alpha, wor, include_best); + for (auto &pieces : piecess) { + RewriteIds(*$self, &pieces.first, add_bos, add_eos, reverse, emit_unk_piece); + } + return piecess; + } + + sentencepiece::util::bytes + _SampleEncodeAndScoreAsSerializedProto(absl::string_view text, + int num_samples, float alpha, bool wor, + bool include_best, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + RewriteIds(*$self, static_cast(nullptr), + add_bos, add_eos, reverse, emit_unk_piece); + return $self->SampleEncodeAndScoreAsSerializedProto(text, num_samples, + alpha, wor, include_best); + } + + sentencepiece::ImmutableNBestSentencePieceText + _SampleEncodeAndScoreAsImmutableProto(absl::string_view text, + int num_samples, float alpha, bool wor, + bool include_best, + bool add_bos, bool add_eos, bool reverse, + bool emit_unk_piece) const { + RewriteIds(*$self, static_cast(nullptr), + add_bos, add_eos, reverse, emit_unk_piece); + auto proto = $self->SampleEncodeAndScoreAsImmutableProto(text, num_samples, + alpha, wor, include_best); + proto.ConvertToUnicodeSpans(); + return proto; + } + + // Normalize + std::string _Normalize(absl::string_view text) { + return $self->Normalize(text); + } + + std::pair> _NormalizeWithOffsets(absl::string_view text) { + std::pair> result; + $self->Normalize(text, &result.first, &result.second).IgnoreError(); + return result; + } + + // Calculate Entropy + float _CalculateEntropy(absl::string_view text, float alpha) { + return $self->CalculateEntropy(text, alpha); + } + + std::vector _CalculateEntropyBatch(const std::vector &ins, + float alpha, int num_threads) { + std::vector outs(ins.size()); + InitNumThreads(ins, &num_threads); + { + ThreadPool pool(ins.size()); + std::atomic index = 0; + for (int n = 0; n < num_threads; ++n) { + pool.Schedule([&]() { + size_t i = 0; + while ((i = std::atomic_fetch_add(&index, 1)) < outs.size()) { + outs[i] = self->CalculateEntropy(ins[i], alpha); + } + }); + } + } + return outs; + } + + // override normalizer_spec + sentencepiece::util::Status _OverrideNormalizerSpec( + const std::unordered_map &args) { + sentencepiece::util::Status status; + for (const auto &[key, value] : args) { + status = sentencepiece::SentencePieceTrainer::SetProtoField( + key, value, + $self->mutable_normalizer_spec()); + if (!status.ok()) return status; + } + return status; + } + +%pythoncode { + def Init(self, + model_file=None, + model_proto=None, + out_type=int, + add_bos=False, + add_eos=False, + reverse=False, + emit_unk_piece=False, + enable_sampling=False, + nbest_size=-1, + alpha=0.1, + num_threads=-1): + """Initialzie sentencepieceProcessor. + + Args: + model_file: The sentencepiece model file path. + model_proto: The sentencepiece model serialized proto. + out_type: output type. int or str. + add_bos: Add to the result (Default = false) + add_eos: Add to the result (Default = false) / is added after + reversing (if enabled). + reverse: Reverses the tokenized sequence (Default = false) + emit_unk_piece: Emits the unk literal string (Default = false) + nbest_size: sampling parameters for unigram. Invalid in BPE-Dropout. + nbest_size = {0,1}: No sampling is performed. + nbest_size > 1: samples from the nbest_size results. + nbest_size < 0: assuming that nbest_size is infinite and samples + from the all hypothesis (lattice) using + forward-filtering-and-backward-sampling algorithm. + alpha: Soothing parameter for unigram sampling, and dropout probability of + merge operations for BPE-dropout. + num_threads: number of threads in batch processing (Default = -1, auto-detected) + """ + + _sentencepiece_processor_init_native(self) + self._out_type = out_type + self._add_bos = add_bos + self._add_eos = add_eos + self._reverse = reverse + self._emit_unk_piece = emit_unk_piece + self._enable_sampling = enable_sampling + self._nbest_size = nbest_size + self._alpha = alpha + self._num_threads = num_threads + if model_file or model_proto: + self.Load(model_file=model_file, model_proto=model_proto) + + + def Encode(self, + input, + out_type=None, + add_bos=None, + add_eos=None, + reverse=None, + emit_unk_piece=None, + enable_sampling=None, + nbest_size=None, + alpha=None, + num_threads=None): + """Encode text input to segmented ids or tokens. + + Args: + input: input string. accepsts list of string. + out_type: output type. int or str. + add_bos: Add to the result (Default = false) + add_eos: Add to the result (Default = false) / is added after + reversing (if enabled). + reverse: Reverses the tokenized sequence (Default = false) + emit_unk_piece: Emits the unk literal string (Default = false) + nbest_size: sampling parameters for unigram. Invalid in BPE-Dropout. + nbest_size = {0,1}: No sampling is performed. + nbest_size > 1: samples from the nbest_size results. + nbest_size < 0: assuming that nbest_size is infinite and samples + from the all hypothesis (lattice) using + forward-filtering-and-backward-sampling algorithm. + alpha: Soothing parameter for unigram sampling, and merge probability for + BPE-dropout (probablity 'p' in BPE-dropout paper). + num_threads: the number of threads used in the batch processing (Default = -1). + """ + + if out_type is None: + out_type = self._out_type + if add_bos is None: + add_bos = self._add_bos + if add_eos is None: + add_eos = self._add_eos + if reverse is None: + reverse = self._reverse + if emit_unk_piece is None: + emit_unk_piece = self._emit_unk_piece + if enable_sampling is None: + enable_sampling = self._enable_sampling + if nbest_size is None: + nbest_size = self._nbest_size + if alpha is None: + alpha = self._alpha + if num_threads is None: + num_threads = self._num_threads + + if enable_sampling == True and (nbest_size is None or nbest_size == 0 or + nbest_size == 1 or alpha is None): + raise RuntimeError( + 'When enable_sampling is True, We must specify "nbest_size > 1" or "nbest_size = -1", ' + 'and "alpha". "nbest_size" is enabled only on unigram mode ignored in BPE-dropout. ' + 'when "nbest_size = -1" , this method samples from all candidates on the lattice ' + 'instead of nbest segmentations.' + ) + + if num_threads is None or type(num_threads) is not int: + raise RuntimeError('num_threads must be int') + + if type(input) is list: + if out_type is int: + return self._EncodeAsIdsBatch(input, num_threads, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + if out_type is str: + return self._EncodeAsPiecesBatch(input, num_threads, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + if out_type == 'serialized_proto' or out_type == 'proto': + return self._EncodeAsSerializedProtoBatch(input, num_threads, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + if out_type == 'immutable_proto': + return self._EncodeAsImmutableProtoBatch(input, num_threads, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + + if out_type is int: + return self._EncodeAsIds(input, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + if out_type is str: + return self._EncodeAsPieces(input, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + if out_type == 'serialized_proto' or out_type == 'proto': + return self._EncodeAsSerializedProto(input, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + if out_type == 'immutable_proto': + return self._EncodeAsImmutableProto(input, enable_sampling, nbest_size, + alpha, add_bos, add_eos, reverse, emit_unk_piece) + + raise RuntimeError('unknown out_type={}'.format(out_type)) + return None + + + def EncodeAsPieces(self, input, **kwargs): + return self.Encode(input=input, out_type=str, **kwargs) + + + def EncodeAsIds(self, input, **kwargs): + return self.Encode(input=input, out_type=int, **kwargs) + + + def EncodeAsSerializedProto(self, input, **kwargs): + return self.Encode(input=input, out_type='serialized_proto', **kwargs) + + + def EncodeAsImmutableProto(self, input, **kwargs): + return self.Encode(input=input, out_type='immutable_proto', **kwargs) + + + def SampleEncodeAsPieces(self, input, nbest_size=None, alpha=None, **kwargs): + return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha, + out_type=str, enable_sampling=True, **kwargs) + + + def SampleEncodeAsIds(self, input, nbest_size=None, alpha=None,**kwargs): + return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha, + out_type=int, enable_sampling=True, **kwargs) + + + def SampleEncodeAsSerializedProto(self, input, nbest_size=None, alpha=None, **kwargs): + return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha, + out_type='serialized_proto', enable_sampling=True, **kwargs) + + + def SampleEncodeAsImmutableProto(self, input, nbest_size=None, alpha=None, **kwargs): + return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha, + out_type='immutable_proto', enable_sampling=True, **kwargs) + + + def NBestEncode(self, + input, + out_type=None, + add_bos=None, + add_eos=None, + reverse=None, + emit_unk_piece=None, + nbest_size=None): + """NBestEncode text input to segmented ids or tokens. + + Args: + input: input string. accepsts list of string. + out_type: output type. int or str. + add_bos: Add to the result (Default = false) + add_eos: Add to the result (Default = false) / is added after reversing (if enabled). + reverse: Reverses the tokenized sequence (Default = false) + emit_unk_piece: Emits the unk literal string (Default = false) + nbest_size: nbest size + """ + + if out_type is None: + out_type = self._out_type + if add_bos is None: + add_bos = self._add_bos + if add_eos is None: + add_eos = self._add_eos + if reverse is None: + reverse = self._reverse + if emit_unk_piece is None: + emit_unk_piece = self._emit_unk_piece + if nbest_size is None: + nbest_size = self._nbest_size + + if nbest_size <= 0: + nbest_size=1 + + def _encode(text): + if out_type is int: + return self._NBestEncodeAsIds(text, nbest_size, + add_bos, add_eos, reverse, emit_unk_piece) + if out_type is str: + return self._NBestEncodeAsPieces(text, nbest_size, + add_bos, add_eos, reverse, emit_unk_piece) + if out_type == 'serialized_proto' or out_type == 'proto': + return self._NBestEncodeAsSerializedProto(text, nbest_size, + add_bos, add_eos, reverse, emit_unk_piece) + if out_type == 'immutable_proto': + return self._NBestEncodeAsImmutableProto(text, nbest_size, + add_bos, add_eos, reverse, emit_unk_piece) + + raise RuntimeError('unknown out_type') + + if type(input) is list: + return [_encode(n) for n in input] + + return _encode(input) + + + def NBestEncodeAsPieces(self, input, nbest_size=None, **kwargs): + return self.NBestEncode(input=input, nbest_size=nbest_size, + out_type=str, **kwargs) + + + def NBestEncodeAsIds(self, input, nbest_size=None, **kwargs): + return self.NBestEncode(input=input, nbest_size=nbest_size, + out_type=int, **kwargs) + + + def NBestEncodeAsSerializedProto(self, input, nbest_size=None, **kwargs): + return self.NBestEncode(input=input, nbest_size=nbest_size, + out_type='serialized_proto', **kwargs) + + + def NBestEncodeAsImmutableProto(self, input, nbest_size=None, **kwargs): + return self.NBestEncode(input=input, nbest_size=nbest_size, + out_type='immutable_proto', **kwargs) + + + def SampleEncodeAndScore(self, + input, + out_type=None, + add_bos=None, + add_eos=None, + reverse=None, + emit_unk_piece=None, + num_samples=None, + alpha=None, + wor=None, + include_best=None): + """SampleEncodeAndScore text input to segmented ids or tokens. + + Args: + input: input string. accepsts list of string. + out_type: output type. int or str or 'serialized_proto' or 'immutable_proto' + add_bos: Add to the result (Default = false) + add_eos: Add to the result (Default = false) / is added after reversing (if enabled). + reverse: Reverses the tokenized sequence (Default = false) + emit_unk_piece: Emits the unk literal string (Default = false) + num_samples: How many samples to return (Default = 1) + alpha: inverse temperature for sampling + wor: whether to sample without replacement (Default = false) + include_best: whether to include the best tokenization, requires wor=True (Default = false) + """ + + if out_type is None: + out_type = self._out_type + if add_bos is None: + add_bos = self._add_bos + if add_eos is None: + add_eos = self._add_eos + if reverse is None: + reverse = self._reverse + if emit_unk_piece is None: + emit_unk_piece = self._emit_unk_piece + if num_samples is None: + num_samples = 1 + if alpha is None: + alpha = 1. + if wor is None: + wor = False + if include_best is None: + include_best = False + + if num_samples <= 0: + raise RuntimeError('num_examples must be positive') + + if include_best and not wor: + raise RuntimeError('When include_best is True, We must specify "wor = True".') + + + def _encode(text): + if out_type is int: + return self._SampleEncodeAndScoreAsIds(text, num_samples, alpha, wor, include_best, + add_bos, add_eos, reverse, emit_unk_piece) + if out_type is str: + return self._SampleEncodeAndScoreAsPieces(text, num_samples, alpha, wor, include_best, + add_bos, add_eos, reverse, emit_unk_piece) + + if out_type == 'serialized_proto' or out_type == 'proto': + return self._SampleEncodeAndScoreAsSerializedProto(text, num_samples, alpha, wor, include_best, + add_bos, add_eos, reverse, emit_unk_piece) + + if out_type == 'immutable_proto': + return self._SampleEncodeAndScoreAsImmutableProto(text, num_samples, alpha, wor, include_best, + add_bos, add_eos, reverse, emit_unk_piece) + + raise RuntimeError('unknown output type') + + + if type(input) is list: + return [_encode(n) for n in input] + + return _encode(input) + + + def SampleEncodeAndScoreAsPieces(self, input, num_samples=None, alpha=None, **kwargs): + return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha, + out_type=str, **kwargs) + + + def SampleEncodeAndScoreAsIds(self, input, num_samples=None, alpha=None, **kwargs): + return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha, + out_type=int, **kwargs) + + + def SampleEncodeAndScoreAsSerializedProto(self, input, num_samples=None, alpha=None, **kwargs): + return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha, + out_type='serialized_proto', **kwargs) + + + def SampleEncodeAndScoreAsImmutableProto(self, input, num_samples=None, alpha=None, **kwargs): + return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha, + out_type='immutable_proto', **kwargs) + + + def Decode(self, input, out_type=str, num_threads=None): + """Decode processed id or token sequences. + + Args: + out_type: output type. str, bytes or 'serialized_proto' or 'immutable_proto' (Default = str) + num_threads: the number of threads used in the batch processing (Default = -1). + """ + + if num_threads is None: + num_threads = self._num_threads + + if num_threads is None or type(num_threads) is not int: + raise RuntimeError('num_threads must be int') + + if not input: + return '' + + if out_type is str: + if type(input) is int: + return self._DecodeIds([input]) + if type(input) is str: + return self._DecodePieces([input]) + + if type(input) is list: + if len(input) == 0 or type(input[0]) is int: + return self._DecodeIds(input) + if type(input[0]) is str: + return self._DecodePieces(input) + + if type(input[0]) is list: + if len(input[0]) == 0 or type(input[0][0]) is int: + return self._DecodeIdsBatch(input, num_threads) + if type(input[0][0]) is str: + return self._DecodePiecesBatch(input, num_threads) + + if out_type is bytes: + if type(input) is int: + return self._DecodeIdsAsBytes([input]) + if type(input) is str: + return self._DecodePieces([input]) + + if type(input) is list: + if len(input) == 0 or type(input[0]) is int: + return self._DecodeIdsAsBytes(input) + if type(input[0]) is str: + return self._DecodePieces(input) + + if type(input[0]) is list: + if len(input[0]) == 0 or type(input[0][0]) is int: + return self._DecodeIdsAsBytesBatch(input, num_threads) + if type(input[0][0]) is str: + return self._DecodePiecesBatch(input, num_threads) + + if out_type == 'serialized_proto': + if type(input) is int: + return self._DecodeIdsAsSerializedProto([input]) + if type(input) is str: + return self._DecodePiecesAsSerializedProto([input]) + + if type(input) is list: + if len(input) == 0 or type(input[0]) is int: + return self._DecodeIdsAsSerializedProto(input) + if type(input[0]) is str: + return self._DecodePiecesAsSerializedProto(input) + + if type(input[0]) is list: + if len(input[0]) == 0 or type(input[0][0]) is int: + return self._DecodeIdsAsSerializedProtoBatch(input, num_threads) + if type(input[0][0]) is str: + return self._DecodePiecesAsSerializedProtoBatch(input, num_threads) + + + if out_type == 'immutable_proto': + if type(input) is int: + return self._DecodeIdsAsImmutableProto([input]) + if type(input) is str: + return self._DecodePiecesAsImmutableProto([input]) + + if type(input) is list: + if len(input) == 0 or type(input[0]) is int: + return self._DecodeIdsAsImmutableProto(input) + if type(input[0]) is str: + return self._DecodePiecesAsImmutableProto(input) + + if type(input[0]) is list: + if len(input[0]) == 0 or type(input[0][0]) is int: + return self._DecodeIdsAsImmutableProtoBatch(input, num_threads) + if type(input[0][0]) is str: + return self._DecodePiecesAsImmutableProtoBatch(input, num_threads) + + + raise RuntimeError('unknown output or input type') + return None + + + def DecodePieces(self, input, out_type=str, **kwargs): + return self.Decode(input=input, out_type=out_type, **kwargs) + + + def DecodeIds(self, input, out_type=str, **kwargs): + return self.Decode(input=input, out_type=out_type, **kwargs) + + + def DecodePiecesAsSerializedProto(self, input, out_type='serialized_proto', **kwargs): + return self.Decode(input=input, out_type=out_type, **kwargs) + + + def DecodeIdsAsSerializedProto(self, input, out_type='serialized_proto', **kwargs): + return self.Decode(input=input, out_type=out_type, **kwargs) + + + def DecodePiecesAsImmutableProto(self, input, out_type='immutable_proto', **kwargs): + return self.Decode(input=input, out_type=out_type, **kwargs) + + + def DecodeIdsAsImmutableProto(self, input, out_type='immutable_proto', **kwargs): + return self.Decode(input=input, out_type=out_type, **kwargs) + + + def CalculateEntropy(self, input, alpha, num_threads=None): + """Calculate sentence entropy""" + if type(input) is list: + if num_threads is None: + num_threads = self._num_threads + if num_threads is None or type(num_threads) is not int: + raise RuntimeError('num_threads must be int') + return self._CalculateEntropyBatch(input, alpha, num_threads) + + return self._CalculateEntropy(input, alpha) + + + def Normalize(self, input, with_offsets=None): + def _normalize(text): + if with_offsets: + return self._NormalizeWithOffsets(text) + return self._Normalize(text) + + if type(input) is list: + return [_normalize(x) for x in input] + return _normalize(input) + + def OverrideNormalizerSpec(self, **kwargs): + new_kwargs = {} + for key, value in kwargs.items(): + new_kwargs[key] = str(value) + return self._OverrideNormalizerSpec(new_kwargs) + + + def piece_size(self): + return self.GetPieceSize() + + + def vocab_size(self): + return self.GetPieceSize() + + + def __getstate__(self): + return self.serialized_model_proto() + + + def __setstate__(self, serialized_model_proto): + self.__init__() + self.LoadFromSerializedProto(serialized_model_proto) + + + def __len__(self): + return self.GetPieceSize() + + + def __getitem__(self, piece): + return self.PieceToId(piece) + + + def Load(self, model_file=None, model_proto=None): + """Overwride SentencePieceProcessor.Load to support both model_file and model_proto. + + Args: + model_file: The sentencepiece model file path. + model_proto: The sentencepiece model serialized proto. Either `model_file` + or `model_proto` must be set. + """ + if model_file and model_proto: + raise RuntimeError('model_file and model_proto must be exclusive.') + if model_proto: + return self.LoadFromSerializedProto(model_proto) + return self.LoadFromFile(model_file) +} +} + +%extend sentencepiece::SentencePieceTrainer { + static void _TrainFromString(absl::string_view arg) { + const auto _status = sentencepiece::SentencePieceTrainer::Train(arg); + if (!_status.ok()) throw _status; + return; + } + + static void _TrainFromMap(const std::unordered_map &args) { + const auto _status = sentencepiece::SentencePieceTrainer::Train(args); + if (!_status.ok()) throw _status; + return; + } + + static void _TrainFromMap2(const std::unordered_map &args, + SentenceIterator *iter) { + const auto _status = sentencepiece::SentencePieceTrainer::Train(args, iter); + if (!_status.ok()) throw _status; + return; + } + + static sentencepiece::util::bytes _TrainFromMap3(const std::unordered_map &args) { + sentencepiece::util::bytes model_proto; + const auto _status = sentencepiece::SentencePieceTrainer::Train(args, nullptr, &model_proto); + if (!_status.ok()) throw _status; + return model_proto; + } + + static sentencepiece::util::bytes _TrainFromMap4(const std::unordered_map &args, + SentenceIterator *iter) { + sentencepiece::util::bytes model_proto; + const auto _status = sentencepiece::SentencePieceTrainer::Train(args, iter, &model_proto); + if (!_status.ok()) throw _status; + return model_proto; + } + +%pythoncode { + @staticmethod + def _Train(arg=None, **kwargs): + """Train Sentencepiece model. Accept both kwargs and legacy string arg.""" + if arg is not None and type(arg) is str: + return SentencePieceTrainer._TrainFromString(arg) + + def _encode(value): + """Encode value to CSV..""" + if type(value) is list: + if sys.version_info[0] == 3: + f = StringIO() + else: + f = BytesIO() + writer = csv.writer(f, lineterminator='') + writer.writerow([str(v) for v in value]) + return f.getvalue() + else: + return str(value) + + sentence_iterator = None + model_writer = None + new_kwargs = {} + for key, value in kwargs.items(): + if key in ['sentence_iterator', 'sentence_reader']: + sentence_iterator = value + elif key in ['model_writer']: + model_writer = value + else: + new_kwargs[key] = _encode(value) + + if model_writer: + if sentence_iterator: + model_proto = SentencePieceTrainer._TrainFromMap4(new_kwargs, + sentence_iterator) + else: + model_proto = SentencePieceTrainer._TrainFromMap3(new_kwargs) + model_writer.write(model_proto) + else: + if sentence_iterator: + return SentencePieceTrainer._TrainFromMap2(new_kwargs, sentence_iterator) + else: + return SentencePieceTrainer._TrainFromMap(new_kwargs) + + return None + + @staticmethod + def Train(arg=None, logstream=None, **kwargs): + with _LogStream(ostream=logstream): + SentencePieceTrainer._Train(arg=arg, **kwargs) +} +} + +%extend sentencepiece::SentencePieceNormalizer { + sentencepiece::util::Status LoadFromFile(absl::string_view arg) { + return $self->Load(arg); + } + + std::string _Normalize(absl::string_view text) { + std::string result; + const auto _status = $self->Normalize(text, &result); + if (!_status.ok()) throw _status; + return result; + } + + std::pair> _NormalizeWithOffsets(absl::string_view text) { + std::pair> result; + const auto _status = $self->Normalize(text, &result.first, &result.second); + if (!_status.ok()) throw _status; + return result; + } + + void _SetProtoField(absl::string_view name, bool value) { + sentencepiece::SentencePieceTrainer::SetProtoField( + name, + value ? "1" : "0", + $self->mutable_normalizer_spec()).IgnoreError(); + } + +%pythoncode %{ + def Init(self, + model_file=None, + model_proto=None, + rule_tsv=None, + rule_name=None, + add_dummy_prefix=False, + escape_whitespaces=False, + remove_extra_whitespaces=False): + """Initialzie sentencePieceNormalizer. + + Args: + model_file: The sentencepiece model file path. + model_proto: The sentencepiece model serialized proto. + rule_tsv: The normalization rule file in TSV format. + rule_name: Pre-defined normalization name. + add_dummy_prefix: add dummy prefix. + escape_whitespaces: escape whitespaces. + remove_extra_whitespaces: remove extra whitespaces. + """ + + _sentencepiece_normalizer_init_native(self) + + if model_file: + status = self.LoadFromFile(model_file) + elif model_proto: + status = self.LoadFromSerializedProto(model_proto) + elif rule_tsv: + status = self.LoadFromRuleTSV(rule_tsv) + elif rule_name: + status = self.LoadFromRuleName(rule_name) + else: + raise RuntimeError('no model is specified') + + if status: + self._SetProtoField('add_dummy_prefix', add_dummy_prefix) + self._SetProtoField('escape_whitespaces', escape_whitespaces) + self._SetProtoField('remove_extra_whitespaces', remove_extra_whitespaces) + + def Normalize(self, input, with_offsets=None): + def _normalize(text): + if with_offsets: + return self._NormalizeWithOffsets(text) + return self._Normalize(text) + + if type(input) is list: + return [_normalize(x) for x in input] + return _normalize(input) + + + def __getstate__(self): + return self.serialized_model_proto() + + + def __setstate__(self, serialized_model_proto): + self.__init__() + self.LoadFromSerializedProto(serialized_model_proto) +%} +} + +%extend sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece { + const sentencepiece::util::bytes& _surface_as_bytes() const { + return $self->surface(); + } + + const sentencepiece::util::bytes& _piece_as_bytes() const { + return $self->piece(); + } + + %rename(_piece) piece; + %rename(_piece_as_bytes) piece_as_bytes; + %rename(_id) id; + %rename(_surface) surface; + %rename(_surface_as_bytes) surface_as_bytes; + %rename(_begin) begin; + %rename(_end) end; + + %pythoncode %{ + piece = property(_piece) + piece_as_bytes = property(_piece_as_bytes) + surface = property(_surface) + surface_as_bytes = property(_surface_as_bytes) + id = property(_id) + begin = property(_begin) + end = property(_end) + + def __str__(self): + return ('piece: \"{}\"\n' + 'id: {}\n' + 'surface: \"{}\"\n' + 'begin: {}\n' + 'end: {}\n').format(self.piece, self.id, self.surface, + self.begin, self.end) + + def __eq__(self, other): + return self.piece == other.piece and self.id == other.id and self.surface == other.surface and self.begin == other.begin and self.end == other.end + + def __hash__(self): + return hash(str(self)) + + __repr__ = __str__ + %} +} + +%extend sentencepiece::ImmutableSentencePieceText { + const sentencepiece::util::bytes& _text_as_bytes() const { + return $self->text(); + } + + %rename(_text) text; + %rename(_text_as_bytes) text_as_bytes; + %rename(_score) score; + %rename(_pieces) pieces; + %rename(_pieces_size) pieces_size; + + %pythoncode %{ + text = property(_text) + text_as_bytes = property(_text_as_bytes) + score = property(_score) + + class ImmutableSentencePieceIterator: + def __init__(self, proto): + self.proto = proto + self.len = self.proto._pieces_size() + + def __len__(self): + return self.len + + def __getitem__(self, index): + if isinstance(index, slice): + return [self.proto._pieces(i) for i in range(self.len)][index.start:index.stop:index.step] + if index < 0: + index = index + self.len + if index < 0 or index >= self.len: + raise IndexError('piece index is out of range') + return self.proto._pieces(index) + + def __str__(self): + return '\n'.join(['pieces {{\n{}}}'.format(str(x)) for x in self]) + + __repr__ = __str__ + + @property + def pieces(self): + return ImmutableSentencePieceText.ImmutableSentencePieceIterator(self) + + def __eq__(self, other): + return self.SerializeAsString() == other.SerializeAsString() + + def __hash__(self): + return hash(self.SerializeAsString()) + + def __str__(self): + return ('text: \"{}\"\n' + 'score: {}\n' + '{}').format(self.text, self.score, + '\n'.join(['pieces {{\n{}}}'.format(str(x)) for x in self.pieces])) + + __repr__ = __str__ + %} +} + +%extend sentencepiece::ImmutableNBestSentencePieceText { + %rename(_nbests) nbests; + %rename(_nbests_size) nbests_size; + + %pythoncode %{ + class ImmutableSentencePieceTextIterator: + def __init__(self, proto): + self.proto = proto + self.len = self.proto._nbests_size() + + def __len__(self): + return self.len + + def __getitem__(self, index): + if isinstance(index, slice): + return [self.proto._nbests(i) for i in range(self.len)][index.start:index.stop:index.step] + if index < 0: + index = index + self.len + if index < 0 or index >= self.len: + raise IndexError('nbests index is out of range') + return self.proto._nbests(index) + + def __str__(self): + return '\n'.join(['nbests {{\n{}}}'.format(str(x)) for x in self]) + + __repr__ = __str__ + + @property + def nbests(self): + return ImmutableNBestSentencePieceText.ImmutableSentencePieceTextIterator(self) + + def __eq__(self, other): + return self.SerializeAsString() == other.SerializeAsString() + + def __hash__(self): + return hash(self.SerializeAsString()) + + def __str__(self): + return '\n'.join(['nbests {{\n{}}}'.format(str(x)) for x in self.nbests]) + + __repr__ = __str__ + %} +} + +%typemap(out) std::vector { + $result = PyList_New($1.size()); + for (size_t i = 0; i < $1.size(); ++i) { + PyList_SET_ITEM($result, i, PyInt_FromLong(static_cast($1[i]))); + } +} + +%typemap(out) std::vector { + $result = PyList_New($1.size()); + for (size_t i = 0; i < $1.size(); ++i) { + PyList_SET_ITEM($result, i, PyFloat_FromDouble(static_cast($1[i]))); + } +} + +%typemap(out) std::vector> { + $result = PyList_New($1.size()); + for (size_t i = 0; i < $1.size(); ++i) { + PyObject *obj = PyList_New($1[i].size()); + for (size_t j = 0; j < $1[i].size(); ++j) { + PyList_SET_ITEM(obj, j, PyInt_FromLong(static_cast($1[i][j]))); + } + PyList_SET_ITEM($result, i, obj); + } +} + +%typemap(out) std::vector { + PyObject *input_type = resultobj; + $result = PyList_New($1.size()); + for (size_t i = 0; i < $1.size(); ++i) { + PyList_SET_ITEM($result, i, MakePyOutputString($1[i], input_type)); + } +} + +%typemap(out) BytesArray { + $result = PyList_New($1.size()); + for (size_t i = 0; i < $1.size(); ++i) { + PyList_SET_ITEM($result, i, MakePyOutputBytes($1[i])); + } +} + +%typemap(out) std::vector> { + PyObject *input_type = resultobj; + $result = PyList_New($1.size()); + for (size_t i = 0; i < $1.size(); ++i) { + PyObject *obj = PyList_New($1[i].size()); + for (size_t j = 0; j < $1[i].size(); ++j) { + PyList_SET_ITEM(obj, j, MakePyOutputString($1[i][j], input_type)); + } + PyList_SET_ITEM($result, i, obj); + } +} + +%typemap(out) sentencepiece::util::bytes { + $result = MakePyOutputBytes($1); +} + +%typemap(out) const sentencepiece::util::bytes& { + $result = MakePyOutputBytes(*$1); +} + +%typemap(out) std::string { + PyObject *input_type = resultobj; + $result = MakePyOutputString($1, input_type); +} + +%typemap(out) const std::string& { + PyObject *input_type = resultobj; + $result = MakePyOutputString(*$1, input_type); +} + +%typemap(out) sentencepiece::util::Status { + if (!$1.ok()) { + SWIG_exception(ToSwigError($1.code()), $1.ToString().c_str()); + } + $result = SWIG_From_bool($1.ok());} + + +%typemap(in) const std::string & { + const PyInputString ustring($input); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + $1 = new std::string(ustring.data(), ustring.size()); +} + +%typemap(typecheck) absl::string_view = char *; + +%typemap(in) absl::string_view { + const PyInputString ustring($input); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + $1 = ustring.str(); +} + +%typemap(in) const std::vector& { + std::vector *out = nullptr; + if (PyList_Check($input)) { + const size_t size = PyList_Size($input); + out = new std::vector(size); + for (size_t i = 0; i < size; ++i) { + const PyInputString ustring(PyList_GetItem($input, i)); + if (ustring.IsAvalable()) { + (*out)[i] = ustring.str(); + } else { + PyErr_SetString(PyExc_TypeError, "list must contain strings"); + SWIG_fail; + } + resultobj = ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a list"); + SWIG_fail; + } + $1 = out; +} + +%typemap(in) const std::vector& { + std::vector *out = nullptr; + if (PyList_Check($input)) { + const size_t size = PyList_Size($input); + out = new std::vector(size); + for (size_t i = 0; i < size; ++i) { + PyObject *o = PyList_GetItem($input, i); + if (PyInt_Check(o)) { + (*out)[i] = static_cast(PyInt_AsLong(o)); + } else { + PyErr_SetString(PyExc_TypeError,"list must contain integers"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + $1 = out; +} + +%typemap(in) const std::vector>& { + std::vector> *out = nullptr; + if (PyList_Check($input)) { + const size_t size = PyList_Size($input); + out = new std::vector>(size); + for (size_t i = 0; i < size; ++i) { + PyObject *o = PyList_GetItem($input, i); + if (PyList_Check(o)) { + const size_t size2 = PyList_Size(o); + (*out)[i].resize(size2); + for (size_t j = 0; j < size2; ++j) { + const PyInputString ustring(PyList_GetItem(o, j)); + if (ustring.IsAvalable()) { + (*out)[i][j] = ustring.str(); + } else { + PyErr_SetString(PyExc_TypeError,"list must contain integers"); + SWIG_fail; + } + resultobj = ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + $1 = out; +} + +%typemap(in) const std::vector>& { + std::vector> *out = nullptr; + if (PyList_Check($input)) { + const size_t size = PyList_Size($input); + out = new std::vector>(size); + for (size_t i = 0; i < size; ++i) { + PyObject *o = PyList_GetItem($input, i); + if (PyList_Check(o)) { + const size_t size2 = PyList_Size(o); + (*out)[i].resize(size2); + for (size_t j = 0; j < size2; ++j) { + PyObject *o2 = PyList_GetItem(o, j); + if (PyInt_Check(o2)) { + (*out)[i][j] = static_cast(PyInt_AsLong(o2)); + } else { + PyErr_SetString(PyExc_TypeError, "list must contain strings"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError, "not a list"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + $1 = out; +} + +%typemap(in) const std::unordered_map & { + std::unordered_map *out = nullptr; + if (PyDict_Check($input)) { + PyObject *key, *value; + Py_ssize_t pos = 0; + out = new std::unordered_map; + while (PyDict_Next($input, &pos, &key, &value)) { + const PyInputString key_ustring(key); + const PyInputString value_ustring(value); + if (key_ustring.IsAvalable() && value_ustring.IsAvalable()) { + out->emplace(std::string(key_ustring.data(), key_ustring.size()), + std::string(value_ustring.data(), value_ustring.size())); + } else { + PyErr_SetString(PyExc_TypeError, "map must contain strings."); + SWIG_fail; + } + resultobj = key_ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a dictionary"); + SWIG_fail; + } + $1 = out; +} + +%typemap(out) std::vector, float>> { + PyObject *input_type = resultobj; + $result = PyList_New($1.size()); + for (size_t i = 0; i < $1.size(); ++i) { + PyObject *obj = PyList_New($1[i].first.size()); + for (size_t j = 0; j < $1[i].first.size(); ++j) { + PyList_SET_ITEM(obj, j, MakePyOutputString($1[i].first[j], input_type)); + } + PyList_SET_ITEM($result, i, PyTuple_Pack(2, obj, PyFloat_FromDouble(static_cast($1[i].second)))); + } +} + +%typemap(out) std::vector, float>> { + $result = PyList_New($1.size()); + for (size_t i = 0; i < $1.size(); ++i) { + PyObject *obj = PyList_New($1[i].first.size()); + for (size_t j = 0; j < $1[i].first.size(); ++j) { + PyList_SET_ITEM(obj, j, PyInt_FromLong(static_cast($1[i].first[j]))); + } + PyList_SET_ITEM($result, i, PyTuple_Pack(2, obj, PyFloat_FromDouble(static_cast($1[i].second)))); + } +} + +%typemap(out) std::vector { + $result = PyList_New($1.size()); + for (size_t i = 0; i < $1.size(); ++i) { + PyObject *obj = SWIG_NewPointerObj(new sentencepiece::ImmutableSentencePieceText($1.at(i)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN | 0); + PyList_SET_ITEM($result, i, obj); + } +} + +// Types for normalized string and offset +%typemap(out) std::pair> { + PyObject *input_type = resultobj; + if (PyInputString::IsUnicode(input_type)) { + sentencepiece::ConvertToUnicodeAlignment(arg2, $1.first, &$1.second); + } + PyObject *obj = PyList_New($1.second.size()); + for (size_t i = 0; i < $1.second.size(); ++i) { + PyList_SET_ITEM(obj, i, PyInt_FromLong(static_cast($1.second[i]))); + } + $result = PyTuple_Pack(2, MakePyOutputString($1.first, input_type), obj); +} + +%typemap(in) sentencepiece::SentenceIterator * { + sentencepiece::SentenceIterator *out = nullptr; + if (PyIter_Check($input)) { + out = new PySentenceIterator($input); + } else { + PyErr_SetString(PyExc_TypeError, "not a iterator"); + SWIG_fail; + } + $1 = out; +} + +%typemap(freearg) const std::string& { + delete $1; +} + +%typemap(freearg) const std::vector& { + delete $1; +} + +%typemap(freearg) const std::vector& { + delete $1; +} + +%typemap(freearg) const std::vector>& { + delete $1; +} + +%typemap(freearg) const std::vector& { + delete $1; +} + +%typemap(freearg) const std::vector& { + delete $1; +} + +%typemap(freearg) const std::vector>& { + delete $1; +} + +%typemap(freearg) const std::unordered_map & { + delete $1; +} + +%typemap(freearg) sentencepiece::SentenceIterator * { + delete $1; +} + +%typemap(freearg) sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece { + delete $1; +} + +%typemap(freearg) sentencepiece::ImmutableSentencePieceText { + delete $1; +} + +%typemap(freearg) sentencepiece::ImmutableNBestSentencePieceText { + delete $1; +} + +%include +%include + +%pythoncode %{ + +import re +import csv +import sys +import os +import importlib.resources +from io import StringIO +from io import BytesIO + + +def _add_snake_case(classname): + """Added snake_cased method from CammelCased method.""" + + snake_map = {} + for k, v in classname.__dict__.items(): + if re.match(r'^[A-Z]+', k): + snake = re.sub(r'(?= v.piece_size()): + raise IndexError('piece id is out of range.') + return func(v, n) + + def _batched_func(self, arg): + if type(arg) is list: + return [_func(self, n) for n in arg] + else: + return _func(self, arg) + + setattr(classname, name, _batched_func) + + +_sentencepiece_processor_init_native = SentencePieceProcessor.__init__ +_sentencepiece_normalizer_init_native = SentencePieceNormalizer.__init__ +setattr(SentencePieceProcessor, '__init__', SentencePieceProcessor.Init) +setattr(SentencePieceNormalizer, '__init__', SentencePieceNormalizer.Init) + +SentencePieceProcessor.Tokenize = SentencePieceProcessor.Encode +SentencePieceProcessor.Detokenize = SentencePieceProcessor.Decode + +for m in [ + 'PieceToId', 'IdToPiece', 'GetScore', 'IsUnknown', 'IsControl', 'IsUnused', + 'IsByte' +]: + _batchnize(SentencePieceProcessor, m) + +_add_snake_case(SentencePieceProcessor) +_add_snake_case(SentencePieceTrainer) +_add_snake_case(SentencePieceNormalizer) +set_random_generator_seed = SetRandomGeneratorSeed +set_min_log_level = SetMinLogLevel + +from ._version import __version__ + +SetDataDir(os.path.join(str(importlib.resources.files('sentencepiece')), 'package_data')) + +class _LogStream(object): + def __init__(self, ostream=None): + self.ostream = ostream + if self.ostream is not None: + self.orig_stream_fileno = sys.stderr.fileno() + + def __enter__(self): + if self.ostream is not None: + self.orig_stream_dup = os.dup(self.orig_stream_fileno) + os.dup2(self.ostream.fileno(), self.orig_stream_fileno) + + def __exit__(self, type, value, traceback): + if self.ostream is not None: + os.close(self.orig_stream_fileno) + os.dup2(self.orig_stream_dup, self.orig_stream_fileno) + os.close(self.orig_stream_dup) + self.ostream.close() +%} diff --git a/venv/lib/python3.10/site-packages/sentencepiece/sentencepiece_model_pb2.py b/venv/lib/python3.10/site-packages/sentencepiece/sentencepiece_model_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..b07107d69de178e107544a29bb4d0280b5482241 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sentencepiece/sentencepiece_model_pb2.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: sentencepiece_model.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x19sentencepiece_model.proto\x12\rsentencepiece\"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12\"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12\"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18\" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05\x12\x16\n\tbos_piece\x18. \x01(\t:\x03\x12\x17\n\teos_piece\x18/ \x01(\t:\x04\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse\"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32\".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL\"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sentencepiece_model_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'H\003' + _TRAINERSPEC.fields_by_name['mining_sentence_size']._options = None + _TRAINERSPEC.fields_by_name['mining_sentence_size']._serialized_options = b'\030\001' + _TRAINERSPEC.fields_by_name['training_sentence_size']._options = None + _TRAINERSPEC.fields_by_name['training_sentence_size']._serialized_options = b'\030\001' + _TRAINERSPEC._serialized_start=45 + _TRAINERSPEC._serialized_end=1581 + _TRAINERSPEC_MODELTYPE._serialized_start=1517 + _TRAINERSPEC_MODELTYPE._serialized_end=1570 + _NORMALIZERSPEC._serialized_start=1584 + _NORMALIZERSPEC._serialized_end=1793 + _SELFTESTDATA._serialized_start=1795 + _SELFTESTDATA._serialized_end=1916 + _SELFTESTDATA_SAMPLE._serialized_start=1864 + _SELFTESTDATA_SAMPLE._serialized_end=1905 + _MODELPROTO._serialized_start=1919 + _MODELPROTO._serialized_end=2429 + _MODELPROTO_SENTENCEPIECE._serialized_start=2208 + _MODELPROTO_SENTENCEPIECE._serialized_end=2418 + _MODELPROTO_SENTENCEPIECE_TYPE._serialized_start=2323 + _MODELPROTO_SENTENCEPIECE_TYPE._serialized_end=2407 +# @@protoc_insertion_point(module_scope) diff --git a/venv/lib/python3.10/site-packages/sentencepiece/sentencepiece_pb2.py b/venv/lib/python3.10/site-packages/sentencepiece/sentencepiece_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..840cfd2143a47d8a972008bd946a8dd271aa0a0f --- /dev/null +++ b/venv/lib/python3.10/site-packages/sentencepiece/sentencepiece_pb2.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: sentencepiece.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x13sentencepiece.proto\x12\rsentencepiece\"\xdf\x01\n\x11SentencePieceText\x12\x0c\n\x04text\x18\x01 \x01(\t\x12>\n\x06pieces\x18\x02 \x03(\x0b\x32..sentencepiece.SentencePieceText.SentencePiece\x12\r\n\x05score\x18\x03 \x01(\x02\x1a\x62\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\n\n\x02id\x18\x02 \x01(\r\x12\x0f\n\x07surface\x18\x03 \x01(\t\x12\r\n\x05\x62\x65gin\x18\x04 \x01(\r\x12\x0b\n\x03\x65nd\x18\x05 \x01(\r*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"J\n\x16NBestSentencePieceText\x12\x30\n\x06nbests\x18\x01 \x03(\x0b\x32 .sentencepiece.SentencePieceTextB\x02H\x03') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sentencepiece_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'H\003' + _SENTENCEPIECETEXT._serialized_start=39 + _SENTENCEPIECETEXT._serialized_end=262 + _SENTENCEPIECETEXT_SENTENCEPIECE._serialized_start=153 + _SENTENCEPIECETEXT_SENTENCEPIECE._serialized_end=251 + _NBESTSENTENCEPIECETEXT._serialized_start=264 + _NBESTSENTENCEPIECETEXT._serialized_end=338 +# @@protoc_insertion_point(module_scope) diff --git a/venv/lib/python3.10/site-packages/sentencepiece/sentencepiece_wrap.cxx b/venv/lib/python3.10/site-packages/sentencepiece/sentencepiece_wrap.cxx new file mode 100644 index 0000000000000000000000000000000000000000..e6c3d659469e6cbe9c7bab2d8349fa289cd758b1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sentencepiece/sentencepiece_wrap.cxx @@ -0,0 +1,10628 @@ +/* ---------------------------------------------------------------------------- + * This file was automatically generated by SWIG (https://www.swig.org). + * Version 4.3.0 + * + * Do not make changes to this file unless you know what you are doing - modify + * the SWIG interface file instead. + * ----------------------------------------------------------------------------- */ + + +#define SWIG_VERSION 0x040300 +#define SWIGPYTHON +#define SWIG_PYTHON_DIRECTOR_NO_VTABLE + +#define SWIG_name "_sentencepiece" +/* ----------------------------------------------------------------------------- + * This section contains generic SWIG labels for method/variable + * declarations/attributes, and other compiler dependent labels. + * ----------------------------------------------------------------------------- */ + +/* template workaround for compilers that cannot correctly implement the C++ standard */ +#ifndef SWIGTEMPLATEDISAMBIGUATOR +# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) +# define SWIGTEMPLATEDISAMBIGUATOR template +# elif defined(__HP_aCC) +/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ +/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ +# define SWIGTEMPLATEDISAMBIGUATOR template +# else +# define SWIGTEMPLATEDISAMBIGUATOR +# endif +#endif + +/* inline attribute */ +#ifndef SWIGINLINE +# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) +# define SWIGINLINE inline +# else +# define SWIGINLINE +# endif +#endif + +/* attribute recognised by some compilers to avoid 'unused' warnings */ +#ifndef SWIGUNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define SWIGUNUSED __attribute__ ((__unused__)) +# else +# define SWIGUNUSED +# endif +# elif defined(__ICC) +# define SWIGUNUSED __attribute__ ((__unused__)) +# else +# define SWIGUNUSED +# endif +#endif + +#ifndef SWIG_MSC_UNSUPPRESS_4505 +# if defined(_MSC_VER) +# pragma warning(disable : 4505) /* unreferenced local function has been removed */ +# endif +#endif + +#ifndef SWIGUNUSEDPARM +# ifdef __cplusplus +# define SWIGUNUSEDPARM(p) +# else +# define SWIGUNUSEDPARM(p) p SWIGUNUSED +# endif +#endif + +/* internal SWIG method */ +#ifndef SWIGINTERN +# define SWIGINTERN static SWIGUNUSED +#endif + +/* internal inline SWIG method */ +#ifndef SWIGINTERNINLINE +# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE +#endif + +/* exporting methods */ +#if defined(__GNUC__) +# if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) +# ifndef GCC_HASCLASSVISIBILITY +# define GCC_HASCLASSVISIBILITY +# endif +# endif +#endif + +#ifndef SWIGEXPORT +# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) +# if defined(STATIC_LINKED) +# define SWIGEXPORT +# else +# define SWIGEXPORT __declspec(dllexport) +# endif +# else +# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) +# define SWIGEXPORT __attribute__ ((visibility("default"))) +# else +# define SWIGEXPORT +# endif +# endif +#endif + +/* calling conventions for Windows */ +#ifndef SWIGSTDCALL +# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) +# define SWIGSTDCALL __stdcall +# else +# define SWIGSTDCALL +# endif +#endif + +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ +#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) +# define _CRT_SECURE_NO_DEPRECATE +#endif + +/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ +#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) +# define _SCL_SECURE_NO_DEPRECATE +#endif + +/* Deal with Apple's deprecated 'AssertMacros.h' from Carbon-framework */ +#if defined(__APPLE__) && !defined(__ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES) +# define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0 +#endif + +/* Intel's compiler complains if a variable which was never initialised is + * cast to void, which is a common idiom which we use to indicate that we + * are aware a variable isn't used. So we just silence that warning. + * See: https://github.com/swig/swig/issues/192 for more discussion. + */ +#ifdef __INTEL_COMPILER +# pragma warning disable 592 +#endif + +#if defined(__cplusplus) && __cplusplus >=201103L +# define SWIG_NULLPTR nullptr +#else +# define SWIG_NULLPTR NULL +#endif + +/* ----------------------------------------------------------------------------- + * swigcompat.swg + * + * Macros to provide support compatibility with older C and C++ standards. + * + * Note that SWIG expects __cplusplus to be defined to the appropriate C++ standard. + * MSVC users are urged to check and examine the /Zc:__cplusplus compiler option. + * See https://learn.microsoft.com/en-us/cpp/build/reference/zc-cplusplus. + * ----------------------------------------------------------------------------- */ + +/* C99 and C++11 should provide snprintf, but define SWIG_NO_SNPRINTF + * if you're missing it. + */ +#if ((defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L) || \ + (defined __cplusplus && __cplusplus >= 201103L) || \ + defined SWIG_HAVE_SNPRINTF) && \ + !defined SWIG_NO_SNPRINTF +# define SWIG_snprintf(O,S,F,A) snprintf(O,S,F,A) +# define SWIG_snprintf2(O,S,F,A,B) snprintf(O,S,F,A,B) +#else +/* Fallback versions ignore the buffer size, but most of our uses either have a + * fixed maximum possible size or dynamically allocate a buffer that's large + * enough. + */ +# define SWIG_snprintf(O,S,F,A) sprintf(O,F,A) +# define SWIG_snprintf2(O,S,F,A,B) sprintf(O,F,A,B) +#endif + + +#if defined(__GNUC__) && defined(_WIN32) && !defined(SWIG_PYTHON_NO_HYPOT_WORKAROUND) +/* Workaround for '::hypot' has not been declared', see https://bugs.python.org/issue11566 */ +# include +#endif + +#if !defined(PY_SSIZE_T_CLEAN) && !defined(SWIG_NO_PY_SSIZE_T_CLEAN) +#define PY_SSIZE_T_CLEAN +#endif + +#if __GNUC__ >= 7 +#pragma GCC diagnostic push +#if defined(__cplusplus) && __cplusplus >=201703L +#pragma GCC diagnostic ignored "-Wregister" /* For python-2.7 headers that use register */ +#endif +#endif + +#if defined(_DEBUG) && defined(SWIG_PYTHON_INTERPRETER_NO_DEBUG) +/* Use debug wrappers with the Python release dll */ + +#if defined(_MSC_VER) && _MSC_VER >= 1929 +/* Workaround compilation errors when redefining _DEBUG in MSVC 2019 version 16.10 and later + * See https://github.com/swig/swig/issues/2090 */ +# include +#endif + +# undef _DEBUG +# include +# define _DEBUG 1 +#else +# include +#endif + +#if !defined(SWIGPYTHON_BUILTIN) && PY_VERSION_HEX >= 0x03030000 +# define SWIG_HEAPTYPES + +/* Note: Currently this won't activate - it is in place ready for when the + * SWIGPYTHON_BUILTIN condition above gets removed. */ +# if PY_VERSION_HEX < 0x030c0000 && defined(SWIGPYTHON_BUILTIN) +# include +# define Py_READONLY READONLY +# define Py_T_PYSSIZET T_PYSSIZET +# endif +#endif + +#if __GNUC__ >= 7 +#pragma GCC diagnostic pop +#endif + +#include +#include + +/* ----------------------------------------------------------------------------- + * swigrun.swg + * + * This file contains generic C API SWIG runtime support for pointer + * type checking. + * ----------------------------------------------------------------------------- */ + +/* This should only be incremented when either the layout of swig_type_info changes, + or for whatever reason, the runtime changes incompatibly */ +#define SWIG_RUNTIME_VERSION "4" + +/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ +#ifdef SWIG_TYPE_TABLE +# define SWIG_QUOTE_STRING(x) #x +# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) +# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) +#else +# define SWIG_TYPE_TABLE_NAME +#endif + +/* + You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for + creating a static or dynamic library from the SWIG runtime code. + In 99.9% of the cases, SWIG just needs to declare them as 'static'. + + But only do this if strictly necessary, ie, if you have problems + with your compiler or suchlike. +*/ + +#ifndef SWIGRUNTIME +# define SWIGRUNTIME SWIGINTERN +#endif + +#ifndef SWIGRUNTIMEINLINE +# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE +#endif + +/* Generic buffer size */ +#ifndef SWIG_BUFFER_SIZE +# define SWIG_BUFFER_SIZE 1024 +#endif + +/* Flags for pointer conversions */ +#define SWIG_POINTER_DISOWN 0x1 +#define SWIG_CAST_NEW_MEMORY 0x2 +#define SWIG_POINTER_NO_NULL 0x4 +#define SWIG_POINTER_CLEAR 0x8 +#define SWIG_POINTER_RELEASE (SWIG_POINTER_CLEAR | SWIG_POINTER_DISOWN) + +/* Flags for new pointer objects */ +#define SWIG_POINTER_OWN 0x1 + + +/* + Flags/methods for returning states. + + The SWIG conversion methods, as ConvertPtr, return an integer + that tells if the conversion was successful or not. And if not, + an error code can be returned (see swigerrors.swg for the codes). + + Use the following macros/flags to set or process the returning + states. + + In old versions of SWIG, code such as the following was usually written: + + if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { + // success code + } else { + //fail code + } + + Now you can be more explicit: + + int res = SWIG_ConvertPtr(obj,vptr,ty.flags); + if (SWIG_IsOK(res)) { + // success code + } else { + // fail code + } + + which is the same really, but now you can also do + + Type *ptr; + int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); + if (SWIG_IsOK(res)) { + // success code + if (SWIG_IsNewObj(res) { + ... + delete *ptr; + } else { + ... + } + } else { + // fail code + } + + I.e., now SWIG_ConvertPtr can return new objects and you can + identify the case and take care of the deallocation. Of course that + also requires SWIG_ConvertPtr to return new result values, such as + + int SWIG_ConvertPtr(obj, ptr,...) { + if () { + if () { + *ptr = ; + return SWIG_NEWOBJ; + } else { + *ptr = ; + return SWIG_OLDOBJ; + } + } else { + return SWIG_BADOBJ; + } + } + + Of course, returning the plain '0(success)/-1(fail)' still works, but you can be + more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the + SWIG errors code. + + Finally, if the SWIG_CASTRANK_MODE is enabled, the result code + allows returning the 'cast rank', for example, if you have this + + int food(double) + int fooi(int); + + and you call + + food(1) // cast rank '1' (1 -> 1.0) + fooi(1) // cast rank '0' + + just use the SWIG_AddCast()/SWIG_CheckState() +*/ + +#define SWIG_OK (0) +/* Runtime errors are < 0 */ +#define SWIG_ERROR (-1) +/* Errors in range -1 to -99 are in swigerrors.swg (errors for all languages including those not using the runtime) */ +/* Errors in range -100 to -199 are language specific errors defined in *errors.swg */ +/* Errors < -200 are generic runtime specific errors */ +#define SWIG_ERROR_RELEASE_NOT_OWNED (-200) + +#define SWIG_IsOK(r) (r >= 0) +#define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) + +/* The CastRankLimit says how many bits are used for the cast rank */ +#define SWIG_CASTRANKLIMIT (1 << 8) +/* The NewMask denotes the object was created (using new/malloc) */ +#define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) +/* The TmpMask is for in/out typemaps that use temporary objects */ +#define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) +/* Simple returning values */ +#define SWIG_BADOBJ (SWIG_ERROR) +#define SWIG_OLDOBJ (SWIG_OK) +#define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) +#define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) +/* Check, add and del object mask methods */ +#define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) +#define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) +#define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) +#define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) +#define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) +#define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) + +/* Cast-Rank Mode */ +#if defined(SWIG_CASTRANK_MODE) +# ifndef SWIG_TypeRank +# define SWIG_TypeRank unsigned long +# endif +# ifndef SWIG_MAXCASTRANK /* Default cast allowed */ +# define SWIG_MAXCASTRANK (2) +# endif +# define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) +# define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) +SWIGINTERNINLINE int SWIG_AddCast(int r) { + return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; +} +SWIGINTERNINLINE int SWIG_CheckState(int r) { + return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; +} +#else /* no cast-rank mode */ +# define SWIG_AddCast(r) (r) +# define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) +#endif + + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void *(*swig_converter_func)(void *, int *); +typedef struct swig_type_info *(*swig_dycast_func)(void **); + +/* Structure to store information on one type */ +typedef struct swig_type_info { + const char *name; /* mangled name of this type */ + const char *str; /* human readable name of this type */ + swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ + struct swig_cast_info *cast; /* linked list of types that can cast into this type */ + void *clientdata; /* language specific type data */ + int owndata; /* flag if the structure owns the clientdata */ +} swig_type_info; + +/* Structure to store a type and conversion function used for casting */ +typedef struct swig_cast_info { + swig_type_info *type; /* pointer to type that is equivalent to this type */ + swig_converter_func converter; /* function to cast the void pointers */ + struct swig_cast_info *next; /* pointer to next cast in linked list */ + struct swig_cast_info *prev; /* pointer to the previous cast */ +} swig_cast_info; + +/* Structure used to store module information + * Each module generates one structure like this, and the runtime collects + * all of these structures and stores them in a circularly linked list.*/ +typedef struct swig_module_info { + swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ + size_t size; /* Number of types in this module */ + struct swig_module_info *next; /* Pointer to next element in circularly linked list */ + swig_type_info **type_initial; /* Array of initially generated type structures */ + swig_cast_info **cast_initial; /* Array of initially generated casting structures */ + void *clientdata; /* Language specific module data */ +} swig_module_info; + +/* + Compare two type names skipping the space characters, therefore + "char*" == "char *" and "Class" == "Class", etc. + + Return 0 when the two name types are equivalent, as in + strncmp, but skipping ' '. +*/ +SWIGRUNTIME int +SWIG_TypeNameComp(const char *f1, const char *l1, + const char *f2, const char *l2) { + for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { + while ((*f1 == ' ') && (f1 != l1)) ++f1; + while ((*f2 == ' ') && (f2 != l2)) ++f2; + if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; + } + return (int)((l1 - f1) - (l2 - f2)); +} + +/* + Check type equivalence in a name list like ||... + Return 0 if equal, -1 if nb < tb, 1 if nb > tb +*/ +SWIGRUNTIME int +SWIG_TypeCmp(const char *nb, const char *tb) { + int equiv = 1; + const char* te = tb + strlen(tb); + const char* ne = nb; + while (equiv != 0 && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') break; + } + equiv = SWIG_TypeNameComp(nb, ne, tb, te); + if (*ne) ++ne; + } + return equiv; +} + +/* + Check type equivalence in a name list like ||... + Return 0 if not equal, 1 if equal +*/ +SWIGRUNTIME int +SWIG_TypeEquiv(const char *nb, const char *tb) { + return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; +} + +/* + Check the typename +*/ +SWIGRUNTIME swig_cast_info * +SWIG_TypeCheck(const char *c, swig_type_info *ty) { + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (strcmp(iter->type->name, c) == 0) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; + } + } + return 0; +} + +/* + Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison +*/ +SWIGRUNTIME swig_cast_info * +SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) { + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (iter->type == from) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; + } + } + return 0; +} + +/* + Cast a pointer up an inheritance hierarchy +*/ +SWIGRUNTIMEINLINE void * +SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { + return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); +} + +/* + Dynamic pointer casting. Down an inheritance hierarchy +*/ +SWIGRUNTIME swig_type_info * +SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { + swig_type_info *lastty = ty; + if (!ty || !ty->dcast) return ty; + while (ty && (ty->dcast)) { + ty = (*ty->dcast)(ptr); + if (ty) lastty = ty; + } + return lastty; +} + +/* + Return the name associated with this type +*/ +SWIGRUNTIMEINLINE const char * +SWIG_TypeName(const swig_type_info *ty) { + return ty->name; +} + +/* + Return the pretty name associated with this type, + that is an unmangled type name in a form presentable to the user. +*/ +SWIGRUNTIME const char * +SWIG_TypePrettyName(const swig_type_info *type) { + /* The "str" field contains the equivalent pretty names of the + type, separated by vertical-bar characters. Choose the last + name. It should be the most specific; a fully resolved name + but not necessarily with default template parameters expanded. */ + if (!type) return NULL; + if (type->str != NULL) { + const char *last_name = type->str; + const char *s; + for (s = type->str; *s; s++) + if (*s == '|') last_name = s+1; + return last_name; + } + else + return type->name; +} + +/* + Set the clientdata field for a type +*/ +SWIGRUNTIME void +SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { + swig_cast_info *cast = ti->cast; + /* if (ti->clientdata == clientdata) return; */ + ti->clientdata = clientdata; + + while (cast) { + if (!cast->converter) { + swig_type_info *tc = cast->type; + if (!tc->clientdata) { + SWIG_TypeClientData(tc, clientdata); + } + } + cast = cast->next; + } +} +SWIGRUNTIME void +SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { + SWIG_TypeClientData(ti, clientdata); + ti->owndata = 1; +} + +/* + Search for a swig_type_info structure only by mangled name + Search is a O(log #types) + + We start searching at module start, and finish searching when start == end. + Note: if start == end at the beginning of the function, we go all the way around + the circular list. +*/ +SWIGRUNTIME swig_type_info * +SWIG_MangledTypeQueryModule(swig_module_info *start, + swig_module_info *end, + const char *name) { + swig_module_info *iter = start; + do { + if (iter->size) { + size_t l = 0; + size_t r = iter->size - 1; + do { + /* since l+r >= 0, we can (>> 1) instead (/ 2) */ + size_t i = (l + r) >> 1; + const char *iname = iter->types[i]->name; + if (iname) { + int compare = strcmp(name, iname); + if (compare == 0) { + return iter->types[i]; + } else if (compare < 0) { + if (i) { + r = i - 1; + } else { + break; + } + } else if (compare > 0) { + l = i + 1; + } + } else { + break; /* should never happen */ + } + } while (l <= r); + } + iter = iter->next; + } while (iter != end); + return 0; +} + +/* + Search for a swig_type_info structure for either a mangled name or a human readable name. + It first searches the mangled names of the types, which is a O(log #types) + If a type is not found it then searches the human readable names, which is O(#types). + + We start searching at module start, and finish searching when start == end. + Note: if start == end at the beginning of the function, we go all the way around + the circular list. +*/ +SWIGRUNTIME swig_type_info * +SWIG_TypeQueryModule(swig_module_info *start, + swig_module_info *end, + const char *name) { + /* STEP 1: Search the name field using binary search */ + swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); + if (ret) { + return ret; + } else { + /* STEP 2: If the type hasn't been found, do a complete search + of the str field (the human readable name) */ + swig_module_info *iter = start; + do { + size_t i = 0; + for (; i < iter->size; ++i) { + if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) + return iter->types[i]; + } + iter = iter->next; + } while (iter != end); + } + + /* neither found a match */ + return 0; +} + +/* + Pack binary data into a string +*/ +SWIGRUNTIME char * +SWIG_PackData(char *c, void *ptr, size_t sz) { + static const char hex[17] = "0123456789abcdef"; + const unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + unsigned char uu = *u; + *(c++) = hex[(uu & 0xf0) >> 4]; + *(c++) = hex[uu & 0xf]; + } + return c; +} + +/* + Unpack binary data from a string +*/ +SWIGRUNTIME const char * +SWIG_UnpackData(const char *c, void *ptr, size_t sz) { + unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + char d = *(c++); + unsigned char uu; + if ((d >= '0') && (d <= '9')) + uu = (unsigned char)((d - '0') << 4); + else if ((d >= 'a') && (d <= 'f')) + uu = (unsigned char)((d - ('a'-10)) << 4); + else + return (char *) 0; + d = *(c++); + if ((d >= '0') && (d <= '9')) + uu |= (unsigned char)(d - '0'); + else if ((d >= 'a') && (d <= 'f')) + uu |= (unsigned char)(d - ('a'-10)); + else + return (char *) 0; + *u = uu; + } + return c; +} + +/* + Pack 'void *' into a string buffer. +*/ +SWIGRUNTIME char * +SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { + char *r = buff; + if ((2*sizeof(void *) + 2) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r,&ptr,sizeof(void *)); + if (strlen(name) + 1 > (bsz - (r - buff))) return 0; + strcpy(r,name); + return buff; +} + +SWIGRUNTIME const char * +SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { + if (*c != '_') { + if (strcmp(c,"NULL") == 0) { + *ptr = (void *) 0; + return name; + } else { + return 0; + } + } + return SWIG_UnpackData(++c,ptr,sizeof(void *)); +} + +SWIGRUNTIME char * +SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { + char *r = buff; + size_t lname = (name ? strlen(name) : 0); + if ((2*sz + 2 + lname) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r,ptr,sz); + if (lname) { + strncpy(r,name,lname+1); + } else { + *r = 0; + } + return buff; +} + +SWIGRUNTIME const char * +SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { + if (*c != '_') { + if (strcmp(c,"NULL") == 0) { + memset(ptr,0,sz); + return name; + } else { + return 0; + } + } + return SWIG_UnpackData(++c,ptr,sz); +} + +#ifdef __cplusplus +} +#endif + +/* SWIG Errors applicable to all language modules, values are reserved from -1 to -99 */ +#define SWIG_UnknownError -1 +#define SWIG_IOError -2 +#define SWIG_RuntimeError -3 +#define SWIG_IndexError -4 +#define SWIG_TypeError -5 +#define SWIG_DivisionByZero -6 +#define SWIG_OverflowError -7 +#define SWIG_SyntaxError -8 +#define SWIG_ValueError -9 +#define SWIG_SystemError -10 +#define SWIG_AttributeError -11 +#define SWIG_MemoryError -12 +#define SWIG_NullReferenceError -13 + + +/* Compatibility macros for Python 3 */ +#if PY_VERSION_HEX >= 0x03000000 + +#define PyClass_Check(obj) PyObject_IsInstance(obj, (PyObject *)&PyType_Type) +#define PyInt_Check(x) PyLong_Check(x) +#define PyInt_AsLong(x) PyLong_AsLong(x) +#define PyInt_FromLong(x) PyLong_FromLong(x) +#define PyInt_FromSize_t(x) PyLong_FromSize_t(x) +#define PyString_Check(name) PyBytes_Check(name) +#define PyString_FromString(x) PyUnicode_FromString(x) +#define PyString_Format(fmt, args) PyUnicode_Format(fmt, args) +#define PyString_AsString(str) PyBytes_AsString(str) +#define PyString_Size(str) PyBytes_Size(str) +#define PyString_InternFromString(key) PyUnicode_InternFromString(key) +#define Py_TPFLAGS_HAVE_CLASS Py_TPFLAGS_BASETYPE +#define _PyLong_FromSsize_t(x) PyLong_FromSsize_t(x) + +#endif + +/* SWIG APIs for compatibility of both Python 2 & 3 */ + +#if PY_VERSION_HEX >= 0x03000000 +# define SWIG_Python_str_FromFormat PyUnicode_FromFormat +#else +# define SWIG_Python_str_FromFormat PyString_FromFormat +#endif + + +/* Wrapper around PyUnicode_AsUTF8AndSize - call Py_XDECREF on the returned pbytes when finished with the returned string */ +SWIGINTERN const char * +SWIG_PyUnicode_AsUTF8AndSize(PyObject *str, Py_ssize_t *psize, PyObject **pbytes) +{ +#if PY_VERSION_HEX >= 0x03030000 +# if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000 + *pbytes = NULL; + return PyUnicode_AsUTF8AndSize(str, psize); +# else + const char *chars; + *pbytes = PyUnicode_AsUTF8String(str); + chars = *pbytes ? PyBytes_AsString(*pbytes) : NULL; + if (chars && psize) + *psize = PyBytes_Size(*pbytes); + return chars; +# endif +#else + char *chars = NULL; + *pbytes = NULL; + PyString_AsStringAndSize(str, &chars, psize); + return chars; +#endif +} + +SWIGINTERN PyObject* +SWIG_Python_str_FromChar(const char *c) +{ +#if PY_VERSION_HEX >= 0x03000000 + return PyUnicode_FromString(c); +#else + return PyString_FromString(c); +#endif +} + +/* SWIGPY_USE_CAPSULE is no longer used within SWIG itself, but some user interface files check for it. */ +# define SWIGPY_USE_CAPSULE +#ifdef SWIGPYTHON_BUILTIN +# define SWIGPY_CAPSULE_ATTR_NAME "type_pointer_capsule_builtin" SWIG_TYPE_TABLE_NAME +#else +# define SWIGPY_CAPSULE_ATTR_NAME "type_pointer_capsule" SWIG_TYPE_TABLE_NAME +#endif +# define SWIGPY_CAPSULE_NAME ("swig_runtime_data" SWIG_RUNTIME_VERSION "." SWIGPY_CAPSULE_ATTR_NAME) + +#if PY_VERSION_HEX < 0x03020000 +#define PyDescr_TYPE(x) (((PyDescrObject *)(x))->d_type) +#define PyDescr_NAME(x) (((PyDescrObject *)(x))->d_name) +#define Py_hash_t long +#endif + +#ifdef Py_LIMITED_API +# define PyTuple_GET_ITEM PyTuple_GetItem +/* Note that PyTuple_SetItem() has different semantics from PyTuple_SET_ITEM as it decref's the original tuple item, so in general they cannot be used + interchangeably. However in SWIG-generated code PyTuple_SET_ITEM is only used with newly initialized tuples without any items and for them this does work. */ +# define PyTuple_SET_ITEM PyTuple_SetItem +# define PyTuple_GET_SIZE PyTuple_Size +# define PyCFunction_GET_FLAGS PyCFunction_GetFlags +# define PyCFunction_GET_FUNCTION PyCFunction_GetFunction +# define PyCFunction_GET_SELF PyCFunction_GetSelf +# define PyList_GET_ITEM PyList_GetItem +# define PyList_SET_ITEM PyList_SetItem +# define PySliceObject PyObject +#endif + +/* Increment and Decrement wrappers - for portability when using the stable abi and for performance otherwise */ +#ifdef Py_LIMITED_API +# define SWIG_Py_INCREF Py_IncRef +# define SWIG_Py_XINCREF Py_IncRef +# define SWIG_Py_DECREF Py_DecRef +# define SWIG_Py_XDECREF Py_DecRef +#else +# define SWIG_Py_INCREF Py_INCREF +# define SWIG_Py_XINCREF Py_XINCREF +# define SWIG_Py_DECREF Py_DECREF +# define SWIG_Py_XDECREF Py_XDECREF +#endif + +/* ----------------------------------------------------------------------------- + * error manipulation + * ----------------------------------------------------------------------------- */ + +SWIGRUNTIME PyObject* +SWIG_Python_ErrorType(int code) { + PyObject* type = 0; + switch(code) { + case SWIG_MemoryError: + type = PyExc_MemoryError; + break; + case SWIG_IOError: + type = PyExc_IOError; + break; + case SWIG_RuntimeError: + type = PyExc_RuntimeError; + break; + case SWIG_IndexError: + type = PyExc_IndexError; + break; + case SWIG_TypeError: + type = PyExc_TypeError; + break; + case SWIG_DivisionByZero: + type = PyExc_ZeroDivisionError; + break; + case SWIG_OverflowError: + type = PyExc_OverflowError; + break; + case SWIG_SyntaxError: + type = PyExc_SyntaxError; + break; + case SWIG_ValueError: + type = PyExc_ValueError; + break; + case SWIG_SystemError: + type = PyExc_SystemError; + break; + case SWIG_AttributeError: + type = PyExc_AttributeError; + break; + case SWIG_NullReferenceError: + type = PyExc_TypeError; + break; + default: + type = PyExc_RuntimeError; + } + return type; +} + + +SWIGRUNTIME void +SWIG_Python_AddErrorMsg(const char* mesg) +{ + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; + + if (PyErr_Occurred()) + PyErr_Fetch(&type, &value, &traceback); + if (value) { + PyObject *old_str = PyObject_Str(value); + PyObject *bytes = NULL; + const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes); + PyErr_Clear(); + SWIG_Py_XINCREF(type); + if (tmp) + PyErr_Format(type, "%s %s", tmp, mesg); + else + PyErr_Format(type, "%s", mesg); + SWIG_Py_XDECREF(bytes); + SWIG_Py_DECREF(old_str); + SWIG_Py_DECREF(value); + } else { + PyErr_SetString(PyExc_RuntimeError, mesg); + } +} + +SWIGRUNTIME int +SWIG_Python_TypeErrorOccurred(PyObject *obj) +{ + PyObject *error; + if (obj) + return 0; + error = PyErr_Occurred(); + return error && PyErr_GivenExceptionMatches(error, PyExc_TypeError); +} + +SWIGRUNTIME void +SWIG_Python_RaiseOrModifyTypeError(const char *message) +{ + if (SWIG_Python_TypeErrorOccurred(NULL)) { + /* Use existing TypeError to preserve stacktrace and enhance with given message */ + PyObject *newvalue; + PyObject *type = NULL, *value = NULL, *traceback = NULL; + PyErr_Fetch(&type, &value, &traceback); +#if PY_VERSION_HEX >= 0x03000000 + newvalue = PyUnicode_FromFormat("%S\nAdditional information:\n%s", value, message); +#else + newvalue = PyString_FromFormat("%s\nAdditional information:\n%s", PyString_AsString(value), message); +#endif + if (newvalue) { + SWIG_Py_XDECREF(value); + PyErr_Restore(type, newvalue, traceback); + } else { + PyErr_Restore(type, value, traceback); + } + } else { + /* Raise TypeError using given message */ + PyErr_SetString(PyExc_TypeError, message); + } +} + +#if defined(SWIG_PYTHON_NO_THREADS) +# if defined(SWIG_PYTHON_THREADS) +# undef SWIG_PYTHON_THREADS +# endif +#endif +#if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */ +# if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL) +# define SWIG_PYTHON_USE_GIL +# endif +# if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */ +# if !defined(SWIG_PYTHON_INITIALIZE_THREADS) +# if PY_VERSION_HEX < 0x03070000 +# define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() +# else +# define SWIG_PYTHON_INITIALIZE_THREADS +# endif +# endif +# ifdef __cplusplus /* C++ code */ + class SWIG_Python_Thread_Block { + bool status; + PyGILState_STATE state; + public: + void end() { if (status) { PyGILState_Release(state); status = false;} } + SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} + ~SWIG_Python_Thread_Block() { end(); } + }; + class SWIG_Python_Thread_Allow { + bool status; + PyThreadState *save; + public: + void end() { if (status) { status = false; PyEval_RestoreThread(save); }} + SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} + ~SWIG_Python_Thread_Allow() { end(); } + }; +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block +# define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow +# define SWIG_PYTHON_THREAD_END_ALLOW _swig_thread_allow.end() +# else /* C code */ +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK PyGILState_STATE _swig_thread_block = PyGILState_Ensure() +# define SWIG_PYTHON_THREAD_END_BLOCK PyGILState_Release(_swig_thread_block) +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW PyThreadState *_swig_thread_allow = PyEval_SaveThread() +# define SWIG_PYTHON_THREAD_END_ALLOW PyEval_RestoreThread(_swig_thread_allow) +# endif +# else /* Old thread way, not implemented, user must provide it */ +# if !defined(SWIG_PYTHON_INITIALIZE_THREADS) +# define SWIG_PYTHON_INITIALIZE_THREADS +# endif +# if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK) +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK +# endif +# if !defined(SWIG_PYTHON_THREAD_END_BLOCK) +# define SWIG_PYTHON_THREAD_END_BLOCK +# endif +# if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW) +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW +# endif +# if !defined(SWIG_PYTHON_THREAD_END_ALLOW) +# define SWIG_PYTHON_THREAD_END_ALLOW +# endif +# endif +#else /* No thread support */ +# define SWIG_PYTHON_INITIALIZE_THREADS +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK +# define SWIG_PYTHON_THREAD_END_BLOCK +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW +# define SWIG_PYTHON_THREAD_END_ALLOW +#endif + +/* ----------------------------------------------------------------------------- + * Python API portion that goes into the runtime + * ----------------------------------------------------------------------------- */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* ----------------------------------------------------------------------------- + * Constant declarations + * ----------------------------------------------------------------------------- */ + +/* Constant Types */ +#define SWIG_PY_POINTER 4 +#define SWIG_PY_BINARY 5 + +/* Constant information structure */ +typedef struct swig_const_info { + int type; + const char *name; + long lvalue; + double dvalue; + void *pvalue; + swig_type_info **ptype; +} swig_const_info; + +#ifdef __cplusplus +} +#endif + + +/* ----------------------------------------------------------------------------- + * pyrun.swg + * + * This file contains the runtime support for Python modules + * and includes code for managing global variables and pointer + * type checking. + * + * ----------------------------------------------------------------------------- */ + +#if PY_VERSION_HEX < 0x02070000 /* 2.7.0 */ +# error "This version of SWIG only supports Python >= 2.7" +#endif + +#if PY_VERSION_HEX >= 0x03000000 && PY_VERSION_HEX < 0x03030000 +# error "This version of SWIG only supports Python 3 >= 3.3" +#endif + +/* Common SWIG API */ + +/* for raw pointers */ +#define SWIG_Python_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0) +#define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtr(obj, pptr, type, flags) +#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own) + +#ifdef SWIGPYTHON_BUILTIN +#define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(self, ptr, type, flags) +#else +#define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(NULL, ptr, type, flags) +#endif + +#define SWIG_InternalNewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(NULL, ptr, type, flags) + +#define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) +#define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) +#define swig_owntype int + +/* for raw packed data */ +#define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) +#define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) + +/* for class or struct pointers */ +#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) +#define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) + +/* for C or C++ function pointers */ +#define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_Python_ConvertFunctionPtr(obj, pptr, type) +#define SWIG_NewFunctionPtrObj(ptr, type) SWIG_Python_NewPointerObj(NULL, ptr, type, 0) + +/* for C++ member pointers, ie, member methods */ +#define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) +#define SWIG_NewMemberObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) + + +/* Runtime API */ + +#define SWIG_GetModule(clientdata) SWIG_Python_GetModule(clientdata) +#define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) +#define SWIG_NewClientData(obj) SwigPyClientData_New(obj) + +#define SWIG_SetErrorObj SWIG_Python_SetErrorObj +#define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg +#define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) +#define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) +#define SWIG_fail goto fail + + +/* Runtime API implementation */ + +/* Error manipulation */ + +SWIGINTERN void +SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetObject(errtype, obj); + SWIG_Py_DECREF(obj); + SWIG_PYTHON_THREAD_END_BLOCK; +} + +SWIGINTERN void +SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetString(errtype, msg); + SWIG_PYTHON_THREAD_END_BLOCK; +} + +#define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) + +/* Set a constant value */ + +#if defined(SWIGPYTHON_BUILTIN) + +SWIGINTERN void +SwigPyBuiltin_AddPublicSymbol(PyObject *seq, const char *key) { + PyObject *s = PyString_InternFromString(key); + PyList_Append(seq, s); + SWIG_Py_DECREF(s); +} + +SWIGINTERN void +SWIG_Python_SetConstant(PyObject *d, PyObject *public_interface, const char *name, PyObject *obj) { + PyDict_SetItemString(d, name, obj); + SWIG_Py_DECREF(obj); + if (public_interface) + SwigPyBuiltin_AddPublicSymbol(public_interface, name); +} + +#else + +SWIGINTERN void +SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { + PyDict_SetItemString(d, name, obj); + SWIG_Py_DECREF(obj); +} + +#endif + +/* Append a value to the result obj */ + +SWIGINTERN PyObject* +SWIG_Python_AppendOutput(PyObject* result, PyObject* obj, int is_void) { + if (!result) { + result = obj; + } else if (result == Py_None && is_void) { + SWIG_Py_DECREF(result); + result = obj; + } else { + if (!PyList_Check(result)) { + PyObject *o2 = result; + result = PyList_New(1); + if (result) { + PyList_SET_ITEM(result, 0, o2); + } else { + SWIG_Py_DECREF(obj); + return o2; + } + } + PyList_Append(result,obj); + SWIG_Py_DECREF(obj); + } + return result; +} + +/* Unpack the argument tuple */ + +SWIGINTERN Py_ssize_t +SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) +{ + if (!args) { + if (!min && !max) { + return 1; + } else { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", + name, (min == max ? "" : "at least "), (int)min); + return 0; + } + } + if (!PyTuple_Check(args)) { + if (min <= 1 && max >= 1) { + Py_ssize_t i; + objs[0] = args; + for (i = 1; i < max; ++i) { + objs[i] = 0; + } + return 2; + } + PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); + return 0; + } else { + Py_ssize_t l = PyTuple_GET_SIZE(args); + if (l < min) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at least "), (int)min, (int)l); + return 0; + } else if (l > max) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at most "), (int)max, (int)l); + return 0; + } else { + Py_ssize_t i; + for (i = 0; i < l; ++i) { + objs[i] = PyTuple_GET_ITEM(args, i); + } + for (; l < max; ++l) { + objs[l] = 0; + } + return i + 1; + } + } +} + +SWIGINTERN int +SWIG_Python_CheckNoKeywords(PyObject *kwargs, const char *name) { + int no_kwargs = 1; + if (kwargs) { + assert(PyDict_Check(kwargs)); + if (PyDict_Size(kwargs) > 0) { + PyErr_Format(PyExc_TypeError, "%s() does not take keyword arguments", name); + no_kwargs = 0; + } + } + return no_kwargs; +} + +/* A functor is a function object with one single object argument */ +#define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunctionObjArgs(functor, obj, NULL); + +/* + Helper for static pointer initialization for both C and C++ code, for example + static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...); +*/ +#ifdef __cplusplus +#define SWIG_STATIC_POINTER(var) var +#else +#define SWIG_STATIC_POINTER(var) var = 0; if (!var) var +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* Python-specific SWIG API */ +#define SWIG_newvarlink() SWIG_Python_newvarlink() +#define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) +#define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) + +/* ----------------------------------------------------------------------------- + * global variable support code. + * ----------------------------------------------------------------------------- */ + +typedef struct swig_globalvar { + char *name; /* Name of global variable */ + PyObject *(*get_attr)(void); /* Return the current value */ + int (*set_attr)(PyObject *); /* Set the value */ + struct swig_globalvar *next; +} swig_globalvar; + +typedef struct swig_varlinkobject { + PyObject_HEAD + swig_globalvar *vars; +} swig_varlinkobject; + +SWIGINTERN PyObject * +swig_varlink_repr(PyObject *SWIGUNUSEDPARM(v)) { +#if PY_VERSION_HEX >= 0x03000000 + return PyUnicode_InternFromString(""); +#else + return PyString_FromString(""); +#endif +} + +SWIGINTERN PyObject * +swig_varlink_str(PyObject *o) { + swig_varlinkobject *v = (swig_varlinkobject *) o; +#if PY_VERSION_HEX >= 0x03000000 + PyObject *str = PyUnicode_InternFromString("("); + PyObject *tail; + PyObject *joined; + swig_globalvar *var; + for (var = v->vars; var; var=var->next) { + tail = PyUnicode_FromString(var->name); + joined = PyUnicode_Concat(str, tail); + SWIG_Py_DECREF(str); + SWIG_Py_DECREF(tail); + str = joined; + if (var->next) { + tail = PyUnicode_InternFromString(", "); + joined = PyUnicode_Concat(str, tail); + SWIG_Py_DECREF(str); + SWIG_Py_DECREF(tail); + str = joined; + } + } + tail = PyUnicode_InternFromString(")"); + joined = PyUnicode_Concat(str, tail); + SWIG_Py_DECREF(str); + SWIG_Py_DECREF(tail); + str = joined; +#else + PyObject *str = PyString_FromString("("); + swig_globalvar *var; + for (var = v->vars; var; var=var->next) { + PyString_ConcatAndDel(&str,PyString_FromString(var->name)); + if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); + } + PyString_ConcatAndDel(&str,PyString_FromString(")")); +#endif + return str; +} + +SWIGINTERN void +swig_varlink_dealloc(PyObject *o) { + swig_varlinkobject *v = (swig_varlinkobject *) o; + swig_globalvar *var = v->vars; + while (var) { + swig_globalvar *n = var->next; + free(var->name); + free(var); + var = n; + } +} + +SWIGINTERN PyObject * +swig_varlink_getattr(PyObject *o, char *n) { + swig_varlinkobject *v = (swig_varlinkobject *) o; + PyObject *res = NULL; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name,n) == 0) { + res = (*var->get_attr)(); + break; + } + var = var->next; + } + if (res == NULL && !PyErr_Occurred()) { + PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); + } + return res; +} + +SWIGINTERN int +swig_varlink_setattr(PyObject *o, char *n, PyObject *p) { + swig_varlinkobject *v = (swig_varlinkobject *) o; + int res = 1; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name,n) == 0) { + res = (*var->set_attr)(p); + break; + } + var = var->next; + } + if (res == 1 && !PyErr_Occurred()) { + PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); + } + return res; +} + +SWIGINTERN PyTypeObject* +swig_varlink_type(void) { + static char varlink__doc__[] = "Swig var link object"; +#ifndef SWIG_HEAPTYPES + static PyTypeObject varlink_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { +#if PY_VERSION_HEX >= 0x03000000 + PyVarObject_HEAD_INIT(NULL, 0) +#else + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ +#endif + "swigvarlink", /* tp_name */ + sizeof(swig_varlinkobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor) swig_varlink_dealloc, /* tp_dealloc */ +#if PY_VERSION_HEX < 0x030800b4 + (printfunc)0, /* tp_print */ +#else + (Py_ssize_t)0, /* tp_vectorcall_offset */ +#endif + (getattrfunc) swig_varlink_getattr, /* tp_getattr */ + (setattrfunc) swig_varlink_setattr, /* tp_setattr */ + 0, /* tp_compare */ + (reprfunc) swig_varlink_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + (reprfunc) swig_varlink_str, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + 0, /* tp_flags */ + varlink__doc__, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ + 0, /* tp_del */ + 0, /* tp_version_tag */ +#if PY_VERSION_HEX >= 0x03040000 + 0, /* tp_finalize */ +#endif +#if PY_VERSION_HEX >= 0x03080000 + 0, /* tp_vectorcall */ +#endif +#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) + 0, /* tp_print */ +#endif +#if PY_VERSION_HEX >= 0x030c0000 + 0, /* tp_watched */ +#endif +#if PY_VERSION_HEX >= 0x030d00a4 + 0, /* tp_versions_used */ +#endif +#ifdef COUNT_ALLOCS + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ + 0, /* tp_prev */ + 0 /* tp_next */ +#endif + }; + varlink_type = tmp; + type_init = 1; + if (PyType_Ready(&varlink_type) < 0) + return NULL; + } + return &varlink_type; +#else + PyType_Slot slots[] = { + { Py_tp_dealloc, (void *)swig_varlink_dealloc }, + { Py_tp_repr, (void *)swig_varlink_repr }, + { Py_tp_getattr, (void *)swig_varlink_getattr }, + { Py_tp_setattr, (void *)swig_varlink_setattr }, + { Py_tp_str, (void *)swig_varlink_str }, + { Py_tp_doc, (void *)varlink__doc__ }, + { 0, NULL } + }; + PyType_Spec spec = { + "swigvarlink", + sizeof(swig_varlinkobject), + 0, + Py_TPFLAGS_DEFAULT, + slots + }; + return (PyTypeObject *)PyType_FromSpec(&spec); +#endif +} + +/* Create a variable linking object for use later */ +SWIGINTERN PyObject * +SWIG_Python_newvarlink(void) { + swig_varlinkobject *result = PyObject_New(swig_varlinkobject, swig_varlink_type()); + if (result) { + result->vars = 0; + } + return ((PyObject*) result); +} + +SWIGINTERN void +SWIG_Python_addvarlink(PyObject *p, const char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { + swig_varlinkobject *v = (swig_varlinkobject *) p; + swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); + if (gv) { + size_t size = strlen(name)+1; + gv->name = (char *)malloc(size); + if (gv->name) { + memcpy(gv->name, name, size); + gv->get_attr = get_attr; + gv->set_attr = set_attr; + gv->next = v->vars; + } + } + v->vars = gv; +} + + +static PyObject *Swig_Globals_global = NULL; + +SWIGINTERN PyObject * +SWIG_globals(void) { + if (Swig_Globals_global == NULL) { + Swig_Globals_global = SWIG_newvarlink(); + } + return Swig_Globals_global; +} + +#ifdef __cplusplus +} +#endif + +/* ----------------------------------------------------------------------------- + * Pointer declarations + * ----------------------------------------------------------------------------- */ + +/* Flags for new pointer objects */ +#define SWIG_POINTER_NOSHADOW (SWIG_POINTER_OWN << 1) +#define SWIG_POINTER_NEW (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN) + +#define SWIG_POINTER_IMPLICIT_CONV (SWIG_POINTER_DISOWN << 1) + +#define SWIG_BUILTIN_TP_INIT (SWIG_POINTER_OWN << 2) +#define SWIG_BUILTIN_INIT (SWIG_BUILTIN_TP_INIT | SWIG_POINTER_OWN) + +#ifdef __cplusplus +extern "C" { +#endif + +/* The python void return value */ + +SWIGRUNTIMEINLINE PyObject * +SWIG_Py_Void(void) +{ + PyObject *none = Py_None; + SWIG_Py_INCREF(none); + return none; +} + +/* SwigPyClientData */ + +typedef struct { + PyObject *klass; + PyObject *newraw; + PyObject *newargs; + PyObject *destroy; + int delargs; + int implicitconv; + PyTypeObject *pytype; +} SwigPyClientData; + +SWIGRUNTIMEINLINE int +SWIG_Python_CheckImplicit(swig_type_info *ty) +{ + SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; + int fail = data ? data->implicitconv : 0; + if (fail) + PyErr_SetString(PyExc_TypeError, "Implicit conversion is prohibited for explicit constructors."); + return fail; +} + +SWIGRUNTIMEINLINE PyObject * +SWIG_Python_ExceptionType(swig_type_info *desc) { + SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; + PyObject *klass = data ? data->klass : 0; + return (klass ? klass : PyExc_RuntimeError); +} + + +SWIGRUNTIME SwigPyClientData * +SwigPyClientData_New(PyObject* obj) +{ + if (!obj) { + return 0; + } else { + SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); + /* the klass element */ + data->klass = obj; + SWIG_Py_INCREF(data->klass); + /* the newraw method and newargs arguments used to create a new raw instance */ + if (PyClass_Check(obj)) { + data->newraw = 0; + SWIG_Py_INCREF(obj); + data->newargs = obj; + } else { + data->newraw = PyObject_GetAttrString(data->klass, "__new__"); + if (data->newraw) { + data->newargs = PyTuple_New(1); + if (data->newargs) { + SWIG_Py_INCREF(obj); + PyTuple_SET_ITEM(data->newargs, 0, obj); + } else { + SWIG_Py_DECREF(data->newraw); + SWIG_Py_DECREF(data->klass); + free(data); + return 0; + } + } else { + SWIG_Py_INCREF(obj); + data->newargs = obj; + } + } + /* the destroy method, aka as the C++ delete method */ + data->destroy = PyObject_GetAttrString(data->klass, "__swig_destroy__"); + if (PyErr_Occurred()) { + PyErr_Clear(); + data->destroy = 0; + } + if (data->destroy) { + data->delargs = !(PyCFunction_GET_FLAGS(data->destroy) & METH_O); + } else { + data->delargs = 0; + } + data->implicitconv = 0; + data->pytype = 0; + return data; + } +} + +SWIGRUNTIME void +SwigPyClientData_Del(SwigPyClientData *data) +{ + SWIG_Py_XDECREF(data->klass); + SWIG_Py_XDECREF(data->newraw); + SWIG_Py_XDECREF(data->newargs); + SWIG_Py_XDECREF(data->destroy); + free(data); +} + +/* =============== SwigPyObject =====================*/ + +typedef struct { + PyObject_HEAD + void *ptr; + swig_type_info *ty; + int own; + PyObject *next; +#ifdef SWIGPYTHON_BUILTIN + PyObject *dict; +#endif +} SwigPyObject; + + +#ifdef SWIGPYTHON_BUILTIN + +SWIGRUNTIME PyObject * +SwigPyObject_get___dict__(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) +{ + SwigPyObject *sobj = (SwigPyObject *)v; + + if (!sobj->dict) + sobj->dict = PyDict_New(); + + SWIG_Py_XINCREF(sobj->dict); + return sobj->dict; +} + +#endif + +SWIGRUNTIME PyObject * +SwigPyObject_long(SwigPyObject *v) +{ + return PyLong_FromVoidPtr(v->ptr); +} + +SWIGRUNTIME PyObject * +SwigPyObject_format(const char* fmt, SwigPyObject *v) +{ + PyObject *res = NULL; + PyObject *args = PyTuple_New(1); + if (args) { + PyObject *val = SwigPyObject_long(v); + if (val) { + PyObject *ofmt; + PyTuple_SET_ITEM(args, 0, val); + ofmt = SWIG_Python_str_FromChar(fmt); + if (ofmt) { +#if PY_VERSION_HEX >= 0x03000000 + res = PyUnicode_Format(ofmt,args); +#else + res = PyString_Format(ofmt,args); +#endif + SWIG_Py_DECREF(ofmt); + } + } + SWIG_Py_DECREF(args); + } + return res; +} + +SWIGRUNTIME PyObject * +SwigPyObject_oct(SwigPyObject *v) +{ + return SwigPyObject_format("%o",v); +} + +SWIGRUNTIME PyObject * +SwigPyObject_hex(SwigPyObject *v) +{ + return SwigPyObject_format("%x",v); +} + +SWIGRUNTIME PyObject * +SwigPyObject_repr(SwigPyObject *v) +{ + const char *name = SWIG_TypePrettyName(v->ty); + PyObject *repr = SWIG_Python_str_FromFormat("", (name ? name : "unknown"), (void *)v); + if (repr && v->next) { + PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); + if (nrep) { +# if PY_VERSION_HEX >= 0x03000000 + PyObject *joined = PyUnicode_Concat(repr, nrep); + SWIG_Py_DECREF(repr); + SWIG_Py_DECREF(nrep); + repr = joined; +# else + PyString_ConcatAndDel(&repr,nrep); +# endif + } else { + SWIG_Py_DECREF(repr); + repr = NULL; + } + } + return repr; +} + +/* We need a version taking two PyObject* parameters so it's a valid + * PyCFunction to use in swigobject_methods[]. */ +SWIGRUNTIME PyObject * +SwigPyObject_repr2(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) +{ + return SwigPyObject_repr((SwigPyObject*)v); +} + +SWIGRUNTIME int +SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) +{ + void *i = v->ptr; + void *j = w->ptr; + return (i < j) ? -1 : ((i > j) ? 1 : 0); +} + +/* Added for Python 3.x, would it also be useful for Python 2.x? */ +SWIGRUNTIME PyObject* +SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) +{ + PyObject* res = NULL; + if (!PyErr_Occurred()) { + if (op != Py_EQ && op != Py_NE) { + SWIG_Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + res = PyBool_FromLong( (SwigPyObject_compare(v, w)==0) == (op == Py_EQ) ? 1 : 0); + } + return res; +} + + +SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void); + +#ifdef SWIGPYTHON_BUILTIN +static swig_type_info *SwigPyObject_stype = 0; +SWIGRUNTIME PyTypeObject* +SwigPyObject_type(void) { + SwigPyClientData *cd; + assert(SwigPyObject_stype); + cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; + assert(cd); + assert(cd->pytype); + return cd->pytype; +} +#else +SWIGRUNTIME PyTypeObject* +SwigPyObject_type(void) { + static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyObject_TypeOnce(); + return type; +} +#endif + +SWIGRUNTIMEINLINE int +SwigPyObject_Check(PyObject *op) { + PyTypeObject *target_tp = SwigPyObject_type(); + PyTypeObject *op_type = Py_TYPE(op); +#ifdef SWIGPYTHON_BUILTIN + if (PyType_IsSubtype(op_type, target_tp)) + return 1; + return (strcmp(op_type->tp_name, "SwigPyObject") == 0); +#else +# ifdef Py_LIMITED_API + int cmp; + PyObject *tp_name; +#endif + if (op_type == target_tp) + return 1; +# ifdef Py_LIMITED_API + tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__"); + if (!tp_name) + return 0; + cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyObject"); + SWIG_Py_DECREF(tp_name); + return cmp == 0; +# else + return (strcmp(op_type->tp_name, "SwigPyObject") == 0); +# endif +#endif +} + +SWIGRUNTIME PyObject * +SwigPyObject_New(void *ptr, swig_type_info *ty, int own); + +static PyObject* Swig_Capsule_global = NULL; + +SWIGRUNTIME void +SwigPyObject_dealloc(PyObject *v) +{ + SwigPyObject *sobj = (SwigPyObject *) v; + PyObject *next = sobj->next; + if (sobj->own == SWIG_POINTER_OWN) { + swig_type_info *ty = sobj->ty; + SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; + PyObject *destroy = data ? data->destroy : 0; + if (destroy) { + /* destroy is always a VARARGS method */ + PyObject *res; + + /* PyObject_CallFunction() has the potential to silently drop + the active exception. In cases of unnamed temporary + variable or where we just finished iterating over a generator + StopIteration will be active right now, and this needs to + remain true upon return from SwigPyObject_dealloc. So save + and restore. */ + + PyObject *type = NULL, *value = NULL, *traceback = NULL; + PyErr_Fetch(&type, &value, &traceback); + + if (data->delargs) { + /* we need to create a temporary object to carry the destroy operation */ + PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); + if (tmp) { + res = SWIG_Python_CallFunctor(destroy, tmp); + } else { + res = 0; + } + SWIG_Py_XDECREF(tmp); + } else { + PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); + PyObject *mself = PyCFunction_GET_SELF(destroy); + res = ((*meth)(mself, v)); + } + if (!res) + PyErr_WriteUnraisable(destroy); + + PyErr_Restore(type, value, traceback); + + SWIG_Py_XDECREF(res); + } +#if !defined(SWIG_PYTHON_SILENT_MEMLEAK) + else { + const char *name = SWIG_TypePrettyName(ty); + printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); + } +#endif + SWIG_Py_XDECREF(Swig_Capsule_global); + } + SWIG_Py_XDECREF(next); +#ifdef SWIGPYTHON_BUILTIN + SWIG_Py_XDECREF(sobj->dict); +#endif + PyObject_Free(v); +} + +SWIGRUNTIME PyObject* +SwigPyObject_append(PyObject* v, PyObject* next) +{ + SwigPyObject *sobj = (SwigPyObject *) v; + if (!SwigPyObject_Check(next)) { + PyErr_SetString(PyExc_TypeError, "Attempt to append a non SwigPyObject"); + return NULL; + } + ((SwigPyObject *)next)->next = sobj->next; + sobj->next = next; + SWIG_Py_INCREF(next); + return SWIG_Py_Void(); +} + +SWIGRUNTIME PyObject* +SwigPyObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +{ + SwigPyObject *sobj = (SwigPyObject *) v; + if (sobj->next) { + SWIG_Py_INCREF(sobj->next); + return sobj->next; + } else { + return SWIG_Py_Void(); + } +} + +SWIGINTERN PyObject* +SwigPyObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +{ + SwigPyObject *sobj = (SwigPyObject *)v; + sobj->own = 0; + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject* +SwigPyObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +{ + SwigPyObject *sobj = (SwigPyObject *)v; + sobj->own = SWIG_POINTER_OWN; + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject* +SwigPyObject_own(PyObject *v, PyObject *args) +{ + PyObject *val = 0; + if (!PyArg_UnpackTuple(args, "own", 0, 1, &val)) { + return NULL; + } else { + SwigPyObject *sobj = (SwigPyObject *)v; + PyObject *obj = PyBool_FromLong(sobj->own); + if (val) { + if (PyObject_IsTrue(val)) { + SWIG_Py_DECREF(SwigPyObject_acquire(v,args)); + } else { + SWIG_Py_DECREF(SwigPyObject_disown(v,args)); + } + } + return obj; + } +} + +static PyMethodDef +swigobject_methods[] = { + {"disown", SwigPyObject_disown, METH_NOARGS, "releases ownership of the pointer"}, + {"acquire", SwigPyObject_acquire, METH_NOARGS, "acquires ownership of the pointer"}, + {"own", SwigPyObject_own, METH_VARARGS, "returns/sets ownership of the pointer"}, + {"append", SwigPyObject_append, METH_O, "appends another 'this' object"}, + {"next", SwigPyObject_next, METH_NOARGS, "returns the next 'this' object"}, + {"__repr__",SwigPyObject_repr2, METH_NOARGS, "returns object representation"}, + {0, 0, 0, 0} +}; + +SWIGRUNTIME PyTypeObject* +SwigPyObject_TypeOnce(void) { + static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; +#ifndef SWIG_HEAPTYPES + static PyNumberMethods SwigPyObject_as_number = { + (binaryfunc)0, /*nb_add*/ + (binaryfunc)0, /*nb_subtract*/ + (binaryfunc)0, /*nb_multiply*/ + /* nb_divide removed in Python 3 */ +#if PY_VERSION_HEX < 0x03000000 + (binaryfunc)0, /*nb_divide*/ +#endif + (binaryfunc)0, /*nb_remainder*/ + (binaryfunc)0, /*nb_divmod*/ + (ternaryfunc)0,/*nb_power*/ + (unaryfunc)0, /*nb_negative*/ + (unaryfunc)0, /*nb_positive*/ + (unaryfunc)0, /*nb_absolute*/ + (inquiry)0, /*nb_nonzero*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + 0, /*nb_and*/ + 0, /*nb_xor*/ + 0, /*nb_or*/ +#if PY_VERSION_HEX < 0x03000000 + 0, /*nb_coerce*/ +#endif + (unaryfunc)SwigPyObject_long, /*nb_int*/ +#if PY_VERSION_HEX < 0x03000000 + (unaryfunc)SwigPyObject_long, /*nb_long*/ +#else + 0, /*nb_reserved*/ +#endif + (unaryfunc)0, /*nb_float*/ +#if PY_VERSION_HEX < 0x03000000 + (unaryfunc)SwigPyObject_oct, /*nb_oct*/ + (unaryfunc)SwigPyObject_hex, /*nb_hex*/ +#endif +#if PY_VERSION_HEX >= 0x03050000 /* 3.5 */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_matrix_multiply */ +#elif PY_VERSION_HEX >= 0x03000000 /* 3.0 */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ +#else + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ +#endif + }; + + static PyTypeObject swigpyobject_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { +#if PY_VERSION_HEX >= 0x03000000 + PyVarObject_HEAD_INIT(NULL, 0) +#else + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ +#endif + "SwigPyObject", /* tp_name */ + sizeof(SwigPyObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)SwigPyObject_dealloc, /* tp_dealloc */ +#if PY_VERSION_HEX < 0x030800b4 + (printfunc)0, /* tp_print */ +#else + (Py_ssize_t)0, /* tp_vectorcall_offset */ +#endif + (getattrfunc)0, /* tp_getattr */ + (setattrfunc)0, /* tp_setattr */ +#if PY_VERSION_HEX >= 0x03000000 + 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ +#else + (cmpfunc)SwigPyObject_compare, /* tp_compare */ +#endif + (reprfunc)SwigPyObject_repr, /* tp_repr */ + &SwigPyObject_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigobject_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)SwigPyObject_richcompare,/* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + swigobject_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ + 0, /* tp_del */ + 0, /* tp_version_tag */ +#if PY_VERSION_HEX >= 0x03040000 + 0, /* tp_finalize */ +#endif +#if PY_VERSION_HEX >= 0x03080000 + 0, /* tp_vectorcall */ +#endif +#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) + 0, /* tp_print */ +#endif +#if PY_VERSION_HEX >= 0x030c0000 + 0, /* tp_watched */ +#endif +#if PY_VERSION_HEX >= 0x030d00a4 + 0, /* tp_versions_used */ +#endif +#ifdef COUNT_ALLOCS + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ + 0, /* tp_prev */ + 0 /* tp_next */ +#endif + }; + swigpyobject_type = tmp; + type_init = 1; + if (PyType_Ready(&swigpyobject_type) != 0) + return NULL; + } + return &swigpyobject_type; +#else + PyType_Slot slots[] = { + { Py_tp_dealloc, (void *)SwigPyObject_dealloc }, + { Py_tp_repr, (void *)SwigPyObject_repr }, + { Py_tp_getattro, (void *)PyObject_GenericGetAttr }, + { Py_tp_doc, (void *)swigobject_doc }, + { Py_tp_richcompare, (void *)SwigPyObject_richcompare }, + { Py_tp_methods, (void *)swigobject_methods }, + { Py_nb_int, (void *)SwigPyObject_long }, + { 0, NULL } + }; + PyType_Spec spec = { + "SwigPyObject", + sizeof(SwigPyObject), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, + slots + }; + return (PyTypeObject *)PyType_FromSpec(&spec); +#endif +} + +SWIGRUNTIME PyObject * +SwigPyObject_New(void *ptr, swig_type_info *ty, int own) +{ + SwigPyObject *sobj = PyObject_New(SwigPyObject, SwigPyObject_type()); + if (sobj) { + sobj->ptr = ptr; + sobj->ty = ty; + sobj->own = own; + sobj->next = 0; +#ifdef SWIGPYTHON_BUILTIN + sobj->dict = 0; +#endif + if (own == SWIG_POINTER_OWN) { + /* Obtain a reference to the Python capsule wrapping the module information, so that the + * module information is correctly destroyed after all SWIG python objects have been freed + * by the GC (and corresponding destructors invoked) */ + SWIG_Py_XINCREF(Swig_Capsule_global); + } + } + return (PyObject *)sobj; +} + +/* ----------------------------------------------------------------------------- + * Implements a simple Swig Packed type, and use it instead of string + * ----------------------------------------------------------------------------- */ + +typedef struct { + PyObject_HEAD + void *pack; + swig_type_info *ty; + size_t size; +} SwigPyPacked; + +SWIGRUNTIME PyObject * +SwigPyPacked_repr(SwigPyPacked *v) +{ + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { + return SWIG_Python_str_FromFormat("", result, v->ty->name); + } else { + return SWIG_Python_str_FromFormat("", v->ty->name); + } +} + +SWIGRUNTIME PyObject * +SwigPyPacked_str(SwigPyPacked *v) +{ + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ + return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); + } else { + return SWIG_Python_str_FromChar(v->ty->name); + } +} + +SWIGRUNTIME int +SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) +{ + size_t i = v->size; + size_t j = w->size; + int s = (i < j) ? -1 : ((i > j) ? 1 : 0); + return s ? s : strncmp((const char *)v->pack, (const char *)w->pack, 2*v->size); +} + +SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void); + +SWIGRUNTIME PyTypeObject* +SwigPyPacked_type(void) { + static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyPacked_TypeOnce(); + return type; +} + +SWIGRUNTIMEINLINE int +SwigPyPacked_Check(PyObject *op) { +#ifdef Py_LIMITED_API + int cmp; + PyObject *tp_name; +#endif + PyTypeObject* op_type = Py_TYPE(op); + if (op_type == SwigPyPacked_TypeOnce()) + return 1; +#ifdef Py_LIMITED_API + tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__"); + if (!tp_name) + return 0; + cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyPacked"); + SWIG_Py_DECREF(tp_name); + return cmp == 0; +#else + return (strcmp(op_type->tp_name, "SwigPyPacked") == 0); +#endif +} + +SWIGRUNTIME void +SwigPyPacked_dealloc(PyObject *v) +{ + if (SwigPyPacked_Check(v)) { + SwigPyPacked *sobj = (SwigPyPacked *) v; + free(sobj->pack); + } + PyObject_Free(v); +} + +SWIGRUNTIME PyTypeObject* +SwigPyPacked_TypeOnce(void) { + static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; +#ifndef SWIG_HEAPTYPES + static PyTypeObject swigpypacked_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { +#if PY_VERSION_HEX>=0x03000000 + PyVarObject_HEAD_INIT(NULL, 0) +#else + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ +#endif + "SwigPyPacked", /* tp_name */ + sizeof(SwigPyPacked), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ +#if PY_VERSION_HEX < 0x030800b4 + (printfunc)0, /* tp_print */ +#else + (Py_ssize_t)0, /* tp_vectorcall_offset */ +#endif + (getattrfunc)0, /* tp_getattr */ + (setattrfunc)0, /* tp_setattr */ +#if PY_VERSION_HEX>=0x03000000 + 0, /* tp_reserved in 3.0.1 */ +#else + (cmpfunc)SwigPyPacked_compare, /* tp_compare */ +#endif + (reprfunc)SwigPyPacked_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + (reprfunc)SwigPyPacked_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigpacked_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ + 0, /* tp_del */ + 0, /* tp_version_tag */ +#if PY_VERSION_HEX >= 0x03040000 + 0, /* tp_finalize */ +#endif +#if PY_VERSION_HEX >= 0x03080000 + 0, /* tp_vectorcall */ +#endif +#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) + 0, /* tp_print */ +#endif +#if PY_VERSION_HEX >= 0x030c0000 + 0, /* tp_watched */ +#endif +#if PY_VERSION_HEX >= 0x030d00a4 + 0, /* tp_versions_used */ +#endif +#ifdef COUNT_ALLOCS + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ + 0, /* tp_prev */ + 0 /* tp_next */ +#endif + }; + swigpypacked_type = tmp; + type_init = 1; + if (PyType_Ready(&swigpypacked_type) != 0) + return NULL; + } + return &swigpypacked_type; +#else + PyType_Slot slots[] = { + { Py_tp_dealloc, (void *)SwigPyPacked_dealloc }, + { Py_tp_repr, (void *)SwigPyPacked_repr }, + { Py_tp_str, (void *)SwigPyPacked_str }, + { Py_tp_getattro, (void *)PyObject_GenericGetAttr }, + { Py_tp_doc, (void *)swigpacked_doc }, + { 0, NULL } + }; + PyType_Spec spec = { + "SwigPyPacked", + sizeof(SwigPyPacked), + 0, + Py_TPFLAGS_DEFAULT, + slots + }; + return (PyTypeObject *)PyType_FromSpec(&spec); +#endif +} + +SWIGRUNTIME PyObject * +SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) +{ + SwigPyPacked *sobj = PyObject_New(SwigPyPacked, SwigPyPacked_type()); + if (sobj) { + void *pack = malloc(size); + if (pack) { + memcpy(pack, ptr, size); + sobj->pack = pack; + sobj->ty = ty; + sobj->size = size; + } else { + PyObject_Free((PyObject *)sobj); + sobj = 0; + } + } + return (PyObject *) sobj; +} + +SWIGRUNTIME swig_type_info * +SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) +{ + if (SwigPyPacked_Check(obj)) { + SwigPyPacked *sobj = (SwigPyPacked *)obj; + if (sobj->size != size) return 0; + memcpy(ptr, sobj->pack, size); + return sobj->ty; + } else { + return 0; + } +} + +/* ----------------------------------------------------------------------------- + * pointers/data manipulation + * ----------------------------------------------------------------------------- */ + +static PyObject *Swig_This_global = NULL; + +SWIGRUNTIME PyObject * +SWIG_This(void) +{ + if (Swig_This_global == NULL) + Swig_This_global = SWIG_Python_str_FromChar("this"); + return Swig_This_global; +} + +/* #define SWIG_PYTHON_SLOW_GETSET_THIS */ + +/* TODO: I don't know how to implement the fast getset in Python 3 right now */ +#if PY_VERSION_HEX>=0x03000000 +#define SWIG_PYTHON_SLOW_GETSET_THIS +#endif + +SWIGRUNTIME SwigPyObject * +SWIG_Python_GetSwigThis(PyObject *pyobj) +{ + PyObject *obj; + + if (SwigPyObject_Check(pyobj)) + return (SwigPyObject *) pyobj; + +#ifdef SWIGPYTHON_BUILTIN + (void)obj; +# ifdef PyWeakref_CheckProxy + if (PyWeakref_CheckProxy(pyobj)) { +#if PY_VERSION_HEX >= 0x030d0000 + PyWeakref_GetRef(pyobj, &pyobj); + Py_DECREF(pyobj); +#else + pyobj = PyWeakref_GET_OBJECT(pyobj); +#endif + if (pyobj && SwigPyObject_Check(pyobj)) + return (SwigPyObject*) pyobj; + } +# endif + return NULL; +#else + + obj = 0; + +#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) + if (PyInstance_Check(pyobj)) { + obj = _PyInstance_Lookup(pyobj, SWIG_This()); + } else { + PyObject **dictptr = _PyObject_GetDictPtr(pyobj); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; + } else { +#ifdef PyWeakref_CheckProxy + if (PyWeakref_CheckProxy(pyobj)) { + PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); + return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; + } +#endif + obj = PyObject_GetAttr(pyobj,SWIG_This()); + if (obj) { + SWIG_Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } + } + } +#else + obj = PyObject_GetAttr(pyobj,SWIG_This()); + if (obj) { + SWIG_Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } +#endif + if (obj && !SwigPyObject_Check(obj)) { + /* a PyObject is called 'this', try to get the 'real this' + SwigPyObject from it */ + return SWIG_Python_GetSwigThis(obj); + } + return (SwigPyObject *)obj; +#endif +} + +/* Acquire a pointer value */ + +SWIGRUNTIME int +SWIG_Python_AcquirePtr(PyObject *obj, int own) { + if (own == SWIG_POINTER_OWN) { + SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); + if (sobj) { + int oldown = sobj->own; + sobj->own = own; + return oldown; + } + } + return 0; +} + +/* Convert a pointer value */ + +SWIGRUNTIME int +SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { + int res; + SwigPyObject *sobj; + int implicit_conv = (flags & SWIG_POINTER_IMPLICIT_CONV) != 0; + + if (!obj) + return SWIG_ERROR; + if (obj == Py_None && !implicit_conv) { + if (ptr) + *ptr = 0; + return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; + } + + res = SWIG_ERROR; + + sobj = SWIG_Python_GetSwigThis(obj); + if (own) + *own = 0; + while (sobj) { + void *vptr = sobj->ptr; + if (ty) { + swig_type_info *to = sobj->ty; + if (to == ty) { + /* no type cast needed */ + if (ptr) *ptr = vptr; + break; + } else { + swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); + if (!tc) { + sobj = (SwigPyObject *)sobj->next; + } else { + if (ptr) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc,vptr,&newmemory); + if (newmemory == SWIG_CAST_NEW_MEMORY) { + assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */ + if (own) + *own = *own | SWIG_CAST_NEW_MEMORY; + } + } + break; + } + } + } else { + if (ptr) *ptr = vptr; + break; + } + } + if (sobj) { + if (((flags & SWIG_POINTER_RELEASE) == SWIG_POINTER_RELEASE) && !sobj->own) { + res = SWIG_ERROR_RELEASE_NOT_OWNED; + } else { + if (own) + *own = *own | sobj->own; + if (flags & SWIG_POINTER_DISOWN) { + sobj->own = 0; + } + if (flags & SWIG_POINTER_CLEAR) { + sobj->ptr = 0; + } + res = SWIG_OK; + } + } else { + if (implicit_conv) { + SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; + if (data && !data->implicitconv) { + PyObject *klass = data->klass; + if (klass) { + PyObject *impconv; + data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ + impconv = SWIG_Python_CallFunctor(klass, obj); + data->implicitconv = 0; + if (PyErr_Occurred()) { + PyErr_Clear(); + impconv = 0; + } + if (impconv) { + SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); + if (iobj) { + void *vptr; + res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); + if (SWIG_IsOK(res)) { + if (ptr) { + *ptr = vptr; + /* transfer the ownership to 'ptr' */ + iobj->own = 0; + res = SWIG_AddCast(res); + res = SWIG_AddNewMask(res); + } else { + res = SWIG_AddCast(res); + } + } + } + SWIG_Py_DECREF(impconv); + } + } + } + if (!SWIG_IsOK(res) && obj == Py_None) { + if (ptr) + *ptr = 0; + if (PyErr_Occurred()) + PyErr_Clear(); + res = SWIG_OK; + } + } + } + return res; +} + +/* Convert a function ptr value */ + +SWIGRUNTIME int +SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { + if (!PyCFunction_Check(obj)) { + return SWIG_ConvertPtr(obj, ptr, ty, 0); + } else { + void *vptr = 0; + swig_cast_info *tc; + + /* here we get the method pointer for callbacks */ +#ifndef Py_LIMITED_API + const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); +#else + PyObject* pystr_doc = PyObject_GetAttrString(obj, "__doc__"); + PyObject *bytes = NULL; + const char *doc = pystr_doc ? SWIG_PyUnicode_AsUTF8AndSize(pystr_doc, NULL, &bytes) : 0; +#endif + const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; + if (desc) + desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; +#ifdef Py_LIMITED_API + SWIG_Py_XDECREF(bytes); + SWIG_Py_XDECREF(pystr_doc); +#endif + if (!desc) + return SWIG_ERROR; + tc = SWIG_TypeCheck(desc,ty); + if (tc) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc,vptr,&newmemory); + assert(!newmemory); /* newmemory handling not yet implemented */ + } else { + return SWIG_ERROR; + } + return SWIG_OK; + } +} + +/* Convert a packed pointer value */ + +SWIGRUNTIME int +SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { + swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); + if (!to) return SWIG_ERROR; + if (ty) { + if (to != ty) { + /* check type cast? */ + swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); + if (!tc) return SWIG_ERROR; + } + } + return SWIG_OK; +} + +/* ----------------------------------------------------------------------------- + * Create a new pointer object + * ----------------------------------------------------------------------------- */ + +/* + Create a new instance object, without calling __init__, and set the + 'this' attribute. +*/ + +SWIGRUNTIME PyObject* +SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) +{ + PyObject *inst = 0; + PyObject *newraw = data->newraw; + if (newraw) { + inst = PyObject_Call(newraw, data->newargs, NULL); + if (inst) { +#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) + PyObject **dictptr = _PyObject_GetDictPtr(inst); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; + } + if (dict) { + PyDict_SetItem(dict, SWIG_This(), swig_this); + } else{ + SWIG_Py_DECREF(inst); + inst = 0; + } + } +#else + if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) { + SWIG_Py_DECREF(inst); + inst = 0; + } +#endif + } + } else { +#if PY_VERSION_HEX >= 0x03000000 + PyObject *empty_args = PyTuple_New(0); + if (empty_args) { + PyObject *empty_kwargs = PyDict_New(); + if (empty_kwargs) { +#ifndef Py_LIMITED_API + newfunc newfn = ((PyTypeObject *)data->newargs)->tp_new; +#else + newfunc newfn = (newfunc)PyType_GetSlot((PyTypeObject *)data->newargs, Py_tp_new); +#endif + inst = newfn((PyTypeObject *)data->newargs, empty_args, empty_kwargs); + SWIG_Py_DECREF(empty_kwargs); + if (inst) { + if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) { + SWIG_Py_DECREF(inst); + inst = 0; + } else { + PyType_Modified(Py_TYPE(inst)); + } + } + } + SWIG_Py_DECREF(empty_args); + } +#else + PyObject *dict = PyDict_New(); + if (dict) { + PyDict_SetItem(dict, SWIG_This(), swig_this); + inst = PyInstance_NewRaw(data->newargs, dict); + SWIG_Py_DECREF(dict); + } +#endif + } + return inst; +} + +SWIGRUNTIME int +SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) +{ +#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) + PyObject **dictptr = _PyObject_GetDictPtr(inst); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; + } + if (dict) { + return PyDict_SetItem(dict, SWIG_This(), swig_this); + } else{ + return -1; + } + } +#endif + return PyObject_SetAttr(inst, SWIG_This(), swig_this); +} + + +SWIGINTERN PyObject * +SWIG_Python_InitShadowInstance(PyObject *args) { + PyObject *obj[2]; + if (!SWIG_Python_UnpackTuple(args, "swiginit", 2, 2, obj)) { + return NULL; + } else { + SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); + if (sthis) { + SWIG_Py_DECREF(SwigPyObject_append((PyObject*) sthis, obj[1])); + } else { + if (SWIG_Python_SetSwigThis(obj[0], obj[1]) != 0) + return NULL; + } + return SWIG_Py_Void(); + } +} + +/* Create a new pointer object */ + +SWIGRUNTIME PyObject * +SWIG_Python_NewPointerObj(PyObject *self, void *ptr, swig_type_info *type, int flags) { + SwigPyClientData *clientdata; + PyObject * robj; + int own; + + if (!ptr) + return SWIG_Py_Void(); + + clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; + own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; + if (clientdata && clientdata->pytype) { + SwigPyObject *newobj; + if (flags & SWIG_BUILTIN_TP_INIT) { + newobj = (SwigPyObject*) self; + if (newobj->ptr) { +#ifndef Py_LIMITED_API + allocfunc alloc = clientdata->pytype->tp_alloc; +#else + allocfunc alloc = (allocfunc)PyType_GetSlot(clientdata->pytype, Py_tp_alloc); +#endif + PyObject *next_self = alloc(clientdata->pytype, 0); + while (newobj->next) + newobj = (SwigPyObject *) newobj->next; + newobj->next = next_self; + newobj = (SwigPyObject *)next_self; +#ifdef SWIGPYTHON_BUILTIN + newobj->dict = 0; +#endif + } + } else { + newobj = PyObject_New(SwigPyObject, clientdata->pytype); +#ifdef SWIGPYTHON_BUILTIN + if (newobj) { + newobj->dict = 0; + } +#endif + } + if (newobj) { + newobj->ptr = ptr; + newobj->ty = type; + newobj->own = own; + newobj->next = 0; + return (PyObject*) newobj; + } + return SWIG_Py_Void(); + } + + assert(!(flags & SWIG_BUILTIN_TP_INIT)); + + robj = SwigPyObject_New(ptr, type, own); + if (robj && clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { + PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); + SWIG_Py_DECREF(robj); + robj = inst; + } + return robj; +} + +/* Create a new packed object */ + +SWIGRUNTIMEINLINE PyObject * +SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { + return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); +} + +/* -----------------------------------------------------------------------------* + * Get type list + * -----------------------------------------------------------------------------*/ + +#ifdef SWIG_LINK_RUNTIME +void *SWIG_ReturnGlobalTypeList(void *); +#endif + +static PyObject *Swig_TypeCache_global = NULL; + +/* The python cached type query */ +SWIGRUNTIME PyObject * +SWIG_Python_TypeCache(void) { + if (Swig_TypeCache_global == NULL) { + Swig_TypeCache_global = PyDict_New(); + } + return Swig_TypeCache_global; +} + +SWIGRUNTIME swig_module_info * +SWIG_Python_GetModule(void *SWIGUNUSEDPARM(clientdata)) { +#ifdef SWIG_LINK_RUNTIME + static void *type_pointer = (void *)0; + /* first check if module already created */ + if (!type_pointer) { + type_pointer = SWIG_ReturnGlobalTypeList((void *)0); + } +#else + void *type_pointer = PyCapsule_Import(SWIGPY_CAPSULE_NAME, 0); + if (PyErr_Occurred()) { + PyErr_Clear(); + type_pointer = (void *)0; + } +#endif + return (swig_module_info *) type_pointer; +} + + +static int interpreter_counter = 0; /* how many (sub-)interpreters are using swig_module's types */ + +SWIGRUNTIME void +SWIG_Python_DestroyModule(PyObject *obj) +{ + swig_module_info *swig_module = (swig_module_info *) PyCapsule_GetPointer(obj, SWIGPY_CAPSULE_NAME); + swig_type_info **types = swig_module->types; + size_t i; + if (--interpreter_counter != 0) /* another sub-interpreter may still be using the swig_module's types */ + return; + for (i =0; i < swig_module->size; ++i) { + swig_type_info *ty = types[i]; + if (ty->owndata) { + SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; + ty->clientdata = 0; + if (data) SwigPyClientData_Del(data); + } + } + SWIG_Py_DECREF(SWIG_This()); + Swig_This_global = NULL; + SWIG_Py_DECREF(SWIG_globals()); + Swig_Globals_global = NULL; + SWIG_Py_DECREF(SWIG_Python_TypeCache()); + Swig_TypeCache_global = NULL; + Swig_Capsule_global = NULL; +} + +SWIGRUNTIME void +SWIG_Python_SetModule(swig_module_info *swig_module) { +#if PY_VERSION_HEX >= 0x03000000 + /* Add a dummy module object into sys.modules */ + PyObject *module = PyImport_AddModule("swig_runtime_data" SWIG_RUNTIME_VERSION); +#else + static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} }; /* Sentinel */ + PyObject *module = Py_InitModule("swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table); +#endif + PyObject *pointer = PyCapsule_New((void *) swig_module, SWIGPY_CAPSULE_NAME, SWIG_Python_DestroyModule); + if (pointer && module) { + if (PyModule_AddObject(module, SWIGPY_CAPSULE_ATTR_NAME, pointer) == 0) { + ++interpreter_counter; + Swig_Capsule_global = pointer; + } else { + SWIG_Py_DECREF(pointer); + } + } else { + SWIG_Py_XDECREF(pointer); + } +} + +SWIGRUNTIME swig_type_info * +SWIG_Python_TypeQuery(const char *type) +{ + PyObject *cache = SWIG_Python_TypeCache(); + PyObject *key = SWIG_Python_str_FromChar(type); + PyObject *obj = PyDict_GetItem(cache, key); + swig_type_info *descriptor; + if (obj) { + descriptor = (swig_type_info *) PyCapsule_GetPointer(obj, NULL); + } else { + swig_module_info *swig_module = SWIG_GetModule(0); + descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); + if (descriptor) { + obj = PyCapsule_New((void*) descriptor, NULL, NULL); + if (obj) { + PyDict_SetItem(cache, key, obj); + SWIG_Py_DECREF(obj); + } + } + } + SWIG_Py_DECREF(key); + return descriptor; +} + +/* + For backward compatibility only +*/ +#define SWIG_POINTER_EXCEPTION 0 +#define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg) +#define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) + +SWIGRUNTIME int +SWIG_Python_AddErrMesg(const char* mesg, int infront) +{ + if (PyErr_Occurred()) { + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; + PyErr_Fetch(&type, &value, &traceback); + if (value) { + PyObject *old_str = PyObject_Str(value); + PyObject *bytes = NULL; + const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes); + const char *errmesg = tmp ? tmp : "Invalid error message"; + SWIG_Py_XINCREF(type); + PyErr_Clear(); + if (infront) { + PyErr_Format(type, "%s %s", mesg, errmesg); + } else { + PyErr_Format(type, "%s %s", errmesg, mesg); + } + SWIG_Py_XDECREF(bytes); + SWIG_Py_DECREF(old_str); + } + return 1; + } else { + return 0; + } +} + +SWIGRUNTIME int +SWIG_Python_ArgFail(int argnum) +{ + if (PyErr_Occurred()) { + /* add information about failing argument */ + char mesg[256]; + PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); + return SWIG_Python_AddErrMesg(mesg, 1); + } else { + return 0; + } +} + +SWIGRUNTIMEINLINE const char * +SwigPyObject_GetDesc(PyObject *self) +{ + SwigPyObject *v = (SwigPyObject *)self; + swig_type_info *ty = v ? v->ty : 0; + return ty ? ty->str : ""; +} + +SWIGRUNTIME void +SWIG_Python_TypeError(const char *type, PyObject *obj) +{ + (void) obj; + if (type) { +#if defined(SWIG_COBJECT_TYPES) + if (obj && SwigPyObject_Check(obj)) { + const char *otype = (const char *) SwigPyObject_GetDesc(obj); + if (otype) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", + type, otype); + return; + } + } else +#endif + { +#ifndef Py_LIMITED_API + /* tp_name is not accessible */ + const char *otype = (obj ? obj->ob_type->tp_name : 0); + if (otype) { + PyObject *str = PyObject_Str(obj); + PyObject *bytes = NULL; + const char *cstr = str ? SWIG_PyUnicode_AsUTF8AndSize(str, NULL, &bytes) : 0; + if (cstr) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", + type, otype, cstr); + } else { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", + type, otype); + } + SWIG_Py_XDECREF(bytes); + SWIG_Py_XDECREF(str); + return; + } +#endif + } + PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); + } else { + PyErr_Format(PyExc_TypeError, "unexpected type is received"); + } +} + + +/* Convert a pointer value, signal an exception on a type mismatch */ +SWIGRUNTIME void * +SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int SWIGUNUSEDPARM(argnum), int flags) { + void *result; + if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { + PyErr_Clear(); + } + return result; +} + +#ifdef SWIGPYTHON_BUILTIN +SWIGRUNTIME int +SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) { + PyTypeObject *tp = obj->ob_type; + PyObject *descr; + PyObject *encoded_name; + descrsetfunc f; + int res = -1; + +# ifdef Py_USING_UNICODE + if (PyString_Check(name)) { + name = PyUnicode_Decode(PyString_AsString(name), PyString_Size(name), NULL, NULL); + if (!name) + return -1; + } else if (!PyUnicode_Check(name)) +# else + if (!PyString_Check(name)) +# endif + { + PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); + return -1; + } else { + SWIG_Py_INCREF(name); + } + + if (!tp->tp_dict) { + if (PyType_Ready(tp) != 0) + goto done; + } + + descr = _PyType_Lookup(tp, name); + f = NULL; + if (descr != NULL) + f = descr->ob_type->tp_descr_set; + if (!f) { + if (PyString_Check(name)) { + encoded_name = name; + SWIG_Py_INCREF(name); + } else { + encoded_name = PyUnicode_AsUTF8String(name); + if (!encoded_name) + goto done; + } + PyErr_Format(PyExc_AttributeError, "'%.100s' object has no attribute '%.200s'", tp->tp_name, PyString_AsString(encoded_name)); + SWIG_Py_DECREF(encoded_name); + } else { + res = f(descr, obj, value); + } + + done: + SWIG_Py_DECREF(name); + return res; +} +#endif + + +#ifdef __cplusplus +} +#endif + + + +#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) + +#define SWIG_contract_assert(expr, msg) do { if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } } while (0) + + + + #define SWIG_exception(code, msg) do { SWIG_Error(code, msg); SWIG_fail;; } while(0) + + +/* -------- TYPES TABLE (BEGIN) -------- */ + +#define SWIGTYPE_p_char swig_types[0] +#define SWIGTYPE_p_float swig_types[1] +#define SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText swig_types[2] +#define SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText swig_types[3] +#define SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece swig_types[4] +#define SWIGTYPE_p_sentencepiece__SentenceIterator swig_types[5] +#define SWIGTYPE_p_sentencepiece__SentencePieceNormalizer swig_types[6] +#define SWIGTYPE_p_sentencepiece__SentencePieceProcessor swig_types[7] +#define SWIGTYPE_p_sentencepiece__SentencePieceTrainer swig_types[8] +#define SWIGTYPE_p_std__string swig_types[9] +#define SWIGTYPE_p_std__unordered_mapT_std__string_std__string_t swig_types[10] +#define SWIGTYPE_p_std__vectorT_absl__string_view_t swig_types[11] +#define SWIGTYPE_p_std__vectorT_int_t swig_types[12] +#define SWIGTYPE_p_std__vectorT_std__vectorT_absl__string_view_t_t swig_types[13] +#define SWIGTYPE_p_std__vectorT_std__vectorT_int_t_t swig_types[14] +static swig_type_info *swig_types[16]; +static swig_module_info swig_module = {swig_types, 15, 0, 0, 0, 0}; +#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) +#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) + +/* -------- TYPES TABLE (END) -------- */ + +#ifdef SWIG_TypeQuery +# undef SWIG_TypeQuery +#endif +#define SWIG_TypeQuery SWIG_Python_TypeQuery + +/*----------------------------------------------- + @(target):= _sentencepiece.so + ------------------------------------------------*/ +#if PY_VERSION_HEX >= 0x03000000 +# define SWIG_init PyInit__sentencepiece + +#else +# define SWIG_init init_sentencepiece + +#endif + +#ifdef __cplusplus +#include +/* SwigValueWrapper is described in swig.swg */ +template class SwigValueWrapper { + struct SwigSmartPointer { + T *ptr; + SwigSmartPointer(T *p) : ptr(p) { } + ~SwigSmartPointer() { delete ptr; } + SwigSmartPointer& operator=(SwigSmartPointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; } + void reset(T *p) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = p; } + } pointer; + SwigValueWrapper& operator=(const SwigValueWrapper& rhs); + SwigValueWrapper(const SwigValueWrapper& rhs); +public: + SwigValueWrapper() : pointer(0) { } + SwigValueWrapper& operator=(const T& t) { SwigSmartPointer tmp(new T(t)); pointer = tmp; return *this; } +#if __cplusplus >=201103L + SwigValueWrapper& operator=(T&& t) { SwigSmartPointer tmp(new T(std::move(t))); pointer = tmp; return *this; } + operator T&&() const { return std::move(*pointer.ptr); } +#else + operator T&() const { return *pointer.ptr; } +#endif + T *operator&() const { return pointer.ptr; } + static void reset(SwigValueWrapper& t, T *p) { t.pointer.reset(p); } +}; + +/* + * SwigValueInit() is a generic initialisation solution as the following approach: + * + * T c_result = T(); + * + * doesn't compile for all types for example: + * + * unsigned int c_result = unsigned int(); + */ +template T SwigValueInit() { + return T(); +} + +#if __cplusplus >=201103L +# define SWIG_STD_MOVE(OBJ) std::move(OBJ) +#else +# define SWIG_STD_MOVE(OBJ) OBJ +#endif + +#endif + + +#define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) +#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),reinterpret_cast< void** >(a)) + + +#include + + +namespace swig { + class SwigPtr_PyObject { + protected: + PyObject *_obj; + + public: + SwigPtr_PyObject() :_obj(0) + { + } + + SwigPtr_PyObject(const SwigPtr_PyObject& item) : _obj(item._obj) + { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + SWIG_Py_XINCREF(_obj); + SWIG_PYTHON_THREAD_END_BLOCK; + } + + SwigPtr_PyObject(PyObject *obj, bool initial_ref = true) :_obj(obj) + { + if (initial_ref) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + SWIG_Py_XINCREF(_obj); + SWIG_PYTHON_THREAD_END_BLOCK; + } + } + + SwigPtr_PyObject & operator=(const SwigPtr_PyObject& item) + { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + SWIG_Py_XINCREF(item._obj); + SWIG_Py_XDECREF(_obj); + _obj = item._obj; + SWIG_PYTHON_THREAD_END_BLOCK; + return *this; + } + + ~SwigPtr_PyObject() + { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + SWIG_Py_XDECREF(_obj); + SWIG_PYTHON_THREAD_END_BLOCK; + } + + operator PyObject *() const + { + return _obj; + } + + PyObject *operator->() const + { + return _obj; + } + }; +} + + +namespace swig { + struct SwigVar_PyObject : SwigPtr_PyObject { + SwigVar_PyObject(PyObject* obj = 0) : SwigPtr_PyObject(obj, false) { } + + SwigVar_PyObject & operator = (PyObject* obj) + { + SWIG_Py_XDECREF(_obj); + _obj = obj; + return *this; + } + }; +} + + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +PyObject* kUnicodeInput = reinterpret_cast(0x1); +PyObject* kByteInput = reinterpret_cast(0x2); + +using BytesArray = std::vector; + +inline void ReleaseResultObject(PyObject *obj) { + if (obj != nullptr && obj != kUnicodeInput && obj != kByteInput) { + Py_XDECREF(obj); + } +} + +class PyInputString { + public: + explicit PyInputString(PyObject* obj) { + if (PyUnicode_Check(obj)) { + str_ = const_cast(PyUnicode_AsUTF8AndSize(obj, &size_)); + input_type_ = kUnicodeInput; + } else if (PyBytes_Check(obj)) { + PyBytes_AsStringAndSize(obj, &str_, &size_); + input_type_ = kByteInput; + } else { + str_ = nullptr; + } + } + absl::string_view str() const { return absl::string_view(data(), size()); } + const char* data() const { return str_; } + Py_ssize_t size() const { return size_; } + bool IsAvalable() const { return str_ != nullptr; } + PyObject *input_type() const { return input_type_; } + + static bool IsUnicode(PyObject *resultobj) { + return (resultobj == nullptr || resultobj == kUnicodeInput); + } + + private: + PyObject* input_type_ = nullptr; + char* str_ = nullptr; + Py_ssize_t size_ = 0; +}; + +PyObject* MakePyOutputString(const std::string& output, + PyObject *resultobj) { + if (PyInputString::IsUnicode(resultobj)) { + return PyUnicode_FromStringAndSize(output.data(), output.size()); + } + return PyBytes_FromStringAndSize(output.data(), output.size()); +} + +PyObject* MakePyOutputBytes(const sentencepiece::util::bytes& output) { + return PyBytes_FromStringAndSize(output.data(), output.size()); +} + +int ToSwigError(sentencepiece::util::StatusCode code) { + switch (code) { + case sentencepiece::util::StatusCode::kNotFound: + return SWIG_IOError; + case sentencepiece::util::StatusCode::kOutOfRange: + return SWIG_IndexError; + case sentencepiece::util::StatusCode::kInvalidArgument: + return SWIG_SyntaxError; + default: + return SWIG_RuntimeError; + } + return SWIG_RuntimeError; +} + +class PySentenceIterator : public sentencepiece::SentenceIterator { + public: + PySentenceIterator(PyObject *iter) : iter_(iter) { + item_ = PyIter_Next(iter_); + CopyValue(); + } + + ~PySentenceIterator() { + // Py_XDECREF(iter_); + } + + bool done() const override { + return item_ == nullptr; + } + + void Next() override { + item_ = PyIter_Next(iter_); + CopyValue(); + } + + const std::string &value() const override { + return value_; + } + + sentencepiece::util::Status status() const override { + return status_; + } + + private: + void CopyValue() { + if (item_ == nullptr) return; + const PyInputString ustring(item_); + if (ustring.IsAvalable()) { + const char *data = ustring.data(); + size_t size = ustring.size(); + while (size > 0) { + if (data[size - 1] == '\r' || data[size - 1] == '\n') + --size; + else + break; + } + value_.assign(data, size); + } else { + status_ = sentencepiece::util::Status(sentencepiece::util::StatusCode::kInternal, + "Not a string."); + } + Py_XDECREF(item_); + } + PyObject *iter_ = nullptr; + PyObject *item_ = nullptr; + std::string value_; + sentencepiece::util::Status status_; +}; + +inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp, + std::vector *ids, + bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) { + if (!add_bos && !add_eos && !reverse) return; + if (reverse) std::reverse(ids->begin(), ids->end()); + if (add_bos) ids->insert(ids->begin(), sp.bos_id()); + if (add_eos) ids->push_back(sp.eos_id()); +} + +inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp, + std::vector *pieces, + bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) { + if (!add_bos && !add_eos && !reverse && !emit_unk_piece) return; + if (reverse) std::reverse(pieces->begin(), pieces->end()); + if (add_bos) pieces->insert(pieces->begin(), sp.IdToPiece(sp.bos_id())); + if (add_eos) pieces->push_back(sp.IdToPiece(sp.eos_id())); + if (emit_unk_piece) { + const auto &unk = sp.IdToPiece(sp.unk_id()); + for (auto &piece : *pieces) { + const int id = sp.PieceToId(piece); + if (id == sp.unk_id()) { + piece = unk; + } + } + } +} + +inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp, + sentencepiece::util::bytes *proto, + bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) { + if (add_bos || add_eos || reverse || emit_unk_piece) { + throw sentencepiece::util::Status( + sentencepiece::util::StatusCode::kUnimplemented, + "add_bos, add_eos, reverse, and emit_unk_piece is not supported in proto API"); + } +} + +inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp, + sentencepiece::ImmutableSentencePieceText *proto, + bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) { + if (add_bos || add_eos || reverse || emit_unk_piece) { + throw sentencepiece::util::Status( + sentencepiece::util::StatusCode::kUnimplemented, + "add_bos, add_eos, reverse, and emit_unk_piece is not supported in proto API"); + } +} + +inline void CheckIds(const std::vector &ids, int num_pieces) { + for (int id : ids) { + if (id < 0 || id >= num_pieces) { + throw sentencepiece::util::Status( + sentencepiece::util::StatusCode::kOutOfRange, + "piece id is out of range."); + } + } +} + +inline void CheckIds(const std::vector &ids, int num_pieces) {} + +inline void CheckIdsBatch(const std::vector> &ids, int num_pieces) { + for (const auto &v : ids) CheckIds(v, num_pieces); +} + +template +inline void ConvertToUnicodeSpans(T *proto) {} + +template <> +inline void ConvertToUnicodeSpans(sentencepiece::ImmutableSentencePieceText *proto) { + proto->ConvertToUnicodeSpans(); +} + +template <> +inline void ConvertToUnicodeSpans(sentencepiece::ImmutableNBestSentencePieceText *proto) { + proto->ConvertToUnicodeSpans(); +} + +class ThreadPool { + public: + explicit ThreadPool(size_t request_size) : + request_size_(request_size) {} + + virtual ~ThreadPool() { + for (auto &task : tasks_) { + task.join(); + } + } + + void Schedule(std::function closure) { + static constexpr size_t kMinThreadSize = 2; + if (request_size_ < kMinThreadSize) { + closure(); + } else { + tasks_.emplace_back(closure); + } + } + + private: + size_t request_size_ = 0; + std::vector tasks_; +}; + +template +inline void InitNumThreads(const std::vector &ins, int *num_threads) { + if (*num_threads < 0) { + *num_threads = std::thread::hardware_concurrency(); + } + *num_threads = std::max(1, + std::min({*num_threads, + static_cast(ins.size()), 256})); +} + +#define DEFINE_ENCODE_BATCH_FUNC_IMPL(FuncName, InType, OutType) \ + std::vector outs(ins.size()); \ + InitNumThreads(ins, &num_threads); \ + { \ + ThreadPool pool(ins.size()); \ + std::atomic index = 0; \ + for (int n = 0; n < num_threads; ++n) { \ + pool.Schedule([&]() { \ + size_t i = 0; \ + while ((i = std::atomic_fetch_add(&index, 1)) < outs.size()) { \ + auto out = enable_sampling ? \ + self->Sample##FuncName(ins[i], \ + nbest_size, alpha) : \ + self->FuncName(ins[i]); \ + RewriteIds(*self, &out, add_bos, add_eos, reverse, \ + emit_unk_piece); \ + ConvertToUnicodeSpans(&out); \ + outs[i] = std::move(out); \ + } \ + }); \ + } \ + } \ + return outs; + +#define DEFINE_DECODE_BATCH_FUNC_IMPL(FuncName, InType, OutType) \ + std::vector outs(ins.size()); \ + InitNumThreads(ins, &num_threads); \ + { \ + std::atomic index = 0; \ + ThreadPool pool(ins.size()); \ + for (int n = 0; n < num_threads; ++n) { \ + pool.Schedule([&]() { \ + size_t i = 0; \ + while ((i = std::atomic_fetch_add(&index, 1)) < outs.size()) { \ + auto out = self->FuncName(ins[i]); \ + ConvertToUnicodeSpans(&out); \ + outs[i] = std::move(out); \ + } \ + }); \ + } \ + } \ + return outs; + +} // namespace + + +SWIGINTERNINLINE PyObject* + SWIG_From_unsigned_SS_int (unsigned int value) +{ + return PyInt_FromSize_t((size_t) value); +} + +SWIGINTERN sentencepiece::util::bytes const &sentencepiece_ImmutableSentencePieceText_ImmutableSentencePiece__surface_as_bytes(sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *self){ + return self->surface(); + } +SWIGINTERN sentencepiece::util::bytes const &sentencepiece_ImmutableSentencePieceText_ImmutableSentencePiece__piece_as_bytes(sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *self){ + return self->piece(); + } + + #define SWIG_From_long PyInt_FromLong + + +SWIGINTERNINLINE PyObject* +SWIG_From_unsigned_SS_long (unsigned long value) +{ + return (value > LONG_MAX) ? + PyLong_FromUnsignedLong(value) : PyInt_FromLong(static_cast< long >(value)); +} + + +#include +#if !defined(SWIG_NO_LLONG_MAX) +# if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__) +# define LLONG_MAX __LONG_LONG_MAX__ +# define LLONG_MIN (-LLONG_MAX - 1LL) +# define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL) +# endif +#endif + + +#if defined(LLONG_MAX) && !defined(SWIG_LONG_LONG_AVAILABLE) +# define SWIG_LONG_LONG_AVAILABLE +#endif + + +#ifdef SWIG_LONG_LONG_AVAILABLE +SWIGINTERNINLINE PyObject* +SWIG_From_unsigned_SS_long_SS_long (unsigned long long value) +{ + return (value > LONG_MAX) ? + PyLong_FromUnsignedLongLong(value) : PyInt_FromLong(static_cast< long >(value)); +} +#endif + + +SWIGINTERNINLINE PyObject * +SWIG_From_size_t (size_t value) +{ +#ifdef SWIG_LONG_LONG_AVAILABLE + if (sizeof(size_t) <= sizeof(unsigned long)) { +#endif + return SWIG_From_unsigned_SS_long (static_cast< unsigned long >(value)); +#ifdef SWIG_LONG_LONG_AVAILABLE + } else { + /* assume sizeof(size_t) <= sizeof(unsigned long long) */ + return SWIG_From_unsigned_SS_long_SS_long (static_cast< unsigned long long >(value)); + } +#endif +} + + +SWIGINTERN int +SWIG_AsVal_double (PyObject *obj, double *val) +{ + int res = SWIG_TypeError; + if (PyFloat_Check(obj)) { + if (val) *val = PyFloat_AsDouble(obj); + return SWIG_OK; +#if PY_VERSION_HEX < 0x03000000 + } else if (PyInt_Check(obj)) { + if (val) *val = (double) PyInt_AsLong(obj); + return SWIG_OK; +#endif + } else if (PyLong_Check(obj)) { + double v = PyLong_AsDouble(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_OK; + } else { + PyErr_Clear(); + } + } +#ifdef SWIG_PYTHON_CAST_MODE + { + int dispatch = 0; + double d = PyFloat_AsDouble(obj); + if (!PyErr_Occurred()) { + if (val) *val = d; + return SWIG_AddCast(SWIG_OK); + } else { + PyErr_Clear(); + } + if (!dispatch) { + long v = PyLong_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); + } else { + PyErr_Clear(); + } + } + } +#endif + return res; +} + + +#include + + +#include + + +SWIGINTERNINLINE int +SWIG_CanCastAsInteger(double *d, double min, double max) { + double x = *d; + if ((min <= x && x <= max)) { + double fx, cx, rd; + errno = 0; + fx = floor(x); + cx = ceil(x); + rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ + if ((errno == EDOM) || (errno == ERANGE)) { + errno = 0; + } else { + double summ, reps, diff; + if (rd < x) { + diff = x - rd; + } else if (rd > x) { + diff = rd - x; + } else { + return 1; + } + summ = rd + x; + reps = diff/summ; + if (reps < 8*DBL_EPSILON) { + *d = rd; + return 1; + } + } + } + return 0; +} + + +SWIGINTERN int +SWIG_AsVal_long (PyObject *obj, long* val) +{ +#if PY_VERSION_HEX < 0x03000000 + if (PyInt_Check(obj)) { + if (val) *val = PyInt_AsLong(obj); + return SWIG_OK; + } else +#endif + if (PyLong_Check(obj)) { + long v = PyLong_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_OK; + } else { + PyErr_Clear(); + return SWIG_OverflowError; + } + } +#ifdef SWIG_PYTHON_CAST_MODE + { + int dispatch = 0; + long v = PyInt_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_AddCast(SWIG_OK); + } else { + PyErr_Clear(); + } + if (!dispatch) { + double d; + int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); + // Largest double not larger than LONG_MAX (not portably calculated easily) + // Note that double(LONG_MAX) is stored in a double rounded up by one (for 64-bit long) + // 0x7ffffffffffffc00LL == (int64_t)std::nextafter(double(__uint128_t(LONG_MAX)+1), double(0)) + const double long_max = sizeof(long) == 8 ? 0x7ffffffffffffc00LL : LONG_MAX; + // No equivalent needed for 64-bit double(LONG_MIN) is exactly LONG_MIN + if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, long_max)) { + if (val) *val = (long)(d); + return res; + } + } + } +#endif + return SWIG_TypeError; +} + + +SWIGINTERN int +SWIG_AsVal_int (PyObject * obj, int *val) +{ + long v; + int res = SWIG_AsVal_long (obj, &v); + if (SWIG_IsOK(res)) { + if ((v < INT_MIN || v > INT_MAX)) { + return SWIG_OverflowError; + } else { + if (val) *val = static_cast< int >(v); + } + } + return res; +} + + + #define SWIG_From_double PyFloat_FromDouble + + +SWIGINTERNINLINE PyObject * +SWIG_From_float (float value) +{ + return SWIG_From_double (value); +} + +SWIGINTERN sentencepiece::util::bytes const &sentencepiece_ImmutableSentencePieceText__text_as_bytes(sentencepiece::ImmutableSentencePieceText const *self){ + return self->text(); + } + +SWIGINTERN swig_type_info* +SWIG_pchar_descriptor(void) +{ + static swig_type_info* info = 0; + if (!info) { + info = SWIG_TypeQuery("_p_char"); + } + return info; +} + + +/* Return string from Python obj. NOTE: obj must remain in scope in order + to use the returned cptr (but only when alloc is set to SWIG_OLDOBJ) */ +SWIGINTERN int +SWIG_AsCharPtrAndSize(PyObject *obj, char **cptr, size_t *psize, int *alloc) +{ +#if PY_VERSION_HEX>=0x03000000 +#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) + if (PyBytes_Check(obj)) +#else + if (PyUnicode_Check(obj)) +#endif +#else + if (PyString_Check(obj)) +#endif + { + char *cstr; Py_ssize_t len; + PyObject *bytes = NULL; + int ret = SWIG_OK; + if (alloc) + *alloc = SWIG_OLDOBJ; +#if PY_VERSION_HEX>=0x03000000 && defined(SWIG_PYTHON_STRICT_BYTE_CHAR) + if (PyBytes_AsStringAndSize(obj, &cstr, &len) == -1) + return SWIG_TypeError; +#else + cstr = (char *)SWIG_PyUnicode_AsUTF8AndSize(obj, &len, &bytes); + if (!cstr) + return SWIG_TypeError; + /* The returned string is only duplicated if the char * returned is not owned and memory managed by obj */ + if (bytes && cptr) { + if (alloc) { + cstr = reinterpret_cast< char* >(memcpy(new char[len + 1], cstr, sizeof(char)*(len + 1))); + *alloc = SWIG_NEWOBJ; + } else { + /* alloc must be set in order to clean up allocated memory */ + return SWIG_RuntimeError; + } + } +#endif + if (cptr) *cptr = cstr; + if (psize) *psize = len + 1; + SWIG_Py_XDECREF(bytes); + return ret; + } else { +#if defined(SWIG_PYTHON_2_UNICODE) +#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) +#error "Cannot use both SWIG_PYTHON_2_UNICODE and SWIG_PYTHON_STRICT_BYTE_CHAR at once" +#endif +#if PY_VERSION_HEX<0x03000000 + if (PyUnicode_Check(obj)) { + char *cstr; Py_ssize_t len; + if (!alloc && cptr) { + return SWIG_RuntimeError; + } + obj = PyUnicode_AsUTF8String(obj); + if (!obj) + return SWIG_TypeError; + if (PyString_AsStringAndSize(obj, &cstr, &len) != -1) { + if (cptr) { + if (alloc) *alloc = SWIG_NEWOBJ; + *cptr = reinterpret_cast< char* >(memcpy(new char[len + 1], cstr, sizeof(char)*(len + 1))); + } + if (psize) *psize = len + 1; + + SWIG_Py_XDECREF(obj); + return SWIG_OK; + } else { + SWIG_Py_XDECREF(obj); + } + } +#endif +#endif + + swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + if (pchar_descriptor) { + void* vptr = 0; + if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { + if (cptr) *cptr = (char *) vptr; + if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; + if (alloc) *alloc = SWIG_OLDOBJ; + return SWIG_OK; + } + } + } + return SWIG_TypeError; +} + + + + + +/* Getting isfinite working pre C99 across multiple platforms is non-trivial. Users can provide SWIG_isfinite on older platforms. */ +#ifndef SWIG_isfinite +/* isfinite() is a macro for C99 */ +# if defined(isfinite) +# define SWIG_isfinite(X) (isfinite(X)) +# elif defined(__cplusplus) && __cplusplus >= 201103L +/* Use a template so that this works whether isfinite() is std::isfinite() or + * in the global namespace. The reality seems to vary between compiler + * versions. + * + * Make sure namespace std exists to avoid compiler warnings. + * + * extern "C++" is required as this fragment can end up inside an extern "C" { } block + */ +namespace std { } +extern "C++" template +inline int SWIG_isfinite_func(T x) { + using namespace std; + return isfinite(x); +} +# define SWIG_isfinite(X) (SWIG_isfinite_func(X)) +# elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2)) +# define SWIG_isfinite(X) (__builtin_isfinite(X)) +# elif defined(_MSC_VER) +# define SWIG_isfinite(X) (_finite(X)) +# elif defined(__sun) && defined(__SVR4) +# include +# define SWIG_isfinite(X) (finite(X)) +# endif +#endif + + +/* Accept infinite as a valid float value unless we are unable to check if a value is finite */ +#ifdef SWIG_isfinite +# define SWIG_Float_Overflow_Check(X) ((X < -FLT_MAX || X > FLT_MAX) && SWIG_isfinite(X)) +#else +# define SWIG_Float_Overflow_Check(X) ((X < -FLT_MAX || X > FLT_MAX)) +#endif + + +SWIGINTERN int +SWIG_AsVal_float (PyObject * obj, float *val) +{ + double v; + int res = SWIG_AsVal_double (obj, &v); + if (SWIG_IsOK(res)) { + if (SWIG_Float_Overflow_Check(v)) { + return SWIG_OverflowError; + } else { + if (val) *val = static_cast< float >(v); + } + } + return res; +} + + +SWIGINTERNINLINE PyObject* + SWIG_From_int (int value) +{ + return PyInt_FromLong((long) value); +} + + +SWIGINTERNINLINE PyObject* + SWIG_From_bool (bool value) +{ + return PyBool_FromLong(value ? 1 : 0); +} + +SWIGINTERN sentencepiece::util::Status sentencepiece_SentencePieceProcessor_LoadFromFile(sentencepiece::SentencePieceProcessor *self,absl::string_view arg){ + return self->Load(arg); + } + +SWIGINTERN int +SWIG_AsVal_bool (PyObject *obj, bool *val) +{ + int r; + if (!PyBool_Check(obj)) + return SWIG_ERROR; + r = PyObject_IsTrue(obj); + if (r == -1) + return SWIG_ERROR; + if (val) *val = r ? true : false; + return SWIG_OK; +} + +SWIGINTERN std::vector< int > sentencepiece_SentencePieceProcessor__EncodeAsIds(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + auto ids = enable_sampling ? + self->SampleEncodeAsIds(text, nbest_size, alpha) : + self->EncodeAsIds(text); + RewriteIds(*self, &ids, add_bos, add_eos, reverse, emit_unk_piece); + return ids; + } +SWIGINTERN std::vector< std::string > sentencepiece_SentencePieceProcessor__EncodeAsPieces(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + auto pieces = enable_sampling ? + self->SampleEncodeAsPieces(text, nbest_size, alpha) : + self->EncodeAsPieces(text); + RewriteIds(*self, &pieces, add_bos, add_eos, reverse, emit_unk_piece); + return pieces; + } +SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceProcessor__EncodeAsSerializedProto(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + auto proto = enable_sampling ? + self->SampleEncodeAsSerializedProto(text, nbest_size, alpha) : + self->EncodeAsSerializedProto(text); + RewriteIds(*self, &proto, add_bos, add_eos, reverse, emit_unk_piece); + return proto; + } +SWIGINTERN sentencepiece::ImmutableSentencePieceText sentencepiece_SentencePieceProcessor__EncodeAsImmutableProto(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + auto proto = enable_sampling ? + self->SampleEncodeAsImmutableProto(text, nbest_size, alpha) : + self->EncodeAsImmutableProto(text); + proto.ConvertToUnicodeSpans(); + RewriteIds(*self, &proto, add_bos, add_eos, reverse, emit_unk_piece); + return proto; + } +SWIGINTERN std::vector< std::vector< int > > sentencepiece_SentencePieceProcessor__EncodeAsIdsBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< absl::string_view > const &ins,int num_threads,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsIds, + absl::string_view, std::vector); + } +SWIGINTERN std::vector< std::vector< std::string > > sentencepiece_SentencePieceProcessor__EncodeAsPiecesBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< absl::string_view > const &ins,int num_threads,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsPieces, + absl::string_view, std::vector); + } +SWIGINTERN BytesArray sentencepiece_SentencePieceProcessor__EncodeAsSerializedProtoBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< absl::string_view > const &ins,int num_threads,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsSerializedProto, + absl::string_view, + sentencepiece::util::bytes); + } +SWIGINTERN std::vector< sentencepiece::ImmutableSentencePieceText > sentencepiece_SentencePieceProcessor__EncodeAsImmutableProtoBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< absl::string_view > const &ins,int num_threads,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsImmutableProto, + absl::string_view, + sentencepiece::ImmutableSentencePieceText); + } +SWIGINTERN std::string sentencepiece_SentencePieceProcessor__DecodeIds(sentencepiece::SentencePieceProcessor const *self,std::vector< int > const &ids){ + CheckIds(ids, self->GetPieceSize()); + return self->DecodeIds(ids); + } +SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceProcessor__DecodeIdsAsBytes(sentencepiece::SentencePieceProcessor const *self,std::vector< int > const &ids){ + CheckIds(ids, self->GetPieceSize()); + return self->DecodeIds(ids); + } +SWIGINTERN std::string sentencepiece_SentencePieceProcessor__DecodePieces(sentencepiece::SentencePieceProcessor const *self,std::vector< absl::string_view > const &pieces){ + return self->DecodePieces(pieces); + } +SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceProcessor__DecodeIdsAsSerializedProto(sentencepiece::SentencePieceProcessor const *self,std::vector< int > const &ids){ + CheckIds(ids, self->GetPieceSize()); + return self->DecodeIdsAsSerializedProto(ids); + } +SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceProcessor__DecodePiecesAsSerializedProto(sentencepiece::SentencePieceProcessor const *self,std::vector< absl::string_view > const &pieces){ + CheckIds(pieces, self->GetPieceSize()); + return self->DecodePiecesAsSerializedProto(pieces); + } +SWIGINTERN sentencepiece::ImmutableSentencePieceText sentencepiece_SentencePieceProcessor__DecodeIdsAsImmutableProto(sentencepiece::SentencePieceProcessor const *self,std::vector< int > const &ids){ + CheckIds(ids, self->GetPieceSize()); + auto proto = self->DecodeIdsAsImmutableProto(ids); + proto.ConvertToUnicodeSpans(); + return proto; + } +SWIGINTERN sentencepiece::ImmutableSentencePieceText sentencepiece_SentencePieceProcessor__DecodePiecesAsImmutableProto(sentencepiece::SentencePieceProcessor const *self,std::vector< absl::string_view > const &pieces){ + CheckIds(pieces, self->GetPieceSize()); + auto proto= self->DecodePiecesAsImmutableProto(pieces); + proto.ConvertToUnicodeSpans(); + return proto; + } +SWIGINTERN std::vector< std::string > sentencepiece_SentencePieceProcessor__DecodeIdsBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< std::vector< int > > const &ins,int num_threads){ + CheckIdsBatch(ins, self->GetPieceSize()); + DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIds, int, std::string); + } +SWIGINTERN BytesArray sentencepiece_SentencePieceProcessor__DecodeIdsAsBytesBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< std::vector< int > > const &ins,int num_threads){ + CheckIdsBatch(ins, self->GetPieceSize()); + DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIds, int, std::string); + } +SWIGINTERN BytesArray sentencepiece_SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< std::vector< int > > const &ins,int num_threads){ + CheckIdsBatch(ins, self->GetPieceSize()); + DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIdsAsSerializedProto, int, + sentencepiece::util::bytes); + } +SWIGINTERN std::vector< sentencepiece::ImmutableSentencePieceText > sentencepiece_SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< std::vector< int > > const &ins,int num_threads){ + CheckIdsBatch(ins, self->GetPieceSize()); + DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIdsAsImmutableProto, int, + sentencepiece::ImmutableSentencePieceText); + } +SWIGINTERN std::vector< std::string > sentencepiece_SentencePieceProcessor__DecodePiecesBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< std::vector< absl::string_view > > const &ins,int num_threads){ + DEFINE_DECODE_BATCH_FUNC_IMPL(DecodePieces, std::string, std::string); + } +SWIGINTERN BytesArray sentencepiece_SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< std::vector< absl::string_view > > const &ins,int num_threads){ + DEFINE_DECODE_BATCH_FUNC_IMPL(DecodePiecesAsSerializedProto, std::string, + sentencepiece::util::bytes); + } +SWIGINTERN std::vector< sentencepiece::ImmutableSentencePieceText > sentencepiece_SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< std::vector< absl::string_view > > const &ins,int num_threads){ + DEFINE_DECODE_BATCH_FUNC_IMPL(DecodePiecesAsImmutableProto, std::string, + sentencepiece::ImmutableSentencePieceText); + } +SWIGINTERN std::vector< std::vector< int > > sentencepiece_SentencePieceProcessor__NBestEncodeAsIds(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int nbest_size,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + auto idss = self->NBestEncodeAsIds(text, nbest_size); + for (auto &ids : idss) { + RewriteIds(*self, &ids, add_bos, add_eos, reverse, emit_unk_piece); + } + return idss; + } +SWIGINTERN std::vector< std::vector< std::string > > sentencepiece_SentencePieceProcessor__NBestEncodeAsPieces(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int nbest_size,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + auto piecess = self->NBestEncodeAsPieces(text, nbest_size); + for (auto &pieces : piecess) { + RewriteIds(*self, &pieces, add_bos, add_eos, reverse, emit_unk_piece); + } + return piecess; + } +SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceProcessor__NBestEncodeAsSerializedProto(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int nbest_size,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + RewriteIds(*self, static_cast(nullptr), + add_bos, add_eos, reverse, emit_unk_piece); + return self->NBestEncodeAsSerializedProto(text, nbest_size); + } +SWIGINTERN sentencepiece::ImmutableNBestSentencePieceText sentencepiece_SentencePieceProcessor__NBestEncodeAsImmutableProto(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int nbest_size,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + RewriteIds(*self, static_cast(nullptr), + add_bos, add_eos, reverse, emit_unk_piece); + auto proto = self->NBestEncodeAsImmutableProto(text, nbest_size); + proto.ConvertToUnicodeSpans(); + return proto; + } +SWIGINTERN std::vector< std::pair< std::vector< int >,float > > sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsIds(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int num_samples,float alpha,bool wor,bool include_best,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + auto idss = self->SampleEncodeAndScoreAsIds(text, num_samples, + alpha, wor, include_best); + for (auto &ids : idss) { + RewriteIds(*self, &ids.first, add_bos, add_eos, reverse, emit_unk_piece); + } + return idss; + } +SWIGINTERN std::vector< std::pair< std::vector< std::string >,float > > sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsPieces(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int num_samples,float alpha,bool wor,bool include_best,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + auto piecess = self->SampleEncodeAndScoreAsPieces(text, num_samples, + alpha, wor, include_best); + for (auto &pieces : piecess) { + RewriteIds(*self, &pieces.first, add_bos, add_eos, reverse, emit_unk_piece); + } + return piecess; + } +SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int num_samples,float alpha,bool wor,bool include_best,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + RewriteIds(*self, static_cast(nullptr), + add_bos, add_eos, reverse, emit_unk_piece); + return self->SampleEncodeAndScoreAsSerializedProto(text, num_samples, + alpha, wor, include_best); + } +SWIGINTERN sentencepiece::ImmutableNBestSentencePieceText sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int num_samples,float alpha,bool wor,bool include_best,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){ + RewriteIds(*self, static_cast(nullptr), + add_bos, add_eos, reverse, emit_unk_piece); + auto proto = self->SampleEncodeAndScoreAsImmutableProto(text, num_samples, + alpha, wor, include_best); + proto.ConvertToUnicodeSpans(); + return proto; + } +SWIGINTERN std::string sentencepiece_SentencePieceProcessor__Normalize(sentencepiece::SentencePieceProcessor *self,absl::string_view text){ + return self->Normalize(text); + } +SWIGINTERN std::pair< std::string,std::vector< size_t > > sentencepiece_SentencePieceProcessor__NormalizeWithOffsets(sentencepiece::SentencePieceProcessor *self,absl::string_view text){ + std::pair> result; + self->Normalize(text, &result.first, &result.second).IgnoreError(); + return result; + } +SWIGINTERN float sentencepiece_SentencePieceProcessor__CalculateEntropy(sentencepiece::SentencePieceProcessor *self,absl::string_view text,float alpha){ + return self->CalculateEntropy(text, alpha); + } +SWIGINTERN std::vector< float > sentencepiece_SentencePieceProcessor__CalculateEntropyBatch(sentencepiece::SentencePieceProcessor *self,std::vector< absl::string_view > const &ins,float alpha,int num_threads){ + std::vector outs(ins.size()); + InitNumThreads(ins, &num_threads); + { + ThreadPool pool(ins.size()); + std::atomic index = 0; + for (int n = 0; n < num_threads; ++n) { + pool.Schedule([&]() { + size_t i = 0; + while ((i = std::atomic_fetch_add(&index, 1)) < outs.size()) { + outs[i] = self->CalculateEntropy(ins[i], alpha); + } + }); + } + } + return outs; + } +SWIGINTERN sentencepiece::util::Status sentencepiece_SentencePieceProcessor__OverrideNormalizerSpec(sentencepiece::SentencePieceProcessor *self,std::unordered_map< std::string,std::string > const &args){ + sentencepiece::util::Status status; + for (const auto &[key, value] : args) { + status = sentencepiece::SentencePieceTrainer::SetProtoField( + key, value, + self->mutable_normalizer_spec()); + if (!status.ok()) return status; + } + return status; + } + +SWIGINTERN int +SWIG_AsVal_unsigned_SS_long (PyObject *obj, unsigned long *val) +{ +#if PY_VERSION_HEX < 0x03000000 + if (PyInt_Check(obj)) { + long v = PyInt_AsLong(obj); + if (v >= 0) { + if (val) *val = v; + return SWIG_OK; + } else { + return SWIG_OverflowError; + } + } else +#endif + if (PyLong_Check(obj)) { + unsigned long v = PyLong_AsUnsignedLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_OK; + } else { + PyErr_Clear(); + return SWIG_OverflowError; + } + } +#ifdef SWIG_PYTHON_CAST_MODE + { + int dispatch = 0; + unsigned long v = PyLong_AsUnsignedLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_AddCast(SWIG_OK); + } else { + PyErr_Clear(); + } + if (!dispatch) { + double d; + int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); + // Largest double not larger than ULONG_MAX (not portably calculated easily) + // Note that double(ULONG_MAX) is stored in a double rounded up by one (for 64-bit unsigned long) + // 0xfffffffffffff800ULL == (uint64_t)std::nextafter(double(__uint128_t(ULONG_MAX)+1), double(0)) + const double ulong_max = sizeof(unsigned long) == 8 ? 0xfffffffffffff800ULL : ULONG_MAX; + if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, 0, ulong_max)) { + if (val) *val = (unsigned long)(d); + return res; + } + } + } +#endif + return SWIG_TypeError; +} + + +SWIGINTERN int +SWIG_AsVal_unsigned_SS_int (PyObject * obj, unsigned int *val) +{ + unsigned long v; + int res = SWIG_AsVal_unsigned_SS_long (obj, &v); + if (SWIG_IsOK(res)) { + if ((v > UINT_MAX)) { + return SWIG_OverflowError; + } else { + if (val) *val = static_cast< unsigned int >(v); + } + } + return res; +} + +SWIGINTERN void sentencepiece_SentencePieceTrainer__TrainFromString(absl::string_view arg){ + const auto _status = sentencepiece::SentencePieceTrainer::Train(arg); + if (!_status.ok()) throw _status; + return; + } +SWIGINTERN void sentencepiece_SentencePieceTrainer__TrainFromMap(std::unordered_map< std::string,std::string > const &args){ + const auto _status = sentencepiece::SentencePieceTrainer::Train(args); + if (!_status.ok()) throw _status; + return; + } +SWIGINTERN void sentencepiece_SentencePieceTrainer__TrainFromMap2(std::unordered_map< std::string,std::string > const &args,sentencepiece::SentenceIterator *iter){ + const auto _status = sentencepiece::SentencePieceTrainer::Train(args, iter); + if (!_status.ok()) throw _status; + return; + } +SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceTrainer__TrainFromMap3(std::unordered_map< std::string,std::string > const &args){ + sentencepiece::util::bytes model_proto; + const auto _status = sentencepiece::SentencePieceTrainer::Train(args, nullptr, &model_proto); + if (!_status.ok()) throw _status; + return model_proto; + } +SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceTrainer__TrainFromMap4(std::unordered_map< std::string,std::string > const &args,sentencepiece::SentenceIterator *iter){ + sentencepiece::util::bytes model_proto; + const auto _status = sentencepiece::SentencePieceTrainer::Train(args, iter, &model_proto); + if (!_status.ok()) throw _status; + return model_proto; + } +SWIGINTERN sentencepiece::util::Status sentencepiece_SentencePieceNormalizer_LoadFromFile(sentencepiece::SentencePieceNormalizer *self,absl::string_view arg){ + return self->Load(arg); + } +SWIGINTERN std::string sentencepiece_SentencePieceNormalizer__Normalize(sentencepiece::SentencePieceNormalizer *self,absl::string_view text){ + std::string result; + const auto _status = self->Normalize(text, &result); + if (!_status.ok()) throw _status; + return result; + } +SWIGINTERN std::pair< std::string,std::vector< size_t > > sentencepiece_SentencePieceNormalizer__NormalizeWithOffsets(sentencepiece::SentencePieceNormalizer *self,absl::string_view text){ + std::pair> result; + const auto _status = self->Normalize(text, &result.first, &result.second); + if (!_status.ok()) throw _status; + return result; + } +SWIGINTERN void sentencepiece_SentencePieceNormalizer__SetProtoField(sentencepiece::SentencePieceNormalizer *self,absl::string_view name,bool value){ + sentencepiece::SentencePieceTrainer::SetProtoField( + name, + value ? "1" : "0", + self->mutable_normalizer_spec()).IgnoreError(); + } +#ifdef __cplusplus +extern "C" { +#endif +SWIGINTERN PyObject *_wrap_new_ImmutableSentencePieceText_ImmutableSentencePiece(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *result = 0 ; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "new_ImmutableSentencePieceText_ImmutableSentencePiece", 0, 0, 0)) SWIG_fail; + { + try { + result = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *)new sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, SWIG_POINTER_NEW | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_delete_ImmutableSentencePieceText_ImmutableSentencePiece(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_ImmutableSentencePieceText_ImmutableSentencePiece" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1); + { + try { + delete arg1; + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_ImmutableSentencePiece__piece(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + std::string *result = 0 ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_ImmutableSentencePiece__piece" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1); + { + try { + result = (std::string *) &((sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *)arg1)->piece(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + resultobj = MakePyOutputString(*result, input_type); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_ImmutableSentencePiece__surface(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + std::string *result = 0 ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_ImmutableSentencePiece__surface" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1); + { + try { + result = (std::string *) &((sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *)arg1)->surface(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + resultobj = MakePyOutputString(*result, input_type); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_ImmutableSentencePiece__id(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + uint32_t result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_ImmutableSentencePiece__id" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1); + { + try { + result = ((sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *)arg1)->id(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_unsigned_SS_int(static_cast< unsigned int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_ImmutableSentencePiece__begin(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + uint32_t result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_ImmutableSentencePiece__begin" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1); + { + try { + result = ((sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *)arg1)->begin(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_unsigned_SS_int(static_cast< unsigned int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_ImmutableSentencePiece__end(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + uint32_t result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_ImmutableSentencePiece__end" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1); + { + try { + result = ((sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *)arg1)->end(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_unsigned_SS_int(static_cast< unsigned int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_ImmutableSentencePiece__surface_as_bytes(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + sentencepiece::util::bytes *result = 0 ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_ImmutableSentencePiece__surface_as_bytes" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1); + { + try { + result = (sentencepiece::util::bytes *) &sentencepiece_ImmutableSentencePieceText_ImmutableSentencePiece__surface_as_bytes((sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *)arg1); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = MakePyOutputBytes(*result); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_ImmutableSentencePiece__piece_as_bytes(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + sentencepiece::util::bytes *result = 0 ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_ImmutableSentencePiece__piece_as_bytes" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1); + { + try { + result = (sentencepiece::util::bytes *) &sentencepiece_ImmutableSentencePieceText_ImmutableSentencePiece__piece_as_bytes((sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *)arg1); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = MakePyOutputBytes(*result); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *ImmutableSentencePieceText_ImmutableSentencePiece_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *obj = NULL; + if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL; + SWIG_TypeNewClientData(SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, SWIG_NewClientData(obj)); + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject *ImmutableSentencePieceText_ImmutableSentencePiece_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + return SWIG_Python_InitShadowInstance(args); +} + +SWIGINTERN PyObject *_wrap_new_ImmutableSentencePieceText(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText *result = 0 ; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "new_ImmutableSentencePieceText", 0, 0, 0)) SWIG_fail; + { + try { + result = (sentencepiece::ImmutableSentencePieceText *)new sentencepiece::ImmutableSentencePieceText(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_NEW | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_delete_ImmutableSentencePieceText(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText *arg1 = (sentencepiece::ImmutableSentencePieceText *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_ImmutableSentencePieceText" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText * >(argp1); + { + try { + delete arg1; + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText__pieces_size(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText *arg1 = (sentencepiece::ImmutableSentencePieceText *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + size_t result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText__pieces_size" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText * >(argp1); + { + try { + result = ((sentencepiece::ImmutableSentencePieceText const *)arg1)->pieces_size(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_size_t(static_cast< size_t >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText__pieces(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText *arg1 = (sentencepiece::ImmutableSentencePieceText *) 0 ; + int arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "ImmutableSentencePieceText__pieces", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText__pieces" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText * >(argp1); + ecode2 = SWIG_AsVal_int(swig_obj[1], &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ImmutableSentencePieceText__pieces" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + try { + result = ((sentencepiece::ImmutableSentencePieceText const *)arg1)->pieces(arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_NewPointerObj((new sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece(result)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, SWIG_POINTER_OWN | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText__text(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText *arg1 = (sentencepiece::ImmutableSentencePieceText *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + std::string *result = 0 ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText__text" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText * >(argp1); + { + try { + result = (std::string *) &((sentencepiece::ImmutableSentencePieceText const *)arg1)->text(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + resultobj = MakePyOutputString(*result, input_type); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText__score(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText *arg1 = (sentencepiece::ImmutableSentencePieceText *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + float result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText__score" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText * >(argp1); + { + try { + result = (float)((sentencepiece::ImmutableSentencePieceText const *)arg1)->score(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_float(static_cast< float >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_SerializeAsString(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText *arg1 = (sentencepiece::ImmutableSentencePieceText *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + sentencepiece::util::bytes result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_SerializeAsString" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText * >(argp1); + { + try { + result = ((sentencepiece::ImmutableSentencePieceText const *)arg1)->SerializeAsString(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = MakePyOutputBytes(result); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText__text_as_bytes(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableSentencePieceText *arg1 = (sentencepiece::ImmutableSentencePieceText *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + sentencepiece::util::bytes *result = 0 ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText__text_as_bytes" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText * >(argp1); + { + try { + result = (sentencepiece::util::bytes *) &sentencepiece_ImmutableSentencePieceText__text_as_bytes((sentencepiece::ImmutableSentencePieceText const *)arg1); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = MakePyOutputBytes(*result); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *ImmutableSentencePieceText_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *obj = NULL; + if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL; + SWIG_TypeNewClientData(SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_NewClientData(obj)); + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject *ImmutableSentencePieceText_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + return SWIG_Python_InitShadowInstance(args); +} + +SWIGINTERN PyObject *_wrap_new_ImmutableNBestSentencePieceText(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableNBestSentencePieceText *result = 0 ; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "new_ImmutableNBestSentencePieceText", 0, 0, 0)) SWIG_fail; + { + try { + result = (sentencepiece::ImmutableNBestSentencePieceText *)new sentencepiece::ImmutableNBestSentencePieceText(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, SWIG_POINTER_NEW | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_delete_ImmutableNBestSentencePieceText(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableNBestSentencePieceText *arg1 = (sentencepiece::ImmutableNBestSentencePieceText *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_ImmutableNBestSentencePieceText" "', argument " "1"" of type '" "sentencepiece::ImmutableNBestSentencePieceText *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableNBestSentencePieceText * >(argp1); + { + try { + delete arg1; + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableNBestSentencePieceText__nbests_size(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableNBestSentencePieceText *arg1 = (sentencepiece::ImmutableNBestSentencePieceText *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + size_t result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableNBestSentencePieceText__nbests_size" "', argument " "1"" of type '" "sentencepiece::ImmutableNBestSentencePieceText const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableNBestSentencePieceText * >(argp1); + { + try { + result = ((sentencepiece::ImmutableNBestSentencePieceText const *)arg1)->nbests_size(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_size_t(static_cast< size_t >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableNBestSentencePieceText__nbests(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableNBestSentencePieceText *arg1 = (sentencepiece::ImmutableNBestSentencePieceText *) 0 ; + int arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::ImmutableSentencePieceText result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "ImmutableNBestSentencePieceText__nbests", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableNBestSentencePieceText__nbests" "', argument " "1"" of type '" "sentencepiece::ImmutableNBestSentencePieceText const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableNBestSentencePieceText * >(argp1); + ecode2 = SWIG_AsVal_int(swig_obj[1], &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ImmutableNBestSentencePieceText__nbests" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + try { + result = ((sentencepiece::ImmutableNBestSentencePieceText const *)arg1)->nbests(arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_NewPointerObj((new sentencepiece::ImmutableSentencePieceText(result)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ImmutableNBestSentencePieceText_SerializeAsString(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::ImmutableNBestSentencePieceText *arg1 = (sentencepiece::ImmutableNBestSentencePieceText *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + sentencepiece::util::bytes result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableNBestSentencePieceText_SerializeAsString" "', argument " "1"" of type '" "sentencepiece::ImmutableNBestSentencePieceText const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::ImmutableNBestSentencePieceText * >(argp1); + { + try { + result = ((sentencepiece::ImmutableNBestSentencePieceText const *)arg1)->SerializeAsString(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = MakePyOutputBytes(result); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *ImmutableNBestSentencePieceText_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *obj = NULL; + if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL; + SWIG_TypeNewClientData(SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, SWIG_NewClientData(obj)); + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject *ImmutableNBestSentencePieceText_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + return SWIG_Python_InitShadowInstance(args); +} + +SWIGINTERN PyObject *_wrap_new_SentencePieceProcessor(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *result = 0 ; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "new_SentencePieceProcessor", 0, 0, 0)) SWIG_fail; + { + try { + result = (sentencepiece::SentencePieceProcessor *)new sentencepiece::SentencePieceProcessor(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_sentencepiece__SentencePieceProcessor, SWIG_POINTER_NEW | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_delete_SentencePieceProcessor(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_SentencePieceProcessor" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + try { + delete arg1; + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_LoadFromSerializedProto(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::util::Status result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_LoadFromSerializedProto", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_LoadFromSerializedProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + { + try { + result = (arg1)->LoadFromSerializedProto(SWIG_STD_MOVE(arg2)); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + if (!(&result)->ok()) { + SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str()); + } + resultobj = SWIG_From_bool((&result)->ok()); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_SetEncodeExtraOptions(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::util::Status result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_SetEncodeExtraOptions", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_SetEncodeExtraOptions" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + { + try { + result = (arg1)->SetEncodeExtraOptions(SWIG_STD_MOVE(arg2)); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + if (!(&result)->ok()) { + SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str()); + } + resultobj = SWIG_From_bool((&result)->ok()); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_SetDecodeExtraOptions(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::util::Status result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_SetDecodeExtraOptions", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_SetDecodeExtraOptions" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + { + try { + result = (arg1)->SetDecodeExtraOptions(SWIG_STD_MOVE(arg2)); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + if (!(&result)->ok()) { + SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str()); + } + resultobj = SWIG_From_bool((&result)->ok()); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_SetVocabulary(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< absl::string_view > *arg2 = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::util::Status result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_SetVocabulary", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_SetVocabulary" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector(size); + for (size_t i = 0; i < size; ++i) { + const PyInputString ustring(PyList_GetItem(swig_obj[1], i)); + if (ustring.IsAvalable()) { + (*out)[i] = ustring.str(); + } else { + PyErr_SetString(PyExc_TypeError, "list must contain strings"); + SWIG_fail; + } + resultobj = ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a list"); + SWIG_fail; + } + arg2 = out; + } + { + try { + result = (arg1)->SetVocabulary((std::vector< absl::string_view > const &)*arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + if (!(&result)->ok()) { + SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str()); + } + resultobj = SWIG_From_bool((&result)->ok()); + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_ResetVocabulary(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + sentencepiece::util::Status result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_ResetVocabulary" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + try { + result = (arg1)->ResetVocabulary(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + if (!(&result)->ok()) { + SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str()); + } + resultobj = SWIG_From_bool((&result)->ok()); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_LoadVocabulary(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + int arg3 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyObject *swig_obj[3] ; + sentencepiece::util::Status result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_LoadVocabulary", 3, 3, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_LoadVocabulary" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor_LoadVocabulary" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + try { + result = (arg1)->LoadVocabulary(SWIG_STD_MOVE(arg2),arg3); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + if (!(&result)->ok()) { + SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str()); + } + resultobj = SWIG_From_bool((&result)->ok()); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_CalculateEntropy__SWIG_0(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + float arg3 ; + float *arg4 = (float *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + float val3 ; + int ecode3 = 0 ; + void *argp4 = 0 ; + int res4 = 0 ; + sentencepiece::util::Status result; + + (void)self; + if ((nobjs < 4) || (nobjs > 4)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_CalculateEntropy" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_float(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor_CalculateEntropy" "', argument " "3"" of type '" "float""'"); + } + arg3 = static_cast< float >(val3); + res4 = SWIG_ConvertPtr(swig_obj[3], &argp4,SWIGTYPE_p_float, 0 | 0 ); + if (!SWIG_IsOK(res4)) { + SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "SentencePieceProcessor_CalculateEntropy" "', argument " "4"" of type '" "float *""'"); + } + arg4 = reinterpret_cast< float * >(argp4); + { + try { + result = ((sentencepiece::SentencePieceProcessor const *)arg1)->CalculateEntropy(SWIG_STD_MOVE(arg2),arg3,arg4); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + if (!(&result)->ok()) { + SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str()); + } + resultobj = SWIG_From_bool((&result)->ok()); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_CalculateEntropy__SWIG_1(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + float arg3 ; + void *argp1 = 0 ; + int res1 = 0 ; + float val3 ; + int ecode3 = 0 ; + float result; + + (void)self; + if ((nobjs < 3) || (nobjs > 3)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_CalculateEntropy" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_float(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor_CalculateEntropy" "', argument " "3"" of type '" "float""'"); + } + arg3 = static_cast< float >(val3); + { + try { + result = (float)((sentencepiece::SentencePieceProcessor const *)arg1)->CalculateEntropy(SWIG_STD_MOVE(arg2),arg3); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_float(static_cast< float >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_CalculateEntropy(PyObject *self, PyObject *args) { + Py_ssize_t argc; + PyObject *argv[5] = { + 0 + }; + + if (!(argc = SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_CalculateEntropy", 0, 4, argv))) SWIG_fail; + --argc; + if (argc == 3) { + int _v = 0; + void *vptr = 0; + int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0); + _v = SWIG_CheckState(res); + if (_v) { + int res = SWIG_AsCharPtrAndSize(argv[1], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + { + int res = SWIG_AsVal_float(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + return _wrap_SentencePieceProcessor_CalculateEntropy__SWIG_1(self, argc, argv); + } + } + } + } + if (argc == 4) { + int _v = 0; + void *vptr = 0; + int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0); + _v = SWIG_CheckState(res); + if (_v) { + int res = SWIG_AsCharPtrAndSize(argv[1], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + { + int res = SWIG_AsVal_float(argv[2], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + void *vptr = 0; + int res = SWIG_ConvertPtr(argv[3], &vptr, SWIGTYPE_p_float, 0); + _v = SWIG_CheckState(res); + if (_v) { + return _wrap_SentencePieceProcessor_CalculateEntropy__SWIG_0(self, argc, argv); + } + } + } + } + } + +fail: + SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function 'SentencePieceProcessor_CalculateEntropy'.\n" + " Possible C/C++ prototypes are:\n" + " sentencepiece::SentencePieceProcessor::CalculateEntropy(absl::string_view,float,float *) const\n" + " sentencepiece::SentencePieceProcessor::CalculateEntropy(absl::string_view,float) const\n"); + return 0; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_GetPieceSize(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + int result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_GetPieceSize" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + try { + result = (int)((sentencepiece::SentencePieceProcessor const *)arg1)->GetPieceSize(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_int(static_cast< int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_PieceToId(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + int result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_PieceToId", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_PieceToId" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + { + try { + result = (int)((sentencepiece::SentencePieceProcessor const *)arg1)->PieceToId(SWIG_STD_MOVE(arg2)); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_int(static_cast< int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_IdToPiece(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + int arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject *swig_obj[2] ; + std::string *result = 0 ; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_IdToPiece", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_IdToPiece" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + ecode2 = SWIG_AsVal_int(swig_obj[1], &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "SentencePieceProcessor_IdToPiece" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + try { + result = (std::string *) &((sentencepiece::SentencePieceProcessor const *)arg1)->IdToPiece(arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + resultobj = MakePyOutputString(*result, input_type); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_GetScore(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + int arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject *swig_obj[2] ; + float result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_GetScore", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_GetScore" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + ecode2 = SWIG_AsVal_int(swig_obj[1], &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "SentencePieceProcessor_GetScore" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + try { + result = (float)((sentencepiece::SentencePieceProcessor const *)arg1)->GetScore(arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_float(static_cast< float >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_IsUnknown(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + int arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject *swig_obj[2] ; + bool result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_IsUnknown", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_IsUnknown" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + ecode2 = SWIG_AsVal_int(swig_obj[1], &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "SentencePieceProcessor_IsUnknown" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + try { + result = (bool)((sentencepiece::SentencePieceProcessor const *)arg1)->IsUnknown(arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_bool(static_cast< bool >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_IsControl(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + int arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject *swig_obj[2] ; + bool result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_IsControl", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_IsControl" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + ecode2 = SWIG_AsVal_int(swig_obj[1], &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "SentencePieceProcessor_IsControl" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + try { + result = (bool)((sentencepiece::SentencePieceProcessor const *)arg1)->IsControl(arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_bool(static_cast< bool >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_IsUnused(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + int arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject *swig_obj[2] ; + bool result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_IsUnused", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_IsUnused" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + ecode2 = SWIG_AsVal_int(swig_obj[1], &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "SentencePieceProcessor_IsUnused" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + try { + result = (bool)((sentencepiece::SentencePieceProcessor const *)arg1)->IsUnused(arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_bool(static_cast< bool >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_IsByte(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + int arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject *swig_obj[2] ; + bool result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_IsByte", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_IsByte" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + ecode2 = SWIG_AsVal_int(swig_obj[1], &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "SentencePieceProcessor_IsByte" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + try { + result = (bool)((sentencepiece::SentencePieceProcessor const *)arg1)->IsByte(arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_bool(static_cast< bool >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_unk_id(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + int result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_unk_id" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + try { + result = (int)((sentencepiece::SentencePieceProcessor const *)arg1)->unk_id(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_int(static_cast< int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_bos_id(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + int result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_bos_id" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + try { + result = (int)((sentencepiece::SentencePieceProcessor const *)arg1)->bos_id(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_int(static_cast< int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_eos_id(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + int result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_eos_id" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + try { + result = (int)((sentencepiece::SentencePieceProcessor const *)arg1)->eos_id(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_int(static_cast< int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_pad_id(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + int result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_pad_id" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + try { + result = (int)((sentencepiece::SentencePieceProcessor const *)arg1)->pad_id(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_int(static_cast< int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_serialized_model_proto(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + sentencepiece::util::bytes result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_serialized_model_proto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + try { + result = ((sentencepiece::SentencePieceProcessor const *)arg1)->serialized_model_proto(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = MakePyOutputBytes(result); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor_LoadFromFile(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::util::Status result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_LoadFromFile", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_LoadFromFile" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + { + try { + result = sentencepiece_SentencePieceProcessor_LoadFromFile(arg1,SWIG_STD_MOVE(arg2)); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + if (!(&result)->ok()) { + SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str()); + } + resultobj = SWIG_From_bool((&result)->ok()); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsIds(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + bool arg3 ; + int arg4 ; + float arg5 ; + bool arg6 ; + bool arg7 ; + bool arg8 ; + bool arg9 ; + void *argp1 = 0 ; + int res1 = 0 ; + bool val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + float val5 ; + int ecode5 = 0 ; + bool val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + bool val8 ; + int ecode8 = 0 ; + bool val9 ; + int ecode9 = 0 ; + PyObject *swig_obj[9] ; + std::vector< int > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsIds", 9, 9, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_bool(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "3"" of type '" "bool""'"); + } + arg3 = static_cast< bool >(val3); + ecode4 = SWIG_AsVal_int(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + ecode5 = SWIG_AsVal_float(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "5"" of type '" "float""'"); + } + arg5 = static_cast< float >(val5); + ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "6"" of type '" "bool""'"); + } + arg6 = static_cast< bool >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "8"" of type '" "bool""'"); + } + arg8 = static_cast< bool >(val8); + ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9); + if (!SWIG_IsOK(ecode9)) { + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "9"" of type '" "bool""'"); + } + arg9 = static_cast< bool >(val9); + { + try { + result = sentencepiece_SentencePieceProcessor__EncodeAsIds((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyList_SET_ITEM(resultobj, i, PyInt_FromLong(static_cast(result[i]))); + } + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsPieces(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + bool arg3 ; + int arg4 ; + float arg5 ; + bool arg6 ; + bool arg7 ; + bool arg8 ; + bool arg9 ; + void *argp1 = 0 ; + int res1 = 0 ; + bool val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + float val5 ; + int ecode5 = 0 ; + bool val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + bool val8 ; + int ecode8 = 0 ; + bool val9 ; + int ecode9 = 0 ; + PyObject *swig_obj[9] ; + std::vector< std::string > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsPieces", 9, 9, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_bool(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "3"" of type '" "bool""'"); + } + arg3 = static_cast< bool >(val3); + ecode4 = SWIG_AsVal_int(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + ecode5 = SWIG_AsVal_float(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "5"" of type '" "float""'"); + } + arg5 = static_cast< float >(val5); + ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "6"" of type '" "bool""'"); + } + arg6 = static_cast< bool >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "8"" of type '" "bool""'"); + } + arg8 = static_cast< bool >(val8); + ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9); + if (!SWIG_IsOK(ecode9)) { + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "9"" of type '" "bool""'"); + } + arg9 = static_cast< bool >(val9); + { + try { + result = sentencepiece_SentencePieceProcessor__EncodeAsPieces((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyList_SET_ITEM(resultobj, i, MakePyOutputString(result[i], input_type)); + } + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsSerializedProto(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + bool arg3 ; + int arg4 ; + float arg5 ; + bool arg6 ; + bool arg7 ; + bool arg8 ; + bool arg9 ; + void *argp1 = 0 ; + int res1 = 0 ; + bool val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + float val5 ; + int ecode5 = 0 ; + bool val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + bool val8 ; + int ecode8 = 0 ; + bool val9 ; + int ecode9 = 0 ; + PyObject *swig_obj[9] ; + sentencepiece::util::bytes result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsSerializedProto", 9, 9, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_bool(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "3"" of type '" "bool""'"); + } + arg3 = static_cast< bool >(val3); + ecode4 = SWIG_AsVal_int(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + ecode5 = SWIG_AsVal_float(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "5"" of type '" "float""'"); + } + arg5 = static_cast< float >(val5); + ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "6"" of type '" "bool""'"); + } + arg6 = static_cast< bool >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "8"" of type '" "bool""'"); + } + arg8 = static_cast< bool >(val8); + ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9); + if (!SWIG_IsOK(ecode9)) { + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "9"" of type '" "bool""'"); + } + arg9 = static_cast< bool >(val9); + { + try { + result = sentencepiece_SentencePieceProcessor__EncodeAsSerializedProto((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = MakePyOutputBytes(result); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsImmutableProto(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + bool arg3 ; + int arg4 ; + float arg5 ; + bool arg6 ; + bool arg7 ; + bool arg8 ; + bool arg9 ; + void *argp1 = 0 ; + int res1 = 0 ; + bool val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + float val5 ; + int ecode5 = 0 ; + bool val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + bool val8 ; + int ecode8 = 0 ; + bool val9 ; + int ecode9 = 0 ; + PyObject *swig_obj[9] ; + sentencepiece::ImmutableSentencePieceText result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsImmutableProto", 9, 9, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_bool(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "3"" of type '" "bool""'"); + } + arg3 = static_cast< bool >(val3); + ecode4 = SWIG_AsVal_int(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + ecode5 = SWIG_AsVal_float(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "5"" of type '" "float""'"); + } + arg5 = static_cast< float >(val5); + ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "6"" of type '" "bool""'"); + } + arg6 = static_cast< bool >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "8"" of type '" "bool""'"); + } + arg8 = static_cast< bool >(val8); + ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9); + if (!SWIG_IsOK(ecode9)) { + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "9"" of type '" "bool""'"); + } + arg9 = static_cast< bool >(val9); + { + try { + result = sentencepiece_SentencePieceProcessor__EncodeAsImmutableProto((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_NewPointerObj((new sentencepiece::ImmutableSentencePieceText(result)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsIdsBatch(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< absl::string_view > *arg2 = 0 ; + int arg3 ; + bool arg4 ; + int arg5 ; + float arg6 ; + bool arg7 ; + bool arg8 ; + bool arg9 ; + bool arg10 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + bool val4 ; + int ecode4 = 0 ; + int val5 ; + int ecode5 = 0 ; + float val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + bool val8 ; + int ecode8 = 0 ; + bool val9 ; + int ecode9 = 0 ; + bool val10 ; + int ecode10 = 0 ; + PyObject *swig_obj[10] ; + std::vector< std::vector< int > > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsIdsBatch", 10, 10, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector(size); + for (size_t i = 0; i < size; ++i) { + const PyInputString ustring(PyList_GetItem(swig_obj[1], i)); + if (ustring.IsAvalable()) { + (*out)[i] = ustring.str(); + } else { + PyErr_SetString(PyExc_TypeError, "list must contain strings"); + SWIG_fail; + } + resultobj = ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a list"); + SWIG_fail; + } + arg2 = out; + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "4"" of type '" "bool""'"); + } + arg4 = static_cast< bool >(val4); + ecode5 = SWIG_AsVal_int(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "5"" of type '" "int""'"); + } + arg5 = static_cast< int >(val5); + ecode6 = SWIG_AsVal_float(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "6"" of type '" "float""'"); + } + arg6 = static_cast< float >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "8"" of type '" "bool""'"); + } + arg8 = static_cast< bool >(val8); + ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9); + if (!SWIG_IsOK(ecode9)) { + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "9"" of type '" "bool""'"); + } + arg9 = static_cast< bool >(val9); + ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10); + if (!SWIG_IsOK(ecode10)) { + SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "10"" of type '" "bool""'"); + } + arg10 = static_cast< bool >(val10); + { + try { + result = sentencepiece_SentencePieceProcessor__EncodeAsIdsBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< absl::string_view > const &)*arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyObject *obj = PyList_New(result[i].size()); + for (size_t j = 0; j < result[i].size(); ++j) { + PyList_SET_ITEM(obj, j, PyInt_FromLong(static_cast(result[i][j]))); + } + PyList_SET_ITEM(resultobj, i, obj); + } + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsPiecesBatch(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< absl::string_view > *arg2 = 0 ; + int arg3 ; + bool arg4 ; + int arg5 ; + float arg6 ; + bool arg7 ; + bool arg8 ; + bool arg9 ; + bool arg10 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + bool val4 ; + int ecode4 = 0 ; + int val5 ; + int ecode5 = 0 ; + float val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + bool val8 ; + int ecode8 = 0 ; + bool val9 ; + int ecode9 = 0 ; + bool val10 ; + int ecode10 = 0 ; + PyObject *swig_obj[10] ; + std::vector< std::vector< std::string > > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsPiecesBatch", 10, 10, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector(size); + for (size_t i = 0; i < size; ++i) { + const PyInputString ustring(PyList_GetItem(swig_obj[1], i)); + if (ustring.IsAvalable()) { + (*out)[i] = ustring.str(); + } else { + PyErr_SetString(PyExc_TypeError, "list must contain strings"); + SWIG_fail; + } + resultobj = ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a list"); + SWIG_fail; + } + arg2 = out; + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "4"" of type '" "bool""'"); + } + arg4 = static_cast< bool >(val4); + ecode5 = SWIG_AsVal_int(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "5"" of type '" "int""'"); + } + arg5 = static_cast< int >(val5); + ecode6 = SWIG_AsVal_float(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "6"" of type '" "float""'"); + } + arg6 = static_cast< float >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "8"" of type '" "bool""'"); + } + arg8 = static_cast< bool >(val8); + ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9); + if (!SWIG_IsOK(ecode9)) { + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "9"" of type '" "bool""'"); + } + arg9 = static_cast< bool >(val9); + ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10); + if (!SWIG_IsOK(ecode10)) { + SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "10"" of type '" "bool""'"); + } + arg10 = static_cast< bool >(val10); + { + try { + result = sentencepiece_SentencePieceProcessor__EncodeAsPiecesBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< absl::string_view > const &)*arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyObject *obj = PyList_New(result[i].size()); + for (size_t j = 0; j < result[i].size(); ++j) { + PyList_SET_ITEM(obj, j, MakePyOutputString(result[i][j], input_type)); + } + PyList_SET_ITEM(resultobj, i, obj); + } + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsSerializedProtoBatch(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< absl::string_view > *arg2 = 0 ; + int arg3 ; + bool arg4 ; + int arg5 ; + float arg6 ; + bool arg7 ; + bool arg8 ; + bool arg9 ; + bool arg10 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + bool val4 ; + int ecode4 = 0 ; + int val5 ; + int ecode5 = 0 ; + float val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + bool val8 ; + int ecode8 = 0 ; + bool val9 ; + int ecode9 = 0 ; + bool val10 ; + int ecode10 = 0 ; + PyObject *swig_obj[10] ; + BytesArray result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsSerializedProtoBatch", 10, 10, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector(size); + for (size_t i = 0; i < size; ++i) { + const PyInputString ustring(PyList_GetItem(swig_obj[1], i)); + if (ustring.IsAvalable()) { + (*out)[i] = ustring.str(); + } else { + PyErr_SetString(PyExc_TypeError, "list must contain strings"); + SWIG_fail; + } + resultobj = ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a list"); + SWIG_fail; + } + arg2 = out; + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "4"" of type '" "bool""'"); + } + arg4 = static_cast< bool >(val4); + ecode5 = SWIG_AsVal_int(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "5"" of type '" "int""'"); + } + arg5 = static_cast< int >(val5); + ecode6 = SWIG_AsVal_float(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "6"" of type '" "float""'"); + } + arg6 = static_cast< float >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "8"" of type '" "bool""'"); + } + arg8 = static_cast< bool >(val8); + ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9); + if (!SWIG_IsOK(ecode9)) { + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "9"" of type '" "bool""'"); + } + arg9 = static_cast< bool >(val9); + ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10); + if (!SWIG_IsOK(ecode10)) { + SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "10"" of type '" "bool""'"); + } + arg10 = static_cast< bool >(val10); + { + try { + result = sentencepiece_SentencePieceProcessor__EncodeAsSerializedProtoBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< absl::string_view > const &)*arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyList_SET_ITEM(resultobj, i, MakePyOutputBytes(result[i])); + } + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsImmutableProtoBatch(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< absl::string_view > *arg2 = 0 ; + int arg3 ; + bool arg4 ; + int arg5 ; + float arg6 ; + bool arg7 ; + bool arg8 ; + bool arg9 ; + bool arg10 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + bool val4 ; + int ecode4 = 0 ; + int val5 ; + int ecode5 = 0 ; + float val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + bool val8 ; + int ecode8 = 0 ; + bool val9 ; + int ecode9 = 0 ; + bool val10 ; + int ecode10 = 0 ; + PyObject *swig_obj[10] ; + SwigValueWrapper< std::vector< sentencepiece::ImmutableSentencePieceText > > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsImmutableProtoBatch", 10, 10, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector(size); + for (size_t i = 0; i < size; ++i) { + const PyInputString ustring(PyList_GetItem(swig_obj[1], i)); + if (ustring.IsAvalable()) { + (*out)[i] = ustring.str(); + } else { + PyErr_SetString(PyExc_TypeError, "list must contain strings"); + SWIG_fail; + } + resultobj = ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a list"); + SWIG_fail; + } + arg2 = out; + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "4"" of type '" "bool""'"); + } + arg4 = static_cast< bool >(val4); + ecode5 = SWIG_AsVal_int(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "5"" of type '" "int""'"); + } + arg5 = static_cast< int >(val5); + ecode6 = SWIG_AsVal_float(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "6"" of type '" "float""'"); + } + arg6 = static_cast< float >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "8"" of type '" "bool""'"); + } + arg8 = static_cast< bool >(val8); + ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9); + if (!SWIG_IsOK(ecode9)) { + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "9"" of type '" "bool""'"); + } + arg9 = static_cast< bool >(val9); + ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10); + if (!SWIG_IsOK(ecode10)) { + SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "10"" of type '" "bool""'"); + } + arg10 = static_cast< bool >(val10); + { + try { + result = sentencepiece_SentencePieceProcessor__EncodeAsImmutableProtoBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< absl::string_view > const &)*arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyObject *obj = SWIG_NewPointerObj(new sentencepiece::ImmutableSentencePieceText((&result)->at(i)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN | 0); + PyList_SET_ITEM(resultobj, i, obj); + } + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIds(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< int > *arg2 = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + std::string result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIds", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIds" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector(size); + for (size_t i = 0; i < size; ++i) { + PyObject *o = PyList_GetItem(swig_obj[1], i); + if (PyInt_Check(o)) { + (*out)[i] = static_cast(PyInt_AsLong(o)); + } else { + PyErr_SetString(PyExc_TypeError,"list must contain integers"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + arg2 = out; + } + { + try { + result = sentencepiece_SentencePieceProcessor__DecodeIds((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< int > const &)*arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + resultobj = MakePyOutputString(result, input_type); + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIdsAsBytes(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< int > *arg2 = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::util::bytes result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIdsAsBytes", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIdsAsBytes" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector(size); + for (size_t i = 0; i < size; ++i) { + PyObject *o = PyList_GetItem(swig_obj[1], i); + if (PyInt_Check(o)) { + (*out)[i] = static_cast(PyInt_AsLong(o)); + } else { + PyErr_SetString(PyExc_TypeError,"list must contain integers"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + arg2 = out; + } + { + try { + result = sentencepiece_SentencePieceProcessor__DecodeIdsAsBytes((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< int > const &)*arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = MakePyOutputBytes(result); + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodePieces(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< absl::string_view > *arg2 = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + std::string result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodePieces", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodePieces" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector(size); + for (size_t i = 0; i < size; ++i) { + const PyInputString ustring(PyList_GetItem(swig_obj[1], i)); + if (ustring.IsAvalable()) { + (*out)[i] = ustring.str(); + } else { + PyErr_SetString(PyExc_TypeError, "list must contain strings"); + SWIG_fail; + } + resultobj = ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a list"); + SWIG_fail; + } + arg2 = out; + } + { + try { + result = sentencepiece_SentencePieceProcessor__DecodePieces((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< absl::string_view > const &)*arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + resultobj = MakePyOutputString(result, input_type); + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIdsAsSerializedProto(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< int > *arg2 = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::util::bytes result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIdsAsSerializedProto", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIdsAsSerializedProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector(size); + for (size_t i = 0; i < size; ++i) { + PyObject *o = PyList_GetItem(swig_obj[1], i); + if (PyInt_Check(o)) { + (*out)[i] = static_cast(PyInt_AsLong(o)); + } else { + PyErr_SetString(PyExc_TypeError,"list must contain integers"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + arg2 = out; + } + { + try { + result = sentencepiece_SentencePieceProcessor__DecodeIdsAsSerializedProto((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< int > const &)*arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = MakePyOutputBytes(result); + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodePiecesAsSerializedProto(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< absl::string_view > *arg2 = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::util::bytes result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodePiecesAsSerializedProto", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodePiecesAsSerializedProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector(size); + for (size_t i = 0; i < size; ++i) { + const PyInputString ustring(PyList_GetItem(swig_obj[1], i)); + if (ustring.IsAvalable()) { + (*out)[i] = ustring.str(); + } else { + PyErr_SetString(PyExc_TypeError, "list must contain strings"); + SWIG_fail; + } + resultobj = ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a list"); + SWIG_fail; + } + arg2 = out; + } + { + try { + result = sentencepiece_SentencePieceProcessor__DecodePiecesAsSerializedProto((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< absl::string_view > const &)*arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = MakePyOutputBytes(result); + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIdsAsImmutableProto(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< int > *arg2 = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::ImmutableSentencePieceText result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIdsAsImmutableProto", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIdsAsImmutableProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector(size); + for (size_t i = 0; i < size; ++i) { + PyObject *o = PyList_GetItem(swig_obj[1], i); + if (PyInt_Check(o)) { + (*out)[i] = static_cast(PyInt_AsLong(o)); + } else { + PyErr_SetString(PyExc_TypeError,"list must contain integers"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + arg2 = out; + } + { + try { + result = sentencepiece_SentencePieceProcessor__DecodeIdsAsImmutableProto((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< int > const &)*arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_NewPointerObj((new sentencepiece::ImmutableSentencePieceText(result)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN | 0 ); + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodePiecesAsImmutableProto(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< absl::string_view > *arg2 = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::ImmutableSentencePieceText result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodePiecesAsImmutableProto", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodePiecesAsImmutableProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector(size); + for (size_t i = 0; i < size; ++i) { + const PyInputString ustring(PyList_GetItem(swig_obj[1], i)); + if (ustring.IsAvalable()) { + (*out)[i] = ustring.str(); + } else { + PyErr_SetString(PyExc_TypeError, "list must contain strings"); + SWIG_fail; + } + resultobj = ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a list"); + SWIG_fail; + } + arg2 = out; + } + { + try { + result = sentencepiece_SentencePieceProcessor__DecodePiecesAsImmutableProto((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< absl::string_view > const &)*arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_NewPointerObj((new sentencepiece::ImmutableSentencePieceText(result)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN | 0 ); + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIdsBatch(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< std::vector< int > > *arg2 = 0 ; + int arg3 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyObject *swig_obj[3] ; + std::vector< std::string > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIdsBatch", 3, 3, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIdsBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector> *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector>(size); + for (size_t i = 0; i < size; ++i) { + PyObject *o = PyList_GetItem(swig_obj[1], i); + if (PyList_Check(o)) { + const size_t size2 = PyList_Size(o); + (*out)[i].resize(size2); + for (size_t j = 0; j < size2; ++j) { + PyObject *o2 = PyList_GetItem(o, j); + if (PyInt_Check(o2)) { + (*out)[i][j] = static_cast(PyInt_AsLong(o2)); + } else { + PyErr_SetString(PyExc_TypeError, "list must contain strings"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError, "not a list"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + arg2 = out; + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__DecodeIdsBatch" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + try { + result = sentencepiece_SentencePieceProcessor__DecodeIdsBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< std::vector< int > > const &)*arg2,arg3); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyList_SET_ITEM(resultobj, i, MakePyOutputString(result[i], input_type)); + } + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIdsAsBytesBatch(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< std::vector< int > > *arg2 = 0 ; + int arg3 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyObject *swig_obj[3] ; + BytesArray result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIdsAsBytesBatch", 3, 3, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIdsAsBytesBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector> *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector>(size); + for (size_t i = 0; i < size; ++i) { + PyObject *o = PyList_GetItem(swig_obj[1], i); + if (PyList_Check(o)) { + const size_t size2 = PyList_Size(o); + (*out)[i].resize(size2); + for (size_t j = 0; j < size2; ++j) { + PyObject *o2 = PyList_GetItem(o, j); + if (PyInt_Check(o2)) { + (*out)[i][j] = static_cast(PyInt_AsLong(o2)); + } else { + PyErr_SetString(PyExc_TypeError, "list must contain strings"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError, "not a list"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + arg2 = out; + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__DecodeIdsAsBytesBatch" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + try { + result = sentencepiece_SentencePieceProcessor__DecodeIdsAsBytesBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< std::vector< int > > const &)*arg2,arg3); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyList_SET_ITEM(resultobj, i, MakePyOutputBytes(result[i])); + } + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< std::vector< int > > *arg2 = 0 ; + int arg3 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyObject *swig_obj[3] ; + BytesArray result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch", 3, 3, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector> *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector>(size); + for (size_t i = 0; i < size; ++i) { + PyObject *o = PyList_GetItem(swig_obj[1], i); + if (PyList_Check(o)) { + const size_t size2 = PyList_Size(o); + (*out)[i].resize(size2); + for (size_t j = 0; j < size2; ++j) { + PyObject *o2 = PyList_GetItem(o, j); + if (PyInt_Check(o2)) { + (*out)[i][j] = static_cast(PyInt_AsLong(o2)); + } else { + PyErr_SetString(PyExc_TypeError, "list must contain strings"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError, "not a list"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + arg2 = out; + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + try { + result = sentencepiece_SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< std::vector< int > > const &)*arg2,arg3); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyList_SET_ITEM(resultobj, i, MakePyOutputBytes(result[i])); + } + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< std::vector< int > > *arg2 = 0 ; + int arg3 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyObject *swig_obj[3] ; + SwigValueWrapper< std::vector< sentencepiece::ImmutableSentencePieceText > > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch", 3, 3, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector> *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector>(size); + for (size_t i = 0; i < size; ++i) { + PyObject *o = PyList_GetItem(swig_obj[1], i); + if (PyList_Check(o)) { + const size_t size2 = PyList_Size(o); + (*out)[i].resize(size2); + for (size_t j = 0; j < size2; ++j) { + PyObject *o2 = PyList_GetItem(o, j); + if (PyInt_Check(o2)) { + (*out)[i][j] = static_cast(PyInt_AsLong(o2)); + } else { + PyErr_SetString(PyExc_TypeError, "list must contain strings"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError, "not a list"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + arg2 = out; + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + try { + result = sentencepiece_SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< std::vector< int > > const &)*arg2,arg3); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyObject *obj = SWIG_NewPointerObj(new sentencepiece::ImmutableSentencePieceText((&result)->at(i)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN | 0); + PyList_SET_ITEM(resultobj, i, obj); + } + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodePiecesBatch(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< std::vector< absl::string_view > > *arg2 = 0 ; + int arg3 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyObject *swig_obj[3] ; + std::vector< std::string > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodePiecesBatch", 3, 3, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodePiecesBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector> *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector>(size); + for (size_t i = 0; i < size; ++i) { + PyObject *o = PyList_GetItem(swig_obj[1], i); + if (PyList_Check(o)) { + const size_t size2 = PyList_Size(o); + (*out)[i].resize(size2); + for (size_t j = 0; j < size2; ++j) { + const PyInputString ustring(PyList_GetItem(o, j)); + if (ustring.IsAvalable()) { + (*out)[i][j] = ustring.str(); + } else { + PyErr_SetString(PyExc_TypeError,"list must contain integers"); + SWIG_fail; + } + resultobj = ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + arg2 = out; + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__DecodePiecesBatch" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + try { + result = sentencepiece_SentencePieceProcessor__DecodePiecesBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< std::vector< absl::string_view > > const &)*arg2,arg3); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyList_SET_ITEM(resultobj, i, MakePyOutputString(result[i], input_type)); + } + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< std::vector< absl::string_view > > *arg2 = 0 ; + int arg3 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyObject *swig_obj[3] ; + BytesArray result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch", 3, 3, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector> *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector>(size); + for (size_t i = 0; i < size; ++i) { + PyObject *o = PyList_GetItem(swig_obj[1], i); + if (PyList_Check(o)) { + const size_t size2 = PyList_Size(o); + (*out)[i].resize(size2); + for (size_t j = 0; j < size2; ++j) { + const PyInputString ustring(PyList_GetItem(o, j)); + if (ustring.IsAvalable()) { + (*out)[i][j] = ustring.str(); + } else { + PyErr_SetString(PyExc_TypeError,"list must contain integers"); + SWIG_fail; + } + resultobj = ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + arg2 = out; + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + try { + result = sentencepiece_SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< std::vector< absl::string_view > > const &)*arg2,arg3); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyList_SET_ITEM(resultobj, i, MakePyOutputBytes(result[i])); + } + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< std::vector< absl::string_view > > *arg2 = 0 ; + int arg3 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyObject *swig_obj[3] ; + SwigValueWrapper< std::vector< sentencepiece::ImmutableSentencePieceText > > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch", 3, 3, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector> *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector>(size); + for (size_t i = 0; i < size; ++i) { + PyObject *o = PyList_GetItem(swig_obj[1], i); + if (PyList_Check(o)) { + const size_t size2 = PyList_Size(o); + (*out)[i].resize(size2); + for (size_t j = 0; j < size2; ++j) { + const PyInputString ustring(PyList_GetItem(o, j)); + if (ustring.IsAvalable()) { + (*out)[i][j] = ustring.str(); + } else { + PyErr_SetString(PyExc_TypeError,"list must contain integers"); + SWIG_fail; + } + resultobj = ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + } + } else { + PyErr_SetString(PyExc_TypeError,"not a list"); + SWIG_fail; + } + arg2 = out; + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + { + try { + result = sentencepiece_SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< std::vector< absl::string_view > > const &)*arg2,arg3); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyObject *obj = SWIG_NewPointerObj(new sentencepiece::ImmutableSentencePieceText((&result)->at(i)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN | 0); + PyList_SET_ITEM(resultobj, i, obj); + } + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__NBestEncodeAsIds(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + int arg3 ; + bool arg4 ; + bool arg5 ; + bool arg6 ; + bool arg7 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + bool val4 ; + int ecode4 = 0 ; + bool val5 ; + int ecode5 = 0 ; + bool val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + PyObject *swig_obj[7] ; + std::vector< std::vector< int > > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__NBestEncodeAsIds", 7, 7, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__NBestEncodeAsIds" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__NBestEncodeAsIds" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__NBestEncodeAsIds" "', argument " "4"" of type '" "bool""'"); + } + arg4 = static_cast< bool >(val4); + ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__NBestEncodeAsIds" "', argument " "5"" of type '" "bool""'"); + } + arg5 = static_cast< bool >(val5); + ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__NBestEncodeAsIds" "', argument " "6"" of type '" "bool""'"); + } + arg6 = static_cast< bool >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__NBestEncodeAsIds" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + { + try { + result = sentencepiece_SentencePieceProcessor__NBestEncodeAsIds((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyObject *obj = PyList_New(result[i].size()); + for (size_t j = 0; j < result[i].size(); ++j) { + PyList_SET_ITEM(obj, j, PyInt_FromLong(static_cast(result[i][j]))); + } + PyList_SET_ITEM(resultobj, i, obj); + } + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__NBestEncodeAsPieces(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + int arg3 ; + bool arg4 ; + bool arg5 ; + bool arg6 ; + bool arg7 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + bool val4 ; + int ecode4 = 0 ; + bool val5 ; + int ecode5 = 0 ; + bool val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + PyObject *swig_obj[7] ; + std::vector< std::vector< std::string > > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__NBestEncodeAsPieces", 7, 7, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__NBestEncodeAsPieces" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__NBestEncodeAsPieces" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__NBestEncodeAsPieces" "', argument " "4"" of type '" "bool""'"); + } + arg4 = static_cast< bool >(val4); + ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__NBestEncodeAsPieces" "', argument " "5"" of type '" "bool""'"); + } + arg5 = static_cast< bool >(val5); + ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__NBestEncodeAsPieces" "', argument " "6"" of type '" "bool""'"); + } + arg6 = static_cast< bool >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__NBestEncodeAsPieces" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + { + try { + result = sentencepiece_SentencePieceProcessor__NBestEncodeAsPieces((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyObject *obj = PyList_New(result[i].size()); + for (size_t j = 0; j < result[i].size(); ++j) { + PyList_SET_ITEM(obj, j, MakePyOutputString(result[i][j], input_type)); + } + PyList_SET_ITEM(resultobj, i, obj); + } + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__NBestEncodeAsSerializedProto(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + int arg3 ; + bool arg4 ; + bool arg5 ; + bool arg6 ; + bool arg7 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + bool val4 ; + int ecode4 = 0 ; + bool val5 ; + int ecode5 = 0 ; + bool val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + PyObject *swig_obj[7] ; + sentencepiece::util::bytes result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__NBestEncodeAsSerializedProto", 7, 7, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__NBestEncodeAsSerializedProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__NBestEncodeAsSerializedProto" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__NBestEncodeAsSerializedProto" "', argument " "4"" of type '" "bool""'"); + } + arg4 = static_cast< bool >(val4); + ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__NBestEncodeAsSerializedProto" "', argument " "5"" of type '" "bool""'"); + } + arg5 = static_cast< bool >(val5); + ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__NBestEncodeAsSerializedProto" "', argument " "6"" of type '" "bool""'"); + } + arg6 = static_cast< bool >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__NBestEncodeAsSerializedProto" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + { + try { + result = sentencepiece_SentencePieceProcessor__NBestEncodeAsSerializedProto((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = MakePyOutputBytes(result); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__NBestEncodeAsImmutableProto(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + int arg3 ; + bool arg4 ; + bool arg5 ; + bool arg6 ; + bool arg7 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + bool val4 ; + int ecode4 = 0 ; + bool val5 ; + int ecode5 = 0 ; + bool val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + PyObject *swig_obj[7] ; + sentencepiece::ImmutableNBestSentencePieceText result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__NBestEncodeAsImmutableProto", 7, 7, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__NBestEncodeAsImmutableProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__NBestEncodeAsImmutableProto" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__NBestEncodeAsImmutableProto" "', argument " "4"" of type '" "bool""'"); + } + arg4 = static_cast< bool >(val4); + ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__NBestEncodeAsImmutableProto" "', argument " "5"" of type '" "bool""'"); + } + arg5 = static_cast< bool >(val5); + ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__NBestEncodeAsImmutableProto" "', argument " "6"" of type '" "bool""'"); + } + arg6 = static_cast< bool >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__NBestEncodeAsImmutableProto" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + { + try { + result = sentencepiece_SentencePieceProcessor__NBestEncodeAsImmutableProto((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_NewPointerObj((new sentencepiece::ImmutableNBestSentencePieceText(result)), SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, SWIG_POINTER_OWN | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__SampleEncodeAndScoreAsIds(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + int arg3 ; + float arg4 ; + bool arg5 ; + bool arg6 ; + bool arg7 ; + bool arg8 ; + bool arg9 ; + bool arg10 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + float val4 ; + int ecode4 = 0 ; + bool val5 ; + int ecode5 = 0 ; + bool val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + bool val8 ; + int ecode8 = 0 ; + bool val9 ; + int ecode9 = 0 ; + bool val10 ; + int ecode10 = 0 ; + PyObject *swig_obj[10] ; + std::vector< std::pair< std::vector< int >,float > > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__SampleEncodeAndScoreAsIds", 10, 10, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_float(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "4"" of type '" "float""'"); + } + arg4 = static_cast< float >(val4); + ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "5"" of type '" "bool""'"); + } + arg5 = static_cast< bool >(val5); + ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "6"" of type '" "bool""'"); + } + arg6 = static_cast< bool >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "8"" of type '" "bool""'"); + } + arg8 = static_cast< bool >(val8); + ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9); + if (!SWIG_IsOK(ecode9)) { + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "9"" of type '" "bool""'"); + } + arg9 = static_cast< bool >(val9); + ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10); + if (!SWIG_IsOK(ecode10)) { + SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "10"" of type '" "bool""'"); + } + arg10 = static_cast< bool >(val10); + { + try { + result = sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsIds((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyObject *obj = PyList_New(result[i].first.size()); + for (size_t j = 0; j < result[i].first.size(); ++j) { + PyList_SET_ITEM(obj, j, PyInt_FromLong(static_cast(result[i].first[j]))); + } + PyList_SET_ITEM(resultobj, i, PyTuple_Pack(2, obj, PyFloat_FromDouble(static_cast(result[i].second)))); + } + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__SampleEncodeAndScoreAsPieces(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + int arg3 ; + float arg4 ; + bool arg5 ; + bool arg6 ; + bool arg7 ; + bool arg8 ; + bool arg9 ; + bool arg10 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + float val4 ; + int ecode4 = 0 ; + bool val5 ; + int ecode5 = 0 ; + bool val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + bool val8 ; + int ecode8 = 0 ; + bool val9 ; + int ecode9 = 0 ; + bool val10 ; + int ecode10 = 0 ; + PyObject *swig_obj[10] ; + std::vector< std::pair< std::vector< std::string >,float > > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__SampleEncodeAndScoreAsPieces", 10, 10, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_float(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "4"" of type '" "float""'"); + } + arg4 = static_cast< float >(val4); + ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "5"" of type '" "bool""'"); + } + arg5 = static_cast< bool >(val5); + ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "6"" of type '" "bool""'"); + } + arg6 = static_cast< bool >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "8"" of type '" "bool""'"); + } + arg8 = static_cast< bool >(val8); + ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9); + if (!SWIG_IsOK(ecode9)) { + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "9"" of type '" "bool""'"); + } + arg9 = static_cast< bool >(val9); + ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10); + if (!SWIG_IsOK(ecode10)) { + SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "10"" of type '" "bool""'"); + } + arg10 = static_cast< bool >(val10); + { + try { + result = sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsPieces((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyObject *obj = PyList_New(result[i].first.size()); + for (size_t j = 0; j < result[i].first.size(); ++j) { + PyList_SET_ITEM(obj, j, MakePyOutputString(result[i].first[j], input_type)); + } + PyList_SET_ITEM(resultobj, i, PyTuple_Pack(2, obj, PyFloat_FromDouble(static_cast(result[i].second)))); + } + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + int arg3 ; + float arg4 ; + bool arg5 ; + bool arg6 ; + bool arg7 ; + bool arg8 ; + bool arg9 ; + bool arg10 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + float val4 ; + int ecode4 = 0 ; + bool val5 ; + int ecode5 = 0 ; + bool val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + bool val8 ; + int ecode8 = 0 ; + bool val9 ; + int ecode9 = 0 ; + bool val10 ; + int ecode10 = 0 ; + PyObject *swig_obj[10] ; + sentencepiece::util::bytes result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto", 10, 10, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_float(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "4"" of type '" "float""'"); + } + arg4 = static_cast< float >(val4); + ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "5"" of type '" "bool""'"); + } + arg5 = static_cast< bool >(val5); + ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "6"" of type '" "bool""'"); + } + arg6 = static_cast< bool >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "8"" of type '" "bool""'"); + } + arg8 = static_cast< bool >(val8); + ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9); + if (!SWIG_IsOK(ecode9)) { + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "9"" of type '" "bool""'"); + } + arg9 = static_cast< bool >(val9); + ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10); + if (!SWIG_IsOK(ecode10)) { + SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "10"" of type '" "bool""'"); + } + arg10 = static_cast< bool >(val10); + { + try { + result = sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = MakePyOutputBytes(result); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + int arg3 ; + float arg4 ; + bool arg5 ; + bool arg6 ; + bool arg7 ; + bool arg8 ; + bool arg9 ; + bool arg10 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val3 ; + int ecode3 = 0 ; + float val4 ; + int ecode4 = 0 ; + bool val5 ; + int ecode5 = 0 ; + bool val6 ; + int ecode6 = 0 ; + bool val7 ; + int ecode7 = 0 ; + bool val8 ; + int ecode8 = 0 ; + bool val9 ; + int ecode9 = 0 ; + bool val10 ; + int ecode10 = 0 ; + PyObject *swig_obj[10] ; + sentencepiece::ImmutableNBestSentencePieceText result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto", 10, 10, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + ecode4 = SWIG_AsVal_float(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "4"" of type '" "float""'"); + } + arg4 = static_cast< float >(val4); + ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "5"" of type '" "bool""'"); + } + arg5 = static_cast< bool >(val5); + ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "6"" of type '" "bool""'"); + } + arg6 = static_cast< bool >(val6); + ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "7"" of type '" "bool""'"); + } + arg7 = static_cast< bool >(val7); + ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "8"" of type '" "bool""'"); + } + arg8 = static_cast< bool >(val8); + ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9); + if (!SWIG_IsOK(ecode9)) { + SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "9"" of type '" "bool""'"); + } + arg9 = static_cast< bool >(val9); + ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10); + if (!SWIG_IsOK(ecode10)) { + SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "10"" of type '" "bool""'"); + } + arg10 = static_cast< bool >(val10); + { + try { + result = sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_NewPointerObj((new sentencepiece::ImmutableNBestSentencePieceText(result)), SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, SWIG_POINTER_OWN | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__Normalize(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + std::string result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__Normalize", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__Normalize" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + { + try { + result = sentencepiece_SentencePieceProcessor__Normalize(arg1,SWIG_STD_MOVE(arg2)); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + resultobj = MakePyOutputString(result, input_type); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__NormalizeWithOffsets(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + std::pair< std::string,std::vector< size_t > > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__NormalizeWithOffsets", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__NormalizeWithOffsets" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + { + try { + result = sentencepiece_SentencePieceProcessor__NormalizeWithOffsets(arg1,SWIG_STD_MOVE(arg2)); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + if (PyInputString::IsUnicode(input_type)) { + sentencepiece::ConvertToUnicodeAlignment(arg2, (&result)->first, &(&result)->second); + } + PyObject *obj = PyList_New((&result)->second.size()); + for (size_t i = 0; i < (&result)->second.size(); ++i) { + PyList_SET_ITEM(obj, i, PyInt_FromLong(static_cast((&result)->second[i]))); + } + resultobj = PyTuple_Pack(2, MakePyOutputString((&result)->first, input_type), obj); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__CalculateEntropy(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + absl::string_view arg2 ; + float arg3 ; + void *argp1 = 0 ; + int res1 = 0 ; + float val3 ; + int ecode3 = 0 ; + PyObject *swig_obj[3] ; + float result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__CalculateEntropy", 3, 3, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__CalculateEntropy" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_float(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__CalculateEntropy" "', argument " "3"" of type '" "float""'"); + } + arg3 = static_cast< float >(val3); + { + try { + result = (float)sentencepiece_SentencePieceProcessor__CalculateEntropy(arg1,SWIG_STD_MOVE(arg2),arg3); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_From_float(static_cast< float >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__CalculateEntropyBatch(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::vector< absl::string_view > *arg2 = 0 ; + float arg3 ; + int arg4 ; + void *argp1 = 0 ; + int res1 = 0 ; + float val3 ; + int ecode3 = 0 ; + int val4 ; + int ecode4 = 0 ; + PyObject *swig_obj[4] ; + std::vector< float > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__CalculateEntropyBatch", 4, 4, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__CalculateEntropyBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::vector *out = nullptr; + if (PyList_Check(swig_obj[1])) { + const size_t size = PyList_Size(swig_obj[1]); + out = new std::vector(size); + for (size_t i = 0; i < size; ++i) { + const PyInputString ustring(PyList_GetItem(swig_obj[1], i)); + if (ustring.IsAvalable()) { + (*out)[i] = ustring.str(); + } else { + PyErr_SetString(PyExc_TypeError, "list must contain strings"); + SWIG_fail; + } + resultobj = ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a list"); + SWIG_fail; + } + arg2 = out; + } + ecode3 = SWIG_AsVal_float(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__CalculateEntropyBatch" "', argument " "3"" of type '" "float""'"); + } + arg3 = static_cast< float >(val3); + ecode4 = SWIG_AsVal_int(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__CalculateEntropyBatch" "', argument " "4"" of type '" "int""'"); + } + arg4 = static_cast< int >(val4); + { + try { + result = sentencepiece_SentencePieceProcessor__CalculateEntropyBatch(arg1,(std::vector< absl::string_view > const &)*arg2,arg3,arg4); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = PyList_New((&result)->size()); + for (size_t i = 0; i < (&result)->size(); ++i) { + PyList_SET_ITEM(resultobj, i, PyFloat_FromDouble(static_cast(result[i]))); + } + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceProcessor__OverrideNormalizerSpec(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ; + std::unordered_map< std::string,std::string > *arg2 = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::util::Status result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__OverrideNormalizerSpec", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__OverrideNormalizerSpec" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1); + { + std::unordered_map *out = nullptr; + if (PyDict_Check(swig_obj[1])) { + PyObject *key, *value; + Py_ssize_t pos = 0; + out = new std::unordered_map; + while (PyDict_Next(swig_obj[1], &pos, &key, &value)) { + const PyInputString key_ustring(key); + const PyInputString value_ustring(value); + if (key_ustring.IsAvalable() && value_ustring.IsAvalable()) { + out->emplace(std::string(key_ustring.data(), key_ustring.size()), + std::string(value_ustring.data(), value_ustring.size())); + } else { + PyErr_SetString(PyExc_TypeError, "map must contain strings."); + SWIG_fail; + } + resultobj = key_ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a dictionary"); + SWIG_fail; + } + arg2 = out; + } + { + try { + result = sentencepiece_SentencePieceProcessor__OverrideNormalizerSpec(arg1,(std::unordered_map< std::string,std::string > const &)*arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + if (!(&result)->ok()) { + SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str()); + } + resultobj = SWIG_From_bool((&result)->ok()); + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *SentencePieceProcessor_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *obj = NULL; + if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL; + SWIG_TypeNewClientData(SWIGTYPE_p_sentencepiece__SentencePieceProcessor, SWIG_NewClientData(obj)); + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject *SentencePieceProcessor_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + return SWIG_Python_InitShadowInstance(args); +} + +SWIGINTERN PyObject *_wrap_SetRandomGeneratorSeed(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + unsigned int arg1 ; + unsigned int val1 ; + int ecode1 = 0 ; + PyObject *swig_obj[1] ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + ecode1 = SWIG_AsVal_unsigned_SS_int(swig_obj[0], &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "SetRandomGeneratorSeed" "', argument " "1"" of type '" "unsigned int""'"); + } + arg1 = static_cast< unsigned int >(val1); + { + try { + sentencepiece::SetRandomGeneratorSeed(arg1); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SetMinLogLevel(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int val1 ; + int ecode1 = 0 ; + PyObject *swig_obj[1] ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + ecode1 = SWIG_AsVal_int(swig_obj[0], &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "SetMinLogLevel" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + { + try { + sentencepiece::SetMinLogLevel(arg1); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceTrainer__TrainFromString(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + absl::string_view arg1 ; + PyObject *swig_obj[1] ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + { + const PyInputString ustring(swig_obj[0]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg1 = ustring.str(); + } + { + try { + sentencepiece_SentencePieceTrainer__TrainFromString(SWIG_STD_MOVE(arg1)); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceTrainer__TrainFromMap(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + std::unordered_map< std::string,std::string > *arg1 = 0 ; + PyObject *swig_obj[1] ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + { + std::unordered_map *out = nullptr; + if (PyDict_Check(swig_obj[0])) { + PyObject *key, *value; + Py_ssize_t pos = 0; + out = new std::unordered_map; + while (PyDict_Next(swig_obj[0], &pos, &key, &value)) { + const PyInputString key_ustring(key); + const PyInputString value_ustring(value); + if (key_ustring.IsAvalable() && value_ustring.IsAvalable()) { + out->emplace(std::string(key_ustring.data(), key_ustring.size()), + std::string(value_ustring.data(), value_ustring.size())); + } else { + PyErr_SetString(PyExc_TypeError, "map must contain strings."); + SWIG_fail; + } + resultobj = key_ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a dictionary"); + SWIG_fail; + } + arg1 = out; + } + { + try { + sentencepiece_SentencePieceTrainer__TrainFromMap((std::unordered_map< std::string,std::string > const &)*arg1); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_Py_Void(); + { + delete arg1; + } + return resultobj; +fail: + { + delete arg1; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceTrainer__TrainFromMap2(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + std::unordered_map< std::string,std::string > *arg1 = 0 ; + sentencepiece::SentenceIterator *arg2 = (sentencepiece::SentenceIterator *) 0 ; + PyObject *swig_obj[2] ; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceTrainer__TrainFromMap2", 2, 2, swig_obj)) SWIG_fail; + { + std::unordered_map *out = nullptr; + if (PyDict_Check(swig_obj[0])) { + PyObject *key, *value; + Py_ssize_t pos = 0; + out = new std::unordered_map; + while (PyDict_Next(swig_obj[0], &pos, &key, &value)) { + const PyInputString key_ustring(key); + const PyInputString value_ustring(value); + if (key_ustring.IsAvalable() && value_ustring.IsAvalable()) { + out->emplace(std::string(key_ustring.data(), key_ustring.size()), + std::string(value_ustring.data(), value_ustring.size())); + } else { + PyErr_SetString(PyExc_TypeError, "map must contain strings."); + SWIG_fail; + } + resultobj = key_ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a dictionary"); + SWIG_fail; + } + arg1 = out; + } + { + sentencepiece::SentenceIterator *out = nullptr; + if (PyIter_Check(swig_obj[1])) { + out = new PySentenceIterator(swig_obj[1]); + } else { + PyErr_SetString(PyExc_TypeError, "not a iterator"); + SWIG_fail; + } + arg2 = out; + } + { + try { + sentencepiece_SentencePieceTrainer__TrainFromMap2((std::unordered_map< std::string,std::string > const &)*arg1,arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_Py_Void(); + { + delete arg1; + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg1; + } + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceTrainer__TrainFromMap3(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + std::unordered_map< std::string,std::string > *arg1 = 0 ; + PyObject *swig_obj[1] ; + sentencepiece::util::bytes result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + { + std::unordered_map *out = nullptr; + if (PyDict_Check(swig_obj[0])) { + PyObject *key, *value; + Py_ssize_t pos = 0; + out = new std::unordered_map; + while (PyDict_Next(swig_obj[0], &pos, &key, &value)) { + const PyInputString key_ustring(key); + const PyInputString value_ustring(value); + if (key_ustring.IsAvalable() && value_ustring.IsAvalable()) { + out->emplace(std::string(key_ustring.data(), key_ustring.size()), + std::string(value_ustring.data(), value_ustring.size())); + } else { + PyErr_SetString(PyExc_TypeError, "map must contain strings."); + SWIG_fail; + } + resultobj = key_ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a dictionary"); + SWIG_fail; + } + arg1 = out; + } + { + try { + result = sentencepiece_SentencePieceTrainer__TrainFromMap3((std::unordered_map< std::string,std::string > const &)*arg1); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = MakePyOutputBytes(result); + } + { + delete arg1; + } + return resultobj; +fail: + { + delete arg1; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceTrainer__TrainFromMap4(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + std::unordered_map< std::string,std::string > *arg1 = 0 ; + sentencepiece::SentenceIterator *arg2 = (sentencepiece::SentenceIterator *) 0 ; + PyObject *swig_obj[2] ; + sentencepiece::util::bytes result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceTrainer__TrainFromMap4", 2, 2, swig_obj)) SWIG_fail; + { + std::unordered_map *out = nullptr; + if (PyDict_Check(swig_obj[0])) { + PyObject *key, *value; + Py_ssize_t pos = 0; + out = new std::unordered_map; + while (PyDict_Next(swig_obj[0], &pos, &key, &value)) { + const PyInputString key_ustring(key); + const PyInputString value_ustring(value); + if (key_ustring.IsAvalable() && value_ustring.IsAvalable()) { + out->emplace(std::string(key_ustring.data(), key_ustring.size()), + std::string(value_ustring.data(), value_ustring.size())); + } else { + PyErr_SetString(PyExc_TypeError, "map must contain strings."); + SWIG_fail; + } + resultobj = key_ustring.input_type(); + } + } else { + PyErr_SetString(PyExc_TypeError, "not a dictionary"); + SWIG_fail; + } + arg1 = out; + } + { + sentencepiece::SentenceIterator *out = nullptr; + if (PyIter_Check(swig_obj[1])) { + out = new PySentenceIterator(swig_obj[1]); + } else { + PyErr_SetString(PyExc_TypeError, "not a iterator"); + SWIG_fail; + } + arg2 = out; + } + { + try { + result = sentencepiece_SentencePieceTrainer__TrainFromMap4((std::unordered_map< std::string,std::string > const &)*arg1,arg2); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + resultobj = MakePyOutputBytes(result); + } + { + delete arg1; + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg1; + } + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *SentencePieceTrainer_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *obj = NULL; + if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL; + SWIG_TypeNewClientData(SWIGTYPE_p_sentencepiece__SentencePieceTrainer, SWIG_NewClientData(obj)); + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject *_wrap_new_SentencePieceNormalizer(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceNormalizer *result = 0 ; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "new_SentencePieceNormalizer", 0, 0, 0)) SWIG_fail; + { + try { + result = (sentencepiece::SentencePieceNormalizer *)new sentencepiece::SentencePieceNormalizer(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, SWIG_POINTER_NEW | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_delete_SentencePieceNormalizer(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_SentencePieceNormalizer" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1); + { + try { + delete arg1; + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceNormalizer_LoadFromSerializedProto(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ; + absl::string_view arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::util::Status result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceNormalizer_LoadFromSerializedProto", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer_LoadFromSerializedProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + { + try { + result = (arg1)->LoadFromSerializedProto(SWIG_STD_MOVE(arg2)); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + if (!(&result)->ok()) { + SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str()); + } + resultobj = SWIG_From_bool((&result)->ok()); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceNormalizer_LoadFromRuleTSV(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ; + absl::string_view arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::util::Status result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceNormalizer_LoadFromRuleTSV", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer_LoadFromRuleTSV" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + { + try { + result = (arg1)->LoadFromRuleTSV(SWIG_STD_MOVE(arg2)); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + if (!(&result)->ok()) { + SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str()); + } + resultobj = SWIG_From_bool((&result)->ok()); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceNormalizer_LoadFromRuleName(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ; + absl::string_view arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::util::Status result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceNormalizer_LoadFromRuleName", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer_LoadFromRuleName" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + { + try { + result = (arg1)->LoadFromRuleName(SWIG_STD_MOVE(arg2)); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + if (!(&result)->ok()) { + SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str()); + } + resultobj = SWIG_From_bool((&result)->ok()); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceNormalizer_serialized_model_proto(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + std::string result; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer_serialized_model_proto" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer const *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1); + { + try { + result = ((sentencepiece::SentencePieceNormalizer const *)arg1)->serialized_model_proto(); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + resultobj = MakePyOutputString(result, input_type); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceNormalizer_LoadFromFile(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ; + absl::string_view arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + sentencepiece::util::Status result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceNormalizer_LoadFromFile", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer_LoadFromFile" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + { + try { + result = sentencepiece_SentencePieceNormalizer_LoadFromFile(arg1,SWIG_STD_MOVE(arg2)); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + if (!(&result)->ok()) { + SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str()); + } + resultobj = SWIG_From_bool((&result)->ok()); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceNormalizer__Normalize(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ; + absl::string_view arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + std::string result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceNormalizer__Normalize", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer__Normalize" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + { + try { + result = sentencepiece_SentencePieceNormalizer__Normalize(arg1,SWIG_STD_MOVE(arg2)); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + resultobj = MakePyOutputString(result, input_type); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceNormalizer__NormalizeWithOffsets(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ; + absl::string_view arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[2] ; + std::pair< std::string,std::vector< size_t > > result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceNormalizer__NormalizeWithOffsets", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer__NormalizeWithOffsets" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + { + try { + result = sentencepiece_SentencePieceNormalizer__NormalizeWithOffsets(arg1,SWIG_STD_MOVE(arg2)); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + { + PyObject *input_type = resultobj; + if (PyInputString::IsUnicode(input_type)) { + sentencepiece::ConvertToUnicodeAlignment(arg2, (&result)->first, &(&result)->second); + } + PyObject *obj = PyList_New((&result)->second.size()); + for (size_t i = 0; i < (&result)->second.size(); ++i) { + PyList_SET_ITEM(obj, i, PyInt_FromLong(static_cast((&result)->second[i]))); + } + resultobj = PyTuple_Pack(2, MakePyOutputString((&result)->first, input_type), obj); + } + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_SentencePieceNormalizer__SetProtoField(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ; + absl::string_view arg2 ; + bool arg3 ; + void *argp1 = 0 ; + int res1 = 0 ; + bool val3 ; + int ecode3 = 0 ; + PyObject *swig_obj[3] ; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "SentencePieceNormalizer__SetProtoField", 3, 3, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer__SetProtoField" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); + } + arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1); + { + const PyInputString ustring(swig_obj[1]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg2 = ustring.str(); + } + ecode3 = SWIG_AsVal_bool(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceNormalizer__SetProtoField" "', argument " "3"" of type '" "bool""'"); + } + arg3 = static_cast< bool >(val3); + { + try { + sentencepiece_SentencePieceNormalizer__SetProtoField(arg1,SWIG_STD_MOVE(arg2),arg3); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *SentencePieceNormalizer_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *obj = NULL; + if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL; + SWIG_TypeNewClientData(SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, SWIG_NewClientData(obj)); + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject *SentencePieceNormalizer_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + return SWIG_Python_InitShadowInstance(args); +} + +SWIGINTERN PyObject *_wrap_SetDataDir(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + absl::string_view arg1 ; + PyObject *swig_obj[1] ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + { + const PyInputString ustring(swig_obj[0]); + if (!ustring.IsAvalable()) { + PyErr_SetString(PyExc_TypeError, "not a string"); + SWIG_fail; + } + resultobj = ustring.input_type(); + arg1 = ustring.str(); + } + { + try { + sentencepiece::SetDataDir(SWIG_STD_MOVE(arg1)); + ReleaseResultObject(resultobj); + } + catch (const sentencepiece::util::Status &status) { + SWIG_exception(ToSwigError(status.code()), status.ToString().c_str()); + } + } + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +static PyMethodDef SwigMethods[] = { + { "new_ImmutableSentencePieceText_ImmutableSentencePiece", _wrap_new_ImmutableSentencePieceText_ImmutableSentencePiece, METH_NOARGS, NULL}, + { "delete_ImmutableSentencePieceText_ImmutableSentencePiece", _wrap_delete_ImmutableSentencePieceText_ImmutableSentencePiece, METH_O, NULL}, + { "ImmutableSentencePieceText_ImmutableSentencePiece__piece", _wrap_ImmutableSentencePieceText_ImmutableSentencePiece__piece, METH_O, NULL}, + { "ImmutableSentencePieceText_ImmutableSentencePiece__surface", _wrap_ImmutableSentencePieceText_ImmutableSentencePiece__surface, METH_O, NULL}, + { "ImmutableSentencePieceText_ImmutableSentencePiece__id", _wrap_ImmutableSentencePieceText_ImmutableSentencePiece__id, METH_O, NULL}, + { "ImmutableSentencePieceText_ImmutableSentencePiece__begin", _wrap_ImmutableSentencePieceText_ImmutableSentencePiece__begin, METH_O, NULL}, + { "ImmutableSentencePieceText_ImmutableSentencePiece__end", _wrap_ImmutableSentencePieceText_ImmutableSentencePiece__end, METH_O, NULL}, + { "ImmutableSentencePieceText_ImmutableSentencePiece__surface_as_bytes", _wrap_ImmutableSentencePieceText_ImmutableSentencePiece__surface_as_bytes, METH_O, NULL}, + { "ImmutableSentencePieceText_ImmutableSentencePiece__piece_as_bytes", _wrap_ImmutableSentencePieceText_ImmutableSentencePiece__piece_as_bytes, METH_O, NULL}, + { "ImmutableSentencePieceText_ImmutableSentencePiece_swigregister", ImmutableSentencePieceText_ImmutableSentencePiece_swigregister, METH_O, NULL}, + { "ImmutableSentencePieceText_ImmutableSentencePiece_swiginit", ImmutableSentencePieceText_ImmutableSentencePiece_swiginit, METH_VARARGS, NULL}, + { "new_ImmutableSentencePieceText", _wrap_new_ImmutableSentencePieceText, METH_NOARGS, NULL}, + { "delete_ImmutableSentencePieceText", _wrap_delete_ImmutableSentencePieceText, METH_O, NULL}, + { "ImmutableSentencePieceText__pieces_size", _wrap_ImmutableSentencePieceText__pieces_size, METH_O, NULL}, + { "ImmutableSentencePieceText__pieces", _wrap_ImmutableSentencePieceText__pieces, METH_VARARGS, NULL}, + { "ImmutableSentencePieceText__text", _wrap_ImmutableSentencePieceText__text, METH_O, NULL}, + { "ImmutableSentencePieceText__score", _wrap_ImmutableSentencePieceText__score, METH_O, NULL}, + { "ImmutableSentencePieceText_SerializeAsString", _wrap_ImmutableSentencePieceText_SerializeAsString, METH_O, NULL}, + { "ImmutableSentencePieceText__text_as_bytes", _wrap_ImmutableSentencePieceText__text_as_bytes, METH_O, NULL}, + { "ImmutableSentencePieceText_swigregister", ImmutableSentencePieceText_swigregister, METH_O, NULL}, + { "ImmutableSentencePieceText_swiginit", ImmutableSentencePieceText_swiginit, METH_VARARGS, NULL}, + { "new_ImmutableNBestSentencePieceText", _wrap_new_ImmutableNBestSentencePieceText, METH_NOARGS, NULL}, + { "delete_ImmutableNBestSentencePieceText", _wrap_delete_ImmutableNBestSentencePieceText, METH_O, NULL}, + { "ImmutableNBestSentencePieceText__nbests_size", _wrap_ImmutableNBestSentencePieceText__nbests_size, METH_O, NULL}, + { "ImmutableNBestSentencePieceText__nbests", _wrap_ImmutableNBestSentencePieceText__nbests, METH_VARARGS, NULL}, + { "ImmutableNBestSentencePieceText_SerializeAsString", _wrap_ImmutableNBestSentencePieceText_SerializeAsString, METH_O, NULL}, + { "ImmutableNBestSentencePieceText_swigregister", ImmutableNBestSentencePieceText_swigregister, METH_O, NULL}, + { "ImmutableNBestSentencePieceText_swiginit", ImmutableNBestSentencePieceText_swiginit, METH_VARARGS, NULL}, + { "new_SentencePieceProcessor", _wrap_new_SentencePieceProcessor, METH_NOARGS, NULL}, + { "delete_SentencePieceProcessor", _wrap_delete_SentencePieceProcessor, METH_O, NULL}, + { "SentencePieceProcessor_LoadFromSerializedProto", _wrap_SentencePieceProcessor_LoadFromSerializedProto, METH_VARARGS, NULL}, + { "SentencePieceProcessor_SetEncodeExtraOptions", _wrap_SentencePieceProcessor_SetEncodeExtraOptions, METH_VARARGS, NULL}, + { "SentencePieceProcessor_SetDecodeExtraOptions", _wrap_SentencePieceProcessor_SetDecodeExtraOptions, METH_VARARGS, NULL}, + { "SentencePieceProcessor_SetVocabulary", _wrap_SentencePieceProcessor_SetVocabulary, METH_VARARGS, NULL}, + { "SentencePieceProcessor_ResetVocabulary", _wrap_SentencePieceProcessor_ResetVocabulary, METH_O, NULL}, + { "SentencePieceProcessor_LoadVocabulary", _wrap_SentencePieceProcessor_LoadVocabulary, METH_VARARGS, NULL}, + { "SentencePieceProcessor_CalculateEntropy", _wrap_SentencePieceProcessor_CalculateEntropy, METH_VARARGS, NULL}, + { "SentencePieceProcessor_GetPieceSize", _wrap_SentencePieceProcessor_GetPieceSize, METH_O, NULL}, + { "SentencePieceProcessor_PieceToId", _wrap_SentencePieceProcessor_PieceToId, METH_VARARGS, NULL}, + { "SentencePieceProcessor_IdToPiece", _wrap_SentencePieceProcessor_IdToPiece, METH_VARARGS, NULL}, + { "SentencePieceProcessor_GetScore", _wrap_SentencePieceProcessor_GetScore, METH_VARARGS, NULL}, + { "SentencePieceProcessor_IsUnknown", _wrap_SentencePieceProcessor_IsUnknown, METH_VARARGS, NULL}, + { "SentencePieceProcessor_IsControl", _wrap_SentencePieceProcessor_IsControl, METH_VARARGS, NULL}, + { "SentencePieceProcessor_IsUnused", _wrap_SentencePieceProcessor_IsUnused, METH_VARARGS, NULL}, + { "SentencePieceProcessor_IsByte", _wrap_SentencePieceProcessor_IsByte, METH_VARARGS, NULL}, + { "SentencePieceProcessor_unk_id", _wrap_SentencePieceProcessor_unk_id, METH_O, NULL}, + { "SentencePieceProcessor_bos_id", _wrap_SentencePieceProcessor_bos_id, METH_O, NULL}, + { "SentencePieceProcessor_eos_id", _wrap_SentencePieceProcessor_eos_id, METH_O, NULL}, + { "SentencePieceProcessor_pad_id", _wrap_SentencePieceProcessor_pad_id, METH_O, NULL}, + { "SentencePieceProcessor_serialized_model_proto", _wrap_SentencePieceProcessor_serialized_model_proto, METH_O, NULL}, + { "SentencePieceProcessor_LoadFromFile", _wrap_SentencePieceProcessor_LoadFromFile, METH_VARARGS, NULL}, + { "SentencePieceProcessor__EncodeAsIds", _wrap_SentencePieceProcessor__EncodeAsIds, METH_VARARGS, NULL}, + { "SentencePieceProcessor__EncodeAsPieces", _wrap_SentencePieceProcessor__EncodeAsPieces, METH_VARARGS, NULL}, + { "SentencePieceProcessor__EncodeAsSerializedProto", _wrap_SentencePieceProcessor__EncodeAsSerializedProto, METH_VARARGS, NULL}, + { "SentencePieceProcessor__EncodeAsImmutableProto", _wrap_SentencePieceProcessor__EncodeAsImmutableProto, METH_VARARGS, NULL}, + { "SentencePieceProcessor__EncodeAsIdsBatch", _wrap_SentencePieceProcessor__EncodeAsIdsBatch, METH_VARARGS, NULL}, + { "SentencePieceProcessor__EncodeAsPiecesBatch", _wrap_SentencePieceProcessor__EncodeAsPiecesBatch, METH_VARARGS, NULL}, + { "SentencePieceProcessor__EncodeAsSerializedProtoBatch", _wrap_SentencePieceProcessor__EncodeAsSerializedProtoBatch, METH_VARARGS, NULL}, + { "SentencePieceProcessor__EncodeAsImmutableProtoBatch", _wrap_SentencePieceProcessor__EncodeAsImmutableProtoBatch, METH_VARARGS, NULL}, + { "SentencePieceProcessor__DecodeIds", _wrap_SentencePieceProcessor__DecodeIds, METH_VARARGS, NULL}, + { "SentencePieceProcessor__DecodeIdsAsBytes", _wrap_SentencePieceProcessor__DecodeIdsAsBytes, METH_VARARGS, NULL}, + { "SentencePieceProcessor__DecodePieces", _wrap_SentencePieceProcessor__DecodePieces, METH_VARARGS, NULL}, + { "SentencePieceProcessor__DecodeIdsAsSerializedProto", _wrap_SentencePieceProcessor__DecodeIdsAsSerializedProto, METH_VARARGS, NULL}, + { "SentencePieceProcessor__DecodePiecesAsSerializedProto", _wrap_SentencePieceProcessor__DecodePiecesAsSerializedProto, METH_VARARGS, NULL}, + { "SentencePieceProcessor__DecodeIdsAsImmutableProto", _wrap_SentencePieceProcessor__DecodeIdsAsImmutableProto, METH_VARARGS, NULL}, + { "SentencePieceProcessor__DecodePiecesAsImmutableProto", _wrap_SentencePieceProcessor__DecodePiecesAsImmutableProto, METH_VARARGS, NULL}, + { "SentencePieceProcessor__DecodeIdsBatch", _wrap_SentencePieceProcessor__DecodeIdsBatch, METH_VARARGS, NULL}, + { "SentencePieceProcessor__DecodeIdsAsBytesBatch", _wrap_SentencePieceProcessor__DecodeIdsAsBytesBatch, METH_VARARGS, NULL}, + { "SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch", _wrap_SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch, METH_VARARGS, NULL}, + { "SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch", _wrap_SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch, METH_VARARGS, NULL}, + { "SentencePieceProcessor__DecodePiecesBatch", _wrap_SentencePieceProcessor__DecodePiecesBatch, METH_VARARGS, NULL}, + { "SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch", _wrap_SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch, METH_VARARGS, NULL}, + { "SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch", _wrap_SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch, METH_VARARGS, NULL}, + { "SentencePieceProcessor__NBestEncodeAsIds", _wrap_SentencePieceProcessor__NBestEncodeAsIds, METH_VARARGS, NULL}, + { "SentencePieceProcessor__NBestEncodeAsPieces", _wrap_SentencePieceProcessor__NBestEncodeAsPieces, METH_VARARGS, NULL}, + { "SentencePieceProcessor__NBestEncodeAsSerializedProto", _wrap_SentencePieceProcessor__NBestEncodeAsSerializedProto, METH_VARARGS, NULL}, + { "SentencePieceProcessor__NBestEncodeAsImmutableProto", _wrap_SentencePieceProcessor__NBestEncodeAsImmutableProto, METH_VARARGS, NULL}, + { "SentencePieceProcessor__SampleEncodeAndScoreAsIds", _wrap_SentencePieceProcessor__SampleEncodeAndScoreAsIds, METH_VARARGS, NULL}, + { "SentencePieceProcessor__SampleEncodeAndScoreAsPieces", _wrap_SentencePieceProcessor__SampleEncodeAndScoreAsPieces, METH_VARARGS, NULL}, + { "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto", _wrap_SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto, METH_VARARGS, NULL}, + { "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto", _wrap_SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto, METH_VARARGS, NULL}, + { "SentencePieceProcessor__Normalize", _wrap_SentencePieceProcessor__Normalize, METH_VARARGS, NULL}, + { "SentencePieceProcessor__NormalizeWithOffsets", _wrap_SentencePieceProcessor__NormalizeWithOffsets, METH_VARARGS, NULL}, + { "SentencePieceProcessor__CalculateEntropy", _wrap_SentencePieceProcessor__CalculateEntropy, METH_VARARGS, NULL}, + { "SentencePieceProcessor__CalculateEntropyBatch", _wrap_SentencePieceProcessor__CalculateEntropyBatch, METH_VARARGS, NULL}, + { "SentencePieceProcessor__OverrideNormalizerSpec", _wrap_SentencePieceProcessor__OverrideNormalizerSpec, METH_VARARGS, NULL}, + { "SentencePieceProcessor_swigregister", SentencePieceProcessor_swigregister, METH_O, NULL}, + { "SentencePieceProcessor_swiginit", SentencePieceProcessor_swiginit, METH_VARARGS, NULL}, + { "SetRandomGeneratorSeed", _wrap_SetRandomGeneratorSeed, METH_O, NULL}, + { "SetMinLogLevel", _wrap_SetMinLogLevel, METH_O, NULL}, + { "SentencePieceTrainer__TrainFromString", _wrap_SentencePieceTrainer__TrainFromString, METH_O, NULL}, + { "SentencePieceTrainer__TrainFromMap", _wrap_SentencePieceTrainer__TrainFromMap, METH_O, NULL}, + { "SentencePieceTrainer__TrainFromMap2", _wrap_SentencePieceTrainer__TrainFromMap2, METH_VARARGS, NULL}, + { "SentencePieceTrainer__TrainFromMap3", _wrap_SentencePieceTrainer__TrainFromMap3, METH_O, NULL}, + { "SentencePieceTrainer__TrainFromMap4", _wrap_SentencePieceTrainer__TrainFromMap4, METH_VARARGS, NULL}, + { "SentencePieceTrainer_swigregister", SentencePieceTrainer_swigregister, METH_O, NULL}, + { "new_SentencePieceNormalizer", _wrap_new_SentencePieceNormalizer, METH_NOARGS, NULL}, + { "delete_SentencePieceNormalizer", _wrap_delete_SentencePieceNormalizer, METH_O, NULL}, + { "SentencePieceNormalizer_LoadFromSerializedProto", _wrap_SentencePieceNormalizer_LoadFromSerializedProto, METH_VARARGS, NULL}, + { "SentencePieceNormalizer_LoadFromRuleTSV", _wrap_SentencePieceNormalizer_LoadFromRuleTSV, METH_VARARGS, NULL}, + { "SentencePieceNormalizer_LoadFromRuleName", _wrap_SentencePieceNormalizer_LoadFromRuleName, METH_VARARGS, NULL}, + { "SentencePieceNormalizer_serialized_model_proto", _wrap_SentencePieceNormalizer_serialized_model_proto, METH_O, NULL}, + { "SentencePieceNormalizer_LoadFromFile", _wrap_SentencePieceNormalizer_LoadFromFile, METH_VARARGS, NULL}, + { "SentencePieceNormalizer__Normalize", _wrap_SentencePieceNormalizer__Normalize, METH_VARARGS, NULL}, + { "SentencePieceNormalizer__NormalizeWithOffsets", _wrap_SentencePieceNormalizer__NormalizeWithOffsets, METH_VARARGS, NULL}, + { "SentencePieceNormalizer__SetProtoField", _wrap_SentencePieceNormalizer__SetProtoField, METH_VARARGS, NULL}, + { "SentencePieceNormalizer_swigregister", SentencePieceNormalizer_swigregister, METH_O, NULL}, + { "SentencePieceNormalizer_swiginit", SentencePieceNormalizer_swiginit, METH_VARARGS, NULL}, + { "SetDataDir", _wrap_SetDataDir, METH_O, NULL}, + { NULL, NULL, 0, NULL } +}; + + +/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ + +static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_float = {"_p_float", "float *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_sentencepiece__ImmutableNBestSentencePieceText = {"_p_sentencepiece__ImmutableNBestSentencePieceText", "sentencepiece::ImmutableNBestSentencePieceText *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_sentencepiece__ImmutableSentencePieceText = {"_p_sentencepiece__ImmutableSentencePieceText", "sentencepiece::ImmutableSentencePieceText *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece = {"_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece", "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_sentencepiece__SentenceIterator = {"_p_sentencepiece__SentenceIterator", "sentencepiece::SentenceIterator *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_sentencepiece__SentencePieceNormalizer = {"_p_sentencepiece__SentencePieceNormalizer", "sentencepiece::SentencePieceNormalizer *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_sentencepiece__SentencePieceProcessor = {"_p_sentencepiece__SentencePieceProcessor", "sentencepiece::SentencePieceProcessor *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_sentencepiece__SentencePieceTrainer = {"_p_sentencepiece__SentencePieceTrainer", "sentencepiece::SentencePieceTrainer *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_std__string = {"_p_std__string", "sentencepiece::util::bytes *|std::string *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_std__unordered_mapT_std__string_std__string_t = {"_p_std__unordered_mapT_std__string_std__string_t", "std::unordered_map< std::string,std::string > *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_std__vectorT_absl__string_view_t = {"_p_std__vectorT_absl__string_view_t", "std::vector< absl::string_view > *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_std__vectorT_int_t = {"_p_std__vectorT_int_t", "std::vector< int > *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_std__vectorT_std__vectorT_absl__string_view_t_t = {"_p_std__vectorT_std__vectorT_absl__string_view_t_t", "std::vector< std::vector< absl::string_view > > *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_std__vectorT_std__vectorT_int_t_t = {"_p_std__vectorT_std__vectorT_int_t_t", "std::vector< std::vector< int > > *", 0, 0, (void*)0, 0}; + +static swig_type_info *swig_type_initial[] = { + &_swigt__p_char, + &_swigt__p_float, + &_swigt__p_sentencepiece__ImmutableNBestSentencePieceText, + &_swigt__p_sentencepiece__ImmutableSentencePieceText, + &_swigt__p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, + &_swigt__p_sentencepiece__SentenceIterator, + &_swigt__p_sentencepiece__SentencePieceNormalizer, + &_swigt__p_sentencepiece__SentencePieceProcessor, + &_swigt__p_sentencepiece__SentencePieceTrainer, + &_swigt__p_std__string, + &_swigt__p_std__unordered_mapT_std__string_std__string_t, + &_swigt__p_std__vectorT_absl__string_view_t, + &_swigt__p_std__vectorT_int_t, + &_swigt__p_std__vectorT_std__vectorT_absl__string_view_t_t, + &_swigt__p_std__vectorT_std__vectorT_int_t_t, +}; + +static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_float[] = { {&_swigt__p_float, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_sentencepiece__ImmutableNBestSentencePieceText[] = { {&_swigt__p_sentencepiece__ImmutableNBestSentencePieceText, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_sentencepiece__ImmutableSentencePieceText[] = { {&_swigt__p_sentencepiece__ImmutableSentencePieceText, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece[] = { {&_swigt__p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_sentencepiece__SentenceIterator[] = { {&_swigt__p_sentencepiece__SentenceIterator, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_sentencepiece__SentencePieceNormalizer[] = { {&_swigt__p_sentencepiece__SentencePieceNormalizer, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_sentencepiece__SentencePieceProcessor[] = { {&_swigt__p_sentencepiece__SentencePieceProcessor, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_sentencepiece__SentencePieceTrainer[] = { {&_swigt__p_sentencepiece__SentencePieceTrainer, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_std__string[] = { {&_swigt__p_std__string, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_std__unordered_mapT_std__string_std__string_t[] = { {&_swigt__p_std__unordered_mapT_std__string_std__string_t, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_std__vectorT_absl__string_view_t[] = { {&_swigt__p_std__vectorT_absl__string_view_t, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_std__vectorT_int_t[] = { {&_swigt__p_std__vectorT_int_t, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_std__vectorT_std__vectorT_absl__string_view_t_t[] = { {&_swigt__p_std__vectorT_std__vectorT_absl__string_view_t_t, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_std__vectorT_std__vectorT_int_t_t[] = { {&_swigt__p_std__vectorT_std__vectorT_int_t_t, 0, 0, 0},{0, 0, 0, 0}}; + +static swig_cast_info *swig_cast_initial[] = { + _swigc__p_char, + _swigc__p_float, + _swigc__p_sentencepiece__ImmutableNBestSentencePieceText, + _swigc__p_sentencepiece__ImmutableSentencePieceText, + _swigc__p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, + _swigc__p_sentencepiece__SentenceIterator, + _swigc__p_sentencepiece__SentencePieceNormalizer, + _swigc__p_sentencepiece__SentencePieceProcessor, + _swigc__p_sentencepiece__SentencePieceTrainer, + _swigc__p_std__string, + _swigc__p_std__unordered_mapT_std__string_std__string_t, + _swigc__p_std__vectorT_absl__string_view_t, + _swigc__p_std__vectorT_int_t, + _swigc__p_std__vectorT_std__vectorT_absl__string_view_t_t, + _swigc__p_std__vectorT_std__vectorT_int_t_t, +}; + + +/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ + +static swig_const_info swig_const_table[] = { +{0, 0, 0, 0.0, 0, 0}}; + +#ifdef __cplusplus +} +#endif +/* ----------------------------------------------------------------------------- + * Type initialization: + * This problem is tough by the requirement that no dynamic + * memory is used. Also, since swig_type_info structures store pointers to + * swig_cast_info structures and swig_cast_info structures store pointers back + * to swig_type_info structures, we need some lookup code at initialization. + * The idea is that swig generates all the structures that are needed. + * The runtime then collects these partially filled structures. + * The SWIG_InitializeModule function takes these initial arrays out of + * swig_module, and does all the lookup, filling in the swig_module.types + * array with the correct data and linking the correct swig_cast_info + * structures together. + * + * The generated swig_type_info structures are assigned statically to an initial + * array. We just loop through that array, and handle each type individually. + * First we lookup if this type has been already loaded, and if so, use the + * loaded structure instead of the generated one. Then we have to fill in the + * cast linked list. The cast data is initially stored in something like a + * two-dimensional array. Each row corresponds to a type (there are the same + * number of rows as there are in the swig_type_initial array). Each entry in + * a column is one of the swig_cast_info structures for that type. + * The cast_initial array is actually an array of arrays, because each row has + * a variable number of columns. So to actually build the cast linked list, + * we find the array of casts associated with the type, and loop through it + * adding the casts to the list. The one last trick we need to do is making + * sure the type pointer in the swig_cast_info struct is correct. + * + * First off, we lookup the cast->type name to see if it is already loaded. + * There are three cases to handle: + * 1) If the cast->type has already been loaded AND the type we are adding + * casting info to has not been loaded (it is in this module), THEN we + * replace the cast->type pointer with the type pointer that has already + * been loaded. + * 2) If BOTH types (the one we are adding casting info to, and the + * cast->type) are loaded, THEN the cast info has already been loaded by + * the previous module so we just ignore it. + * 3) Finally, if cast->type has not already been loaded, then we add that + * swig_cast_info to the linked list (because the cast->type) pointer will + * be correct. + * ----------------------------------------------------------------------------- */ + +#ifdef __cplusplus +extern "C" { +#if 0 +} /* c-mode */ +#endif +#endif + +#if 0 +#define SWIGRUNTIME_DEBUG +#endif + +#ifndef SWIG_INIT_CLIENT_DATA_TYPE +#define SWIG_INIT_CLIENT_DATA_TYPE void * +#endif + +SWIGRUNTIME void +SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) { + size_t i; + swig_module_info *module_head, *iter; + int init; + + /* check to see if the circular list has been setup, if not, set it up */ + if (swig_module.next==0) { + /* Initialize the swig_module */ + swig_module.type_initial = swig_type_initial; + swig_module.cast_initial = swig_cast_initial; + swig_module.next = &swig_module; + init = 1; + } else { + init = 0; + } + + /* Try and load any already created modules */ + module_head = SWIG_GetModule(clientdata); + if (!module_head) { + /* This is the first module loaded for this interpreter */ + /* so set the swig module into the interpreter */ + SWIG_SetModule(clientdata, &swig_module); + } else { + /* the interpreter has loaded a SWIG module, but has it loaded this one? */ + iter=module_head; + do { + if (iter==&swig_module) { + /* Our module is already in the list, so there's nothing more to do. */ + return; + } + iter=iter->next; + } while (iter!= module_head); + + /* otherwise we must add our module into the list */ + swig_module.next = module_head->next; + module_head->next = &swig_module; + } + + /* When multiple interpreters are used, a module could have already been initialized in + a different interpreter, but not yet have a pointer in this interpreter. + In this case, we do not want to continue adding types... everything should be + set up already */ + if (init == 0) return; + + /* Now work on filling in swig_module.types */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size); +#endif + for (i = 0; i < swig_module.size; ++i) { + swig_type_info *type = 0; + swig_type_info *ret; + swig_cast_info *cast; + +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); +#endif + + /* if there is another module already loaded */ + if (swig_module.next != &swig_module) { + type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); + } + if (type) { + /* Overwrite clientdata field */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found type %s\n", type->name); +#endif + if (swig_module.type_initial[i]->clientdata) { + type->clientdata = swig_module.type_initial[i]->clientdata; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); +#endif + } + } else { + type = swig_module.type_initial[i]; + } + + /* Insert casting types */ + cast = swig_module.cast_initial[i]; + while (cast->type) { + /* Don't need to add information already in the list */ + ret = 0; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); +#endif + if (swig_module.next != &swig_module) { + ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); +#ifdef SWIGRUNTIME_DEBUG + if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); +#endif + } + if (ret) { + if (type == swig_module.type_initial[i]) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: skip old type %s\n", ret->name); +#endif + cast->type = ret; + ret = 0; + } else { + /* Check for casting already in the list */ + swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); +#ifdef SWIGRUNTIME_DEBUG + if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); +#endif + if (!ocast) ret = 0; + } + } + + if (!ret) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); +#endif + if (type->cast) { + type->cast->prev = cast; + cast->next = type->cast; + } + type->cast = cast; + } + cast++; + } + /* Set entry in modules->types array equal to the type */ + swig_module.types[i] = type; + } + swig_module.types[i] = 0; + +#ifdef SWIGRUNTIME_DEBUG + printf("**** SWIG_InitializeModule: Cast List ******\n"); + for (i = 0; i < swig_module.size; ++i) { + int j = 0; + swig_cast_info *cast = swig_module.cast_initial[i]; + printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); + while (cast->type) { + printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); + cast++; + ++j; + } + printf("---- Total casts: %d\n",j); + } + printf("**** SWIG_InitializeModule: Cast List ******\n"); +#endif +} + +/* This function will propagate the clientdata field of type to +* any new swig_type_info structures that have been added into the list +* of equivalent types. It is like calling +* SWIG_TypeClientData(type, clientdata) a second time. +*/ +SWIGRUNTIME void +SWIG_PropagateClientData(void) { + size_t i; + swig_cast_info *equiv; + static int init_run = 0; + + if (init_run) return; + init_run = 1; + + for (i = 0; i < swig_module.size; i++) { + if (swig_module.types[i]->clientdata) { + equiv = swig_module.types[i]->cast; + while (equiv) { + if (!equiv->converter) { + if (equiv->type && !equiv->type->clientdata) + SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); + } + equiv = equiv->next; + } + } + } +} + +#ifdef __cplusplus +#if 0 +{ + /* c-mode */ +#endif +} +#endif + + + +#ifdef __cplusplus +extern "C" { +#endif + + /* ----------------------------------------------------------------------------- + * constants/methods manipulation + * ----------------------------------------------------------------------------- */ + + /* Install Constants */ + SWIGINTERN void + SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { + PyObject *obj = 0; + size_t i; + for (i = 0; constants[i].type; ++i) { + switch(constants[i].type) { + case SWIG_PY_POINTER: + obj = SWIG_InternalNewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); + break; + case SWIG_PY_BINARY: + obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); + break; + default: + obj = 0; + break; + } + if (obj) { + PyDict_SetItemString(d, constants[i].name, obj); + SWIG_Py_DECREF(obj); + } + } + } + + /* ----------------------------------------------------------------------------- + * Patch %callback methods' docstrings to hold the callback ptrs + * -----------------------------------------------------------------------------*/ + + SWIGINTERN void + SWIG_Python_FixMethods(PyMethodDef *methods, const swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) { + size_t i; + for (i = 0; methods[i].ml_name; ++i) { + const char *c = methods[i].ml_doc; + if (!c) continue; + c = strstr(c, "swig_ptr: "); + if (c) { + int j; + const swig_const_info *ci = 0; + const char *name = c + 10; + for (j = 0; const_table[j].type; ++j) { + if (strncmp(const_table[j].name, name, + strlen(const_table[j].name)) == 0) { + ci = &(const_table[j]); + break; + } + } + if (ci) { + void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; + if (ptr) { + size_t shift = (ci->ptype) - types; + swig_type_info *ty = types_initial[shift]; + size_t ldoc = (c - methods[i].ml_doc); + size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; + char *ndoc = (char*)malloc(ldoc + lptr + 10); + if (ndoc) { + char *buff = ndoc; + memcpy(buff, methods[i].ml_doc, ldoc); + buff += ldoc; + memcpy(buff, "swig_ptr: ", 10); + buff += 10; + SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); + methods[i].ml_doc = ndoc; + } + } + } + } + } + } + +#ifdef __cplusplus +} +#endif + + + + +/* -----------------------------------------------------------------------------* + * Partial Init method + * -----------------------------------------------------------------------------*/ + +#ifdef __cplusplus +extern "C" +#endif + +SWIGEXPORT +#if PY_VERSION_HEX >= 0x03000000 +PyObject* +#else +void +#endif +SWIG_init(void) { + PyObject *m, *d, *md, *globals; + +#if PY_VERSION_HEX >= 0x03000000 + static struct PyModuleDef SWIG_module = { + PyModuleDef_HEAD_INIT, + SWIG_name, + NULL, + -1, + SwigMethods, + NULL, + NULL, + NULL, + NULL + }; +#endif + +#if defined(SWIGPYTHON_BUILTIN) + static SwigPyClientData SwigPyObject_clientdata = { + 0, 0, 0, 0, 0, 0, 0 + }; + static PyGetSetDef this_getset_def = { + (char *)"this", &SwigPyBuiltin_ThisClosure, NULL, NULL, NULL + }; + static SwigPyGetSet thisown_getset_closure = { + SwigPyObject_own, + SwigPyObject_own + }; + static PyGetSetDef thisown_getset_def = { + (char *)"thisown", SwigPyBuiltin_GetterClosure, SwigPyBuiltin_SetterClosure, NULL, &thisown_getset_closure + }; + PyTypeObject *builtin_pytype; + int builtin_base_count; + swig_type_info *builtin_basetype; + PyObject *tuple; + PyGetSetDescrObject *static_getset; + PyTypeObject *metatype; + PyTypeObject *swigpyobject; + SwigPyClientData *cd; + PyObject *public_interface, *public_symbol; + PyObject *this_descr; + PyObject *thisown_descr; + PyObject *self = 0; + int i; + + (void)builtin_pytype; + (void)builtin_base_count; + (void)builtin_basetype; + (void)tuple; + (void)static_getset; + (void)self; + + /* Metaclass is used to implement static member variables */ + metatype = SwigPyObjectType(); + assert(metatype); +#endif + + (void)globals; + + /* Create singletons now to avoid potential deadlocks with multi-threaded usage after module initialization */ + SWIG_This(); + SWIG_Python_TypeCache(); + SwigPyPacked_type(); +#ifndef SWIGPYTHON_BUILTIN + SwigPyObject_type(); +#endif + + /* Fix SwigMethods to carry the callback ptrs when needed */ + SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); + +#if PY_VERSION_HEX >= 0x03000000 + m = PyModule_Create(&SWIG_module); +#else + m = Py_InitModule(SWIG_name, SwigMethods); +#endif + + md = d = PyModule_GetDict(m); + (void)md; + + SWIG_InitializeModule(0); + +#ifdef SWIGPYTHON_BUILTIN + swigpyobject = SwigPyObject_TypeOnce(); + + SwigPyObject_stype = SWIG_MangledTypeQuery("_p_SwigPyObject"); + assert(SwigPyObject_stype); + cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; + if (!cd) { + SwigPyObject_stype->clientdata = &SwigPyObject_clientdata; + SwigPyObject_clientdata.pytype = swigpyobject; + } else if (swigpyobject->tp_basicsize != cd->pytype->tp_basicsize) { + PyErr_SetString(PyExc_RuntimeError, "Import error: attempted to load two incompatible swig-generated modules."); +# if PY_VERSION_HEX >= 0x03000000 + return NULL; +# else + return; +# endif + } + + /* All objects have a 'this' attribute */ + this_descr = PyDescr_NewGetSet(SwigPyObject_type(), &this_getset_def); + (void)this_descr; + + /* All objects have a 'thisown' attribute */ + thisown_descr = PyDescr_NewGetSet(SwigPyObject_type(), &thisown_getset_def); + (void)thisown_descr; + + public_interface = PyList_New(0); + public_symbol = 0; + (void)public_symbol; + + PyDict_SetItemString(md, "__all__", public_interface); + SWIG_Py_DECREF(public_interface); + for (i = 0; SwigMethods[i].ml_name != NULL; ++i) + SwigPyBuiltin_AddPublicSymbol(public_interface, SwigMethods[i].ml_name); + for (i = 0; swig_const_table[i].name != 0; ++i) + SwigPyBuiltin_AddPublicSymbol(public_interface, swig_const_table[i].name); +#endif + + SWIG_InstallConstants(d,swig_const_table); + + +#ifdef Py_GIL_DISABLED + PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED); +#endif + +#if PY_VERSION_HEX >= 0x03000000 + return m; +#else + return; +#endif +} + diff --git a/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/LICENSE b/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b9077766e9b9bdcae49ea5c8fced750ed13ec8f7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2018, Tzu-ping Chung + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/METADATA b/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..52118f1e5c83bd7ef39196a749651fc87d176812 --- /dev/null +++ b/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/METADATA @@ -0,0 +1,106 @@ +Metadata-Version: 2.1 +Name: shellingham +Version: 1.5.4 +Summary: Tool to Detect Surrounding Shell +Home-page: https://github.com/sarugaku/shellingham +Author: Tzu-ping Chung +Author-email: uranusjr@gmail.com +License: ISC License +Keywords: shell +Classifier: Development Status :: 3 - Alpha +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: ISC License (ISCL) +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 :: Only +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.12 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE + +============================================= +Shellingham: Tool to Detect Surrounding Shell +============================================= + +.. image:: https://img.shields.io/pypi/v/shellingham.svg + :target: https://pypi.org/project/shellingham/ + +Shellingham detects what shell the current Python executable is running in. + + +Usage +===== + +.. code-block:: python + + >>> import shellingham + >>> shellingham.detect_shell() + ('bash', '/bin/bash') + +``detect_shell`` pokes around the process's running environment to determine +what shell it is run in. It returns a 2-tuple: + +* The shell name, always lowercased. +* The command used to run the shell. + +``ShellDetectionFailure`` is raised if ``detect_shell`` fails to detect the +surrounding shell. + + +Notes +===== + +* The shell name is always lowercased. +* On Windows, the shell name is the name of the executable, minus the file + extension. + + +Notes for Application Developers +================================ + +Remember, your application's user is not necessarily using a shell. +Shellingham raises ``ShellDetectionFailure`` if there is no shell to detect, +but *your application should almost never do this to your user*. + +A practical approach to this is to wrap ``detect_shell`` in a try block, and +provide a sane default on failure + +.. code-block:: python + + try: + shell = shellingham.detect_shell() + except shellingham.ShellDetectionFailure: + shell = provide_default() + + +There are a few choices for you to choose from. + +* The POSIX standard mandates the environment variable ``SHELL`` to refer to + "the user's preferred command language interpreter". This is always available + (even if the user is not in an interactive session), and likely the correct + choice to launch an interactive sub-shell with. +* A command ``sh`` is almost guaranteed to exist, likely at ``/bin/sh``, since + several POSIX tools rely on it. This should be suitable if you want to run a + (possibly non-interactive) script. +* All versions of DOS and Windows have an environment variable ``COMSPEC``. + This can always be used to launch a usable command prompt (e.g. `cmd.exe` on + Windows). + +Here's a simple implementation to provide a default shell + +.. code-block:: python + + import os + + def provide_default(): + if os.name == 'posix': + return os.environ['SHELL'] + elif os.name == 'nt': + return os.environ['COMSPEC'] + raise NotImplementedError(f'OS {os.name!r} support not available') diff --git a/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/RECORD b/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..a03e85926af1ddd60a801034a230b4812a4b9ffd --- /dev/null +++ b/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/RECORD @@ -0,0 +1,21 @@ +shellingham-1.5.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +shellingham-1.5.4.dist-info/LICENSE,sha256=84j9OMrRMRLB3A9mm76A5_hFQe26-3LzAw0sp2QsPJ0,751 +shellingham-1.5.4.dist-info/METADATA,sha256=GD2AIgo3STJieVc53TV8xbs_Sb05DMkZjVGA5UUaB_o,3461 +shellingham-1.5.4.dist-info/RECORD,, +shellingham-1.5.4.dist-info/WHEEL,sha256=iYlv5fX357PQyRT2o6tw1bN-YcKFFHKqB_LwHO5wP-g,110 +shellingham-1.5.4.dist-info/top_level.txt,sha256=uKMQL5AKxPi4O9_Rbd838QeEs4ImpGQKNbEDZYqgBgk,12 +shellingham-1.5.4.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +shellingham/__init__.py,sha256=pAKXUPKUdwyErC0ZjS-5w-fRdSbmdcfvnpt_x1yWqtA,635 +shellingham/__pycache__/__init__.cpython-310.pyc,, +shellingham/__pycache__/_core.cpython-310.pyc,, +shellingham/__pycache__/nt.cpython-310.pyc,, +shellingham/_core.py,sha256=v-CTr_7F7cJAtNnzpa1N_Hl8afkY5yiDA4joGmsUBu0,300 +shellingham/nt.py,sha256=m6J6SuwyqVVlxXT9Bc-9F_1x-T5u0gCFFrRAF2LIkeg,4516 +shellingham/posix/__init__.py,sha256=pB69qtvZJ_yIf48nl4-ZfS3wLwwuXuknXOZhBnC2T1o,3129 +shellingham/posix/__pycache__/__init__.cpython-310.pyc,, +shellingham/posix/__pycache__/_core.cpython-310.pyc,, +shellingham/posix/__pycache__/proc.cpython-310.pyc,, +shellingham/posix/__pycache__/ps.cpython-310.pyc,, +shellingham/posix/_core.py,sha256=_v18UaXbzr4muNhr3-mH1FdSdjZ_dOXQrtUyomIbKYQ,81 +shellingham/posix/proc.py,sha256=nSUxIuQSotvaDW76i0oTQAM9aZ9PXBLFAEktWljSKCo,2659 +shellingham/posix/ps.py,sha256=NGmDKCukhNp0lahwYCaMXphBYaVbhbiR9BtE0OkT8qU,1770 diff --git a/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/WHEEL b/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..c34f1162ef9a50c355df1261ef6194ffc1b39975 --- /dev/null +++ b/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.2) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..d4e44ce0299bb38463f8491ec8850910235c2709 --- /dev/null +++ b/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/top_level.txt @@ -0,0 +1 @@ +shellingham diff --git a/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/zip-safe b/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/venv/lib/python3.10/site-packages/shellingham-1.5.4.dist-info/zip-safe @@ -0,0 +1 @@ + diff --git a/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..51f3442917839f8e0f0cccb52b3c10968ad0779e --- /dev/null +++ b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE @@ -0,0 +1,3 @@ +This software is made available under the terms of *either* of the +licenses found in LICENSE.APACHE2 or LICENSE.MIT. Contributions to are +made under the terms of *both* these licenses. diff --git a/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE.APACHE2 b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE.APACHE2 new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE.APACHE2 @@ -0,0 +1,202 @@ + + 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. diff --git a/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE.MIT b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE.MIT new file mode 100644 index 0000000000000000000000000000000000000000..b8bb97185926d7daed314609753173945ed4ff1a --- /dev/null +++ b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/LICENSE.MIT @@ -0,0 +1,20 @@ +The MIT License (MIT) + +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/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/METADATA b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..75e0057bbad50ca4c117b9130b92f1bed2720669 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/METADATA @@ -0,0 +1,104 @@ +Metadata-Version: 2.1 +Name: sniffio +Version: 1.3.1 +Summary: Sniff out which async library your code is running under +Author-email: "Nathaniel J. Smith" +License: MIT OR Apache-2.0 +Project-URL: Homepage, https://github.com/python-trio/sniffio +Project-URL: Documentation, https://sniffio.readthedocs.io/ +Project-URL: Changelog, https://sniffio.readthedocs.io/en/latest/history.html +Keywords: async,trio,asyncio +Classifier: License :: OSI Approved :: MIT License +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Framework :: Trio +Classifier: Framework :: AsyncIO +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Intended Audience :: Developers +Classifier: Development Status :: 5 - Production/Stable +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: LICENSE.APACHE2 +License-File: LICENSE.MIT + +.. image:: https://img.shields.io/badge/chat-join%20now-blue.svg + :target: https://gitter.im/python-trio/general + :alt: Join chatroom + +.. image:: https://img.shields.io/badge/docs-read%20now-blue.svg + :target: https://sniffio.readthedocs.io/en/latest/?badge=latest + :alt: Documentation Status + +.. image:: https://img.shields.io/pypi/v/sniffio.svg + :target: https://pypi.org/project/sniffio + :alt: Latest PyPi version + +.. image:: https://img.shields.io/conda/vn/conda-forge/sniffio.svg + :target: https://anaconda.org/conda-forge/sniffio + :alt: Latest conda-forge version + +.. image:: https://travis-ci.org/python-trio/sniffio.svg?branch=master + :target: https://travis-ci.org/python-trio/sniffio + :alt: Automated test status + +.. image:: https://codecov.io/gh/python-trio/sniffio/branch/master/graph/badge.svg + :target: https://codecov.io/gh/python-trio/sniffio + :alt: Test coverage + +================================================================= +sniffio: Sniff out which async library your code is running under +================================================================= + +You're writing a library. You've decided to be ambitious, and support +multiple async I/O packages, like `Trio +`__, and `asyncio +`__, and ... You've +written a bunch of clever code to handle all the differences. But... +how do you know *which* piece of clever code to run? + +This is a tiny package whose only purpose is to let you detect which +async library your code is running under. + +* Documentation: https://sniffio.readthedocs.io + +* Bug tracker and source code: https://github.com/python-trio/sniffio + +* License: MIT or Apache License 2.0, your choice + +* Contributor guide: https://trio.readthedocs.io/en/latest/contributing.html + +* Code of conduct: Contributors are requested to follow our `code of + conduct + `_ + in all project spaces. + +This library is maintained by the Trio project, as a service to the +async Python community as a whole. + + +Quickstart +---------- + +.. code-block:: python3 + + from sniffio import current_async_library + import trio + import asyncio + + async def print_library(): + library = current_async_library() + print("This is:", library) + + # Prints "This is trio" + trio.run(print_library) + + # Prints "This is asyncio" + asyncio.run(print_library()) + +For more details, including how to add support to new async libraries, +`please peruse our fine manual `__. diff --git a/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/RECORD b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..68d8d987668df5b887295da207750819779e43b4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/RECORD @@ -0,0 +1,19 @@ +sniffio-1.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +sniffio-1.3.1.dist-info/LICENSE,sha256=ZSyHhIjRRWNh4Iw_hgf9e6WYkqFBA9Fczk_5PIW1zIs,185 +sniffio-1.3.1.dist-info/LICENSE.APACHE2,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +sniffio-1.3.1.dist-info/LICENSE.MIT,sha256=Pm2uVV65J4f8gtHUg1Vnf0VMf2Wus40_nnK_mj2vA0s,1046 +sniffio-1.3.1.dist-info/METADATA,sha256=CzGLVwmO3sz1heYKiJprantcQIbzqapi7_dqHTzuEtk,3875 +sniffio-1.3.1.dist-info/RECORD,, +sniffio-1.3.1.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92 +sniffio-1.3.1.dist-info/top_level.txt,sha256=v9UJXGs5CyddCVeAqXkQiWOrpp6Wtx6GeRrPt9-jjHg,8 +sniffio/__init__.py,sha256=9WJEJlXu7yluP0YtI5SQ9M9OTQfbNHkadarK1vXGDPM,335 +sniffio/__pycache__/__init__.cpython-310.pyc,, +sniffio/__pycache__/_impl.cpython-310.pyc,, +sniffio/__pycache__/_version.cpython-310.pyc,, +sniffio/_impl.py,sha256=UmUFMZpiuOrcjnuHhuYiYMxeCNWfqu9kBlaPf0xk6X8,2843 +sniffio/_tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sniffio/_tests/__pycache__/__init__.cpython-310.pyc,, +sniffio/_tests/__pycache__/test_sniffio.cpython-310.pyc,, +sniffio/_tests/test_sniffio.py,sha256=MMJZZJjQrUi95RANNM-a_55BZquA_gv4rHU1pevcTCM,2058 +sniffio/_version.py,sha256=iVes5xwsHeRzQDexBaAhyx_taNt2ucfA7CWAo4QDt6Q,89 +sniffio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/WHEEL b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..98c0d20b7a64f4f998d7913e1d38a05dba20916c --- /dev/null +++ b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.42.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..01c650244d0ccb6043c603b736fcf8d9e622bc71 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sniffio-1.3.1.dist-info/top_level.txt @@ -0,0 +1 @@ +sniffio diff --git a/venv/lib/python3.10/site-packages/tenacity/__init__.py b/venv/lib/python3.10/site-packages/tenacity/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bcee3f5910483410017fde58127a25b24bdac470 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tenacity/__init__.py @@ -0,0 +1,704 @@ +# Copyright 2016-2018 Julien Danjou +# Copyright 2017 Elisey Zanko +# Copyright 2016 Étienne Bersac +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# 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. +import dataclasses +import functools +import sys +import threading +import time +import typing as t +import warnings +from abc import ABC, abstractmethod +from concurrent import futures +from inspect import iscoroutinefunction + +# Import all built-in retry strategies for easier usage. +from .retry import retry_base # noqa +from .retry import retry_all # noqa +from .retry import retry_always # noqa +from .retry import retry_any # noqa +from .retry import retry_if_exception # noqa +from .retry import retry_if_exception_type # noqa +from .retry import retry_if_exception_cause_type # noqa +from .retry import retry_if_not_exception_type # noqa +from .retry import retry_if_not_result # noqa +from .retry import retry_if_result # noqa +from .retry import retry_never # noqa +from .retry import retry_unless_exception_type # noqa +from .retry import retry_if_exception_message # noqa +from .retry import retry_if_not_exception_message # noqa + +# Import all nap strategies for easier usage. +from .nap import sleep # noqa +from .nap import sleep_using_event # noqa + +# Import all built-in stop strategies for easier usage. +from .stop import stop_after_attempt # noqa +from .stop import stop_after_delay # noqa +from .stop import stop_before_delay # noqa +from .stop import stop_all # noqa +from .stop import stop_any # noqa +from .stop import stop_never # noqa +from .stop import stop_when_event_set # noqa + +# Import all built-in wait strategies for easier usage. +from .wait import wait_chain # noqa +from .wait import wait_combine # noqa +from .wait import wait_exponential # noqa +from .wait import wait_fixed # noqa +from .wait import wait_incrementing # noqa +from .wait import wait_none # noqa +from .wait import wait_random # noqa +from .wait import wait_random_exponential # noqa +from .wait import wait_random_exponential as wait_full_jitter # noqa +from .wait import wait_exponential_jitter # noqa + +# Import all built-in before strategies for easier usage. +from .before import before_log # noqa +from .before import before_nothing # noqa + +# Import all built-in after strategies for easier usage. +from .after import after_log # noqa +from .after import after_nothing # noqa + +# Import all built-in after strategies for easier usage. +from .before_sleep import before_sleep_log # noqa +from .before_sleep import before_sleep_nothing # noqa + +try: + import tornado +except ImportError: + tornado = None + +if t.TYPE_CHECKING: + import types + + from .retry import RetryBaseT + from .stop import StopBaseT + from .wait import WaitBaseT + + +WrappedFnReturnT = t.TypeVar("WrappedFnReturnT") +WrappedFn = t.TypeVar("WrappedFn", bound=t.Callable[..., t.Any]) + + +dataclass_kwargs = {} +if sys.version_info >= (3, 10): + dataclass_kwargs.update({"slots": True}) + + +@dataclasses.dataclass(**dataclass_kwargs) +class IterState: + actions: t.List[t.Callable[["RetryCallState"], t.Any]] = dataclasses.field( + default_factory=list + ) + retry_run_result: bool = False + delay_since_first_attempt: int = 0 + stop_run_result: bool = False + is_explicit_retry: bool = False + + def reset(self) -> None: + self.actions = [] + self.retry_run_result = False + self.delay_since_first_attempt = 0 + self.stop_run_result = False + self.is_explicit_retry = False + + +class TryAgain(Exception): + """Always retry the executed function when raised.""" + + +NO_RESULT = object() + + +class DoAttempt: + pass + + +class DoSleep(float): + pass + + +class BaseAction: + """Base class for representing actions to take by retry object. + + Concrete implementations must define: + - __init__: to initialize all necessary fields + - REPR_FIELDS: class variable specifying attributes to include in repr(self) + - NAME: for identification in retry object methods and callbacks + """ + + REPR_FIELDS: t.Sequence[str] = () + NAME: t.Optional[str] = None + + def __repr__(self) -> str: + state_str = ", ".join( + f"{field}={getattr(self, field)!r}" for field in self.REPR_FIELDS + ) + return f"{self.__class__.__name__}({state_str})" + + def __str__(self) -> str: + return repr(self) + + +class RetryAction(BaseAction): + REPR_FIELDS = ("sleep",) + NAME = "retry" + + def __init__(self, sleep: t.SupportsFloat) -> None: + self.sleep = float(sleep) + + +_unset = object() + + +def _first_set(first: t.Union[t.Any, object], second: t.Any) -> t.Any: + return second if first is _unset else first + + +class RetryError(Exception): + """Encapsulates the last attempt instance right before giving up.""" + + def __init__(self, last_attempt: "Future") -> None: + self.last_attempt = last_attempt + super().__init__(last_attempt) + + def reraise(self) -> t.NoReturn: + if self.last_attempt.failed: + raise self.last_attempt.result() + raise self + + def __str__(self) -> str: + return f"{self.__class__.__name__}[{self.last_attempt}]" + + +class AttemptManager: + """Manage attempt context.""" + + def __init__(self, retry_state: "RetryCallState"): + self.retry_state = retry_state + + def __enter__(self) -> None: + pass + + def __exit__( + self, + exc_type: t.Optional[t.Type[BaseException]], + exc_value: t.Optional[BaseException], + traceback: t.Optional["types.TracebackType"], + ) -> t.Optional[bool]: + if exc_type is not None and exc_value is not None: + self.retry_state.set_exception((exc_type, exc_value, traceback)) + return True # Swallow exception. + else: + # We don't have the result, actually. + self.retry_state.set_result(None) + return None + + +class BaseRetrying(ABC): + def __init__( + self, + sleep: t.Callable[[t.Union[int, float]], None] = sleep, + stop: "StopBaseT" = stop_never, + wait: "WaitBaseT" = wait_none(), + retry: "RetryBaseT" = retry_if_exception_type(), + before: t.Callable[["RetryCallState"], None] = before_nothing, + after: t.Callable[["RetryCallState"], None] = after_nothing, + before_sleep: t.Optional[t.Callable[["RetryCallState"], None]] = None, + reraise: bool = False, + retry_error_cls: t.Type[RetryError] = RetryError, + retry_error_callback: t.Optional[t.Callable[["RetryCallState"], t.Any]] = None, + ): + self.sleep = sleep + self.stop = stop + self.wait = wait + self.retry = retry + self.before = before + self.after = after + self.before_sleep = before_sleep + self.reraise = reraise + self._local = threading.local() + self.retry_error_cls = retry_error_cls + self.retry_error_callback = retry_error_callback + + def copy( + self, + sleep: t.Union[t.Callable[[t.Union[int, float]], None], object] = _unset, + stop: t.Union["StopBaseT", object] = _unset, + wait: t.Union["WaitBaseT", object] = _unset, + retry: t.Union[retry_base, object] = _unset, + before: t.Union[t.Callable[["RetryCallState"], None], object] = _unset, + after: t.Union[t.Callable[["RetryCallState"], None], object] = _unset, + before_sleep: t.Union[ + t.Optional[t.Callable[["RetryCallState"], None]], object + ] = _unset, + reraise: t.Union[bool, object] = _unset, + retry_error_cls: t.Union[t.Type[RetryError], object] = _unset, + retry_error_callback: t.Union[ + t.Optional[t.Callable[["RetryCallState"], t.Any]], object + ] = _unset, + ) -> "BaseRetrying": + """Copy this object with some parameters changed if needed.""" + return self.__class__( + sleep=_first_set(sleep, self.sleep), + stop=_first_set(stop, self.stop), + wait=_first_set(wait, self.wait), + retry=_first_set(retry, self.retry), + before=_first_set(before, self.before), + after=_first_set(after, self.after), + before_sleep=_first_set(before_sleep, self.before_sleep), + reraise=_first_set(reraise, self.reraise), + retry_error_cls=_first_set(retry_error_cls, self.retry_error_cls), + retry_error_callback=_first_set( + retry_error_callback, self.retry_error_callback + ), + ) + + def __repr__(self) -> str: + return ( + f"<{self.__class__.__name__} object at 0x{id(self):x} (" + f"stop={self.stop}, " + f"wait={self.wait}, " + f"sleep={self.sleep}, " + f"retry={self.retry}, " + f"before={self.before}, " + f"after={self.after})>" + ) + + @property + def statistics(self) -> t.Dict[str, t.Any]: + """Return a dictionary of runtime statistics. + + This dictionary will be empty when the controller has never been + ran. When it is running or has ran previously it should have (but + may not) have useful and/or informational keys and values when + running is underway and/or completed. + + .. warning:: The keys in this dictionary **should** be some what + stable (not changing), but there existence **may** + change between major releases as new statistics are + gathered or removed so before accessing keys ensure that + they actually exist and handle when they do not. + + .. note:: The values in this dictionary are local to the thread + running call (so if multiple threads share the same retrying + object - either directly or indirectly) they will each have + there own view of statistics they have collected (in the + future we may provide a way to aggregate the various + statistics from each thread). + """ + try: + return self._local.statistics # type: ignore[no-any-return] + except AttributeError: + self._local.statistics = t.cast(t.Dict[str, t.Any], {}) + return self._local.statistics + + @property + def iter_state(self) -> IterState: + try: + return self._local.iter_state # type: ignore[no-any-return] + except AttributeError: + self._local.iter_state = IterState() + return self._local.iter_state + + def wraps(self, f: WrappedFn) -> WrappedFn: + """Wrap a function for retrying. + + :param f: A function to wraps for retrying. + """ + + @functools.wraps( + f, functools.WRAPPER_ASSIGNMENTS + ("__defaults__", "__kwdefaults__") + ) + def wrapped_f(*args: t.Any, **kw: t.Any) -> t.Any: + return self(f, *args, **kw) + + def retry_with(*args: t.Any, **kwargs: t.Any) -> WrappedFn: + return self.copy(*args, **kwargs).wraps(f) + + wrapped_f.retry = self # type: ignore[attr-defined] + wrapped_f.retry_with = retry_with # type: ignore[attr-defined] + + return wrapped_f # type: ignore[return-value] + + def begin(self) -> None: + self.statistics.clear() + self.statistics["start_time"] = time.monotonic() + self.statistics["attempt_number"] = 1 + self.statistics["idle_for"] = 0 + + def _add_action_func(self, fn: t.Callable[..., t.Any]) -> None: + self.iter_state.actions.append(fn) + + def _run_retry(self, retry_state: "RetryCallState") -> None: + self.iter_state.retry_run_result = self.retry(retry_state) + + def _run_wait(self, retry_state: "RetryCallState") -> None: + if self.wait: + sleep = self.wait(retry_state) + else: + sleep = 0.0 + + retry_state.upcoming_sleep = sleep + + def _run_stop(self, retry_state: "RetryCallState") -> None: + self.statistics["delay_since_first_attempt"] = retry_state.seconds_since_start + self.iter_state.stop_run_result = self.stop(retry_state) + + def iter(self, retry_state: "RetryCallState") -> t.Union[DoAttempt, DoSleep, t.Any]: # noqa + self._begin_iter(retry_state) + result = None + for action in self.iter_state.actions: + result = action(retry_state) + return result + + def _begin_iter(self, retry_state: "RetryCallState") -> None: # noqa + self.iter_state.reset() + + fut = retry_state.outcome + if fut is None: + if self.before is not None: + self._add_action_func(self.before) + self._add_action_func(lambda rs: DoAttempt()) + return + + self.iter_state.is_explicit_retry = fut.failed and isinstance( + fut.exception(), TryAgain + ) + if not self.iter_state.is_explicit_retry: + self._add_action_func(self._run_retry) + self._add_action_func(self._post_retry_check_actions) + + def _post_retry_check_actions(self, retry_state: "RetryCallState") -> None: + if not (self.iter_state.is_explicit_retry or self.iter_state.retry_run_result): + self._add_action_func(lambda rs: rs.outcome.result()) + return + + if self.after is not None: + self._add_action_func(self.after) + + self._add_action_func(self._run_wait) + self._add_action_func(self._run_stop) + self._add_action_func(self._post_stop_check_actions) + + def _post_stop_check_actions(self, retry_state: "RetryCallState") -> None: + if self.iter_state.stop_run_result: + if self.retry_error_callback: + self._add_action_func(self.retry_error_callback) + return + + def exc_check(rs: "RetryCallState") -> None: + fut = t.cast(Future, rs.outcome) + retry_exc = self.retry_error_cls(fut) + if self.reraise: + raise retry_exc.reraise() + raise retry_exc from fut.exception() + + self._add_action_func(exc_check) + return + + def next_action(rs: "RetryCallState") -> None: + sleep = rs.upcoming_sleep + rs.next_action = RetryAction(sleep) + rs.idle_for += sleep + self.statistics["idle_for"] += sleep + self.statistics["attempt_number"] += 1 + + self._add_action_func(next_action) + + if self.before_sleep is not None: + self._add_action_func(self.before_sleep) + + self._add_action_func(lambda rs: DoSleep(rs.upcoming_sleep)) + + def __iter__(self) -> t.Generator[AttemptManager, None, None]: + self.begin() + + retry_state = RetryCallState(self, fn=None, args=(), kwargs={}) + while True: + do = self.iter(retry_state=retry_state) + if isinstance(do, DoAttempt): + yield AttemptManager(retry_state=retry_state) + elif isinstance(do, DoSleep): + retry_state.prepare_for_next_attempt() + self.sleep(do) + else: + break + + @abstractmethod + def __call__( + self, + fn: t.Callable[..., WrappedFnReturnT], + *args: t.Any, + **kwargs: t.Any, + ) -> WrappedFnReturnT: + pass + + +class Retrying(BaseRetrying): + """Retrying controller.""" + + def __call__( + self, + fn: t.Callable[..., WrappedFnReturnT], + *args: t.Any, + **kwargs: t.Any, + ) -> WrappedFnReturnT: + self.begin() + + retry_state = RetryCallState(retry_object=self, fn=fn, args=args, kwargs=kwargs) + while True: + do = self.iter(retry_state=retry_state) + if isinstance(do, DoAttempt): + try: + result = fn(*args, **kwargs) + except BaseException: # noqa: B902 + retry_state.set_exception(sys.exc_info()) # type: ignore[arg-type] + else: + retry_state.set_result(result) + elif isinstance(do, DoSleep): + retry_state.prepare_for_next_attempt() + self.sleep(do) + else: + return do # type: ignore[no-any-return] + + +if sys.version_info >= (3, 9): + FutureGenericT = futures.Future[t.Any] +else: + FutureGenericT = futures.Future + + +class Future(FutureGenericT): + """Encapsulates a (future or past) attempted call to a target function.""" + + def __init__(self, attempt_number: int) -> None: + super().__init__() + self.attempt_number = attempt_number + + @property + def failed(self) -> bool: + """Return whether a exception is being held in this future.""" + return self.exception() is not None + + @classmethod + def construct( + cls, attempt_number: int, value: t.Any, has_exception: bool + ) -> "Future": + """Construct a new Future object.""" + fut = cls(attempt_number) + if has_exception: + fut.set_exception(value) + else: + fut.set_result(value) + return fut + + +class RetryCallState: + """State related to a single call wrapped with Retrying.""" + + def __init__( + self, + retry_object: BaseRetrying, + fn: t.Optional[WrappedFn], + args: t.Any, + kwargs: t.Any, + ) -> None: + #: Retry call start timestamp + self.start_time = time.monotonic() + #: Retry manager object + self.retry_object = retry_object + #: Function wrapped by this retry call + self.fn = fn + #: Arguments of the function wrapped by this retry call + self.args = args + #: Keyword arguments of the function wrapped by this retry call + self.kwargs = kwargs + + #: The number of the current attempt + self.attempt_number: int = 1 + #: Last outcome (result or exception) produced by the function + self.outcome: t.Optional[Future] = None + #: Timestamp of the last outcome + self.outcome_timestamp: t.Optional[float] = None + #: Time spent sleeping in retries + self.idle_for: float = 0.0 + #: Next action as decided by the retry manager + self.next_action: t.Optional[RetryAction] = None + #: Next sleep time as decided by the retry manager. + self.upcoming_sleep: float = 0.0 + + @property + def seconds_since_start(self) -> t.Optional[float]: + if self.outcome_timestamp is None: + return None + return self.outcome_timestamp - self.start_time + + def prepare_for_next_attempt(self) -> None: + self.outcome = None + self.outcome_timestamp = None + self.attempt_number += 1 + self.next_action = None + + def set_result(self, val: t.Any) -> None: + ts = time.monotonic() + fut = Future(self.attempt_number) + fut.set_result(val) + self.outcome, self.outcome_timestamp = fut, ts + + def set_exception( + self, + exc_info: t.Tuple[ + t.Type[BaseException], BaseException, "types.TracebackType| None" + ], + ) -> None: + ts = time.monotonic() + fut = Future(self.attempt_number) + fut.set_exception(exc_info[1]) + self.outcome, self.outcome_timestamp = fut, ts + + def __repr__(self) -> str: + if self.outcome is None: + result = "none yet" + elif self.outcome.failed: + exception = self.outcome.exception() + result = f"failed ({exception.__class__.__name__} {exception})" + else: + result = f"returned {self.outcome.result()}" + + slept = float(round(self.idle_for, 2)) + clsname = self.__class__.__name__ + return f"<{clsname} {id(self)}: attempt #{self.attempt_number}; slept for {slept}; last result: {result}>" + + +@t.overload +def retry(func: WrappedFn) -> WrappedFn: ... + + +@t.overload +def retry( + sleep: t.Callable[[t.Union[int, float]], t.Optional[t.Awaitable[None]]] = sleep, + stop: "StopBaseT" = stop_never, + wait: "WaitBaseT" = wait_none(), + retry: "RetryBaseT" = retry_if_exception_type(), + before: t.Callable[["RetryCallState"], None] = before_nothing, + after: t.Callable[["RetryCallState"], None] = after_nothing, + before_sleep: t.Optional[t.Callable[["RetryCallState"], None]] = None, + reraise: bool = False, + retry_error_cls: t.Type["RetryError"] = RetryError, + retry_error_callback: t.Optional[t.Callable[["RetryCallState"], t.Any]] = None, +) -> t.Callable[[WrappedFn], WrappedFn]: ... + + +def retry(*dargs: t.Any, **dkw: t.Any) -> t.Any: + """Wrap a function with a new `Retrying` object. + + :param dargs: positional arguments passed to Retrying object + :param dkw: keyword arguments passed to the Retrying object + """ + # support both @retry and @retry() as valid syntax + if len(dargs) == 1 and callable(dargs[0]): + return retry()(dargs[0]) + else: + + def wrap(f: WrappedFn) -> WrappedFn: + if isinstance(f, retry_base): + warnings.warn( + f"Got retry_base instance ({f.__class__.__name__}) as callable argument, " + f"this will probably hang indefinitely (did you mean retry={f.__class__.__name__}(...)?)" + ) + r: "BaseRetrying" + if iscoroutinefunction(f): + r = AsyncRetrying(*dargs, **dkw) + elif ( + tornado + and hasattr(tornado.gen, "is_coroutine_function") + and tornado.gen.is_coroutine_function(f) + ): + r = TornadoRetrying(*dargs, **dkw) + else: + r = Retrying(*dargs, **dkw) + + return r.wraps(f) + + return wrap + + +from tenacity._asyncio import AsyncRetrying # noqa:E402,I100 + +if tornado: + from tenacity.tornadoweb import TornadoRetrying + + +__all__ = [ + "retry_base", + "retry_all", + "retry_always", + "retry_any", + "retry_if_exception", + "retry_if_exception_type", + "retry_if_exception_cause_type", + "retry_if_not_exception_type", + "retry_if_not_result", + "retry_if_result", + "retry_never", + "retry_unless_exception_type", + "retry_if_exception_message", + "retry_if_not_exception_message", + "sleep", + "sleep_using_event", + "stop_after_attempt", + "stop_after_delay", + "stop_before_delay", + "stop_all", + "stop_any", + "stop_never", + "stop_when_event_set", + "wait_chain", + "wait_combine", + "wait_exponential", + "wait_fixed", + "wait_incrementing", + "wait_none", + "wait_random", + "wait_random_exponential", + "wait_full_jitter", + "wait_exponential_jitter", + "before_log", + "before_nothing", + "after_log", + "after_nothing", + "before_sleep_log", + "before_sleep_nothing", + "retry", + "WrappedFn", + "TryAgain", + "NO_RESULT", + "DoAttempt", + "DoSleep", + "BaseAction", + "RetryAction", + "RetryError", + "AttemptManager", + "BaseRetrying", + "Retrying", + "Future", + "RetryCallState", + "AsyncRetrying", +] diff --git a/venv/lib/python3.10/site-packages/tenacity/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/tenacity/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2c2457d551c3d7c12ac404f00e71aa864a607d5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/tenacity/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/tenacity/__pycache__/_asyncio.cpython-310.pyc b/venv/lib/python3.10/site-packages/tenacity/__pycache__/_asyncio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2002b05943ad5882c572d6113617c4e4cf02c23d Binary files /dev/null and b/venv/lib/python3.10/site-packages/tenacity/__pycache__/_asyncio.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/tenacity/__pycache__/_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/tenacity/__pycache__/_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8078a03176c53dc1fd613e76d68fa76cd620f985 Binary files /dev/null and b/venv/lib/python3.10/site-packages/tenacity/__pycache__/_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/tenacity/__pycache__/after.cpython-310.pyc b/venv/lib/python3.10/site-packages/tenacity/__pycache__/after.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1eaae63f647307bea782430cad7d17aa25ea235 Binary files /dev/null and b/venv/lib/python3.10/site-packages/tenacity/__pycache__/after.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/tenacity/__pycache__/before.cpython-310.pyc b/venv/lib/python3.10/site-packages/tenacity/__pycache__/before.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd527e4c7ab5fe0b1a3eed70b0836123b85f7ac4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/tenacity/__pycache__/before.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/tenacity/__pycache__/before_sleep.cpython-310.pyc b/venv/lib/python3.10/site-packages/tenacity/__pycache__/before_sleep.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93d8598626d6221e546c428455d632e14297592c Binary files /dev/null and b/venv/lib/python3.10/site-packages/tenacity/__pycache__/before_sleep.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/tenacity/__pycache__/nap.cpython-310.pyc b/venv/lib/python3.10/site-packages/tenacity/__pycache__/nap.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e023b2ebe92c1f1c8193c000f7962619c79f613 Binary files /dev/null and b/venv/lib/python3.10/site-packages/tenacity/__pycache__/nap.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/tenacity/__pycache__/retry.cpython-310.pyc b/venv/lib/python3.10/site-packages/tenacity/__pycache__/retry.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23974e5826c3bc3c9148dfeb4bc39cbc1d2ccc72 Binary files /dev/null and b/venv/lib/python3.10/site-packages/tenacity/__pycache__/retry.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/tenacity/__pycache__/stop.cpython-310.pyc b/venv/lib/python3.10/site-packages/tenacity/__pycache__/stop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3e54cc9b7df080f1ac258473185777d8e86a981 Binary files /dev/null and b/venv/lib/python3.10/site-packages/tenacity/__pycache__/stop.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/tenacity/__pycache__/tornadoweb.cpython-310.pyc b/venv/lib/python3.10/site-packages/tenacity/__pycache__/tornadoweb.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8adbe666bd98176eed3390890be698018601deae Binary files /dev/null and b/venv/lib/python3.10/site-packages/tenacity/__pycache__/tornadoweb.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/tenacity/__pycache__/wait.cpython-310.pyc b/venv/lib/python3.10/site-packages/tenacity/__pycache__/wait.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..504145c427f54924442330ee1be468ffc7e9a55d Binary files /dev/null and b/venv/lib/python3.10/site-packages/tenacity/__pycache__/wait.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/tenacity/_asyncio.py b/venv/lib/python3.10/site-packages/tenacity/_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..b06303f4844828724c676f76c2ca484ec0e9aced --- /dev/null +++ b/venv/lib/python3.10/site-packages/tenacity/_asyncio.py @@ -0,0 +1,148 @@ +# Copyright 2016 Étienne Bersac +# Copyright 2016 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# 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. + +import functools +import sys +import typing as t + +from tenacity import AttemptManager +from tenacity import BaseRetrying +from tenacity import DoAttempt +from tenacity import DoSleep +from tenacity import RetryCallState +from tenacity import _utils + +WrappedFnReturnT = t.TypeVar("WrappedFnReturnT") +WrappedFn = t.TypeVar("WrappedFn", bound=t.Callable[..., t.Awaitable[t.Any]]) + + +def asyncio_sleep(duration: float) -> t.Awaitable[None]: + # Lazy import asyncio as it's expensive (responsible for 25-50% of total import overhead). + import asyncio + + return asyncio.sleep(duration) + + +class AsyncRetrying(BaseRetrying): + sleep: t.Callable[[float], t.Awaitable[t.Any]] + + def __init__( + self, + sleep: t.Callable[[float], t.Awaitable[t.Any]] = asyncio_sleep, + **kwargs: t.Any, + ) -> None: + super().__init__(**kwargs) + self.sleep = sleep + + async def __call__( # type: ignore[override] + self, fn: WrappedFn, *args: t.Any, **kwargs: t.Any + ) -> WrappedFnReturnT: + self.begin() + + retry_state = RetryCallState(retry_object=self, fn=fn, args=args, kwargs=kwargs) + while True: + do = await self.iter(retry_state=retry_state) + if isinstance(do, DoAttempt): + try: + result = await fn(*args, **kwargs) + except BaseException: # noqa: B902 + retry_state.set_exception(sys.exc_info()) # type: ignore[arg-type] + else: + retry_state.set_result(result) + elif isinstance(do, DoSleep): + retry_state.prepare_for_next_attempt() + await self.sleep(do) + else: + return do # type: ignore[no-any-return] + + @classmethod + def _wrap_action_func(cls, fn: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: + if _utils.is_coroutine_callable(fn): + return fn + + async def inner(*args: t.Any, **kwargs: t.Any) -> t.Any: + return fn(*args, **kwargs) + + return inner + + def _add_action_func(self, fn: t.Callable[..., t.Any]) -> None: + self.iter_state.actions.append(self._wrap_action_func(fn)) + + async def _run_retry(self, retry_state: "RetryCallState") -> None: # type: ignore[override] + self.iter_state.retry_run_result = await self._wrap_action_func(self.retry)( + retry_state + ) + + async def _run_wait(self, retry_state: "RetryCallState") -> None: # type: ignore[override] + if self.wait: + sleep = await self._wrap_action_func(self.wait)(retry_state) + else: + sleep = 0.0 + + retry_state.upcoming_sleep = sleep + + async def _run_stop(self, retry_state: "RetryCallState") -> None: # type: ignore[override] + self.statistics["delay_since_first_attempt"] = retry_state.seconds_since_start + self.iter_state.stop_run_result = await self._wrap_action_func(self.stop)( + retry_state + ) + + async def iter( + self, retry_state: "RetryCallState" + ) -> t.Union[DoAttempt, DoSleep, t.Any]: # noqa: A003 + self._begin_iter(retry_state) + result = None + for action in self.iter_state.actions: + result = await action(retry_state) + return result + + def __iter__(self) -> t.Generator[AttemptManager, None, None]: + raise TypeError("AsyncRetrying object is not iterable") + + def __aiter__(self) -> "AsyncRetrying": + self.begin() + self._retry_state = RetryCallState(self, fn=None, args=(), kwargs={}) + return self + + async def __anext__(self) -> AttemptManager: + while True: + do = await self.iter(retry_state=self._retry_state) + if do is None: + raise StopAsyncIteration + elif isinstance(do, DoAttempt): + return AttemptManager(retry_state=self._retry_state) + elif isinstance(do, DoSleep): + self._retry_state.prepare_for_next_attempt() + await self.sleep(do) + else: + raise StopAsyncIteration + + def wraps(self, fn: WrappedFn) -> WrappedFn: + fn = super().wraps(fn) + # Ensure wrapper is recognized as a coroutine function. + + @functools.wraps( + fn, functools.WRAPPER_ASSIGNMENTS + ("__defaults__", "__kwdefaults__") + ) + async def async_wrapped(*args: t.Any, **kwargs: t.Any) -> t.Any: + return await fn(*args, **kwargs) + + # Preserve attributes + async_wrapped.retry = fn.retry # type: ignore[attr-defined] + async_wrapped.retry_with = fn.retry_with # type: ignore[attr-defined] + + return async_wrapped # type: ignore[return-value] diff --git a/venv/lib/python3.10/site-packages/tenacity/_utils.py b/venv/lib/python3.10/site-packages/tenacity/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4e34115e0e44f98cfd7b7e1b322bed5fbaee6a4d --- /dev/null +++ b/venv/lib/python3.10/site-packages/tenacity/_utils.py @@ -0,0 +1,89 @@ +# Copyright 2016 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# 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. +import functools +import inspect +import sys +import typing +from datetime import timedelta + + +# sys.maxsize: +# An integer giving the maximum value a variable of type Py_ssize_t can take. +MAX_WAIT = sys.maxsize / 2 + + +def find_ordinal(pos_num: int) -> str: + # See: https://en.wikipedia.org/wiki/English_numerals#Ordinal_numbers + if pos_num == 0: + return "th" + elif pos_num == 1: + return "st" + elif pos_num == 2: + return "nd" + elif pos_num == 3: + return "rd" + elif 4 <= pos_num <= 20: + return "th" + else: + return find_ordinal(pos_num % 10) + + +def to_ordinal(pos_num: int) -> str: + return f"{pos_num}{find_ordinal(pos_num)}" + + +def get_callback_name(cb: typing.Callable[..., typing.Any]) -> str: + """Get a callback fully-qualified name. + + If no name can be produced ``repr(cb)`` is called and returned. + """ + segments = [] + try: + segments.append(cb.__qualname__) + except AttributeError: + try: + segments.append(cb.__name__) + except AttributeError: + pass + if not segments: + return repr(cb) + else: + try: + # When running under sphinx it appears this can be none? + if cb.__module__: + segments.insert(0, cb.__module__) + except AttributeError: + pass + return ".".join(segments) + + +time_unit_type = typing.Union[int, float, timedelta] + + +def to_seconds(time_unit: time_unit_type) -> float: + return float( + time_unit.total_seconds() if isinstance(time_unit, timedelta) else time_unit + ) + + +def is_coroutine_callable(call: typing.Callable[..., typing.Any]) -> bool: + if inspect.isclass(call): + return False + if inspect.iscoroutinefunction(call): + return True + partial_call = isinstance(call, functools.partial) and call.func + dunder_call = partial_call or getattr(call, "__call__", None) + return inspect.iscoroutinefunction(dunder_call) diff --git a/venv/lib/python3.10/site-packages/tenacity/after.py b/venv/lib/python3.10/site-packages/tenacity/after.py new file mode 100644 index 0000000000000000000000000000000000000000..aa3cc9df0c263e65ebd0643de0a2e6ef66dfbce1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tenacity/after.py @@ -0,0 +1,51 @@ +# Copyright 2016 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# 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. + +import typing + +from tenacity import _utils + +if typing.TYPE_CHECKING: + import logging + + from tenacity import RetryCallState + + +def after_nothing(retry_state: "RetryCallState") -> None: + """After call strategy that does nothing.""" + + +def after_log( + logger: "logging.Logger", + log_level: int, + sec_format: str = "%0.3f", +) -> typing.Callable[["RetryCallState"], None]: + """After call strategy that logs to some logger the finished attempt.""" + + def log_it(retry_state: "RetryCallState") -> None: + if retry_state.fn is None: + # NOTE(sileht): can't really happen, but we must please mypy + fn_name = "" + else: + fn_name = _utils.get_callback_name(retry_state.fn) + logger.log( + log_level, + f"Finished call to '{fn_name}' " + f"after {sec_format % retry_state.seconds_since_start}(s), " + f"this was the {_utils.to_ordinal(retry_state.attempt_number)} time calling it.", + ) + + return log_it diff --git a/venv/lib/python3.10/site-packages/tenacity/before.py b/venv/lib/python3.10/site-packages/tenacity/before.py new file mode 100644 index 0000000000000000000000000000000000000000..366235af6af5b9261c94184521ea6c63759a2b38 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tenacity/before.py @@ -0,0 +1,48 @@ +# Copyright 2016 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# 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. + +import typing + +from tenacity import _utils + +if typing.TYPE_CHECKING: + import logging + + from tenacity import RetryCallState + + +def before_nothing(retry_state: "RetryCallState") -> None: + """Before call strategy that does nothing.""" + + +def before_log( + logger: "logging.Logger", log_level: int +) -> typing.Callable[["RetryCallState"], None]: + """Before call strategy that logs to some logger the attempt.""" + + def log_it(retry_state: "RetryCallState") -> None: + if retry_state.fn is None: + # NOTE(sileht): can't really happen, but we must please mypy + fn_name = "" + else: + fn_name = _utils.get_callback_name(retry_state.fn) + logger.log( + log_level, + f"Starting call to '{fn_name}', " + f"this is the {_utils.to_ordinal(retry_state.attempt_number)} time calling it.", + ) + + return log_it diff --git a/venv/lib/python3.10/site-packages/tenacity/before_sleep.py b/venv/lib/python3.10/site-packages/tenacity/before_sleep.py new file mode 100644 index 0000000000000000000000000000000000000000..d04edcf9bd8034f08530b58c66e15e39c17380cb --- /dev/null +++ b/venv/lib/python3.10/site-packages/tenacity/before_sleep.py @@ -0,0 +1,72 @@ +# Copyright 2016 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# 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. + +import typing + +from tenacity import _utils + +if typing.TYPE_CHECKING: + import logging + + from tenacity import RetryCallState + + +def before_sleep_nothing(retry_state: "RetryCallState") -> None: + """Before call strategy that does nothing.""" + + +def before_sleep_log( + logger: "logging.Logger", + log_level: int, + exc_info: bool = False, +) -> typing.Callable[["RetryCallState"], None]: + """Before call strategy that logs to some logger the attempt.""" + + def log_it(retry_state: "RetryCallState") -> None: + local_exc_info: BaseException | bool | None + + if retry_state.outcome is None: + raise RuntimeError("log_it() called before outcome was set") + + if retry_state.next_action is None: + raise RuntimeError("log_it() called before next_action was set") + + if retry_state.outcome.failed: + ex = retry_state.outcome.exception() + verb, value = "raised", f"{ex.__class__.__name__}: {ex}" + + if exc_info: + local_exc_info = retry_state.outcome.exception() + else: + local_exc_info = False + else: + verb, value = "returned", retry_state.outcome.result() + local_exc_info = False # exc_info does not apply when no exception + + if retry_state.fn is None: + # NOTE(sileht): can't really happen, but we must please mypy + fn_name = "" + else: + fn_name = _utils.get_callback_name(retry_state.fn) + + logger.log( + log_level, + f"Retrying {fn_name} " + f"in {retry_state.next_action.sleep} seconds as it {verb} {value}.", + exc_info=local_exc_info, + ) + + return log_it diff --git a/venv/lib/python3.10/site-packages/tenacity/nap.py b/venv/lib/python3.10/site-packages/tenacity/nap.py new file mode 100644 index 0000000000000000000000000000000000000000..72aa5bfd4b60d8e6ef6ed0cf2ae4f763d12195cc --- /dev/null +++ b/venv/lib/python3.10/site-packages/tenacity/nap.py @@ -0,0 +1,43 @@ +# Copyright 2016 Étienne Bersac +# Copyright 2016 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# 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. + +import time +import typing + +if typing.TYPE_CHECKING: + import threading + + +def sleep(seconds: float) -> None: + """ + Sleep strategy that delays execution for a given number of seconds. + + This is the default strategy, and may be mocked out for unit testing. + """ + time.sleep(seconds) + + +class sleep_using_event: + """Sleep strategy that waits on an event to be set.""" + + def __init__(self, event: "threading.Event") -> None: + self.event = event + + def __call__(self, timeout: typing.Optional[float]) -> None: + # NOTE(harlowja): this may *not* actually wait for timeout + # seconds if the event is set (ie this may eject out early). + self.event.wait(timeout=timeout) diff --git a/venv/lib/python3.10/site-packages/tenacity/py.typed b/venv/lib/python3.10/site-packages/tenacity/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/tenacity/retry.py b/venv/lib/python3.10/site-packages/tenacity/retry.py new file mode 100644 index 0000000000000000000000000000000000000000..c5e55a653fc01bdd06514ad58a3cb3815da5e2f8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tenacity/retry.py @@ -0,0 +1,276 @@ +# Copyright 2016–2021 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# 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. + +import abc +import re +import typing + +if typing.TYPE_CHECKING: + from tenacity import RetryCallState + + +class retry_base(abc.ABC): + """Abstract base class for retry strategies.""" + + @abc.abstractmethod + def __call__(self, retry_state: "RetryCallState") -> bool: + pass + + def __and__(self, other: "retry_base") -> "retry_all": + return retry_all(self, other) + + def __or__(self, other: "retry_base") -> "retry_any": + return retry_any(self, other) + + +RetryBaseT = typing.Union[retry_base, typing.Callable[["RetryCallState"], bool]] + + +class _retry_never(retry_base): + """Retry strategy that never rejects any result.""" + + def __call__(self, retry_state: "RetryCallState") -> bool: + return False + + +retry_never = _retry_never() + + +class _retry_always(retry_base): + """Retry strategy that always rejects any result.""" + + def __call__(self, retry_state: "RetryCallState") -> bool: + return True + + +retry_always = _retry_always() + + +class retry_if_exception(retry_base): + """Retry strategy that retries if an exception verifies a predicate.""" + + def __init__(self, predicate: typing.Callable[[BaseException], bool]) -> None: + self.predicate = predicate + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.outcome is None: + raise RuntimeError("__call__() called before outcome was set") + + if retry_state.outcome.failed: + exception = retry_state.outcome.exception() + if exception is None: + raise RuntimeError("outcome failed but the exception is None") + return self.predicate(exception) + else: + return False + + +class retry_if_exception_type(retry_if_exception): + """Retries if an exception has been raised of one or more types.""" + + def __init__( + self, + exception_types: typing.Union[ + typing.Type[BaseException], + typing.Tuple[typing.Type[BaseException], ...], + ] = Exception, + ) -> None: + self.exception_types = exception_types + super().__init__(lambda e: isinstance(e, exception_types)) + + +class retry_if_not_exception_type(retry_if_exception): + """Retries except an exception has been raised of one or more types.""" + + def __init__( + self, + exception_types: typing.Union[ + typing.Type[BaseException], + typing.Tuple[typing.Type[BaseException], ...], + ] = Exception, + ) -> None: + self.exception_types = exception_types + super().__init__(lambda e: not isinstance(e, exception_types)) + + +class retry_unless_exception_type(retry_if_exception): + """Retries until an exception is raised of one or more types.""" + + def __init__( + self, + exception_types: typing.Union[ + typing.Type[BaseException], + typing.Tuple[typing.Type[BaseException], ...], + ] = Exception, + ) -> None: + self.exception_types = exception_types + super().__init__(lambda e: not isinstance(e, exception_types)) + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.outcome is None: + raise RuntimeError("__call__() called before outcome was set") + + # always retry if no exception was raised + if not retry_state.outcome.failed: + return True + + exception = retry_state.outcome.exception() + if exception is None: + raise RuntimeError("outcome failed but the exception is None") + return self.predicate(exception) + + +class retry_if_exception_cause_type(retry_base): + """Retries if any of the causes of the raised exception is of one or more types. + + The check on the type of the cause of the exception is done recursively (until finding + an exception in the chain that has no `__cause__`) + """ + + def __init__( + self, + exception_types: typing.Union[ + typing.Type[BaseException], + typing.Tuple[typing.Type[BaseException], ...], + ] = Exception, + ) -> None: + self.exception_cause_types = exception_types + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.outcome is None: + raise RuntimeError("__call__ called before outcome was set") + + if retry_state.outcome.failed: + exc = retry_state.outcome.exception() + while exc is not None: + if isinstance(exc.__cause__, self.exception_cause_types): + return True + exc = exc.__cause__ + + return False + + +class retry_if_result(retry_base): + """Retries if the result verifies a predicate.""" + + def __init__(self, predicate: typing.Callable[[typing.Any], bool]) -> None: + self.predicate = predicate + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.outcome is None: + raise RuntimeError("__call__() called before outcome was set") + + if not retry_state.outcome.failed: + return self.predicate(retry_state.outcome.result()) + else: + return False + + +class retry_if_not_result(retry_base): + """Retries if the result refutes a predicate.""" + + def __init__(self, predicate: typing.Callable[[typing.Any], bool]) -> None: + self.predicate = predicate + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.outcome is None: + raise RuntimeError("__call__() called before outcome was set") + + if not retry_state.outcome.failed: + return not self.predicate(retry_state.outcome.result()) + else: + return False + + +class retry_if_exception_message(retry_if_exception): + """Retries if an exception message equals or matches.""" + + def __init__( + self, + message: typing.Optional[str] = None, + match: typing.Optional[str] = None, + ) -> None: + if message and match: + raise TypeError( + f"{self.__class__.__name__}() takes either 'message' or 'match', not both" + ) + + # set predicate + if message: + + def message_fnc(exception: BaseException) -> bool: + return message == str(exception) + + predicate = message_fnc + elif match: + prog = re.compile(match) + + def match_fnc(exception: BaseException) -> bool: + return bool(prog.match(str(exception))) + + predicate = match_fnc + else: + raise TypeError( + f"{self.__class__.__name__}() missing 1 required argument 'message' or 'match'" + ) + + super().__init__(predicate) + + +class retry_if_not_exception_message(retry_if_exception_message): + """Retries until an exception message equals or matches.""" + + def __init__( + self, + message: typing.Optional[str] = None, + match: typing.Optional[str] = None, + ) -> None: + super().__init__(message, match) + # invert predicate + if_predicate = self.predicate + self.predicate = lambda *args_, **kwargs_: not if_predicate(*args_, **kwargs_) + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.outcome is None: + raise RuntimeError("__call__() called before outcome was set") + + if not retry_state.outcome.failed: + return True + + exception = retry_state.outcome.exception() + if exception is None: + raise RuntimeError("outcome failed but the exception is None") + return self.predicate(exception) + + +class retry_any(retry_base): + """Retries if any of the retries condition is valid.""" + + def __init__(self, *retries: retry_base) -> None: + self.retries = retries + + def __call__(self, retry_state: "RetryCallState") -> bool: + return any(r(retry_state) for r in self.retries) + + +class retry_all(retry_base): + """Retries if all the retries condition are valid.""" + + def __init__(self, *retries: retry_base) -> None: + self.retries = retries + + def __call__(self, retry_state: "RetryCallState") -> bool: + return all(r(retry_state) for r in self.retries) diff --git a/venv/lib/python3.10/site-packages/tenacity/stop.py b/venv/lib/python3.10/site-packages/tenacity/stop.py new file mode 100644 index 0000000000000000000000000000000000000000..5cda59ab21727eae5de4c60a0622314103f8e973 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tenacity/stop.py @@ -0,0 +1,130 @@ +# Copyright 2016–2021 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# 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. +import abc +import typing + +from tenacity import _utils + +if typing.TYPE_CHECKING: + import threading + + from tenacity import RetryCallState + + +class stop_base(abc.ABC): + """Abstract base class for stop strategies.""" + + @abc.abstractmethod + def __call__(self, retry_state: "RetryCallState") -> bool: + pass + + def __and__(self, other: "stop_base") -> "stop_all": + return stop_all(self, other) + + def __or__(self, other: "stop_base") -> "stop_any": + return stop_any(self, other) + + +StopBaseT = typing.Union[stop_base, typing.Callable[["RetryCallState"], bool]] + + +class stop_any(stop_base): + """Stop if any of the stop condition is valid.""" + + def __init__(self, *stops: stop_base) -> None: + self.stops = stops + + def __call__(self, retry_state: "RetryCallState") -> bool: + return any(x(retry_state) for x in self.stops) + + +class stop_all(stop_base): + """Stop if all the stop conditions are valid.""" + + def __init__(self, *stops: stop_base) -> None: + self.stops = stops + + def __call__(self, retry_state: "RetryCallState") -> bool: + return all(x(retry_state) for x in self.stops) + + +class _stop_never(stop_base): + """Never stop.""" + + def __call__(self, retry_state: "RetryCallState") -> bool: + return False + + +stop_never = _stop_never() + + +class stop_when_event_set(stop_base): + """Stop when the given event is set.""" + + def __init__(self, event: "threading.Event") -> None: + self.event = event + + def __call__(self, retry_state: "RetryCallState") -> bool: + return self.event.is_set() + + +class stop_after_attempt(stop_base): + """Stop when the previous attempt >= max_attempt.""" + + def __init__(self, max_attempt_number: int) -> None: + self.max_attempt_number = max_attempt_number + + def __call__(self, retry_state: "RetryCallState") -> bool: + return retry_state.attempt_number >= self.max_attempt_number + + +class stop_after_delay(stop_base): + """ + Stop when the time from the first attempt >= limit. + + Note: `max_delay` will be exceeded, so when used with a `wait`, the actual total delay will be greater + than `max_delay` by some of the final sleep period before `max_delay` is exceeded. + + If you need stricter timing with waits, consider `stop_before_delay` instead. + """ + + def __init__(self, max_delay: _utils.time_unit_type) -> None: + self.max_delay = _utils.to_seconds(max_delay) + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.seconds_since_start is None: + raise RuntimeError("__call__() called but seconds_since_start is not set") + return retry_state.seconds_since_start >= self.max_delay + + +class stop_before_delay(stop_base): + """ + Stop right before the next attempt would take place after the time from the first attempt >= limit. + + Most useful when you are using with a `wait` function like wait_random_exponential, but need to make + sure that the max_delay is not exceeded. + """ + + def __init__(self, max_delay: _utils.time_unit_type) -> None: + self.max_delay = _utils.to_seconds(max_delay) + + def __call__(self, retry_state: "RetryCallState") -> bool: + if retry_state.seconds_since_start is None: + raise RuntimeError("__call__() called but seconds_since_start is not set") + return ( + retry_state.seconds_since_start + retry_state.upcoming_sleep + >= self.max_delay + ) diff --git a/venv/lib/python3.10/site-packages/tenacity/tornadoweb.py b/venv/lib/python3.10/site-packages/tenacity/tornadoweb.py new file mode 100644 index 0000000000000000000000000000000000000000..44323e40dab2f2617723c085818610ef21243852 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tenacity/tornadoweb.py @@ -0,0 +1,63 @@ +# Copyright 2017 Elisey Zanko +# +# 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. + +import sys +import typing + +from tenacity import BaseRetrying +from tenacity import DoAttempt +from tenacity import DoSleep +from tenacity import RetryCallState + +from tornado import gen + +if typing.TYPE_CHECKING: + from tornado.concurrent import Future + +_RetValT = typing.TypeVar("_RetValT") + + +class TornadoRetrying(BaseRetrying): + def __init__( + self, + sleep: "typing.Callable[[float], Future[None]]" = gen.sleep, + **kwargs: typing.Any, + ) -> None: + super().__init__(**kwargs) + self.sleep = sleep + + @gen.coroutine # type: ignore[misc] + def __call__( + self, + fn: "typing.Callable[..., typing.Union[typing.Generator[typing.Any, typing.Any, _RetValT], Future[_RetValT]]]", + *args: typing.Any, + **kwargs: typing.Any, + ) -> "typing.Generator[typing.Any, typing.Any, _RetValT]": + self.begin() + + retry_state = RetryCallState(retry_object=self, fn=fn, args=args, kwargs=kwargs) + while True: + do = self.iter(retry_state=retry_state) + if isinstance(do, DoAttempt): + try: + result = yield fn(*args, **kwargs) + except BaseException: # noqa: B902 + retry_state.set_exception(sys.exc_info()) # type: ignore[arg-type] + else: + retry_state.set_result(result) + elif isinstance(do, DoSleep): + retry_state.prepare_for_next_attempt() + yield self.sleep(do) + else: + raise gen.Return(do) diff --git a/venv/lib/python3.10/site-packages/tenacity/wait.py b/venv/lib/python3.10/site-packages/tenacity/wait.py new file mode 100644 index 0000000000000000000000000000000000000000..3addbb9c4a2e4641d0541c7ffb5d61c693384e33 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tenacity/wait.py @@ -0,0 +1,234 @@ +# Copyright 2016–2021 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# 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. + +import abc +import random +import typing + +from tenacity import _utils + +if typing.TYPE_CHECKING: + from tenacity import RetryCallState + + +class wait_base(abc.ABC): + """Abstract base class for wait strategies.""" + + @abc.abstractmethod + def __call__(self, retry_state: "RetryCallState") -> float: + pass + + def __add__(self, other: "wait_base") -> "wait_combine": + return wait_combine(self, other) + + def __radd__(self, other: "wait_base") -> typing.Union["wait_combine", "wait_base"]: + # make it possible to use multiple waits with the built-in sum function + if other == 0: # type: ignore[comparison-overlap] + return self + return self.__add__(other) + + +WaitBaseT = typing.Union[ + wait_base, typing.Callable[["RetryCallState"], typing.Union[float, int]] +] + + +class wait_fixed(wait_base): + """Wait strategy that waits a fixed amount of time between each retry.""" + + def __init__(self, wait: _utils.time_unit_type) -> None: + self.wait_fixed = _utils.to_seconds(wait) + + def __call__(self, retry_state: "RetryCallState") -> float: + return self.wait_fixed + + +class wait_none(wait_fixed): + """Wait strategy that doesn't wait at all before retrying.""" + + def __init__(self) -> None: + super().__init__(0) + + +class wait_random(wait_base): + """Wait strategy that waits a random amount of time between min/max.""" + + def __init__( + self, min: _utils.time_unit_type = 0, max: _utils.time_unit_type = 1 + ) -> None: # noqa + self.wait_random_min = _utils.to_seconds(min) + self.wait_random_max = _utils.to_seconds(max) + + def __call__(self, retry_state: "RetryCallState") -> float: + return self.wait_random_min + ( + random.random() * (self.wait_random_max - self.wait_random_min) + ) + + +class wait_combine(wait_base): + """Combine several waiting strategies.""" + + def __init__(self, *strategies: wait_base) -> None: + self.wait_funcs = strategies + + def __call__(self, retry_state: "RetryCallState") -> float: + return sum(x(retry_state=retry_state) for x in self.wait_funcs) + + +class wait_chain(wait_base): + """Chain two or more waiting strategies. + + If all strategies are exhausted, the very last strategy is used + thereafter. + + For example:: + + @retry(wait=wait_chain(*[wait_fixed(1) for i in range(3)] + + [wait_fixed(2) for j in range(5)] + + [wait_fixed(5) for k in range(4))) + def wait_chained(): + print("Wait 1s for 3 attempts, 2s for 5 attempts and 5s + thereafter.") + """ + + def __init__(self, *strategies: wait_base) -> None: + self.strategies = strategies + + def __call__(self, retry_state: "RetryCallState") -> float: + wait_func_no = min(max(retry_state.attempt_number, 1), len(self.strategies)) + wait_func = self.strategies[wait_func_no - 1] + return wait_func(retry_state=retry_state) + + +class wait_incrementing(wait_base): + """Wait an incremental amount of time after each attempt. + + Starting at a starting value and incrementing by a value for each attempt + (and restricting the upper limit to some maximum value). + """ + + def __init__( + self, + start: _utils.time_unit_type = 0, + increment: _utils.time_unit_type = 100, + max: _utils.time_unit_type = _utils.MAX_WAIT, # noqa + ) -> None: + self.start = _utils.to_seconds(start) + self.increment = _utils.to_seconds(increment) + self.max = _utils.to_seconds(max) + + def __call__(self, retry_state: "RetryCallState") -> float: + result = self.start + (self.increment * (retry_state.attempt_number - 1)) + return max(0, min(result, self.max)) + + +class wait_exponential(wait_base): + """Wait strategy that applies exponential backoff. + + It allows for a customized multiplier and an ability to restrict the + upper and lower limits to some maximum and minimum value. + + The intervals are fixed (i.e. there is no jitter), so this strategy is + suitable for balancing retries against latency when a required resource is + unavailable for an unknown duration, but *not* suitable for resolving + contention between multiple processes for a shared resource. Use + wait_random_exponential for the latter case. + """ + + def __init__( + self, + multiplier: typing.Union[int, float] = 1, + max: _utils.time_unit_type = _utils.MAX_WAIT, # noqa + exp_base: typing.Union[int, float] = 2, + min: _utils.time_unit_type = 0, # noqa + ) -> None: + self.multiplier = multiplier + self.min = _utils.to_seconds(min) + self.max = _utils.to_seconds(max) + self.exp_base = exp_base + + def __call__(self, retry_state: "RetryCallState") -> float: + try: + exp = self.exp_base ** (retry_state.attempt_number - 1) + result = self.multiplier * exp + except OverflowError: + return self.max + return max(max(0, self.min), min(result, self.max)) + + +class wait_random_exponential(wait_exponential): + """Random wait with exponentially widening window. + + An exponential backoff strategy used to mediate contention between multiple + uncoordinated processes for a shared resource in distributed systems. This + is the sense in which "exponential backoff" is meant in e.g. Ethernet + networking, and corresponds to the "Full Jitter" algorithm described in + this blog post: + + https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ + + Each retry occurs at a random time in a geometrically expanding interval. + It allows for a custom multiplier and an ability to restrict the upper + limit of the random interval to some maximum value. + + Example:: + + wait_random_exponential(multiplier=0.5, # initial window 0.5s + max=60) # max 60s timeout + + When waiting for an unavailable resource to become available again, as + opposed to trying to resolve contention for a shared resource, the + wait_exponential strategy (which uses a fixed interval) may be preferable. + + """ + + def __call__(self, retry_state: "RetryCallState") -> float: + high = super().__call__(retry_state=retry_state) + return random.uniform(0, high) + + +class wait_exponential_jitter(wait_base): + """Wait strategy that applies exponential backoff and jitter. + + It allows for a customized initial wait, maximum wait and jitter. + + This implements the strategy described here: + https://cloud.google.com/storage/docs/retry-strategy + + The wait time is min(initial * 2**n + random.uniform(0, jitter), maximum) + where n is the retry count. + """ + + def __init__( + self, + initial: float = 1, + max: float = _utils.MAX_WAIT, # noqa + exp_base: float = 2, + jitter: float = 1, + ) -> None: + self.initial = initial + self.max = max + self.exp_base = exp_base + self.jitter = jitter + + def __call__(self, retry_state: "RetryCallState") -> float: + jitter = random.uniform(0, self.jitter) + try: + exp = self.exp_base ** (retry_state.attempt_number - 1) + result = self.initial * exp + jitter + except OverflowError: + result = self.max + return max(0, min(result, self.max)) diff --git a/venv/lib/python3.10/site-packages/termcolor-3.1.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/termcolor-3.1.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/termcolor-3.1.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/termcolor-3.1.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/termcolor-3.1.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..5e276c0449f84a4a40314c781bd04425bde8a3d0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/termcolor-3.1.0.dist-info/METADATA @@ -0,0 +1,150 @@ +Metadata-Version: 2.4 +Name: termcolor +Version: 3.1.0 +Summary: ANSI color formatting for output in terminal +Project-URL: Changelog, https://github.com/termcolor/termcolor/releases +Project-URL: Homepage, https://github.com/termcolor/termcolor +Project-URL: Source, https://github.com/termcolor/termcolor +Author-email: Konstantin Lepa +Maintainer: Hugo van Kemenade +License-Expression: MIT +License-File: COPYING.txt +Keywords: ANSI,ANSI color,ANSI colour,color,colour,formatting,termcolor,terminal +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 :: Only +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 :: Terminals +Classifier: Typing :: Typed +Requires-Python: >=3.9 +Provides-Extra: tests +Requires-Dist: pytest; extra == 'tests' +Requires-Dist: pytest-cov; extra == 'tests' +Description-Content-Type: text/markdown + +# termcolor + +[![PyPI version](https://img.shields.io/pypi/v/termcolor.svg?logo=pypi&logoColor=FFE873)](https://pypi.org/project/termcolor) +[![Supported Python versions](https://img.shields.io/pypi/pyversions/termcolor.svg?logo=python&logoColor=FFE873)](https://pypi.org/project/termcolor) +[![PyPI downloads](https://img.shields.io/pypi/dm/termcolor.svg)](https://pypistats.org/packages/termcolor) +[![GitHub Actions status](https://github.com/termcolor/termcolor/workflows/Test/badge.svg)](https://github.com/termcolor/termcolor/actions) +[![Codecov](https://codecov.io/gh/termcolor/termcolor/branch/main/graph/badge.svg)](https://codecov.io/gh/termcolor/termcolor) +[![Licence](https://img.shields.io/github/license/termcolor/termcolor.svg)](COPYING.txt) +[![Code style: Black](https://img.shields.io/badge/code%20style-Black-000000.svg)](https://github.com/psf/black) +[![Tidelift](https://tidelift.com/badges/package/pypi/termcolor)](https://tidelift.com/subscription/pkg/pypi-termcolor?utm_source=pypi-termcolor&utm_medium=referral&utm_campaign=readme) + +## Installation + +### From PyPI + +```bash +python3 -m pip install --upgrade termcolor +``` + +### From source + +```bash +git clone https://github.com/termcolor/termcolor +cd termcolor +python3 -m pip install . +``` + +### Demo + +To see demo output, run: + +```bash +python3 -m termcolor +``` + +## Example + +```python +import sys + +from termcolor import colored, cprint + +text = colored("Hello, World!", "red", attrs=["reverse", "blink"]) +print(text) +cprint("Hello, World!", "green", "on_red") + +print_red_on_cyan = lambda x: cprint(x, "red", "on_cyan") +print_red_on_cyan("Hello, World!") +print_red_on_cyan("Hello, Universe!") + +for i in range(10): + cprint(i, "magenta", end=" ") + +cprint("Attention!", "red", attrs=["bold"], file=sys.stderr) + +# You can also specify 0-255 RGB ints via a tuple +cprint("Both foreground and background can use tuples", (100, 150, 250), (50, 60, 70)) +``` + +## Text properties + +| Text colors | Text highlights | Attributes | +| --------------- | ------------------ | ----------- | +| `black` | `on_black` | `bold` | +| `red` | `on_red` | `dark` | +| `green` | `on_green` | `underline` | +| `yellow` | `on_yellow` | `blink` | +| `blue` | `on_blue` | `reverse` | +| `magenta` | `on_magenta` | `concealed` | +| `cyan` | `on_cyan` | `strike` | +| `white` | `on_white` | | +| `light_grey` | `on_light_grey` | | +| `dark_grey` | `on_dark_grey` | | +| `light_red` | `on_light_red` | | +| `light_green` | `on_light_green` | | +| `light_yellow` | `on_light_yellow` | | +| `light_blue` | `on_light_blue` | | +| `light_magenta` | `on_light_magenta` | | +| `light_cyan` | `on_light_cyan` | | + +You can also use any arbitrary RGB color specified as a tuple of 0-255 integers, for +example, `(100, 150, 250)`. + +## Terminal properties + +| Terminal | bold | dark | underline | blink | reverse | concealed | +| ------------ | ------- | ---- | --------- | ---------- | ------- | --------- | +| xterm | yes | no | yes | bold | yes | yes | +| linux | yes | yes | bold | yes | yes | no | +| rxvt | yes | no | yes | bold/black | yes | no | +| dtterm | yes | yes | yes | reverse | yes | yes | +| teraterm | reverse | no | yes | rev/red | yes | no | +| aixterm | normal | no | yes | no | yes | yes | +| PuTTY | color | no | yes | no | yes | no | +| Windows | no | no | no | no | yes | no | +| Cygwin SSH | yes | no | color | color | color | yes | +| Mac Terminal | yes | no | yes | yes | yes | yes | + +## Overrides + +Terminal colour detection can be disabled or enabled in several ways. + +In order of precedence: + +1. Calling `colored` or `cprint` with a truthy `no_color` disables colour. +2. Calling `colored` or `cprint` with a truthy `force_color` forces colour. +3. Setting the `ANSI_COLORS_DISABLED` environment variable to any non-empty value + disables colour. +4. Setting the [`NO_COLOR`](https://no-color.org/) environment variable to any non-empty + value disables colour. +5. Setting the [`FORCE_COLOR`](https://force-color.org/) environment variable to any + non-empty value forces colour. +6. Setting the `TERM` environment variable to `dumb`, or using such a + [dumb terminal](https://en.wikipedia.org/wiki/Computer_terminal#Character-oriented_terminal), + disables colour. +7. Finally, termcolor will attempt to detect whether the terminal supports colour. diff --git a/venv/lib/python3.10/site-packages/termcolor-3.1.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/termcolor-3.1.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..570530150a16bef3d6f3175b32e180a0da2816a6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/termcolor-3.1.0.dist-info/RECORD @@ -0,0 +1,12 @@ +termcolor-3.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +termcolor-3.1.0.dist-info/METADATA,sha256=9WZ1qe7QQFkmnnE-6GtA_SlsDfjDEHaHvkKcRX2jnTg,6380 +termcolor-3.1.0.dist-info/RECORD,, +termcolor-3.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +termcolor-3.1.0.dist-info/licenses/COPYING.txt,sha256=55tr2CliwTMMqqfEInhWewhmd3dnP44jcaYk1XFdTA4,1072 +termcolor/__init__.py,sha256=pTvnzwOuzlav_lBp4PrM75d3EUXPDe-bugD-Z8GG8Xk,283 +termcolor/__main__.py,sha256=3vLqDeZdeyNRWGpNFSoVv7-zSFeX59QBKjRQCLFMdHI,3520 +termcolor/__pycache__/__init__.cpython-310.pyc,, +termcolor/__pycache__/__main__.cpython-310.pyc,, +termcolor/__pycache__/termcolor.cpython-310.pyc,, +termcolor/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +termcolor/termcolor.py,sha256=BzyHifYoWbksXFF7yYjdgWFSguGSkABNNesfSlrHQRE,6312 diff --git a/venv/lib/python3.10/site-packages/termcolor-3.1.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/termcolor-3.1.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/termcolor-3.1.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/venv/lib/python3.10/site-packages/termcolor-3.1.0.dist-info/licenses/COPYING.txt b/venv/lib/python3.10/site-packages/termcolor-3.1.0.dist-info/licenses/COPYING.txt new file mode 100644 index 0000000000000000000000000000000000000000..d0b79705c354418108635b67e17ee15443a4a130 --- /dev/null +++ b/venv/lib/python3.10/site-packages/termcolor-3.1.0.dist-info/licenses/COPYING.txt @@ -0,0 +1,19 @@ +Copyright (c) 2008-2011 Volvox Development Team + +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/venv/lib/python3.10/site-packages/tiktoken_ext/__pycache__/openai_public.cpython-310.pyc b/venv/lib/python3.10/site-packages/tiktoken_ext/__pycache__/openai_public.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9da961d81a44e141c930c7d35b1d56fc8aa5e02 Binary files /dev/null and b/venv/lib/python3.10/site-packages/tiktoken_ext/__pycache__/openai_public.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/tiktoken_ext/openai_public.py b/venv/lib/python3.10/site-packages/tiktoken_ext/openai_public.py new file mode 100644 index 0000000000000000000000000000000000000000..02c9ee20fa186223145da1de759bdf001f1f1e1c --- /dev/null +++ b/venv/lib/python3.10/site-packages/tiktoken_ext/openai_public.py @@ -0,0 +1,162 @@ +from tiktoken.load import data_gym_to_mergeable_bpe_ranks, load_tiktoken_bpe + +ENDOFTEXT = "<|endoftext|>" +FIM_PREFIX = "<|fim_prefix|>" +FIM_MIDDLE = "<|fim_middle|>" +FIM_SUFFIX = "<|fim_suffix|>" +ENDOFPROMPT = "<|endofprompt|>" + +# The pattern in the original GPT-2 release is: +# r"""'s|'t|'re|'ve|'m|'ll|'d| ?[\p{L}]+| ?[\p{N}]+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""" +# This is equivalent, but executes faster: +r50k_pat_str = ( + r"""'(?:[sdmt]|ll|ve|re)| ?\p{L}++| ?\p{N}++| ?[^\s\p{L}\p{N}]++|\s++$|\s+(?!\S)|\s""" +) + + +def gpt2(): + mergeable_ranks = data_gym_to_mergeable_bpe_ranks( + vocab_bpe_file="https://openaipublic.blob.core.windows.net/gpt-2/encodings/main/vocab.bpe", + encoder_json_file="https://openaipublic.blob.core.windows.net/gpt-2/encodings/main/encoder.json", + vocab_bpe_hash="1ce1664773c50f3e0cc8842619a93edc4624525b728b188a9e0be33b7726adc5", + encoder_json_hash="196139668be63f3b5d6574427317ae82f612a97c5d1cdaf36ed2256dbf636783", + ) + return { + "name": "gpt2", + "explicit_n_vocab": 50257, + "pat_str": r50k_pat_str, + "mergeable_ranks": mergeable_ranks, + "special_tokens": {ENDOFTEXT: 50256}, + } + + +def r50k_base(): + mergeable_ranks = load_tiktoken_bpe( + "https://openaipublic.blob.core.windows.net/encodings/r50k_base.tiktoken", + expected_hash="306cd27f03c1a714eca7108e03d66b7dc042abe8c258b44c199a7ed9838dd930", + ) + return { + "name": "r50k_base", + "explicit_n_vocab": 50257, + "pat_str": r50k_pat_str, + "mergeable_ranks": mergeable_ranks, + "special_tokens": {ENDOFTEXT: 50256}, + } + + +def p50k_base(): + mergeable_ranks = load_tiktoken_bpe( + "https://openaipublic.blob.core.windows.net/encodings/p50k_base.tiktoken", + expected_hash="94b5ca7dff4d00767bc256fdd1b27e5b17361d7b8a5f968547f9f23eb70d2069", + ) + return { + "name": "p50k_base", + "explicit_n_vocab": 50281, + "pat_str": r50k_pat_str, + "mergeable_ranks": mergeable_ranks, + "special_tokens": {ENDOFTEXT: 50256}, + } + + +def p50k_edit(): + mergeable_ranks = load_tiktoken_bpe( + "https://openaipublic.blob.core.windows.net/encodings/p50k_base.tiktoken", + expected_hash="94b5ca7dff4d00767bc256fdd1b27e5b17361d7b8a5f968547f9f23eb70d2069", + ) + special_tokens = {ENDOFTEXT: 50256, FIM_PREFIX: 50281, FIM_MIDDLE: 50282, FIM_SUFFIX: 50283} + return { + "name": "p50k_edit", + "pat_str": r50k_pat_str, + "mergeable_ranks": mergeable_ranks, + "special_tokens": special_tokens, + } + + +def cl100k_base(): + mergeable_ranks = load_tiktoken_bpe( + "https://openaipublic.blob.core.windows.net/encodings/cl100k_base.tiktoken", + expected_hash="223921b76ee99bde995b7ff738513eef100fb51d18c93597a113bcffe865b2a7", + ) + special_tokens = { + ENDOFTEXT: 100257, + FIM_PREFIX: 100258, + FIM_MIDDLE: 100259, + FIM_SUFFIX: 100260, + ENDOFPROMPT: 100276, + } + return { + "name": "cl100k_base", + "pat_str": r"""'(?i:[sdmt]|ll|ve|re)|[^\r\n\p{L}\p{N}]?+\p{L}++|\p{N}{1,3}+| ?[^\s\p{L}\p{N}]++[\r\n]*+|\s++$|\s*[\r\n]|\s+(?!\S)|\s""", + "mergeable_ranks": mergeable_ranks, + "special_tokens": special_tokens, + } + + +def o200k_base(): + mergeable_ranks = load_tiktoken_bpe( + "https://openaipublic.blob.core.windows.net/encodings/o200k_base.tiktoken", + expected_hash="446a9538cb6c348e3516120d7c08b09f57c36495e2acfffe59a5bf8b0cfb1a2d", + ) + special_tokens = {ENDOFTEXT: 199999, ENDOFPROMPT: 200018} + # This regex could be made more efficient. If I was the one working on this encoding, I would + # have done a few other things differently too, e.g. I think you can allocate tokens more + # efficiently across languages. + pat_str = "|".join( + [ + r"""[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?""", + r"""[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?""", + r"""\p{N}{1,3}""", + r""" ?[^\s\p{L}\p{N}]+[\r\n/]*""", + r"""\s*[\r\n]+""", + r"""\s+(?!\S)""", + r"""\s+""", + ] + ) + return { + "name": "o200k_base", + "pat_str": pat_str, + "mergeable_ranks": mergeable_ranks, + "special_tokens": special_tokens, + } + + +def o200k_harmony(): + base_enc = o200k_base() + name = "o200k_harmony" + pat_str = base_enc["pat_str"] + mergeable_ranks = base_enc["mergeable_ranks"] + special_tokens = { + **base_enc["special_tokens"], + "<|startoftext|>": 199998, + "<|endoftext|>": 199999, + "<|reserved_200000|>": 200000, + "<|reserved_200001|>": 200001, + "<|return|>": 200002, + "<|constrain|>": 200003, + "<|reserved_200004|>": 200004, + "<|channel|>": 200005, + "<|start|>": 200006, + "<|end|>": 200007, + "<|message|>": 200008, + "<|reserved_200009|>": 200009, + "<|reserved_200010|>": 200010, + "<|reserved_200011|>": 200011, + "<|call|>": 200012, + } | {f"<|reserved_{i}|>": i for i in range(200013, 201088)} + return { + "name": name, + "pat_str": pat_str, + "mergeable_ranks": mergeable_ranks, + "special_tokens": special_tokens, + } + + +ENCODING_CONSTRUCTORS = { + "gpt2": gpt2, + "r50k_base": r50k_base, + "p50k_base": p50k_base, + "p50k_edit": p50k_edit, + "cl100k_base": cl100k_base, + "o200k_base": o200k_base, + "o200k_harmony": o200k_harmony, +} diff --git a/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/LICENSE b/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..fd49b6ecaf742f1252c3f83b93d2b1651ae31411 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 Max Brunsfeld, GitHub + +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/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..1decaa201025736cad3302c2374c5d8cf69bd6ed --- /dev/null +++ b/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/METADATA @@ -0,0 +1,337 @@ +Metadata-Version: 2.2 +Name: tree-sitter +Version: 0.24.0 +Summary: Python bindings to the Tree-sitter parsing library +Author-email: Max Brunsfeld +Project-URL: Homepage, https://tree-sitter.github.io/tree-sitter/ +Project-URL: Source, https://github.com/tree-sitter/py-tree-sitter +Project-URL: Documentation, https://tree-sitter.github.io/py-tree-sitter/ +Project-URL: Discord, https://discord.gg/w7nTvsVJhm +Keywords: incremental,parsing,tree-sitter +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: C +Classifier: Programming Language :: Python +Classifier: Topic :: Software Development :: Compilers +Classifier: Topic :: Text Processing :: Linguistic +Classifier: Typing :: Typed +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-File: LICENSE +Provides-Extra: docs +Requires-Dist: sphinx~=8.1; extra == "docs" +Requires-Dist: sphinx-book-theme; extra == "docs" +Provides-Extra: tests +Requires-Dist: tree-sitter-html>=0.23.2; extra == "tests" +Requires-Dist: tree-sitter-javascript>=0.23.1; extra == "tests" +Requires-Dist: tree-sitter-json>=0.24.8; extra == "tests" +Requires-Dist: tree-sitter-python>=0.23.6; extra == "tests" +Requires-Dist: tree-sitter-rust>=0.23.2; extra == "tests" + +# Python Tree-sitter + +[![CI][ci]](https://github.com/tree-sitter/py-tree-sitter/actions/workflows/ci.yml) +[![pypi][pypi]](https://pypi.org/project/tree-sitter/) +[![docs][docs]](https://tree-sitter.github.io/py-tree-sitter/) + +This module provides Python bindings to the [tree-sitter] parsing library. + +## Installation + +The package has no library dependencies and provides pre-compiled wheels for all major platforms. + +> [!NOTE] +> If your platform is not currently supported, please submit an [issue] on GitHub. + +```sh +pip install tree-sitter +``` + +## Usage + +### Setup + +#### Install languages + +Tree-sitter language implementations also provide pre-compiled binary wheels. +Let's take [Python][tree-sitter-python] as an example. + +```sh +pip install tree-sitter-python +``` + +Then, you can load it as a `Language` object: + +```python +import tree_sitter_python as tspython +from tree_sitter import Language, Parser + +PY_LANGUAGE = Language(tspython.language()) +``` + +### Basic parsing + +Create a `Parser` and configure it to use a language: + +```python +parser = Parser(PY_LANGUAGE) +``` + +Parse some source code: + +```python +tree = parser.parse( + bytes( + """ +def foo(): + if bar: + baz() +""", + "utf8" + ) +) +``` + +If you have your source code in some data structure other than a bytes object, +you can pass a "read" callable to the parse function. + +The read callable can use either the byte offset or point tuple to read from +buffer and return source code as bytes object. An empty bytes object or None +terminates parsing for that line. The bytes must be encoded as UTF-8 or UTF-16. + +For example, to use the byte offset with UTF-8 encoding: + +```python +src = bytes( + """ +def foo(): + if bar: + baz() +""", + "utf8", +) + + +def read_callable_byte_offset(byte_offset, point): + return src[byte_offset : byte_offset + 1] + + +tree = parser.parse(read_callable_byte_offset, encoding="utf8") +``` + +And to use the point: + +```python +src_lines = ["\n", "def foo():\n", " if bar:\n", " baz()\n"] + + +def read_callable_point(byte_offset, point): + row, column = point + if row >= len(src_lines) or column >= len(src_lines[row]): + return None + return src_lines[row][column:].encode("utf8") + + +tree = parser.parse(read_callable_point, encoding="utf8") +``` + +Inspect the resulting `Tree`: + +```python +root_node = tree.root_node +assert root_node.type == 'module' +assert root_node.start_point == (1, 0) +assert root_node.end_point == (4, 0) + +function_node = root_node.children[0] +assert function_node.type == 'function_definition' +assert function_node.child_by_field_name('name').type == 'identifier' + +function_name_node = function_node.children[1] +assert function_name_node.type == 'identifier' +assert function_name_node.start_point == (1, 4) +assert function_name_node.end_point == (1, 7) + +function_body_node = function_node.child_by_field_name("body") + +if_statement_node = function_body_node.child(0) +assert if_statement_node.type == "if_statement" + +function_call_node = if_statement_node.child_by_field_name("consequence").child(0).child(0) +assert function_call_node.type == "call" + +function_call_name_node = function_call_node.child_by_field_name("function") +assert function_call_name_node.type == "identifier" + +function_call_args_node = function_call_node.child_by_field_name("arguments") +assert function_call_args_node.type == "argument_list" + + +assert str(root_node) == ( + "(module " + "(function_definition " + "name: (identifier) " + "parameters: (parameters) " + "body: (block " + "(if_statement " + "condition: (identifier) " + "consequence: (block " + "(expression_statement (call " + "function: (identifier) " + "arguments: (argument_list))))))))" +) +``` + +Or, to use the byte offset with UTF-16 encoding: + +```python +parser.language = JAVASCRIPT +source_code = bytes("'😎' && '🐍'", "utf16") + +def read(byte_position, _): + return source_code[byte_position: byte_position + 2] + +tree = parser.parse(read, encoding="utf16") +root_node = tree.root_node +statement_node = root_node.children[0] +binary_node = statement_node.children[0] +snake_node = binary_node.children[2] +snake = source_code[snake_node.start_byte:snake_node.end_byte] + +assert binary_node.type == "binary_expression" +assert snake_node.type == "string" +assert snake.decode("utf16") == "'🐍'" +``` + +### Walking syntax trees + +If you need to traverse a large number of nodes efficiently, you can use +a `TreeCursor`: + +```python +cursor = tree.walk() + +assert cursor.node.type == "module" + +assert cursor.goto_first_child() +assert cursor.node.type == "function_definition" + +assert cursor.goto_first_child() +assert cursor.node.type == "def" + +# Returns `False` because the `def` node has no children +assert not cursor.goto_first_child() + +assert cursor.goto_next_sibling() +assert cursor.node.type == "identifier" + +assert cursor.goto_next_sibling() +assert cursor.node.type == "parameters" + +assert cursor.goto_parent() +assert cursor.node.type == "function_definition" +``` + +> [!IMPORTANT] +> Keep in mind that the cursor can only walk into children of the node that it started from. + +See [examples/walk_tree.py] for a complete example of iterating over every node in a tree. + +### Editing + +When a source file is edited, you can edit the syntax tree to keep it in sync with +the source: + +```python +new_src = src[:5] + src[5 : 5 + 2].upper() + src[5 + 2 :] + +tree.edit( + start_byte=5, + old_end_byte=5, + new_end_byte=5 + 2, + start_point=(0, 5), + old_end_point=(0, 5), + new_end_point=(0, 5 + 2), +) +``` + +Then, when you're ready to incorporate the changes into a new syntax tree, +you can call `Parser.parse` again, but pass in the old tree: + +```python +new_tree = parser.parse(new_src, tree) +``` + +This will run much faster than if you were parsing from scratch. + +The `Tree.changed_ranges` method can be called on the _old_ tree to return +the list of ranges whose syntactic structure has been changed: + +```python +for changed_range in tree.changed_ranges(new_tree): + print("Changed range:") + print(f" Start point {changed_range.start_point}") + print(f" Start byte {changed_range.start_byte}") + print(f" End point {changed_range.end_point}") + print(f" End byte {changed_range.end_byte}") +``` + +### Pattern-matching + +You can search for patterns in a syntax tree using a [tree query]: + +```python +query = PY_LANGUAGE.query( + """ +(function_definition + name: (identifier) @function.def + body: (block) @function.block) + +(call + function: (identifier) @function.call + arguments: (argument_list) @function.args) +""" +) +``` + +#### Captures + +```python +captures = query.captures(tree.root_node) +assert len(captures) == 4 +assert captures["function.def"][0] == function_name_node +assert captures["function.block"][0] == function_body_node +assert captures["function.call"][0] == function_call_name_node +assert captures["function.args"][0] == function_call_args_node +``` + +#### Matches + +```python +matches = query.matches(tree.root_node) +assert len(matches) == 2 + +# first match +assert matches[0][1]["function.def"] == [function_name_node] +assert matches[0][1]["function.block"] == [function_body_node] + +# second match +assert matches[1][1]["function.call"] == [function_call_name_node] +assert matches[1][1]["function.args"] == [function_call_args_node] +``` + +The difference between the two methods is that `Query.matches()` groups captures into matches, +which is much more useful when your captures within a query relate to each other. + +To try out and explore the code referenced in this README, check out [examples/usage.py]. + +[tree-sitter]: https://tree-sitter.github.io/tree-sitter/ +[issue]: https://github.com/tree-sitter/py-tree-sitter/issues/new +[tree-sitter-python]: https://github.com/tree-sitter/tree-sitter-python +[tree query]: https://tree-sitter.github.io/tree-sitter/using-parsers#query-syntax +[ci]: https://img.shields.io/github/actions/workflow/status/tree-sitter/py-tree-sitter/ci.yml?logo=github&label=CI +[pypi]: https://img.shields.io/pypi/v/tree-sitter?logo=pypi&logoColor=ffd242&label=PyPI +[docs]: https://img.shields.io/github/deployments/tree-sitter/py-tree-sitter/github-pages?logo=sphinx&label=Docs +[examples/walk_tree.py]: https://github.com/tree-sitter/py-tree-sitter/blob/master/examples/walk_tree.py +[examples/usage.py]: https://github.com/tree-sitter/py-tree-sitter/blob/master/examples/usage.py diff --git a/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..5431354ff8c610bc17083f52676cf0dbce72a02c --- /dev/null +++ b/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/RECORD @@ -0,0 +1,12 @@ +tree_sitter-0.24.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +tree_sitter-0.24.0.dist-info/LICENSE,sha256=GvB5BUP_-smd070pC_g8qWP0-AKQZetvNWOPTfhjro4,1088 +tree_sitter-0.24.0.dist-info/METADATA,sha256=OAosvc3a4bS_bLJfD9p6JiIXH_Q0qKFDmg9pUQ98vd8,9818 +tree_sitter-0.24.0.dist-info/RECORD,, +tree_sitter-0.24.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tree_sitter-0.24.0.dist-info/WHEEL,sha256=ViyZsTV2upbIniGkknQiIrLPLs1cJIoIfr1wsV7PMic,151 +tree_sitter-0.24.0.dist-info/top_level.txt,sha256=oNKDFAeLi6i39EcTTW75DL0SE5sMBkgX0TRMpJe3Lrs,12 +tree_sitter/__init__.py,sha256=LBpeHPh4oQAcFBe4zdqX65IL7cSPpYLArEMdtRYtT5Y,1647 +tree_sitter/__init__.pyi,sha256=CIfwk5IDskCY4P8t9K5S-3hlh4RAT9h-PkyfFX-up8U,11969 +tree_sitter/__pycache__/__init__.cpython-310.pyc,, +tree_sitter/_binding.cpython-310-x86_64-linux-gnu.so,sha256=yuwqNeugpX1NXzPuiSMbWbADul79b1b7l11VU1MbJaY,1726008 +tree_sitter/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/REQUESTED b/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..91ee8fda184e552c2904a70107ce044d35988068 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.8.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 + diff --git a/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..eca3be89f560b3fdf96fbd79d7fc02954a832da1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tree_sitter-0.24.0.dist-info/top_level.txt @@ -0,0 +1 @@ +tree_sitter diff --git a/venv/lib/python3.10/site-packages/triton/__pycache__/testing.cpython-310.pyc b/venv/lib/python3.10/site-packages/triton/__pycache__/testing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0db4c6c75502483e57eea8d9c85cd3dd2cae0887 Binary files /dev/null and b/venv/lib/python3.10/site-packages/triton/__pycache__/testing.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/triton/tools/__pycache__/compile.cpython-310.pyc b/venv/lib/python3.10/site-packages/triton/tools/__pycache__/compile.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dec3a50d4546f79e7c27730c77e6e3b51507e2be Binary files /dev/null and b/venv/lib/python3.10/site-packages/triton/tools/__pycache__/compile.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/triton/tools/__pycache__/disasm.cpython-310.pyc b/venv/lib/python3.10/site-packages/triton/tools/__pycache__/disasm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3ec2871665399de2444c53f036f7865e7400e2e Binary files /dev/null and b/venv/lib/python3.10/site-packages/triton/tools/__pycache__/disasm.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/triton/tools/__pycache__/link.cpython-310.pyc b/venv/lib/python3.10/site-packages/triton/tools/__pycache__/link.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17193ab53870428a9f5b718bb436e07cb831c9e2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/triton/tools/__pycache__/link.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/triton/tools/link.py b/venv/lib/python3.10/site-packages/triton/tools/link.py new file mode 100644 index 0000000000000000000000000000000000000000..75a1157a52f92bbd5d2eae640af97ea360da2ef3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/triton/tools/link.py @@ -0,0 +1,322 @@ +from collections import defaultdict +from pathlib import Path +from typing import Sequence, Union + +from dataclasses import dataclass + + +def _exists(x): + return x is not None + + +class LinkerError(Exception): + pass + + +@dataclass +class KernelLinkerMeta: + orig_kernel_name: str + arg_names: Sequence[str] + arg_ctypes: Sequence[str] + sizes: Sequence[Union[int, None]] + sig_hash: str + triton_suffix: str + suffix: str + num_specs: int + """ number of specialized arguments """ + + +class HeaderParser: + + def __init__(self) -> None: + import re + + # [kernel_name, c signature] + self.linker_directives = re.compile("//[\\s]*tt-linker:[\\s]*([\\w]+):(.+):(.+)") + # [name, hash, suffix] + self.kernel_name = re.compile("^([\\w]+)_([\\w]+)_([\\w]+)$") + # [(type, name)] + self.c_sig = re.compile("[\\s]*(\\w+)\\s(\\w+)[,]?") + # [d|c] + self.arg_suffix = re.compile("[c,d]") + + self.kernels = defaultdict(list) + + def extract_linker_meta(self, header: str): + for ln in header.splitlines(): + if ln.startswith("//"): + m = self.linker_directives.match(ln) + if _exists(m): + ker_name, c_sig, algo_info = m.group(1), m.group(2), m.group(3) + name, sig_hash, suffix = self._match_name(ker_name) + c_types, arg_names = self._match_c_sig(c_sig) + num_specs, sizes = self._match_suffix(suffix, c_sig) + self._add_kernel( + "_".join([name, algo_info]), + KernelLinkerMeta( + orig_kernel_name=name, + arg_names=arg_names, + arg_ctypes=c_types, + sizes=sizes, + sig_hash=sig_hash, + triton_suffix=suffix, + suffix=suffix, + num_specs=num_specs, + ), + ) + + def _match_name(self, ker_name: str): + m = self.kernel_name.match(ker_name) + if _exists(m): + name, sig_hash, suffix = m.group(1), m.group(2), m.group(3) + return name, sig_hash, suffix + raise LinkerError(f"{ker_name} is not a valid kernel name") + + def _match_c_sig(self, c_sig: str): + m = self.c_sig.findall(c_sig) + if len(m): + tys, args = [], [] + for ty, arg_name in m: + tys.append(ty) + args.append(arg_name) + return tys, args + + raise LinkerError(f"{c_sig} is not a valid argument signature") + + def _match_suffix(self, suffix: str, c_sig: str): + args = c_sig.split(",") + s2i = {"c": 1, "d": 16} + num_specs = 0 + sizes = [] + # scan through suffix, first find the index, + # then see if it is followed by d or c + for i in range(len(args)): + pos = suffix.find(str(i)) + if pos == -1: + raise LinkerError(f"{suffix} is not a valid kernel suffix") + pos += len(str(i)) + if self.arg_suffix.match(suffix, pos): + num_specs += 1 + sizes.extend([None] * (i - len(sizes))) + sizes.append(s2i[suffix[pos]]) + pos += 1 + if i < len(args) - 1: + suffix = suffix[pos:] + else: + sizes.extend([None] * (len(args) - len(sizes))) + return num_specs, sizes + + def _add_kernel(self, name: str, ker: KernelLinkerMeta): + if name in self.kernels: + last: KernelLinkerMeta = self.kernels[name][-1] + + for cur, new_ in zip(last.arg_ctypes, ker.arg_ctypes): + if cur != new_: + raise LinkerError( + f"Mismatched signature for kernel {name}: \n\texisting sig is: {','.join(last.arg_ctypes)}\n\tcurrent is: {','.join(ker.arg_ctypes)}" + ) + + self.kernels[name].append(ker) + + +def gen_signature_with_full_args(m): + return ", ".join([f"{ty} {arg}" for ty, arg in zip(m.arg_ctypes, m.arg_names)]) + + +def gen_signature(m): + arg_types = [ty for ty, hint in zip(m.arg_ctypes, m.sizes) if hint != 1] + arg_names = [arg for arg, hint in zip(m.arg_names, m.sizes) if hint != 1] + sig = ", ".join([f"{ty} {arg}" for ty, arg in zip(arg_types, arg_names)]) + return sig + + +# generate declarations of kernels with meta-parameter and constant values +def make_algo_decls(name: str, metas: Sequence[KernelLinkerMeta]) -> str: + return f""" +CUresult {name}(CUstream stream, {gen_signature_with_full_args(metas[-1])}); +void load_{name}(); +void unload_{name}(); + """ + + +# generate declarations of kernels with meta-parameter and constant values +def make_global_decl(meta: KernelLinkerMeta) -> str: + return f""" +CUresult {meta.orig_kernel_name}_default(CUstream stream, {gen_signature_with_full_args(meta)}); +CUresult {meta.orig_kernel_name}(CUstream stream, {gen_signature_with_full_args(meta)}, int algo_id); +void load_{meta.orig_kernel_name}(); +void unload_{meta.orig_kernel_name}(); + """ + + +# generate dispatcher function for kernels with different meta-parameter and constant values +def make_default_algo_kernel(meta: KernelLinkerMeta) -> str: + src = f"CUresult {meta.orig_kernel_name}_default(CUstream stream, {gen_signature_with_full_args(meta)}){{\n" + src += (f" return {meta.orig_kernel_name}(stream, {', '.join(meta.arg_names)}, 0);\n") + src += "}\n" + return src + + +# generate dispatcher function for kernels with different integer value hints +def make_kernel_hints_dispatcher(name: str, metas: Sequence[KernelLinkerMeta]) -> str: + src = f"// launcher for: {name}\n" + for meta in sorted(metas, key=lambda m: -m.num_specs): + src += f"CUresult {meta.orig_kernel_name}_{meta.sig_hash}_{meta.suffix}(CUstream stream, {gen_signature(meta)});\n" + src += "\n" + + src += (f"CUresult {name}(CUstream stream, {gen_signature_with_full_args(metas[-1])}){{") + src += "\n" + for meta in sorted(metas, key=lambda m: -m.num_specs): + cond_fn = ( # + lambda val, hint: f"({val} % {hint} == 0)" # + if hint == 16 # + else f"({val} == {hint})" # + if hint == 1 # + else None) + conds = " && ".join([ # + cond_fn(val, hint) # + for val, hint in zip(meta.arg_names, meta.sizes) # + if hint is not None + ]) + src += (f" if ({conds})\n" if any(meta.sizes) else "if (1)\n" + ) # Edge case where no specializations hence no dispatching required + arg_names = [arg for arg, hint in zip(meta.arg_names, meta.sizes) if hint != 1] + src += f" return {meta.orig_kernel_name}_{meta.sig_hash}_{meta.suffix}(stream, {', '.join(arg_names)});\n" + src += "\n" + src += " return CUDA_ERROR_INVALID_VALUE;\n" + src += "}\n" + + for mode in ["load", "unload"]: + src += f"\n// {mode} for: {name}\n" + for meta in sorted(metas, key=lambda m: -m.num_specs): + src += f"void {mode}_{meta.orig_kernel_name}_{meta.sig_hash}_{meta.suffix}();\n" + src += f"void {mode}_{name}() {{" + src += "\n" + for meta in sorted(metas, key=lambda m: -m.num_specs): + src += (f" {mode}_{meta.orig_kernel_name}_{meta.sig_hash}_{meta.suffix}();\n") + src += "}\n" + return src + + +# generate dispatcher function for kernels with different meta-parameter and constant values +def make_kernel_meta_const_dispatcher(meta: KernelLinkerMeta) -> str: + src = f"CUresult {meta.orig_kernel_name}(CUstream stream, {gen_signature_with_full_args(meta)}, int algo_id){{\n" + src += f" assert (algo_id < (int)sizeof({meta.orig_kernel_name}_kernels));\n" + src += f" return {meta.orig_kernel_name}_kernels[algo_id](stream, {', '.join(meta.arg_names)});\n" + src += "}\n" + return src + + +# generate definition of function pointers of kernel dispatchers based on meta-parameter and constant values +def make_func_pointers(names: str, meta: KernelLinkerMeta) -> str: + # the table of hint dispatchers + src = f"typedef CUresult (*kernel_func_t)(CUstream stream, {gen_signature_with_full_args(meta)});\n" + src += f"kernel_func_t {meta.orig_kernel_name}_kernels[] = {{\n" + for name in names: + src += f" {name},\n" + src += "};\n" + return src + + +# generate definition for load/unload functions for kernels with different meta-parameter and constant values +def make_kernel_load_def(names: str, meta: KernelLinkerMeta) -> str: + src = "" + for mode in ["load", "unload"]: + src += f"void {mode}_{meta.orig_kernel_name}(void){{\n" + for name in names: + src += f" {mode}_{name}();\n" + src += "}\n\n" + return src + + +def make_get_num_algos_decl(meta: KernelLinkerMeta) -> str: + src = f"int {meta.orig_kernel_name}_get_num_algos(void);" + return src + + +def make_get_num_algos_def(meta: KernelLinkerMeta) -> str: + src = f"int {meta.orig_kernel_name}_get_num_algos(void){{\n" + src += f" return (int)(sizeof({meta.orig_kernel_name}_kernels) / sizeof({meta.orig_kernel_name}_kernels[0]));\n" + src += "}\n" + return src + + +desc = """ +Triton ahead-of-time linker: + +This program takes in header files generated by compile.py, and generates a +single entry-point responsible for dispatching the user's input to the right +kernel given the specializations that were compiled. + +Example usage: +python link.py /path/to/headers/*.h -o kernel_name +""" + +if __name__ == "__main__": + from argparse import ArgumentParser + + parser = ArgumentParser(description=desc) + parser.add_argument( + "headers", + nargs="+", + help="Paths to header files to link. Must include linker directive annotations (autogenerated by ttc)", + ) + parser.add_argument("--out", "-o", type=Path, help="Out filename") + parser.add_argument( + "--prefix", + type=str, + default="", + help="String to prefix kernel dispatcher names", + ) + args = parser.parse_args() + + # metadata + parser = HeaderParser() + includes = [] + for header in args.headers: + h_path = Path(header) + h_str = h_path.read_text() + includes.append(h_path.name) + parser.extract_linker_meta(h_str) + + # generate headers + algo_decls = [make_algo_decls(name, meta) for name, meta in parser.kernels.items()] + meta_lists = [meta for name, meta in parser.kernels.items()] + meta = meta_lists[0][0] + get_num_algos_decl = make_get_num_algos_decl(meta) + global_decl = make_global_decl(meta) + with args.out.with_suffix(".h").open("w") as fp: + out = "#include \n" + out += "\n".join(algo_decls) + out += "\n" + out += get_num_algos_decl + out += "\n" + out += global_decl + fp.write(out) + + # generate source + defs = [make_kernel_hints_dispatcher(name, meta) for name, meta in parser.kernels.items()] + names = [name for name in parser.kernels.keys()] + func_pointers_def = make_func_pointers(names, meta) + meta_const_def = make_kernel_meta_const_dispatcher(meta) + load_unload_def = make_kernel_load_def(names, meta) + get_num_algos_def = make_get_num_algos_def(meta) + default_algo_kernel = make_default_algo_kernel(meta) + with args.out.with_suffix(".c").open("w") as fp: + out = "" + out += "#include \n" + out += "#include \n" + out += "#include \n" + out += "\n" + out += "\n".join(defs) + out += "\n" + out += func_pointers_def + out += "\n" + out += get_num_algos_def + out += "\n" + out += meta_const_def + out += "\n" + out += load_unload_def + out += "\n" + out += default_algo_kernel + fp.write(out) diff --git a/venv/lib/python3.10/site-packages/websockets/__init__.py b/venv/lib/python3.10/site-packages/websockets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f90aff5b958ab3a19ecbb3e5ccad676e3719d9ab --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/__init__.py @@ -0,0 +1,236 @@ +from __future__ import annotations + +# Importing the typing module would conflict with websockets.typing. +from typing import TYPE_CHECKING + +from .imports import lazy_import +from .version import version as __version__ # noqa: F401 + + +__all__ = [ + # .asyncio.client + "connect", + "unix_connect", + "ClientConnection", + # .asyncio.router + "route", + "unix_route", + "Router", + # .asyncio.server + "basic_auth", + "broadcast", + "serve", + "unix_serve", + "ServerConnection", + "Server", + # .client + "ClientProtocol", + # .datastructures + "Headers", + "HeadersLike", + "MultipleValuesError", + # .exceptions + "ConcurrencyError", + "ConnectionClosed", + "ConnectionClosedError", + "ConnectionClosedOK", + "DuplicateParameter", + "InvalidHandshake", + "InvalidHeader", + "InvalidHeaderFormat", + "InvalidHeaderValue", + "InvalidMessage", + "InvalidOrigin", + "InvalidParameterName", + "InvalidParameterValue", + "InvalidProxy", + "InvalidProxyMessage", + "InvalidProxyStatus", + "InvalidState", + "InvalidStatus", + "InvalidUpgrade", + "InvalidURI", + "NegotiationError", + "PayloadTooBig", + "ProtocolError", + "ProxyError", + "SecurityError", + "WebSocketException", + # .frames + "Close", + "CloseCode", + "Frame", + "Opcode", + # .http11 + "Request", + "Response", + # .protocol + "Protocol", + "Side", + "State", + # .server + "ServerProtocol", + # .typing + "Data", + "ExtensionName", + "ExtensionParameter", + "LoggerLike", + "StatusLike", + "Origin", + "Subprotocol", +] + +# When type checking, import non-deprecated aliases eagerly. Else, import on demand. +if TYPE_CHECKING: + from .asyncio.client import ClientConnection, connect, unix_connect + from .asyncio.router import Router, route, unix_route + from .asyncio.server import ( + Server, + ServerConnection, + basic_auth, + broadcast, + serve, + unix_serve, + ) + from .client import ClientProtocol + from .datastructures import Headers, HeadersLike, MultipleValuesError + from .exceptions import ( + ConcurrencyError, + ConnectionClosed, + ConnectionClosedError, + ConnectionClosedOK, + DuplicateParameter, + InvalidHandshake, + InvalidHeader, + InvalidHeaderFormat, + InvalidHeaderValue, + InvalidMessage, + InvalidOrigin, + InvalidParameterName, + InvalidParameterValue, + InvalidProxy, + InvalidProxyMessage, + InvalidProxyStatus, + InvalidState, + InvalidStatus, + InvalidUpgrade, + InvalidURI, + NegotiationError, + PayloadTooBig, + ProtocolError, + ProxyError, + SecurityError, + WebSocketException, + ) + from .frames import Close, CloseCode, Frame, Opcode + from .http11 import Request, Response + from .protocol import Protocol, Side, State + from .server import ServerProtocol + from .typing import ( + Data, + ExtensionName, + ExtensionParameter, + LoggerLike, + Origin, + StatusLike, + Subprotocol, + ) +else: + lazy_import( + globals(), + aliases={ + # .asyncio.client + "connect": ".asyncio.client", + "unix_connect": ".asyncio.client", + "ClientConnection": ".asyncio.client", + # .asyncio.router + "route": ".asyncio.router", + "unix_route": ".asyncio.router", + "Router": ".asyncio.router", + # .asyncio.server + "basic_auth": ".asyncio.server", + "broadcast": ".asyncio.server", + "serve": ".asyncio.server", + "unix_serve": ".asyncio.server", + "ServerConnection": ".asyncio.server", + "Server": ".asyncio.server", + # .client + "ClientProtocol": ".client", + # .datastructures + "Headers": ".datastructures", + "HeadersLike": ".datastructures", + "MultipleValuesError": ".datastructures", + # .exceptions + "ConcurrencyError": ".exceptions", + "ConnectionClosed": ".exceptions", + "ConnectionClosedError": ".exceptions", + "ConnectionClosedOK": ".exceptions", + "DuplicateParameter": ".exceptions", + "InvalidHandshake": ".exceptions", + "InvalidHeader": ".exceptions", + "InvalidHeaderFormat": ".exceptions", + "InvalidHeaderValue": ".exceptions", + "InvalidMessage": ".exceptions", + "InvalidOrigin": ".exceptions", + "InvalidParameterName": ".exceptions", + "InvalidParameterValue": ".exceptions", + "InvalidProxy": ".exceptions", + "InvalidProxyMessage": ".exceptions", + "InvalidProxyStatus": ".exceptions", + "InvalidState": ".exceptions", + "InvalidStatus": ".exceptions", + "InvalidUpgrade": ".exceptions", + "InvalidURI": ".exceptions", + "NegotiationError": ".exceptions", + "PayloadTooBig": ".exceptions", + "ProtocolError": ".exceptions", + "ProxyError": ".exceptions", + "SecurityError": ".exceptions", + "WebSocketException": ".exceptions", + # .frames + "Close": ".frames", + "CloseCode": ".frames", + "Frame": ".frames", + "Opcode": ".frames", + # .http11 + "Request": ".http11", + "Response": ".http11", + # .protocol + "Protocol": ".protocol", + "Side": ".protocol", + "State": ".protocol", + # .server + "ServerProtocol": ".server", + # .typing + "Data": ".typing", + "ExtensionName": ".typing", + "ExtensionParameter": ".typing", + "LoggerLike": ".typing", + "Origin": ".typing", + "StatusLike": ".typing", + "Subprotocol": ".typing", + }, + deprecated_aliases={ + # deprecated in 9.0 - 2021-09-01 + "framing": ".legacy", + "handshake": ".legacy", + "parse_uri": ".uri", + "WebSocketURI": ".uri", + # deprecated in 14.0 - 2024-11-09 + # .legacy.auth + "BasicAuthWebSocketServerProtocol": ".legacy.auth", + "basic_auth_protocol_factory": ".legacy.auth", + # .legacy.client + "WebSocketClientProtocol": ".legacy.client", + # .legacy.exceptions + "AbortHandshake": ".legacy.exceptions", + "InvalidStatusCode": ".legacy.exceptions", + "RedirectHandshake": ".legacy.exceptions", + "WebSocketProtocolError": ".legacy.exceptions", + # .legacy.protocol + "WebSocketCommonProtocol": ".legacy.protocol", + # .legacy.server + "WebSocketServer": ".legacy.server", + "WebSocketServerProtocol": ".legacy.server", + }, + ) diff --git a/venv/lib/python3.10/site-packages/websockets/__main__.py b/venv/lib/python3.10/site-packages/websockets/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..2f05ddc225577125ac018702cfe4de55a1aacd71 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/__main__.py @@ -0,0 +1,5 @@ +from .cli import main + + +if __name__ == "__main__": + main() diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f33aaa92881fde83dba122d045c33fc157aa99e2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/__main__.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50d1adf13baf059a6afd607c539456195eac81e0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/__main__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/auth.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/auth.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6a5ac5cc5867be4bc40d25dab1756c9fd09b78d Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/auth.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/cli.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/cli.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09aa558df9e2f2b14cdc4cea8cc37144f2d091d9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/cli.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/client.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/client.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d58a50c8dfda017b0973661cc56ea980b8c03ec Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/client.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/connection.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/connection.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..992f35d35db869872767cd4c8ad924435c527817 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/connection.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/datastructures.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/datastructures.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f0c1ea7c4977178b04e5101a74350316020e325 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/datastructures.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/exceptions.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7762007856d6faad1bc39152047d23d482987034 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/exceptions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/frames.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/frames.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e500e2929bbba761d4413c1a8816c88ba33ba12 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/frames.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/headers.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/headers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ba67caae8b7e1987f7f86690c955bac8d1af742 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/headers.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/http.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/http.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46fb5edef5bbe208ecccd8c2a8587edc9031362b Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/http.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/http11.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/http11.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ece88bb942b2a612c1a068919baf635a68589b3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/http11.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/imports.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/imports.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15533d667bc4e640ae6b8001ab25ff1e73b7cc2c Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/imports.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/protocol.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/protocol.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d27aa9662254ab4967b2ebfd62d39f001053b88e Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/protocol.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/server.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/server.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5e65ef0eacda8a80a136aa768d6277e1e2a44fa Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/server.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/streams.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/streams.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..250de0b736f8a09d328fa2effb8f33320bd4c433 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/streams.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/typing.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/typing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..739077fbf64fb833b29476259e827ee1cddff783 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/typing.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/uri.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/uri.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c20ad927a6665d8983fe2a05088be61ed7651b0c Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/uri.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d01ed6cec77279d0862404080eb6e116a5c65c8f Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/__pycache__/version.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/__pycache__/version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..666c92cc9c8d46a6cdc76d1868b16d5af42982bf Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/__pycache__/version.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/__init__.py b/venv/lib/python3.10/site-packages/websockets/asyncio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b061fd9535a5220bd409dea38d035d6189a36c7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/async_timeout.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/async_timeout.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62852444662da0244164a546636e3bdd8cc7c3a2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/async_timeout.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/client.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/client.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cab20fbac38753926d90370cd11b0d8fbbbcc3d Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/client.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16b5c40e5d84e1b4476a9ecbb61f8c5850ec6bc4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/connection.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/connection.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77adb48f7155f3e103d86f2288229f278df676b1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/connection.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/messages.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/messages.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c88121b38ddb4fe434f5702b0c9ed61e86744c6e Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/messages.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/router.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/router.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9721c660c344e7fc41756553ce99884792a4aee Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/router.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/server.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/server.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d40fbc3fa6a60cfef922e58aac578c0c74f83650 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/asyncio/__pycache__/server.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/async_timeout.py b/venv/lib/python3.10/site-packages/websockets/asyncio/async_timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..6ffa899695637829dd5d3c7b58c68683000fc35d --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/asyncio/async_timeout.py @@ -0,0 +1,282 @@ +# From https://github.com/aio-libs/async-timeout/blob/master/async_timeout/__init__.py +# Licensed under the Apache License (Apache-2.0) + +import asyncio +import enum +import sys +import warnings +from types import TracebackType +from typing import Optional, Type + + +if sys.version_info >= (3, 11): + from typing import final +else: + # From https://github.com/python/typing_extensions/blob/main/src/typing_extensions.py + # Licensed under the Python Software Foundation License (PSF-2.0) + + # @final exists in 3.8+, but we backport it for all versions + # before 3.11 to keep support for the __final__ attribute. + # See https://bugs.python.org/issue46342 + def final(f): + """This decorator can be used to indicate to type checkers that + the decorated method cannot be overridden, and decorated class + cannot be subclassed. For example: + + class Base: + @final + def done(self) -> None: + ... + class Sub(Base): + def done(self) -> None: # Error reported by type checker + ... + @final + class Leaf: + ... + class Other(Leaf): # Error reported by type checker + ... + + There is no runtime checking of these properties. The decorator + sets the ``__final__`` attribute to ``True`` on the decorated object + to allow runtime introspection. + """ + try: + f.__final__ = True + except (AttributeError, TypeError): + # Skip the attribute silently if it is not writable. + # AttributeError happens if the object has __slots__ or a + # read-only property, TypeError if it's a builtin class. + pass + return f + + # End https://github.com/python/typing_extensions/blob/main/src/typing_extensions.py + + +if sys.version_info >= (3, 11): + + def _uncancel_task(task: "asyncio.Task[object]") -> None: + task.uncancel() + +else: + + def _uncancel_task(task: "asyncio.Task[object]") -> None: + pass + + +__version__ = "4.0.3" + + +__all__ = ("timeout", "timeout_at", "Timeout") + + +def timeout(delay: Optional[float]) -> "Timeout": + """timeout context manager. + + Useful in cases when you want to apply timeout logic around block + of code or in cases when asyncio.wait_for is not suitable. For example: + + >>> async with timeout(0.001): + ... async with aiohttp.get('https://github.com') as r: + ... await r.text() + + + delay - value in seconds or None to disable timeout logic + """ + loop = asyncio.get_running_loop() + if delay is not None: + deadline = loop.time() + delay # type: Optional[float] + else: + deadline = None + return Timeout(deadline, loop) + + +def timeout_at(deadline: Optional[float]) -> "Timeout": + """Schedule the timeout at absolute time. + + deadline argument points on the time in the same clock system + as loop.time(). + + Please note: it is not POSIX time but a time with + undefined starting base, e.g. the time of the system power on. + + >>> async with timeout_at(loop.time() + 10): + ... async with aiohttp.get('https://github.com') as r: + ... await r.text() + + + """ + loop = asyncio.get_running_loop() + return Timeout(deadline, loop) + + +class _State(enum.Enum): + INIT = "INIT" + ENTER = "ENTER" + TIMEOUT = "TIMEOUT" + EXIT = "EXIT" + + +@final +class Timeout: + # Internal class, please don't instantiate it directly + # Use timeout() and timeout_at() public factories instead. + # + # Implementation note: `async with timeout()` is preferred + # over `with timeout()`. + # While technically the Timeout class implementation + # doesn't need to be async at all, + # the `async with` statement explicitly points that + # the context manager should be used from async function context. + # + # This design allows to avoid many silly misusages. + # + # TimeoutError is raised immediately when scheduled + # if the deadline is passed. + # The purpose is to time out as soon as possible + # without waiting for the next await expression. + + __slots__ = ("_deadline", "_loop", "_state", "_timeout_handler", "_task") + + def __init__( + self, deadline: Optional[float], loop: asyncio.AbstractEventLoop + ) -> None: + self._loop = loop + self._state = _State.INIT + + self._task: Optional["asyncio.Task[object]"] = None + self._timeout_handler = None # type: Optional[asyncio.Handle] + if deadline is None: + self._deadline = None # type: Optional[float] + else: + self.update(deadline) + + def __enter__(self) -> "Timeout": + warnings.warn( + "with timeout() is deprecated, use async with timeout() instead", + DeprecationWarning, + stacklevel=2, + ) + self._do_enter() + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> Optional[bool]: + self._do_exit(exc_type) + return None + + async def __aenter__(self) -> "Timeout": + self._do_enter() + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> Optional[bool]: + self._do_exit(exc_type) + return None + + @property + def expired(self) -> bool: + """Is timeout expired during execution?""" + return self._state == _State.TIMEOUT + + @property + def deadline(self) -> Optional[float]: + return self._deadline + + def reject(self) -> None: + """Reject scheduled timeout if any.""" + # cancel is maybe better name but + # task.cancel() raises CancelledError in asyncio world. + if self._state not in (_State.INIT, _State.ENTER): + raise RuntimeError(f"invalid state {self._state.value}") + self._reject() + + def _reject(self) -> None: + self._task = None + if self._timeout_handler is not None: + self._timeout_handler.cancel() + self._timeout_handler = None + + def shift(self, delay: float) -> None: + """Advance timeout on delay seconds. + + The delay can be negative. + + Raise RuntimeError if shift is called when deadline is not scheduled + """ + deadline = self._deadline + if deadline is None: + raise RuntimeError("cannot shift timeout if deadline is not scheduled") + self.update(deadline + delay) + + def update(self, deadline: float) -> None: + """Set deadline to absolute value. + + deadline argument points on the time in the same clock system + as loop.time(). + + If new deadline is in the past the timeout is raised immediately. + + Please note: it is not POSIX time but a time with + undefined starting base, e.g. the time of the system power on. + """ + if self._state == _State.EXIT: + raise RuntimeError("cannot reschedule after exit from context manager") + if self._state == _State.TIMEOUT: + raise RuntimeError("cannot reschedule expired timeout") + if self._timeout_handler is not None: + self._timeout_handler.cancel() + self._deadline = deadline + if self._state != _State.INIT: + self._reschedule() + + def _reschedule(self) -> None: + assert self._state == _State.ENTER + deadline = self._deadline + if deadline is None: + return + + now = self._loop.time() + if self._timeout_handler is not None: + self._timeout_handler.cancel() + + self._task = asyncio.current_task() + if deadline <= now: + self._timeout_handler = self._loop.call_soon(self._on_timeout) + else: + self._timeout_handler = self._loop.call_at(deadline, self._on_timeout) + + def _do_enter(self) -> None: + if self._state != _State.INIT: + raise RuntimeError(f"invalid state {self._state.value}") + self._state = _State.ENTER + self._reschedule() + + def _do_exit(self, exc_type: Optional[Type[BaseException]]) -> None: + if exc_type is asyncio.CancelledError and self._state == _State.TIMEOUT: + assert self._task is not None + _uncancel_task(self._task) + self._timeout_handler = None + self._task = None + raise asyncio.TimeoutError + # timeout has not expired + self._state = _State.EXIT + self._reject() + return None + + def _on_timeout(self) -> None: + assert self._task is not None + self._task.cancel() + self._state = _State.TIMEOUT + # drop the reference early + self._timeout_handler = None + + +# End https://github.com/aio-libs/async-timeout/blob/master/async_timeout/__init__.py diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/client.py b/venv/lib/python3.10/site-packages/websockets/asyncio/client.py new file mode 100644 index 0000000000000000000000000000000000000000..38a56ddda36ff8fea61b0e9b1b3c9b6bb0b07265 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/asyncio/client.py @@ -0,0 +1,820 @@ +from __future__ import annotations + +import asyncio +import logging +import os +import socket +import ssl as ssl_module +import traceback +import urllib.parse +from collections.abc import AsyncIterator, Generator, Sequence +from types import TracebackType +from typing import Any, Callable, Literal, cast + +from ..client import ClientProtocol, backoff +from ..datastructures import Headers, HeadersLike +from ..exceptions import ( + InvalidMessage, + InvalidProxyMessage, + InvalidProxyStatus, + InvalidStatus, + ProxyError, + SecurityError, +) +from ..extensions.base import ClientExtensionFactory +from ..extensions.permessage_deflate import enable_client_permessage_deflate +from ..headers import build_authorization_basic, build_host, validate_subprotocols +from ..http11 import USER_AGENT, Response +from ..protocol import CONNECTING, Event +from ..streams import StreamReader +from ..typing import LoggerLike, Origin, Subprotocol +from ..uri import Proxy, WebSocketURI, get_proxy, parse_proxy, parse_uri +from .compatibility import TimeoutError, asyncio_timeout +from .connection import Connection + + +__all__ = ["connect", "unix_connect", "ClientConnection"] + +MAX_REDIRECTS = int(os.environ.get("WEBSOCKETS_MAX_REDIRECTS", "10")) + + +class ClientConnection(Connection): + """ + :mod:`asyncio` implementation of a WebSocket client connection. + + :class:`ClientConnection` provides :meth:`recv` and :meth:`send` coroutines + for receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with close code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_queue``, + and ``write_limit`` arguments have the same meaning as in :func:`connect`. + + Args: + protocol: Sans-I/O connection. + + """ + + def __init__( + self, + protocol: ClientProtocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + ) -> None: + self.protocol: ClientProtocol + super().__init__( + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + self.response_rcvd: asyncio.Future[None] = self.loop.create_future() + + async def handshake( + self, + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + ) -> None: + """ + Perform the opening handshake. + + """ + async with self.send_context(expected_state=CONNECTING): + self.request = self.protocol.connect() + if additional_headers is not None: + self.request.headers.update(additional_headers) + if user_agent_header is not None: + self.request.headers.setdefault("User-Agent", user_agent_header) + self.protocol.send_request(self.request) + + await asyncio.wait( + [self.response_rcvd, self.connection_lost_waiter], + return_when=asyncio.FIRST_COMPLETED, + ) + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a response, when the response cannot be parsed, or when the + # response fails the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake response. + if self.response is None: + assert isinstance(event, Response) + self.response = event + self.response_rcvd.set_result(None) + # Later events - frames. + else: + super().process_event(event) + + +def process_exception(exc: Exception) -> Exception | None: + """ + Determine whether a connection error is retryable or fatal. + + When reconnecting automatically with ``async for ... in connect(...)``, if a + connection attempt fails, :func:`process_exception` is called to determine + whether to retry connecting or to raise the exception. + + This function defines the default behavior, which is to retry on: + + * :exc:`EOFError`, :exc:`OSError`, :exc:`asyncio.TimeoutError`: network + errors; + * :exc:`~websockets.exceptions.InvalidStatus` when the status code is 500, + 502, 503, or 504: server or proxy errors. + + All other exceptions are considered fatal. + + You can change this behavior with the ``process_exception`` argument of + :func:`connect`. + + Return :obj:`None` if the exception is retryable i.e. when the error could + be transient and trying to reconnect with the same parameters could succeed. + The exception will be logged at the ``INFO`` level. + + Return an exception, either ``exc`` or a new exception, if the exception is + fatal i.e. when trying to reconnect will most likely produce the same error. + That exception will be raised, breaking out of the retry loop. + + """ + # This catches python-socks' ProxyConnectionError and ProxyTimeoutError. + # Remove asyncio.TimeoutError when dropping Python < 3.11. + if isinstance(exc, (OSError, TimeoutError, asyncio.TimeoutError)): + return None + if isinstance(exc, InvalidMessage) and isinstance(exc.__cause__, EOFError): + return None + if isinstance(exc, InvalidStatus) and exc.response.status_code in [ + 500, # Internal Server Error + 502, # Bad Gateway + 503, # Service Unavailable + 504, # Gateway Timeout + ]: + return None + return exc + + +# This is spelled in lower case because it's exposed as a callable in the API. +class connect: + """ + Connect to the WebSocket server at ``uri``. + + This coroutine returns a :class:`ClientConnection` instance, which you can + use to send and receive messages. + + :func:`connect` may be used as an asynchronous context manager:: + + from websockets.asyncio.client import connect + + async with connect(...) as websocket: + ... + + The connection is closed automatically when exiting the context. + + :func:`connect` can be used as an infinite asynchronous iterator to + reconnect automatically on errors:: + + async for websocket in connect(...): + try: + ... + except websockets.exceptions.ConnectionClosed: + continue + + If the connection fails with a transient error, it is retried with + exponential backoff. If it fails with a fatal error, the exception is + raised, breaking out of the loop. + + The connection is closed automatically after each iteration of the loop. + + Args: + uri: URI of the WebSocket server. + origin: Value of the ``Origin`` header, for servers that require it. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + additional_headers (HeadersLike | None): Arbitrary HTTP headers to add + to the handshake request. + user_agent_header: Value of the ``User-Agent`` request header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + proxy: If a proxy is configured, it is used by default. Set ``proxy`` + to :obj:`None` to disable the proxy or to the address of a proxy + to override the system configuration. See the :doc:`proxy docs + <../../topics/proxies>` for details. + process_exception: When reconnecting automatically, tell whether an + error is transient or fatal. The default behavior is defined by + :func:`process_exception`. Refer to its documentation for details. + open_timeout: Timeout for opening the connection in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing the connection in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + write_limit: High-water mark of write buffer in bytes. It is passed to + :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults + to 32 KiB. You may pass a ``(high, low)`` tuple to set the + high-water and low-water marks. + logger: Logger for this client. + It defaults to ``logging.getLogger("websockets.client")``. + See the :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ClientConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to the event loop's + :meth:`~asyncio.loop.create_connection` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enforce TLS settings. + When connecting to a ``wss://`` URI, if ``ssl`` isn't provided, a TLS + context is created with :func:`~ssl.create_default_context`. + + * You can set ``server_hostname`` to override the host name from ``uri`` in + the TLS handshake. + + * You can set ``host`` and ``port`` to connect to a different host and port + from those found in ``uri``. This only changes the destination of the TCP + connection. The host name from ``uri`` is still used in the TLS handshake + for secure connections and in the ``Host`` header. + + * You can set ``sock`` to provide a preexisting TCP socket. You may call + :func:`socket.create_connection` (not to be confused with the event loop's + :meth:`~asyncio.loop.create_connection` method) to create a suitable + client socket and customize it. + + When using a proxy: + + * Prefix keyword arguments with ``proxy_`` for configuring TLS between the + client and an HTTPS proxy: ``proxy_ssl``, ``proxy_server_hostname``, + ``proxy_ssl_handshake_timeout``, and ``proxy_ssl_shutdown_timeout``. + * Use the standard keyword arguments for configuring TLS between the proxy + and the WebSocket server: ``ssl``, ``server_hostname``, + ``ssl_handshake_timeout``, and ``ssl_shutdown_timeout``. + * Other keyword arguments are used only for connecting to the proxy. + + Raises: + InvalidURI: If ``uri`` isn't a valid WebSocket URI. + InvalidProxy: If ``proxy`` isn't a valid proxy. + OSError: If the TCP connection fails. + InvalidHandshake: If the opening handshake fails. + TimeoutError: If the opening handshake times out. + + """ + + def __init__( + self, + uri: str, + *, + # WebSocket + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + compression: str | None = "deflate", + # HTTP + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + proxy: str | Literal[True] | None = True, + process_exception: Callable[[Exception], Exception | None] = process_exception, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ClientConnection] | None = None, + # Other keyword arguments are passed to loop.create_connection + **kwargs: Any, + ) -> None: + self.uri = uri + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_client_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if logger is None: + logger = logging.getLogger("websockets.client") + + if create_connection is None: + create_connection = ClientConnection + + def protocol_factory(uri: WebSocketURI) -> ClientConnection: + # This is a protocol in the Sans-I/O implementation of websockets. + protocol = ClientProtocol( + uri, + origin=origin, + extensions=extensions, + subprotocols=subprotocols, + max_size=max_size, + logger=logger, + ) + # This is a connection in websockets and a protocol in asyncio. + connection = create_connection( + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + return connection + + self.proxy = proxy + self.protocol_factory = protocol_factory + self.additional_headers = additional_headers + self.user_agent_header = user_agent_header + self.process_exception = process_exception + self.open_timeout = open_timeout + self.logger = logger + self.connection_kwargs = kwargs + + async def create_connection(self) -> ClientConnection: + """Create TCP or Unix connection.""" + loop = asyncio.get_running_loop() + kwargs = self.connection_kwargs.copy() + + ws_uri = parse_uri(self.uri) + + proxy = self.proxy + if kwargs.get("unix", False): + proxy = None + if kwargs.get("sock") is not None: + proxy = None + if proxy is True: + proxy = get_proxy(ws_uri) + + def factory() -> ClientConnection: + return self.protocol_factory(ws_uri) + + if ws_uri.secure: + kwargs.setdefault("ssl", True) + kwargs.setdefault("server_hostname", ws_uri.host) + if kwargs.get("ssl") is None: + raise ValueError("ssl=None is incompatible with a wss:// URI") + else: + if kwargs.get("ssl") is not None: + raise ValueError("ssl argument is incompatible with a ws:// URI") + + if kwargs.pop("unix", False): + _, connection = await loop.create_unix_connection(factory, **kwargs) + elif proxy is not None: + proxy_parsed = parse_proxy(proxy) + if proxy_parsed.scheme[:5] == "socks": + # Connect to the server through the proxy. + sock = await connect_socks_proxy( + proxy_parsed, + ws_uri, + local_addr=kwargs.pop("local_addr", None), + ) + # Initialize WebSocket connection via the proxy. + _, connection = await loop.create_connection( + factory, + sock=sock, + **kwargs, + ) + elif proxy_parsed.scheme[:4] == "http": + # Split keyword arguments between the proxy and the server. + all_kwargs, proxy_kwargs, kwargs = kwargs, {}, {} + for key, value in all_kwargs.items(): + if key.startswith("ssl") or key == "server_hostname": + kwargs[key] = value + elif key.startswith("proxy_"): + proxy_kwargs[key[6:]] = value + else: + proxy_kwargs[key] = value + # Validate the proxy_ssl argument. + if proxy_parsed.scheme == "https": + proxy_kwargs.setdefault("ssl", True) + if proxy_kwargs.get("ssl") is None: + raise ValueError( + "proxy_ssl=None is incompatible with an https:// proxy" + ) + else: + if proxy_kwargs.get("ssl") is not None: + raise ValueError( + "proxy_ssl argument is incompatible with an http:// proxy" + ) + # Connect to the server through the proxy. + transport = await connect_http_proxy( + proxy_parsed, + ws_uri, + user_agent_header=self.user_agent_header, + **proxy_kwargs, + ) + # Initialize WebSocket connection via the proxy. + connection = factory() + transport.set_protocol(connection) + ssl = kwargs.pop("ssl", None) + if ssl is True: + ssl = ssl_module.create_default_context() + if ssl is not None: + new_transport = await loop.start_tls( + transport, connection, ssl, **kwargs + ) + assert new_transport is not None # help mypy + transport = new_transport + connection.connection_made(transport) + else: + raise AssertionError("unsupported proxy") + else: + # Connect to the server directly. + if kwargs.get("sock") is None: + kwargs.setdefault("host", ws_uri.host) + kwargs.setdefault("port", ws_uri.port) + # Initialize WebSocket connection. + _, connection = await loop.create_connection(factory, **kwargs) + return connection + + def process_redirect(self, exc: Exception) -> Exception | str: + """ + Determine whether a connection error is a redirect that can be followed. + + Return the new URI if it's a valid redirect. Else, return an exception. + + """ + if not ( + isinstance(exc, InvalidStatus) + and exc.response.status_code + in [ + 300, # Multiple Choices + 301, # Moved Permanently + 302, # Found + 303, # See Other + 307, # Temporary Redirect + 308, # Permanent Redirect + ] + and "Location" in exc.response.headers + ): + return exc + + old_ws_uri = parse_uri(self.uri) + new_uri = urllib.parse.urljoin(self.uri, exc.response.headers["Location"]) + new_ws_uri = parse_uri(new_uri) + + # If connect() received a socket, it is closed and cannot be reused. + if self.connection_kwargs.get("sock") is not None: + return ValueError( + f"cannot follow redirect to {new_uri} with a preexisting socket" + ) + + # TLS downgrade is forbidden. + if old_ws_uri.secure and not new_ws_uri.secure: + return SecurityError(f"cannot follow redirect to non-secure URI {new_uri}") + + # Apply restrictions to cross-origin redirects. + if ( + old_ws_uri.secure != new_ws_uri.secure + or old_ws_uri.host != new_ws_uri.host + or old_ws_uri.port != new_ws_uri.port + ): + # Cross-origin redirects on Unix sockets don't quite make sense. + if self.connection_kwargs.get("unix", False): + return ValueError( + f"cannot follow cross-origin redirect to {new_uri} " + f"with a Unix socket" + ) + + # Cross-origin redirects when host and port are overridden are ill-defined. + if ( + self.connection_kwargs.get("host") is not None + or self.connection_kwargs.get("port") is not None + ): + return ValueError( + f"cannot follow cross-origin redirect to {new_uri} " + f"with an explicit host or port" + ) + + return new_uri + + # ... = await connect(...) + + def __await__(self) -> Generator[Any, None, ClientConnection]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> ClientConnection: + try: + async with asyncio_timeout(self.open_timeout): + for _ in range(MAX_REDIRECTS): + self.connection = await self.create_connection() + try: + await self.connection.handshake( + self.additional_headers, + self.user_agent_header, + ) + except asyncio.CancelledError: + self.connection.transport.abort() + raise + except Exception as exc: + # Always close the connection even though keep-alive is + # the default in HTTP/1.1 because create_connection ties + # opening the network connection with initializing the + # protocol. In the current design of connect(), there is + # no easy way to reuse the network connection that works + # in every case nor to reinitialize the protocol. + self.connection.transport.abort() + + uri_or_exc = self.process_redirect(exc) + # Response is a valid redirect; follow it. + if isinstance(uri_or_exc, str): + self.uri = uri_or_exc + continue + # Response isn't a valid redirect; raise the exception. + if uri_or_exc is exc: + raise + else: + raise uri_or_exc from exc + + else: + self.connection.start_keepalive() + return self.connection + else: + raise SecurityError(f"more than {MAX_REDIRECTS} redirects") + + except TimeoutError as exc: + # Re-raise exception with an informative error message. + raise TimeoutError("timed out during opening handshake") from exc + + # ... = yield from connect(...) - remove when dropping Python < 3.10 + + __iter__ = __await__ + + # async with connect(...) as ...: ... + + async def __aenter__(self) -> ClientConnection: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self.connection.close() + + # async for ... in connect(...): + + async def __aiter__(self) -> AsyncIterator[ClientConnection]: + delays: Generator[float] | None = None + while True: + try: + async with self as protocol: + yield protocol + except Exception as exc: + # Determine whether the exception is retryable or fatal. + # The API of process_exception is "return an exception or None"; + # "raise an exception" is also supported because it's a frequent + # mistake. It isn't documented in order to keep the API simple. + try: + new_exc = self.process_exception(exc) + except Exception as raised_exc: + new_exc = raised_exc + + # The connection failed with a fatal error. + # Raise the exception and exit the loop. + if new_exc is exc: + raise + if new_exc is not None: + raise new_exc from exc + + # The connection failed with a retryable error. + # Start or continue backoff and reconnect. + if delays is None: + delays = backoff() + delay = next(delays) + self.logger.info( + "connect failed; reconnecting in %.1f seconds: %s", + delay, + # Remove first argument when dropping Python 3.9. + traceback.format_exception_only(type(exc), exc)[0].strip(), + ) + await asyncio.sleep(delay) + continue + + else: + # The connection succeeded. Reset backoff. + delays = None + + +def unix_connect( + path: str | None = None, + uri: str | None = None, + **kwargs: Any, +) -> connect: + """ + Connect to a WebSocket server listening on a Unix socket. + + This function accepts the same keyword arguments as :func:`connect`. + + It's only available on Unix. + + It's mainly useful for debugging servers listening on Unix sockets. + + Args: + path: File system path to the Unix socket. + uri: URI of the WebSocket server. ``uri`` defaults to + ``ws://localhost/`` or, when a ``ssl`` argument is provided, to + ``wss://localhost/``. + + """ + if uri is None: + if kwargs.get("ssl") is None: + uri = "ws://localhost/" + else: + uri = "wss://localhost/" + return connect(uri=uri, unix=True, path=path, **kwargs) + + +try: + from python_socks import ProxyType + from python_socks.async_.asyncio import Proxy as SocksProxy + + SOCKS_PROXY_TYPES = { + "socks5h": ProxyType.SOCKS5, + "socks5": ProxyType.SOCKS5, + "socks4a": ProxyType.SOCKS4, + "socks4": ProxyType.SOCKS4, + } + + SOCKS_PROXY_RDNS = { + "socks5h": True, + "socks5": False, + "socks4a": True, + "socks4": False, + } + + async def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + **kwargs: Any, + ) -> socket.socket: + """Connect via a SOCKS proxy and return the socket.""" + socks_proxy = SocksProxy( + SOCKS_PROXY_TYPES[proxy.scheme], + proxy.host, + proxy.port, + proxy.username, + proxy.password, + SOCKS_PROXY_RDNS[proxy.scheme], + ) + # connect() is documented to raise OSError. + # socks_proxy.connect() doesn't raise TimeoutError; it gets canceled. + # Wrap other exceptions in ProxyError, a subclass of InvalidHandshake. + try: + return await socks_proxy.connect(ws_uri.host, ws_uri.port, **kwargs) + except OSError: + raise + except Exception as exc: + raise ProxyError("failed to connect to SOCKS proxy") from exc + +except ImportError: + + async def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + **kwargs: Any, + ) -> socket.socket: + raise ImportError("python-socks is required to use a SOCKS proxy") + + +def prepare_connect_request( + proxy: Proxy, + ws_uri: WebSocketURI, + user_agent_header: str | None = None, +) -> bytes: + host = build_host(ws_uri.host, ws_uri.port, ws_uri.secure, always_include_port=True) + headers = Headers() + headers["Host"] = build_host(ws_uri.host, ws_uri.port, ws_uri.secure) + if user_agent_header is not None: + headers["User-Agent"] = user_agent_header + if proxy.username is not None: + assert proxy.password is not None # enforced by parse_proxy() + headers["Proxy-Authorization"] = build_authorization_basic( + proxy.username, proxy.password + ) + # We cannot use the Request class because it supports only GET requests. + return f"CONNECT {host} HTTP/1.1\r\n".encode() + headers.serialize() + + +class HTTPProxyConnection(asyncio.Protocol): + def __init__( + self, + ws_uri: WebSocketURI, + proxy: Proxy, + user_agent_header: str | None = None, + ): + self.ws_uri = ws_uri + self.proxy = proxy + self.user_agent_header = user_agent_header + + self.reader = StreamReader() + self.parser = Response.parse( + self.reader.read_line, + self.reader.read_exact, + self.reader.read_to_eof, + include_body=False, + ) + + loop = asyncio.get_running_loop() + self.response: asyncio.Future[Response] = loop.create_future() + + def run_parser(self) -> None: + try: + next(self.parser) + except StopIteration as exc: + response = exc.value + if 200 <= response.status_code < 300: + self.response.set_result(response) + else: + self.response.set_exception(InvalidProxyStatus(response)) + except Exception as exc: + proxy_exc = InvalidProxyMessage( + "did not receive a valid HTTP response from proxy" + ) + proxy_exc.__cause__ = exc + self.response.set_exception(proxy_exc) + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + transport = cast(asyncio.Transport, transport) + self.transport = transport + self.transport.write( + prepare_connect_request(self.proxy, self.ws_uri, self.user_agent_header) + ) + + def data_received(self, data: bytes) -> None: + self.reader.feed_data(data) + self.run_parser() + + def eof_received(self) -> None: + self.reader.feed_eof() + self.run_parser() + + def connection_lost(self, exc: Exception | None) -> None: + self.reader.feed_eof() + if exc is not None: + self.response.set_exception(exc) + + +async def connect_http_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + user_agent_header: str | None = None, + **kwargs: Any, +) -> asyncio.Transport: + transport, protocol = await asyncio.get_running_loop().create_connection( + lambda: HTTPProxyConnection(ws_uri, proxy, user_agent_header), + proxy.host, + proxy.port, + **kwargs, + ) + + try: + # This raises exceptions if the connection to the proxy fails. + await protocol.response + except Exception: + transport.close() + raise + + return transport diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/compatibility.py b/venv/lib/python3.10/site-packages/websockets/asyncio/compatibility.py new file mode 100644 index 0000000000000000000000000000000000000000..e17000069d530bdde8de5194e0d8257a5c5d1770 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/asyncio/compatibility.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +import sys + + +__all__ = ["TimeoutError", "aiter", "anext", "asyncio_timeout", "asyncio_timeout_at"] + + +if sys.version_info[:2] >= (3, 11): + TimeoutError = TimeoutError + aiter = aiter + anext = anext + from asyncio import ( + timeout as asyncio_timeout, # noqa: F401 + timeout_at as asyncio_timeout_at, # noqa: F401 + ) + +else: # Python < 3.11 + from asyncio import TimeoutError + + def aiter(async_iterable): + return type(async_iterable).__aiter__(async_iterable) + + async def anext(async_iterator): + return await type(async_iterator).__anext__(async_iterator) + + from .async_timeout import ( + timeout as asyncio_timeout, # noqa: F401 + timeout_at as asyncio_timeout_at, # noqa: F401 + ) diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/connection.py b/venv/lib/python3.10/site-packages/websockets/asyncio/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..1b51e479186ef76e6a48096d1ede22b8c1d7cdcb --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/asyncio/connection.py @@ -0,0 +1,1237 @@ +from __future__ import annotations + +import asyncio +import collections +import contextlib +import logging +import random +import struct +import sys +import traceback +import uuid +from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Iterable, Mapping +from types import TracebackType +from typing import Any, Literal, cast, overload + +from ..exceptions import ( + ConcurrencyError, + ConnectionClosed, + ConnectionClosedOK, + ProtocolError, +) +from ..frames import DATA_OPCODES, BytesLike, CloseCode, Frame, Opcode +from ..http11 import Request, Response +from ..protocol import CLOSED, OPEN, Event, Protocol, State +from ..typing import Data, LoggerLike, Subprotocol +from .compatibility import ( + TimeoutError, + aiter, + anext, + asyncio_timeout, + asyncio_timeout_at, +) +from .messages import Assembler + + +__all__ = ["Connection"] + + +class Connection(asyncio.Protocol): + """ + :mod:`asyncio` implementation of a WebSocket connection. + + :class:`Connection` provides APIs shared between WebSocket servers and + clients. + + You shouldn't use it directly. Instead, use + :class:`~websockets.asyncio.client.ClientConnection` or + :class:`~websockets.asyncio.server.ServerConnection`. + + """ + + def __init__( + self, + protocol: Protocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + ) -> None: + self.protocol = protocol + self.ping_interval = ping_interval + self.ping_timeout = ping_timeout + self.close_timeout = close_timeout + if isinstance(max_queue, int) or max_queue is None: + max_queue = (max_queue, None) + self.max_queue = max_queue + if isinstance(write_limit, int): + write_limit = (write_limit, None) + self.write_limit = write_limit + + # Inject reference to this instance in the protocol's logger. + self.protocol.logger = logging.LoggerAdapter( + self.protocol.logger, + {"websocket": self}, + ) + + # Copy attributes from the protocol for convenience. + self.id: uuid.UUID = self.protocol.id + """Unique identifier of the connection. Useful in logs.""" + self.logger: LoggerLike = self.protocol.logger + """Logger for this connection.""" + self.debug = self.protocol.debug + + # HTTP handshake request and response. + self.request: Request | None = None + """Opening handshake request.""" + self.response: Response | None = None + """Opening handshake response.""" + + # Event loop running this connection. + self.loop = asyncio.get_running_loop() + + # Assembler turning frames into messages and serializing reads. + self.recv_messages: Assembler # initialized in connection_made + + # Deadline for the closing handshake. + self.close_deadline: float | None = None + + # Protect sending fragmented messages. + self.fragmented_send_waiter: asyncio.Future[None] | None = None + + # Mapping of ping IDs to pong waiters, in chronological order. + self.pong_waiters: dict[bytes, tuple[asyncio.Future[float], float]] = {} + + self.latency: float = 0 + """ + Latency of the connection, in seconds. + + Latency is defined as the round-trip time of the connection. It is + measured by sending a Ping frame and waiting for a matching Pong frame. + Before the first measurement, :attr:`latency` is ``0``. + + By default, websockets enables a :ref:`keepalive ` mechanism + that sends Ping frames automatically at regular intervals. You can also + send Ping frames and measure latency with :meth:`ping`. + """ + + # Task that sends keepalive pings. None when ping_interval is None. + self.keepalive_task: asyncio.Task[None] | None = None + + # Exception raised while reading from the connection, to be chained to + # ConnectionClosed in order to show why the TCP connection dropped. + self.recv_exc: BaseException | None = None + + # Completed when the TCP connection is closed and the WebSocket + # connection state becomes CLOSED. + self.connection_lost_waiter: asyncio.Future[None] = self.loop.create_future() + + # Adapted from asyncio.FlowControlMixin + self.paused: bool = False + self.drain_waiters: collections.deque[asyncio.Future[None]] = ( + collections.deque() + ) + + # Public attributes + + @property + def local_address(self) -> Any: + """ + Local address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getsockname`. + + """ + return self.transport.get_extra_info("sockname") + + @property + def remote_address(self) -> Any: + """ + Remote address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getpeername`. + + """ + return self.transport.get_extra_info("peername") + + @property + def state(self) -> State: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should call :meth:`~recv` or + :meth:`send` and handle :exc:`~websockets.exceptions.ConnectionClosed` + exceptions. + + """ + return self.protocol.state + + @property + def subprotocol(self) -> Subprotocol | None: + """ + Subprotocol negotiated during the opening handshake. + + :obj:`None` if no subprotocol was negotiated. + + """ + return self.protocol.subprotocol + + @property + def close_code(self) -> int | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_code + + @property + def close_reason(self) -> str | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_reason + + # Public methods + + async def __aenter__(self) -> Connection: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + if exc_type is None: + await self.close() + else: + await self.close(CloseCode.INTERNAL_ERROR) + + async def __aiter__(self) -> AsyncIterator[Data]: + """ + Iterate on incoming messages. + + The iterator calls :meth:`recv` and yields messages asynchronously in an + infinite loop. + + It exits when the connection is closed normally. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` exception after a + protocol error or a network failure. + + """ + try: + while True: + yield await self.recv() + except ConnectionClosedOK: + return + + @overload + async def recv(self, decode: Literal[True]) -> str: ... + + @overload + async def recv(self, decode: Literal[False]) -> bytes: ... + + @overload + async def recv(self, decode: bool | None = None) -> Data: ... + + async def recv(self, decode: bool | None = None) -> Data: + """ + Receive the next message. + + When the connection is closed, :meth:`recv` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises + :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal closure + and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. This is how you detect the end of the + message stream. + + Canceling :meth:`recv` is safe. There's no risk of losing data. The next + invocation of :meth:`recv` will return the next message. + + This makes it possible to enforce a timeout by wrapping :meth:`recv` in + :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`. + + When the message is fragmented, :meth:`recv` waits until all fragments + are received, reassembles them, and returns the whole message. + + Args: + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + A string (:class:`str`) for a Text_ frame or a bytestring + (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and + return a bytestring (:class:`bytes`). This improves performance + when decoding isn't needed, for example if the message contains + JSON and you're using a JSON library that expects a bytestring. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames + and return a string (:class:`str`). This may be useful for + servers that send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two coroutines call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + return await self.recv_messages.get(decode) + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv while another coroutine " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + async with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + await asyncio.shield(self.connection_lost_waiter) + raise self.protocol.close_exc from self.recv_exc + + @overload + def recv_streaming(self, decode: Literal[True]) -> AsyncIterator[str]: ... + + @overload + def recv_streaming(self, decode: Literal[False]) -> AsyncIterator[bytes]: ... + + @overload + def recv_streaming(self, decode: bool | None = None) -> AsyncIterator[Data]: ... + + async def recv_streaming(self, decode: bool | None = None) -> AsyncIterator[Data]: + """ + Receive the next message frame by frame. + + This method is designed for receiving fragmented messages. It returns an + asynchronous iterator that yields each fragment as it is received. This + iterator must be fully consumed. Else, future calls to :meth:`recv` or + :meth:`recv_streaming` will raise + :exc:`~websockets.exceptions.ConcurrencyError`, making the connection + unusable. + + :meth:`recv_streaming` raises the same exceptions as :meth:`recv`. + + Canceling :meth:`recv_streaming` before receiving the first frame is + safe. Canceling it after receiving one or more frames leaves the + iterator in a partially consumed state, making the connection unusable. + Instead, you should close the connection with :meth:`close`. + + Args: + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + An iterator of strings (:class:`str`) for a Text_ frame or + bytestrings (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames + and return bytestrings (:class:`bytes`). This may be useful to + optimize performance when decoding isn't needed. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames + and return strings (:class:`str`). This is useful for servers + that send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two coroutines call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + async for frame in self.recv_messages.get_iter(decode): + yield frame + return + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv_streaming while another coroutine " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + async with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + await asyncio.shield(self.connection_lost_waiter) + raise self.protocol.close_exc from self.recv_exc + + async def send( + self, + message: Data | Iterable[Data] | AsyncIterable[Data], + text: bool | None = None, + ) -> None: + """ + Send a message. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or + bytes-like object (:class:`bytes`, :class:`bytearray`, or + :class:`memoryview`) is sent as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``text`` argument: + + * Set ``text=True`` to send a bytestring or bytes-like object + (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) as a + Text_ frame. This improves performance when the message is already + UTF-8 encoded, for example if the message contains JSON and you're + using a JSON library that produces a bytestring. + * Set ``text=False`` to send a string (:class:`str`) in a Binary_ + frame. This may be useful for servers that expect binary frames + instead of text frames. + + :meth:`send` also accepts an iterable or an asynchronous iterable of + strings, bytestrings, or bytes-like objects to enable fragmentation_. + Each item is treated as a message fragment and sent in its own frame. + All items must be of the same type, or else :meth:`send` will raise a + :exc:`TypeError` and the connection will be closed. + + .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4 + + :meth:`send` rejects dict-like objects because this is often an error. + (If you really want to send the keys of a dict-like object as fragments, + call its :meth:`~dict.keys` method and pass the result to :meth:`send`.) + + Canceling :meth:`send` is discouraged. Instead, you should close the + connection with :meth:`close`. Indeed, there are only two situations + where :meth:`send` may yield control to the event loop and then get + canceled; in both cases, :meth:`close` has the same effect and is + more clear: + + 1. The write buffer is full. If you don't want to wait until enough + data is sent, your only alternative is to close the connection. + :meth:`close` will likely time out then abort the TCP connection. + 2. ``message`` is an asynchronous iterator that yields control. + Stopping in the middle of a fragmented message will cause a + protocol error and the connection will be closed. + + When the connection is closed, :meth:`send` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it + raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. + + Args: + message: Message to send. + + Raises: + ConnectionClosed: When the connection is closed. + TypeError: If ``message`` doesn't have a supported type. + + """ + # While sending a fragmented message, prevent sending other messages + # until all fragments are sent. + while self.fragmented_send_waiter is not None: + await asyncio.shield(self.fragmented_send_waiter) + + # Unfragmented message -- this case must be handled first because + # strings and bytes-like objects are iterable. + + if isinstance(message, str): + async with self.send_context(): + if text is False: + self.protocol.send_binary(message.encode()) + else: + self.protocol.send_text(message.encode()) + + elif isinstance(message, BytesLike): + async with self.send_context(): + if text is True: + self.protocol.send_text(message) + else: + self.protocol.send_binary(message) + + # Catch a common mistake -- passing a dict to send(). + + elif isinstance(message, Mapping): + raise TypeError("data is a dict-like object") + + # Fragmented message -- regular iterator. + + elif isinstance(message, Iterable): + chunks = iter(message) + try: + chunk = next(chunks) + except StopIteration: + return + + assert self.fragmented_send_waiter is None + self.fragmented_send_waiter = self.loop.create_future() + try: + # First fragment. + if isinstance(chunk, str): + async with self.send_context(): + if text is False: + self.protocol.send_binary(chunk.encode(), fin=False) + else: + self.protocol.send_text(chunk.encode(), fin=False) + encode = True + elif isinstance(chunk, BytesLike): + async with self.send_context(): + if text is True: + self.protocol.send_text(chunk, fin=False) + else: + self.protocol.send_binary(chunk, fin=False) + encode = False + else: + raise TypeError("iterable must contain bytes or str") + + # Other fragments + for chunk in chunks: + if isinstance(chunk, str) and encode: + async with self.send_context(): + self.protocol.send_continuation(chunk.encode(), fin=False) + elif isinstance(chunk, BytesLike) and not encode: + async with self.send_context(): + self.protocol.send_continuation(chunk, fin=False) + else: + raise TypeError("iterable must contain uniform types") + + # Final fragment. + async with self.send_context(): + self.protocol.send_continuation(b"", fin=True) + + except Exception: + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + async with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "error in fragmented message", + ) + raise + + finally: + self.fragmented_send_waiter.set_result(None) + self.fragmented_send_waiter = None + + # Fragmented message -- async iterator. + + elif isinstance(message, AsyncIterable): + achunks = aiter(message) + try: + chunk = await anext(achunks) + except StopAsyncIteration: + return + + assert self.fragmented_send_waiter is None + self.fragmented_send_waiter = self.loop.create_future() + try: + # First fragment. + if isinstance(chunk, str): + if text is False: + async with self.send_context(): + self.protocol.send_binary(chunk.encode(), fin=False) + else: + async with self.send_context(): + self.protocol.send_text(chunk.encode(), fin=False) + encode = True + elif isinstance(chunk, BytesLike): + if text is True: + async with self.send_context(): + self.protocol.send_text(chunk, fin=False) + else: + async with self.send_context(): + self.protocol.send_binary(chunk, fin=False) + encode = False + else: + raise TypeError("async iterable must contain bytes or str") + + # Other fragments + async for chunk in achunks: + if isinstance(chunk, str) and encode: + async with self.send_context(): + self.protocol.send_continuation(chunk.encode(), fin=False) + elif isinstance(chunk, BytesLike) and not encode: + async with self.send_context(): + self.protocol.send_continuation(chunk, fin=False) + else: + raise TypeError("async iterable must contain uniform types") + + # Final fragment. + async with self.send_context(): + self.protocol.send_continuation(b"", fin=True) + + except Exception: + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + async with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "error in fragmented message", + ) + raise + + finally: + self.fragmented_send_waiter.set_result(None) + self.fragmented_send_waiter = None + + else: + raise TypeError("data must be str, bytes, iterable, or async iterable") + + async def close(self, code: int = 1000, reason: str = "") -> None: + """ + Perform the closing handshake. + + :meth:`close` waits for the other end to complete the handshake and + for the TCP connection to terminate. + + :meth:`close` is idempotent: it doesn't do anything once the + connection is closed. + + Args: + code: WebSocket close code. + reason: WebSocket close reason. + + """ + try: + # The context manager takes care of waiting for the TCP connection + # to terminate after calling a method that sends a close frame. + async with self.send_context(): + if self.fragmented_send_waiter is not None: + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "close during fragmented message", + ) + else: + self.protocol.send_close(code, reason) + except ConnectionClosed: + # Ignore ConnectionClosed exceptions raised from send_context(). + # They mean that the connection is closed, which was the goal. + pass + + async def wait_closed(self) -> None: + """ + Wait until the connection is closed. + + :meth:`wait_closed` waits for the closing handshake to complete and for + the TCP connection to terminate. + + """ + await asyncio.shield(self.connection_lost_waiter) + + async def ping(self, data: Data | None = None) -> Awaitable[float]: + """ + Send a Ping_. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + A ping may serve as a keepalive or as a check that the remote endpoint + received all messages up to this point + + Args: + data: Payload of the ping. A :class:`str` will be encoded to UTF-8. + If ``data`` is :obj:`None`, the payload is four random bytes. + + Returns: + A future that will be completed when the corresponding pong is + received. You can ignore it if you don't intend to wait. The result + of the future is the latency of the connection in seconds. + + :: + + pong_waiter = await ws.ping() + # only if you want to wait for the corresponding pong + latency = await pong_waiter + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If another ping was sent with the same data and + the corresponding pong wasn't received yet. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + elif data is not None: + raise TypeError("data must be str or bytes-like") + + async with self.send_context(): + # Protect against duplicates if a payload is explicitly set. + if data in self.pong_waiters: + raise ConcurrencyError("already waiting for a pong with the same data") + + # Generate a unique random payload otherwise. + while data is None or data in self.pong_waiters: + data = struct.pack("!I", random.getrandbits(32)) + + pong_waiter = self.loop.create_future() + # The event loop's default clock is time.monotonic(). Its resolution + # is a bit low on Windows (~16ms). This is improved in Python 3.13. + self.pong_waiters[data] = (pong_waiter, self.loop.time()) + self.protocol.send_ping(data) + return pong_waiter + + async def pong(self, data: Data = b"") -> None: + """ + Send a Pong_. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + An unsolicited pong may serve as a unidirectional heartbeat. + + Args: + data: Payload of the pong. A :class:`str` will be encoded to UTF-8. + + Raises: + ConnectionClosed: When the connection is closed. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + else: + raise TypeError("data must be str or bytes-like") + + async with self.send_context(): + self.protocol.send_pong(data) + + # Private methods + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + This method is overridden in subclasses to handle the handshake. + + """ + assert isinstance(event, Frame) + if event.opcode in DATA_OPCODES: + self.recv_messages.put(event) + + if event.opcode is Opcode.PONG: + self.acknowledge_pings(bytes(event.data)) + + def acknowledge_pings(self, data: bytes) -> None: + """ + Acknowledge pings when receiving a pong. + + """ + # Ignore unsolicited pong. + if data not in self.pong_waiters: + return + + pong_timestamp = self.loop.time() + + # Sending a pong for only the most recent ping is legal. + # Acknowledge all previous pings too in that case. + ping_id = None + ping_ids = [] + for ping_id, (pong_waiter, ping_timestamp) in self.pong_waiters.items(): + ping_ids.append(ping_id) + latency = pong_timestamp - ping_timestamp + if not pong_waiter.done(): + pong_waiter.set_result(latency) + if ping_id == data: + self.latency = latency + break + else: + raise AssertionError("solicited pong not found in pings") + + # Remove acknowledged pings from self.pong_waiters. + for ping_id in ping_ids: + del self.pong_waiters[ping_id] + + def abort_pings(self) -> None: + """ + Raise ConnectionClosed in pending pings. + + They'll never receive a pong once the connection is closed. + + """ + assert self.protocol.state is CLOSED + exc = self.protocol.close_exc + + for pong_waiter, _ping_timestamp in self.pong_waiters.values(): + if not pong_waiter.done(): + pong_waiter.set_exception(exc) + # If the exception is never retrieved, it will be logged when ping + # is garbage-collected. This is confusing for users. + # Given that ping is done (with an exception), canceling it does + # nothing, but it prevents logging the exception. + pong_waiter.cancel() + + self.pong_waiters.clear() + + async def keepalive(self) -> None: + """ + Send a Ping frame and wait for a Pong frame at regular intervals. + + """ + assert self.ping_interval is not None + latency = 0.0 + try: + while True: + # If self.ping_timeout > latency > self.ping_interval, + # pings will be sent immediately after receiving pongs. + # The period will be longer than self.ping_interval. + await asyncio.sleep(self.ping_interval - latency) + + # This cannot raise ConnectionClosed when the connection is + # closing because ping(), via send_context(), waits for the + # connection to be closed before raising ConnectionClosed. + # However, connection_lost() cancels keepalive_task before + # it gets a chance to resume excuting. + pong_waiter = await self.ping() + if self.debug: + self.logger.debug("% sent keepalive ping") + + if self.ping_timeout is not None: + try: + async with asyncio_timeout(self.ping_timeout): + # connection_lost cancels keepalive immediately + # after setting a ConnectionClosed exception on + # pong_waiter. A CancelledError is raised here, + # not a ConnectionClosed exception. + latency = await pong_waiter + self.logger.debug("% received keepalive pong") + except asyncio.TimeoutError: + if self.debug: + self.logger.debug("- timed out waiting for keepalive pong") + async with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "keepalive ping timeout", + ) + raise AssertionError( + "send_context() should wait for connection_lost(), " + "which cancels keepalive()" + ) + except Exception: + self.logger.error("keepalive ping failed", exc_info=True) + + def start_keepalive(self) -> None: + """ + Run :meth:`keepalive` in a task, unless keepalive is disabled. + + """ + if self.ping_interval is not None: + self.keepalive_task = self.loop.create_task(self.keepalive()) + + @contextlib.asynccontextmanager + async def send_context( + self, + *, + expected_state: State = OPEN, # CONNECTING during the opening handshake + ) -> AsyncIterator[None]: + """ + Create a context for writing to the connection from user code. + + On entry, :meth:`send_context` checks that the connection is open; on + exit, it writes outgoing data to the socket:: + + async with self.send_context(): + self.protocol.send_text(message.encode()) + + When the connection isn't open on entry, when the connection is expected + to close on exit, or when an unexpected error happens, terminating the + connection, :meth:`send_context` waits until the connection is closed + then raises :exc:`~websockets.exceptions.ConnectionClosed`. + + """ + # Should we wait until the connection is closed? + wait_for_close = False + # Should we close the transport and raise ConnectionClosed? + raise_close_exc = False + # What exception should we chain ConnectionClosed to? + original_exc: BaseException | None = None + + if self.protocol.state is expected_state: + # Let the caller interact with the protocol. + try: + yield + except (ProtocolError, ConcurrencyError): + # The protocol state wasn't changed. Exit immediately. + raise + except Exception as exc: + self.logger.error("unexpected internal error", exc_info=True) + # This branch should never run. It's a safety net in case of + # bugs. Since we don't know what happened, we will close the + # connection and raise the exception to the caller. + wait_for_close = False + raise_close_exc = True + original_exc = exc + else: + # Check if the connection is expected to close soon. + if self.protocol.close_expected(): + wait_for_close = True + # If the connection is expected to close soon, set the + # close deadline based on the close timeout. + # Since we tested earlier that protocol.state was OPEN + # (or CONNECTING), self.close_deadline is still None. + if self.close_timeout is not None: + assert self.close_deadline is None + self.close_deadline = self.loop.time() + self.close_timeout + # Write outgoing data to the socket and enforce flow control. + try: + self.send_data() + await self.drain() + except Exception as exc: + if self.debug: + self.logger.debug("! error while sending data", exc_info=True) + # While the only expected exception here is OSError, + # other exceptions would be treated identically. + wait_for_close = False + raise_close_exc = True + original_exc = exc + + else: # self.protocol.state is not expected_state + # Minor layering violation: we assume that the connection + # will be closing soon if it isn't in the expected state. + wait_for_close = True + # Calculate close_deadline if it wasn't set yet. + if self.close_timeout is not None: + if self.close_deadline is None: + self.close_deadline = self.loop.time() + self.close_timeout + raise_close_exc = True + + # If the connection is expected to close soon and the close timeout + # elapses, close the socket to terminate the connection. + if wait_for_close: + try: + async with asyncio_timeout_at(self.close_deadline): + await asyncio.shield(self.connection_lost_waiter) + except TimeoutError: + # There's no risk to overwrite another error because + # original_exc is never set when wait_for_close is True. + assert original_exc is None + original_exc = TimeoutError("timed out while closing connection") + # Set recv_exc before closing the transport in order to get + # proper exception reporting. + raise_close_exc = True + self.set_recv_exc(original_exc) + + # If an error occurred, close the transport to terminate the connection and + # raise an exception. + if raise_close_exc: + self.transport.abort() + # Wait for the protocol state to be CLOSED before accessing close_exc. + await asyncio.shield(self.connection_lost_waiter) + raise self.protocol.close_exc from original_exc + + def send_data(self) -> None: + """ + Send outgoing data. + + Raises: + OSError: When a socket operations fails. + + """ + for data in self.protocol.data_to_send(): + if data: + self.transport.write(data) + else: + # Half-close the TCP connection when possible i.e. no TLS. + if self.transport.can_write_eof(): + if self.debug: + self.logger.debug("x half-closing TCP connection") + # write_eof() doesn't document which exceptions it raises. + # OSError is plausible. uvloop can raise RuntimeError here. + try: + self.transport.write_eof() + except (OSError, RuntimeError): # pragma: no cover + pass + # Else, close the TCP connection. + else: # pragma: no cover + if self.debug: + self.logger.debug("x closing TCP connection") + self.transport.close() + + def set_recv_exc(self, exc: BaseException | None) -> None: + """ + Set recv_exc, if not set yet. + + """ + if self.recv_exc is None: + self.recv_exc = exc + + # asyncio.Protocol methods + + # Connection callbacks + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + transport = cast(asyncio.Transport, transport) + self.recv_messages = Assembler( + *self.max_queue, + pause=transport.pause_reading, + resume=transport.resume_reading, + ) + transport.set_write_buffer_limits(*self.write_limit) + self.transport = transport + + def connection_lost(self, exc: Exception | None) -> None: + # Calling protocol.receive_eof() is safe because it's idempotent. + # This guarantees that the protocol state becomes CLOSED. + self.protocol.receive_eof() + assert self.protocol.state is CLOSED + + self.set_recv_exc(exc) + + # Abort recv() and pending pings with a ConnectionClosed exception. + self.recv_messages.close() + self.abort_pings() + + if self.keepalive_task is not None: + self.keepalive_task.cancel() + + # If self.connection_lost_waiter isn't pending, that's a bug, because: + # - it's set only here in connection_lost() which is called only once; + # - it must never be canceled. + self.connection_lost_waiter.set_result(None) + + # Adapted from asyncio.streams.FlowControlMixin + if self.paused: # pragma: no cover + self.paused = False + for waiter in self.drain_waiters: + if not waiter.done(): + if exc is None: + waiter.set_result(None) + else: + waiter.set_exception(exc) + + # Flow control callbacks + + def pause_writing(self) -> None: # pragma: no cover + # Adapted from asyncio.streams.FlowControlMixin + assert not self.paused + self.paused = True + + def resume_writing(self) -> None: # pragma: no cover + # Adapted from asyncio.streams.FlowControlMixin + assert self.paused + self.paused = False + for waiter in self.drain_waiters: + if not waiter.done(): + waiter.set_result(None) + + async def drain(self) -> None: # pragma: no cover + # We don't check if the connection is closed because we call drain() + # immediately after write() and write() would fail in that case. + + # Adapted from asyncio.streams.StreamWriter + # Yield to the event loop so that connection_lost() may be called. + if self.transport.is_closing(): + await asyncio.sleep(0) + + # Adapted from asyncio.streams.FlowControlMixin + if self.paused: + waiter = self.loop.create_future() + self.drain_waiters.append(waiter) + try: + await waiter + finally: + self.drain_waiters.remove(waiter) + + # Streaming protocol callbacks + + def data_received(self, data: bytes) -> None: + # Feed incoming data to the protocol. + self.protocol.receive_data(data) + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # Write outgoing data to the transport. + try: + self.send_data() + except Exception as exc: + if self.debug: + self.logger.debug("! error while sending data", exc_info=True) + self.set_recv_exc(exc) + + if self.protocol.close_expected(): + # If the connection is expected to close soon, set the + # close deadline based on the close timeout. + if self.close_timeout is not None: + if self.close_deadline is None: + self.close_deadline = self.loop.time() + self.close_timeout + + for event in events: + # This isn't expected to raise an exception. + self.process_event(event) + + def eof_received(self) -> None: + # Feed the end of the data stream to the connection. + self.protocol.receive_eof() + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # There is no error handling because send_data() can only write + # the end of the data stream here and it shouldn't raise errors. + self.send_data() + + # This code path is triggered when receiving an HTTP response + # without a Content-Length header. This is the only case where + # reading until EOF generates an event; all other events have + # a known length. Ignore for coverage measurement because tests + # are in test_client.py rather than test_connection.py. + for event in events: # pragma: no cover + # This isn't expected to raise an exception. + self.process_event(event) + + # The WebSocket protocol has its own closing handshake: endpoints close + # the TCP or TLS connection after sending and receiving a close frame. + # As a consequence, they never need to write after receiving EOF, so + # there's no reason to keep the transport open by returning True. + # Besides, that doesn't work on TLS connections. + + +# broadcast() is defined in the connection module even though it's primarily +# used by servers and documented in the server module because it works with +# client connections too and because it's easier to test together with the +# Connection class. + + +def broadcast( + connections: Iterable[Connection], + message: Data, + raise_exceptions: bool = False, +) -> None: + """ + Broadcast a message to several WebSocket connections. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or bytes-like + object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) is sent + as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + :func:`broadcast` pushes the message synchronously to all connections even + if their write buffers are overflowing. There's no backpressure. + + If you broadcast messages faster than a connection can handle them, messages + will pile up in its write buffer until the connection times out. Keep + ``ping_interval`` and ``ping_timeout`` low to prevent excessive memory usage + from slow connections. + + Unlike :meth:`~websockets.asyncio.connection.Connection.send`, + :func:`broadcast` doesn't support sending fragmented messages. Indeed, + fragmentation is useful for sending large messages without buffering them in + memory, while :func:`broadcast` buffers one copy per connection as fast as + possible. + + :func:`broadcast` skips connections that aren't open in order to avoid + errors on connections where the closing handshake is in progress. + + :func:`broadcast` ignores failures to write the message on some connections. + It continues writing to other connections. On Python 3.11 and above, you may + set ``raise_exceptions`` to :obj:`True` to record failures and raise all + exceptions in a :pep:`654` :exc:`ExceptionGroup`. + + While :func:`broadcast` makes more sense for servers, it works identically + with clients, if you have a use case for opening connections to many servers + and broadcasting a message to them. + + Args: + websockets: WebSocket connections to which the message will be sent. + message: Message to send. + raise_exceptions: Whether to raise an exception in case of failures. + + Raises: + TypeError: If ``message`` doesn't have a supported type. + + """ + if isinstance(message, str): + send_method = "send_text" + message = message.encode() + elif isinstance(message, BytesLike): + send_method = "send_binary" + else: + raise TypeError("data must be str or bytes") + + if raise_exceptions: + if sys.version_info[:2] < (3, 11): # pragma: no cover + raise ValueError("raise_exceptions requires at least Python 3.11") + exceptions: list[Exception] = [] + + for connection in connections: + exception: Exception + + if connection.protocol.state is not OPEN: + continue + + if connection.fragmented_send_waiter is not None: + if raise_exceptions: + exception = ConcurrencyError("sending a fragmented message") + exceptions.append(exception) + else: + connection.logger.warning( + "skipped broadcast: sending a fragmented message", + ) + continue + + try: + # Call connection.protocol.send_text or send_binary. + # Either way, message is already converted to bytes. + getattr(connection.protocol, send_method)(message) + connection.send_data() + except Exception as write_exception: + if raise_exceptions: + exception = RuntimeError("failed to write message") + exception.__cause__ = write_exception + exceptions.append(exception) + else: + connection.logger.warning( + "skipped broadcast: failed to write message: %s", + traceback.format_exception_only( + # Remove first argument when dropping Python 3.9. + type(write_exception), + write_exception, + )[0].strip(), + ) + + if raise_exceptions and exceptions: + raise ExceptionGroup("skipped broadcast", exceptions) + + +# Pretend that broadcast is actually defined in the server module. +broadcast.__module__ = "websockets.asyncio.server" diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/messages.py b/venv/lib/python3.10/site-packages/websockets/asyncio/messages.py new file mode 100644 index 0000000000000000000000000000000000000000..1fd41811c42f03caf3104d8f6e3352058acf4b2d --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/asyncio/messages.py @@ -0,0 +1,314 @@ +from __future__ import annotations + +import asyncio +import codecs +import collections +from collections.abc import AsyncIterator, Iterable +from typing import Any, Callable, Generic, Literal, TypeVar, overload + +from ..exceptions import ConcurrencyError +from ..frames import OP_BINARY, OP_CONT, OP_TEXT, Frame +from ..typing import Data + + +__all__ = ["Assembler"] + +UTF8Decoder = codecs.getincrementaldecoder("utf-8") + +T = TypeVar("T") + + +class SimpleQueue(Generic[T]): + """ + Simplified version of :class:`asyncio.Queue`. + + Provides only the subset of functionality needed by :class:`Assembler`. + + """ + + def __init__(self) -> None: + self.loop = asyncio.get_running_loop() + self.get_waiter: asyncio.Future[None] | None = None + self.queue: collections.deque[T] = collections.deque() + + def __len__(self) -> int: + return len(self.queue) + + def put(self, item: T) -> None: + """Put an item into the queue without waiting.""" + self.queue.append(item) + if self.get_waiter is not None and not self.get_waiter.done(): + self.get_waiter.set_result(None) + + async def get(self, block: bool = True) -> T: + """Remove and return an item from the queue, waiting if necessary.""" + if not self.queue: + if not block: + raise EOFError("stream of frames ended") + assert self.get_waiter is None, "cannot call get() concurrently" + self.get_waiter = self.loop.create_future() + try: + await self.get_waiter + finally: + self.get_waiter.cancel() + self.get_waiter = None + return self.queue.popleft() + + def reset(self, items: Iterable[T]) -> None: + """Put back items into an empty, idle queue.""" + assert self.get_waiter is None, "cannot reset() while get() is running" + assert not self.queue, "cannot reset() while queue isn't empty" + self.queue.extend(items) + + def abort(self) -> None: + """Close the queue, raising EOFError in get() if necessary.""" + if self.get_waiter is not None and not self.get_waiter.done(): + self.get_waiter.set_exception(EOFError("stream of frames ended")) + + +class Assembler: + """ + Assemble messages from frames. + + :class:`Assembler` expects only data frames. The stream of frames must + respect the protocol; if it doesn't, the behavior is undefined. + + Args: + pause: Called when the buffer of frames goes above the high water mark; + should pause reading from the network. + resume: Called when the buffer of frames goes below the low water mark; + should resume reading from the network. + + """ + + # coverage reports incorrectly: "line NN didn't jump to the function exit" + def __init__( # pragma: no cover + self, + high: int | None = None, + low: int | None = None, + pause: Callable[[], Any] = lambda: None, + resume: Callable[[], Any] = lambda: None, + ) -> None: + # Queue of incoming frames. + self.frames: SimpleQueue[Frame] = SimpleQueue() + + # We cannot put a hard limit on the size of the queue because a single + # call to Protocol.data_received() could produce thousands of frames, + # which must be buffered. Instead, we pause reading when the buffer goes + # above the high limit and we resume when it goes under the low limit. + if high is not None and low is None: + low = high // 4 + if high is None and low is not None: + high = low * 4 + if high is not None and low is not None: + if low < 0: + raise ValueError("low must be positive or equal to zero") + if high < low: + raise ValueError("high must be greater than or equal to low") + self.high, self.low = high, low + self.pause = pause + self.resume = resume + self.paused = False + + # This flag prevents concurrent calls to get() by user code. + self.get_in_progress = False + + # This flag marks the end of the connection. + self.closed = False + + @overload + async def get(self, decode: Literal[True]) -> str: ... + + @overload + async def get(self, decode: Literal[False]) -> bytes: ... + + @overload + async def get(self, decode: bool | None = None) -> Data: ... + + async def get(self, decode: bool | None = None) -> Data: + """ + Read the next message. + + :meth:`get` returns a single :class:`str` or :class:`bytes`. + + If the message is fragmented, :meth:`get` waits until the last frame is + received, then it reassembles the message and returns it. To receive + messages frame by frame, use :meth:`get_iter` instead. + + Args: + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + + """ + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get() fetches a complete message or is canceled. + + try: + # First frame + frame = await self.frames.get(not self.closed) + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + frames = [frame] + + # Following frames, for fragmented messages + while not frame.fin: + try: + frame = await self.frames.get(not self.closed) + except asyncio.CancelledError: + # Put frames already received back into the queue + # so that future calls to get() can return them. + self.frames.reset(frames) + raise + self.maybe_resume() + assert frame.opcode is OP_CONT + frames.append(frame) + + finally: + self.get_in_progress = False + + data = b"".join(frame.data for frame in frames) + if decode: + return data.decode() + else: + return data + + @overload + def get_iter(self, decode: Literal[True]) -> AsyncIterator[str]: ... + + @overload + def get_iter(self, decode: Literal[False]) -> AsyncIterator[bytes]: ... + + @overload + def get_iter(self, decode: bool | None = None) -> AsyncIterator[Data]: ... + + async def get_iter(self, decode: bool | None = None) -> AsyncIterator[Data]: + """ + Stream the next message. + + Iterating the return value of :meth:`get_iter` asynchronously yields a + :class:`str` or :class:`bytes` for each frame in the message. + + The iterator must be fully consumed before calling :meth:`get_iter` or + :meth:`get` again. Else, :exc:`ConcurrencyError` is raised. + + This method only makes sense for fragmented messages. If messages aren't + fragmented, use :meth:`get` instead. + + Args: + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + + """ + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get_iter() fetches a complete message or is canceled. + + # If get_iter() raises an exception e.g. in decoder.decode(), + # get_in_progress remains set and the connection becomes unusable. + + # First frame + try: + frame = await self.frames.get(not self.closed) + except asyncio.CancelledError: + self.get_in_progress = False + raise + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + if decode: + decoder = UTF8Decoder() + yield decoder.decode(frame.data, frame.fin) + else: + yield frame.data + + # Following frames, for fragmented messages + while not frame.fin: + # We cannot handle asyncio.CancelledError because we don't buffer + # previous fragments — we're streaming them. Canceling get_iter() + # here will leave the assembler in a stuck state. Future calls to + # get() or get_iter() will raise ConcurrencyError. + frame = await self.frames.get(not self.closed) + self.maybe_resume() + assert frame.opcode is OP_CONT + if decode: + yield decoder.decode(frame.data, frame.fin) + else: + yield frame.data + + self.get_in_progress = False + + def put(self, frame: Frame) -> None: + """ + Add ``frame`` to the next message. + + Raises: + EOFError: If the stream of frames has ended. + + """ + if self.closed: + raise EOFError("stream of frames ended") + + self.frames.put(frame) + self.maybe_pause() + + def maybe_pause(self) -> None: + """Pause the writer if queue is above the high water mark.""" + # Skip if flow control is disabled + if self.high is None: + return + + # Check for "> high" to support high = 0 + if len(self.frames) > self.high and not self.paused: + self.paused = True + self.pause() + + def maybe_resume(self) -> None: + """Resume the writer if queue is below the low water mark.""" + # Skip if flow control is disabled + if self.low is None: + return + + # Check for "<= low" to support low = 0 + if len(self.frames) <= self.low and self.paused: + self.paused = False + self.resume() + + def close(self) -> None: + """ + End the stream of frames. + + Calling :meth:`close` concurrently with :meth:`get`, :meth:`get_iter`, + or :meth:`put` is safe. They will raise :exc:`EOFError`. + + """ + if self.closed: + return + + self.closed = True + + # Unblock get() or get_iter(). + self.frames.abort() diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/router.py b/venv/lib/python3.10/site-packages/websockets/asyncio/router.py new file mode 100644 index 0000000000000000000000000000000000000000..047e7ef1c6913b90c97b78d2e43ada8f890d16ac --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/asyncio/router.py @@ -0,0 +1,198 @@ +from __future__ import annotations + +import http +import ssl as ssl_module +import urllib.parse +from typing import Any, Awaitable, Callable, Literal + +from werkzeug.exceptions import NotFound +from werkzeug.routing import Map, RequestRedirect + +from ..http11 import Request, Response +from .server import Server, ServerConnection, serve + + +__all__ = ["route", "unix_route", "Router"] + + +class Router: + """WebSocket router supporting :func:`route`.""" + + def __init__( + self, + url_map: Map, + server_name: str | None = None, + url_scheme: str = "ws", + ) -> None: + self.url_map = url_map + self.server_name = server_name + self.url_scheme = url_scheme + for rule in self.url_map.iter_rules(): + rule.websocket = True + + def get_server_name(self, connection: ServerConnection, request: Request) -> str: + if self.server_name is None: + return request.headers["Host"] + else: + return self.server_name + + def redirect(self, connection: ServerConnection, url: str) -> Response: + response = connection.respond(http.HTTPStatus.FOUND, f"Found at {url}") + response.headers["Location"] = url + return response + + def not_found(self, connection: ServerConnection) -> Response: + return connection.respond(http.HTTPStatus.NOT_FOUND, "Not Found") + + def route_request( + self, connection: ServerConnection, request: Request + ) -> Response | None: + """Route incoming request.""" + url_map_adapter = self.url_map.bind( + server_name=self.get_server_name(connection, request), + url_scheme=self.url_scheme, + ) + try: + parsed = urllib.parse.urlparse(request.path) + handler, kwargs = url_map_adapter.match( + path_info=parsed.path, + query_args=parsed.query, + ) + except RequestRedirect as redirect: + return self.redirect(connection, redirect.new_url) + except NotFound: + return self.not_found(connection) + connection.handler, connection.handler_kwargs = handler, kwargs + return None + + async def handler(self, connection: ServerConnection) -> None: + """Handle a connection.""" + return await connection.handler(connection, **connection.handler_kwargs) + + +def route( + url_map: Map, + *args: Any, + server_name: str | None = None, + ssl: ssl_module.SSLContext | Literal[True] | None = None, + create_router: type[Router] | None = None, + **kwargs: Any, +) -> Awaitable[Server]: + """ + Create a WebSocket server dispatching connections to different handlers. + + This feature requires the third-party library `werkzeug`_: + + .. code-block:: console + + $ pip install werkzeug + + .. _werkzeug: https://werkzeug.palletsprojects.com/ + + :func:`route` accepts the same arguments as + :func:`~websockets.sync.server.serve`, except as described below. + + The first argument is a :class:`werkzeug.routing.Map` that maps URL patterns + to connection handlers. In addition to the connection, handlers receive + parameters captured in the URL as keyword arguments. + + Here's an example:: + + + from websockets.asyncio.router import route + from werkzeug.routing import Map, Rule + + async def channel_handler(websocket, channel_id): + ... + + url_map = Map([ + Rule("/channel/", endpoint=channel_handler), + ... + ]) + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + async with route(url_map, ...) as server: + await stop + + + Refer to the documentation of :mod:`werkzeug.routing` for details. + + If you define redirects with ``Rule(..., redirect_to=...)`` in the URL map, + when the server runs behind a reverse proxy that modifies the ``Host`` + header or terminates TLS, you need additional configuration: + + * Set ``server_name`` to the name of the server as seen by clients. When not + provided, websockets uses the value of the ``Host`` header. + + * Set ``ssl=True`` to generate ``wss://`` URIs without actually enabling + TLS. Under the hood, this bind the URL map with a ``url_scheme`` of + ``wss://`` instead of ``ws://``. + + There is no need to specify ``websocket=True`` in each rule. It is added + automatically. + + Args: + url_map: Mapping of URL patterns to connection handlers. + server_name: Name of the server as seen by clients. If :obj:`None`, + websockets uses the value of the ``Host`` header. + ssl: Configuration for enabling TLS on the connection. Set it to + :obj:`True` if a reverse proxy terminates TLS connections. + create_router: Factory for the :class:`Router` dispatching requests to + handlers. Set it to a wrapper or a subclass to customize routing. + + """ + url_scheme = "ws" if ssl is None else "wss" + if ssl is not True and ssl is not None: + kwargs["ssl"] = ssl + + if create_router is None: + create_router = Router + + router = create_router(url_map, server_name, url_scheme) + + _process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = kwargs.pop("process_request", None) + if _process_request is None: + process_request: Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] = router.route_request + else: + + async def process_request( + connection: ServerConnection, request: Request + ) -> Response | None: + response = _process_request(connection, request) + if isinstance(response, Awaitable): + response = await response + if response is not None: + return response + return router.route_request(connection, request) + + return serve(router.handler, *args, process_request=process_request, **kwargs) + + +def unix_route( + url_map: Map, + path: str | None = None, + **kwargs: Any, +) -> Awaitable[Server]: + """ + Create a WebSocket Unix server dispatching connections to different handlers. + + :func:`unix_route` combines the behaviors of :func:`route` and + :func:`~websockets.asyncio.server.unix_serve`. + + Args: + url_map: Mapping of URL patterns to connection handlers. + path: File system path to the Unix socket. + + """ + return route(url_map, unix=True, path=path, **kwargs) diff --git a/venv/lib/python3.10/site-packages/websockets/asyncio/server.py b/venv/lib/python3.10/site-packages/websockets/asyncio/server.py new file mode 100644 index 0000000000000000000000000000000000000000..ec7fc4383ceef9ba9d72d0193ab8f55a90fd71bf --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/asyncio/server.py @@ -0,0 +1,981 @@ +from __future__ import annotations + +import asyncio +import hmac +import http +import logging +import re +import socket +import sys +from collections.abc import Awaitable, Generator, Iterable, Sequence +from types import TracebackType +from typing import Any, Callable, Mapping, cast + +from ..exceptions import InvalidHeader +from ..extensions.base import ServerExtensionFactory +from ..extensions.permessage_deflate import enable_server_permessage_deflate +from ..frames import CloseCode +from ..headers import ( + build_www_authenticate_basic, + parse_authorization_basic, + validate_subprotocols, +) +from ..http11 import SERVER, Request, Response +from ..protocol import CONNECTING, OPEN, Event +from ..server import ServerProtocol +from ..typing import LoggerLike, Origin, StatusLike, Subprotocol +from .compatibility import asyncio_timeout +from .connection import Connection, broadcast + + +__all__ = [ + "broadcast", + "serve", + "unix_serve", + "ServerConnection", + "Server", + "basic_auth", +] + + +class ServerConnection(Connection): + """ + :mod:`asyncio` implementation of a WebSocket server connection. + + :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for + receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with close code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_queue``, + and ``write_limit`` arguments have the same meaning as in :func:`serve`. + + Args: + protocol: Sans-I/O connection. + server: Server that manages this connection. + + """ + + def __init__( + self, + protocol: ServerProtocol, + server: Server, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + ) -> None: + self.protocol: ServerProtocol + super().__init__( + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + self.server = server + self.request_rcvd: asyncio.Future[None] = self.loop.create_future() + self.username: str # see basic_auth() + self.handler: Callable[[ServerConnection], Awaitable[None]] # see route() + self.handler_kwargs: Mapping[str, Any] # see route() + + def respond(self, status: StatusLike, text: str) -> Response: + """ + Create a plain text HTTP response. + + ``process_request`` and ``process_response`` may call this method to + return an HTTP response instead of performing the WebSocket opening + handshake. + + You can modify the response before returning it, for example by changing + HTTP headers. + + Args: + status: HTTP status code. + text: HTTP response body; it will be encoded to UTF-8. + + Returns: + HTTP response to send to the client. + + """ + return self.protocol.reject(status, text) + + async def handshake( + self, + process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + ) -> None: + """ + Perform the opening handshake. + + """ + await asyncio.wait( + [self.request_rcvd, self.connection_lost_waiter], + return_when=asyncio.FIRST_COMPLETED, + ) + + if self.request is not None: + async with self.send_context(expected_state=CONNECTING): + response = None + + if process_request is not None: + try: + response = process_request(self, self.request) + if isinstance(response, Awaitable): + response = await response + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is None: + if self.server.is_serving(): + self.response = self.protocol.accept(self.request) + else: + self.response = self.protocol.reject( + http.HTTPStatus.SERVICE_UNAVAILABLE, + "Server is shutting down.\n", + ) + else: + assert isinstance(response, Response) # help mypy + self.response = response + + if server_header: + self.response.headers["Server"] = server_header + + response = None + + if process_response is not None: + try: + response = process_response(self, self.request, self.response) + if isinstance(response, Awaitable): + response = await response + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is not None: + assert isinstance(response, Response) # help mypy + self.response = response + + self.protocol.send_response(self.response) + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a request, when the request cannot be parsed, or when the + # handshake fails, including when process_request or process_response + # raises an exception. + + # It isn't set when process_request or process_response sends an HTTP + # response that rejects the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake request. + if self.request is None: + assert isinstance(event, Request) + self.request = event + self.request_rcvd.set_result(None) + # Later events - frames. + else: + super().process_event(event) + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + super().connection_made(transport) + self.server.start_connection_handler(self) + + +class Server: + """ + WebSocket server returned by :func:`serve`. + + This class mirrors the API of :class:`asyncio.Server`. + + It keeps track of WebSocket connections in order to close them properly + when shutting down. + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + process_request: Intercept the request during the opening handshake. + Return an HTTP response to force the response. Return :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + ``process_request`` may be a function or a coroutine. + process_response: Intercept the response during the opening handshake. + Modify the response or return a new HTTP response to force the + response. Return :obj:`None` to continue normally. When you force an + HTTP 101 Continue response, the handshake is successful. Else, the + connection is aborted. ``process_response`` may be a function or a + coroutine. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to + :obj:`None` removes the header. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__( + self, + handler: Callable[[ServerConnection], Awaitable[None]], + *, + process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + open_timeout: float | None = 10, + logger: LoggerLike | None = None, + ) -> None: + self.loop = asyncio.get_running_loop() + self.handler = handler + self.process_request = process_request + self.process_response = process_response + self.server_header = server_header + self.open_timeout = open_timeout + if logger is None: + logger = logging.getLogger("websockets.server") + self.logger = logger + + # Keep track of active connections. + self.handlers: dict[ServerConnection, asyncio.Task[None]] = {} + + # Task responsible for closing the server and terminating connections. + self.close_task: asyncio.Task[None] | None = None + + # Completed when the server is closed and connections are terminated. + self.closed_waiter: asyncio.Future[None] = self.loop.create_future() + + @property + def connections(self) -> set[ServerConnection]: + """ + Set of active connections. + + This property contains all connections that completed the opening + handshake successfully and didn't start the closing handshake yet. + It can be useful in combination with :func:`~broadcast`. + + """ + return {connection for connection in self.handlers if connection.state is OPEN} + + def wrap(self, server: asyncio.Server) -> None: + """ + Attach to a given :class:`asyncio.Server`. + + Since :meth:`~asyncio.loop.create_server` doesn't support injecting a + custom ``Server`` class, the easiest solution that doesn't rely on + private :mod:`asyncio` APIs is to: + + - instantiate a :class:`Server` + - give the protocol factory a reference to that instance + - call :meth:`~asyncio.loop.create_server` with the factory + - attach the resulting :class:`asyncio.Server` with this method + + """ + self.server = server + for sock in server.sockets: + if sock.family == socket.AF_INET: + name = "%s:%d" % sock.getsockname() + elif sock.family == socket.AF_INET6: + name = "[%s]:%d" % sock.getsockname()[:2] + elif sock.family == socket.AF_UNIX: + name = sock.getsockname() + # In the unlikely event that someone runs websockets over a + # protocol other than IP or Unix sockets, avoid crashing. + else: # pragma: no cover + name = str(sock.getsockname()) + self.logger.info("server listening on %s", name) + + async def conn_handler(self, connection: ServerConnection) -> None: + """ + Handle the lifecycle of a WebSocket connection. + + Since this method doesn't have a caller that can handle exceptions, + it attempts to log relevant ones. + + It guarantees that the TCP connection is closed before exiting. + + """ + try: + async with asyncio_timeout(self.open_timeout): + try: + await connection.handshake( + self.process_request, + self.process_response, + self.server_header, + ) + except asyncio.CancelledError: + connection.transport.abort() + raise + except Exception: + connection.logger.error("opening handshake failed", exc_info=True) + connection.transport.abort() + return + + if connection.protocol.state is not OPEN: + # process_request or process_response rejected the handshake. + connection.transport.abort() + return + + try: + connection.start_keepalive() + await self.handler(connection) + except Exception: + connection.logger.error("connection handler failed", exc_info=True) + await connection.close(CloseCode.INTERNAL_ERROR) + else: + await connection.close() + + except TimeoutError: + # When the opening handshake times out, there's nothing to log. + pass + + except Exception: # pragma: no cover + # Don't leak connections on unexpected errors. + connection.transport.abort() + + finally: + # Registration is tied to the lifecycle of conn_handler() because + # the server waits for connection handlers to terminate, even if + # all connections are already closed. + del self.handlers[connection] + + def start_connection_handler(self, connection: ServerConnection) -> None: + """ + Register a connection with this server. + + """ + # The connection must be registered in self.handlers immediately. + # If it was registered in conn_handler(), a race condition could + # happen when closing the server after scheduling conn_handler() + # but before it starts executing. + self.handlers[connection] = self.loop.create_task(self.conn_handler(connection)) + + def close(self, close_connections: bool = True) -> None: + """ + Close the server. + + * Close the underlying :class:`asyncio.Server`. + * When ``close_connections`` is :obj:`True`, which is the default, + close existing connections. Specifically: + + * Reject opening WebSocket connections with an HTTP 503 (service + unavailable) error. This happens when the server accepted the TCP + connection but didn't complete the opening handshake before closing. + * Close open WebSocket connections with close code 1001 (going away). + + * Wait until all connection handlers terminate. + + :meth:`close` is idempotent. + + """ + if self.close_task is None: + self.close_task = self.get_loop().create_task( + self._close(close_connections) + ) + + async def _close(self, close_connections: bool) -> None: + """ + Implementation of :meth:`close`. + + This calls :meth:`~asyncio.Server.close` on the underlying + :class:`asyncio.Server` object to stop accepting new connections and + then closes open connections with close code 1001. + + """ + self.logger.info("server closing") + + # Stop accepting new connections. + self.server.close() + + # Wait until all accepted connections reach connection_made() and call + # register(). See https://github.com/python/cpython/issues/79033 for + # details. This workaround can be removed when dropping Python < 3.11. + await asyncio.sleep(0) + + if close_connections: + # Close OPEN connections with close code 1001. After server.close(), + # handshake() closes OPENING connections with an HTTP 503 error. + close_tasks = [ + asyncio.create_task(connection.close(1001)) + for connection in self.handlers + if connection.protocol.state is not CONNECTING + ] + # asyncio.wait doesn't accept an empty first argument. + if close_tasks: + await asyncio.wait(close_tasks) + + # Wait until all TCP connections are closed. + await self.server.wait_closed() + + # Wait until all connection handlers terminate. + # asyncio.wait doesn't accept an empty first argument. + if self.handlers: + await asyncio.wait(self.handlers.values()) + + # Tell wait_closed() to return. + self.closed_waiter.set_result(None) + + self.logger.info("server closed") + + async def wait_closed(self) -> None: + """ + Wait until the server is closed. + + When :meth:`wait_closed` returns, all TCP connections are closed and + all connection handlers have returned. + + To ensure a fast shutdown, a connection handler should always be + awaiting at least one of: + + * :meth:`~ServerConnection.recv`: when the connection is closed, + it raises :exc:`~websockets.exceptions.ConnectionClosedOK`; + * :meth:`~ServerConnection.wait_closed`: when the connection is + closed, it returns. + + Then the connection handler is immediately notified of the shutdown; + it can clean up and exit. + + """ + await asyncio.shield(self.closed_waiter) + + def get_loop(self) -> asyncio.AbstractEventLoop: + """ + See :meth:`asyncio.Server.get_loop`. + + """ + return self.server.get_loop() + + def is_serving(self) -> bool: # pragma: no cover + """ + See :meth:`asyncio.Server.is_serving`. + + """ + return self.server.is_serving() + + async def start_serving(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.start_serving`. + + Typical use:: + + server = await serve(..., start_serving=False) + # perform additional setup here... + # ... then start the server + await server.start_serving() + + """ + await self.server.start_serving() + + async def serve_forever(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.serve_forever`. + + Typical use:: + + server = await serve(...) + # this coroutine doesn't return + # canceling it stops the server + await server.serve_forever() + + This is an alternative to using :func:`serve` as an asynchronous context + manager. Shutdown is triggered by canceling :meth:`serve_forever` + instead of exiting a :func:`serve` context. + + """ + await self.server.serve_forever() + + @property + def sockets(self) -> Iterable[socket.socket]: + """ + See :attr:`asyncio.Server.sockets`. + + """ + return self.server.sockets + + async def __aenter__(self) -> Server: # pragma: no cover + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: # pragma: no cover + self.close() + await self.wait_closed() + + +# This is spelled in lower case because it's exposed as a callable in the API. +class serve: + """ + Create a WebSocket server listening on ``host`` and ``port``. + + Whenever a client connects, the server creates a :class:`ServerConnection`, + performs the opening handshake, and delegates to the ``handler`` coroutine. + + The handler receives the :class:`ServerConnection` instance, which you can + use to send and receive messages. + + Once the handler completes, either normally or with an exception, the server + performs the closing handshake and closes the connection. + + This coroutine returns a :class:`Server` whose API mirrors + :class:`asyncio.Server`. Treat it as an asynchronous context manager to + ensure that the server will be closed:: + + from websockets.asyncio.server import serve + + def handler(websocket): + ... + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + async with serve(handler, host, port): + await stop + + Alternatively, call :meth:`~Server.serve_forever` to serve requests and + cancel it to stop the server:: + + server = await serve(handler, host, port) + await server.serve_forever() + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + host: Network interfaces the server binds to. + See :meth:`~asyncio.loop.create_server` for details. + port: TCP port the server listens on. + See :meth:`~asyncio.loop.create_server` for details. + origins: Acceptable values of the ``Origin`` header, for defending + against Cross-Site WebSocket Hijacking attacks. Values can be + :class:`str` to test for an exact match or regular expressions + compiled by :func:`re.compile` to test against a pattern. Include + :obj:`None` in the list if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + select_subprotocol: Callback for selecting a subprotocol among + those supported by the client and the server. It receives a + :class:`ServerConnection` (not a + :class:`~websockets.server.ServerProtocol`!) instance and a list of + subprotocols offered by the client. Other than the first argument, + it has the same behavior as the + :meth:`ServerProtocol.select_subprotocol + ` method. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + process_request: Intercept the request during the opening handshake. + Return an HTTP response to force the response or :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + ``process_request`` may be a function or a coroutine. + process_response: Intercept the response during the opening handshake. + Return an HTTP response to force the response or :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + ``process_response`` may be a function or a coroutine. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to + :obj:`None` removes the header. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing connections in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + write_limit: High-water mark of write buffer in bytes. It is passed to + :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults + to 32 KiB. You may pass a ``(high, low)`` tuple to set the + high-water and low-water marks. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. See the + :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ServerConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to the event loop's + :meth:`~asyncio.loop.create_server` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS. + + * You can set ``sock`` to provide a preexisting TCP socket. You may call + :func:`socket.create_server` (not to be confused with the event loop's + :meth:`~asyncio.loop.create_server` method) to create a suitable server + socket and customize it. + + * You can set ``start_serving`` to ``False`` to start accepting connections + only after you call :meth:`~Server.start_serving()` or + :meth:`~Server.serve_forever()`. + + """ + + def __init__( + self, + handler: Callable[[ServerConnection], Awaitable[None]], + host: str | None = None, + port: int | None = None, + *, + # WebSocket + origins: Sequence[Origin | re.Pattern[str] | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + select_subprotocol: ( + Callable[ + [ServerConnection, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None, + compression: str | None = "deflate", + # HTTP + process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ServerConnection] | None = None, + # Other keyword arguments are passed to loop.create_server + **kwargs: Any, + ) -> None: + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_server_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if create_connection is None: + create_connection = ServerConnection + + self.server = Server( + handler, + process_request=process_request, + process_response=process_response, + server_header=server_header, + open_timeout=open_timeout, + logger=logger, + ) + + if kwargs.get("ssl") is not None: + kwargs.setdefault("ssl_handshake_timeout", open_timeout) + if sys.version_info[:2] >= (3, 11): # pragma: no branch + kwargs.setdefault("ssl_shutdown_timeout", close_timeout) + + def factory() -> ServerConnection: + """ + Create an asyncio protocol for managing a WebSocket connection. + + """ + # Create a closure to give select_subprotocol access to connection. + protocol_select_subprotocol: ( + Callable[ + [ServerProtocol, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None + if select_subprotocol is not None: + + def protocol_select_subprotocol( + protocol: ServerProtocol, + subprotocols: Sequence[Subprotocol], + ) -> Subprotocol | None: + # mypy doesn't know that select_subprotocol is immutable. + assert select_subprotocol is not None + # Ensure this function is only used in the intended context. + assert protocol is connection.protocol + return select_subprotocol(connection, subprotocols) + + # This is a protocol in the Sans-I/O implementation of websockets. + protocol = ServerProtocol( + origins=origins, + extensions=extensions, + subprotocols=subprotocols, + select_subprotocol=protocol_select_subprotocol, + max_size=max_size, + logger=logger, + ) + # This is a connection in websockets and a protocol in asyncio. + connection = create_connection( + protocol, + self.server, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + return connection + + loop = asyncio.get_running_loop() + if kwargs.pop("unix", False): + self.create_server = loop.create_unix_server(factory, **kwargs) + else: + # mypy cannot tell that kwargs must provide sock when port is None. + self.create_server = loop.create_server(factory, host, port, **kwargs) # type: ignore[arg-type] + + # async with serve(...) as ...: ... + + async def __aenter__(self) -> Server: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.server.close() + await self.server.wait_closed() + + # ... = await serve(...) + + def __await__(self) -> Generator[Any, None, Server]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> Server: + server = await self.create_server + self.server.wrap(server) + return self.server + + # ... = yield from serve(...) - remove when dropping Python < 3.10 + + __iter__ = __await__ + + +def unix_serve( + handler: Callable[[ServerConnection], Awaitable[None]], + path: str | None = None, + **kwargs: Any, +) -> Awaitable[Server]: + """ + Create a WebSocket server listening on a Unix socket. + + This function is identical to :func:`serve`, except the ``host`` and + ``port`` arguments are replaced by ``path``. It's only available on Unix. + + It's useful for deploying a server behind a reverse proxy such as nginx. + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + path: File system path to the Unix socket. + + """ + return serve(handler, unix=True, path=path, **kwargs) + + +def is_credentials(credentials: Any) -> bool: + try: + username, password = credentials + except (TypeError, ValueError): + return False + else: + return isinstance(username, str) and isinstance(password, str) + + +def basic_auth( + realm: str = "", + credentials: tuple[str, str] | Iterable[tuple[str, str]] | None = None, + check_credentials: Callable[[str, str], Awaitable[bool] | bool] | None = None, +) -> Callable[[ServerConnection, Request], Awaitable[Response | None]]: + """ + Factory for ``process_request`` to enforce HTTP Basic Authentication. + + :func:`basic_auth` is designed to integrate with :func:`serve` as follows:: + + from websockets.asyncio.server import basic_auth, serve + + async with serve( + ..., + process_request=basic_auth( + realm="my dev server", + credentials=("hello", "iloveyou"), + ), + ): + + If authentication succeeds, the connection's ``username`` attribute is set. + If it fails, the server responds with an HTTP 401 Unauthorized status. + + One of ``credentials`` or ``check_credentials`` must be provided; not both. + + Args: + realm: Scope of protection. It should contain only ASCII characters + because the encoding of non-ASCII characters is undefined. Refer to + section 2.2 of :rfc:`7235` for details. + credentials: Hard coded authorized credentials. It can be a + ``(username, password)`` pair or a list of such pairs. + check_credentials: Function or coroutine that verifies credentials. + It receives ``username`` and ``password`` arguments and returns + whether they're valid. + Raises: + TypeError: If ``credentials`` or ``check_credentials`` is wrong. + ValueError: If ``credentials`` and ``check_credentials`` are both + provided or both not provided. + + """ + if (credentials is None) == (check_credentials is None): + raise ValueError("provide either credentials or check_credentials") + + if credentials is not None: + if is_credentials(credentials): + credentials_list = [cast(tuple[str, str], credentials)] + elif isinstance(credentials, Iterable): + credentials_list = list(cast(Iterable[tuple[str, str]], credentials)) + if not all(is_credentials(item) for item in credentials_list): + raise TypeError(f"invalid credentials argument: {credentials}") + else: + raise TypeError(f"invalid credentials argument: {credentials}") + + credentials_dict = dict(credentials_list) + + def check_credentials(username: str, password: str) -> bool: + try: + expected_password = credentials_dict[username] + except KeyError: + return False + return hmac.compare_digest(expected_password, password) + + assert check_credentials is not None # help mypy + + async def process_request( + connection: ServerConnection, + request: Request, + ) -> Response | None: + """ + Perform HTTP Basic Authentication. + + If it succeeds, set the connection's ``username`` attribute and return + :obj:`None`. If it fails, return an HTTP 401 Unauthorized responss. + + """ + try: + authorization = request.headers["Authorization"] + except KeyError: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Missing credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + try: + username, password = parse_authorization_basic(authorization) + except InvalidHeader: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Unsupported credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + valid_credentials = check_credentials(username, password) + if isinstance(valid_credentials, Awaitable): + valid_credentials = await valid_credentials + + if not valid_credentials: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Invalid credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + connection.username = username + return None + + return process_request diff --git a/venv/lib/python3.10/site-packages/websockets/auth.py b/venv/lib/python3.10/site-packages/websockets/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..15b70a3727b2eb3202fc87173ad2fc8b742cf72c --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/auth.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +import warnings + + +with warnings.catch_warnings(): + # Suppress redundant DeprecationWarning raised by websockets.legacy. + warnings.filterwarnings("ignore", category=DeprecationWarning) + from .legacy.auth import * + from .legacy.auth import __all__ # noqa: F401 + + +warnings.warn( # deprecated in 14.0 - 2024-11-09 + "websockets.auth, an alias for websockets.legacy.auth, is deprecated; " + "see https://websockets.readthedocs.io/en/stable/howto/upgrade.html " + "for upgrade instructions", + DeprecationWarning, +) diff --git a/venv/lib/python3.10/site-packages/websockets/cli.py b/venv/lib/python3.10/site-packages/websockets/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..e084b62a9ac250a7b20a1b7a7a18fe10e53db3a6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/cli.py @@ -0,0 +1,178 @@ +from __future__ import annotations + +import argparse +import asyncio +import os +import sys +from typing import Generator + +from .asyncio.client import ClientConnection, connect +from .asyncio.messages import SimpleQueue +from .exceptions import ConnectionClosed +from .frames import Close +from .streams import StreamReader +from .version import version as websockets_version + + +__all__ = ["main"] + + +def print_during_input(string: str) -> None: + sys.stdout.write( + # Save cursor position + "\N{ESC}7" + # Add a new line + "\N{LINE FEED}" + # Move cursor up + "\N{ESC}[A" + # Insert blank line, scroll last line down + "\N{ESC}[L" + # Print string in the inserted blank line + f"{string}\N{LINE FEED}" + # Restore cursor position + "\N{ESC}8" + # Move cursor down + "\N{ESC}[B" + ) + sys.stdout.flush() + + +def print_over_input(string: str) -> None: + sys.stdout.write( + # Move cursor to beginning of line + "\N{CARRIAGE RETURN}" + # Delete current line + "\N{ESC}[K" + # Print string + f"{string}\N{LINE FEED}" + ) + sys.stdout.flush() + + +class ReadLines(asyncio.Protocol): + def __init__(self) -> None: + self.reader = StreamReader() + self.messages: SimpleQueue[str] = SimpleQueue() + + def parse(self) -> Generator[None, None, None]: + while True: + sys.stdout.write("> ") + sys.stdout.flush() + line = yield from self.reader.read_line(sys.maxsize) + self.messages.put(line.decode().rstrip("\r\n")) + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + self.parser = self.parse() + next(self.parser) + + def data_received(self, data: bytes) -> None: + self.reader.feed_data(data) + next(self.parser) + + def eof_received(self) -> None: + self.reader.feed_eof() + # next(self.parser) isn't useful and would raise EOFError. + + def connection_lost(self, exc: Exception | None) -> None: + self.reader.discard() + self.messages.abort() + + +async def print_incoming_messages(websocket: ClientConnection) -> None: + async for message in websocket: + if isinstance(message, str): + print_during_input("< " + message) + else: + print_during_input("< (binary) " + message.hex()) + + +async def send_outgoing_messages( + websocket: ClientConnection, + messages: SimpleQueue[str], +) -> None: + while True: + try: + message = await messages.get() + except EOFError: + break + try: + await websocket.send(message) + except ConnectionClosed: # pragma: no cover + break + + +async def interactive_client(uri: str) -> None: + try: + websocket = await connect(uri) + except Exception as exc: + print(f"Failed to connect to {uri}: {exc}.") + sys.exit(1) + else: + print(f"Connected to {uri}.") + + loop = asyncio.get_running_loop() + transport, protocol = await loop.connect_read_pipe(ReadLines, sys.stdin) + incoming = asyncio.create_task( + print_incoming_messages(websocket), + ) + outgoing = asyncio.create_task( + send_outgoing_messages(websocket, protocol.messages), + ) + try: + await asyncio.wait( + [incoming, outgoing], + # Clean up and exit when the server closes the connection + # or the user enters EOT (^D), whichever happens first. + return_when=asyncio.FIRST_COMPLETED, + ) + # asyncio.run() cancels the main task when the user triggers SIGINT (^C). + # https://docs.python.org/3/library/asyncio-runner.html#handling-keyboard-interruption + # Clean up and exit without re-raising CancelledError to prevent Python + # from raising KeyboardInterrupt and displaying a stack track. + except asyncio.CancelledError: # pragma: no cover + pass + finally: + incoming.cancel() + outgoing.cancel() + transport.close() + + await websocket.close() + assert websocket.close_code is not None and websocket.close_reason is not None + close_status = Close(websocket.close_code, websocket.close_reason) + print_over_input(f"Connection closed: {close_status}.") + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser( + prog="websockets", + description="Interactive WebSocket client.", + add_help=False, + ) + group = parser.add_mutually_exclusive_group() + group.add_argument("--version", action="store_true") + group.add_argument("uri", metavar="", nargs="?") + args = parser.parse_args(argv) + + if args.version: + print(f"websockets {websockets_version}") + return + + if args.uri is None: + parser.print_usage() + sys.exit(2) + + # Enable VT100 to support ANSI escape codes in Command Prompt on Windows. + # See https://github.com/python/cpython/issues/74261 for why this works. + if sys.platform == "win32": + os.system("") + + try: + import readline # noqa: F401 + except ImportError: # readline isn't available on all platforms + pass + + # Remove the try/except block when dropping Python < 3.11. + try: + asyncio.run(interactive_client(args.uri)) + except KeyboardInterrupt: # pragma: no cover + pass diff --git a/venv/lib/python3.10/site-packages/websockets/client.py b/venv/lib/python3.10/site-packages/websockets/client.py new file mode 100644 index 0000000000000000000000000000000000000000..9ea21c39c650513dfef24731c9e3eac89232f650 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/client.py @@ -0,0 +1,389 @@ +from __future__ import annotations + +import os +import random +import warnings +from collections.abc import Generator, Sequence +from typing import Any + +from .datastructures import Headers, MultipleValuesError +from .exceptions import ( + InvalidHandshake, + InvalidHeader, + InvalidHeaderValue, + InvalidMessage, + InvalidStatus, + InvalidUpgrade, + NegotiationError, +) +from .extensions import ClientExtensionFactory, Extension +from .headers import ( + build_authorization_basic, + build_extension, + build_host, + build_subprotocol, + parse_connection, + parse_extension, + parse_subprotocol, + parse_upgrade, +) +from .http11 import Request, Response +from .imports import lazy_import +from .protocol import CLIENT, CONNECTING, OPEN, Protocol, State +from .typing import ( + ConnectionOption, + ExtensionHeader, + LoggerLike, + Origin, + Subprotocol, + UpgradeProtocol, +) +from .uri import WebSocketURI +from .utils import accept_key, generate_key + + +__all__ = ["ClientProtocol"] + + +class ClientProtocol(Protocol): + """ + Sans-I/O implementation of a WebSocket client connection. + + Args: + uri: URI of the WebSocket server, parsed + with :func:`~websockets.uri.parse_uri`. + origin: Value of the ``Origin`` header. This is useful when connecting + to a server that validates the ``Origin`` header to defend against + Cross-Site WebSocket Hijacking attacks. + extensions: List of supported extensions, in order in which they + should be tried. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + state: Initial state of the WebSocket connection. + max_size: Maximum size of incoming messages in bytes; + :obj:`None` disables the limit. + logger: Logger for this connection; + defaults to ``logging.getLogger("websockets.client")``; + see the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__( + self, + uri: WebSocketURI, + *, + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + state: State = CONNECTING, + max_size: int | None = 2**20, + logger: LoggerLike | None = None, + ) -> None: + super().__init__( + side=CLIENT, + state=state, + max_size=max_size, + logger=logger, + ) + self.uri = uri + self.origin = origin + self.available_extensions = extensions + self.available_subprotocols = subprotocols + self.key = generate_key() + + def connect(self) -> Request: + """ + Create a handshake request to open a connection. + + You must send the handshake request with :meth:`send_request`. + + You can modify it before sending it, for example to add HTTP headers. + + Returns: + WebSocket handshake request event to send to the server. + + """ + headers = Headers() + headers["Host"] = build_host(self.uri.host, self.uri.port, self.uri.secure) + if self.uri.user_info: + headers["Authorization"] = build_authorization_basic(*self.uri.user_info) + if self.origin is not None: + headers["Origin"] = self.origin + headers["Upgrade"] = "websocket" + headers["Connection"] = "Upgrade" + headers["Sec-WebSocket-Key"] = self.key + headers["Sec-WebSocket-Version"] = "13" + if self.available_extensions is not None: + headers["Sec-WebSocket-Extensions"] = build_extension( + [ + (extension_factory.name, extension_factory.get_request_params()) + for extension_factory in self.available_extensions + ] + ) + if self.available_subprotocols is not None: + headers["Sec-WebSocket-Protocol"] = build_subprotocol( + self.available_subprotocols + ) + return Request(self.uri.resource_name, headers) + + def process_response(self, response: Response) -> None: + """ + Check a handshake response. + + Args: + request: WebSocket handshake response received from the server. + + Raises: + InvalidHandshake: If the handshake response is invalid. + + """ + + if response.status_code != 101: + raise InvalidStatus(response) + + headers = response.headers + + connection: list[ConnectionOption] = sum( + [parse_connection(value) for value in headers.get_all("Connection")], [] + ) + if not any(value.lower() == "upgrade" for value in connection): + raise InvalidUpgrade( + "Connection", ", ".join(connection) if connection else None + ) + + upgrade: list[UpgradeProtocol] = sum( + [parse_upgrade(value) for value in headers.get_all("Upgrade")], [] + ) + # For compatibility with non-strict implementations, ignore case when + # checking the Upgrade header. It's supposed to be 'WebSocket'. + if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): + raise InvalidUpgrade("Upgrade", ", ".join(upgrade) if upgrade else None) + + try: + s_w_accept = headers["Sec-WebSocket-Accept"] + except KeyError: + raise InvalidHeader("Sec-WebSocket-Accept") from None + except MultipleValuesError: + raise InvalidHeader("Sec-WebSocket-Accept", "multiple values") from None + if s_w_accept != accept_key(self.key): + raise InvalidHeaderValue("Sec-WebSocket-Accept", s_w_accept) + + self.extensions = self.process_extensions(headers) + self.subprotocol = self.process_subprotocol(headers) + + def process_extensions(self, headers: Headers) -> list[Extension]: + """ + Handle the Sec-WebSocket-Extensions HTTP response header. + + Check that each extension is supported, as well as its parameters. + + :rfc:`6455` leaves the rules up to the specification of each + extension. + + To provide this level of flexibility, for each extension accepted by + the server, we check for a match with each extension available in the + client configuration. If no match is found, an exception is raised. + + If several variants of the same extension are accepted by the server, + it may be configured several times, which won't make sense in general. + Extensions must implement their own requirements. For this purpose, + the list of previously accepted extensions is provided. + + Other requirements, for example related to mandatory extensions or the + order of extensions, may be implemented by overriding this method. + + Args: + headers: WebSocket handshake response headers. + + Returns: + List of accepted extensions. + + Raises: + InvalidHandshake: To abort the handshake. + + """ + accepted_extensions: list[Extension] = [] + + extensions = headers.get_all("Sec-WebSocket-Extensions") + + if extensions: + if self.available_extensions is None: + raise NegotiationError("no extensions supported") + + parsed_extensions: list[ExtensionHeader] = sum( + [parse_extension(header_value) for header_value in extensions], [] + ) + + for name, response_params in parsed_extensions: + for extension_factory in self.available_extensions: + # Skip non-matching extensions based on their name. + if extension_factory.name != name: + continue + + # Skip non-matching extensions based on their params. + try: + extension = extension_factory.process_response_params( + response_params, accepted_extensions + ) + except NegotiationError: + continue + + # Add matching extension to the final list. + accepted_extensions.append(extension) + + # Break out of the loop once we have a match. + break + + # If we didn't break from the loop, no extension in our list + # matched what the server sent. Fail the connection. + else: + raise NegotiationError( + f"Unsupported extension: " + f"name = {name}, params = {response_params}" + ) + + return accepted_extensions + + def process_subprotocol(self, headers: Headers) -> Subprotocol | None: + """ + Handle the Sec-WebSocket-Protocol HTTP response header. + + If provided, check that it contains exactly one supported subprotocol. + + Args: + headers: WebSocket handshake response headers. + + Returns: + Subprotocol, if one was selected. + + """ + subprotocol: Subprotocol | None = None + + subprotocols = headers.get_all("Sec-WebSocket-Protocol") + + if subprotocols: + if self.available_subprotocols is None: + raise NegotiationError("no subprotocols supported") + + parsed_subprotocols: Sequence[Subprotocol] = sum( + [parse_subprotocol(header_value) for header_value in subprotocols], [] + ) + if len(parsed_subprotocols) > 1: + raise InvalidHeader( + "Sec-WebSocket-Protocol", + f"multiple values: {', '.join(parsed_subprotocols)}", + ) + + subprotocol = parsed_subprotocols[0] + if subprotocol not in self.available_subprotocols: + raise NegotiationError(f"unsupported subprotocol: {subprotocol}") + + return subprotocol + + def send_request(self, request: Request) -> None: + """ + Send a handshake request to the server. + + Args: + request: WebSocket handshake request event. + + """ + if self.debug: + self.logger.debug("> GET %s HTTP/1.1", request.path) + for key, value in request.headers.raw_items(): + self.logger.debug("> %s: %s", key, value) + + self.writes.append(request.serialize()) + + def parse(self) -> Generator[None]: + if self.state is CONNECTING: + try: + response = yield from Response.parse( + self.reader.read_line, + self.reader.read_exact, + self.reader.read_to_eof, + ) + except Exception as exc: + self.handshake_exc = InvalidMessage( + "did not receive a valid HTTP response" + ) + self.handshake_exc.__cause__ = exc + self.send_eof() + self.parser = self.discard() + next(self.parser) # start coroutine + yield + + if self.debug: + code, phrase = response.status_code, response.reason_phrase + self.logger.debug("< HTTP/1.1 %d %s", code, phrase) + for key, value in response.headers.raw_items(): + self.logger.debug("< %s: %s", key, value) + if response.body: + self.logger.debug("< [body] (%d bytes)", len(response.body)) + + try: + self.process_response(response) + except InvalidHandshake as exc: + response._exception = exc + self.events.append(response) + self.handshake_exc = exc + self.send_eof() + self.parser = self.discard() + next(self.parser) # start coroutine + yield + + assert self.state is CONNECTING + self.state = OPEN + self.events.append(response) + + yield from super().parse() + + +class ClientConnection(ClientProtocol): + def __init__(self, *args: Any, **kwargs: Any) -> None: + warnings.warn( # deprecated in 11.0 - 2023-04-02 + "ClientConnection was renamed to ClientProtocol", + DeprecationWarning, + ) + super().__init__(*args, **kwargs) + + +BACKOFF_INITIAL_DELAY = float(os.environ.get("WEBSOCKETS_BACKOFF_INITIAL_DELAY", "5")) +BACKOFF_MIN_DELAY = float(os.environ.get("WEBSOCKETS_BACKOFF_MIN_DELAY", "3.1")) +BACKOFF_MAX_DELAY = float(os.environ.get("WEBSOCKETS_BACKOFF_MAX_DELAY", "90.0")) +BACKOFF_FACTOR = float(os.environ.get("WEBSOCKETS_BACKOFF_FACTOR", "1.618")) + + +def backoff( + initial_delay: float = BACKOFF_INITIAL_DELAY, + min_delay: float = BACKOFF_MIN_DELAY, + max_delay: float = BACKOFF_MAX_DELAY, + factor: float = BACKOFF_FACTOR, +) -> Generator[float]: + """ + Generate a series of backoff delays between reconnection attempts. + + Yields: + How many seconds to wait before retrying to connect. + + """ + # Add a random initial delay between 0 and 5 seconds. + # See 7.2.3. Recovering from Abnormal Closure in RFC 6455. + yield random.random() * initial_delay + delay = min_delay + while delay < max_delay: + yield delay + delay *= factor + while True: + yield max_delay + + +lazy_import( + globals(), + deprecated_aliases={ + # deprecated in 14.0 - 2024-11-09 + "WebSocketClientProtocol": ".legacy.client", + "connect": ".legacy.client", + "unix_connect": ".legacy.client", + }, +) diff --git a/venv/lib/python3.10/site-packages/websockets/connection.py b/venv/lib/python3.10/site-packages/websockets/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..5e78e34479224d0332b165badd67a8933e0c73db --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/connection.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +import warnings + +from .protocol import SEND_EOF, Protocol as Connection, Side, State # noqa: F401 + + +warnings.warn( # deprecated in 11.0 - 2023-04-02 + "websockets.connection was renamed to websockets.protocol " + "and Connection was renamed to Protocol", + DeprecationWarning, +) diff --git a/venv/lib/python3.10/site-packages/websockets/datastructures.py b/venv/lib/python3.10/site-packages/websockets/datastructures.py new file mode 100644 index 0000000000000000000000000000000000000000..3c5dcbe9a8a9a0de44b457e3b813814d11f67445 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/datastructures.py @@ -0,0 +1,187 @@ +from __future__ import annotations + +from collections.abc import Iterable, Iterator, Mapping, MutableMapping +from typing import Any, Protocol, Union + + +__all__ = [ + "Headers", + "HeadersLike", + "MultipleValuesError", +] + + +class MultipleValuesError(LookupError): + """ + Exception raised when :class:`Headers` has multiple values for a key. + + """ + + def __str__(self) -> str: + # Implement the same logic as KeyError_str in Objects/exceptions.c. + if len(self.args) == 1: + return repr(self.args[0]) + return super().__str__() + + +class Headers(MutableMapping[str, str]): + """ + Efficient data structure for manipulating HTTP headers. + + A :class:`list` of ``(name, values)`` is inefficient for lookups. + + A :class:`dict` doesn't suffice because header names are case-insensitive + and multiple occurrences of headers with the same name are possible. + + :class:`Headers` stores HTTP headers in a hybrid data structure to provide + efficient insertions and lookups while preserving the original data. + + In order to account for multiple values with minimal hassle, + :class:`Headers` follows this logic: + + - When getting a header with ``headers[name]``: + - if there's no value, :exc:`KeyError` is raised; + - if there's exactly one value, it's returned; + - if there's more than one value, :exc:`MultipleValuesError` is raised. + + - When setting a header with ``headers[name] = value``, the value is + appended to the list of values for that header. + + - When deleting a header with ``del headers[name]``, all values for that + header are removed (this is slow). + + Other methods for manipulating headers are consistent with this logic. + + As long as no header occurs multiple times, :class:`Headers` behaves like + :class:`dict`, except keys are lower-cased to provide case-insensitivity. + + Two methods support manipulating multiple values explicitly: + + - :meth:`get_all` returns a list of all values for a header; + - :meth:`raw_items` returns an iterator of ``(name, values)`` pairs. + + """ + + __slots__ = ["_dict", "_list"] + + # Like dict, Headers accepts an optional "mapping or iterable" argument. + def __init__(self, *args: HeadersLike, **kwargs: str) -> None: + self._dict: dict[str, list[str]] = {} + self._list: list[tuple[str, str]] = [] + self.update(*args, **kwargs) + + def __str__(self) -> str: + return "".join(f"{key}: {value}\r\n" for key, value in self._list) + "\r\n" + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self._list!r})" + + def copy(self) -> Headers: + copy = self.__class__() + copy._dict = self._dict.copy() + copy._list = self._list.copy() + return copy + + def serialize(self) -> bytes: + # Since headers only contain ASCII characters, we can keep this simple. + return str(self).encode() + + # Collection methods + + def __contains__(self, key: object) -> bool: + return isinstance(key, str) and key.lower() in self._dict + + def __iter__(self) -> Iterator[str]: + return iter(self._dict) + + def __len__(self) -> int: + return len(self._dict) + + # MutableMapping methods + + def __getitem__(self, key: str) -> str: + value = self._dict[key.lower()] + if len(value) == 1: + return value[0] + else: + raise MultipleValuesError(key) + + def __setitem__(self, key: str, value: str) -> None: + self._dict.setdefault(key.lower(), []).append(value) + self._list.append((key, value)) + + def __delitem__(self, key: str) -> None: + key_lower = key.lower() + self._dict.__delitem__(key_lower) + # This is inefficient. Fortunately deleting HTTP headers is uncommon. + self._list = [(k, v) for k, v in self._list if k.lower() != key_lower] + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, Headers): + return NotImplemented + return self._dict == other._dict + + def clear(self) -> None: + """ + Remove all headers. + + """ + self._dict = {} + self._list = [] + + def update(self, *args: HeadersLike, **kwargs: str) -> None: + """ + Update from a :class:`Headers` instance and/or keyword arguments. + + """ + args = tuple( + arg.raw_items() if isinstance(arg, Headers) else arg for arg in args + ) + super().update(*args, **kwargs) + + # Methods for handling multiple values + + def get_all(self, key: str) -> list[str]: + """ + Return the (possibly empty) list of all values for a header. + + Args: + key: Header name. + + """ + return self._dict.get(key.lower(), []) + + def raw_items(self) -> Iterator[tuple[str, str]]: + """ + Return an iterator of all values as ``(name, value)`` pairs. + + """ + return iter(self._list) + + +# copy of _typeshed.SupportsKeysAndGetItem. +class SupportsKeysAndGetItem(Protocol): # pragma: no cover + """ + Dict-like types with ``keys() -> str`` and ``__getitem__(key: str) -> str`` methods. + + """ + + def keys(self) -> Iterable[str]: ... + + def __getitem__(self, key: str) -> str: ... + + +# Change to Headers | Mapping[str, str] | ... when dropping Python < 3.10. +HeadersLike = Union[ + Headers, + Mapping[str, str], + Iterable[tuple[str, str]], + SupportsKeysAndGetItem, +] +""" +Types accepted where :class:`Headers` is expected. + +In addition to :class:`Headers` itself, this includes dict-like types where both +keys and values are :class:`str`. + +""" diff --git a/venv/lib/python3.10/site-packages/websockets/exceptions.py b/venv/lib/python3.10/site-packages/websockets/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..ab1a15ca8f97ddd26a5fb11fb4bfeb2461e4fba1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/exceptions.py @@ -0,0 +1,473 @@ +""" +:mod:`websockets.exceptions` defines the following hierarchy of exceptions. + +* :exc:`WebSocketException` + * :exc:`ConnectionClosed` + * :exc:`ConnectionClosedOK` + * :exc:`ConnectionClosedError` + * :exc:`InvalidURI` + * :exc:`InvalidProxy` + * :exc:`InvalidHandshake` + * :exc:`SecurityError` + * :exc:`ProxyError` + * :exc:`InvalidProxyMessage` + * :exc:`InvalidProxyStatus` + * :exc:`InvalidMessage` + * :exc:`InvalidStatus` + * :exc:`InvalidStatusCode` (legacy) + * :exc:`InvalidHeader` + * :exc:`InvalidHeaderFormat` + * :exc:`InvalidHeaderValue` + * :exc:`InvalidOrigin` + * :exc:`InvalidUpgrade` + * :exc:`NegotiationError` + * :exc:`DuplicateParameter` + * :exc:`InvalidParameterName` + * :exc:`InvalidParameterValue` + * :exc:`AbortHandshake` (legacy) + * :exc:`RedirectHandshake` (legacy) + * :exc:`ProtocolError` (Sans-I/O) + * :exc:`PayloadTooBig` (Sans-I/O) + * :exc:`InvalidState` (Sans-I/O) + * :exc:`ConcurrencyError` + +""" + +from __future__ import annotations + +import warnings + +from .imports import lazy_import + + +__all__ = [ + "WebSocketException", + "ConnectionClosed", + "ConnectionClosedOK", + "ConnectionClosedError", + "InvalidURI", + "InvalidProxy", + "InvalidHandshake", + "SecurityError", + "ProxyError", + "InvalidProxyMessage", + "InvalidProxyStatus", + "InvalidMessage", + "InvalidStatus", + "InvalidHeader", + "InvalidHeaderFormat", + "InvalidHeaderValue", + "InvalidOrigin", + "InvalidUpgrade", + "NegotiationError", + "DuplicateParameter", + "InvalidParameterName", + "InvalidParameterValue", + "ProtocolError", + "PayloadTooBig", + "InvalidState", + "ConcurrencyError", +] + + +class WebSocketException(Exception): + """ + Base class for all exceptions defined by websockets. + + """ + + +class ConnectionClosed(WebSocketException): + """ + Raised when trying to interact with a closed connection. + + Attributes: + rcvd: If a close frame was received, its code and reason are available + in ``rcvd.code`` and ``rcvd.reason``. + sent: If a close frame was sent, its code and reason are available + in ``sent.code`` and ``sent.reason``. + rcvd_then_sent: If close frames were received and sent, this attribute + tells in which order this happened, from the perspective of this + side of the connection. + + """ + + def __init__( + self, + rcvd: frames.Close | None, + sent: frames.Close | None, + rcvd_then_sent: bool | None = None, + ) -> None: + self.rcvd = rcvd + self.sent = sent + self.rcvd_then_sent = rcvd_then_sent + assert (self.rcvd_then_sent is None) == (self.rcvd is None or self.sent is None) + + def __str__(self) -> str: + if self.rcvd is None: + if self.sent is None: + return "no close frame received or sent" + else: + return f"sent {self.sent}; no close frame received" + else: + if self.sent is None: + return f"received {self.rcvd}; no close frame sent" + else: + if self.rcvd_then_sent: + return f"received {self.rcvd}; then sent {self.sent}" + else: + return f"sent {self.sent}; then received {self.rcvd}" + + # code and reason attributes are provided for backwards-compatibility + + @property + def code(self) -> int: + warnings.warn( # deprecated in 13.1 - 2024-09-21 + "ConnectionClosed.code is deprecated; " + "use Protocol.close_code or ConnectionClosed.rcvd.code", + DeprecationWarning, + ) + if self.rcvd is None: + return frames.CloseCode.ABNORMAL_CLOSURE + return self.rcvd.code + + @property + def reason(self) -> str: + warnings.warn( # deprecated in 13.1 - 2024-09-21 + "ConnectionClosed.reason is deprecated; " + "use Protocol.close_reason or ConnectionClosed.rcvd.reason", + DeprecationWarning, + ) + if self.rcvd is None: + return "" + return self.rcvd.reason + + +class ConnectionClosedOK(ConnectionClosed): + """ + Like :exc:`ConnectionClosed`, when the connection terminated properly. + + A close code with code 1000 (OK) or 1001 (going away) or without a code was + received and sent. + + """ + + +class ConnectionClosedError(ConnectionClosed): + """ + Like :exc:`ConnectionClosed`, when the connection terminated with an error. + + A close frame with a code other than 1000 (OK) or 1001 (going away) was + received or sent, or the closing handshake didn't complete properly. + + """ + + +class InvalidURI(WebSocketException): + """ + Raised when connecting to a URI that isn't a valid WebSocket URI. + + """ + + def __init__(self, uri: str, msg: str) -> None: + self.uri = uri + self.msg = msg + + def __str__(self) -> str: + return f"{self.uri} isn't a valid URI: {self.msg}" + + +class InvalidProxy(WebSocketException): + """ + Raised when connecting via a proxy that isn't valid. + + """ + + def __init__(self, proxy: str, msg: str) -> None: + self.proxy = proxy + self.msg = msg + + def __str__(self) -> str: + return f"{self.proxy} isn't a valid proxy: {self.msg}" + + +class InvalidHandshake(WebSocketException): + """ + Base class for exceptions raised when the opening handshake fails. + + """ + + +class SecurityError(InvalidHandshake): + """ + Raised when a handshake request or response breaks a security rule. + + Security limits can be configured with :doc:`environment variables + <../reference/variables>`. + + """ + + +class ProxyError(InvalidHandshake): + """ + Raised when failing to connect to a proxy. + + """ + + +class InvalidProxyMessage(ProxyError): + """ + Raised when an HTTP proxy response is malformed. + + """ + + +class InvalidProxyStatus(ProxyError): + """ + Raised when an HTTP proxy rejects the connection. + + """ + + def __init__(self, response: http11.Response) -> None: + self.response = response + + def __str__(self) -> str: + return f"proxy rejected connection: HTTP {self.response.status_code:d}" + + +class InvalidMessage(InvalidHandshake): + """ + Raised when a handshake request or response is malformed. + + """ + + +class InvalidStatus(InvalidHandshake): + """ + Raised when a handshake response rejects the WebSocket upgrade. + + """ + + def __init__(self, response: http11.Response) -> None: + self.response = response + + def __str__(self) -> str: + return ( + f"server rejected WebSocket connection: HTTP {self.response.status_code:d}" + ) + + +class InvalidHeader(InvalidHandshake): + """ + Raised when an HTTP header doesn't have a valid format or value. + + """ + + def __init__(self, name: str, value: str | None = None) -> None: + self.name = name + self.value = value + + def __str__(self) -> str: + if self.value is None: + return f"missing {self.name} header" + elif self.value == "": + return f"empty {self.name} header" + else: + return f"invalid {self.name} header: {self.value}" + + +class InvalidHeaderFormat(InvalidHeader): + """ + Raised when an HTTP header cannot be parsed. + + The format of the header doesn't match the grammar for that header. + + """ + + def __init__(self, name: str, error: str, header: str, pos: int) -> None: + super().__init__(name, f"{error} at {pos} in {header}") + + +class InvalidHeaderValue(InvalidHeader): + """ + Raised when an HTTP header has a wrong value. + + The format of the header is correct but the value isn't acceptable. + + """ + + +class InvalidOrigin(InvalidHeader): + """ + Raised when the Origin header in a request isn't allowed. + + """ + + def __init__(self, origin: str | None) -> None: + super().__init__("Origin", origin) + + +class InvalidUpgrade(InvalidHeader): + """ + Raised when the Upgrade or Connection header isn't correct. + + """ + + +class NegotiationError(InvalidHandshake): + """ + Raised when negotiating an extension or a subprotocol fails. + + """ + + +class DuplicateParameter(NegotiationError): + """ + Raised when a parameter name is repeated in an extension header. + + """ + + def __init__(self, name: str) -> None: + self.name = name + + def __str__(self) -> str: + return f"duplicate parameter: {self.name}" + + +class InvalidParameterName(NegotiationError): + """ + Raised when a parameter name in an extension header is invalid. + + """ + + def __init__(self, name: str) -> None: + self.name = name + + def __str__(self) -> str: + return f"invalid parameter name: {self.name}" + + +class InvalidParameterValue(NegotiationError): + """ + Raised when a parameter value in an extension header is invalid. + + """ + + def __init__(self, name: str, value: str | None) -> None: + self.name = name + self.value = value + + def __str__(self) -> str: + if self.value is None: + return f"missing value for parameter {self.name}" + elif self.value == "": + return f"empty value for parameter {self.name}" + else: + return f"invalid value for parameter {self.name}: {self.value}" + + +class ProtocolError(WebSocketException): + """ + Raised when receiving or sending a frame that breaks the protocol. + + The Sans-I/O implementation raises this exception when: + + * receiving or sending a frame that contains invalid data; + * receiving or sending an invalid sequence of frames. + + """ + + +class PayloadTooBig(WebSocketException): + """ + Raised when parsing a frame with a payload that exceeds the maximum size. + + The Sans-I/O layer uses this exception internally. It doesn't bubble up to + the I/O layer. + + The :meth:`~websockets.extensions.Extension.decode` method of extensions + must raise :exc:`PayloadTooBig` if decoding a frame would exceed the limit. + + """ + + def __init__( + self, + size_or_message: int | None | str, + max_size: int | None = None, + cur_size: int | None = None, + ) -> None: + if isinstance(size_or_message, str): + assert max_size is None + assert cur_size is None + warnings.warn( # deprecated in 14.0 - 2024-11-09 + "PayloadTooBig(message) is deprecated; " + "change to PayloadTooBig(size, max_size)", + DeprecationWarning, + ) + self.message: str | None = size_or_message + else: + self.message = None + self.size: int | None = size_or_message + assert max_size is not None + self.max_size: int = max_size + self.cur_size: int | None = None + self.set_current_size(cur_size) + + def __str__(self) -> str: + if self.message is not None: + return self.message + else: + message = "frame " + if self.size is not None: + message += f"with {self.size} bytes " + if self.cur_size is not None: + message += f"after reading {self.cur_size} bytes " + message += f"exceeds limit of {self.max_size} bytes" + return message + + def set_current_size(self, cur_size: int | None) -> None: + assert self.cur_size is None + if cur_size is not None: + self.max_size += cur_size + self.cur_size = cur_size + + +class InvalidState(WebSocketException, AssertionError): + """ + Raised when sending a frame is forbidden in the current state. + + Specifically, the Sans-I/O layer raises this exception when: + + * sending a data frame to a connection in a state other + :attr:`~websockets.protocol.State.OPEN`; + * sending a control frame to a connection in a state other than + :attr:`~websockets.protocol.State.OPEN` or + :attr:`~websockets.protocol.State.CLOSING`. + + """ + + +class ConcurrencyError(WebSocketException, RuntimeError): + """ + Raised when receiving or sending messages concurrently. + + WebSocket is a connection-oriented protocol. Reads must be serialized; so + must be writes. However, reading and writing concurrently is possible. + + """ + + +# At the bottom to break import cycles created by type annotations. +from . import frames, http11 # noqa: E402 + + +lazy_import( + globals(), + deprecated_aliases={ + # deprecated in 14.0 - 2024-11-09 + "AbortHandshake": ".legacy.exceptions", + "InvalidStatusCode": ".legacy.exceptions", + "RedirectHandshake": ".legacy.exceptions", + "WebSocketProtocolError": ".legacy.exceptions", + }, +) diff --git a/venv/lib/python3.10/site-packages/websockets/extensions/__init__.py b/venv/lib/python3.10/site-packages/websockets/extensions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..02838b98a5335322daad566de9c0d9d0843fc49a --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/extensions/__init__.py @@ -0,0 +1,4 @@ +from .base import * + + +__all__ = ["Extension", "ClientExtensionFactory", "ServerExtensionFactory"] diff --git a/venv/lib/python3.10/site-packages/websockets/extensions/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/extensions/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42b34ce3b45bb11045a11d33d46462fc824c3d67 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/extensions/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/extensions/__pycache__/base.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/extensions/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62284a52d3bdea9ccdbefdccfa3118be5156b4f8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/extensions/__pycache__/base.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b1423f21fc3ecc81887d35f4fc4c60174949b68 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/extensions/base.py b/venv/lib/python3.10/site-packages/websockets/extensions/base.py new file mode 100644 index 0000000000000000000000000000000000000000..2fdc59f0fdae4d28fdcf18b6f9edf8d62ad22f01 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/extensions/base.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +from collections.abc import Sequence + +from ..frames import Frame +from ..typing import ExtensionName, ExtensionParameter + + +__all__ = ["Extension", "ClientExtensionFactory", "ServerExtensionFactory"] + + +class Extension: + """ + Base class for extensions. + + """ + + name: ExtensionName + """Extension identifier.""" + + def decode(self, frame: Frame, *, max_size: int | None = None) -> Frame: + """ + Decode an incoming frame. + + Args: + frame: Incoming frame. + max_size: Maximum payload size in bytes. + + Returns: + Decoded frame. + + Raises: + PayloadTooBig: If decoding the payload exceeds ``max_size``. + + """ + raise NotImplementedError + + def encode(self, frame: Frame) -> Frame: + """ + Encode an outgoing frame. + + Args: + frame: Outgoing frame. + + Returns: + Encoded frame. + + """ + raise NotImplementedError + + +class ClientExtensionFactory: + """ + Base class for client-side extension factories. + + """ + + name: ExtensionName + """Extension identifier.""" + + def get_request_params(self) -> Sequence[ExtensionParameter]: + """ + Build parameters to send to the server for this extension. + + Returns: + Parameters to send to the server. + + """ + raise NotImplementedError + + def process_response_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> Extension: + """ + Process parameters received from the server. + + Args: + params: Parameters received from the server for this extension. + accepted_extensions: List of previously accepted extensions. + + Returns: + An extension instance. + + Raises: + NegotiationError: If parameters aren't acceptable. + + """ + raise NotImplementedError + + +class ServerExtensionFactory: + """ + Base class for server-side extension factories. + + """ + + name: ExtensionName + """Extension identifier.""" + + def process_request_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> tuple[list[ExtensionParameter], Extension]: + """ + Process parameters received from the client. + + Args: + params: Parameters received from the client for this extension. + accepted_extensions: List of previously accepted extensions. + + Returns: + To accept the offer, parameters to send to the client for this + extension and an extension instance. + + Raises: + NegotiationError: To reject the offer, if parameters received from + the client aren't acceptable. + + """ + raise NotImplementedError diff --git a/venv/lib/python3.10/site-packages/websockets/extensions/permessage_deflate.py b/venv/lib/python3.10/site-packages/websockets/extensions/permessage_deflate.py new file mode 100644 index 0000000000000000000000000000000000000000..7e9e7a5dd56b2d17e7d622717006db391edcc7d8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/extensions/permessage_deflate.py @@ -0,0 +1,697 @@ +from __future__ import annotations + +import zlib +from collections.abc import Sequence +from typing import Any, Literal + +from .. import frames +from ..exceptions import ( + DuplicateParameter, + InvalidParameterName, + InvalidParameterValue, + NegotiationError, + PayloadTooBig, + ProtocolError, +) +from ..typing import ExtensionName, ExtensionParameter +from .base import ClientExtensionFactory, Extension, ServerExtensionFactory + + +__all__ = [ + "PerMessageDeflate", + "ClientPerMessageDeflateFactory", + "enable_client_permessage_deflate", + "ServerPerMessageDeflateFactory", + "enable_server_permessage_deflate", +] + +_EMPTY_UNCOMPRESSED_BLOCK = b"\x00\x00\xff\xff" + +_MAX_WINDOW_BITS_VALUES = [str(bits) for bits in range(8, 16)] + + +class PerMessageDeflate(Extension): + """ + Per-Message Deflate extension. + + """ + + name = ExtensionName("permessage-deflate") + + def __init__( + self, + remote_no_context_takeover: bool, + local_no_context_takeover: bool, + remote_max_window_bits: int, + local_max_window_bits: int, + compress_settings: dict[Any, Any] | None = None, + ) -> None: + """ + Configure the Per-Message Deflate extension. + + """ + if compress_settings is None: + compress_settings = {} + + assert remote_no_context_takeover in [False, True] + assert local_no_context_takeover in [False, True] + assert 8 <= remote_max_window_bits <= 15 + assert 8 <= local_max_window_bits <= 15 + assert "wbits" not in compress_settings + + self.remote_no_context_takeover = remote_no_context_takeover + self.local_no_context_takeover = local_no_context_takeover + self.remote_max_window_bits = remote_max_window_bits + self.local_max_window_bits = local_max_window_bits + self.compress_settings = compress_settings + + if not self.remote_no_context_takeover: + self.decoder = zlib.decompressobj(wbits=-self.remote_max_window_bits) + + if not self.local_no_context_takeover: + self.encoder = zlib.compressobj( + wbits=-self.local_max_window_bits, + **self.compress_settings, + ) + + # To handle continuation frames properly, we must keep track of + # whether that initial frame was encoded. + self.decode_cont_data = False + # There's no need for self.encode_cont_data because we always encode + # outgoing frames, so it would always be True. + + def __repr__(self) -> str: + return ( + f"PerMessageDeflate(" + f"remote_no_context_takeover={self.remote_no_context_takeover}, " + f"local_no_context_takeover={self.local_no_context_takeover}, " + f"remote_max_window_bits={self.remote_max_window_bits}, " + f"local_max_window_bits={self.local_max_window_bits})" + ) + + def decode( + self, + frame: frames.Frame, + *, + max_size: int | None = None, + ) -> frames.Frame: + """ + Decode an incoming frame. + + """ + # Skip control frames. + if frame.opcode in frames.CTRL_OPCODES: + return frame + + # Handle continuation data frames: + # - skip if the message isn't encoded + # - reset "decode continuation data" flag if it's a final frame + if frame.opcode is frames.OP_CONT: + if not self.decode_cont_data: + return frame + if frame.fin: + self.decode_cont_data = False + + # Handle text and binary data frames: + # - skip if the message isn't encoded + # - unset the rsv1 flag on the first frame of a compressed message + # - set "decode continuation data" flag if it's a non-final frame + else: + if not frame.rsv1: + return frame + if not frame.fin: + self.decode_cont_data = True + + # Re-initialize per-message decoder. + if self.remote_no_context_takeover: + self.decoder = zlib.decompressobj(wbits=-self.remote_max_window_bits) + + # Uncompress data. Protect against zip bombs by preventing zlib from + # decompressing more than max_length bytes (except when the limit is + # disabled with max_size = None). + if frame.fin and len(frame.data) < 2044: + # Profiling shows that appending four bytes, which makes a copy, is + # faster than calling decompress() again when data is less than 2kB. + data = bytes(frame.data) + _EMPTY_UNCOMPRESSED_BLOCK + else: + data = frame.data + max_length = 0 if max_size is None else max_size + try: + data = self.decoder.decompress(data, max_length) + if self.decoder.unconsumed_tail: + assert max_size is not None # help mypy + raise PayloadTooBig(None, max_size) + if frame.fin and len(frame.data) >= 2044: + # This cannot generate additional data. + self.decoder.decompress(_EMPTY_UNCOMPRESSED_BLOCK) + except zlib.error as exc: + raise ProtocolError("decompression failed") from exc + + # Allow garbage collection of the decoder if it won't be reused. + if frame.fin and self.remote_no_context_takeover: + del self.decoder + + return frames.Frame( + frame.opcode, + data, + frame.fin, + # Unset the rsv1 flag on the first frame of a compressed message. + False, + frame.rsv2, + frame.rsv3, + ) + + def encode(self, frame: frames.Frame) -> frames.Frame: + """ + Encode an outgoing frame. + + """ + # Skip control frames. + if frame.opcode in frames.CTRL_OPCODES: + return frame + + # Since we always encode messages, there's no "encode continuation + # data" flag similar to "decode continuation data" at this time. + + if frame.opcode is not frames.OP_CONT: + # Re-initialize per-message decoder. + if self.local_no_context_takeover: + self.encoder = zlib.compressobj( + wbits=-self.local_max_window_bits, + **self.compress_settings, + ) + + # Compress data. + data = self.encoder.compress(frame.data) + self.encoder.flush(zlib.Z_SYNC_FLUSH) + if frame.fin: + # Sync flush generates between 5 or 6 bytes, ending with the bytes + # 0x00 0x00 0xff 0xff, which must be removed. + assert data[-4:] == _EMPTY_UNCOMPRESSED_BLOCK + # Making a copy is faster than memoryview(a)[:-4] until 2kB. + if len(data) < 2048: + data = data[:-4] + else: + data = memoryview(data)[:-4] + + # Allow garbage collection of the encoder if it won't be reused. + if frame.fin and self.local_no_context_takeover: + del self.encoder + + return frames.Frame( + frame.opcode, + data, + frame.fin, + # Set the rsv1 flag on the first frame of a compressed message. + frame.opcode is not frames.OP_CONT, + frame.rsv2, + frame.rsv3, + ) + + +def _build_parameters( + server_no_context_takeover: bool, + client_no_context_takeover: bool, + server_max_window_bits: int | None, + client_max_window_bits: int | Literal[True] | None, +) -> list[ExtensionParameter]: + """ + Build a list of ``(name, value)`` pairs for some compression parameters. + + """ + params: list[ExtensionParameter] = [] + if server_no_context_takeover: + params.append(("server_no_context_takeover", None)) + if client_no_context_takeover: + params.append(("client_no_context_takeover", None)) + if server_max_window_bits: + params.append(("server_max_window_bits", str(server_max_window_bits))) + if client_max_window_bits is True: # only in handshake requests + params.append(("client_max_window_bits", None)) + elif client_max_window_bits: + params.append(("client_max_window_bits", str(client_max_window_bits))) + return params + + +def _extract_parameters( + params: Sequence[ExtensionParameter], *, is_server: bool +) -> tuple[bool, bool, int | None, int | Literal[True] | None]: + """ + Extract compression parameters from a list of ``(name, value)`` pairs. + + If ``is_server`` is :obj:`True`, ``client_max_window_bits`` may be + provided without a value. This is only allowed in handshake requests. + + """ + server_no_context_takeover: bool = False + client_no_context_takeover: bool = False + server_max_window_bits: int | None = None + client_max_window_bits: int | Literal[True] | None = None + + for name, value in params: + if name == "server_no_context_takeover": + if server_no_context_takeover: + raise DuplicateParameter(name) + if value is None: + server_no_context_takeover = True + else: + raise InvalidParameterValue(name, value) + + elif name == "client_no_context_takeover": + if client_no_context_takeover: + raise DuplicateParameter(name) + if value is None: + client_no_context_takeover = True + else: + raise InvalidParameterValue(name, value) + + elif name == "server_max_window_bits": + if server_max_window_bits is not None: + raise DuplicateParameter(name) + if value in _MAX_WINDOW_BITS_VALUES: + server_max_window_bits = int(value) + else: + raise InvalidParameterValue(name, value) + + elif name == "client_max_window_bits": + if client_max_window_bits is not None: + raise DuplicateParameter(name) + if is_server and value is None: # only in handshake requests + client_max_window_bits = True + elif value in _MAX_WINDOW_BITS_VALUES: + client_max_window_bits = int(value) + else: + raise InvalidParameterValue(name, value) + + else: + raise InvalidParameterName(name) + + return ( + server_no_context_takeover, + client_no_context_takeover, + server_max_window_bits, + client_max_window_bits, + ) + + +class ClientPerMessageDeflateFactory(ClientExtensionFactory): + """ + Client-side extension factory for the Per-Message Deflate extension. + + Parameters behave as described in `section 7.1 of RFC 7692`_. + + .. _section 7.1 of RFC 7692: https://datatracker.ietf.org/doc/html/rfc7692#section-7.1 + + Set them to :obj:`True` to include them in the negotiation offer without a + value or to an integer value to include them with this value. + + Args: + server_no_context_takeover: Prevent server from using context takeover. + client_no_context_takeover: Prevent client from using context takeover. + server_max_window_bits: Maximum size of the server's LZ77 sliding window + in bits, between 8 and 15. + client_max_window_bits: Maximum size of the client's LZ77 sliding window + in bits, between 8 and 15, or :obj:`True` to indicate support without + setting a limit. + compress_settings: Additional keyword arguments for :func:`zlib.compressobj`, + excluding ``wbits``. + + """ + + name = ExtensionName("permessage-deflate") + + def __init__( + self, + server_no_context_takeover: bool = False, + client_no_context_takeover: bool = False, + server_max_window_bits: int | None = None, + client_max_window_bits: int | Literal[True] | None = True, + compress_settings: dict[str, Any] | None = None, + ) -> None: + """ + Configure the Per-Message Deflate extension factory. + + """ + if not (server_max_window_bits is None or 8 <= server_max_window_bits <= 15): + raise ValueError("server_max_window_bits must be between 8 and 15") + if not ( + client_max_window_bits is None + or client_max_window_bits is True + or 8 <= client_max_window_bits <= 15 + ): + raise ValueError("client_max_window_bits must be between 8 and 15") + if compress_settings is not None and "wbits" in compress_settings: + raise ValueError( + "compress_settings must not include wbits, " + "set client_max_window_bits instead" + ) + + self.server_no_context_takeover = server_no_context_takeover + self.client_no_context_takeover = client_no_context_takeover + self.server_max_window_bits = server_max_window_bits + self.client_max_window_bits = client_max_window_bits + self.compress_settings = compress_settings + + def get_request_params(self) -> Sequence[ExtensionParameter]: + """ + Build request parameters. + + """ + return _build_parameters( + self.server_no_context_takeover, + self.client_no_context_takeover, + self.server_max_window_bits, + self.client_max_window_bits, + ) + + def process_response_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> PerMessageDeflate: + """ + Process response parameters. + + Return an extension instance. + + """ + if any(other.name == self.name for other in accepted_extensions): + raise NegotiationError(f"received duplicate {self.name}") + + # Request parameters are available in instance variables. + + # Load response parameters in local variables. + ( + server_no_context_takeover, + client_no_context_takeover, + server_max_window_bits, + client_max_window_bits, + ) = _extract_parameters(params, is_server=False) + + # After comparing the request and the response, the final + # configuration must be available in the local variables. + + # server_no_context_takeover + # + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # False False False + # False True True + # True False Error! + # True True True + + if self.server_no_context_takeover: + if not server_no_context_takeover: + raise NegotiationError("expected server_no_context_takeover") + + # client_no_context_takeover + # + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # False False False + # False True True + # True False True - must change value + # True True True + + if self.client_no_context_takeover: + if not client_no_context_takeover: + client_no_context_takeover = True + + # server_max_window_bits + + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # None None None + # None 8≤M≤15 M + # 8≤N≤15 None Error! + # 8≤N≤15 8≤M≤N M + # 8≤N≤15 N self.server_max_window_bits: + raise NegotiationError("unsupported server_max_window_bits") + + # client_max_window_bits + + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # None None None + # None 8≤M≤15 Error! + # True None None + # True 8≤M≤15 M + # 8≤N≤15 None N - must change value + # 8≤N≤15 8≤M≤N M + # 8≤N≤15 N self.client_max_window_bits: + raise NegotiationError("unsupported client_max_window_bits") + + return PerMessageDeflate( + server_no_context_takeover, # remote_no_context_takeover + client_no_context_takeover, # local_no_context_takeover + server_max_window_bits or 15, # remote_max_window_bits + client_max_window_bits or 15, # local_max_window_bits + self.compress_settings, + ) + + +def enable_client_permessage_deflate( + extensions: Sequence[ClientExtensionFactory] | None, +) -> Sequence[ClientExtensionFactory]: + """ + Enable Per-Message Deflate with default settings in client extensions. + + If the extension is already present, perhaps with non-default settings, + the configuration isn't changed. + + """ + if extensions is None: + extensions = [] + if not any( + extension_factory.name == ClientPerMessageDeflateFactory.name + for extension_factory in extensions + ): + extensions = list(extensions) + [ + ClientPerMessageDeflateFactory( + compress_settings={"memLevel": 5}, + ) + ] + return extensions + + +class ServerPerMessageDeflateFactory(ServerExtensionFactory): + """ + Server-side extension factory for the Per-Message Deflate extension. + + Parameters behave as described in `section 7.1 of RFC 7692`_. + + .. _section 7.1 of RFC 7692: https://datatracker.ietf.org/doc/html/rfc7692#section-7.1 + + Set them to :obj:`True` to include them in the negotiation offer without a + value or to an integer value to include them with this value. + + Args: + server_no_context_takeover: Prevent server from using context takeover. + client_no_context_takeover: Prevent client from using context takeover. + server_max_window_bits: Maximum size of the server's LZ77 sliding window + in bits, between 8 and 15. + client_max_window_bits: Maximum size of the client's LZ77 sliding window + in bits, between 8 and 15. + compress_settings: Additional keyword arguments for :func:`zlib.compressobj`, + excluding ``wbits``. + require_client_max_window_bits: Do not enable compression at all if + client doesn't advertise support for ``client_max_window_bits``; + the default behavior is to enable compression without enforcing + ``client_max_window_bits``. + + """ + + name = ExtensionName("permessage-deflate") + + def __init__( + self, + server_no_context_takeover: bool = False, + client_no_context_takeover: bool = False, + server_max_window_bits: int | None = None, + client_max_window_bits: int | None = None, + compress_settings: dict[str, Any] | None = None, + require_client_max_window_bits: bool = False, + ) -> None: + """ + Configure the Per-Message Deflate extension factory. + + """ + if not (server_max_window_bits is None or 8 <= server_max_window_bits <= 15): + raise ValueError("server_max_window_bits must be between 8 and 15") + if not (client_max_window_bits is None or 8 <= client_max_window_bits <= 15): + raise ValueError("client_max_window_bits must be between 8 and 15") + if compress_settings is not None and "wbits" in compress_settings: + raise ValueError( + "compress_settings must not include wbits, " + "set server_max_window_bits instead" + ) + if client_max_window_bits is None and require_client_max_window_bits: + raise ValueError( + "require_client_max_window_bits is enabled, " + "but client_max_window_bits isn't configured" + ) + + self.server_no_context_takeover = server_no_context_takeover + self.client_no_context_takeover = client_no_context_takeover + self.server_max_window_bits = server_max_window_bits + self.client_max_window_bits = client_max_window_bits + self.compress_settings = compress_settings + self.require_client_max_window_bits = require_client_max_window_bits + + def process_request_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> tuple[list[ExtensionParameter], PerMessageDeflate]: + """ + Process request parameters. + + Return response params and an extension instance. + + """ + if any(other.name == self.name for other in accepted_extensions): + raise NegotiationError(f"skipped duplicate {self.name}") + + # Load request parameters in local variables. + ( + server_no_context_takeover, + client_no_context_takeover, + server_max_window_bits, + client_max_window_bits, + ) = _extract_parameters(params, is_server=True) + + # Configuration parameters are available in instance variables. + + # After comparing the request and the configuration, the response must + # be available in the local variables. + + # server_no_context_takeover + # + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # False False False + # False True True + # True False True - must change value to True + # True True True + + if self.server_no_context_takeover: + if not server_no_context_takeover: + server_no_context_takeover = True + + # client_no_context_takeover + # + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # False False False + # False True True (or False) + # True False True - must change value to True + # True True True (or False) + + if self.client_no_context_takeover: + if not client_no_context_takeover: + client_no_context_takeover = True + + # server_max_window_bits + + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # None None None + # None 8≤M≤15 M + # 8≤N≤15 None N - must change value + # 8≤N≤15 8≤M≤N M + # 8≤N≤15 N self.server_max_window_bits: + server_max_window_bits = self.server_max_window_bits + + # client_max_window_bits + + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # None None None + # None True None - must change value + # None 8≤M≤15 M (or None) + # 8≤N≤15 None None or Error! + # 8≤N≤15 True N - must change value + # 8≤N≤15 8≤M≤N M (or None) + # 8≤N≤15 N Sequence[ServerExtensionFactory]: + """ + Enable Per-Message Deflate with default settings in server extensions. + + If the extension is already present, perhaps with non-default settings, + the configuration isn't changed. + + """ + if extensions is None: + extensions = [] + if not any( + ext_factory.name == ServerPerMessageDeflateFactory.name + for ext_factory in extensions + ): + extensions = list(extensions) + [ + ServerPerMessageDeflateFactory( + server_max_window_bits=12, + client_max_window_bits=12, + compress_settings={"memLevel": 5}, + ) + ] + return extensions diff --git a/venv/lib/python3.10/site-packages/websockets/frames.py b/venv/lib/python3.10/site-packages/websockets/frames.py new file mode 100644 index 0000000000000000000000000000000000000000..ab0869d013389a8c1c0d4b48db85c8a1619b44ef --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/frames.py @@ -0,0 +1,430 @@ +from __future__ import annotations + +import dataclasses +import enum +import io +import os +import secrets +import struct +from collections.abc import Generator, Sequence +from typing import Callable, Union + +from .exceptions import PayloadTooBig, ProtocolError + + +try: + from .speedups import apply_mask +except ImportError: + from .utils import apply_mask + + +__all__ = [ + "Opcode", + "OP_CONT", + "OP_TEXT", + "OP_BINARY", + "OP_CLOSE", + "OP_PING", + "OP_PONG", + "DATA_OPCODES", + "CTRL_OPCODES", + "CloseCode", + "Frame", + "Close", +] + + +class Opcode(enum.IntEnum): + """Opcode values for WebSocket frames.""" + + CONT, TEXT, BINARY = 0x00, 0x01, 0x02 + CLOSE, PING, PONG = 0x08, 0x09, 0x0A + + +OP_CONT = Opcode.CONT +OP_TEXT = Opcode.TEXT +OP_BINARY = Opcode.BINARY +OP_CLOSE = Opcode.CLOSE +OP_PING = Opcode.PING +OP_PONG = Opcode.PONG + +DATA_OPCODES = OP_CONT, OP_TEXT, OP_BINARY +CTRL_OPCODES = OP_CLOSE, OP_PING, OP_PONG + + +class CloseCode(enum.IntEnum): + """Close code values for WebSocket close frames.""" + + NORMAL_CLOSURE = 1000 + GOING_AWAY = 1001 + PROTOCOL_ERROR = 1002 + UNSUPPORTED_DATA = 1003 + # 1004 is reserved + NO_STATUS_RCVD = 1005 + ABNORMAL_CLOSURE = 1006 + INVALID_DATA = 1007 + POLICY_VIOLATION = 1008 + MESSAGE_TOO_BIG = 1009 + MANDATORY_EXTENSION = 1010 + INTERNAL_ERROR = 1011 + SERVICE_RESTART = 1012 + TRY_AGAIN_LATER = 1013 + BAD_GATEWAY = 1014 + TLS_HANDSHAKE = 1015 + + +# See https://www.iana.org/assignments/websocket/websocket.xhtml +CLOSE_CODE_EXPLANATIONS: dict[int, str] = { + CloseCode.NORMAL_CLOSURE: "OK", + CloseCode.GOING_AWAY: "going away", + CloseCode.PROTOCOL_ERROR: "protocol error", + CloseCode.UNSUPPORTED_DATA: "unsupported data", + CloseCode.NO_STATUS_RCVD: "no status received [internal]", + CloseCode.ABNORMAL_CLOSURE: "abnormal closure [internal]", + CloseCode.INVALID_DATA: "invalid frame payload data", + CloseCode.POLICY_VIOLATION: "policy violation", + CloseCode.MESSAGE_TOO_BIG: "message too big", + CloseCode.MANDATORY_EXTENSION: "mandatory extension", + CloseCode.INTERNAL_ERROR: "internal error", + CloseCode.SERVICE_RESTART: "service restart", + CloseCode.TRY_AGAIN_LATER: "try again later", + CloseCode.BAD_GATEWAY: "bad gateway", + CloseCode.TLS_HANDSHAKE: "TLS handshake failure [internal]", +} + + +# Close code that are allowed in a close frame. +# Using a set optimizes `code in EXTERNAL_CLOSE_CODES`. +EXTERNAL_CLOSE_CODES = { + CloseCode.NORMAL_CLOSURE, + CloseCode.GOING_AWAY, + CloseCode.PROTOCOL_ERROR, + CloseCode.UNSUPPORTED_DATA, + CloseCode.INVALID_DATA, + CloseCode.POLICY_VIOLATION, + CloseCode.MESSAGE_TOO_BIG, + CloseCode.MANDATORY_EXTENSION, + CloseCode.INTERNAL_ERROR, + CloseCode.SERVICE_RESTART, + CloseCode.TRY_AGAIN_LATER, + CloseCode.BAD_GATEWAY, +} + + +OK_CLOSE_CODES = { + CloseCode.NORMAL_CLOSURE, + CloseCode.GOING_AWAY, + CloseCode.NO_STATUS_RCVD, +} + + +BytesLike = bytes, bytearray, memoryview + + +@dataclasses.dataclass +class Frame: + """ + WebSocket frame. + + Attributes: + opcode: Opcode. + data: Payload data. + fin: FIN bit. + rsv1: RSV1 bit. + rsv2: RSV2 bit. + rsv3: RSV3 bit. + + Only these fields are needed. The MASK bit, payload length and masking-key + are handled on the fly when parsing and serializing frames. + + """ + + opcode: Opcode + data: Union[bytes, bytearray, memoryview] + fin: bool = True + rsv1: bool = False + rsv2: bool = False + rsv3: bool = False + + # Configure if you want to see more in logs. Should be a multiple of 3. + MAX_LOG_SIZE = int(os.environ.get("WEBSOCKETS_MAX_LOG_SIZE", "75")) + + def __str__(self) -> str: + """ + Return a human-readable representation of a frame. + + """ + coding = None + length = f"{len(self.data)} byte{'' if len(self.data) == 1 else 's'}" + non_final = "" if self.fin else "continued" + + if self.opcode is OP_TEXT: + # Decoding only the beginning and the end is needlessly hard. + # Decode the entire payload then elide later if necessary. + data = repr(bytes(self.data).decode()) + elif self.opcode is OP_BINARY: + # We'll show at most the first 16 bytes and the last 8 bytes. + # Encode just what we need, plus two dummy bytes to elide later. + binary = self.data + if len(binary) > self.MAX_LOG_SIZE // 3: + cut = (self.MAX_LOG_SIZE // 3 - 1) // 3 # by default cut = 8 + binary = b"".join([binary[: 2 * cut], b"\x00\x00", binary[-cut:]]) + data = " ".join(f"{byte:02x}" for byte in binary) + elif self.opcode is OP_CLOSE: + data = str(Close.parse(self.data)) + elif self.data: + # We don't know if a Continuation frame contains text or binary. + # Ping and Pong frames could contain UTF-8. + # Attempt to decode as UTF-8 and display it as text; fallback to + # binary. If self.data is a memoryview, it has no decode() method, + # which raises AttributeError. + try: + data = repr(bytes(self.data).decode()) + coding = "text" + except (UnicodeDecodeError, AttributeError): + binary = self.data + if len(binary) > self.MAX_LOG_SIZE // 3: + cut = (self.MAX_LOG_SIZE // 3 - 1) // 3 # by default cut = 8 + binary = b"".join([binary[: 2 * cut], b"\x00\x00", binary[-cut:]]) + data = " ".join(f"{byte:02x}" for byte in binary) + coding = "binary" + else: + data = "''" + + if len(data) > self.MAX_LOG_SIZE: + cut = self.MAX_LOG_SIZE // 3 - 1 # by default cut = 24 + data = data[: 2 * cut] + "..." + data[-cut:] + + metadata = ", ".join(filter(None, [coding, length, non_final])) + + return f"{self.opcode.name} {data} [{metadata}]" + + @classmethod + def parse( + cls, + read_exact: Callable[[int], Generator[None, None, bytes]], + *, + mask: bool, + max_size: int | None = None, + extensions: Sequence[extensions.Extension] | None = None, + ) -> Generator[None, None, Frame]: + """ + Parse a WebSocket frame. + + This is a generator-based coroutine. + + Args: + read_exact: Generator-based coroutine that reads the requested + bytes or raises an exception if there isn't enough data. + mask: Whether the frame should be masked i.e. whether the read + happens on the server side. + max_size: Maximum payload size in bytes. + extensions: List of extensions, applied in reverse order. + + Raises: + EOFError: If the connection is closed without a full WebSocket frame. + PayloadTooBig: If the frame's payload size exceeds ``max_size``. + ProtocolError: If the frame contains incorrect values. + + """ + # Read the header. + data = yield from read_exact(2) + head1, head2 = struct.unpack("!BB", data) + + # While not Pythonic, this is marginally faster than calling bool(). + fin = True if head1 & 0b10000000 else False + rsv1 = True if head1 & 0b01000000 else False + rsv2 = True if head1 & 0b00100000 else False + rsv3 = True if head1 & 0b00010000 else False + + try: + opcode = Opcode(head1 & 0b00001111) + except ValueError as exc: + raise ProtocolError("invalid opcode") from exc + + if (True if head2 & 0b10000000 else False) != mask: + raise ProtocolError("incorrect masking") + + length = head2 & 0b01111111 + if length == 126: + data = yield from read_exact(2) + (length,) = struct.unpack("!H", data) + elif length == 127: + data = yield from read_exact(8) + (length,) = struct.unpack("!Q", data) + if max_size is not None and length > max_size: + raise PayloadTooBig(length, max_size) + if mask: + mask_bytes = yield from read_exact(4) + + # Read the data. + data = yield from read_exact(length) + if mask: + data = apply_mask(data, mask_bytes) + + frame = cls(opcode, data, fin, rsv1, rsv2, rsv3) + + if extensions is None: + extensions = [] + for extension in reversed(extensions): + frame = extension.decode(frame, max_size=max_size) + + frame.check() + + return frame + + def serialize( + self, + *, + mask: bool, + extensions: Sequence[extensions.Extension] | None = None, + ) -> bytes: + """ + Serialize a WebSocket frame. + + Args: + mask: Whether the frame should be masked i.e. whether the write + happens on the client side. + extensions: List of extensions, applied in order. + + Raises: + ProtocolError: If the frame contains incorrect values. + + """ + self.check() + + if extensions is None: + extensions = [] + for extension in extensions: + self = extension.encode(self) + + output = io.BytesIO() + + # Prepare the header. + head1 = ( + (0b10000000 if self.fin else 0) + | (0b01000000 if self.rsv1 else 0) + | (0b00100000 if self.rsv2 else 0) + | (0b00010000 if self.rsv3 else 0) + | self.opcode + ) + + head2 = 0b10000000 if mask else 0 + + length = len(self.data) + if length < 126: + output.write(struct.pack("!BB", head1, head2 | length)) + elif length < 65536: + output.write(struct.pack("!BBH", head1, head2 | 126, length)) + else: + output.write(struct.pack("!BBQ", head1, head2 | 127, length)) + + if mask: + mask_bytes = secrets.token_bytes(4) + output.write(mask_bytes) + + # Prepare the data. + if mask: + data = apply_mask(self.data, mask_bytes) + else: + data = self.data + output.write(data) + + return output.getvalue() + + def check(self) -> None: + """ + Check that reserved bits and opcode have acceptable values. + + Raises: + ProtocolError: If a reserved bit or the opcode is invalid. + + """ + if self.rsv1 or self.rsv2 or self.rsv3: + raise ProtocolError("reserved bits must be 0") + + if self.opcode in CTRL_OPCODES: + if len(self.data) > 125: + raise ProtocolError("control frame too long") + if not self.fin: + raise ProtocolError("fragmented control frame") + + +@dataclasses.dataclass +class Close: + """ + Code and reason for WebSocket close frames. + + Attributes: + code: Close code. + reason: Close reason. + + """ + + code: int + reason: str + + def __str__(self) -> str: + """ + Return a human-readable representation of a close code and reason. + + """ + if 3000 <= self.code < 4000: + explanation = "registered" + elif 4000 <= self.code < 5000: + explanation = "private use" + else: + explanation = CLOSE_CODE_EXPLANATIONS.get(self.code, "unknown") + result = f"{self.code} ({explanation})" + + if self.reason: + result = f"{result} {self.reason}" + + return result + + @classmethod + def parse(cls, data: bytes) -> Close: + """ + Parse the payload of a close frame. + + Args: + data: Payload of the close frame. + + Raises: + ProtocolError: If data is ill-formed. + UnicodeDecodeError: If the reason isn't valid UTF-8. + + """ + if len(data) >= 2: + (code,) = struct.unpack("!H", data[:2]) + reason = data[2:].decode() + close = cls(code, reason) + close.check() + return close + elif len(data) == 0: + return cls(CloseCode.NO_STATUS_RCVD, "") + else: + raise ProtocolError("close frame too short") + + def serialize(self) -> bytes: + """ + Serialize the payload of a close frame. + + """ + self.check() + return struct.pack("!H", self.code) + self.reason.encode() + + def check(self) -> None: + """ + Check that the close code has a valid value for a close frame. + + Raises: + ProtocolError: If the close code is invalid. + + """ + if not (self.code in EXTERNAL_CLOSE_CODES or 3000 <= self.code < 5000): + raise ProtocolError("invalid status code") + + +# At the bottom to break import cycles created by type annotations. +from . import extensions # noqa: E402 diff --git a/venv/lib/python3.10/site-packages/websockets/headers.py b/venv/lib/python3.10/site-packages/websockets/headers.py new file mode 100644 index 0000000000000000000000000000000000000000..e05ff5b4c34fcd3b3021eb6456e9b2d71dbe0222 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/headers.py @@ -0,0 +1,586 @@ +from __future__ import annotations + +import base64 +import binascii +import ipaddress +import re +from collections.abc import Sequence +from typing import Callable, TypeVar, cast + +from .exceptions import InvalidHeaderFormat, InvalidHeaderValue +from .typing import ( + ConnectionOption, + ExtensionHeader, + ExtensionName, + ExtensionParameter, + Subprotocol, + UpgradeProtocol, +) + + +__all__ = [ + "build_host", + "parse_connection", + "parse_upgrade", + "parse_extension", + "build_extension", + "parse_subprotocol", + "build_subprotocol", + "validate_subprotocols", + "build_www_authenticate_basic", + "parse_authorization_basic", + "build_authorization_basic", +] + + +T = TypeVar("T") + + +def build_host( + host: str, + port: int, + secure: bool, + *, + always_include_port: bool = False, +) -> str: + """ + Build a ``Host`` header. + + """ + # https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2 + # IPv6 addresses must be enclosed in brackets. + try: + address = ipaddress.ip_address(host) + except ValueError: + # host is a hostname + pass + else: + # host is an IP address + if address.version == 6: + host = f"[{host}]" + + if always_include_port or port != (443 if secure else 80): + host = f"{host}:{port}" + + return host + + +# To avoid a dependency on a parsing library, we implement manually the ABNF +# described in https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 and +# https://datatracker.ietf.org/doc/html/rfc7230#appendix-B. + + +def peek_ahead(header: str, pos: int) -> str | None: + """ + Return the next character from ``header`` at the given position. + + Return :obj:`None` at the end of ``header``. + + We never need to peek more than one character ahead. + + """ + return None if pos == len(header) else header[pos] + + +_OWS_re = re.compile(r"[\t ]*") + + +def parse_OWS(header: str, pos: int) -> int: + """ + Parse optional whitespace from ``header`` at the given position. + + Return the new position. + + The whitespace itself isn't returned because it isn't significant. + + """ + # There's always a match, possibly empty, whose content doesn't matter. + match = _OWS_re.match(header, pos) + assert match is not None + return match.end() + + +_token_re = re.compile(r"[-!#$%&\'*+.^_`|~0-9a-zA-Z]+") + + +def parse_token(header: str, pos: int, header_name: str) -> tuple[str, int]: + """ + Parse a token from ``header`` at the given position. + + Return the token value and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + match = _token_re.match(header, pos) + if match is None: + raise InvalidHeaderFormat(header_name, "expected token", header, pos) + return match.group(), match.end() + + +_quoted_string_re = re.compile( + r'"(?:[\x09\x20-\x21\x23-\x5b\x5d-\x7e]|\\[\x09\x20-\x7e\x80-\xff])*"' +) + + +_unquote_re = re.compile(r"\\([\x09\x20-\x7e\x80-\xff])") + + +def parse_quoted_string(header: str, pos: int, header_name: str) -> tuple[str, int]: + """ + Parse a quoted string from ``header`` at the given position. + + Return the unquoted value and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + match = _quoted_string_re.match(header, pos) + if match is None: + raise InvalidHeaderFormat(header_name, "expected quoted string", header, pos) + return _unquote_re.sub(r"\1", match.group()[1:-1]), match.end() + + +_quotable_re = re.compile(r"[\x09\x20-\x7e\x80-\xff]*") + + +_quote_re = re.compile(r"([\x22\x5c])") + + +def build_quoted_string(value: str) -> str: + """ + Format ``value`` as a quoted string. + + This is the reverse of :func:`parse_quoted_string`. + + """ + match = _quotable_re.fullmatch(value) + if match is None: + raise ValueError("invalid characters for quoted-string encoding") + return '"' + _quote_re.sub(r"\\\1", value) + '"' + + +def parse_list( + parse_item: Callable[[str, int, str], tuple[T, int]], + header: str, + pos: int, + header_name: str, +) -> list[T]: + """ + Parse a comma-separated list from ``header`` at the given position. + + This is appropriate for parsing values with the following grammar: + + 1#item + + ``parse_item`` parses one item. + + ``header`` is assumed not to start or end with whitespace. + + (This function is designed for parsing an entire header value and + :func:`~websockets.http.read_headers` strips whitespace from values.) + + Return a list of items. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + # Per https://datatracker.ietf.org/doc/html/rfc7230#section-7, "a recipient + # MUST parse and ignore a reasonable number of empty list elements"; + # hence while loops that remove extra delimiters. + + # Remove extra delimiters before the first item. + while peek_ahead(header, pos) == ",": + pos = parse_OWS(header, pos + 1) + + items = [] + while True: + # Loop invariant: a item starts at pos in header. + item, pos = parse_item(header, pos, header_name) + items.append(item) + pos = parse_OWS(header, pos) + + # We may have reached the end of the header. + if pos == len(header): + break + + # There must be a delimiter after each element except the last one. + if peek_ahead(header, pos) == ",": + pos = parse_OWS(header, pos + 1) + else: + raise InvalidHeaderFormat(header_name, "expected comma", header, pos) + + # Remove extra delimiters before the next item. + while peek_ahead(header, pos) == ",": + pos = parse_OWS(header, pos + 1) + + # We may have reached the end of the header. + if pos == len(header): + break + + # Since we only advance in the header by one character with peek_ahead() + # or with the end position of a regex match, we can't overshoot the end. + assert pos == len(header) + + return items + + +def parse_connection_option( + header: str, pos: int, header_name: str +) -> tuple[ConnectionOption, int]: + """ + Parse a Connection option from ``header`` at the given position. + + Return the protocol value and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + item, pos = parse_token(header, pos, header_name) + return cast(ConnectionOption, item), pos + + +def parse_connection(header: str) -> list[ConnectionOption]: + """ + Parse a ``Connection`` header. + + Return a list of HTTP connection options. + + Args + header: value of the ``Connection`` header. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + return parse_list(parse_connection_option, header, 0, "Connection") + + +_protocol_re = re.compile( + r"[-!#$%&\'*+.^_`|~0-9a-zA-Z]+(?:/[-!#$%&\'*+.^_`|~0-9a-zA-Z]+)?" +) + + +def parse_upgrade_protocol( + header: str, pos: int, header_name: str +) -> tuple[UpgradeProtocol, int]: + """ + Parse an Upgrade protocol from ``header`` at the given position. + + Return the protocol value and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + match = _protocol_re.match(header, pos) + if match is None: + raise InvalidHeaderFormat(header_name, "expected protocol", header, pos) + return cast(UpgradeProtocol, match.group()), match.end() + + +def parse_upgrade(header: str) -> list[UpgradeProtocol]: + """ + Parse an ``Upgrade`` header. + + Return a list of HTTP protocols. + + Args: + header: Value of the ``Upgrade`` header. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + return parse_list(parse_upgrade_protocol, header, 0, "Upgrade") + + +def parse_extension_item_param( + header: str, pos: int, header_name: str +) -> tuple[ExtensionParameter, int]: + """ + Parse a single extension parameter from ``header`` at the given position. + + Return a ``(name, value)`` pair and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + # Extract parameter name. + name, pos = parse_token(header, pos, header_name) + pos = parse_OWS(header, pos) + # Extract parameter value, if there is one. + value: str | None = None + if peek_ahead(header, pos) == "=": + pos = parse_OWS(header, pos + 1) + if peek_ahead(header, pos) == '"': + pos_before = pos # for proper error reporting below + value, pos = parse_quoted_string(header, pos, header_name) + # https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 says: + # the value after quoted-string unescaping MUST conform to + # the 'token' ABNF. + if _token_re.fullmatch(value) is None: + raise InvalidHeaderFormat( + header_name, "invalid quoted header content", header, pos_before + ) + else: + value, pos = parse_token(header, pos, header_name) + pos = parse_OWS(header, pos) + + return (name, value), pos + + +def parse_extension_item( + header: str, pos: int, header_name: str +) -> tuple[ExtensionHeader, int]: + """ + Parse an extension definition from ``header`` at the given position. + + Return an ``(extension name, parameters)`` pair, where ``parameters`` is a + list of ``(name, value)`` pairs, and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + # Extract extension name. + name, pos = parse_token(header, pos, header_name) + pos = parse_OWS(header, pos) + # Extract all parameters. + parameters = [] + while peek_ahead(header, pos) == ";": + pos = parse_OWS(header, pos + 1) + parameter, pos = parse_extension_item_param(header, pos, header_name) + parameters.append(parameter) + return (cast(ExtensionName, name), parameters), pos + + +def parse_extension(header: str) -> list[ExtensionHeader]: + """ + Parse a ``Sec-WebSocket-Extensions`` header. + + Return a list of WebSocket extensions and their parameters in this format:: + + [ + ( + 'extension name', + [ + ('parameter name', 'parameter value'), + .... + ] + ), + ... + ] + + Parameter values are :obj:`None` when no value is provided. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + return parse_list(parse_extension_item, header, 0, "Sec-WebSocket-Extensions") + + +parse_extension_list = parse_extension # alias for backwards compatibility + + +def build_extension_item( + name: ExtensionName, parameters: Sequence[ExtensionParameter] +) -> str: + """ + Build an extension definition. + + This is the reverse of :func:`parse_extension_item`. + + """ + return "; ".join( + [cast(str, name)] + + [ + # Quoted strings aren't necessary because values are always tokens. + name if value is None else f"{name}={value}" + for name, value in parameters + ] + ) + + +def build_extension(extensions: Sequence[ExtensionHeader]) -> str: + """ + Build a ``Sec-WebSocket-Extensions`` header. + + This is the reverse of :func:`parse_extension`. + + """ + return ", ".join( + build_extension_item(name, parameters) for name, parameters in extensions + ) + + +build_extension_list = build_extension # alias for backwards compatibility + + +def parse_subprotocol_item( + header: str, pos: int, header_name: str +) -> tuple[Subprotocol, int]: + """ + Parse a subprotocol from ``header`` at the given position. + + Return the subprotocol value and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + item, pos = parse_token(header, pos, header_name) + return cast(Subprotocol, item), pos + + +def parse_subprotocol(header: str) -> list[Subprotocol]: + """ + Parse a ``Sec-WebSocket-Protocol`` header. + + Return a list of WebSocket subprotocols. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + return parse_list(parse_subprotocol_item, header, 0, "Sec-WebSocket-Protocol") + + +parse_subprotocol_list = parse_subprotocol # alias for backwards compatibility + + +def build_subprotocol(subprotocols: Sequence[Subprotocol]) -> str: + """ + Build a ``Sec-WebSocket-Protocol`` header. + + This is the reverse of :func:`parse_subprotocol`. + + """ + return ", ".join(subprotocols) + + +build_subprotocol_list = build_subprotocol # alias for backwards compatibility + + +def validate_subprotocols(subprotocols: Sequence[Subprotocol]) -> None: + """ + Validate that ``subprotocols`` is suitable for :func:`build_subprotocol`. + + """ + if not isinstance(subprotocols, Sequence): + raise TypeError("subprotocols must be a list") + if isinstance(subprotocols, str): + raise TypeError("subprotocols must be a list, not a str") + for subprotocol in subprotocols: + if not _token_re.fullmatch(subprotocol): + raise ValueError(f"invalid subprotocol: {subprotocol}") + + +def build_www_authenticate_basic(realm: str) -> str: + """ + Build a ``WWW-Authenticate`` header for HTTP Basic Auth. + + Args: + realm: Identifier of the protection space. + + """ + # https://datatracker.ietf.org/doc/html/rfc7617#section-2 + realm = build_quoted_string(realm) + charset = build_quoted_string("UTF-8") + return f"Basic realm={realm}, charset={charset}" + + +_token68_re = re.compile(r"[A-Za-z0-9-._~+/]+=*") + + +def parse_token68(header: str, pos: int, header_name: str) -> tuple[str, int]: + """ + Parse a token68 from ``header`` at the given position. + + Return the token value and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + match = _token68_re.match(header, pos) + if match is None: + raise InvalidHeaderFormat(header_name, "expected token68", header, pos) + return match.group(), match.end() + + +def parse_end(header: str, pos: int, header_name: str) -> None: + """ + Check that parsing reached the end of header. + + """ + if pos < len(header): + raise InvalidHeaderFormat(header_name, "trailing data", header, pos) + + +def parse_authorization_basic(header: str) -> tuple[str, str]: + """ + Parse an ``Authorization`` header for HTTP Basic Auth. + + Return a ``(username, password)`` tuple. + + Args: + header: Value of the ``Authorization`` header. + + Raises: + InvalidHeaderFormat: On invalid inputs. + InvalidHeaderValue: On unsupported inputs. + + """ + # https://datatracker.ietf.org/doc/html/rfc7235#section-2.1 + # https://datatracker.ietf.org/doc/html/rfc7617#section-2 + scheme, pos = parse_token(header, 0, "Authorization") + if scheme.lower() != "basic": + raise InvalidHeaderValue( + "Authorization", + f"unsupported scheme: {scheme}", + ) + if peek_ahead(header, pos) != " ": + raise InvalidHeaderFormat( + "Authorization", "expected space after scheme", header, pos + ) + pos += 1 + basic_credentials, pos = parse_token68(header, pos, "Authorization") + parse_end(header, pos, "Authorization") + + try: + user_pass = base64.b64decode(basic_credentials.encode()).decode() + except binascii.Error: + raise InvalidHeaderValue( + "Authorization", + "expected base64-encoded credentials", + ) from None + try: + username, password = user_pass.split(":", 1) + except ValueError: + raise InvalidHeaderValue( + "Authorization", + "expected username:password credentials", + ) from None + + return username, password + + +def build_authorization_basic(username: str, password: str) -> str: + """ + Build an ``Authorization`` header for HTTP Basic Auth. + + This is the reverse of :func:`parse_authorization_basic`. + + """ + # https://datatracker.ietf.org/doc/html/rfc7617#section-2 + assert ":" not in username + user_pass = f"{username}:{password}" + basic_credentials = base64.b64encode(user_pass.encode()).decode() + return "Basic " + basic_credentials diff --git a/venv/lib/python3.10/site-packages/websockets/http.py b/venv/lib/python3.10/site-packages/websockets/http.py new file mode 100644 index 0000000000000000000000000000000000000000..0d860e5379404c12f8fb4177ca4fcb6764b86f3b --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/http.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import warnings + +from .datastructures import Headers, MultipleValuesError # noqa: F401 + + +with warnings.catch_warnings(): + # Suppress redundant DeprecationWarning raised by websockets.legacy. + warnings.filterwarnings("ignore", category=DeprecationWarning) + from .legacy.http import read_request, read_response # noqa: F401 + + +warnings.warn( # deprecated in 9.0 - 2021-09-01 + "Headers and MultipleValuesError were moved " + "from websockets.http to websockets.datastructures" + "and read_request and read_response were moved " + "from websockets.http to websockets.legacy.http", + DeprecationWarning, +) diff --git a/venv/lib/python3.10/site-packages/websockets/http11.py b/venv/lib/python3.10/site-packages/websockets/http11.py new file mode 100644 index 0000000000000000000000000000000000000000..530ac3d09e386996e77cfbd6e5c077d3a45c96ab --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/http11.py @@ -0,0 +1,427 @@ +from __future__ import annotations + +import dataclasses +import os +import re +import sys +import warnings +from collections.abc import Generator +from typing import Callable + +from .datastructures import Headers +from .exceptions import SecurityError +from .version import version as websockets_version + + +__all__ = [ + "SERVER", + "USER_AGENT", + "Request", + "Response", +] + + +PYTHON_VERSION = "{}.{}".format(*sys.version_info) + +# User-Agent header for HTTP requests. +USER_AGENT = os.environ.get( + "WEBSOCKETS_USER_AGENT", + f"Python/{PYTHON_VERSION} websockets/{websockets_version}", +) + +# Server header for HTTP responses. +SERVER = os.environ.get( + "WEBSOCKETS_SERVER", + f"Python/{PYTHON_VERSION} websockets/{websockets_version}", +) + +# Maximum total size of headers is around 128 * 8 KiB = 1 MiB. +MAX_NUM_HEADERS = int(os.environ.get("WEBSOCKETS_MAX_NUM_HEADERS", "128")) + +# Limit request line and header lines. 8KiB is the most common default +# configuration of popular HTTP servers. +MAX_LINE_LENGTH = int(os.environ.get("WEBSOCKETS_MAX_LINE_LENGTH", "8192")) + +# Support for HTTP response bodies is intended to read an error message +# returned by a server. It isn't designed to perform large file transfers. +MAX_BODY_SIZE = int(os.environ.get("WEBSOCKETS_MAX_BODY_SIZE", "1_048_576")) # 1 MiB + + +def d(value: bytes) -> str: + """ + Decode a bytestring for interpolating into an error message. + + """ + return value.decode(errors="backslashreplace") + + +# See https://datatracker.ietf.org/doc/html/rfc7230#appendix-B. + +# Regex for validating header names. + +_token_re = re.compile(rb"[-!#$%&\'*+.^_`|~0-9a-zA-Z]+") + +# Regex for validating header values. + +# We don't attempt to support obsolete line folding. + +# Include HTAB (\x09), SP (\x20), VCHAR (\x21-\x7e), obs-text (\x80-\xff). + +# The ABNF is complicated because it attempts to express that optional +# whitespace is ignored. We strip whitespace and don't revalidate that. + +# See also https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189 + +_value_re = re.compile(rb"[\x09\x20-\x7e\x80-\xff]*") + + +@dataclasses.dataclass +class Request: + """ + WebSocket handshake request. + + Attributes: + path: Request path, including optional query. + headers: Request headers. + """ + + path: str + headers: Headers + # body isn't useful is the context of this library. + + _exception: Exception | None = None + + @property + def exception(self) -> Exception | None: # pragma: no cover + warnings.warn( # deprecated in 10.3 - 2022-04-17 + "Request.exception is deprecated; use ServerProtocol.handshake_exc instead", + DeprecationWarning, + ) + return self._exception + + @classmethod + def parse( + cls, + read_line: Callable[[int], Generator[None, None, bytes]], + ) -> Generator[None, None, Request]: + """ + Parse a WebSocket handshake request. + + This is a generator-based coroutine. + + The request path isn't URL-decoded or validated in any way. + + The request path and headers are expected to contain only ASCII + characters. Other characters are represented with surrogate escapes. + + :meth:`parse` doesn't attempt to read the request body because + WebSocket handshake requests don't have one. If the request contains a + body, it may be read from the data stream after :meth:`parse` returns. + + Args: + read_line: Generator-based coroutine that reads a LF-terminated + line or raises an exception if there isn't enough data + + Raises: + EOFError: If the connection is closed without a full HTTP request. + SecurityError: If the request exceeds a security limit. + ValueError: If the request isn't well formatted. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.1 + + # Parsing is simple because fixed values are expected for method and + # version and because path isn't checked. Since WebSocket software tends + # to implement HTTP/1.1 strictly, there's little need for lenient parsing. + + try: + request_line = yield from parse_line(read_line) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP request line") from exc + + try: + method, raw_path, protocol = request_line.split(b" ", 2) + except ValueError: # not enough values to unpack (expected 3, got 1-2) + raise ValueError(f"invalid HTTP request line: {d(request_line)}") from None + if protocol != b"HTTP/1.1": + raise ValueError( + f"unsupported protocol; expected HTTP/1.1: {d(request_line)}" + ) + if method != b"GET": + raise ValueError(f"unsupported HTTP method; expected GET; got {d(method)}") + path = raw_path.decode("ascii", "surrogateescape") + + headers = yield from parse_headers(read_line) + + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.3 + + if "Transfer-Encoding" in headers: + raise NotImplementedError("transfer codings aren't supported") + + if "Content-Length" in headers: + raise ValueError("unsupported request body") + + return cls(path, headers) + + def serialize(self) -> bytes: + """ + Serialize a WebSocket handshake request. + + """ + # Since the request line and headers only contain ASCII characters, + # we can keep this simple. + request = f"GET {self.path} HTTP/1.1\r\n".encode() + request += self.headers.serialize() + return request + + +@dataclasses.dataclass +class Response: + """ + WebSocket handshake response. + + Attributes: + status_code: Response code. + reason_phrase: Response reason. + headers: Response headers. + body: Response body. + + """ + + status_code: int + reason_phrase: str + headers: Headers + body: bytes = b"" + + _exception: Exception | None = None + + @property + def exception(self) -> Exception | None: # pragma: no cover + warnings.warn( # deprecated in 10.3 - 2022-04-17 + "Response.exception is deprecated; " + "use ClientProtocol.handshake_exc instead", + DeprecationWarning, + ) + return self._exception + + @classmethod + def parse( + cls, + read_line: Callable[[int], Generator[None, None, bytes]], + read_exact: Callable[[int], Generator[None, None, bytes]], + read_to_eof: Callable[[int], Generator[None, None, bytes]], + include_body: bool = True, + ) -> Generator[None, None, Response]: + """ + Parse a WebSocket handshake response. + + This is a generator-based coroutine. + + The reason phrase and headers are expected to contain only ASCII + characters. Other characters are represented with surrogate escapes. + + Args: + read_line: Generator-based coroutine that reads a LF-terminated + line or raises an exception if there isn't enough data. + read_exact: Generator-based coroutine that reads the requested + bytes or raises an exception if there isn't enough data. + read_to_eof: Generator-based coroutine that reads until the end + of the stream. + + Raises: + EOFError: If the connection is closed without a full HTTP response. + SecurityError: If the response exceeds a security limit. + LookupError: If the response isn't well formatted. + ValueError: If the response isn't well formatted. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2 + + try: + status_line = yield from parse_line(read_line) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP status line") from exc + + try: + protocol, raw_status_code, raw_reason = status_line.split(b" ", 2) + except ValueError: # not enough values to unpack (expected 3, got 1-2) + raise ValueError(f"invalid HTTP status line: {d(status_line)}") from None + if protocol != b"HTTP/1.1": + raise ValueError( + f"unsupported protocol; expected HTTP/1.1: {d(status_line)}" + ) + try: + status_code = int(raw_status_code) + except ValueError: # invalid literal for int() with base 10 + raise ValueError( + f"invalid status code; expected integer; got {d(raw_status_code)}" + ) from None + if not 100 <= status_code < 600: + raise ValueError( + f"invalid status code; expected 100–599; got {d(raw_status_code)}" + ) + if not _value_re.fullmatch(raw_reason): + raise ValueError(f"invalid HTTP reason phrase: {d(raw_reason)}") + reason = raw_reason.decode("ascii", "surrogateescape") + + headers = yield from parse_headers(read_line) + + if include_body: + body = yield from read_body( + status_code, headers, read_line, read_exact, read_to_eof + ) + else: + body = b"" + + return cls(status_code, reason, headers, body) + + def serialize(self) -> bytes: + """ + Serialize a WebSocket handshake response. + + """ + # Since the status line and headers only contain ASCII characters, + # we can keep this simple. + response = f"HTTP/1.1 {self.status_code} {self.reason_phrase}\r\n".encode() + response += self.headers.serialize() + response += self.body + return response + + +def parse_line( + read_line: Callable[[int], Generator[None, None, bytes]], +) -> Generator[None, None, bytes]: + """ + Parse a single line. + + CRLF is stripped from the return value. + + Args: + read_line: Generator-based coroutine that reads a LF-terminated line + or raises an exception if there isn't enough data. + + Raises: + EOFError: If the connection is closed without a CRLF. + SecurityError: If the response exceeds a security limit. + + """ + try: + line = yield from read_line(MAX_LINE_LENGTH) + except RuntimeError: + raise SecurityError("line too long") + # Not mandatory but safe - https://datatracker.ietf.org/doc/html/rfc7230#section-3.5 + if not line.endswith(b"\r\n"): + raise EOFError("line without CRLF") + return line[:-2] + + +def parse_headers( + read_line: Callable[[int], Generator[None, None, bytes]], +) -> Generator[None, None, Headers]: + """ + Parse HTTP headers. + + Non-ASCII characters are represented with surrogate escapes. + + Args: + read_line: Generator-based coroutine that reads a LF-terminated line + or raises an exception if there isn't enough data. + + Raises: + EOFError: If the connection is closed without complete headers. + SecurityError: If the request exceeds a security limit. + ValueError: If the request isn't well formatted. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 + + # We don't attempt to support obsolete line folding. + + headers = Headers() + for _ in range(MAX_NUM_HEADERS + 1): + try: + line = yield from parse_line(read_line) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP headers") from exc + if line == b"": + break + + try: + raw_name, raw_value = line.split(b":", 1) + except ValueError: # not enough values to unpack (expected 2, got 1) + raise ValueError(f"invalid HTTP header line: {d(line)}") from None + if not _token_re.fullmatch(raw_name): + raise ValueError(f"invalid HTTP header name: {d(raw_name)}") + raw_value = raw_value.strip(b" \t") + if not _value_re.fullmatch(raw_value): + raise ValueError(f"invalid HTTP header value: {d(raw_value)}") + + name = raw_name.decode("ascii") # guaranteed to be ASCII at this point + value = raw_value.decode("ascii", "surrogateescape") + headers[name] = value + + else: + raise SecurityError("too many HTTP headers") + + return headers + + +def read_body( + status_code: int, + headers: Headers, + read_line: Callable[[int], Generator[None, None, bytes]], + read_exact: Callable[[int], Generator[None, None, bytes]], + read_to_eof: Callable[[int], Generator[None, None, bytes]], +) -> Generator[None, None, bytes]: + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.3 + + # Since websockets only does GET requests (no HEAD, no CONNECT), all + # responses except 1xx, 204, and 304 include a message body. + if 100 <= status_code < 200 or status_code == 204 or status_code == 304: + return b"" + + # MultipleValuesError is sufficiently unlikely that we don't attempt to + # handle it when accessing headers. Instead we document that its parent + # class, LookupError, may be raised. + # Conversions from str to int are protected by sys.set_int_max_str_digits.. + + elif (coding := headers.get("Transfer-Encoding")) is not None: + if coding != "chunked": + raise NotImplementedError(f"transfer coding {coding} isn't supported") + + body = b"" + while True: + chunk_size_line = yield from parse_line(read_line) + raw_chunk_size = chunk_size_line.split(b";", 1)[0] + # Set a lower limit than default_max_str_digits; 1 EB is plenty. + if len(raw_chunk_size) > 15: + str_chunk_size = raw_chunk_size.decode(errors="backslashreplace") + raise SecurityError(f"chunk too large: 0x{str_chunk_size} bytes") + chunk_size = int(raw_chunk_size, 16) + if chunk_size == 0: + break + if len(body) + chunk_size > MAX_BODY_SIZE: + raise SecurityError( + f"chunk too large: {chunk_size} bytes after {len(body)} bytes" + ) + body += yield from read_exact(chunk_size) + if (yield from read_exact(2)) != b"\r\n": + raise ValueError("chunk without CRLF") + # Read the trailer. + yield from parse_headers(read_line) + return body + + elif (raw_content_length := headers.get("Content-Length")) is not None: + # Set a lower limit than default_max_str_digits; 1 EiB is plenty. + if len(raw_content_length) > 18: + raise SecurityError(f"body too large: {raw_content_length} bytes") + content_length = int(raw_content_length) + if content_length > MAX_BODY_SIZE: + raise SecurityError(f"body too large: {content_length} bytes") + return (yield from read_exact(content_length)) + + else: + try: + return (yield from read_to_eof(MAX_BODY_SIZE)) + except RuntimeError: + raise SecurityError(f"body too large: over {MAX_BODY_SIZE} bytes") diff --git a/venv/lib/python3.10/site-packages/websockets/imports.py b/venv/lib/python3.10/site-packages/websockets/imports.py new file mode 100644 index 0000000000000000000000000000000000000000..c63fb212ec602ae6ec75fe1b86a29fb2e11334df --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/imports.py @@ -0,0 +1,100 @@ +from __future__ import annotations + +import warnings +from collections.abc import Iterable +from typing import Any + + +__all__ = ["lazy_import"] + + +def import_name(name: str, source: str, namespace: dict[str, Any]) -> Any: + """ + Import ``name`` from ``source`` in ``namespace``. + + There are two use cases: + + - ``name`` is an object defined in ``source``; + - ``name`` is a submodule of ``source``. + + Neither :func:`__import__` nor :func:`~importlib.import_module` does + exactly this. :func:`__import__` is closer to the intended behavior. + + """ + level = 0 + while source[level] == ".": + level += 1 + assert level < len(source), "importing from parent isn't supported" + module = __import__(source[level:], namespace, None, [name], level) + return getattr(module, name) + + +def lazy_import( + namespace: dict[str, Any], + aliases: dict[str, str] | None = None, + deprecated_aliases: dict[str, str] | None = None, +) -> None: + """ + Provide lazy, module-level imports. + + Typical use:: + + __getattr__, __dir__ = lazy_import( + globals(), + aliases={ + "": "", + ... + }, + deprecated_aliases={ + ..., + } + ) + + This function defines ``__getattr__`` and ``__dir__`` per :pep:`562`. + + """ + if aliases is None: + aliases = {} + if deprecated_aliases is None: + deprecated_aliases = {} + + namespace_set = set(namespace) + aliases_set = set(aliases) + deprecated_aliases_set = set(deprecated_aliases) + + assert not namespace_set & aliases_set, "namespace conflict" + assert not namespace_set & deprecated_aliases_set, "namespace conflict" + assert not aliases_set & deprecated_aliases_set, "namespace conflict" + + package = namespace["__name__"] + + def __getattr__(name: str) -> Any: + assert aliases is not None # mypy cannot figure this out + try: + source = aliases[name] + except KeyError: + pass + else: + return import_name(name, source, namespace) + + assert deprecated_aliases is not None # mypy cannot figure this out + try: + source = deprecated_aliases[name] + except KeyError: + pass + else: + warnings.warn( + f"{package}.{name} is deprecated", + DeprecationWarning, + stacklevel=2, + ) + return import_name(name, source, namespace) + + raise AttributeError(f"module {package!r} has no attribute {name!r}") + + namespace["__getattr__"] = __getattr__ + + def __dir__() -> Iterable[str]: + return sorted(namespace_set | aliases_set | deprecated_aliases_set) + + namespace["__dir__"] = __dir__ diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/__init__.py b/venv/lib/python3.10/site-packages/websockets/legacy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9aa25064f626754bda8a8bb149d974002a064e --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/legacy/__init__.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +import warnings + + +warnings.warn( # deprecated in 14.0 - 2024-11-09 + "websockets.legacy is deprecated; " + "see https://websockets.readthedocs.io/en/stable/howto/upgrade.html " + "for upgrade instructions", + DeprecationWarning, +) diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9b4e416e309542f6ee668e9dad692e7808b525a Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/auth.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/auth.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c10915649004ac08c6e4da7996d3323ee0316802 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/auth.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/client.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/client.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c562f82ca32714aa56e95f32e39038d375f5ef54 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/client.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/exceptions.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..323036d0ef888f468c6a9c1e2e9231472cebeec0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/exceptions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/framing.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/framing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4f258305235c2c52a6eb837c5236a3ef86e67ea Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/framing.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/handshake.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/handshake.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1172aa13b0a1fb2594f5ba6129854a96033ec312 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/handshake.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/http.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/http.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9125912bc6efd7650ae1bc1cc8f9111dac3a40a Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/http.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/protocol.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/protocol.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92c40ea4c917569ef6cbfa0643027775fe29ea17 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/protocol.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/server.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/server.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ba00d8d20254c22a8f823acd6960fd4bc346595 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/legacy/__pycache__/server.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/auth.py b/venv/lib/python3.10/site-packages/websockets/legacy/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..a262fcd791bc66a1ad0ee9389faed1c62c69e2be --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/legacy/auth.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import functools +import hmac +import http +from collections.abc import Awaitable, Iterable +from typing import Any, Callable, cast + +from ..datastructures import Headers +from ..exceptions import InvalidHeader +from ..headers import build_www_authenticate_basic, parse_authorization_basic +from .server import HTTPResponse, WebSocketServerProtocol + + +__all__ = ["BasicAuthWebSocketServerProtocol", "basic_auth_protocol_factory"] + +Credentials = tuple[str, str] + + +def is_credentials(value: Any) -> bool: + try: + username, password = value + except (TypeError, ValueError): + return False + else: + return isinstance(username, str) and isinstance(password, str) + + +class BasicAuthWebSocketServerProtocol(WebSocketServerProtocol): + """ + WebSocket server protocol that enforces HTTP Basic Auth. + + """ + + realm: str = "" + """ + Scope of protection. + + If provided, it should contain only ASCII characters because the + encoding of non-ASCII characters is undefined. + """ + + username: str | None = None + """Username of the authenticated user.""" + + def __init__( + self, + *args: Any, + realm: str | None = None, + check_credentials: Callable[[str, str], Awaitable[bool]] | None = None, + **kwargs: Any, + ) -> None: + if realm is not None: + self.realm = realm # shadow class attribute + self._check_credentials = check_credentials + super().__init__(*args, **kwargs) + + async def check_credentials(self, username: str, password: str) -> bool: + """ + Check whether credentials are authorized. + + This coroutine may be overridden in a subclass, for example to + authenticate against a database or an external service. + + Args: + username: HTTP Basic Auth username. + password: HTTP Basic Auth password. + + Returns: + :obj:`True` if the handshake should continue; + :obj:`False` if it should fail with an HTTP 401 error. + + """ + if self._check_credentials is not None: + return await self._check_credentials(username, password) + + return False + + async def process_request( + self, + path: str, + request_headers: Headers, + ) -> HTTPResponse | None: + """ + Check HTTP Basic Auth and return an HTTP 401 response if needed. + + """ + try: + authorization = request_headers["Authorization"] + except KeyError: + return ( + http.HTTPStatus.UNAUTHORIZED, + [("WWW-Authenticate", build_www_authenticate_basic(self.realm))], + b"Missing credentials\n", + ) + + try: + username, password = parse_authorization_basic(authorization) + except InvalidHeader: + return ( + http.HTTPStatus.UNAUTHORIZED, + [("WWW-Authenticate", build_www_authenticate_basic(self.realm))], + b"Unsupported credentials\n", + ) + + if not await self.check_credentials(username, password): + return ( + http.HTTPStatus.UNAUTHORIZED, + [("WWW-Authenticate", build_www_authenticate_basic(self.realm))], + b"Invalid credentials\n", + ) + + self.username = username + + return await super().process_request(path, request_headers) + + +def basic_auth_protocol_factory( + realm: str | None = None, + credentials: Credentials | Iterable[Credentials] | None = None, + check_credentials: Callable[[str, str], Awaitable[bool]] | None = None, + create_protocol: Callable[..., BasicAuthWebSocketServerProtocol] | None = None, +) -> Callable[..., BasicAuthWebSocketServerProtocol]: + """ + Protocol factory that enforces HTTP Basic Auth. + + :func:`basic_auth_protocol_factory` is designed to integrate with + :func:`~websockets.legacy.server.serve` like this:: + + serve( + ..., + create_protocol=basic_auth_protocol_factory( + realm="my dev server", + credentials=("hello", "iloveyou"), + ) + ) + + Args: + realm: Scope of protection. It should contain only ASCII characters + because the encoding of non-ASCII characters is undefined. + Refer to section 2.2 of :rfc:`7235` for details. + credentials: Hard coded authorized credentials. It can be a + ``(username, password)`` pair or a list of such pairs. + check_credentials: Coroutine that verifies credentials. + It receives ``username`` and ``password`` arguments + and returns a :class:`bool`. One of ``credentials`` or + ``check_credentials`` must be provided but not both. + create_protocol: Factory that creates the protocol. By default, this + is :class:`BasicAuthWebSocketServerProtocol`. It can be replaced + by a subclass. + Raises: + TypeError: If the ``credentials`` or ``check_credentials`` argument is + wrong. + + """ + if (credentials is None) == (check_credentials is None): + raise TypeError("provide either credentials or check_credentials") + + if credentials is not None: + if is_credentials(credentials): + credentials_list = [cast(Credentials, credentials)] + elif isinstance(credentials, Iterable): + credentials_list = list(cast(Iterable[Credentials], credentials)) + if not all(is_credentials(item) for item in credentials_list): + raise TypeError(f"invalid credentials argument: {credentials}") + else: + raise TypeError(f"invalid credentials argument: {credentials}") + + credentials_dict = dict(credentials_list) + + async def check_credentials(username: str, password: str) -> bool: + try: + expected_password = credentials_dict[username] + except KeyError: + return False + return hmac.compare_digest(expected_password, password) + + if create_protocol is None: + create_protocol = BasicAuthWebSocketServerProtocol + + # Help mypy and avoid this error: "type[BasicAuthWebSocketServerProtocol] | + # Callable[..., BasicAuthWebSocketServerProtocol]" not callable [misc] + create_protocol = cast( + Callable[..., BasicAuthWebSocketServerProtocol], create_protocol + ) + return functools.partial( + create_protocol, + realm=realm, + check_credentials=check_credentials, + ) diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/client.py b/venv/lib/python3.10/site-packages/websockets/legacy/client.py new file mode 100644 index 0000000000000000000000000000000000000000..29141f39a59c9ab01c6c7ae914cbed12e68ad66b --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/legacy/client.py @@ -0,0 +1,705 @@ +from __future__ import annotations + +import asyncio +import functools +import logging +import os +import random +import traceback +import urllib.parse +import warnings +from collections.abc import AsyncIterator, Generator, Sequence +from types import TracebackType +from typing import Any, Callable, cast + +from ..asyncio.compatibility import asyncio_timeout +from ..datastructures import Headers, HeadersLike +from ..exceptions import ( + InvalidHeader, + InvalidHeaderValue, + InvalidMessage, + NegotiationError, + SecurityError, +) +from ..extensions import ClientExtensionFactory, Extension +from ..extensions.permessage_deflate import enable_client_permessage_deflate +from ..headers import ( + build_authorization_basic, + build_extension, + build_host, + build_subprotocol, + parse_extension, + parse_subprotocol, + validate_subprotocols, +) +from ..http11 import USER_AGENT +from ..typing import ExtensionHeader, LoggerLike, Origin, Subprotocol +from ..uri import WebSocketURI, parse_uri +from .exceptions import InvalidStatusCode, RedirectHandshake +from .handshake import build_request, check_response +from .http import read_response +from .protocol import WebSocketCommonProtocol + + +__all__ = ["connect", "unix_connect", "WebSocketClientProtocol"] + + +class WebSocketClientProtocol(WebSocketCommonProtocol): + """ + WebSocket client connection. + + :class:`WebSocketClientProtocol` provides :meth:`recv` and :meth:`send` + coroutines for receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with close code + 1000 (OK) or 1001 (going away) or without a close code. It raises + a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection + is closed with any other code. + + See :func:`connect` for the documentation of ``logger``, ``origin``, + ``extensions``, ``subprotocols``, ``extra_headers``, and + ``user_agent_header``. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + """ + + is_client = True + side = "client" + + def __init__( + self, + *, + logger: LoggerLike | None = None, + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + **kwargs: Any, + ) -> None: + if logger is None: + logger = logging.getLogger("websockets.client") + super().__init__(logger=logger, **kwargs) + self.origin = origin + self.available_extensions = extensions + self.available_subprotocols = subprotocols + self.extra_headers = extra_headers + self.user_agent_header = user_agent_header + + def write_http_request(self, path: str, headers: Headers) -> None: + """ + Write request line and headers to the HTTP request. + + """ + self.path = path + self.request_headers = headers + + if self.debug: + self.logger.debug("> GET %s HTTP/1.1", path) + for key, value in headers.raw_items(): + self.logger.debug("> %s: %s", key, value) + + # Since the path and headers only contain ASCII characters, + # we can keep this simple. + request = f"GET {path} HTTP/1.1\r\n" + request += str(headers) + + self.transport.write(request.encode()) + + async def read_http_response(self) -> tuple[int, Headers]: + """ + Read status line and headers from the HTTP response. + + If the response contains a body, it may be read from ``self.reader`` + after this coroutine returns. + + Raises: + InvalidMessage: If the HTTP message is malformed or isn't an + HTTP/1.1 GET response. + + """ + try: + status_code, reason, headers = await read_response(self.reader) + except Exception as exc: + raise InvalidMessage("did not receive a valid HTTP response") from exc + + if self.debug: + self.logger.debug("< HTTP/1.1 %d %s", status_code, reason) + for key, value in headers.raw_items(): + self.logger.debug("< %s: %s", key, value) + + self.response_headers = headers + + return status_code, self.response_headers + + @staticmethod + def process_extensions( + headers: Headers, + available_extensions: Sequence[ClientExtensionFactory] | None, + ) -> list[Extension]: + """ + Handle the Sec-WebSocket-Extensions HTTP response header. + + Check that each extension is supported, as well as its parameters. + + Return the list of accepted extensions. + + Raise :exc:`~websockets.exceptions.InvalidHandshake` to abort the + connection. + + :rfc:`6455` leaves the rules up to the specification of each + :extension. + + To provide this level of flexibility, for each extension accepted by + the server, we check for a match with each extension available in the + client configuration. If no match is found, an exception is raised. + + If several variants of the same extension are accepted by the server, + it may be configured several times, which won't make sense in general. + Extensions must implement their own requirements. For this purpose, + the list of previously accepted extensions is provided. + + Other requirements, for example related to mandatory extensions or the + order of extensions, may be implemented by overriding this method. + + """ + accepted_extensions: list[Extension] = [] + + header_values = headers.get_all("Sec-WebSocket-Extensions") + + if header_values: + if available_extensions is None: + raise NegotiationError("no extensions supported") + + parsed_header_values: list[ExtensionHeader] = sum( + [parse_extension(header_value) for header_value in header_values], [] + ) + + for name, response_params in parsed_header_values: + for extension_factory in available_extensions: + # Skip non-matching extensions based on their name. + if extension_factory.name != name: + continue + + # Skip non-matching extensions based on their params. + try: + extension = extension_factory.process_response_params( + response_params, accepted_extensions + ) + except NegotiationError: + continue + + # Add matching extension to the final list. + accepted_extensions.append(extension) + + # Break out of the loop once we have a match. + break + + # If we didn't break from the loop, no extension in our list + # matched what the server sent. Fail the connection. + else: + raise NegotiationError( + f"Unsupported extension: " + f"name = {name}, params = {response_params}" + ) + + return accepted_extensions + + @staticmethod + def process_subprotocol( + headers: Headers, available_subprotocols: Sequence[Subprotocol] | None + ) -> Subprotocol | None: + """ + Handle the Sec-WebSocket-Protocol HTTP response header. + + Check that it contains exactly one supported subprotocol. + + Return the selected subprotocol. + + """ + subprotocol: Subprotocol | None = None + + header_values = headers.get_all("Sec-WebSocket-Protocol") + + if header_values: + if available_subprotocols is None: + raise NegotiationError("no subprotocols supported") + + parsed_header_values: Sequence[Subprotocol] = sum( + [parse_subprotocol(header_value) for header_value in header_values], [] + ) + + if len(parsed_header_values) > 1: + raise InvalidHeaderValue( + "Sec-WebSocket-Protocol", + f"multiple values: {', '.join(parsed_header_values)}", + ) + + subprotocol = parsed_header_values[0] + + if subprotocol not in available_subprotocols: + raise NegotiationError(f"unsupported subprotocol: {subprotocol}") + + return subprotocol + + async def handshake( + self, + wsuri: WebSocketURI, + origin: Origin | None = None, + available_extensions: Sequence[ClientExtensionFactory] | None = None, + available_subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLike | None = None, + ) -> None: + """ + Perform the client side of the opening handshake. + + Args: + wsuri: URI of the WebSocket server. + origin: Value of the ``Origin`` header. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + extra_headers: Arbitrary HTTP headers to add to the handshake request. + + Raises: + InvalidHandshake: If the handshake fails. + + """ + request_headers = Headers() + + request_headers["Host"] = build_host(wsuri.host, wsuri.port, wsuri.secure) + + if wsuri.user_info: + request_headers["Authorization"] = build_authorization_basic( + *wsuri.user_info + ) + + if origin is not None: + request_headers["Origin"] = origin + + key = build_request(request_headers) + + if available_extensions is not None: + extensions_header = build_extension( + [ + (extension_factory.name, extension_factory.get_request_params()) + for extension_factory in available_extensions + ] + ) + request_headers["Sec-WebSocket-Extensions"] = extensions_header + + if available_subprotocols is not None: + protocol_header = build_subprotocol(available_subprotocols) + request_headers["Sec-WebSocket-Protocol"] = protocol_header + + if self.extra_headers is not None: + request_headers.update(self.extra_headers) + + if self.user_agent_header: + request_headers.setdefault("User-Agent", self.user_agent_header) + + self.write_http_request(wsuri.resource_name, request_headers) + + status_code, response_headers = await self.read_http_response() + if status_code in (301, 302, 303, 307, 308): + if "Location" not in response_headers: + raise InvalidHeader("Location") + raise RedirectHandshake(response_headers["Location"]) + elif status_code != 101: + raise InvalidStatusCode(status_code, response_headers) + + check_response(response_headers, key) + + self.extensions = self.process_extensions( + response_headers, available_extensions + ) + + self.subprotocol = self.process_subprotocol( + response_headers, available_subprotocols + ) + + self.connection_open() + + +class Connect: + """ + Connect to the WebSocket server at ``uri``. + + Awaiting :func:`connect` yields a :class:`WebSocketClientProtocol` which + can then be used to send and receive messages. + + :func:`connect` can be used as a asynchronous context manager:: + + async with connect(...) as websocket: + ... + + The connection is closed automatically when exiting the context. + + :func:`connect` can be used as an infinite asynchronous iterator to + reconnect automatically on errors:: + + async for websocket in connect(...): + try: + ... + except websockets.exceptions.ConnectionClosed: + continue + + The connection is closed automatically after each iteration of the loop. + + If an error occurs while establishing the connection, :func:`connect` + retries with exponential backoff. The backoff delay starts at three + seconds and increases up to one minute. + + If an error occurs in the body of the loop, you can handle the exception + and :func:`connect` will reconnect with the next iteration; or you can + let the exception bubble up and break out of the loop. This lets you + decide which errors trigger a reconnection and which errors are fatal. + + Args: + uri: URI of the WebSocket server. + create_protocol: Factory for the :class:`asyncio.Protocol` managing + the connection. It defaults to :class:`WebSocketClientProtocol`. + Set it to a wrapper or a subclass to customize connection handling. + logger: Logger for this client. + It defaults to ``logging.getLogger("websockets.client")``. + See the :doc:`logging guide <../../topics/logging>` for details. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + origin: Value of the ``Origin`` header, for servers that require it. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + extra_headers: Arbitrary HTTP headers to add to the handshake request. + user_agent_header: Value of the ``User-Agent`` request header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + open_timeout: Timeout for opening the connection in seconds. + :obj:`None` disables the timeout. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + Any other keyword arguments are passed the event loop's + :meth:`~asyncio.loop.create_connection` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enforce TLS + settings. When connecting to a ``wss://`` URI, if ``ssl`` isn't + provided, a TLS context is created + with :func:`~ssl.create_default_context`. + + * You can set ``host`` and ``port`` to connect to a different host and + port from those found in ``uri``. This only changes the destination of + the TCP connection. The host name from ``uri`` is still used in the TLS + handshake for secure connections and in the ``Host`` header. + + Raises: + InvalidURI: If ``uri`` isn't a valid WebSocket URI. + OSError: If the TCP connection fails. + InvalidHandshake: If the opening handshake fails. + ~asyncio.TimeoutError: If the opening handshake times out. + + """ + + MAX_REDIRECTS_ALLOWED = int(os.environ.get("WEBSOCKETS_MAX_REDIRECTS", "10")) + + def __init__( + self, + uri: str, + *, + create_protocol: Callable[..., WebSocketClientProtocol] | None = None, + logger: LoggerLike | None = None, + compression: str | None = "deflate", + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = None, + max_size: int | None = 2**20, + max_queue: int | None = 2**5, + read_limit: int = 2**16, + write_limit: int = 2**16, + **kwargs: Any, + ) -> None: + # Backwards compatibility: close_timeout used to be called timeout. + timeout: float | None = kwargs.pop("timeout", None) + if timeout is None: + timeout = 10 + else: + warnings.warn("rename timeout to close_timeout", DeprecationWarning) + # If both are specified, timeout is ignored. + if close_timeout is None: + close_timeout = timeout + + # Backwards compatibility: create_protocol used to be called klass. + klass: type[WebSocketClientProtocol] | None = kwargs.pop("klass", None) + if klass is None: + klass = WebSocketClientProtocol + else: + warnings.warn("rename klass to create_protocol", DeprecationWarning) + # If both are specified, klass is ignored. + if create_protocol is None: + create_protocol = klass + + # Backwards compatibility: recv() used to return None on closed connections + legacy_recv: bool = kwargs.pop("legacy_recv", False) + + # Backwards compatibility: the loop parameter used to be supported. + _loop: asyncio.AbstractEventLoop | None = kwargs.pop("loop", None) + if _loop is None: + loop = asyncio.get_event_loop() + else: + loop = _loop + warnings.warn("remove loop argument", DeprecationWarning) + + wsuri = parse_uri(uri) + if wsuri.secure: + kwargs.setdefault("ssl", True) + elif kwargs.get("ssl") is not None: + raise ValueError( + "connect() received a ssl argument for a ws:// URI, " + "use a wss:// URI to enable TLS" + ) + + if compression == "deflate": + extensions = enable_client_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + # Help mypy and avoid this error: "type[WebSocketClientProtocol] | + # Callable[..., WebSocketClientProtocol]" not callable [misc] + create_protocol = cast(Callable[..., WebSocketClientProtocol], create_protocol) + factory = functools.partial( + create_protocol, + logger=logger, + origin=origin, + extensions=extensions, + subprotocols=subprotocols, + extra_headers=extra_headers, + user_agent_header=user_agent_header, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_size=max_size, + max_queue=max_queue, + read_limit=read_limit, + write_limit=write_limit, + host=wsuri.host, + port=wsuri.port, + secure=wsuri.secure, + legacy_recv=legacy_recv, + loop=_loop, + ) + + if kwargs.pop("unix", False): + path: str | None = kwargs.pop("path", None) + create_connection = functools.partial( + loop.create_unix_connection, factory, path, **kwargs + ) + else: + host: str | None + port: int | None + if kwargs.get("sock") is None: + host, port = wsuri.host, wsuri.port + else: + # If sock is given, host and port shouldn't be specified. + host, port = None, None + if kwargs.get("ssl"): + kwargs.setdefault("server_hostname", wsuri.host) + # If host and port are given, override values from the URI. + host = kwargs.pop("host", host) + port = kwargs.pop("port", port) + create_connection = functools.partial( + loop.create_connection, factory, host, port, **kwargs + ) + + self.open_timeout = open_timeout + if logger is None: + logger = logging.getLogger("websockets.client") + self.logger = logger + + # This is a coroutine function. + self._create_connection = create_connection + self._uri = uri + self._wsuri = wsuri + + def handle_redirect(self, uri: str) -> None: + # Update the state of this instance to connect to a new URI. + old_uri = self._uri + old_wsuri = self._wsuri + new_uri = urllib.parse.urljoin(old_uri, uri) + new_wsuri = parse_uri(new_uri) + + # Forbid TLS downgrade. + if old_wsuri.secure and not new_wsuri.secure: + raise SecurityError("redirect from WSS to WS") + + same_origin = ( + old_wsuri.secure == new_wsuri.secure + and old_wsuri.host == new_wsuri.host + and old_wsuri.port == new_wsuri.port + ) + + # Rewrite secure, host, and port for cross-origin redirects. + # This preserves connection overrides with the host and port + # arguments if the redirect points to the same host and port. + if not same_origin: + factory = self._create_connection.args[0] + # Support TLS upgrade. + if not old_wsuri.secure and new_wsuri.secure: + factory.keywords["secure"] = True + self._create_connection.keywords.setdefault("ssl", True) + # Replace secure, host, and port arguments of the protocol factory. + factory = functools.partial( + factory.func, + *factory.args, + **dict(factory.keywords, host=new_wsuri.host, port=new_wsuri.port), + ) + # Replace secure, host, and port arguments of create_connection. + self._create_connection = functools.partial( + self._create_connection.func, + *(factory, new_wsuri.host, new_wsuri.port), + **self._create_connection.keywords, + ) + + # Set the new WebSocket URI. This suffices for same-origin redirects. + self._uri = new_uri + self._wsuri = new_wsuri + + # async for ... in connect(...): + + BACKOFF_INITIAL = float(os.environ.get("WEBSOCKETS_BACKOFF_INITIAL_DELAY", "5")) + BACKOFF_MIN = float(os.environ.get("WEBSOCKETS_BACKOFF_MIN_DELAY", "3.1")) + BACKOFF_MAX = float(os.environ.get("WEBSOCKETS_BACKOFF_MAX_DELAY", "90.0")) + BACKOFF_FACTOR = float(os.environ.get("WEBSOCKETS_BACKOFF_FACTOR", "1.618")) + + async def __aiter__(self) -> AsyncIterator[WebSocketClientProtocol]: + backoff_delay = self.BACKOFF_MIN / self.BACKOFF_FACTOR + while True: + try: + async with self as protocol: + yield protocol + except Exception as exc: + # Add a random initial delay between 0 and 5 seconds. + # See 7.2.3. Recovering from Abnormal Closure in RFC 6455. + if backoff_delay == self.BACKOFF_MIN: + initial_delay = random.random() * self.BACKOFF_INITIAL + self.logger.info( + "connect failed; reconnecting in %.1f seconds: %s", + initial_delay, + # Remove first argument when dropping Python 3.9. + traceback.format_exception_only(type(exc), exc)[0].strip(), + ) + await asyncio.sleep(initial_delay) + else: + self.logger.info( + "connect failed again; retrying in %d seconds: %s", + int(backoff_delay), + # Remove first argument when dropping Python 3.9. + traceback.format_exception_only(type(exc), exc)[0].strip(), + ) + await asyncio.sleep(int(backoff_delay)) + # Increase delay with truncated exponential backoff. + backoff_delay = backoff_delay * self.BACKOFF_FACTOR + backoff_delay = min(backoff_delay, self.BACKOFF_MAX) + continue + else: + # Connection succeeded - reset backoff delay + backoff_delay = self.BACKOFF_MIN + + # async with connect(...) as ...: + + async def __aenter__(self) -> WebSocketClientProtocol: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self.protocol.close() + + # ... = await connect(...) + + def __await__(self) -> Generator[Any, None, WebSocketClientProtocol]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> WebSocketClientProtocol: + async with asyncio_timeout(self.open_timeout): + for _redirects in range(self.MAX_REDIRECTS_ALLOWED): + _transport, protocol = await self._create_connection() + try: + await protocol.handshake( + self._wsuri, + origin=protocol.origin, + available_extensions=protocol.available_extensions, + available_subprotocols=protocol.available_subprotocols, + extra_headers=protocol.extra_headers, + ) + except RedirectHandshake as exc: + protocol.fail_connection() + await protocol.wait_closed() + self.handle_redirect(exc.uri) + # Avoid leaking a connected socket when the handshake fails. + except (Exception, asyncio.CancelledError): + protocol.fail_connection() + await protocol.wait_closed() + raise + else: + self.protocol = protocol + return protocol + else: + raise SecurityError("too many redirects") + + # ... = yield from connect(...) - remove when dropping Python < 3.10 + + __iter__ = __await__ + + +connect = Connect + + +def unix_connect( + path: str | None = None, + uri: str = "ws://localhost/", + **kwargs: Any, +) -> Connect: + """ + Similar to :func:`connect`, but for connecting to a Unix socket. + + This function builds upon the event loop's + :meth:`~asyncio.loop.create_unix_connection` method. + + It is only available on Unix. + + It's mainly useful for debugging servers listening on Unix sockets. + + Args: + path: File system path to the Unix socket. + uri: URI of the WebSocket server; the host is used in the TLS + handshake for secure connections and in the ``Host`` header. + + """ + return connect(uri=uri, path=path, unix=True, **kwargs) diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/exceptions.py b/venv/lib/python3.10/site-packages/websockets/legacy/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..29a2525b4e73b788f773682ce0b88e13eafc6e26 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/legacy/exceptions.py @@ -0,0 +1,71 @@ +import http + +from .. import datastructures +from ..exceptions import ( + InvalidHandshake, + # InvalidMessage was incorrectly moved here in versions 14.0 and 14.1. + InvalidMessage, # noqa: F401 + ProtocolError as WebSocketProtocolError, # noqa: F401 +) +from ..typing import StatusLike + + +class InvalidStatusCode(InvalidHandshake): + """ + Raised when a handshake response status code is invalid. + + """ + + def __init__(self, status_code: int, headers: datastructures.Headers) -> None: + self.status_code = status_code + self.headers = headers + + def __str__(self) -> str: + return f"server rejected WebSocket connection: HTTP {self.status_code}" + + +class AbortHandshake(InvalidHandshake): + """ + Raised to abort the handshake on purpose and return an HTTP response. + + This exception is an implementation detail. + + The public API is + :meth:`~websockets.legacy.server.WebSocketServerProtocol.process_request`. + + Attributes: + status (~http.HTTPStatus): HTTP status code. + headers (Headers): HTTP response headers. + body (bytes): HTTP response body. + """ + + def __init__( + self, + status: StatusLike, + headers: datastructures.HeadersLike, + body: bytes = b"", + ) -> None: + # If a user passes an int instead of an HTTPStatus, fix it automatically. + self.status = http.HTTPStatus(status) + self.headers = datastructures.Headers(headers) + self.body = body + + def __str__(self) -> str: + return ( + f"HTTP {self.status:d}, {len(self.headers)} headers, {len(self.body)} bytes" + ) + + +class RedirectHandshake(InvalidHandshake): + """ + Raised when a handshake gets redirected. + + This exception is an implementation detail. + + """ + + def __init__(self, uri: str) -> None: + self.uri = uri + + def __str__(self) -> str: + return f"redirect to {self.uri}" diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/framing.py b/venv/lib/python3.10/site-packages/websockets/legacy/framing.py new file mode 100644 index 0000000000000000000000000000000000000000..add0c6e0e20af588c3f99b4ef11befac0ad7502d --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/legacy/framing.py @@ -0,0 +1,225 @@ +from __future__ import annotations + +import struct +from collections.abc import Awaitable, Sequence +from typing import Any, Callable, NamedTuple + +from .. import extensions, frames +from ..exceptions import PayloadTooBig, ProtocolError +from ..frames import BytesLike +from ..typing import Data + + +try: + from ..speedups import apply_mask +except ImportError: + from ..utils import apply_mask + + +class Frame(NamedTuple): + fin: bool + opcode: frames.Opcode + data: bytes + rsv1: bool = False + rsv2: bool = False + rsv3: bool = False + + @property + def new_frame(self) -> frames.Frame: + return frames.Frame( + self.opcode, + self.data, + self.fin, + self.rsv1, + self.rsv2, + self.rsv3, + ) + + def __str__(self) -> str: + return str(self.new_frame) + + def check(self) -> None: + return self.new_frame.check() + + @classmethod + async def read( + cls, + reader: Callable[[int], Awaitable[bytes]], + *, + mask: bool, + max_size: int | None = None, + extensions: Sequence[extensions.Extension] | None = None, + ) -> Frame: + """ + Read a WebSocket frame. + + Args: + reader: Coroutine that reads exactly the requested number of + bytes, unless the end of file is reached. + mask: Whether the frame should be masked i.e. whether the read + happens on the server side. + max_size: Maximum payload size in bytes. + extensions: List of extensions, applied in reverse order. + + Raises: + PayloadTooBig: If the frame exceeds ``max_size``. + ProtocolError: If the frame contains incorrect values. + + """ + + # Read the header. + data = await reader(2) + head1, head2 = struct.unpack("!BB", data) + + # While not Pythonic, this is marginally faster than calling bool(). + fin = True if head1 & 0b10000000 else False + rsv1 = True if head1 & 0b01000000 else False + rsv2 = True if head1 & 0b00100000 else False + rsv3 = True if head1 & 0b00010000 else False + + try: + opcode = frames.Opcode(head1 & 0b00001111) + except ValueError as exc: + raise ProtocolError("invalid opcode") from exc + + if (True if head2 & 0b10000000 else False) != mask: + raise ProtocolError("incorrect masking") + + length = head2 & 0b01111111 + if length == 126: + data = await reader(2) + (length,) = struct.unpack("!H", data) + elif length == 127: + data = await reader(8) + (length,) = struct.unpack("!Q", data) + if max_size is not None and length > max_size: + raise PayloadTooBig(length, max_size) + if mask: + mask_bits = await reader(4) + + # Read the data. + data = await reader(length) + if mask: + data = apply_mask(data, mask_bits) + + new_frame = frames.Frame(opcode, data, fin, rsv1, rsv2, rsv3) + + if extensions is None: + extensions = [] + for extension in reversed(extensions): + new_frame = extension.decode(new_frame, max_size=max_size) + + new_frame.check() + + return cls( + new_frame.fin, + new_frame.opcode, + new_frame.data, + new_frame.rsv1, + new_frame.rsv2, + new_frame.rsv3, + ) + + def write( + self, + write: Callable[[bytes], Any], + *, + mask: bool, + extensions: Sequence[extensions.Extension] | None = None, + ) -> None: + """ + Write a WebSocket frame. + + Args: + frame: Frame to write. + write: Function that writes bytes. + mask: Whether the frame should be masked i.e. whether the write + happens on the client side. + extensions: List of extensions, applied in order. + + Raises: + ProtocolError: If the frame contains incorrect values. + + """ + # The frame is written in a single call to write in order to prevent + # TCP fragmentation. See #68 for details. This also makes it safe to + # send frames concurrently from multiple coroutines. + write(self.new_frame.serialize(mask=mask, extensions=extensions)) + + +def prepare_data(data: Data) -> tuple[int, bytes]: + """ + Convert a string or byte-like object to an opcode and a bytes-like object. + + This function is designed for data frames. + + If ``data`` is a :class:`str`, return ``OP_TEXT`` and a :class:`bytes` + object encoding ``data`` in UTF-8. + + If ``data`` is a bytes-like object, return ``OP_BINARY`` and a bytes-like + object. + + Raises: + TypeError: If ``data`` doesn't have a supported type. + + """ + if isinstance(data, str): + return frames.Opcode.TEXT, data.encode() + elif isinstance(data, BytesLike): + return frames.Opcode.BINARY, data + else: + raise TypeError("data must be str or bytes-like") + + +def prepare_ctrl(data: Data) -> bytes: + """ + Convert a string or byte-like object to bytes. + + This function is designed for ping and pong frames. + + If ``data`` is a :class:`str`, return a :class:`bytes` object encoding + ``data`` in UTF-8. + + If ``data`` is a bytes-like object, return a :class:`bytes` object. + + Raises: + TypeError: If ``data`` doesn't have a supported type. + + """ + if isinstance(data, str): + return data.encode() + elif isinstance(data, BytesLike): + return bytes(data) + else: + raise TypeError("data must be str or bytes-like") + + +# Backwards compatibility with previously documented public APIs +encode_data = prepare_ctrl + +# Backwards compatibility with previously documented public APIs +from ..frames import Close # noqa: E402 F401, I001 + + +def parse_close(data: bytes) -> tuple[int, str]: + """ + Parse the payload from a close frame. + + Returns: + Close code and reason. + + Raises: + ProtocolError: If data is ill-formed. + UnicodeDecodeError: If the reason isn't valid UTF-8. + + """ + close = Close.parse(data) + return close.code, close.reason + + +def serialize_close(code: int, reason: str) -> bytes: + """ + Serialize the payload for a close frame. + + """ + return Close(code, reason).serialize() diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/handshake.py b/venv/lib/python3.10/site-packages/websockets/legacy/handshake.py new file mode 100644 index 0000000000000000000000000000000000000000..6a7157c010720733ca42d363cd810c354bf9d221 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/legacy/handshake.py @@ -0,0 +1,158 @@ +from __future__ import annotations + +import base64 +import binascii + +from ..datastructures import Headers, MultipleValuesError +from ..exceptions import InvalidHeader, InvalidHeaderValue, InvalidUpgrade +from ..headers import parse_connection, parse_upgrade +from ..typing import ConnectionOption, UpgradeProtocol +from ..utils import accept_key as accept, generate_key + + +__all__ = ["build_request", "check_request", "build_response", "check_response"] + + +def build_request(headers: Headers) -> str: + """ + Build a handshake request to send to the server. + + Update request headers passed in argument. + + Args: + headers: Handshake request headers. + + Returns: + ``key`` that must be passed to :func:`check_response`. + + """ + key = generate_key() + headers["Upgrade"] = "websocket" + headers["Connection"] = "Upgrade" + headers["Sec-WebSocket-Key"] = key + headers["Sec-WebSocket-Version"] = "13" + return key + + +def check_request(headers: Headers) -> str: + """ + Check a handshake request received from the client. + + This function doesn't verify that the request is an HTTP/1.1 or higher GET + request and doesn't perform ``Host`` and ``Origin`` checks. These controls + are usually performed earlier in the HTTP request handling code. They're + the responsibility of the caller. + + Args: + headers: Handshake request headers. + + Returns: + ``key`` that must be passed to :func:`build_response`. + + Raises: + InvalidHandshake: If the handshake request is invalid. + Then, the server must return a 400 Bad Request error. + + """ + connection: list[ConnectionOption] = sum( + [parse_connection(value) for value in headers.get_all("Connection")], [] + ) + + if not any(value.lower() == "upgrade" for value in connection): + raise InvalidUpgrade("Connection", ", ".join(connection)) + + upgrade: list[UpgradeProtocol] = sum( + [parse_upgrade(value) for value in headers.get_all("Upgrade")], [] + ) + + # For compatibility with non-strict implementations, ignore case when + # checking the Upgrade header. The RFC always uses "websocket", except + # in section 11.2. (IANA registration) where it uses "WebSocket". + if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): + raise InvalidUpgrade("Upgrade", ", ".join(upgrade)) + + try: + s_w_key = headers["Sec-WebSocket-Key"] + except KeyError as exc: + raise InvalidHeader("Sec-WebSocket-Key") from exc + except MultipleValuesError as exc: + raise InvalidHeader("Sec-WebSocket-Key", "multiple values") from exc + + try: + raw_key = base64.b64decode(s_w_key.encode(), validate=True) + except binascii.Error as exc: + raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key) from exc + if len(raw_key) != 16: + raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key) + + try: + s_w_version = headers["Sec-WebSocket-Version"] + except KeyError as exc: + raise InvalidHeader("Sec-WebSocket-Version") from exc + except MultipleValuesError as exc: + raise InvalidHeader("Sec-WebSocket-Version", "multiple values") from exc + + if s_w_version != "13": + raise InvalidHeaderValue("Sec-WebSocket-Version", s_w_version) + + return s_w_key + + +def build_response(headers: Headers, key: str) -> None: + """ + Build a handshake response to send to the client. + + Update response headers passed in argument. + + Args: + headers: Handshake response headers. + key: Returned by :func:`check_request`. + + """ + headers["Upgrade"] = "websocket" + headers["Connection"] = "Upgrade" + headers["Sec-WebSocket-Accept"] = accept(key) + + +def check_response(headers: Headers, key: str) -> None: + """ + Check a handshake response received from the server. + + This function doesn't verify that the response is an HTTP/1.1 or higher + response with a 101 status code. These controls are the responsibility of + the caller. + + Args: + headers: Handshake response headers. + key: Returned by :func:`build_request`. + + Raises: + InvalidHandshake: If the handshake response is invalid. + + """ + connection: list[ConnectionOption] = sum( + [parse_connection(value) for value in headers.get_all("Connection")], [] + ) + + if not any(value.lower() == "upgrade" for value in connection): + raise InvalidUpgrade("Connection", " ".join(connection)) + + upgrade: list[UpgradeProtocol] = sum( + [parse_upgrade(value) for value in headers.get_all("Upgrade")], [] + ) + + # For compatibility with non-strict implementations, ignore case when + # checking the Upgrade header. The RFC always uses "websocket", except + # in section 11.2. (IANA registration) where it uses "WebSocket". + if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): + raise InvalidUpgrade("Upgrade", ", ".join(upgrade)) + + try: + s_w_accept = headers["Sec-WebSocket-Accept"] + except KeyError as exc: + raise InvalidHeader("Sec-WebSocket-Accept") from exc + except MultipleValuesError as exc: + raise InvalidHeader("Sec-WebSocket-Accept", "multiple values") from exc + + if s_w_accept != accept(key): + raise InvalidHeaderValue("Sec-WebSocket-Accept", s_w_accept) diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/http.py b/venv/lib/python3.10/site-packages/websockets/legacy/http.py new file mode 100644 index 0000000000000000000000000000000000000000..a7c8a927e177d36f6a54bcc293dc853e2e15e736 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/legacy/http.py @@ -0,0 +1,201 @@ +from __future__ import annotations + +import asyncio +import os +import re + +from ..datastructures import Headers +from ..exceptions import SecurityError + + +__all__ = ["read_request", "read_response"] + +MAX_NUM_HEADERS = int(os.environ.get("WEBSOCKETS_MAX_NUM_HEADERS", "128")) +MAX_LINE_LENGTH = int(os.environ.get("WEBSOCKETS_MAX_LINE_LENGTH", "8192")) + + +def d(value: bytes) -> str: + """ + Decode a bytestring for interpolating into an error message. + + """ + return value.decode(errors="backslashreplace") + + +# See https://datatracker.ietf.org/doc/html/rfc7230#appendix-B. + +# Regex for validating header names. + +_token_re = re.compile(rb"[-!#$%&\'*+.^_`|~0-9a-zA-Z]+") + +# Regex for validating header values. + +# We don't attempt to support obsolete line folding. + +# Include HTAB (\x09), SP (\x20), VCHAR (\x21-\x7e), obs-text (\x80-\xff). + +# The ABNF is complicated because it attempts to express that optional +# whitespace is ignored. We strip whitespace and don't revalidate that. + +# See also https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189 + +_value_re = re.compile(rb"[\x09\x20-\x7e\x80-\xff]*") + + +async def read_request(stream: asyncio.StreamReader) -> tuple[str, Headers]: + """ + Read an HTTP/1.1 GET request and return ``(path, headers)``. + + ``path`` isn't URL-decoded or validated in any way. + + ``path`` and ``headers`` are expected to contain only ASCII characters. + Other characters are represented with surrogate escapes. + + :func:`read_request` doesn't attempt to read the request body because + WebSocket handshake requests don't have one. If the request contains a + body, it may be read from ``stream`` after this coroutine returns. + + Args: + stream: Input to read the request from. + + Raises: + EOFError: If the connection is closed without a full HTTP request. + SecurityError: If the request exceeds a security limit. + ValueError: If the request isn't well formatted. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.1 + + # Parsing is simple because fixed values are expected for method and + # version and because path isn't checked. Since WebSocket software tends + # to implement HTTP/1.1 strictly, there's little need for lenient parsing. + + try: + request_line = await read_line(stream) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP request line") from exc + + try: + method, raw_path, version = request_line.split(b" ", 2) + except ValueError: # not enough values to unpack (expected 3, got 1-2) + raise ValueError(f"invalid HTTP request line: {d(request_line)}") from None + + if method != b"GET": + raise ValueError(f"unsupported HTTP method: {d(method)}") + if version != b"HTTP/1.1": + raise ValueError(f"unsupported HTTP version: {d(version)}") + path = raw_path.decode("ascii", "surrogateescape") + + headers = await read_headers(stream) + + return path, headers + + +async def read_response(stream: asyncio.StreamReader) -> tuple[int, str, Headers]: + """ + Read an HTTP/1.1 response and return ``(status_code, reason, headers)``. + + ``reason`` and ``headers`` are expected to contain only ASCII characters. + Other characters are represented with surrogate escapes. + + :func:`read_request` doesn't attempt to read the response body because + WebSocket handshake responses don't have one. If the response contains a + body, it may be read from ``stream`` after this coroutine returns. + + Args: + stream: Input to read the response from. + + Raises: + EOFError: If the connection is closed without a full HTTP response. + SecurityError: If the response exceeds a security limit. + ValueError: If the response isn't well formatted. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2 + + # As in read_request, parsing is simple because a fixed value is expected + # for version, status_code is a 3-digit number, and reason can be ignored. + + try: + status_line = await read_line(stream) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP status line") from exc + + try: + version, raw_status_code, raw_reason = status_line.split(b" ", 2) + except ValueError: # not enough values to unpack (expected 3, got 1-2) + raise ValueError(f"invalid HTTP status line: {d(status_line)}") from None + + if version != b"HTTP/1.1": + raise ValueError(f"unsupported HTTP version: {d(version)}") + try: + status_code = int(raw_status_code) + except ValueError: # invalid literal for int() with base 10 + raise ValueError(f"invalid HTTP status code: {d(raw_status_code)}") from None + if not 100 <= status_code < 1000: + raise ValueError(f"unsupported HTTP status code: {d(raw_status_code)}") + if not _value_re.fullmatch(raw_reason): + raise ValueError(f"invalid HTTP reason phrase: {d(raw_reason)}") + reason = raw_reason.decode() + + headers = await read_headers(stream) + + return status_code, reason, headers + + +async def read_headers(stream: asyncio.StreamReader) -> Headers: + """ + Read HTTP headers from ``stream``. + + Non-ASCII characters are represented with surrogate escapes. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 + + # We don't attempt to support obsolete line folding. + + headers = Headers() + for _ in range(MAX_NUM_HEADERS + 1): + try: + line = await read_line(stream) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP headers") from exc + if line == b"": + break + + try: + raw_name, raw_value = line.split(b":", 1) + except ValueError: # not enough values to unpack (expected 2, got 1) + raise ValueError(f"invalid HTTP header line: {d(line)}") from None + if not _token_re.fullmatch(raw_name): + raise ValueError(f"invalid HTTP header name: {d(raw_name)}") + raw_value = raw_value.strip(b" \t") + if not _value_re.fullmatch(raw_value): + raise ValueError(f"invalid HTTP header value: {d(raw_value)}") + + name = raw_name.decode("ascii") # guaranteed to be ASCII at this point + value = raw_value.decode("ascii", "surrogateescape") + headers[name] = value + + else: + raise SecurityError("too many HTTP headers") + + return headers + + +async def read_line(stream: asyncio.StreamReader) -> bytes: + """ + Read a single line from ``stream``. + + CRLF is stripped from the return value. + + """ + # Security: this is bounded by the StreamReader's limit (default = 32 KiB). + line = await stream.readline() + # Security: this guarantees header values are small (hard-coded = 8 KiB) + if len(line) > MAX_LINE_LENGTH: + raise SecurityError("line too long") + # Not mandatory but safe - https://datatracker.ietf.org/doc/html/rfc7230#section-3.5 + if not line.endswith(b"\r\n"): + raise EOFError("line without CRLF") + return line[:-2] diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/protocol.py b/venv/lib/python3.10/site-packages/websockets/legacy/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..db126c01e70aa2fb474de5d7a2ff4001e62f4a7e --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/legacy/protocol.py @@ -0,0 +1,1641 @@ +from __future__ import annotations + +import asyncio +import codecs +import collections +import logging +import random +import ssl +import struct +import sys +import time +import traceback +import uuid +import warnings +from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Iterable, Mapping +from typing import Any, Callable, Deque, cast + +from ..asyncio.compatibility import asyncio_timeout +from ..datastructures import Headers +from ..exceptions import ( + ConnectionClosed, + ConnectionClosedError, + ConnectionClosedOK, + InvalidState, + PayloadTooBig, + ProtocolError, +) +from ..extensions import Extension +from ..frames import ( + OK_CLOSE_CODES, + OP_BINARY, + OP_CLOSE, + OP_CONT, + OP_PING, + OP_PONG, + OP_TEXT, + Close, + CloseCode, + Opcode, +) +from ..protocol import State +from ..typing import Data, LoggerLike, Subprotocol +from .framing import Frame, prepare_ctrl, prepare_data + + +__all__ = ["WebSocketCommonProtocol"] + + +# In order to ensure consistency, the code always checks the current value of +# WebSocketCommonProtocol.state before assigning a new value and never yields +# between the check and the assignment. + + +class WebSocketCommonProtocol(asyncio.Protocol): + """ + WebSocket connection. + + :class:`WebSocketCommonProtocol` provides APIs shared between WebSocket + servers and clients. You shouldn't use it directly. Instead, use + :class:`~websockets.legacy.client.WebSocketClientProtocol` or + :class:`~websockets.legacy.server.WebSocketServerProtocol`. + + This documentation focuses on low-level details that aren't covered in the + documentation of :class:`~websockets.legacy.client.WebSocketClientProtocol` + and :class:`~websockets.legacy.server.WebSocketServerProtocol` for the sake + of simplicity. + + Once the connection is open, a Ping_ frame is sent every ``ping_interval`` + seconds. This serves as a keepalive. It helps keeping the connection open, + especially in the presence of proxies with short timeouts on inactive + connections. Set ``ping_interval`` to :obj:`None` to disable this behavior. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + If the corresponding Pong_ frame isn't received within ``ping_timeout`` + seconds, the connection is considered unusable and is closed with code 1011. + This ensures that the remote endpoint remains responsive. Set + ``ping_timeout`` to :obj:`None` to disable this behavior. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + See the discussion of :doc:`keepalive <../../topics/keepalive>` for details. + + The ``close_timeout`` parameter defines a maximum wait time for completing + the closing handshake and terminating the TCP connection. For legacy + reasons, :meth:`close` completes in at most ``5 * close_timeout`` seconds + for clients and ``4 * close_timeout`` for servers. + + ``close_timeout`` is a parameter of the protocol because websockets usually + calls :meth:`close` implicitly upon exit: + + * on the client side, when using :func:`~websockets.legacy.client.connect` + as a context manager; + * on the server side, when the connection handler terminates. + + To apply a timeout to any other API, wrap it in :func:`~asyncio.timeout` or + :func:`~asyncio.wait_for`. + + The ``max_size`` parameter enforces the maximum size for incoming messages + in bytes. The default value is 1 MiB. If a larger message is received, + :meth:`recv` will raise :exc:`~websockets.exceptions.ConnectionClosedError` + and the connection will be closed with code 1009. + + The ``max_queue`` parameter sets the maximum length of the queue that + holds incoming messages. The default value is ``32``. Messages are added + to an in-memory queue when they're received; then :meth:`recv` pops from + that queue. In order to prevent excessive memory consumption when + messages are received faster than they can be processed, the queue must + be bounded. If the queue fills up, the protocol stops processing incoming + data until :meth:`recv` is called. In this situation, various receive + buffers (at least in :mod:`asyncio` and in the OS) will fill up, then the + TCP receive window will shrink, slowing down transmission to avoid packet + loss. + + Since Python can use up to 4 bytes of memory to represent a single + character, each connection may use up to ``4 * max_size * max_queue`` + bytes of memory to store incoming messages. By default, this is 128 MiB. + You may want to lower the limits, depending on your application's + requirements. + + The ``read_limit`` argument sets the high-water limit of the buffer for + incoming bytes. The low-water limit is half the high-water limit. The + default value is 64 KiB, half of asyncio's default (based on the current + implementation of :class:`~asyncio.StreamReader`). + + The ``write_limit`` argument sets the high-water limit of the buffer for + outgoing bytes. The low-water limit is a quarter of the high-water limit. + The default value is 64 KiB, equal to asyncio's default (based on the + current implementation of ``FlowControlMixin``). + + See the discussion of :doc:`memory usage <../../topics/memory>` for details. + + Args: + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.protocol")``. + See the :doc:`logging guide <../../topics/logging>` for details. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing the connection in seconds. + For legacy reasons, the actual timeout is 4 or 5 times larger. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. + max_queue: Maximum number of incoming messages in receive buffer. + :obj:`None` disables the limit. + read_limit: High-water mark of read buffer in bytes. + write_limit: High-water mark of write buffer in bytes. + + """ + + # There are only two differences between the client-side and server-side + # behavior: masking the payload and closing the underlying TCP connection. + # Set is_client = True/False and side = "client"/"server" to pick a side. + is_client: bool + side: str = "undefined" + + def __init__( + self, + *, + logger: LoggerLike | None = None, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = None, + max_size: int | None = 2**20, + max_queue: int | None = 2**5, + read_limit: int = 2**16, + write_limit: int = 2**16, + # The following arguments are kept only for backwards compatibility. + host: str | None = None, + port: int | None = None, + secure: bool | None = None, + legacy_recv: bool = False, + loop: asyncio.AbstractEventLoop | None = None, + timeout: float | None = None, + ) -> None: + if legacy_recv: # pragma: no cover + warnings.warn("legacy_recv is deprecated", DeprecationWarning) + + # Backwards compatibility: close_timeout used to be called timeout. + if timeout is None: + timeout = 10 + else: + warnings.warn("rename timeout to close_timeout", DeprecationWarning) + # If both are specified, timeout is ignored. + if close_timeout is None: + close_timeout = timeout + + # Backwards compatibility: the loop parameter used to be supported. + if loop is None: + loop = asyncio.get_event_loop() + else: + warnings.warn("remove loop argument", DeprecationWarning) + + self.ping_interval = ping_interval + self.ping_timeout = ping_timeout + self.close_timeout = close_timeout + self.max_size = max_size + self.max_queue = max_queue + self.read_limit = read_limit + self.write_limit = write_limit + + # Unique identifier. For logs. + self.id: uuid.UUID = uuid.uuid4() + """Unique identifier of the connection. Useful in logs.""" + + # Logger or LoggerAdapter for this connection. + if logger is None: + logger = logging.getLogger("websockets.protocol") + self.logger: LoggerLike = logging.LoggerAdapter(logger, {"websocket": self}) + """Logger for this connection.""" + + # Track if DEBUG is enabled. Shortcut logging calls if it isn't. + self.debug = logger.isEnabledFor(logging.DEBUG) + + self.loop = loop + + self._host = host + self._port = port + self._secure = secure + self.legacy_recv = legacy_recv + + # Configure read buffer limits. The high-water limit is defined by + # ``self.read_limit``. The ``limit`` argument controls the line length + # limit and half the buffer limit of :class:`~asyncio.StreamReader`. + # That's why it must be set to half of ``self.read_limit``. + self.reader = asyncio.StreamReader(limit=read_limit // 2, loop=loop) + + # Copied from asyncio.FlowControlMixin + self._paused = False + self._drain_waiter: asyncio.Future[None] | None = None + + self._drain_lock = asyncio.Lock() + + # This class implements the data transfer and closing handshake, which + # are shared between the client-side and the server-side. + # Subclasses implement the opening handshake and, on success, execute + # :meth:`connection_open` to change the state to OPEN. + self.state = State.CONNECTING + if self.debug: + self.logger.debug("= connection is CONNECTING") + + # HTTP protocol parameters. + self.path: str + """Path of the opening handshake request.""" + self.request_headers: Headers + """Opening handshake request headers.""" + self.response_headers: Headers + """Opening handshake response headers.""" + + # WebSocket protocol parameters. + self.extensions: list[Extension] = [] + self.subprotocol: Subprotocol | None = None + """Subprotocol, if one was negotiated.""" + + # Close code and reason, set when a close frame is sent or received. + self.close_rcvd: Close | None = None + self.close_sent: Close | None = None + self.close_rcvd_then_sent: bool | None = None + + # Completed when the connection state becomes CLOSED. Translates the + # :meth:`connection_lost` callback to a :class:`~asyncio.Future` + # that can be awaited. (Other :class:`~asyncio.Protocol` callbacks are + # translated by ``self.stream_reader``). + self.connection_lost_waiter: asyncio.Future[None] = loop.create_future() + + # Queue of received messages. + self.messages: Deque[Data] = collections.deque() + self._pop_message_waiter: asyncio.Future[None] | None = None + self._put_message_waiter: asyncio.Future[None] | None = None + + # Protect sending fragmented messages. + self._fragmented_message_waiter: asyncio.Future[None] | None = None + + # Mapping of ping IDs to pong waiters, in chronological order. + self.pings: dict[bytes, tuple[asyncio.Future[float], float]] = {} + + self.latency: float = 0 + """ + Latency of the connection, in seconds. + + Latency is defined as the round-trip time of the connection. It is + measured by sending a Ping frame and waiting for a matching Pong frame. + Before the first measurement, :attr:`latency` is ``0``. + + By default, websockets enables a :ref:`keepalive ` mechanism + that sends Ping frames automatically at regular intervals. You can also + send Ping frames and measure latency with :meth:`ping`. + """ + + # Task running the data transfer. + self.transfer_data_task: asyncio.Task[None] + + # Exception that occurred during data transfer, if any. + self.transfer_data_exc: BaseException | None = None + + # Task sending keepalive pings. + self.keepalive_ping_task: asyncio.Task[None] + + # Task closing the TCP connection. + self.close_connection_task: asyncio.Task[None] + + # Copied from asyncio.FlowControlMixin + async def _drain_helper(self) -> None: # pragma: no cover + if self.connection_lost_waiter.done(): + raise ConnectionResetError("Connection lost") + if not self._paused: + return + waiter = self._drain_waiter + assert waiter is None or waiter.cancelled() + waiter = self.loop.create_future() + self._drain_waiter = waiter + await waiter + + # Copied from asyncio.StreamWriter + async def _drain(self) -> None: # pragma: no cover + if self.reader is not None: + exc = self.reader.exception() + if exc is not None: + raise exc + if self.transport is not None: + if self.transport.is_closing(): + # Yield to the event loop so connection_lost() may be + # called. Without this, _drain_helper() would return + # immediately, and code that calls + # write(...); yield from drain() + # in a loop would never call connection_lost(), so it + # would not see an error when the socket is closed. + await asyncio.sleep(0) + await self._drain_helper() + + def connection_open(self) -> None: + """ + Callback when the WebSocket opening handshake completes. + + Enter the OPEN state and start the data transfer phase. + + """ + # 4.1. The WebSocket Connection is Established. + assert self.state is State.CONNECTING + self.state = State.OPEN + if self.debug: + self.logger.debug("= connection is OPEN") + # Start the task that receives incoming WebSocket messages. + self.transfer_data_task = self.loop.create_task(self.transfer_data()) + # Start the task that sends pings at regular intervals. + self.keepalive_ping_task = self.loop.create_task(self.keepalive_ping()) + # Start the task that eventually closes the TCP connection. + self.close_connection_task = self.loop.create_task(self.close_connection()) + + @property + def host(self) -> str | None: + alternative = "remote_address" if self.is_client else "local_address" + warnings.warn(f"use {alternative}[0] instead of host", DeprecationWarning) + return self._host + + @property + def port(self) -> int | None: + alternative = "remote_address" if self.is_client else "local_address" + warnings.warn(f"use {alternative}[1] instead of port", DeprecationWarning) + return self._port + + @property + def secure(self) -> bool | None: + warnings.warn("don't use secure", DeprecationWarning) + return self._secure + + # Public API + + @property + def local_address(self) -> Any: + """ + Local address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family; + see :meth:`~socket.socket.getsockname`. + + :obj:`None` if the TCP connection isn't established yet. + + """ + try: + transport = self.transport + except AttributeError: + return None + else: + return transport.get_extra_info("sockname") + + @property + def remote_address(self) -> Any: + """ + Remote address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family; + see :meth:`~socket.socket.getpeername`. + + :obj:`None` if the TCP connection isn't established yet. + + """ + try: + transport = self.transport + except AttributeError: + return None + else: + return transport.get_extra_info("peername") + + @property + def open(self) -> bool: + """ + :obj:`True` when the connection is open; :obj:`False` otherwise. + + This attribute may be used to detect disconnections. However, this + approach is discouraged per the EAFP_ principle. Instead, you should + handle :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + .. _EAFP: https://docs.python.org/3/glossary.html#term-eafp + + """ + return self.state is State.OPEN and not self.transfer_data_task.done() + + @property + def closed(self) -> bool: + """ + :obj:`True` when the connection is closed; :obj:`False` otherwise. + + Be aware that both :attr:`open` and :attr:`closed` are :obj:`False` + during the opening and closing sequences. + + """ + return self.state is State.CLOSED + + @property + def close_code(self) -> int | None: + """ + WebSocket close code, defined in `section 7.1.5 of RFC 6455`_. + + .. _section 7.1.5 of RFC 6455: + https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + + :obj:`None` if the connection isn't closed yet. + + """ + if self.state is not State.CLOSED: + return None + elif self.close_rcvd is None: + return CloseCode.ABNORMAL_CLOSURE + else: + return self.close_rcvd.code + + @property + def close_reason(self) -> str | None: + """ + WebSocket close reason, defined in `section 7.1.6 of RFC 6455`_. + + .. _section 7.1.6 of RFC 6455: + https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + + :obj:`None` if the connection isn't closed yet. + + """ + if self.state is not State.CLOSED: + return None + elif self.close_rcvd is None: + return "" + else: + return self.close_rcvd.reason + + async def __aiter__(self) -> AsyncIterator[Data]: + """ + Iterate on incoming messages. + + The iterator exits normally when the connection is closed with the close + code 1000 (OK) or 1001 (going away) or without a close code. + + It raises a :exc:`~websockets.exceptions.ConnectionClosedError` + exception when the connection is closed with any other code. + + """ + try: + while True: + yield await self.recv() + except ConnectionClosedOK: + return + + async def recv(self) -> Data: + """ + Receive the next message. + + When the connection is closed, :meth:`recv` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises + :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. This is how you detect the end of the + message stream. + + Canceling :meth:`recv` is safe. There's no risk of losing the next + message. The next invocation of :meth:`recv` will return it. + + This makes it possible to enforce a timeout by wrapping :meth:`recv` in + :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`. + + Returns: + A string (:class:`str`) for a Text_ frame. A bytestring + (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + Raises: + ConnectionClosed: When the connection is closed. + RuntimeError: If two coroutines call :meth:`recv` concurrently. + + """ + if self._pop_message_waiter is not None: + raise RuntimeError( + "cannot call recv while another coroutine " + "is already waiting for the next message" + ) + + # Don't await self.ensure_open() here: + # - messages could be available in the queue even if the connection + # is closed; + # - messages could be received before the closing frame even if the + # connection is closing. + + # Wait until there's a message in the queue (if necessary) or the + # connection is closed. + while len(self.messages) <= 0: + pop_message_waiter: asyncio.Future[None] = self.loop.create_future() + self._pop_message_waiter = pop_message_waiter + try: + # If asyncio.wait() is canceled, it doesn't cancel + # pop_message_waiter and self.transfer_data_task. + await asyncio.wait( + [pop_message_waiter, self.transfer_data_task], + return_when=asyncio.FIRST_COMPLETED, + ) + finally: + self._pop_message_waiter = None + + # If asyncio.wait(...) exited because self.transfer_data_task + # completed before receiving a new message, raise a suitable + # exception (or return None if legacy_recv is enabled). + if not pop_message_waiter.done(): + if self.legacy_recv: + return None # type: ignore + else: + # Wait until the connection is closed to raise + # ConnectionClosed with the correct code and reason. + await self.ensure_open() + + # Pop a message from the queue. + message = self.messages.popleft() + + # Notify transfer_data(). + if self._put_message_waiter is not None: + self._put_message_waiter.set_result(None) + self._put_message_waiter = None + + return message + + async def send( + self, + message: Data | Iterable[Data] | AsyncIterable[Data], + ) -> None: + """ + Send a message. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or + bytes-like object (:class:`bytes`, :class:`bytearray`, or + :class:`memoryview`) is sent as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + :meth:`send` also accepts an iterable or an asynchronous iterable of + strings, bytestrings, or bytes-like objects to enable fragmentation_. + Each item is treated as a message fragment and sent in its own frame. + All items must be of the same type, or else :meth:`send` will raise a + :exc:`TypeError` and the connection will be closed. + + .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4 + + :meth:`send` rejects dict-like objects because this is often an error. + (If you want to send the keys of a dict-like object as fragments, call + its :meth:`~dict.keys` method and pass the result to :meth:`send`.) + + Canceling :meth:`send` is discouraged. Instead, you should close the + connection with :meth:`close`. Indeed, there are only two situations + where :meth:`send` may yield control to the event loop and then get + canceled; in both cases, :meth:`close` has the same effect and is + more clear: + + 1. The write buffer is full. If you don't want to wait until enough + data is sent, your only alternative is to close the connection. + :meth:`close` will likely time out then abort the TCP connection. + 2. ``message`` is an asynchronous iterator that yields control. + Stopping in the middle of a fragmented message will cause a + protocol error and the connection will be closed. + + When the connection is closed, :meth:`send` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it + raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. + + Args: + message: Message to send. + + Raises: + ConnectionClosed: When the connection is closed. + TypeError: If ``message`` doesn't have a supported type. + + """ + await self.ensure_open() + + # While sending a fragmented message, prevent sending other messages + # until all fragments are sent. + while self._fragmented_message_waiter is not None: + await asyncio.shield(self._fragmented_message_waiter) + + # Unfragmented message -- this case must be handled first because + # strings and bytes-like objects are iterable. + + if isinstance(message, (str, bytes, bytearray, memoryview)): + opcode, data = prepare_data(message) + await self.write_frame(True, opcode, data) + + # Catch a common mistake -- passing a dict to send(). + + elif isinstance(message, Mapping): + raise TypeError("data is a dict-like object") + + # Fragmented message -- regular iterator. + + elif isinstance(message, Iterable): + # Work around https://github.com/python/mypy/issues/6227 + message = cast(Iterable[Data], message) + + iter_message = iter(message) + try: + fragment = next(iter_message) + except StopIteration: + return + opcode, data = prepare_data(fragment) + + self._fragmented_message_waiter = self.loop.create_future() + try: + # First fragment. + await self.write_frame(False, opcode, data) + + # Other fragments. + for fragment in iter_message: + confirm_opcode, data = prepare_data(fragment) + if confirm_opcode != opcode: + raise TypeError("data contains inconsistent types") + await self.write_frame(False, OP_CONT, data) + + # Final fragment. + await self.write_frame(True, OP_CONT, b"") + + except (Exception, asyncio.CancelledError): + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + self.fail_connection(CloseCode.INTERNAL_ERROR) + raise + + finally: + self._fragmented_message_waiter.set_result(None) + self._fragmented_message_waiter = None + + # Fragmented message -- asynchronous iterator + + elif isinstance(message, AsyncIterable): + # Implement aiter_message = aiter(message) without aiter + # Work around https://github.com/python/mypy/issues/5738 + aiter_message = cast( + Callable[[AsyncIterable[Data]], AsyncIterator[Data]], + type(message).__aiter__, + )(message) + try: + # Implement fragment = anext(aiter_message) without anext + # Work around https://github.com/python/mypy/issues/5738 + fragment = await cast( + Callable[[AsyncIterator[Data]], Awaitable[Data]], + type(aiter_message).__anext__, + )(aiter_message) + except StopAsyncIteration: + return + opcode, data = prepare_data(fragment) + + self._fragmented_message_waiter = self.loop.create_future() + try: + # First fragment. + await self.write_frame(False, opcode, data) + + # Other fragments. + async for fragment in aiter_message: + confirm_opcode, data = prepare_data(fragment) + if confirm_opcode != opcode: + raise TypeError("data contains inconsistent types") + await self.write_frame(False, OP_CONT, data) + + # Final fragment. + await self.write_frame(True, OP_CONT, b"") + + except (Exception, asyncio.CancelledError): + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + self.fail_connection(CloseCode.INTERNAL_ERROR) + raise + + finally: + self._fragmented_message_waiter.set_result(None) + self._fragmented_message_waiter = None + + else: + raise TypeError("data must be str, bytes-like, or iterable") + + async def close( + self, + code: int = CloseCode.NORMAL_CLOSURE, + reason: str = "", + ) -> None: + """ + Perform the closing handshake. + + :meth:`close` waits for the other end to complete the handshake and + for the TCP connection to terminate. As a consequence, there's no need + to await :meth:`wait_closed` after :meth:`close`. + + :meth:`close` is idempotent: it doesn't do anything once the + connection is closed. + + Wrapping :func:`close` in :func:`~asyncio.create_task` is safe, given + that errors during connection termination aren't particularly useful. + + Canceling :meth:`close` is discouraged. If it takes too long, you can + set a shorter ``close_timeout``. If you don't want to wait, let the + Python process exit, then the OS will take care of closing the TCP + connection. + + Args: + code: WebSocket close code. + reason: WebSocket close reason. + + """ + try: + async with asyncio_timeout(self.close_timeout): + await self.write_close_frame(Close(code, reason)) + except asyncio.TimeoutError: + # If the close frame cannot be sent because the send buffers + # are full, the closing handshake won't complete anyway. + # Fail the connection to shut down faster. + self.fail_connection() + + # If no close frame is received within the timeout, asyncio_timeout() + # cancels the data transfer task and raises TimeoutError. + + # If close() is called multiple times concurrently and one of these + # calls hits the timeout, the data transfer task will be canceled. + # Other calls will receive a CancelledError here. + + try: + # If close() is canceled during the wait, self.transfer_data_task + # is canceled before the timeout elapses. + async with asyncio_timeout(self.close_timeout): + await self.transfer_data_task + except (asyncio.TimeoutError, asyncio.CancelledError): + pass + + # Wait for the close connection task to close the TCP connection. + await asyncio.shield(self.close_connection_task) + + async def wait_closed(self) -> None: + """ + Wait until the connection is closed. + + This coroutine is identical to the :attr:`closed` attribute, except it + can be awaited. + + This can make it easier to detect connection termination, regardless + of its cause, in tasks that interact with the WebSocket connection. + + """ + await asyncio.shield(self.connection_lost_waiter) + + async def ping(self, data: Data | None = None) -> Awaitable[float]: + """ + Send a Ping_. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + A ping may serve as a keepalive, as a check that the remote endpoint + received all messages up to this point, or to measure :attr:`latency`. + + Canceling :meth:`ping` is discouraged. If :meth:`ping` doesn't return + immediately, it means the write buffer is full. If you don't want to + wait, you should close the connection. + + Canceling the :class:`~asyncio.Future` returned by :meth:`ping` has no + effect. + + Args: + data: Payload of the ping. A string will be encoded to UTF-8. + If ``data`` is :obj:`None`, the payload is four random bytes. + + Returns: + A future that will be completed when the corresponding pong is + received. You can ignore it if you don't intend to wait. The result + of the future is the latency of the connection in seconds. + + :: + + pong_waiter = await ws.ping() + # only if you want to wait for the corresponding pong + latency = await pong_waiter + + Raises: + ConnectionClosed: When the connection is closed. + RuntimeError: If another ping was sent with the same data and + the corresponding pong wasn't received yet. + + """ + await self.ensure_open() + + if data is not None: + data = prepare_ctrl(data) + + # Protect against duplicates if a payload is explicitly set. + if data in self.pings: + raise RuntimeError("already waiting for a pong with the same data") + + # Generate a unique random payload otherwise. + while data is None or data in self.pings: + data = struct.pack("!I", random.getrandbits(32)) + + pong_waiter = self.loop.create_future() + # Resolution of time.monotonic() may be too low on Windows. + ping_timestamp = time.perf_counter() + self.pings[data] = (pong_waiter, ping_timestamp) + + await self.write_frame(True, OP_PING, data) + + return asyncio.shield(pong_waiter) + + async def pong(self, data: Data = b"") -> None: + """ + Send a Pong_. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + An unsolicited pong may serve as a unidirectional heartbeat. + + Canceling :meth:`pong` is discouraged. If :meth:`pong` doesn't return + immediately, it means the write buffer is full. If you don't want to + wait, you should close the connection. + + Args: + data: Payload of the pong. A string will be encoded to UTF-8. + + Raises: + ConnectionClosed: When the connection is closed. + + """ + await self.ensure_open() + + data = prepare_ctrl(data) + + await self.write_frame(True, OP_PONG, data) + + # Private methods - no guarantees. + + def connection_closed_exc(self) -> ConnectionClosed: + exc: ConnectionClosed + if ( + self.close_rcvd is not None + and self.close_rcvd.code in OK_CLOSE_CODES + and self.close_sent is not None + and self.close_sent.code in OK_CLOSE_CODES + ): + exc = ConnectionClosedOK( + self.close_rcvd, + self.close_sent, + self.close_rcvd_then_sent, + ) + else: + exc = ConnectionClosedError( + self.close_rcvd, + self.close_sent, + self.close_rcvd_then_sent, + ) + # Chain to the exception that terminated data transfer, if any. + exc.__cause__ = self.transfer_data_exc + return exc + + async def ensure_open(self) -> None: + """ + Check that the WebSocket connection is open. + + Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't. + + """ + # Handle cases from most common to least common for performance. + if self.state is State.OPEN: + # If self.transfer_data_task exited without a closing handshake, + # self.close_connection_task may be closing the connection, going + # straight from OPEN to CLOSED. + if self.transfer_data_task.done(): + await asyncio.shield(self.close_connection_task) + raise self.connection_closed_exc() + else: + return + + if self.state is State.CLOSED: + raise self.connection_closed_exc() + + if self.state is State.CLOSING: + # If we started the closing handshake, wait for its completion to + # get the proper close code and reason. self.close_connection_task + # will complete within 4 or 5 * close_timeout after close(). The + # CLOSING state also occurs when failing the connection. In that + # case self.close_connection_task will complete even faster. + await asyncio.shield(self.close_connection_task) + raise self.connection_closed_exc() + + # Control may only reach this point in buggy third-party subclasses. + assert self.state is State.CONNECTING + raise InvalidState("WebSocket connection isn't established yet") + + async def transfer_data(self) -> None: + """ + Read incoming messages and put them in a queue. + + This coroutine runs in a task until the closing handshake is started. + + """ + try: + while True: + message = await self.read_message() + + # Exit the loop when receiving a close frame. + if message is None: + break + + # Wait until there's room in the queue (if necessary). + if self.max_queue is not None: + while len(self.messages) >= self.max_queue: + self._put_message_waiter = self.loop.create_future() + try: + await asyncio.shield(self._put_message_waiter) + finally: + self._put_message_waiter = None + + # Put the message in the queue. + self.messages.append(message) + + # Notify recv(). + if self._pop_message_waiter is not None: + self._pop_message_waiter.set_result(None) + self._pop_message_waiter = None + + except asyncio.CancelledError as exc: + self.transfer_data_exc = exc + # If fail_connection() cancels this task, avoid logging the error + # twice and failing the connection again. + raise + + except ProtocolError as exc: + self.transfer_data_exc = exc + self.fail_connection(CloseCode.PROTOCOL_ERROR) + + except (ConnectionError, TimeoutError, EOFError, ssl.SSLError) as exc: + # Reading data with self.reader.readexactly may raise: + # - most subclasses of ConnectionError if the TCP connection + # breaks, is reset, or is aborted; + # - TimeoutError if the TCP connection times out; + # - IncompleteReadError, a subclass of EOFError, if fewer + # bytes are available than requested; + # - ssl.SSLError if the other side infringes the TLS protocol. + self.transfer_data_exc = exc + self.fail_connection(CloseCode.ABNORMAL_CLOSURE) + + except UnicodeDecodeError as exc: + self.transfer_data_exc = exc + self.fail_connection(CloseCode.INVALID_DATA) + + except PayloadTooBig as exc: + self.transfer_data_exc = exc + self.fail_connection(CloseCode.MESSAGE_TOO_BIG) + + except Exception as exc: + # This shouldn't happen often because exceptions expected under + # regular circumstances are handled above. If it does, consider + # catching and handling more exceptions. + self.logger.error("data transfer failed", exc_info=True) + + self.transfer_data_exc = exc + self.fail_connection(CloseCode.INTERNAL_ERROR) + + async def read_message(self) -> Data | None: + """ + Read a single message from the connection. + + Re-assemble data frames if the message is fragmented. + + Return :obj:`None` when the closing handshake is started. + + """ + frame = await self.read_data_frame(max_size=self.max_size) + + # A close frame was received. + if frame is None: + return None + + if frame.opcode == OP_TEXT: + text = True + elif frame.opcode == OP_BINARY: + text = False + else: # frame.opcode == OP_CONT + raise ProtocolError("unexpected opcode") + + # Shortcut for the common case - no fragmentation + if frame.fin: + return frame.data.decode() if text else frame.data + + # 5.4. Fragmentation + fragments: list[Data] = [] + max_size = self.max_size + if text: + decoder_factory = codecs.getincrementaldecoder("utf-8") + decoder = decoder_factory(errors="strict") + if max_size is None: + + def append(frame: Frame) -> None: + nonlocal fragments + fragments.append(decoder.decode(frame.data, frame.fin)) + + else: + + def append(frame: Frame) -> None: + nonlocal fragments, max_size + fragments.append(decoder.decode(frame.data, frame.fin)) + assert isinstance(max_size, int) + max_size -= len(frame.data) + + else: + if max_size is None: + + def append(frame: Frame) -> None: + nonlocal fragments + fragments.append(frame.data) + + else: + + def append(frame: Frame) -> None: + nonlocal fragments, max_size + fragments.append(frame.data) + assert isinstance(max_size, int) + max_size -= len(frame.data) + + append(frame) + + while not frame.fin: + frame = await self.read_data_frame(max_size=max_size) + if frame is None: + raise ProtocolError("incomplete fragmented message") + if frame.opcode != OP_CONT: + raise ProtocolError("unexpected opcode") + append(frame) + + return ("" if text else b"").join(fragments) + + async def read_data_frame(self, max_size: int | None) -> Frame | None: + """ + Read a single data frame from the connection. + + Process control frames received before the next data frame. + + Return :obj:`None` if a close frame is encountered before any data frame. + + """ + # 6.2. Receiving Data + while True: + frame = await self.read_frame(max_size) + + # 5.5. Control Frames + if frame.opcode == OP_CLOSE: + # 7.1.5. The WebSocket Connection Close Code + # 7.1.6. The WebSocket Connection Close Reason + self.close_rcvd = Close.parse(frame.data) + if self.close_sent is not None: + self.close_rcvd_then_sent = False + try: + # Echo the original data instead of re-serializing it with + # Close.serialize() because that fails when the close frame + # is empty and Close.parse() synthesizes a 1005 close code. + await self.write_close_frame(self.close_rcvd, frame.data) + except ConnectionClosed: + # Connection closed before we could echo the close frame. + pass + return None + + elif frame.opcode == OP_PING: + # Answer pings, unless connection is CLOSING. + if self.state is State.OPEN: + try: + await self.pong(frame.data) + except ConnectionClosed: + # Connection closed while draining write buffer. + pass + + elif frame.opcode == OP_PONG: + if frame.data in self.pings: + pong_timestamp = time.perf_counter() + # Sending a pong for only the most recent ping is legal. + # Acknowledge all previous pings too in that case. + ping_id = None + ping_ids = [] + for ping_id, (pong_waiter, ping_timestamp) in self.pings.items(): + ping_ids.append(ping_id) + if not pong_waiter.done(): + pong_waiter.set_result(pong_timestamp - ping_timestamp) + if ping_id == frame.data: + self.latency = pong_timestamp - ping_timestamp + break + else: + raise AssertionError("solicited pong not found in pings") + # Remove acknowledged pings from self.pings. + for ping_id in ping_ids: + del self.pings[ping_id] + + # 5.6. Data Frames + else: + return frame + + async def read_frame(self, max_size: int | None) -> Frame: + """ + Read a single frame from the connection. + + """ + frame = await Frame.read( + self.reader.readexactly, + mask=not self.is_client, + max_size=max_size, + extensions=self.extensions, + ) + if self.debug: + self.logger.debug("< %s", frame) + return frame + + def write_frame_sync(self, fin: bool, opcode: int, data: bytes) -> None: + frame = Frame(fin, Opcode(opcode), data) + if self.debug: + self.logger.debug("> %s", frame) + frame.write( + self.transport.write, + mask=self.is_client, + extensions=self.extensions, + ) + + async def drain(self) -> None: + try: + # drain() cannot be called concurrently by multiple coroutines. + # See https://github.com/python/cpython/issues/74116 for details. + # This workaround can be removed when dropping Python < 3.10. + async with self._drain_lock: + # Handle flow control automatically. + await self._drain() + except ConnectionError: + # Terminate the connection if the socket died. + self.fail_connection() + # Wait until the connection is closed to raise ConnectionClosed + # with the correct code and reason. + await self.ensure_open() + + async def write_frame( + self, fin: bool, opcode: int, data: bytes, *, _state: int = State.OPEN + ) -> None: + # Defensive assertion for protocol compliance. + if self.state is not _state: # pragma: no cover + raise InvalidState( + f"Cannot write to a WebSocket in the {self.state.name} state" + ) + self.write_frame_sync(fin, opcode, data) + await self.drain() + + async def write_close_frame(self, close: Close, data: bytes | None = None) -> None: + """ + Write a close frame if and only if the connection state is OPEN. + + This dedicated coroutine must be used for writing close frames to + ensure that at most one close frame is sent on a given connection. + + """ + # Test and set the connection state before sending the close frame to + # avoid sending two frames in case of concurrent calls. + if self.state is State.OPEN: + # 7.1.3. The WebSocket Closing Handshake is Started + self.state = State.CLOSING + if self.debug: + self.logger.debug("= connection is CLOSING") + + self.close_sent = close + if self.close_rcvd is not None: + self.close_rcvd_then_sent = True + if data is None: + data = close.serialize() + + # 7.1.2. Start the WebSocket Closing Handshake + await self.write_frame(True, OP_CLOSE, data, _state=State.CLOSING) + + async def keepalive_ping(self) -> None: + """ + Send a Ping frame and wait for a Pong frame at regular intervals. + + This coroutine exits when the connection terminates and one of the + following happens: + + - :meth:`ping` raises :exc:`ConnectionClosed`, or + - :meth:`close_connection` cancels :attr:`keepalive_ping_task`. + + """ + if self.ping_interval is None: + return + + try: + while True: + await asyncio.sleep(self.ping_interval) + + self.logger.debug("% sending keepalive ping") + pong_waiter = await self.ping() + + if self.ping_timeout is not None: + try: + async with asyncio_timeout(self.ping_timeout): + # Raises CancelledError if the connection is closed, + # when close_connection() cancels keepalive_ping(). + # Raises ConnectionClosed if the connection is lost, + # when connection_lost() calls abort_pings(). + await pong_waiter + self.logger.debug("% received keepalive pong") + except asyncio.TimeoutError: + if self.debug: + self.logger.debug("- timed out waiting for keepalive pong") + self.fail_connection( + CloseCode.INTERNAL_ERROR, + "keepalive ping timeout", + ) + break + + except ConnectionClosed: + pass + + except Exception: + self.logger.error("keepalive ping failed", exc_info=True) + + async def close_connection(self) -> None: + """ + 7.1.1. Close the WebSocket Connection + + When the opening handshake succeeds, :meth:`connection_open` starts + this coroutine in a task. It waits for the data transfer phase to + complete then it closes the TCP connection cleanly. + + When the opening handshake fails, :meth:`fail_connection` does the + same. There's no data transfer phase in that case. + + """ + try: + # Wait for the data transfer phase to complete. + if hasattr(self, "transfer_data_task"): + try: + await self.transfer_data_task + except asyncio.CancelledError: + pass + + # Cancel the keepalive ping task. + if hasattr(self, "keepalive_ping_task"): + self.keepalive_ping_task.cancel() + + # A client should wait for a TCP close from the server. + if self.is_client and hasattr(self, "transfer_data_task"): + if await self.wait_for_connection_lost(): + return + if self.debug: + self.logger.debug("- timed out waiting for TCP close") + + # Half-close the TCP connection if possible (when there's no TLS). + if self.transport.can_write_eof(): + if self.debug: + self.logger.debug("x half-closing TCP connection") + # write_eof() doesn't document which exceptions it raises. + # "[Errno 107] Transport endpoint is not connected" happens + # but it isn't completely clear under which circumstances. + # uvloop can raise RuntimeError here. + try: + self.transport.write_eof() + except (OSError, RuntimeError): # pragma: no cover + pass + + if await self.wait_for_connection_lost(): + return + if self.debug: + self.logger.debug("- timed out waiting for TCP close") + + finally: + # The try/finally ensures that the transport never remains open, + # even if this coroutine is canceled (for example). + await self.close_transport() + + async def close_transport(self) -> None: + """ + Close the TCP connection. + + """ + # If connection_lost() was called, the TCP connection is closed. + # However, if TLS is enabled, the transport still needs closing. + # Else asyncio complains: ResourceWarning: unclosed transport. + if self.connection_lost_waiter.done() and self.transport.is_closing(): + return + + # Close the TCP connection. Buffers are flushed asynchronously. + if self.debug: + self.logger.debug("x closing TCP connection") + self.transport.close() + + if await self.wait_for_connection_lost(): + return + if self.debug: + self.logger.debug("- timed out waiting for TCP close") + + # Abort the TCP connection. Buffers are discarded. + if self.debug: + self.logger.debug("x aborting TCP connection") + self.transport.abort() + + # connection_lost() is called quickly after aborting. + await self.wait_for_connection_lost() + + async def wait_for_connection_lost(self) -> bool: + """ + Wait until the TCP connection is closed or ``self.close_timeout`` elapses. + + Return :obj:`True` if the connection is closed and :obj:`False` + otherwise. + + """ + if not self.connection_lost_waiter.done(): + try: + async with asyncio_timeout(self.close_timeout): + await asyncio.shield(self.connection_lost_waiter) + except asyncio.TimeoutError: + pass + # Re-check self.connection_lost_waiter.done() synchronously because + # connection_lost() could run between the moment the timeout occurs + # and the moment this coroutine resumes running. + return self.connection_lost_waiter.done() + + def fail_connection( + self, + code: int = CloseCode.ABNORMAL_CLOSURE, + reason: str = "", + ) -> None: + """ + 7.1.7. Fail the WebSocket Connection + + This requires: + + 1. Stopping all processing of incoming data, which means cancelling + :attr:`transfer_data_task`. The close code will be 1006 unless a + close frame was received earlier. + + 2. Sending a close frame with an appropriate code if the opening + handshake succeeded and the other side is likely to process it. + + 3. Closing the connection. :meth:`close_connection` takes care of + this once :attr:`transfer_data_task` exits after being canceled. + + (The specification describes these steps in the opposite order.) + + """ + if self.debug: + self.logger.debug("! failing connection with code %d", code) + + # Cancel transfer_data_task if the opening handshake succeeded. + # cancel() is idempotent and ignored if the task is done already. + if hasattr(self, "transfer_data_task"): + self.transfer_data_task.cancel() + + # Send a close frame when the state is OPEN (a close frame was already + # sent if it's CLOSING), except when failing the connection because of + # an error reading from or writing to the network. + # Don't send a close frame if the connection is broken. + if code != CloseCode.ABNORMAL_CLOSURE and self.state is State.OPEN: + close = Close(code, reason) + + # Write the close frame without draining the write buffer. + + # Keeping fail_connection() synchronous guarantees it can't + # get stuck and simplifies the implementation of the callers. + # Not drainig the write buffer is acceptable in this context. + + # This duplicates a few lines of code from write_close_frame(). + + self.state = State.CLOSING + if self.debug: + self.logger.debug("= connection is CLOSING") + + # If self.close_rcvd was set, the connection state would be + # CLOSING. Therefore self.close_rcvd isn't set and we don't + # have to set self.close_rcvd_then_sent. + assert self.close_rcvd is None + self.close_sent = close + + self.write_frame_sync(True, OP_CLOSE, close.serialize()) + + # Start close_connection_task if the opening handshake didn't succeed. + if not hasattr(self, "close_connection_task"): + self.close_connection_task = self.loop.create_task(self.close_connection()) + + def abort_pings(self) -> None: + """ + Raise ConnectionClosed in pending keepalive pings. + + They'll never receive a pong once the connection is closed. + + """ + assert self.state is State.CLOSED + exc = self.connection_closed_exc() + + for pong_waiter, _ping_timestamp in self.pings.values(): + pong_waiter.set_exception(exc) + # If the exception is never retrieved, it will be logged when ping + # is garbage-collected. This is confusing for users. + # Given that ping is done (with an exception), canceling it does + # nothing, but it prevents logging the exception. + pong_waiter.cancel() + + # asyncio.Protocol methods + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + """ + Configure write buffer limits. + + The high-water limit is defined by ``self.write_limit``. + + The low-water limit currently defaults to ``self.write_limit // 4`` in + :meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which should + be all right for reasonable use cases of this library. + + This is the earliest point where we can get hold of the transport, + which means it's the best point for configuring it. + + """ + transport = cast(asyncio.Transport, transport) + transport.set_write_buffer_limits(self.write_limit) + self.transport = transport + + # Copied from asyncio.StreamReaderProtocol + self.reader.set_transport(transport) + + def connection_lost(self, exc: Exception | None) -> None: + """ + 7.1.4. The WebSocket Connection is Closed. + + """ + self.state = State.CLOSED + self.logger.debug("= connection is CLOSED") + + self.abort_pings() + + # If self.connection_lost_waiter isn't pending, that's a bug, because: + # - it's set only here in connection_lost() which is called only once; + # - it must never be canceled. + self.connection_lost_waiter.set_result(None) + + if True: # pragma: no cover + # Copied from asyncio.StreamReaderProtocol + if self.reader is not None: + if exc is None: + self.reader.feed_eof() + else: + self.reader.set_exception(exc) + + # Copied from asyncio.FlowControlMixin + # Wake up the writer if currently paused. + if not self._paused: + return + waiter = self._drain_waiter + if waiter is None: + return + self._drain_waiter = None + if waiter.done(): + return + if exc is None: + waiter.set_result(None) + else: + waiter.set_exception(exc) + + def pause_writing(self) -> None: # pragma: no cover + assert not self._paused + self._paused = True + + def resume_writing(self) -> None: # pragma: no cover + assert self._paused + self._paused = False + + waiter = self._drain_waiter + if waiter is not None: + self._drain_waiter = None + if not waiter.done(): + waiter.set_result(None) + + def data_received(self, data: bytes) -> None: + self.reader.feed_data(data) + + def eof_received(self) -> None: + """ + Close the transport after receiving EOF. + + The WebSocket protocol has its own closing handshake: endpoints close + the TCP or TLS connection after sending and receiving a close frame. + + As a consequence, they never need to write after receiving EOF, so + there's no reason to keep the transport open by returning :obj:`True`. + + Besides, that doesn't work on TLS connections. + + """ + self.reader.feed_eof() + + +# broadcast() is defined in the protocol module even though it's primarily +# used by servers and documented in the server module because it works with +# client connections too and because it's easier to test together with the +# WebSocketCommonProtocol class. + + +def broadcast( + websockets: Iterable[WebSocketCommonProtocol], + message: Data, + raise_exceptions: bool = False, +) -> None: + """ + Broadcast a message to several WebSocket connections. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or bytes-like + object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) is sent + as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + :func:`broadcast` pushes the message synchronously to all connections even + if their write buffers are overflowing. There's no backpressure. + + If you broadcast messages faster than a connection can handle them, messages + will pile up in its write buffer until the connection times out. Keep + ``ping_interval`` and ``ping_timeout`` low to prevent excessive memory usage + from slow connections. + + Unlike :meth:`~websockets.legacy.protocol.WebSocketCommonProtocol.send`, + :func:`broadcast` doesn't support sending fragmented messages. Indeed, + fragmentation is useful for sending large messages without buffering them in + memory, while :func:`broadcast` buffers one copy per connection as fast as + possible. + + :func:`broadcast` skips connections that aren't open in order to avoid + errors on connections where the closing handshake is in progress. + + :func:`broadcast` ignores failures to write the message on some connections. + It continues writing to other connections. On Python 3.11 and above, you may + set ``raise_exceptions`` to :obj:`True` to record failures and raise all + exceptions in a :pep:`654` :exc:`ExceptionGroup`. + + While :func:`broadcast` makes more sense for servers, it works identically + with clients, if you have a use case for opening connections to many servers + and broadcasting a message to them. + + Args: + websockets: WebSocket connections to which the message will be sent. + message: Message to send. + raise_exceptions: Whether to raise an exception in case of failures. + + Raises: + TypeError: If ``message`` doesn't have a supported type. + + """ + if not isinstance(message, (str, bytes, bytearray, memoryview)): + raise TypeError("data must be str or bytes-like") + + if raise_exceptions: + if sys.version_info[:2] < (3, 11): # pragma: no cover + raise ValueError("raise_exceptions requires at least Python 3.11") + exceptions = [] + + opcode, data = prepare_data(message) + + for websocket in websockets: + if websocket.state is not State.OPEN: + continue + + if websocket._fragmented_message_waiter is not None: + if raise_exceptions: + exception = RuntimeError("sending a fragmented message") + exceptions.append(exception) + else: + websocket.logger.warning( + "skipped broadcast: sending a fragmented message", + ) + continue + + try: + websocket.write_frame_sync(True, opcode, data) + except Exception as write_exception: + if raise_exceptions: + exception = RuntimeError("failed to write message") + exception.__cause__ = write_exception + exceptions.append(exception) + else: + websocket.logger.warning( + "skipped broadcast: failed to write message: %s", + traceback.format_exception_only( + # Remove first argument when dropping Python 3.9. + type(write_exception), + write_exception, + )[0].strip(), + ) + + if raise_exceptions and exceptions: + raise ExceptionGroup("skipped broadcast", exceptions) + + +# Pretend that broadcast is actually defined in the server module. +broadcast.__module__ = "websockets.legacy.server" diff --git a/venv/lib/python3.10/site-packages/websockets/legacy/server.py b/venv/lib/python3.10/site-packages/websockets/legacy/server.py new file mode 100644 index 0000000000000000000000000000000000000000..f9d57cb99f2e6e89f617c03acd78df4bc91784eb --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/legacy/server.py @@ -0,0 +1,1191 @@ +from __future__ import annotations + +import asyncio +import email.utils +import functools +import http +import inspect +import logging +import socket +import warnings +from collections.abc import Awaitable, Generator, Iterable, Sequence +from types import TracebackType +from typing import Any, Callable, Union, cast + +from ..asyncio.compatibility import asyncio_timeout +from ..datastructures import Headers, HeadersLike, MultipleValuesError +from ..exceptions import ( + InvalidHandshake, + InvalidHeader, + InvalidMessage, + InvalidOrigin, + InvalidUpgrade, + NegotiationError, +) +from ..extensions import Extension, ServerExtensionFactory +from ..extensions.permessage_deflate import enable_server_permessage_deflate +from ..headers import ( + build_extension, + parse_extension, + parse_subprotocol, + validate_subprotocols, +) +from ..http11 import SERVER +from ..protocol import State +from ..typing import ExtensionHeader, LoggerLike, Origin, StatusLike, Subprotocol +from .exceptions import AbortHandshake +from .handshake import build_response, check_request +from .http import read_request +from .protocol import WebSocketCommonProtocol, broadcast + + +__all__ = [ + "broadcast", + "serve", + "unix_serve", + "WebSocketServerProtocol", + "WebSocketServer", +] + + +# Change to HeadersLike | ... when dropping Python < 3.10. +HeadersLikeOrCallable = Union[HeadersLike, Callable[[str, Headers], HeadersLike]] + +HTTPResponse = tuple[StatusLike, HeadersLike, bytes] + + +class WebSocketServerProtocol(WebSocketCommonProtocol): + """ + WebSocket server connection. + + :class:`WebSocketServerProtocol` provides :meth:`recv` and :meth:`send` + coroutines for receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with close code + 1000 (OK) or 1001 (going away) or without a close code. It raises + a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection + is closed with any other code. + + You may customize the opening handshake in a subclass by + overriding :meth:`process_request` or :meth:`select_subprotocol`. + + Args: + ws_server: WebSocket server that created this connection. + + See :func:`serve` for the documentation of ``ws_handler``, ``logger``, ``origins``, + ``extensions``, ``subprotocols``, ``extra_headers``, and ``server_header``. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + """ + + is_client = False + side = "server" + + def __init__( + self, + # The version that accepts the path in the second argument is deprecated. + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), + ws_server: WebSocketServer, + *, + logger: LoggerLike | None = None, + origins: Sequence[Origin | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLikeOrCallable | None = None, + server_header: str | None = SERVER, + process_request: ( + Callable[[str, Headers], Awaitable[HTTPResponse | None]] | None + ) = None, + select_subprotocol: ( + Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol] | None + ) = None, + open_timeout: float | None = 10, + **kwargs: Any, + ) -> None: + if logger is None: + logger = logging.getLogger("websockets.server") + super().__init__(logger=logger, **kwargs) + # For backwards compatibility with 6.0 or earlier. + if origins is not None and "" in origins: + warnings.warn("use None instead of '' in origins", DeprecationWarning) + origins = [None if origin == "" else origin for origin in origins] + # For backwards compatibility with 10.0 or earlier. Done here in + # addition to serve to trigger the deprecation warning on direct + # use of WebSocketServerProtocol. + self.ws_handler = remove_path_argument(ws_handler) + self.ws_server = ws_server + self.origins = origins + self.available_extensions = extensions + self.available_subprotocols = subprotocols + self.extra_headers = extra_headers + self.server_header = server_header + self._process_request = process_request + self._select_subprotocol = select_subprotocol + self.open_timeout = open_timeout + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + """ + Register connection and initialize a task to handle it. + + """ + super().connection_made(transport) + # Register the connection with the server before creating the handler + # task. Registering at the beginning of the handler coroutine would + # create a race condition between the creation of the task, which + # schedules its execution, and the moment the handler starts running. + self.ws_server.register(self) + self.handler_task = self.loop.create_task(self.handler()) + + async def handler(self) -> None: + """ + Handle the lifecycle of a WebSocket connection. + + Since this method doesn't have a caller able to handle exceptions, it + attempts to log relevant ones and guarantees that the TCP connection is + closed before exiting. + + """ + try: + try: + async with asyncio_timeout(self.open_timeout): + await self.handshake( + origins=self.origins, + available_extensions=self.available_extensions, + available_subprotocols=self.available_subprotocols, + extra_headers=self.extra_headers, + ) + except asyncio.TimeoutError: # pragma: no cover + raise + except ConnectionError: + raise + except Exception as exc: + if isinstance(exc, AbortHandshake): + status, headers, body = exc.status, exc.headers, exc.body + elif isinstance(exc, InvalidOrigin): + if self.debug: + self.logger.debug("! invalid origin", exc_info=True) + status, headers, body = ( + http.HTTPStatus.FORBIDDEN, + Headers(), + f"Failed to open a WebSocket connection: {exc}.\n".encode(), + ) + elif isinstance(exc, InvalidUpgrade): + if self.debug: + self.logger.debug("! invalid upgrade", exc_info=True) + status, headers, body = ( + http.HTTPStatus.UPGRADE_REQUIRED, + Headers([("Upgrade", "websocket")]), + ( + f"Failed to open a WebSocket connection: {exc}.\n" + f"\n" + f"You cannot access a WebSocket server directly " + f"with a browser. You need a WebSocket client.\n" + ).encode(), + ) + elif isinstance(exc, InvalidHandshake): + if self.debug: + self.logger.debug("! invalid handshake", exc_info=True) + exc_chain = cast(BaseException, exc) + exc_str = f"{exc_chain}" + while exc_chain.__cause__ is not None: + exc_chain = exc_chain.__cause__ + exc_str += f"; {exc_chain}" + status, headers, body = ( + http.HTTPStatus.BAD_REQUEST, + Headers(), + f"Failed to open a WebSocket connection: {exc_str}.\n".encode(), + ) + else: + self.logger.error("opening handshake failed", exc_info=True) + status, headers, body = ( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + Headers(), + ( + b"Failed to open a WebSocket connection.\n" + b"See server log for more information.\n" + ), + ) + + headers.setdefault("Date", email.utils.formatdate(usegmt=True)) + if self.server_header: + headers.setdefault("Server", self.server_header) + + headers.setdefault("Content-Length", str(len(body))) + headers.setdefault("Content-Type", "text/plain") + headers.setdefault("Connection", "close") + + self.write_http_response(status, headers, body) + self.logger.info( + "connection rejected (%d %s)", status.value, status.phrase + ) + await self.close_transport() + return + + try: + await self.ws_handler(self) + except Exception: + self.logger.error("connection handler failed", exc_info=True) + if not self.closed: + self.fail_connection(1011) + raise + + try: + await self.close() + except ConnectionError: + raise + except Exception: + self.logger.error("closing handshake failed", exc_info=True) + raise + + except Exception: + # Last-ditch attempt to avoid leaking connections on errors. + try: + self.transport.close() + except Exception: # pragma: no cover + pass + + finally: + # Unregister the connection with the server when the handler task + # terminates. Registration is tied to the lifecycle of the handler + # task because the server waits for tasks attached to registered + # connections before terminating. + self.ws_server.unregister(self) + self.logger.info("connection closed") + + async def read_http_request(self) -> tuple[str, Headers]: + """ + Read request line and headers from the HTTP request. + + If the request contains a body, it may be read from ``self.reader`` + after this coroutine returns. + + Raises: + InvalidMessage: If the HTTP message is malformed or isn't an + HTTP/1.1 GET request. + + """ + try: + path, headers = await read_request(self.reader) + except asyncio.CancelledError: # pragma: no cover + raise + except Exception as exc: + raise InvalidMessage("did not receive a valid HTTP request") from exc + + if self.debug: + self.logger.debug("< GET %s HTTP/1.1", path) + for key, value in headers.raw_items(): + self.logger.debug("< %s: %s", key, value) + + self.path = path + self.request_headers = headers + + return path, headers + + def write_http_response( + self, status: http.HTTPStatus, headers: Headers, body: bytes | None = None + ) -> None: + """ + Write status line and headers to the HTTP response. + + This coroutine is also able to write a response body. + + """ + self.response_headers = headers + + if self.debug: + self.logger.debug("> HTTP/1.1 %d %s", status.value, status.phrase) + for key, value in headers.raw_items(): + self.logger.debug("> %s: %s", key, value) + if body is not None: + self.logger.debug("> [body] (%d bytes)", len(body)) + + # Since the status line and headers only contain ASCII characters, + # we can keep this simple. + response = f"HTTP/1.1 {status.value} {status.phrase}\r\n" + response += str(headers) + + self.transport.write(response.encode()) + + if body is not None: + self.transport.write(body) + + async def process_request( + self, path: str, request_headers: Headers + ) -> HTTPResponse | None: + """ + Intercept the HTTP request and return an HTTP response if appropriate. + + You may override this method in a :class:`WebSocketServerProtocol` + subclass, for example: + + * to return an HTTP 200 OK response on a given path; then a load + balancer can use this path for a health check; + * to authenticate the request and return an HTTP 401 Unauthorized or an + HTTP 403 Forbidden when authentication fails. + + You may also override this method with the ``process_request`` + argument of :func:`serve` and :class:`WebSocketServerProtocol`. This + is equivalent, except ``process_request`` won't have access to the + protocol instance, so it can't store information for later use. + + :meth:`process_request` is expected to complete quickly. If it may run + for a long time, then it should await :meth:`wait_closed` and exit if + :meth:`wait_closed` completes, or else it could prevent the server + from shutting down. + + Args: + path: Request path, including optional query string. + request_headers: Request headers. + + Returns: + tuple[StatusLike, HeadersLike, bytes] | None: :obj:`None` to + continue the WebSocket handshake normally. + + An HTTP response, represented by a 3-uple of the response status, + headers, and body, to abort the WebSocket handshake and return + that HTTP response instead. + + """ + if self._process_request is not None: + response = self._process_request(path, request_headers) + if isinstance(response, Awaitable): + return await response + else: + # For backwards compatibility with 7.0. + warnings.warn( + "declare process_request as a coroutine", DeprecationWarning + ) + return response + return None + + @staticmethod + def process_origin( + headers: Headers, origins: Sequence[Origin | None] | None = None + ) -> Origin | None: + """ + Handle the Origin HTTP request header. + + Args: + headers: Request headers. + origins: Optional list of acceptable origins. + + Raises: + InvalidOrigin: If the origin isn't acceptable. + + """ + # "The user agent MUST NOT include more than one Origin header field" + # per https://datatracker.ietf.org/doc/html/rfc6454#section-7.3. + try: + origin = headers.get("Origin") + except MultipleValuesError as exc: + raise InvalidHeader("Origin", "multiple values") from exc + if origin is not None: + origin = cast(Origin, origin) + if origins is not None: + if origin not in origins: + raise InvalidOrigin(origin) + return origin + + @staticmethod + def process_extensions( + headers: Headers, + available_extensions: Sequence[ServerExtensionFactory] | None, + ) -> tuple[str | None, list[Extension]]: + """ + Handle the Sec-WebSocket-Extensions HTTP request header. + + Accept or reject each extension proposed in the client request. + Negotiate parameters for accepted extensions. + + Return the Sec-WebSocket-Extensions HTTP response header and the list + of accepted extensions. + + :rfc:`6455` leaves the rules up to the specification of each + :extension. + + To provide this level of flexibility, for each extension proposed by + the client, we check for a match with each extension available in the + server configuration. If no match is found, the extension is ignored. + + If several variants of the same extension are proposed by the client, + it may be accepted several times, which won't make sense in general. + Extensions must implement their own requirements. For this purpose, + the list of previously accepted extensions is provided. + + This process doesn't allow the server to reorder extensions. It can + only select a subset of the extensions proposed by the client. + + Other requirements, for example related to mandatory extensions or the + order of extensions, may be implemented by overriding this method. + + Args: + headers: Request headers. + extensions: Optional list of supported extensions. + + Raises: + InvalidHandshake: To abort the handshake with an HTTP 400 error. + + """ + response_header_value: str | None = None + + extension_headers: list[ExtensionHeader] = [] + accepted_extensions: list[Extension] = [] + + header_values = headers.get_all("Sec-WebSocket-Extensions") + + if header_values and available_extensions: + parsed_header_values: list[ExtensionHeader] = sum( + [parse_extension(header_value) for header_value in header_values], [] + ) + + for name, request_params in parsed_header_values: + for ext_factory in available_extensions: + # Skip non-matching extensions based on their name. + if ext_factory.name != name: + continue + + # Skip non-matching extensions based on their params. + try: + response_params, extension = ext_factory.process_request_params( + request_params, accepted_extensions + ) + except NegotiationError: + continue + + # Add matching extension to the final list. + extension_headers.append((name, response_params)) + accepted_extensions.append(extension) + + # Break out of the loop once we have a match. + break + + # If we didn't break from the loop, no extension in our list + # matched what the client sent. The extension is declined. + + # Serialize extension header. + if extension_headers: + response_header_value = build_extension(extension_headers) + + return response_header_value, accepted_extensions + + # Not @staticmethod because it calls self.select_subprotocol() + def process_subprotocol( + self, headers: Headers, available_subprotocols: Sequence[Subprotocol] | None + ) -> Subprotocol | None: + """ + Handle the Sec-WebSocket-Protocol HTTP request header. + + Return Sec-WebSocket-Protocol HTTP response header, which is the same + as the selected subprotocol. + + Args: + headers: Request headers. + available_subprotocols: Optional list of supported subprotocols. + + Raises: + InvalidHandshake: To abort the handshake with an HTTP 400 error. + + """ + subprotocol: Subprotocol | None = None + + header_values = headers.get_all("Sec-WebSocket-Protocol") + + if header_values and available_subprotocols: + parsed_header_values: list[Subprotocol] = sum( + [parse_subprotocol(header_value) for header_value in header_values], [] + ) + + subprotocol = self.select_subprotocol( + parsed_header_values, available_subprotocols + ) + + return subprotocol + + def select_subprotocol( + self, + client_subprotocols: Sequence[Subprotocol], + server_subprotocols: Sequence[Subprotocol], + ) -> Subprotocol | None: + """ + Pick a subprotocol among those supported by the client and the server. + + If several subprotocols are available, select the preferred subprotocol + by giving equal weight to the preferences of the client and the server. + + If no subprotocol is available, proceed without a subprotocol. + + You may provide a ``select_subprotocol`` argument to :func:`serve` or + :class:`WebSocketServerProtocol` to override this logic. For example, + you could reject the handshake if the client doesn't support a + particular subprotocol, rather than accept the handshake without that + subprotocol. + + Args: + client_subprotocols: List of subprotocols offered by the client. + server_subprotocols: List of subprotocols available on the server. + + Returns: + Selected subprotocol, if a common subprotocol was found. + + :obj:`None` to continue without a subprotocol. + + """ + if self._select_subprotocol is not None: + return self._select_subprotocol(client_subprotocols, server_subprotocols) + + subprotocols = set(client_subprotocols) & set(server_subprotocols) + if not subprotocols: + return None + return sorted( + subprotocols, + key=lambda p: client_subprotocols.index(p) + server_subprotocols.index(p), + )[0] + + async def handshake( + self, + origins: Sequence[Origin | None] | None = None, + available_extensions: Sequence[ServerExtensionFactory] | None = None, + available_subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLikeOrCallable | None = None, + ) -> str: + """ + Perform the server side of the opening handshake. + + Args: + origins: List of acceptable values of the Origin HTTP header; + include :obj:`None` if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be tried. + subprotocols: List of supported subprotocols, in order of + decreasing preference. + extra_headers: Arbitrary HTTP headers to add to the response when + the handshake succeeds. + + Returns: + path of the URI of the request. + + Raises: + InvalidHandshake: If the handshake fails. + + """ + path, request_headers = await self.read_http_request() + + # Hook for customizing request handling, for example checking + # authentication or treating some paths as plain HTTP endpoints. + early_response_awaitable = self.process_request(path, request_headers) + if isinstance(early_response_awaitable, Awaitable): + early_response = await early_response_awaitable + else: + # For backwards compatibility with 7.0. + warnings.warn("declare process_request as a coroutine", DeprecationWarning) + early_response = early_response_awaitable + + # The connection may drop while process_request is running. + if self.state is State.CLOSED: + # This subclass of ConnectionError is silently ignored in handler(). + raise BrokenPipeError("connection closed during opening handshake") + + # Change the response to a 503 error if the server is shutting down. + if not self.ws_server.is_serving(): + early_response = ( + http.HTTPStatus.SERVICE_UNAVAILABLE, + [], + b"Server is shutting down.\n", + ) + + if early_response is not None: + raise AbortHandshake(*early_response) + + key = check_request(request_headers) + + self.origin = self.process_origin(request_headers, origins) + + extensions_header, self.extensions = self.process_extensions( + request_headers, available_extensions + ) + + protocol_header = self.subprotocol = self.process_subprotocol( + request_headers, available_subprotocols + ) + + response_headers = Headers() + + build_response(response_headers, key) + + if extensions_header is not None: + response_headers["Sec-WebSocket-Extensions"] = extensions_header + + if protocol_header is not None: + response_headers["Sec-WebSocket-Protocol"] = protocol_header + + if callable(extra_headers): + extra_headers = extra_headers(path, self.request_headers) + if extra_headers is not None: + response_headers.update(extra_headers) + + response_headers.setdefault("Date", email.utils.formatdate(usegmt=True)) + if self.server_header is not None: + response_headers.setdefault("Server", self.server_header) + + self.write_http_response(http.HTTPStatus.SWITCHING_PROTOCOLS, response_headers) + + self.logger.info("connection open") + + self.connection_open() + + return path + + +class WebSocketServer: + """ + WebSocket server returned by :func:`serve`. + + This class mirrors the API of :class:`~asyncio.Server`. + + It keeps track of WebSocket connections in order to close them properly + when shutting down. + + Args: + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__(self, logger: LoggerLike | None = None) -> None: + if logger is None: + logger = logging.getLogger("websockets.server") + self.logger = logger + + # Keep track of active connections. + self.websockets: set[WebSocketServerProtocol] = set() + + # Task responsible for closing the server and terminating connections. + self.close_task: asyncio.Task[None] | None = None + + # Completed when the server is closed and connections are terminated. + self.closed_waiter: asyncio.Future[None] + + def wrap(self, server: asyncio.base_events.Server) -> None: + """ + Attach to a given :class:`~asyncio.Server`. + + Since :meth:`~asyncio.loop.create_server` doesn't support injecting a + custom ``Server`` class, the easiest solution that doesn't rely on + private :mod:`asyncio` APIs is to: + + - instantiate a :class:`WebSocketServer` + - give the protocol factory a reference to that instance + - call :meth:`~asyncio.loop.create_server` with the factory + - attach the resulting :class:`~asyncio.Server` with this method + + """ + self.server = server + for sock in server.sockets: + if sock.family == socket.AF_INET: + name = "%s:%d" % sock.getsockname() + elif sock.family == socket.AF_INET6: + name = "[%s]:%d" % sock.getsockname()[:2] + elif sock.family == socket.AF_UNIX: + name = sock.getsockname() + # In the unlikely event that someone runs websockets over a + # protocol other than IP or Unix sockets, avoid crashing. + else: # pragma: no cover + name = str(sock.getsockname()) + self.logger.info("server listening on %s", name) + + # Initialized here because we need a reference to the event loop. + # This should be moved back to __init__ when dropping Python < 3.10. + self.closed_waiter = server.get_loop().create_future() + + def register(self, protocol: WebSocketServerProtocol) -> None: + """ + Register a connection with this server. + + """ + self.websockets.add(protocol) + + def unregister(self, protocol: WebSocketServerProtocol) -> None: + """ + Unregister a connection with this server. + + """ + self.websockets.remove(protocol) + + def close(self, close_connections: bool = True) -> None: + """ + Close the server. + + * Close the underlying :class:`~asyncio.Server`. + * When ``close_connections`` is :obj:`True`, which is the default, + close existing connections. Specifically: + + * Reject opening WebSocket connections with an HTTP 503 (service + unavailable) error. This happens when the server accepted the TCP + connection but didn't complete the opening handshake before closing. + * Close open WebSocket connections with close code 1001 (going away). + + * Wait until all connection handlers terminate. + + :meth:`close` is idempotent. + + """ + if self.close_task is None: + self.close_task = self.get_loop().create_task( + self._close(close_connections) + ) + + async def _close(self, close_connections: bool) -> None: + """ + Implementation of :meth:`close`. + + This calls :meth:`~asyncio.Server.close` on the underlying + :class:`~asyncio.Server` object to stop accepting new connections and + then closes open connections with close code 1001. + + """ + self.logger.info("server closing") + + # Stop accepting new connections. + self.server.close() + + # Wait until all accepted connections reach connection_made() and call + # register(). See https://github.com/python/cpython/issues/79033 for + # details. This workaround can be removed when dropping Python < 3.11. + await asyncio.sleep(0) + + if close_connections: + # Close OPEN connections with close code 1001. After server.close(), + # handshake() closes OPENING connections with an HTTP 503 error. + close_tasks = [ + asyncio.create_task(websocket.close(1001)) + for websocket in self.websockets + if websocket.state is not State.CONNECTING + ] + # asyncio.wait doesn't accept an empty first argument. + if close_tasks: + await asyncio.wait(close_tasks) + + # Wait until all TCP connections are closed. + await self.server.wait_closed() + + # Wait until all connection handlers terminate. + # asyncio.wait doesn't accept an empty first argument. + if self.websockets: + await asyncio.wait( + [websocket.handler_task for websocket in self.websockets] + ) + + # Tell wait_closed() to return. + self.closed_waiter.set_result(None) + + self.logger.info("server closed") + + async def wait_closed(self) -> None: + """ + Wait until the server is closed. + + When :meth:`wait_closed` returns, all TCP connections are closed and + all connection handlers have returned. + + To ensure a fast shutdown, a connection handler should always be + awaiting at least one of: + + * :meth:`~WebSocketServerProtocol.recv`: when the connection is closed, + it raises :exc:`~websockets.exceptions.ConnectionClosedOK`; + * :meth:`~WebSocketServerProtocol.wait_closed`: when the connection is + closed, it returns. + + Then the connection handler is immediately notified of the shutdown; + it can clean up and exit. + + """ + await asyncio.shield(self.closed_waiter) + + def get_loop(self) -> asyncio.AbstractEventLoop: + """ + See :meth:`asyncio.Server.get_loop`. + + """ + return self.server.get_loop() + + def is_serving(self) -> bool: + """ + See :meth:`asyncio.Server.is_serving`. + + """ + return self.server.is_serving() + + async def start_serving(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.start_serving`. + + Typical use:: + + server = await serve(..., start_serving=False) + # perform additional setup here... + # ... then start the server + await server.start_serving() + + """ + await self.server.start_serving() + + async def serve_forever(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.serve_forever`. + + Typical use:: + + server = await serve(...) + # this coroutine doesn't return + # canceling it stops the server + await server.serve_forever() + + This is an alternative to using :func:`serve` as an asynchronous context + manager. Shutdown is triggered by canceling :meth:`serve_forever` + instead of exiting a :func:`serve` context. + + """ + await self.server.serve_forever() + + @property + def sockets(self) -> Iterable[socket.socket]: + """ + See :attr:`asyncio.Server.sockets`. + + """ + return self.server.sockets + + async def __aenter__(self) -> WebSocketServer: # pragma: no cover + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: # pragma: no cover + self.close() + await self.wait_closed() + + +class Serve: + """ + Start a WebSocket server listening on ``host`` and ``port``. + + Whenever a client connects, the server creates a + :class:`WebSocketServerProtocol`, performs the opening handshake, and + delegates to the connection handler, ``ws_handler``. + + The handler receives the :class:`WebSocketServerProtocol` and uses it to + send and receive messages. + + Once the handler completes, either normally or with an exception, the + server performs the closing handshake and closes the connection. + + Awaiting :func:`serve` yields a :class:`WebSocketServer`. This object + provides a :meth:`~WebSocketServer.close` method to shut down the server:: + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + server = await serve(...) + await stop + server.close() + await server.wait_closed() + + :func:`serve` can be used as an asynchronous context manager. Then, the + server is shut down automatically when exiting the context:: + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + async with serve(...): + await stop + + Args: + ws_handler: Connection handler. It receives the WebSocket connection, + which is a :class:`WebSocketServerProtocol`, in argument. + host: Network interfaces the server binds to. + See :meth:`~asyncio.loop.create_server` for details. + port: TCP port the server listens on. + See :meth:`~asyncio.loop.create_server` for details. + create_protocol: Factory for the :class:`asyncio.Protocol` managing + the connection. It defaults to :class:`WebSocketServerProtocol`. + Set it to a wrapper or a subclass to customize connection handling. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + origins: Acceptable values of the ``Origin`` header, for defending + against Cross-Site WebSocket Hijacking attacks. Include :obj:`None` + in the list if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + extra_headers (HeadersLike | Callable[[str, Headers] | HeadersLike]): + Arbitrary HTTP headers to add to the response. This can be + a :data:`~websockets.datastructures.HeadersLike` or a callable + taking the request path and headers in arguments and returning + a :data:`~websockets.datastructures.HeadersLike`. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + process_request (Callable[[str, Headers], \ + Awaitable[tuple[StatusLike, HeadersLike, bytes] | None]] | None): + Intercept HTTP request before the opening handshake. + See :meth:`~WebSocketServerProtocol.process_request` for details. + select_subprotocol: Select a subprotocol supported by the client. + See :meth:`~WebSocketServerProtocol.select_subprotocol` for details. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + Any other keyword arguments are passed the event loop's + :meth:`~asyncio.loop.create_server` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS. + + * You can set ``sock`` to a :obj:`~socket.socket` that you created + outside of websockets. + + Returns: + WebSocket server. + + """ + + def __init__( + self, + # The version that accepts the path in the second argument is deprecated. + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), + host: str | Sequence[str] | None = None, + port: int | None = None, + *, + create_protocol: Callable[..., WebSocketServerProtocol] | None = None, + logger: LoggerLike | None = None, + compression: str | None = "deflate", + origins: Sequence[Origin | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLikeOrCallable | None = None, + server_header: str | None = SERVER, + process_request: ( + Callable[[str, Headers], Awaitable[HTTPResponse | None]] | None + ) = None, + select_subprotocol: ( + Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol] | None + ) = None, + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = None, + max_size: int | None = 2**20, + max_queue: int | None = 2**5, + read_limit: int = 2**16, + write_limit: int = 2**16, + **kwargs: Any, + ) -> None: + # Backwards compatibility: close_timeout used to be called timeout. + timeout: float | None = kwargs.pop("timeout", None) + if timeout is None: + timeout = 10 + else: + warnings.warn("rename timeout to close_timeout", DeprecationWarning) + # If both are specified, timeout is ignored. + if close_timeout is None: + close_timeout = timeout + + # Backwards compatibility: create_protocol used to be called klass. + klass: type[WebSocketServerProtocol] | None = kwargs.pop("klass", None) + if klass is None: + klass = WebSocketServerProtocol + else: + warnings.warn("rename klass to create_protocol", DeprecationWarning) + # If both are specified, klass is ignored. + if create_protocol is None: + create_protocol = klass + + # Backwards compatibility: recv() used to return None on closed connections + legacy_recv: bool = kwargs.pop("legacy_recv", False) + + # Backwards compatibility: the loop parameter used to be supported. + _loop: asyncio.AbstractEventLoop | None = kwargs.pop("loop", None) + if _loop is None: + loop = asyncio.get_event_loop() + else: + loop = _loop + warnings.warn("remove loop argument", DeprecationWarning) + + ws_server = WebSocketServer(logger=logger) + + secure = kwargs.get("ssl") is not None + + if compression == "deflate": + extensions = enable_server_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + # Help mypy and avoid this error: "type[WebSocketServerProtocol] | + # Callable[..., WebSocketServerProtocol]" not callable [misc] + create_protocol = cast(Callable[..., WebSocketServerProtocol], create_protocol) + factory = functools.partial( + create_protocol, + # For backwards compatibility with 10.0 or earlier. Done here in + # addition to WebSocketServerProtocol to trigger the deprecation + # warning once per serve() call rather than once per connection. + remove_path_argument(ws_handler), + ws_server, + host=host, + port=port, + secure=secure, + open_timeout=open_timeout, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_size=max_size, + max_queue=max_queue, + read_limit=read_limit, + write_limit=write_limit, + loop=_loop, + legacy_recv=legacy_recv, + origins=origins, + extensions=extensions, + subprotocols=subprotocols, + extra_headers=extra_headers, + server_header=server_header, + process_request=process_request, + select_subprotocol=select_subprotocol, + logger=logger, + ) + + if kwargs.pop("unix", False): + path: str | None = kwargs.pop("path", None) + # unix_serve(path) must not specify host and port parameters. + assert host is None and port is None + create_server = functools.partial( + loop.create_unix_server, factory, path, **kwargs + ) + else: + create_server = functools.partial( + loop.create_server, factory, host, port, **kwargs + ) + + # This is a coroutine function. + self._create_server = create_server + self.ws_server = ws_server + + # async with serve(...) + + async def __aenter__(self) -> WebSocketServer: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.ws_server.close() + await self.ws_server.wait_closed() + + # await serve(...) + + def __await__(self) -> Generator[Any, None, WebSocketServer]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> WebSocketServer: + server = await self._create_server() + self.ws_server.wrap(server) + return self.ws_server + + # yield from serve(...) - remove when dropping Python < 3.10 + + __iter__ = __await__ + + +serve = Serve + + +def unix_serve( + # The version that accepts the path in the second argument is deprecated. + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), + path: str | None = None, + **kwargs: Any, +) -> Serve: + """ + Start a WebSocket server listening on a Unix socket. + + This function is identical to :func:`serve`, except the ``host`` and + ``port`` arguments are replaced by ``path``. It is only available on Unix. + + Unrecognized keyword arguments are passed the event loop's + :meth:`~asyncio.loop.create_unix_server` method. + + It's useful for deploying a server behind a reverse proxy such as nginx. + + Args: + path: File system path to the Unix socket. + + """ + return serve(ws_handler, path=path, unix=True, **kwargs) + + +def remove_path_argument( + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), +) -> Callable[[WebSocketServerProtocol], Awaitable[Any]]: + try: + inspect.signature(ws_handler).bind(None) + except TypeError: + try: + inspect.signature(ws_handler).bind(None, "") + except TypeError: # pragma: no cover + # ws_handler accepts neither one nor two arguments; leave it alone. + pass + else: + # ws_handler accepts two arguments; activate backwards compatibility. + warnings.warn("remove second argument of ws_handler", DeprecationWarning) + + async def _ws_handler(websocket: WebSocketServerProtocol) -> Any: + return await cast( + Callable[[WebSocketServerProtocol, str], Awaitable[Any]], + ws_handler, + )(websocket, websocket.path) + + return _ws_handler + + return cast( + Callable[[WebSocketServerProtocol], Awaitable[Any]], + ws_handler, + ) diff --git a/venv/lib/python3.10/site-packages/websockets/protocol.py b/venv/lib/python3.10/site-packages/websockets/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..bc64a216ad1beb045eb552eb0c7bbee186122f74 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/protocol.py @@ -0,0 +1,758 @@ +from __future__ import annotations + +import enum +import logging +import uuid +from collections.abc import Generator +from typing import Union + +from .exceptions import ( + ConnectionClosed, + ConnectionClosedError, + ConnectionClosedOK, + InvalidState, + PayloadTooBig, + ProtocolError, +) +from .extensions import Extension +from .frames import ( + OK_CLOSE_CODES, + OP_BINARY, + OP_CLOSE, + OP_CONT, + OP_PING, + OP_PONG, + OP_TEXT, + Close, + CloseCode, + Frame, +) +from .http11 import Request, Response +from .streams import StreamReader +from .typing import LoggerLike, Origin, Subprotocol + + +__all__ = [ + "Protocol", + "Side", + "State", + "SEND_EOF", +] + +# Change to Request | Response | Frame when dropping Python < 3.10. +Event = Union[Request, Response, Frame] +"""Events that :meth:`~Protocol.events_received` may return.""" + + +class Side(enum.IntEnum): + """A WebSocket connection is either a server or a client.""" + + SERVER, CLIENT = range(2) + + +SERVER = Side.SERVER +CLIENT = Side.CLIENT + + +class State(enum.IntEnum): + """A WebSocket connection is in one of these four states.""" + + CONNECTING, OPEN, CLOSING, CLOSED = range(4) + + +CONNECTING = State.CONNECTING +OPEN = State.OPEN +CLOSING = State.CLOSING +CLOSED = State.CLOSED + + +SEND_EOF = b"" +"""Sentinel signaling that the TCP connection must be half-closed.""" + + +class Protocol: + """ + Sans-I/O implementation of a WebSocket connection. + + Args: + side: :attr:`~Side.CLIENT` or :attr:`~Side.SERVER`. + state: Initial state of the WebSocket connection. + max_size: Maximum size of incoming messages in bytes; + :obj:`None` disables the limit. + logger: Logger for this connection; depending on ``side``, + defaults to ``logging.getLogger("websockets.client")`` + or ``logging.getLogger("websockets.server")``; + see the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__( + self, + side: Side, + *, + state: State = OPEN, + max_size: int | None = 2**20, + logger: LoggerLike | None = None, + ) -> None: + # Unique identifier. For logs. + self.id: uuid.UUID = uuid.uuid4() + """Unique identifier of the connection. Useful in logs.""" + + # Logger or LoggerAdapter for this connection. + if logger is None: + logger = logging.getLogger(f"websockets.{side.name.lower()}") + self.logger: LoggerLike = logger + """Logger for this connection.""" + + # Track if DEBUG is enabled. Shortcut logging calls if it isn't. + self.debug = logger.isEnabledFor(logging.DEBUG) + + # Connection side. CLIENT or SERVER. + self.side = side + + # Connection state. Initially OPEN because subclasses handle CONNECTING. + self.state = state + + # Maximum size of incoming messages in bytes. + self.max_size = max_size + + # Current size of incoming message in bytes. Only set while reading a + # fragmented message i.e. a data frames with the FIN bit not set. + self.cur_size: int | None = None + + # True while sending a fragmented message i.e. a data frames with the + # FIN bit not set. + self.expect_continuation_frame = False + + # WebSocket protocol parameters. + self.origin: Origin | None = None + self.extensions: list[Extension] = [] + self.subprotocol: Subprotocol | None = None + + # Close code and reason, set when a close frame is sent or received. + self.close_rcvd: Close | None = None + self.close_sent: Close | None = None + self.close_rcvd_then_sent: bool | None = None + + # Track if an exception happened during the handshake. + self.handshake_exc: Exception | None = None + """ + Exception to raise if the opening handshake failed. + + :obj:`None` if the opening handshake succeeded. + + """ + + # Track if send_eof() was called. + self.eof_sent = False + + # Parser state. + self.reader = StreamReader() + self.events: list[Event] = [] + self.writes: list[bytes] = [] + self.parser = self.parse() + next(self.parser) # start coroutine + self.parser_exc: Exception | None = None + + @property + def state(self) -> State: + """ + State of the WebSocket connection. + + Defined in 4.1_, 4.2_, 7.1.3_, and 7.1.4_ of :rfc:`6455`. + + .. _4.1: https://datatracker.ietf.org/doc/html/rfc6455#section-4.1 + .. _4.2: https://datatracker.ietf.org/doc/html/rfc6455#section-4.2 + .. _7.1.3: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.3 + .. _7.1.4: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 + + """ + return self._state + + @state.setter + def state(self, state: State) -> None: + if self.debug: + self.logger.debug("= connection is %s", state.name) + self._state = state + + @property + def close_code(self) -> int | None: + """ + WebSocket close code received from the remote endpoint. + + Defined in 7.1.5_ of :rfc:`6455`. + + .. _7.1.5: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + + :obj:`None` if the connection isn't closed yet. + + """ + if self.state is not CLOSED: + return None + elif self.close_rcvd is None: + return CloseCode.ABNORMAL_CLOSURE + else: + return self.close_rcvd.code + + @property + def close_reason(self) -> str | None: + """ + WebSocket close reason received from the remote endpoint. + + Defined in 7.1.6_ of :rfc:`6455`. + + .. _7.1.6: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + + :obj:`None` if the connection isn't closed yet. + + """ + if self.state is not CLOSED: + return None + elif self.close_rcvd is None: + return "" + else: + return self.close_rcvd.reason + + @property + def close_exc(self) -> ConnectionClosed: + """ + Exception to raise when trying to interact with a closed connection. + + Don't raise this exception while the connection :attr:`state` + is :attr:`~websockets.protocol.State.CLOSING`; wait until + it's :attr:`~websockets.protocol.State.CLOSED`. + + Indeed, the exception includes the close code and reason, which are + known only once the connection is closed. + + Raises: + AssertionError: If the connection isn't closed yet. + + """ + assert self.state is CLOSED, "connection isn't closed yet" + exc_type: type[ConnectionClosed] + if ( + self.close_rcvd is not None + and self.close_sent is not None + and self.close_rcvd.code in OK_CLOSE_CODES + and self.close_sent.code in OK_CLOSE_CODES + ): + exc_type = ConnectionClosedOK + else: + exc_type = ConnectionClosedError + exc: ConnectionClosed = exc_type( + self.close_rcvd, + self.close_sent, + self.close_rcvd_then_sent, + ) + # Chain to the exception raised in the parser, if any. + exc.__cause__ = self.parser_exc + return exc + + # Public methods for receiving data. + + def receive_data(self, data: bytes) -> None: + """ + Receive data from the network. + + After calling this method: + + - You must call :meth:`data_to_send` and send this data to the network. + - You should call :meth:`events_received` and process resulting events. + + Raises: + EOFError: If :meth:`receive_eof` was called earlier. + + """ + self.reader.feed_data(data) + next(self.parser) + + def receive_eof(self) -> None: + """ + Receive the end of the data stream from the network. + + After calling this method: + + - You must call :meth:`data_to_send` and send this data to the network; + it will return ``[b""]``, signaling the end of the stream, or ``[]``. + - You aren't expected to call :meth:`events_received`; it won't return + any new events. + + :meth:`receive_eof` is idempotent. + + """ + if self.reader.eof: + return + self.reader.feed_eof() + next(self.parser) + + # Public methods for sending events. + + def send_continuation(self, data: bytes, fin: bool) -> None: + """ + Send a `Continuation frame`_. + + .. _Continuation frame: + https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + Parameters: + data: payload containing the same kind of data + as the initial frame. + fin: FIN bit; set it to :obj:`True` if this is the last frame + of a fragmented message and to :obj:`False` otherwise. + + Raises: + ProtocolError: If a fragmented message isn't in progress. + + """ + if not self.expect_continuation_frame: + raise ProtocolError("unexpected continuation frame") + if self._state is not OPEN: + raise InvalidState(f"connection is {self.state.name.lower()}") + self.expect_continuation_frame = not fin + self.send_frame(Frame(OP_CONT, data, fin)) + + def send_text(self, data: bytes, fin: bool = True) -> None: + """ + Send a `Text frame`_. + + .. _Text frame: + https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + Parameters: + data: payload containing text encoded with UTF-8. + fin: FIN bit; set it to :obj:`False` if this is the first frame of + a fragmented message. + + Raises: + ProtocolError: If a fragmented message is in progress. + + """ + if self.expect_continuation_frame: + raise ProtocolError("expected a continuation frame") + if self._state is not OPEN: + raise InvalidState(f"connection is {self.state.name.lower()}") + self.expect_continuation_frame = not fin + self.send_frame(Frame(OP_TEXT, data, fin)) + + def send_binary(self, data: bytes, fin: bool = True) -> None: + """ + Send a `Binary frame`_. + + .. _Binary frame: + https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + Parameters: + data: payload containing arbitrary binary data. + fin: FIN bit; set it to :obj:`False` if this is the first frame of + a fragmented message. + + Raises: + ProtocolError: If a fragmented message is in progress. + + """ + if self.expect_continuation_frame: + raise ProtocolError("expected a continuation frame") + if self._state is not OPEN: + raise InvalidState(f"connection is {self.state.name.lower()}") + self.expect_continuation_frame = not fin + self.send_frame(Frame(OP_BINARY, data, fin)) + + def send_close(self, code: int | None = None, reason: str = "") -> None: + """ + Send a `Close frame`_. + + .. _Close frame: + https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.1 + + Parameters: + code: close code. + reason: close reason. + + Raises: + ProtocolError: If the code isn't valid or if a reason is provided + without a code. + + """ + # While RFC 6455 doesn't rule out sending more than one close Frame, + # websockets is conservative in what it sends and doesn't allow that. + if self._state is not OPEN: + raise InvalidState(f"connection is {self.state.name.lower()}") + if code is None: + if reason != "": + raise ProtocolError("cannot send a reason without a code") + close = Close(CloseCode.NO_STATUS_RCVD, "") + data = b"" + else: + close = Close(code, reason) + data = close.serialize() + # 7.1.3. The WebSocket Closing Handshake is Started + self.send_frame(Frame(OP_CLOSE, data)) + # Since the state is OPEN, no close frame was received yet. + # As a consequence, self.close_rcvd_then_sent remains None. + assert self.close_rcvd is None + self.close_sent = close + self.state = CLOSING + + def send_ping(self, data: bytes) -> None: + """ + Send a `Ping frame`_. + + .. _Ping frame: + https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + Parameters: + data: payload containing arbitrary binary data. + + """ + # RFC 6455 allows control frames after starting the closing handshake. + if self._state is not OPEN and self._state is not CLOSING: + raise InvalidState(f"connection is {self.state.name.lower()}") + self.send_frame(Frame(OP_PING, data)) + + def send_pong(self, data: bytes) -> None: + """ + Send a `Pong frame`_. + + .. _Pong frame: + https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + Parameters: + data: payload containing arbitrary binary data. + + """ + # RFC 6455 allows control frames after starting the closing handshake. + if self._state is not OPEN and self._state is not CLOSING: + raise InvalidState(f"connection is {self.state.name.lower()}") + self.send_frame(Frame(OP_PONG, data)) + + def fail(self, code: int, reason: str = "") -> None: + """ + `Fail the WebSocket connection`_. + + .. _Fail the WebSocket connection: + https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.7 + + Parameters: + code: close code + reason: close reason + + Raises: + ProtocolError: If the code isn't valid. + """ + # 7.1.7. Fail the WebSocket Connection + + # Send a close frame when the state is OPEN (a close frame was already + # sent if it's CLOSING), except when failing the connection because + # of an error reading from or writing to the network. + if self.state is OPEN: + if code != CloseCode.ABNORMAL_CLOSURE: + close = Close(code, reason) + data = close.serialize() + self.send_frame(Frame(OP_CLOSE, data)) + self.close_sent = close + # If recv_messages() raised an exception upon receiving a close + # frame but before echoing it, then close_rcvd is not None even + # though the state is OPEN. This happens when the connection is + # closed while receiving a fragmented message. + if self.close_rcvd is not None: + self.close_rcvd_then_sent = True + self.state = CLOSING + + # When failing the connection, a server closes the TCP connection + # without waiting for the client to complete the handshake, while a + # client waits for the server to close the TCP connection, possibly + # after sending a close frame that the client will ignore. + if self.side is SERVER and not self.eof_sent: + self.send_eof() + + # 7.1.7. Fail the WebSocket Connection "An endpoint MUST NOT continue + # to attempt to process data(including a responding Close frame) from + # the remote endpoint after being instructed to _Fail the WebSocket + # Connection_." + self.parser = self.discard() + next(self.parser) # start coroutine + + # Public method for getting incoming events after receiving data. + + def events_received(self) -> list[Event]: + """ + Fetch events generated from data received from the network. + + Call this method immediately after any of the ``receive_*()`` methods. + + Process resulting events, likely by passing them to the application. + + Returns: + Events read from the connection. + """ + events, self.events = self.events, [] + return events + + # Public method for getting outgoing data after receiving data or sending events. + + def data_to_send(self) -> list[bytes]: + """ + Obtain data to send to the network. + + Call this method immediately after any of the ``receive_*()``, + ``send_*()``, or :meth:`fail` methods. + + Write resulting data to the connection. + + The empty bytestring :data:`~websockets.protocol.SEND_EOF` signals + the end of the data stream. When you receive it, half-close the TCP + connection. + + Returns: + Data to write to the connection. + + """ + writes, self.writes = self.writes, [] + return writes + + def close_expected(self) -> bool: + """ + Tell if the TCP connection is expected to close soon. + + Call this method immediately after any of the ``receive_*()``, + ``send_close()``, or :meth:`fail` methods. + + If it returns :obj:`True`, schedule closing the TCP connection after a + short timeout if the other side hasn't already closed it. + + Returns: + Whether the TCP connection is expected to close soon. + + """ + # During the opening handshake, when our state is CONNECTING, we expect + # a TCP close if and only if the hansdake fails. When it does, we start + # the TCP closing handshake by sending EOF with send_eof(). + + # Once the opening handshake completes successfully, we expect a TCP + # close if and only if we sent a close frame, meaning that our state + # progressed to CLOSING: + + # * Normal closure: once we send a close frame, we expect a TCP close: + # server waits for client to complete the TCP closing handshake; + # client waits for server to initiate the TCP closing handshake. + + # * Abnormal closure: we always send a close frame and the same logic + # applies, except on EOFError where we don't send a close frame + # because we already received the TCP close, so we don't expect it. + + # If our state is CLOSED, we already received a TCP close so we don't + # expect it anymore. + + # Micro-optimization: put the most common case first + if self.state is OPEN: + return False + if self.state is CLOSING: + return True + if self.state is CLOSED: + return False + assert self.state is CONNECTING + return self.eof_sent + + # Private methods for receiving data. + + def parse(self) -> Generator[None]: + """ + Parse incoming data into frames. + + :meth:`receive_data` and :meth:`receive_eof` run this generator + coroutine until it needs more data or reaches EOF. + + :meth:`parse` never raises an exception. Instead, it sets the + :attr:`parser_exc` and yields control. + + """ + try: + while True: + if (yield from self.reader.at_eof()): + if self.debug: + self.logger.debug("< EOF") + # If the WebSocket connection is closed cleanly, with a + # closing handhshake, recv_frame() substitutes parse() + # with discard(). This branch is reached only when the + # connection isn't closed cleanly. + raise EOFError("unexpected end of stream") + + if self.max_size is None: + max_size = None + elif self.cur_size is None: + max_size = self.max_size + else: + max_size = self.max_size - self.cur_size + + # During a normal closure, execution ends here on the next + # iteration of the loop after receiving a close frame. At + # this point, recv_frame() replaced parse() by discard(). + frame = yield from Frame.parse( + self.reader.read_exact, + mask=self.side is SERVER, + max_size=max_size, + extensions=self.extensions, + ) + + if self.debug: + self.logger.debug("< %s", frame) + + self.recv_frame(frame) + + except ProtocolError as exc: + self.fail(CloseCode.PROTOCOL_ERROR, str(exc)) + self.parser_exc = exc + + except EOFError as exc: + self.fail(CloseCode.ABNORMAL_CLOSURE, str(exc)) + self.parser_exc = exc + + except UnicodeDecodeError as exc: + self.fail(CloseCode.INVALID_DATA, f"{exc.reason} at position {exc.start}") + self.parser_exc = exc + + except PayloadTooBig as exc: + exc.set_current_size(self.cur_size) + self.fail(CloseCode.MESSAGE_TOO_BIG, str(exc)) + self.parser_exc = exc + + except Exception as exc: + self.logger.error("parser failed", exc_info=True) + # Don't include exception details, which may be security-sensitive. + self.fail(CloseCode.INTERNAL_ERROR) + self.parser_exc = exc + + # During an abnormal closure, execution ends here after catching an + # exception. At this point, fail() replaced parse() by discard(). + yield + raise AssertionError("parse() shouldn't step after error") + + def discard(self) -> Generator[None]: + """ + Discard incoming data. + + This coroutine replaces :meth:`parse`: + + - after receiving a close frame, during a normal closure (1.4); + - after sending a close frame, during an abnormal closure (7.1.7). + + """ + # After the opening handshake completes, the server closes the TCP + # connection in the same circumstances where discard() replaces parse(). + # The client closes it when it receives EOF from the server or times + # out. (The latter case cannot be handled in this Sans-I/O layer.) + assert (self.side is SERVER or self.state is CONNECTING) == (self.eof_sent) + while not (yield from self.reader.at_eof()): + self.reader.discard() + if self.debug: + self.logger.debug("< EOF") + # A server closes the TCP connection immediately, while a client + # waits for the server to close the TCP connection. + if self.side is CLIENT and self.state is not CONNECTING: + self.send_eof() + self.state = CLOSED + # If discard() completes normally, execution ends here. + yield + # Once the reader reaches EOF, its feed_data/eof() methods raise an + # error, so our receive_data/eof() methods don't step the generator. + raise AssertionError("discard() shouldn't step after EOF") + + def recv_frame(self, frame: Frame) -> None: + """ + Process an incoming frame. + + """ + if frame.opcode is OP_TEXT or frame.opcode is OP_BINARY: + if self.cur_size is not None: + raise ProtocolError("expected a continuation frame") + if not frame.fin: + self.cur_size = len(frame.data) + + elif frame.opcode is OP_CONT: + if self.cur_size is None: + raise ProtocolError("unexpected continuation frame") + if frame.fin: + self.cur_size = None + else: + self.cur_size += len(frame.data) + + elif frame.opcode is OP_PING: + # 5.5.2. Ping: "Upon receipt of a Ping frame, an endpoint MUST + # send a Pong frame in response" + pong_frame = Frame(OP_PONG, frame.data) + self.send_frame(pong_frame) + + elif frame.opcode is OP_PONG: + # 5.5.3 Pong: "A response to an unsolicited Pong frame is not + # expected." + pass + + elif frame.opcode is OP_CLOSE: + # 7.1.5. The WebSocket Connection Close Code + # 7.1.6. The WebSocket Connection Close Reason + self.close_rcvd = Close.parse(frame.data) + if self.state is CLOSING: + assert self.close_sent is not None + self.close_rcvd_then_sent = False + + if self.cur_size is not None: + raise ProtocolError("incomplete fragmented message") + + # 5.5.1 Close: "If an endpoint receives a Close frame and did + # not previously send a Close frame, the endpoint MUST send a + # Close frame in response. (When sending a Close frame in + # response, the endpoint typically echos the status code it + # received.)" + + if self.state is OPEN: + # Echo the original data instead of re-serializing it with + # Close.serialize() because that fails when the close frame + # is empty and Close.parse() synthesizes a 1005 close code. + # The rest is identical to send_close(). + self.send_frame(Frame(OP_CLOSE, frame.data)) + self.close_sent = self.close_rcvd + self.close_rcvd_then_sent = True + self.state = CLOSING + + # 7.1.2. Start the WebSocket Closing Handshake: "Once an + # endpoint has both sent and received a Close control frame, + # that endpoint SHOULD _Close the WebSocket Connection_" + + # A server closes the TCP connection immediately, while a client + # waits for the server to close the TCP connection. + if self.side is SERVER: + self.send_eof() + + # 1.4. Closing Handshake: "after receiving a control frame + # indicating the connection should be closed, a peer discards + # any further data received." + # RFC 6455 allows reading Ping and Pong frames after a Close frame. + # However, that doesn't seem useful; websockets doesn't support it. + self.parser = self.discard() + next(self.parser) # start coroutine + + else: + # This can't happen because Frame.parse() validates opcodes. + raise AssertionError(f"unexpected opcode: {frame.opcode:02x}") + + self.events.append(frame) + + # Private methods for sending events. + + def send_frame(self, frame: Frame) -> None: + if self.debug: + self.logger.debug("> %s", frame) + self.writes.append( + frame.serialize( + mask=self.side is CLIENT, + extensions=self.extensions, + ) + ) + + def send_eof(self) -> None: + assert not self.eof_sent + self.eof_sent = True + if self.debug: + self.logger.debug("> EOF") + self.writes.append(SEND_EOF) diff --git a/venv/lib/python3.10/site-packages/websockets/py.typed b/venv/lib/python3.10/site-packages/websockets/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/websockets/server.py b/venv/lib/python3.10/site-packages/websockets/server.py new file mode 100644 index 0000000000000000000000000000000000000000..1744412031b39c2dbcd5df20b7f886552aa6c1fe --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/server.py @@ -0,0 +1,587 @@ +from __future__ import annotations + +import base64 +import binascii +import email.utils +import http +import re +import warnings +from collections.abc import Generator, Sequence +from typing import Any, Callable, cast + +from .datastructures import Headers, MultipleValuesError +from .exceptions import ( + InvalidHandshake, + InvalidHeader, + InvalidHeaderValue, + InvalidMessage, + InvalidOrigin, + InvalidUpgrade, + NegotiationError, +) +from .extensions import Extension, ServerExtensionFactory +from .headers import ( + build_extension, + parse_connection, + parse_extension, + parse_subprotocol, + parse_upgrade, +) +from .http11 import Request, Response +from .imports import lazy_import +from .protocol import CONNECTING, OPEN, SERVER, Protocol, State +from .typing import ( + ConnectionOption, + ExtensionHeader, + LoggerLike, + Origin, + StatusLike, + Subprotocol, + UpgradeProtocol, +) +from .utils import accept_key + + +__all__ = ["ServerProtocol"] + + +class ServerProtocol(Protocol): + """ + Sans-I/O implementation of a WebSocket server connection. + + Args: + origins: Acceptable values of the ``Origin`` header. Values can be + :class:`str` to test for an exact match or regular expressions + compiled by :func:`re.compile` to test against a pattern. Include + :obj:`None` in the list if the lack of an origin is acceptable. + This is useful for defending against Cross-Site WebSocket + Hijacking attacks. + extensions: List of supported extensions, in order in which they + should be tried. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + select_subprotocol: Callback for selecting a subprotocol among + those supported by the client and the server. It has the same + signature as the :meth:`select_subprotocol` method, including a + :class:`ServerProtocol` instance as first argument. + state: Initial state of the WebSocket connection. + max_size: Maximum size of incoming messages in bytes; + :obj:`None` disables the limit. + logger: Logger for this connection; + defaults to ``logging.getLogger("websockets.server")``; + see the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__( + self, + *, + origins: Sequence[Origin | re.Pattern[str] | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + select_subprotocol: ( + Callable[ + [ServerProtocol, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None, + state: State = CONNECTING, + max_size: int | None = 2**20, + logger: LoggerLike | None = None, + ) -> None: + super().__init__( + side=SERVER, + state=state, + max_size=max_size, + logger=logger, + ) + self.origins = origins + self.available_extensions = extensions + self.available_subprotocols = subprotocols + if select_subprotocol is not None: + # Bind select_subprotocol then shadow self.select_subprotocol. + # Use setattr to work around https://github.com/python/mypy/issues/2427. + setattr( + self, + "select_subprotocol", + select_subprotocol.__get__(self, self.__class__), + ) + + def accept(self, request: Request) -> Response: + """ + Create a handshake response to accept the connection. + + If the handshake request is valid and the handshake successful, + :meth:`accept` returns an HTTP response with status code 101. + + Else, it returns an HTTP response with another status code. This rejects + the connection, like :meth:`reject` would. + + You must send the handshake response with :meth:`send_response`. + + You may modify the response before sending it, typically by adding HTTP + headers. + + Args: + request: WebSocket handshake request received from the client. + + Returns: + WebSocket handshake response or HTTP response to send to the client. + + """ + try: + ( + accept_header, + extensions_header, + protocol_header, + ) = self.process_request(request) + except InvalidOrigin as exc: + request._exception = exc + self.handshake_exc = exc + if self.debug: + self.logger.debug("! invalid origin", exc_info=True) + return self.reject( + http.HTTPStatus.FORBIDDEN, + f"Failed to open a WebSocket connection: {exc}.\n", + ) + except InvalidUpgrade as exc: + request._exception = exc + self.handshake_exc = exc + if self.debug: + self.logger.debug("! invalid upgrade", exc_info=True) + response = self.reject( + http.HTTPStatus.UPGRADE_REQUIRED, + ( + f"Failed to open a WebSocket connection: {exc}.\n" + f"\n" + f"You cannot access a WebSocket server directly " + f"with a browser. You need a WebSocket client.\n" + ), + ) + response.headers["Upgrade"] = "websocket" + return response + except InvalidHandshake as exc: + request._exception = exc + self.handshake_exc = exc + if self.debug: + self.logger.debug("! invalid handshake", exc_info=True) + exc_chain = cast(BaseException, exc) + exc_str = f"{exc_chain}" + while exc_chain.__cause__ is not None: + exc_chain = exc_chain.__cause__ + exc_str += f"; {exc_chain}" + return self.reject( + http.HTTPStatus.BAD_REQUEST, + f"Failed to open a WebSocket connection: {exc_str}.\n", + ) + except Exception as exc: + # Handle exceptions raised by user-provided select_subprotocol and + # unexpected errors. + request._exception = exc + self.handshake_exc = exc + self.logger.error("opening handshake failed", exc_info=True) + return self.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + headers = Headers() + headers["Date"] = email.utils.formatdate(usegmt=True) + headers["Upgrade"] = "websocket" + headers["Connection"] = "Upgrade" + headers["Sec-WebSocket-Accept"] = accept_header + if extensions_header is not None: + headers["Sec-WebSocket-Extensions"] = extensions_header + if protocol_header is not None: + headers["Sec-WebSocket-Protocol"] = protocol_header + return Response(101, "Switching Protocols", headers) + + def process_request( + self, + request: Request, + ) -> tuple[str, str | None, str | None]: + """ + Check a handshake request and negotiate extensions and subprotocol. + + This function doesn't verify that the request is an HTTP/1.1 or higher + GET request and doesn't check the ``Host`` header. These controls are + usually performed earlier in the HTTP request handling code. They're + the responsibility of the caller. + + Args: + request: WebSocket handshake request received from the client. + + Returns: + ``Sec-WebSocket-Accept``, ``Sec-WebSocket-Extensions``, and + ``Sec-WebSocket-Protocol`` headers for the handshake response. + + Raises: + InvalidHandshake: If the handshake request is invalid; + then the server must return 400 Bad Request error. + + """ + headers = request.headers + + connection: list[ConnectionOption] = sum( + [parse_connection(value) for value in headers.get_all("Connection")], [] + ) + if not any(value.lower() == "upgrade" for value in connection): + raise InvalidUpgrade( + "Connection", ", ".join(connection) if connection else None + ) + + upgrade: list[UpgradeProtocol] = sum( + [parse_upgrade(value) for value in headers.get_all("Upgrade")], [] + ) + # For compatibility with non-strict implementations, ignore case when + # checking the Upgrade header. The RFC always uses "websocket", except + # in section 11.2. (IANA registration) where it uses "WebSocket". + if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): + raise InvalidUpgrade("Upgrade", ", ".join(upgrade) if upgrade else None) + + try: + key = headers["Sec-WebSocket-Key"] + except KeyError: + raise InvalidHeader("Sec-WebSocket-Key") from None + except MultipleValuesError: + raise InvalidHeader("Sec-WebSocket-Key", "multiple values") from None + try: + raw_key = base64.b64decode(key.encode(), validate=True) + except binascii.Error as exc: + raise InvalidHeaderValue("Sec-WebSocket-Key", key) from exc + if len(raw_key) != 16: + raise InvalidHeaderValue("Sec-WebSocket-Key", key) + accept_header = accept_key(key) + + try: + version = headers["Sec-WebSocket-Version"] + except KeyError: + raise InvalidHeader("Sec-WebSocket-Version") from None + except MultipleValuesError: + raise InvalidHeader("Sec-WebSocket-Version", "multiple values") from None + if version != "13": + raise InvalidHeaderValue("Sec-WebSocket-Version", version) + + self.origin = self.process_origin(headers) + extensions_header, self.extensions = self.process_extensions(headers) + protocol_header = self.subprotocol = self.process_subprotocol(headers) + + return (accept_header, extensions_header, protocol_header) + + def process_origin(self, headers: Headers) -> Origin | None: + """ + Handle the Origin HTTP request header. + + Args: + headers: WebSocket handshake request headers. + + Returns: + origin, if it is acceptable. + + Raises: + InvalidHandshake: If the Origin header is invalid. + InvalidOrigin: If the origin isn't acceptable. + + """ + # "The user agent MUST NOT include more than one Origin header field" + # per https://datatracker.ietf.org/doc/html/rfc6454#section-7.3. + try: + origin = headers.get("Origin") + except MultipleValuesError: + raise InvalidHeader("Origin", "multiple values") from None + if origin is not None: + origin = cast(Origin, origin) + if self.origins is not None: + for origin_or_regex in self.origins: + if origin_or_regex == origin or ( + isinstance(origin_or_regex, re.Pattern) + and origin is not None + and origin_or_regex.fullmatch(origin) is not None + ): + break + else: + raise InvalidOrigin(origin) + return origin + + def process_extensions( + self, + headers: Headers, + ) -> tuple[str | None, list[Extension]]: + """ + Handle the Sec-WebSocket-Extensions HTTP request header. + + Accept or reject each extension proposed in the client request. + Negotiate parameters for accepted extensions. + + Per :rfc:`6455`, negotiation rules are defined by the specification of + each extension. + + To provide this level of flexibility, for each extension proposed by + the client, we check for a match with each extension available in the + server configuration. If no match is found, the extension is ignored. + + If several variants of the same extension are proposed by the client, + it may be accepted several times, which won't make sense in general. + Extensions must implement their own requirements. For this purpose, + the list of previously accepted extensions is provided. + + This process doesn't allow the server to reorder extensions. It can + only select a subset of the extensions proposed by the client. + + Other requirements, for example related to mandatory extensions or the + order of extensions, may be implemented by overriding this method. + + Args: + headers: WebSocket handshake request headers. + + Returns: + ``Sec-WebSocket-Extensions`` HTTP response header and list of + accepted extensions. + + Raises: + InvalidHandshake: If the Sec-WebSocket-Extensions header is invalid. + + """ + response_header_value: str | None = None + + extension_headers: list[ExtensionHeader] = [] + accepted_extensions: list[Extension] = [] + + header_values = headers.get_all("Sec-WebSocket-Extensions") + + if header_values and self.available_extensions: + parsed_header_values: list[ExtensionHeader] = sum( + [parse_extension(header_value) for header_value in header_values], [] + ) + + for name, request_params in parsed_header_values: + for ext_factory in self.available_extensions: + # Skip non-matching extensions based on their name. + if ext_factory.name != name: + continue + + # Skip non-matching extensions based on their params. + try: + response_params, extension = ext_factory.process_request_params( + request_params, accepted_extensions + ) + except NegotiationError: + continue + + # Add matching extension to the final list. + extension_headers.append((name, response_params)) + accepted_extensions.append(extension) + + # Break out of the loop once we have a match. + break + + # If we didn't break from the loop, no extension in our list + # matched what the client sent. The extension is declined. + + # Serialize extension header. + if extension_headers: + response_header_value = build_extension(extension_headers) + + return response_header_value, accepted_extensions + + def process_subprotocol(self, headers: Headers) -> Subprotocol | None: + """ + Handle the Sec-WebSocket-Protocol HTTP request header. + + Args: + headers: WebSocket handshake request headers. + + Returns: + Subprotocol, if one was selected; this is also the value of the + ``Sec-WebSocket-Protocol`` response header. + + Raises: + InvalidHandshake: If the Sec-WebSocket-Subprotocol header is invalid. + + """ + subprotocols: Sequence[Subprotocol] = sum( + [ + parse_subprotocol(header_value) + for header_value in headers.get_all("Sec-WebSocket-Protocol") + ], + [], + ) + return self.select_subprotocol(subprotocols) + + def select_subprotocol( + self, + subprotocols: Sequence[Subprotocol], + ) -> Subprotocol | None: + """ + Pick a subprotocol among those offered by the client. + + If several subprotocols are supported by both the client and the server, + pick the first one in the list declared the server. + + If the server doesn't support any subprotocols, continue without a + subprotocol, regardless of what the client offers. + + If the server supports at least one subprotocol and the client doesn't + offer any, abort the handshake with an HTTP 400 error. + + You provide a ``select_subprotocol`` argument to :class:`ServerProtocol` + to override this logic. For example, you could accept the connection + even if client doesn't offer a subprotocol, rather than reject it. + + Here's how to negotiate the ``chat`` subprotocol if the client supports + it and continue without a subprotocol otherwise:: + + def select_subprotocol(protocol, subprotocols): + if "chat" in subprotocols: + return "chat" + + Args: + subprotocols: List of subprotocols offered by the client. + + Returns: + Selected subprotocol, if a common subprotocol was found. + + :obj:`None` to continue without a subprotocol. + + Raises: + NegotiationError: Custom implementations may raise this exception + to abort the handshake with an HTTP 400 error. + + """ + # Server doesn't offer any subprotocols. + if not self.available_subprotocols: # None or empty list + return None + + # Server offers at least one subprotocol but client doesn't offer any. + if not subprotocols: + raise NegotiationError("missing subprotocol") + + # Server and client both offer subprotocols. Look for a shared one. + proposed_subprotocols = set(subprotocols) + for subprotocol in self.available_subprotocols: + if subprotocol in proposed_subprotocols: + return subprotocol + + # No common subprotocol was found. + raise NegotiationError( + "invalid subprotocol; expected one of " + + ", ".join(self.available_subprotocols) + ) + + def reject(self, status: StatusLike, text: str) -> Response: + """ + Create a handshake response to reject the connection. + + A short plain text response is the best fallback when failing to + establish a WebSocket connection. + + You must send the handshake response with :meth:`send_response`. + + You may modify the response before sending it, for example by changing + HTTP headers. + + Args: + status: HTTP status code. + text: HTTP response body; it will be encoded to UTF-8. + + Returns: + HTTP response to send to the client. + + """ + # If status is an int instead of an HTTPStatus, fix it automatically. + status = http.HTTPStatus(status) + body = text.encode() + headers = Headers( + [ + ("Date", email.utils.formatdate(usegmt=True)), + ("Connection", "close"), + ("Content-Length", str(len(body))), + ("Content-Type", "text/plain; charset=utf-8"), + ] + ) + return Response(status.value, status.phrase, headers, body) + + def send_response(self, response: Response) -> None: + """ + Send a handshake response to the client. + + Args: + response: WebSocket handshake response event to send. + + """ + if self.debug: + code, phrase = response.status_code, response.reason_phrase + self.logger.debug("> HTTP/1.1 %d %s", code, phrase) + for key, value in response.headers.raw_items(): + self.logger.debug("> %s: %s", key, value) + if response.body: + self.logger.debug("> [body] (%d bytes)", len(response.body)) + + self.writes.append(response.serialize()) + + if response.status_code == 101: + assert self.state is CONNECTING + self.state = OPEN + self.logger.info("connection open") + + else: + self.logger.info( + "connection rejected (%d %s)", + response.status_code, + response.reason_phrase, + ) + + self.send_eof() + self.parser = self.discard() + next(self.parser) # start coroutine + + def parse(self) -> Generator[None]: + if self.state is CONNECTING: + try: + request = yield from Request.parse( + self.reader.read_line, + ) + except Exception as exc: + self.handshake_exc = InvalidMessage( + "did not receive a valid HTTP request" + ) + self.handshake_exc.__cause__ = exc + self.send_eof() + self.parser = self.discard() + next(self.parser) # start coroutine + yield + + if self.debug: + self.logger.debug("< GET %s HTTP/1.1", request.path) + for key, value in request.headers.raw_items(): + self.logger.debug("< %s: %s", key, value) + + self.events.append(request) + + yield from super().parse() + + +class ServerConnection(ServerProtocol): + def __init__(self, *args: Any, **kwargs: Any) -> None: + warnings.warn( # deprecated in 11.0 - 2023-04-02 + "ServerConnection was renamed to ServerProtocol", + DeprecationWarning, + ) + super().__init__(*args, **kwargs) + + +lazy_import( + globals(), + deprecated_aliases={ + # deprecated in 14.0 - 2024-11-09 + "WebSocketServer": ".legacy.server", + "WebSocketServerProtocol": ".legacy.server", + "broadcast": ".legacy.server", + "serve": ".legacy.server", + "unix_serve": ".legacy.server", + }, +) diff --git a/venv/lib/python3.10/site-packages/websockets/speedups.c b/venv/lib/python3.10/site-packages/websockets/speedups.c new file mode 100644 index 0000000000000000000000000000000000000000..cb10dedb83fd160b340cdb72f2d11ba94424a807 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/speedups.c @@ -0,0 +1,222 @@ +/* C implementation of performance sensitive functions. */ + +#define PY_SSIZE_T_CLEAN +#include +#include /* uint8_t, uint32_t, uint64_t */ + +#if __ARM_NEON +#include +#elif __SSE2__ +#include +#endif + +static const Py_ssize_t MASK_LEN = 4; + +/* Similar to PyBytes_AsStringAndSize, but accepts more types */ + +static int +_PyBytesLike_AsStringAndSize(PyObject *obj, PyObject **tmp, char **buffer, Py_ssize_t *length) +{ + // This supports bytes, bytearrays, and memoryview objects, + // which are common data structures for handling byte streams. + // If *tmp isn't NULL, the caller gets a new reference. + if (PyBytes_Check(obj)) + { + *tmp = NULL; + *buffer = PyBytes_AS_STRING(obj); + *length = PyBytes_GET_SIZE(obj); + } + else if (PyByteArray_Check(obj)) + { + *tmp = NULL; + *buffer = PyByteArray_AS_STRING(obj); + *length = PyByteArray_GET_SIZE(obj); + } + else if (PyMemoryView_Check(obj)) + { + *tmp = PyMemoryView_GetContiguous(obj, PyBUF_READ, 'C'); + if (*tmp == NULL) + { + return -1; + } + Py_buffer *mv_buf; + mv_buf = PyMemoryView_GET_BUFFER(*tmp); + *buffer = mv_buf->buf; + *length = mv_buf->len; + } + else + { + PyErr_Format( + PyExc_TypeError, + "expected a bytes-like object, %.200s found", + Py_TYPE(obj)->tp_name); + return -1; + } + + return 0; +} + +/* C implementation of websockets.utils.apply_mask */ + +static PyObject * +apply_mask(PyObject *self, PyObject *args, PyObject *kwds) +{ + + // In order to support various bytes-like types, accept any Python object. + + static char *kwlist[] = {"data", "mask", NULL}; + PyObject *input_obj; + PyObject *mask_obj; + + // A pointer to a char * + length will be extracted from the data and mask + // arguments, possibly via a Py_buffer. + + PyObject *input_tmp = NULL; + char *input; + Py_ssize_t input_len; + PyObject *mask_tmp = NULL; + char *mask; + Py_ssize_t mask_len; + + // Initialize a PyBytesObject then get a pointer to the underlying char * + // in order to avoid an extra memory copy in PyBytes_FromStringAndSize. + + PyObject *result = NULL; + char *output; + + // Other variables. + + Py_ssize_t i = 0; + + // Parse inputs. + + if (!PyArg_ParseTupleAndKeywords( + args, kwds, "OO", kwlist, &input_obj, &mask_obj)) + { + goto exit; + } + + if (_PyBytesLike_AsStringAndSize(input_obj, &input_tmp, &input, &input_len) == -1) + { + goto exit; + } + + if (_PyBytesLike_AsStringAndSize(mask_obj, &mask_tmp, &mask, &mask_len) == -1) + { + goto exit; + } + + if (mask_len != MASK_LEN) + { + PyErr_SetString(PyExc_ValueError, "mask must contain 4 bytes"); + goto exit; + } + + // Create output. + + result = PyBytes_FromStringAndSize(NULL, input_len); + if (result == NULL) + { + goto exit; + } + + // Since we just created result, we don't need error checks. + output = PyBytes_AS_STRING(result); + + // Perform the masking operation. + + // Apparently GCC cannot figure out the following optimizations by itself. + + // We need a new scope for MSVC 2010 (non C99 friendly) + { +#if __ARM_NEON + + // With NEON support, XOR by blocks of 16 bytes = 128 bits. + + Py_ssize_t input_len_128 = input_len & ~15; + uint8x16_t mask_128 = vreinterpretq_u8_u32(vdupq_n_u32(*(uint32_t *)mask)); + + for (; i < input_len_128; i += 16) + { + uint8x16_t in_128 = vld1q_u8((uint8_t *)(input + i)); + uint8x16_t out_128 = veorq_u8(in_128, mask_128); + vst1q_u8((uint8_t *)(output + i), out_128); + } + +#elif __SSE2__ + + // With SSE2 support, XOR by blocks of 16 bytes = 128 bits. + + // Since we cannot control the 16-bytes alignment of input and output + // buffers, we rely on loadu/storeu rather than load/store. + + Py_ssize_t input_len_128 = input_len & ~15; + __m128i mask_128 = _mm_set1_epi32(*(uint32_t *)mask); + + for (; i < input_len_128; i += 16) + { + __m128i in_128 = _mm_loadu_si128((__m128i *)(input + i)); + __m128i out_128 = _mm_xor_si128(in_128, mask_128); + _mm_storeu_si128((__m128i *)(output + i), out_128); + } + +#else + + // Without SSE2 support, XOR by blocks of 8 bytes = 64 bits. + + // We assume the memory allocator aligns everything on 8 bytes boundaries. + + Py_ssize_t input_len_64 = input_len & ~7; + uint32_t mask_32 = *(uint32_t *)mask; + uint64_t mask_64 = ((uint64_t)mask_32 << 32) | (uint64_t)mask_32; + + for (; i < input_len_64; i += 8) + { + *(uint64_t *)(output + i) = *(uint64_t *)(input + i) ^ mask_64; + } + +#endif + } + + // XOR the remainder of the input byte by byte. + + for (; i < input_len; i++) + { + output[i] = input[i] ^ mask[i & (MASK_LEN - 1)]; + } + +exit: + Py_XDECREF(input_tmp); + Py_XDECREF(mask_tmp); + return result; + +} + +static PyMethodDef speedups_methods[] = { + { + "apply_mask", + (PyCFunction)apply_mask, + METH_VARARGS | METH_KEYWORDS, + "Apply masking to the data of a WebSocket message.", + }, + {NULL, NULL, 0, NULL}, /* Sentinel */ +}; + +static struct PyModuleDef speedups_module = { + PyModuleDef_HEAD_INIT, + "websocket.speedups", /* m_name */ + "C implementation of performance sensitive functions.", + /* m_doc */ + -1, /* m_size */ + speedups_methods, /* m_methods */ + NULL, + NULL, + NULL, + NULL +}; + +PyMODINIT_FUNC +PyInit_speedups(void) +{ + return PyModule_Create(&speedups_module); +} diff --git a/venv/lib/python3.10/site-packages/websockets/speedups.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/websockets/speedups.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b685359f67c0ebb5d44154281da8135ea3384d52 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/speedups.cpython-310-x86_64-linux-gnu.so differ diff --git a/venv/lib/python3.10/site-packages/websockets/speedups.pyi b/venv/lib/python3.10/site-packages/websockets/speedups.pyi new file mode 100644 index 0000000000000000000000000000000000000000..821438a064e6ad32154eb6536c975f70d4c35d05 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/speedups.pyi @@ -0,0 +1 @@ +def apply_mask(data: bytes, mask: bytes) -> bytes: ... diff --git a/venv/lib/python3.10/site-packages/websockets/streams.py b/venv/lib/python3.10/site-packages/websockets/streams.py new file mode 100644 index 0000000000000000000000000000000000000000..f52e6193aa979564dab68058835ff0ca86b9ca38 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/streams.py @@ -0,0 +1,151 @@ +from __future__ import annotations + +from collections.abc import Generator + + +class StreamReader: + """ + Generator-based stream reader. + + This class doesn't support concurrent calls to :meth:`read_line`, + :meth:`read_exact`, or :meth:`read_to_eof`. Make sure calls are + serialized. + + """ + + def __init__(self) -> None: + self.buffer = bytearray() + self.eof = False + + def read_line(self, m: int) -> Generator[None, None, bytes]: + """ + Read a LF-terminated line from the stream. + + This is a generator-based coroutine. + + The return value includes the LF character. + + Args: + m: Maximum number bytes to read; this is a security limit. + + Raises: + EOFError: If the stream ends without a LF. + RuntimeError: If the stream ends in more than ``m`` bytes. + + """ + n = 0 # number of bytes to read + p = 0 # number of bytes without a newline + while True: + n = self.buffer.find(b"\n", p) + 1 + if n > 0: + break + p = len(self.buffer) + if p > m: + raise RuntimeError(f"read {p} bytes, expected no more than {m} bytes") + if self.eof: + raise EOFError(f"stream ends after {p} bytes, before end of line") + yield + if n > m: + raise RuntimeError(f"read {n} bytes, expected no more than {m} bytes") + r = self.buffer[:n] + del self.buffer[:n] + return r + + def read_exact(self, n: int) -> Generator[None, None, bytes]: + """ + Read a given number of bytes from the stream. + + This is a generator-based coroutine. + + Args: + n: How many bytes to read. + + Raises: + EOFError: If the stream ends in less than ``n`` bytes. + + """ + assert n >= 0 + while len(self.buffer) < n: + if self.eof: + p = len(self.buffer) + raise EOFError(f"stream ends after {p} bytes, expected {n} bytes") + yield + r = self.buffer[:n] + del self.buffer[:n] + return r + + def read_to_eof(self, m: int) -> Generator[None, None, bytes]: + """ + Read all bytes from the stream. + + This is a generator-based coroutine. + + Args: + m: Maximum number bytes to read; this is a security limit. + + Raises: + RuntimeError: If the stream ends in more than ``m`` bytes. + + """ + while not self.eof: + p = len(self.buffer) + if p > m: + raise RuntimeError(f"read {p} bytes, expected no more than {m} bytes") + yield + r = self.buffer[:] + del self.buffer[:] + return r + + def at_eof(self) -> Generator[None, None, bool]: + """ + Tell whether the stream has ended and all data was read. + + This is a generator-based coroutine. + + """ + while True: + if self.buffer: + return False + if self.eof: + return True + # When all data was read but the stream hasn't ended, we can't + # tell if until either feed_data() or feed_eof() is called. + yield + + def feed_data(self, data: bytes) -> None: + """ + Write data to the stream. + + :meth:`feed_data` cannot be called after :meth:`feed_eof`. + + Args: + data: Data to write. + + Raises: + EOFError: If the stream has ended. + + """ + if self.eof: + raise EOFError("stream ended") + self.buffer += data + + def feed_eof(self) -> None: + """ + End the stream. + + :meth:`feed_eof` cannot be called more than once. + + Raises: + EOFError: If the stream has ended. + + """ + if self.eof: + raise EOFError("stream ended") + self.eof = True + + def discard(self) -> None: + """ + Discard all buffered data, but don't end the stream. + + """ + del self.buffer[:] diff --git a/venv/lib/python3.10/site-packages/websockets/sync/__init__.py b/venv/lib/python3.10/site-packages/websockets/sync/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..682553d6d0b5141827e021f9524ef019af134fb1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/client.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/client.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..148085a58ca72183b7b1388394b5cd53c77c2265 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/client.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/connection.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/connection.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d052ec29196742833b629aa2bc4d0b481fe41d6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/connection.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/messages.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/messages.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1b3e07c2e6659406e2587dafbaa5f1c37b400ce Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/messages.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/router.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/router.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6df483b8763f5e05bbb64df837d8121bf5241a8e Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/router.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/server.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/server.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5242c0d394f8887d81997018c34b1c65d9ef9a1c Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/server.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41b9bcf02914cee2e61bea7ea3f74d21b39067c7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/websockets/sync/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/websockets/sync/client.py b/venv/lib/python3.10/site-packages/websockets/sync/client.py new file mode 100644 index 0000000000000000000000000000000000000000..58cb84710eb08804f1b55f92b6e539cf98ed7b75 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/sync/client.py @@ -0,0 +1,648 @@ +from __future__ import annotations + +import socket +import ssl as ssl_module +import threading +import warnings +from collections.abc import Sequence +from typing import Any, Callable, Literal, TypeVar, cast + +from ..client import ClientProtocol +from ..datastructures import Headers, HeadersLike +from ..exceptions import InvalidProxyMessage, InvalidProxyStatus, ProxyError +from ..extensions.base import ClientExtensionFactory +from ..extensions.permessage_deflate import enable_client_permessage_deflate +from ..headers import build_authorization_basic, build_host, validate_subprotocols +from ..http11 import USER_AGENT, Response +from ..protocol import CONNECTING, Event +from ..streams import StreamReader +from ..typing import LoggerLike, Origin, Subprotocol +from ..uri import Proxy, WebSocketURI, get_proxy, parse_proxy, parse_uri +from .connection import Connection +from .utils import Deadline + + +__all__ = ["connect", "unix_connect", "ClientConnection"] + + +class ClientConnection(Connection): + """ + :mod:`threading` implementation of a WebSocket client connection. + + :class:`ClientConnection` provides :meth:`recv` and :meth:`send` methods for + receiving and sending messages. + + It supports iteration to receive messages:: + + for message in websocket: + process(message) + + The iterator exits normally when the connection is closed with close code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and + ``max_queue`` arguments have the same meaning as in :func:`connect`. + + Args: + socket: Socket connected to a WebSocket server. + protocol: Sans-I/O connection. + + """ + + def __init__( + self, + socket: socket.socket, + protocol: ClientProtocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + ) -> None: + self.protocol: ClientProtocol + self.response_rcvd = threading.Event() + super().__init__( + socket, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + + def handshake( + self, + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + timeout: float | None = None, + ) -> None: + """ + Perform the opening handshake. + + """ + with self.send_context(expected_state=CONNECTING): + self.request = self.protocol.connect() + if additional_headers is not None: + self.request.headers.update(additional_headers) + if user_agent_header is not None: + self.request.headers.setdefault("User-Agent", user_agent_header) + self.protocol.send_request(self.request) + + if not self.response_rcvd.wait(timeout): + raise TimeoutError("timed out while waiting for handshake response") + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a response, when the response cannot be parsed, or when the + # response fails the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake response. + if self.response is None: + assert isinstance(event, Response) + self.response = event + self.response_rcvd.set() + # Later events - frames. + else: + super().process_event(event) + + def recv_events(self) -> None: + """ + Read incoming data from the socket and process events. + + """ + try: + super().recv_events() + finally: + # If the connection is closed during the handshake, unblock it. + self.response_rcvd.set() + + +def connect( + uri: str, + *, + # TCP/TLS + sock: socket.socket | None = None, + ssl: ssl_module.SSLContext | None = None, + server_hostname: str | None = None, + # WebSocket + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + compression: str | None = "deflate", + # HTTP + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + proxy: str | Literal[True] | None = True, + proxy_ssl: ssl_module.SSLContext | None = None, + proxy_server_hostname: str | None = None, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ClientConnection] | None = None, + **kwargs: Any, +) -> ClientConnection: + """ + Connect to the WebSocket server at ``uri``. + + This function returns a :class:`ClientConnection` instance, which you can + use to send and receive messages. + + :func:`connect` may be used as a context manager:: + + from websockets.sync.client import connect + + with connect(...) as websocket: + ... + + The connection is closed automatically when exiting the context. + + Args: + uri: URI of the WebSocket server. + sock: Preexisting TCP socket. ``sock`` overrides the host and port + from ``uri``. You may call :func:`socket.create_connection` to + create a suitable TCP socket. + ssl: Configuration for enabling TLS on the connection. + server_hostname: Host name for the TLS handshake. ``server_hostname`` + overrides the host name from ``uri``. + origin: Value of the ``Origin`` header, for servers that require it. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + additional_headers (HeadersLike | None): Arbitrary HTTP headers to add + to the handshake request. + user_agent_header: Value of the ``User-Agent`` request header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + proxy: If a proxy is configured, it is used by default. Set ``proxy`` + to :obj:`None` to disable the proxy or to the address of a proxy + to override the system configuration. See the :doc:`proxy docs + <../../topics/proxies>` for details. + proxy_ssl: Configuration for enabling TLS on the proxy connection. + proxy_server_hostname: Host name for the TLS handshake with the proxy. + ``proxy_server_hostname`` overrides the host name from ``proxy``. + open_timeout: Timeout for opening the connection in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing the connection in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + logger: Logger for this client. + It defaults to ``logging.getLogger("websockets.client")``. + See the :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ClientConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to :func:`~socket.create_connection`. + + Raises: + InvalidURI: If ``uri`` isn't a valid WebSocket URI. + OSError: If the TCP connection fails. + InvalidHandshake: If the opening handshake fails. + TimeoutError: If the opening handshake times out. + + """ + + # Process parameters + + # Backwards compatibility: ssl used to be called ssl_context. + if ssl is None and "ssl_context" in kwargs: + ssl = kwargs.pop("ssl_context") + warnings.warn( # deprecated in 13.0 - 2024-08-20 + "ssl_context was renamed to ssl", + DeprecationWarning, + ) + + ws_uri = parse_uri(uri) + if not ws_uri.secure and ssl is not None: + raise ValueError("ssl argument is incompatible with a ws:// URI") + + # Private APIs for unix_connect() + unix: bool = kwargs.pop("unix", False) + path: str | None = kwargs.pop("path", None) + + if unix: + if path is None and sock is None: + raise ValueError("missing path argument") + elif path is not None and sock is not None: + raise ValueError("path and sock arguments are incompatible") + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_client_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if unix: + proxy = None + if sock is not None: + proxy = None + if proxy is True: + proxy = get_proxy(ws_uri) + + # Calculate timeouts on the TCP, TLS, and WebSocket handshakes. + # The TCP and TLS timeouts must be set on the socket, then removed + # to avoid conflicting with the WebSocket timeout in handshake(). + deadline = Deadline(open_timeout) + + if create_connection is None: + create_connection = ClientConnection + + try: + # Connect socket + + if sock is None: + if unix: + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.settimeout(deadline.timeout()) + assert path is not None # mypy cannot figure this out + sock.connect(path) + elif proxy is not None: + proxy_parsed = parse_proxy(proxy) + if proxy_parsed.scheme[:5] == "socks": + # Connect to the server through the proxy. + sock = connect_socks_proxy( + proxy_parsed, + ws_uri, + deadline, + # websockets is consistent with the socket module while + # python_socks is consistent across implementations. + local_addr=kwargs.pop("source_address", None), + ) + elif proxy_parsed.scheme[:4] == "http": + # Validate the proxy_ssl argument. + if proxy_parsed.scheme != "https" and proxy_ssl is not None: + raise ValueError( + "proxy_ssl argument is incompatible with an http:// proxy" + ) + # Connect to the server through the proxy. + sock = connect_http_proxy( + proxy_parsed, + ws_uri, + deadline, + user_agent_header=user_agent_header, + ssl=proxy_ssl, + server_hostname=proxy_server_hostname, + **kwargs, + ) + else: + raise AssertionError("unsupported proxy") + else: + kwargs.setdefault("timeout", deadline.timeout()) + sock = socket.create_connection( + (ws_uri.host, ws_uri.port), + **kwargs, + ) + sock.settimeout(None) + + # Disable Nagle algorithm + + if not unix: + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) + + # Initialize TLS wrapper and perform TLS handshake + + if ws_uri.secure: + if ssl is None: + ssl = ssl_module.create_default_context() + if server_hostname is None: + server_hostname = ws_uri.host + sock.settimeout(deadline.timeout()) + if proxy_ssl is None: + sock = ssl.wrap_socket(sock, server_hostname=server_hostname) + else: + sock_2 = SSLSSLSocket(sock, ssl, server_hostname=server_hostname) + # Let's pretend that sock is a socket, even though it isn't. + sock = cast(socket.socket, sock_2) + sock.settimeout(None) + + # Initialize WebSocket protocol + + protocol = ClientProtocol( + ws_uri, + origin=origin, + extensions=extensions, + subprotocols=subprotocols, + max_size=max_size, + logger=logger, + ) + + # Initialize WebSocket connection + + connection = create_connection( + sock, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + except Exception: + if sock is not None: + sock.close() + raise + + try: + connection.handshake( + additional_headers, + user_agent_header, + deadline.timeout(), + ) + except Exception: + connection.close_socket() + connection.recv_events_thread.join() + raise + + connection.start_keepalive() + return connection + + +def unix_connect( + path: str | None = None, + uri: str | None = None, + **kwargs: Any, +) -> ClientConnection: + """ + Connect to a WebSocket server listening on a Unix socket. + + This function accepts the same keyword arguments as :func:`connect`. + + It's only available on Unix. + + It's mainly useful for debugging servers listening on Unix sockets. + + Args: + path: File system path to the Unix socket. + uri: URI of the WebSocket server. ``uri`` defaults to + ``ws://localhost/`` or, when a ``ssl`` is provided, to + ``wss://localhost/``. + + """ + if uri is None: + # Backwards compatibility: ssl used to be called ssl_context. + if kwargs.get("ssl") is None and kwargs.get("ssl_context") is None: + uri = "ws://localhost/" + else: + uri = "wss://localhost/" + return connect(uri=uri, unix=True, path=path, **kwargs) + + +try: + from python_socks import ProxyType + from python_socks.sync import Proxy as SocksProxy + + SOCKS_PROXY_TYPES = { + "socks5h": ProxyType.SOCKS5, + "socks5": ProxyType.SOCKS5, + "socks4a": ProxyType.SOCKS4, + "socks4": ProxyType.SOCKS4, + } + + SOCKS_PROXY_RDNS = { + "socks5h": True, + "socks5": False, + "socks4a": True, + "socks4": False, + } + + def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + deadline: Deadline, + **kwargs: Any, + ) -> socket.socket: + """Connect via a SOCKS proxy and return the socket.""" + socks_proxy = SocksProxy( + SOCKS_PROXY_TYPES[proxy.scheme], + proxy.host, + proxy.port, + proxy.username, + proxy.password, + SOCKS_PROXY_RDNS[proxy.scheme], + ) + kwargs.setdefault("timeout", deadline.timeout()) + # connect() is documented to raise OSError and TimeoutError. + # Wrap other exceptions in ProxyError, a subclass of InvalidHandshake. + try: + return socks_proxy.connect(ws_uri.host, ws_uri.port, **kwargs) + except (OSError, TimeoutError, socket.timeout): + raise + except Exception as exc: + raise ProxyError("failed to connect to SOCKS proxy") from exc + +except ImportError: + + def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + deadline: Deadline, + **kwargs: Any, + ) -> socket.socket: + raise ImportError("python-socks is required to use a SOCKS proxy") + + +def prepare_connect_request( + proxy: Proxy, + ws_uri: WebSocketURI, + user_agent_header: str | None = None, +) -> bytes: + host = build_host(ws_uri.host, ws_uri.port, ws_uri.secure, always_include_port=True) + headers = Headers() + headers["Host"] = build_host(ws_uri.host, ws_uri.port, ws_uri.secure) + if user_agent_header is not None: + headers["User-Agent"] = user_agent_header + if proxy.username is not None: + assert proxy.password is not None # enforced by parse_proxy() + headers["Proxy-Authorization"] = build_authorization_basic( + proxy.username, proxy.password + ) + # We cannot use the Request class because it supports only GET requests. + return f"CONNECT {host} HTTP/1.1\r\n".encode() + headers.serialize() + + +def read_connect_response(sock: socket.socket, deadline: Deadline) -> Response: + reader = StreamReader() + parser = Response.parse( + reader.read_line, + reader.read_exact, + reader.read_to_eof, + include_body=False, + ) + try: + while True: + sock.settimeout(deadline.timeout()) + data = sock.recv(4096) + if data: + reader.feed_data(data) + else: + reader.feed_eof() + next(parser) + except StopIteration as exc: + assert isinstance(exc.value, Response) # help mypy + response = exc.value + if 200 <= response.status_code < 300: + return response + else: + raise InvalidProxyStatus(response) + except socket.timeout: + raise TimeoutError("timed out while connecting to HTTP proxy") + except Exception as exc: + raise InvalidProxyMessage( + "did not receive a valid HTTP response from proxy" + ) from exc + finally: + sock.settimeout(None) + + +def connect_http_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + deadline: Deadline, + *, + user_agent_header: str | None = None, + ssl: ssl_module.SSLContext | None = None, + server_hostname: str | None = None, + **kwargs: Any, +) -> socket.socket: + # Connect socket + + kwargs.setdefault("timeout", deadline.timeout()) + sock = socket.create_connection((proxy.host, proxy.port), **kwargs) + + # Initialize TLS wrapper and perform TLS handshake + + if proxy.scheme == "https": + if ssl is None: + ssl = ssl_module.create_default_context() + if server_hostname is None: + server_hostname = proxy.host + sock.settimeout(deadline.timeout()) + sock = ssl.wrap_socket(sock, server_hostname=server_hostname) + sock.settimeout(None) + + # Send CONNECT request to the proxy and read response. + + sock.sendall(prepare_connect_request(proxy, ws_uri, user_agent_header)) + try: + read_connect_response(sock, deadline) + except Exception: + sock.close() + raise + + return sock + + +T = TypeVar("T") +F = TypeVar("F", bound=Callable[..., T]) + + +class SSLSSLSocket: + """ + Socket-like object providing TLS-in-TLS. + + Only methods that are used by websockets are implemented. + + """ + + recv_bufsize = 65536 + + def __init__( + self, + sock: socket.socket, + ssl_context: ssl_module.SSLContext, + server_hostname: str | None = None, + ) -> None: + self.incoming = ssl_module.MemoryBIO() + self.outgoing = ssl_module.MemoryBIO() + self.ssl_socket = sock + self.ssl_object = ssl_context.wrap_bio( + self.incoming, + self.outgoing, + server_hostname=server_hostname, + ) + self.run_io(self.ssl_object.do_handshake) + + def run_io(self, func: Callable[..., T], *args: Any) -> T: + while True: + want_read = False + want_write = False + try: + result = func(*args) + except ssl_module.SSLWantReadError: + want_read = True + except ssl_module.SSLWantWriteError: # pragma: no cover + want_write = True + + # Write outgoing data in all cases. + data = self.outgoing.read() + if data: + self.ssl_socket.sendall(data) + + # Read incoming data and retry on SSLWantReadError. + if want_read: + data = self.ssl_socket.recv(self.recv_bufsize) + if data: + self.incoming.write(data) + else: + self.incoming.write_eof() + continue + # Retry after writing outgoing data on SSLWantWriteError. + if want_write: # pragma: no cover + continue + # Return result if no error happened. + return result + + def recv(self, buflen: int) -> bytes: + try: + return self.run_io(self.ssl_object.read, buflen) + except ssl_module.SSLEOFError: + return b"" # always ignore ragged EOFs + + def send(self, data: bytes) -> int: + return self.run_io(self.ssl_object.write, data) + + def sendall(self, data: bytes) -> None: + # adapted from ssl_module.SSLSocket.sendall() + count = 0 + with memoryview(data) as view, view.cast("B") as byte_view: + amount = len(byte_view) + while count < amount: + count += self.send(byte_view[count:]) + + # recv_into(), recvfrom(), recvfrom_into(), sendto(), unwrap(), and the + # flags argument aren't implemented because websockets doesn't need them. + + def __getattr__(self, name: str) -> Any: + return getattr(self.ssl_socket, name) diff --git a/venv/lib/python3.10/site-packages/websockets/sync/connection.py b/venv/lib/python3.10/site-packages/websockets/sync/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..8b9e062573e48563c6c03cf79058e91f78174d76 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/sync/connection.py @@ -0,0 +1,1072 @@ +from __future__ import annotations + +import contextlib +import logging +import random +import socket +import struct +import threading +import time +import uuid +from collections.abc import Iterable, Iterator, Mapping +from types import TracebackType +from typing import Any, Literal, overload + +from ..exceptions import ( + ConcurrencyError, + ConnectionClosed, + ConnectionClosedOK, + ProtocolError, +) +from ..frames import DATA_OPCODES, BytesLike, CloseCode, Frame, Opcode +from ..http11 import Request, Response +from ..protocol import CLOSED, OPEN, Event, Protocol, State +from ..typing import Data, LoggerLike, Subprotocol +from .messages import Assembler +from .utils import Deadline + + +__all__ = ["Connection"] + + +class Connection: + """ + :mod:`threading` implementation of a WebSocket connection. + + :class:`Connection` provides APIs shared between WebSocket servers and + clients. + + You shouldn't use it directly. Instead, use + :class:`~websockets.sync.client.ClientConnection` or + :class:`~websockets.sync.server.ServerConnection`. + + """ + + recv_bufsize = 65536 + + def __init__( + self, + socket: socket.socket, + protocol: Protocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + ) -> None: + self.socket = socket + self.protocol = protocol + self.ping_interval = ping_interval + self.ping_timeout = ping_timeout + self.close_timeout = close_timeout + if isinstance(max_queue, int) or max_queue is None: + max_queue = (max_queue, None) + self.max_queue = max_queue + + # Inject reference to this instance in the protocol's logger. + self.protocol.logger = logging.LoggerAdapter( + self.protocol.logger, + {"websocket": self}, + ) + + # Copy attributes from the protocol for convenience. + self.id: uuid.UUID = self.protocol.id + """Unique identifier of the connection. Useful in logs.""" + self.logger: LoggerLike = self.protocol.logger + """Logger for this connection.""" + self.debug = self.protocol.debug + + # HTTP handshake request and response. + self.request: Request | None = None + """Opening handshake request.""" + self.response: Response | None = None + """Opening handshake response.""" + + # Mutex serializing interactions with the protocol. + self.protocol_mutex = threading.Lock() + + # Lock stopping reads when the assembler buffer is full. + self.recv_flow_control = threading.Lock() + + # Assembler turning frames into messages and serializing reads. + self.recv_messages = Assembler( + *self.max_queue, + pause=self.recv_flow_control.acquire, + resume=self.recv_flow_control.release, + ) + + # Deadline for the closing handshake. + self.close_deadline: Deadline | None = None + + # Whether we are busy sending a fragmented message. + self.send_in_progress = False + + # Mapping of ping IDs to pong waiters, in chronological order. + self.pong_waiters: dict[bytes, tuple[threading.Event, float, bool]] = {} + + self.latency: float = 0 + """ + Latency of the connection, in seconds. + + Latency is defined as the round-trip time of the connection. It is + measured by sending a Ping frame and waiting for a matching Pong frame. + Before the first measurement, :attr:`latency` is ``0``. + + By default, websockets enables a :ref:`keepalive ` mechanism + that sends Ping frames automatically at regular intervals. You can also + send Ping frames and measure latency with :meth:`ping`. + """ + + # Thread that sends keepalive pings. None when ping_interval is None. + self.keepalive_thread: threading.Thread | None = None + + # Exception raised in recv_events, to be chained to ConnectionClosed + # in the user thread in order to show why the TCP connection dropped. + self.recv_exc: BaseException | None = None + + # Receiving events from the socket. This thread is marked as daemon to + # allow creating a connection in a non-daemon thread and using it in a + # daemon thread. This mustn't prevent the interpreter from exiting. + self.recv_events_thread = threading.Thread( + target=self.recv_events, + daemon=True, + ) + + # Start recv_events only after all attributes are initialized. + self.recv_events_thread.start() + + # Public attributes + + @property + def local_address(self) -> Any: + """ + Local address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getsockname`. + + """ + return self.socket.getsockname() + + @property + def remote_address(self) -> Any: + """ + Remote address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getpeername`. + + """ + return self.socket.getpeername() + + @property + def state(self) -> State: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should call :meth:`~recv` or + :meth:`send` and handle :exc:`~websockets.exceptions.ConnectionClosed` + exceptions. + + """ + return self.protocol.state + + @property + def subprotocol(self) -> Subprotocol | None: + """ + Subprotocol negotiated during the opening handshake. + + :obj:`None` if no subprotocol was negotiated. + + """ + return self.protocol.subprotocol + + @property + def close_code(self) -> int | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_code + + @property + def close_reason(self) -> str | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_reason + + # Public methods + + def __enter__(self) -> Connection: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + if exc_type is None: + self.close() + else: + self.close(CloseCode.INTERNAL_ERROR) + + def __iter__(self) -> Iterator[Data]: + """ + Iterate on incoming messages. + + The iterator calls :meth:`recv` and yields messages in an infinite loop. + + It exits when the connection is closed normally. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` exception after a + protocol error or a network failure. + + """ + try: + while True: + yield self.recv() + except ConnectionClosedOK: + return + + # This overload structure is required to avoid the error: + # "parameter without a default follows parameter with a default" + + @overload + def recv(self, timeout: float | None, decode: Literal[True]) -> str: ... + + @overload + def recv(self, timeout: float | None, decode: Literal[False]) -> bytes: ... + + @overload + def recv(self, timeout: float | None = None, *, decode: Literal[True]) -> str: ... + + @overload + def recv( + self, timeout: float | None = None, *, decode: Literal[False] + ) -> bytes: ... + + @overload + def recv( + self, timeout: float | None = None, decode: bool | None = None + ) -> Data: ... + + def recv(self, timeout: float | None = None, decode: bool | None = None) -> Data: + """ + Receive the next message. + + When the connection is closed, :meth:`recv` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises + :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal closure + and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. This is how you detect the end of the + message stream. + + If ``timeout`` is :obj:`None`, block until a message is received. If + ``timeout`` is set, wait up to ``timeout`` seconds for a message to be + received and return it, else raise :exc:`TimeoutError`. If ``timeout`` + is ``0`` or negative, check if a message has been received already and + return it, else raise :exc:`TimeoutError`. + + If the message is fragmented, wait until all fragments are received, + reassemble them, and return the whole message. + + Args: + timeout: Timeout for receiving a message in seconds. + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + A string (:class:`str`) for a Text_ frame or a bytestring + (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and + return a bytestring (:class:`bytes`). This improves performance + when decoding isn't needed, for example if the message contains + JSON and you're using a JSON library that expects a bytestring. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames + and return a string (:class:`str`). This may be useful for + servers that send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two threads call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + return self.recv_messages.get(timeout, decode) + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv while another thread " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + self.recv_events_thread.join() + raise self.protocol.close_exc from self.recv_exc + + @overload + def recv_streaming(self, decode: Literal[True]) -> Iterator[str]: ... + + @overload + def recv_streaming(self, decode: Literal[False]) -> Iterator[bytes]: ... + + @overload + def recv_streaming(self, decode: bool | None = None) -> Iterator[Data]: ... + + def recv_streaming(self, decode: bool | None = None) -> Iterator[Data]: + """ + Receive the next message frame by frame. + + This method is designed for receiving fragmented messages. It returns an + iterator that yields each fragment as it is received. This iterator must + be fully consumed. Else, future calls to :meth:`recv` or + :meth:`recv_streaming` will raise + :exc:`~websockets.exceptions.ConcurrencyError`, making the connection + unusable. + + :meth:`recv_streaming` raises the same exceptions as :meth:`recv`. + + Args: + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + An iterator of strings (:class:`str`) for a Text_ frame or + bytestrings (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames + and return bytestrings (:class:`bytes`). This may be useful to + optimize performance when decoding isn't needed. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames + and return strings (:class:`str`). This is useful for servers + that send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two threads call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + yield from self.recv_messages.get_iter(decode) + return + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv_streaming while another thread " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + self.recv_events_thread.join() + raise self.protocol.close_exc from self.recv_exc + + def send( + self, + message: Data | Iterable[Data], + text: bool | None = None, + ) -> None: + """ + Send a message. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or + bytes-like object (:class:`bytes`, :class:`bytearray`, or + :class:`memoryview`) is sent as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``text`` argument: + + * Set ``text=True`` to send a bytestring or bytes-like object + (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) as a + Text_ frame. This improves performance when the message is already + UTF-8 encoded, for example if the message contains JSON and you're + using a JSON library that produces a bytestring. + * Set ``text=False`` to send a string (:class:`str`) in a Binary_ + frame. This may be useful for servers that expect binary frames + instead of text frames. + + :meth:`send` also accepts an iterable of strings, bytestrings, or + bytes-like objects to enable fragmentation_. Each item is treated as a + message fragment and sent in its own frame. All items must be of the + same type, or else :meth:`send` will raise a :exc:`TypeError` and the + connection will be closed. + + .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4 + + :meth:`send` rejects dict-like objects because this is often an error. + (If you really want to send the keys of a dict-like object as fragments, + call its :meth:`~dict.keys` method and pass the result to :meth:`send`.) + + When the connection is closed, :meth:`send` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it + raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. + + Args: + message: Message to send. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If the connection is sending a fragmented message. + TypeError: If ``message`` doesn't have a supported type. + + """ + # Unfragmented message -- this case must be handled first because + # strings and bytes-like objects are iterable. + + if isinstance(message, str): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread is already running send" + ) + if text is False: + self.protocol.send_binary(message.encode()) + else: + self.protocol.send_text(message.encode()) + + elif isinstance(message, BytesLike): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread is already running send" + ) + if text is True: + self.protocol.send_text(message) + else: + self.protocol.send_binary(message) + + # Catch a common mistake -- passing a dict to send(). + + elif isinstance(message, Mapping): + raise TypeError("data is a dict-like object") + + # Fragmented message -- regular iterator. + + elif isinstance(message, Iterable): + chunks = iter(message) + try: + chunk = next(chunks) + except StopIteration: + return + + try: + # First fragment. + if isinstance(chunk, str): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread " + "is already running send" + ) + self.send_in_progress = True + if text is False: + self.protocol.send_binary(chunk.encode(), fin=False) + else: + self.protocol.send_text(chunk.encode(), fin=False) + encode = True + elif isinstance(chunk, BytesLike): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread " + "is already running send" + ) + self.send_in_progress = True + if text is True: + self.protocol.send_text(chunk, fin=False) + else: + self.protocol.send_binary(chunk, fin=False) + encode = False + else: + raise TypeError("data iterable must contain bytes or str") + + # Other fragments + for chunk in chunks: + if isinstance(chunk, str) and encode: + with self.send_context(): + assert self.send_in_progress + self.protocol.send_continuation(chunk.encode(), fin=False) + elif isinstance(chunk, BytesLike) and not encode: + with self.send_context(): + assert self.send_in_progress + self.protocol.send_continuation(chunk, fin=False) + else: + raise TypeError("data iterable must contain uniform types") + + # Final fragment. + with self.send_context(): + self.protocol.send_continuation(b"", fin=True) + self.send_in_progress = False + + except ConcurrencyError: + # We didn't start sending a fragmented message. + # The connection is still usable. + raise + + except Exception: + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "error in fragmented message", + ) + raise + + else: + raise TypeError("data must be str, bytes, or iterable") + + def close(self, code: int = CloseCode.NORMAL_CLOSURE, reason: str = "") -> None: + """ + Perform the closing handshake. + + :meth:`close` waits for the other end to complete the handshake, for the + TCP connection to terminate, and for all incoming messages to be read + with :meth:`recv`. + + :meth:`close` is idempotent: it doesn't do anything once the + connection is closed. + + Args: + code: WebSocket close code. + reason: WebSocket close reason. + + """ + try: + # The context manager takes care of waiting for the TCP connection + # to terminate after calling a method that sends a close frame. + with self.send_context(): + if self.send_in_progress: + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "close during fragmented message", + ) + else: + self.protocol.send_close(code, reason) + except ConnectionClosed: + # Ignore ConnectionClosed exceptions raised from send_context(). + # They mean that the connection is closed, which was the goal. + pass + + def ping( + self, + data: Data | None = None, + ack_on_close: bool = False, + ) -> threading.Event: + """ + Send a Ping_. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + A ping may serve as a keepalive or as a check that the remote endpoint + received all messages up to this point + + Args: + data: Payload of the ping. A :class:`str` will be encoded to UTF-8. + If ``data`` is :obj:`None`, the payload is four random bytes. + ack_on_close: when this option is :obj:`True`, the event will also + be set when the connection is closed. While this avoids getting + stuck waiting for a pong that will never arrive, it requires + checking that the state of the connection is still ``OPEN`` to + confirm that a pong was received, rather than the connection + being closed. + + Returns: + An event that will be set when the corresponding pong is received. + You can ignore it if you don't intend to wait. + + :: + + pong_event = ws.ping() + pong_event.wait() # only if you want to wait for the pong + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If another ping was sent with the same data and + the corresponding pong wasn't received yet. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + elif data is not None: + raise TypeError("data must be str or bytes-like") + + with self.send_context(): + # Protect against duplicates if a payload is explicitly set. + if data in self.pong_waiters: + raise ConcurrencyError("already waiting for a pong with the same data") + + # Generate a unique random payload otherwise. + while data is None or data in self.pong_waiters: + data = struct.pack("!I", random.getrandbits(32)) + + pong_waiter = threading.Event() + self.pong_waiters[data] = (pong_waiter, time.monotonic(), ack_on_close) + self.protocol.send_ping(data) + return pong_waiter + + def pong(self, data: Data = b"") -> None: + """ + Send a Pong_. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + An unsolicited pong may serve as a unidirectional heartbeat. + + Args: + data: Payload of the pong. A :class:`str` will be encoded to UTF-8. + + Raises: + ConnectionClosed: When the connection is closed. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + else: + raise TypeError("data must be str or bytes-like") + + with self.send_context(): + self.protocol.send_pong(data) + + # Private methods + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + This method is overridden in subclasses to handle the handshake. + + """ + assert isinstance(event, Frame) + if event.opcode in DATA_OPCODES: + self.recv_messages.put(event) + + if event.opcode is Opcode.PONG: + self.acknowledge_pings(bytes(event.data)) + + def acknowledge_pings(self, data: bytes) -> None: + """ + Acknowledge pings when receiving a pong. + + """ + with self.protocol_mutex: + # Ignore unsolicited pong. + if data not in self.pong_waiters: + return + + pong_timestamp = time.monotonic() + + # Sending a pong for only the most recent ping is legal. + # Acknowledge all previous pings too in that case. + ping_id = None + ping_ids = [] + for ping_id, ( + pong_waiter, + ping_timestamp, + _ack_on_close, + ) in self.pong_waiters.items(): + ping_ids.append(ping_id) + pong_waiter.set() + if ping_id == data: + self.latency = pong_timestamp - ping_timestamp + break + else: + raise AssertionError("solicited pong not found in pings") + + # Remove acknowledged pings from self.pong_waiters. + for ping_id in ping_ids: + del self.pong_waiters[ping_id] + + def acknowledge_pending_pings(self) -> None: + """ + Acknowledge pending pings when the connection is closed. + + """ + assert self.protocol.state is CLOSED + + for pong_waiter, _ping_timestamp, ack_on_close in self.pong_waiters.values(): + if ack_on_close: + pong_waiter.set() + + self.pong_waiters.clear() + + def keepalive(self) -> None: + """ + Send a Ping frame and wait for a Pong frame at regular intervals. + + """ + assert self.ping_interval is not None + try: + while True: + # If self.ping_timeout > self.latency > self.ping_interval, + # pings will be sent immediately after receiving pongs. + # The period will be longer than self.ping_interval. + self.recv_events_thread.join(self.ping_interval - self.latency) + if not self.recv_events_thread.is_alive(): + break + + try: + pong_waiter = self.ping(ack_on_close=True) + except ConnectionClosed: + break + if self.debug: + self.logger.debug("% sent keepalive ping") + + if self.ping_timeout is not None: + # + if pong_waiter.wait(self.ping_timeout): + if self.debug: + self.logger.debug("% received keepalive pong") + else: + if self.debug: + self.logger.debug("- timed out waiting for keepalive pong") + with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "keepalive ping timeout", + ) + break + except Exception: + self.logger.error("keepalive ping failed", exc_info=True) + + def start_keepalive(self) -> None: + """ + Run :meth:`keepalive` in a thread, unless keepalive is disabled. + + """ + if self.ping_interval is not None: + # This thread is marked as daemon like self.recv_events_thread. + self.keepalive_thread = threading.Thread( + target=self.keepalive, + daemon=True, + ) + self.keepalive_thread.start() + + def recv_events(self) -> None: + """ + Read incoming data from the socket and process events. + + Run this method in a thread as long as the connection is alive. + + ``recv_events()`` exits immediately when the ``self.socket`` is closed. + + """ + try: + while True: + try: + with self.recv_flow_control: + if self.close_deadline is not None: + self.socket.settimeout(self.close_deadline.timeout()) + data = self.socket.recv(self.recv_bufsize) + except Exception as exc: + if self.debug: + self.logger.debug( + "! error while receiving data", + exc_info=True, + ) + # When the closing handshake is initiated by our side, + # recv() may block until send_context() closes the socket. + # In that case, send_context() already set recv_exc. + # Calling set_recv_exc() avoids overwriting it. + with self.protocol_mutex: + self.set_recv_exc(exc) + break + + if data == b"": + break + + # Acquire the connection lock. + with self.protocol_mutex: + # Feed incoming data to the protocol. + self.protocol.receive_data(data) + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # Write outgoing data to the socket. + try: + self.send_data() + except Exception as exc: + if self.debug: + self.logger.debug( + "! error while sending data", + exc_info=True, + ) + # Similarly to the above, avoid overriding an exception + # set by send_context(), in case of a race condition + # i.e. send_context() closes the socket after recv() + # returns above but before send_data() calls send(). + self.set_recv_exc(exc) + break + + if self.protocol.close_expected(): + # If the connection is expected to close soon, set the + # close deadline based on the close timeout. + if self.close_deadline is None: + self.close_deadline = Deadline(self.close_timeout) + + # Unlock conn_mutex before processing events. Else, the + # application can't send messages in response to events. + + # If self.send_data raised an exception, then events are lost. + # Given that automatic responses write small amounts of data, + # this should be uncommon, so we don't handle the edge case. + + for event in events: + # This isn't expected to raise an exception. + self.process_event(event) + + # Breaking out of the while True: ... loop means that we believe + # that the socket doesn't work anymore. + with self.protocol_mutex: + # Feed the end of the data stream to the protocol. + self.protocol.receive_eof() + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # There is no error handling because send_data() can only write + # the end of the data stream here and it handles errors itself. + self.send_data() + + # This code path is triggered when receiving an HTTP response + # without a Content-Length header. This is the only case where + # reading until EOF generates an event; all other events have + # a known length. Ignore for coverage measurement because tests + # are in test_client.py rather than test_connection.py. + for event in events: # pragma: no cover + # This isn't expected to raise an exception. + self.process_event(event) + + except Exception as exc: + # This branch should never run. It's a safety net in case of bugs. + self.logger.error("unexpected internal error", exc_info=True) + with self.protocol_mutex: + self.set_recv_exc(exc) + finally: + # This isn't expected to raise an exception. + self.close_socket() + + @contextlib.contextmanager + def send_context( + self, + *, + expected_state: State = OPEN, # CONNECTING during the opening handshake + ) -> Iterator[None]: + """ + Create a context for writing to the connection from user code. + + On entry, :meth:`send_context` acquires the connection lock and checks + that the connection is open; on exit, it writes outgoing data to the + socket:: + + with self.send_context(): + self.protocol.send_text(message.encode()) + + When the connection isn't open on entry, when the connection is expected + to close on exit, or when an unexpected error happens, terminating the + connection, :meth:`send_context` waits until the connection is closed + then raises :exc:`~websockets.exceptions.ConnectionClosed`. + + """ + # Should we wait until the connection is closed? + wait_for_close = False + # Should we close the socket and raise ConnectionClosed? + raise_close_exc = False + # What exception should we chain ConnectionClosed to? + original_exc: BaseException | None = None + + # Acquire the protocol lock. + with self.protocol_mutex: + if self.protocol.state is expected_state: + # Let the caller interact with the protocol. + try: + yield + except (ProtocolError, ConcurrencyError): + # The protocol state wasn't changed. Exit immediately. + raise + except Exception as exc: + self.logger.error("unexpected internal error", exc_info=True) + # This branch should never run. It's a safety net in case of + # bugs. Since we don't know what happened, we will close the + # connection and raise the exception to the caller. + wait_for_close = False + raise_close_exc = True + original_exc = exc + else: + # Check if the connection is expected to close soon. + if self.protocol.close_expected(): + wait_for_close = True + # If the connection is expected to close soon, set the + # close deadline based on the close timeout. + # Since we tested earlier that protocol.state was OPEN + # (or CONNECTING) and we didn't release protocol_mutex, + # it is certain that self.close_deadline is still None. + assert self.close_deadline is None + self.close_deadline = Deadline(self.close_timeout) + # Write outgoing data to the socket. + try: + self.send_data() + except Exception as exc: + if self.debug: + self.logger.debug( + "! error while sending data", + exc_info=True, + ) + # While the only expected exception here is OSError, + # other exceptions would be treated identically. + wait_for_close = False + raise_close_exc = True + original_exc = exc + + else: # self.protocol.state is not expected_state + # Minor layering violation: we assume that the connection + # will be closing soon if it isn't in the expected state. + wait_for_close = True + raise_close_exc = True + + # To avoid a deadlock, release the connection lock by exiting the + # context manager before waiting for recv_events() to terminate. + + # If the connection is expected to close soon and the close timeout + # elapses, close the socket to terminate the connection. + if wait_for_close: + if self.close_deadline is None: + timeout = self.close_timeout + else: + # Thread.join() returns immediately if timeout is negative. + timeout = self.close_deadline.timeout(raise_if_elapsed=False) + self.recv_events_thread.join(timeout) + + if self.recv_events_thread.is_alive(): + # There's no risk to overwrite another error because + # original_exc is never set when wait_for_close is True. + assert original_exc is None + original_exc = TimeoutError("timed out while closing connection") + # Set recv_exc before closing the socket in order to get + # proper exception reporting. + raise_close_exc = True + with self.protocol_mutex: + self.set_recv_exc(original_exc) + + # If an error occurred, close the socket to terminate the connection and + # raise an exception. + if raise_close_exc: + self.close_socket() + # Wait for the protocol state to be CLOSED before accessing close_exc. + self.recv_events_thread.join() + raise self.protocol.close_exc from original_exc + + def send_data(self) -> None: + """ + Send outgoing data. + + This method requires holding protocol_mutex. + + Raises: + OSError: When a socket operations fails. + + """ + assert self.protocol_mutex.locked() + for data in self.protocol.data_to_send(): + if data: + if self.close_deadline is not None: + self.socket.settimeout(self.close_deadline.timeout()) + self.socket.sendall(data) + else: + try: + self.socket.shutdown(socket.SHUT_WR) + except OSError: # socket already closed + pass + + def set_recv_exc(self, exc: BaseException | None) -> None: + """ + Set recv_exc, if not set yet. + + This method requires holding protocol_mutex. + + """ + assert self.protocol_mutex.locked() + if self.recv_exc is None: # pragma: no branch + self.recv_exc = exc + + def close_socket(self) -> None: + """ + Shutdown and close socket. Close message assembler. + + Calling close_socket() guarantees that recv_events() terminates. Indeed, + recv_events() may block only on socket.recv() or on recv_messages.put(). + + """ + # shutdown() is required to interrupt recv() on Linux. + try: + self.socket.shutdown(socket.SHUT_RDWR) + except OSError: + pass # socket is already closed + self.socket.close() + + # Calling protocol.receive_eof() is safe because it's idempotent. + # This guarantees that the protocol state becomes CLOSED. + with self.protocol_mutex: + self.protocol.receive_eof() + assert self.protocol.state is CLOSED + + # Abort recv() with a ConnectionClosed exception. + self.recv_messages.close() + + # Acknowledge pings sent with the ack_on_close option. + self.acknowledge_pending_pings() diff --git a/venv/lib/python3.10/site-packages/websockets/sync/messages.py b/venv/lib/python3.10/site-packages/websockets/sync/messages.py new file mode 100644 index 0000000000000000000000000000000000000000..c619e78a1fa73409efd3ee21f1f0f63923e8e68e --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/sync/messages.py @@ -0,0 +1,345 @@ +from __future__ import annotations + +import codecs +import queue +import threading +from typing import Any, Callable, Iterable, Iterator, Literal, overload + +from ..exceptions import ConcurrencyError +from ..frames import OP_BINARY, OP_CONT, OP_TEXT, Frame +from ..typing import Data +from .utils import Deadline + + +__all__ = ["Assembler"] + +UTF8Decoder = codecs.getincrementaldecoder("utf-8") + + +class Assembler: + """ + Assemble messages from frames. + + :class:`Assembler` expects only data frames. The stream of frames must + respect the protocol; if it doesn't, the behavior is undefined. + + Args: + pause: Called when the buffer of frames goes above the high water mark; + should pause reading from the network. + resume: Called when the buffer of frames goes below the low water mark; + should resume reading from the network. + + """ + + def __init__( + self, + high: int | None = None, + low: int | None = None, + pause: Callable[[], Any] = lambda: None, + resume: Callable[[], Any] = lambda: None, + ) -> None: + # Serialize reads and writes -- except for reads via synchronization + # primitives provided by the threading and queue modules. + self.mutex = threading.Lock() + + # Queue of incoming frames. + self.frames: queue.SimpleQueue[Frame | None] = queue.SimpleQueue() + + # We cannot put a hard limit on the size of the queue because a single + # call to Protocol.data_received() could produce thousands of frames, + # which must be buffered. Instead, we pause reading when the buffer goes + # above the high limit and we resume when it goes under the low limit. + if high is not None and low is None: + low = high // 4 + if high is None and low is not None: + high = low * 4 + if high is not None and low is not None: + if low < 0: + raise ValueError("low must be positive or equal to zero") + if high < low: + raise ValueError("high must be greater than or equal to low") + self.high, self.low = high, low + self.pause = pause + self.resume = resume + self.paused = False + + # This flag prevents concurrent calls to get() by user code. + self.get_in_progress = False + + # This flag marks the end of the connection. + self.closed = False + + def get_next_frame(self, timeout: float | None = None) -> Frame: + # Helper to factor out the logic for getting the next frame from the + # queue, while handling timeouts and reaching the end of the stream. + if self.closed: + try: + frame = self.frames.get(block=False) + except queue.Empty: + raise EOFError("stream of frames ended") from None + else: + try: + # Check for a frame that's already received if timeout <= 0. + # SimpleQueue.get() doesn't support negative timeout values. + if timeout is not None and timeout <= 0: + frame = self.frames.get(block=False) + else: + frame = self.frames.get(block=True, timeout=timeout) + except queue.Empty: + raise TimeoutError(f"timed out in {timeout:.1f}s") from None + if frame is None: + raise EOFError("stream of frames ended") + return frame + + def reset_queue(self, frames: Iterable[Frame]) -> None: + # Helper to put frames back into the queue after they were fetched. + # This happens only when the queue is empty. However, by the time + # we acquire self.mutex, put() may have added items in the queue. + # Therefore, we must handle the case where the queue is not empty. + frame: Frame | None + with self.mutex: + queued = [] + try: + while True: + queued.append(self.frames.get(block=False)) + except queue.Empty: + pass + for frame in frames: + self.frames.put(frame) + # This loop runs only when a race condition occurs. + for frame in queued: # pragma: no cover + self.frames.put(frame) + + # This overload structure is required to avoid the error: + # "parameter without a default follows parameter with a default" + + @overload + def get(self, timeout: float | None, decode: Literal[True]) -> str: ... + + @overload + def get(self, timeout: float | None, decode: Literal[False]) -> bytes: ... + + @overload + def get(self, timeout: float | None = None, *, decode: Literal[True]) -> str: ... + + @overload + def get(self, timeout: float | None = None, *, decode: Literal[False]) -> bytes: ... + + @overload + def get(self, timeout: float | None = None, decode: bool | None = None) -> Data: ... + + def get(self, timeout: float | None = None, decode: bool | None = None) -> Data: + """ + Read the next message. + + :meth:`get` returns a single :class:`str` or :class:`bytes`. + + If the message is fragmented, :meth:`get` waits until the last frame is + received, then it reassembles the message and returns it. To receive + messages frame by frame, use :meth:`get_iter` instead. + + Args: + timeout: If a timeout is provided and elapses before a complete + message is received, :meth:`get` raises :exc:`TimeoutError`. + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + TimeoutError: If a timeout is provided and elapses before a + complete message is received. + + """ + with self.mutex: + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get() fetches a complete message or times out. + + try: + deadline = Deadline(timeout) + + # First frame + frame = self.get_next_frame(deadline.timeout(raise_if_elapsed=False)) + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + frames = [frame] + + # Following frames, for fragmented messages + while not frame.fin: + try: + frame = self.get_next_frame( + deadline.timeout(raise_if_elapsed=False) + ) + except TimeoutError: + # Put frames already received back into the queue + # so that future calls to get() can return them. + self.reset_queue(frames) + raise + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_CONT + frames.append(frame) + + finally: + self.get_in_progress = False + + data = b"".join(frame.data for frame in frames) + if decode: + return data.decode() + else: + return data + + @overload + def get_iter(self, decode: Literal[True]) -> Iterator[str]: ... + + @overload + def get_iter(self, decode: Literal[False]) -> Iterator[bytes]: ... + + @overload + def get_iter(self, decode: bool | None = None) -> Iterator[Data]: ... + + def get_iter(self, decode: bool | None = None) -> Iterator[Data]: + """ + Stream the next message. + + Iterating the return value of :meth:`get_iter` yields a :class:`str` or + :class:`bytes` for each frame in the message. + + The iterator must be fully consumed before calling :meth:`get_iter` or + :meth:`get` again. Else, :exc:`ConcurrencyError` is raised. + + This method only makes sense for fragmented messages. If messages aren't + fragmented, use :meth:`get` instead. + + Args: + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + + """ + with self.mutex: + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get_iter() fetches a complete message or times out. + + # If get_iter() raises an exception e.g. in decoder.decode(), + # get_in_progress remains set and the connection becomes unusable. + + # First frame + frame = self.get_next_frame() + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + if decode: + decoder = UTF8Decoder() + yield decoder.decode(frame.data, frame.fin) + else: + yield frame.data + + # Following frames, for fragmented messages + while not frame.fin: + frame = self.get_next_frame() + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_CONT + if decode: + yield decoder.decode(frame.data, frame.fin) + else: + yield frame.data + + self.get_in_progress = False + + def put(self, frame: Frame) -> None: + """ + Add ``frame`` to the next message. + + Raises: + EOFError: If the stream of frames has ended. + + """ + with self.mutex: + if self.closed: + raise EOFError("stream of frames ended") + + self.frames.put(frame) + self.maybe_pause() + + # put() and get/get_iter() call maybe_pause() and maybe_resume() while + # holding self.mutex. This guarantees that the calls interleave properly. + # Specifically, it prevents a race condition where maybe_resume() would + # run before maybe_pause(), leaving the connection incorrectly paused. + + # A race condition is possible when get/get_iter() call self.frames.get() + # without holding self.mutex. However, it's harmless — and even beneficial! + # It can only result in popping an item from the queue before maybe_resume() + # runs and skipping a pause() - resume() cycle that would otherwise occur. + + def maybe_pause(self) -> None: + """Pause the writer if queue is above the high water mark.""" + # Skip if flow control is disabled + if self.high is None: + return + + assert self.mutex.locked() + + # Check for "> high" to support high = 0 + if self.frames.qsize() > self.high and not self.paused: + self.paused = True + self.pause() + + def maybe_resume(self) -> None: + """Resume the writer if queue is below the low water mark.""" + # Skip if flow control is disabled + if self.low is None: + return + + assert self.mutex.locked() + + # Check for "<= low" to support low = 0 + if self.frames.qsize() <= self.low and self.paused: + self.paused = False + self.resume() + + def close(self) -> None: + """ + End the stream of frames. + + Calling :meth:`close` concurrently with :meth:`get`, :meth:`get_iter`, + or :meth:`put` is safe. They will raise :exc:`EOFError`. + + """ + with self.mutex: + if self.closed: + return + + self.closed = True + + if self.get_in_progress: + # Unblock get() or get_iter(). + self.frames.put(None) + + if self.paused: + # Unblock recv_events(). + self.paused = False + self.resume() diff --git a/venv/lib/python3.10/site-packages/websockets/sync/router.py b/venv/lib/python3.10/site-packages/websockets/sync/router.py new file mode 100644 index 0000000000000000000000000000000000000000..5572c42618d7b6207735562edece5c9082823ce0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/sync/router.py @@ -0,0 +1,192 @@ +from __future__ import annotations + +import http +import ssl as ssl_module +import urllib.parse +from typing import Any, Callable, Literal + +from werkzeug.exceptions import NotFound +from werkzeug.routing import Map, RequestRedirect + +from ..http11 import Request, Response +from .server import Server, ServerConnection, serve + + +__all__ = ["route", "unix_route", "Router"] + + +class Router: + """WebSocket router supporting :func:`route`.""" + + def __init__( + self, + url_map: Map, + server_name: str | None = None, + url_scheme: str = "ws", + ) -> None: + self.url_map = url_map + self.server_name = server_name + self.url_scheme = url_scheme + for rule in self.url_map.iter_rules(): + rule.websocket = True + + def get_server_name(self, connection: ServerConnection, request: Request) -> str: + if self.server_name is None: + return request.headers["Host"] + else: + return self.server_name + + def redirect(self, connection: ServerConnection, url: str) -> Response: + response = connection.respond(http.HTTPStatus.FOUND, f"Found at {url}") + response.headers["Location"] = url + return response + + def not_found(self, connection: ServerConnection) -> Response: + return connection.respond(http.HTTPStatus.NOT_FOUND, "Not Found") + + def route_request( + self, connection: ServerConnection, request: Request + ) -> Response | None: + """Route incoming request.""" + url_map_adapter = self.url_map.bind( + server_name=self.get_server_name(connection, request), + url_scheme=self.url_scheme, + ) + try: + parsed = urllib.parse.urlparse(request.path) + handler, kwargs = url_map_adapter.match( + path_info=parsed.path, + query_args=parsed.query, + ) + except RequestRedirect as redirect: + return self.redirect(connection, redirect.new_url) + except NotFound: + return self.not_found(connection) + connection.handler, connection.handler_kwargs = handler, kwargs + return None + + def handler(self, connection: ServerConnection) -> None: + """Handle a connection.""" + return connection.handler(connection, **connection.handler_kwargs) + + +def route( + url_map: Map, + *args: Any, + server_name: str | None = None, + ssl: ssl_module.SSLContext | Literal[True] | None = None, + create_router: type[Router] | None = None, + **kwargs: Any, +) -> Server: + """ + Create a WebSocket server dispatching connections to different handlers. + + This feature requires the third-party library `werkzeug`_: + + .. code-block:: console + + $ pip install werkzeug + + .. _werkzeug: https://werkzeug.palletsprojects.com/ + + :func:`route` accepts the same arguments as + :func:`~websockets.sync.server.serve`, except as described below. + + The first argument is a :class:`werkzeug.routing.Map` that maps URL patterns + to connection handlers. In addition to the connection, handlers receive + parameters captured in the URL as keyword arguments. + + Here's an example:: + + + from websockets.sync.router import route + from werkzeug.routing import Map, Rule + + def channel_handler(websocket, channel_id): + ... + + url_map = Map([ + Rule("/channel/", endpoint=channel_handler), + ... + ]) + + with route(url_map, ...) as server: + server.serve_forever() + + Refer to the documentation of :mod:`werkzeug.routing` for details. + + If you define redirects with ``Rule(..., redirect_to=...)`` in the URL map, + when the server runs behind a reverse proxy that modifies the ``Host`` + header or terminates TLS, you need additional configuration: + + * Set ``server_name`` to the name of the server as seen by clients. When not + provided, websockets uses the value of the ``Host`` header. + + * Set ``ssl=True`` to generate ``wss://`` URIs without actually enabling + TLS. Under the hood, this bind the URL map with a ``url_scheme`` of + ``wss://`` instead of ``ws://``. + + There is no need to specify ``websocket=True`` in each rule. It is added + automatically. + + Args: + url_map: Mapping of URL patterns to connection handlers. + server_name: Name of the server as seen by clients. If :obj:`None`, + websockets uses the value of the ``Host`` header. + ssl: Configuration for enabling TLS on the connection. Set it to + :obj:`True` if a reverse proxy terminates TLS connections. + create_router: Factory for the :class:`Router` dispatching requests to + handlers. Set it to a wrapper or a subclass to customize routing. + + """ + url_scheme = "ws" if ssl is None else "wss" + if ssl is not True and ssl is not None: + kwargs["ssl"] = ssl + + if create_router is None: + create_router = Router + + router = create_router(url_map, server_name, url_scheme) + + _process_request: ( + Callable[ + [ServerConnection, Request], + Response | None, + ] + | None + ) = kwargs.pop("process_request", None) + if _process_request is None: + process_request: Callable[ + [ServerConnection, Request], + Response | None, + ] = router.route_request + else: + + def process_request( + connection: ServerConnection, request: Request + ) -> Response | None: + response = _process_request(connection, request) + if response is not None: + return response + return router.route_request(connection, request) + + return serve(router.handler, *args, process_request=process_request, **kwargs) + + +def unix_route( + url_map: Map, + path: str | None = None, + **kwargs: Any, +) -> Server: + """ + Create a WebSocket Unix server dispatching connections to different handlers. + + :func:`unix_route` combines the behaviors of :func:`route` and + :func:`~websockets.sync.server.unix_serve`. + + Args: + url_map: Mapping of URL patterns to connection handlers. + path: File system path to the Unix socket. + + """ + return route(url_map, unix=True, path=path, **kwargs) diff --git a/venv/lib/python3.10/site-packages/websockets/sync/server.py b/venv/lib/python3.10/site-packages/websockets/sync/server.py new file mode 100644 index 0000000000000000000000000000000000000000..efb40a7f4777c1b8d5568f9c990aac267c0b6a6e --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/sync/server.py @@ -0,0 +1,763 @@ +from __future__ import annotations + +import hmac +import http +import logging +import os +import re +import selectors +import socket +import ssl as ssl_module +import sys +import threading +import warnings +from collections.abc import Iterable, Sequence +from types import TracebackType +from typing import Any, Callable, Mapping, cast + +from ..exceptions import InvalidHeader +from ..extensions.base import ServerExtensionFactory +from ..extensions.permessage_deflate import enable_server_permessage_deflate +from ..frames import CloseCode +from ..headers import ( + build_www_authenticate_basic, + parse_authorization_basic, + validate_subprotocols, +) +from ..http11 import SERVER, Request, Response +from ..protocol import CONNECTING, OPEN, Event +from ..server import ServerProtocol +from ..typing import LoggerLike, Origin, StatusLike, Subprotocol +from .connection import Connection +from .utils import Deadline + + +__all__ = ["serve", "unix_serve", "ServerConnection", "Server", "basic_auth"] + + +class ServerConnection(Connection): + """ + :mod:`threading` implementation of a WebSocket server connection. + + :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for + receiving and sending messages. + + It supports iteration to receive messages:: + + for message in websocket: + process(message) + + The iterator exits normally when the connection is closed with close code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and + ``max_queue`` arguments have the same meaning as in :func:`serve`. + + Args: + socket: Socket connected to a WebSocket client. + protocol: Sans-I/O connection. + + """ + + def __init__( + self, + socket: socket.socket, + protocol: ServerProtocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + ) -> None: + self.protocol: ServerProtocol + self.request_rcvd = threading.Event() + super().__init__( + socket, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + self.username: str # see basic_auth() + self.handler: Callable[[ServerConnection], None] # see route() + self.handler_kwargs: Mapping[str, Any] # see route() + + def respond(self, status: StatusLike, text: str) -> Response: + """ + Create a plain text HTTP response. + + ``process_request`` and ``process_response`` may call this method to + return an HTTP response instead of performing the WebSocket opening + handshake. + + You can modify the response before returning it, for example by changing + HTTP headers. + + Args: + status: HTTP status code. + text: HTTP response body; it will be encoded to UTF-8. + + Returns: + HTTP response to send to the client. + + """ + return self.protocol.reject(status, text) + + def handshake( + self, + process_request: ( + Callable[ + [ServerConnection, Request], + Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + timeout: float | None = None, + ) -> None: + """ + Perform the opening handshake. + + """ + if not self.request_rcvd.wait(timeout): + raise TimeoutError("timed out while waiting for handshake request") + + if self.request is not None: + with self.send_context(expected_state=CONNECTING): + response = None + + if process_request is not None: + try: + response = process_request(self, self.request) + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is None: + self.response = self.protocol.accept(self.request) + else: + self.response = response + + if server_header: + self.response.headers["Server"] = server_header + + response = None + + if process_response is not None: + try: + response = process_response(self, self.request, self.response) + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is not None: + self.response = response + + self.protocol.send_response(self.response) + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a request, when the request cannot be parsed, or when the + # handshake fails, including when process_request or process_response + # raises an exception. + + # It isn't set when process_request or process_response sends an HTTP + # response that rejects the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake request. + if self.request is None: + assert isinstance(event, Request) + self.request = event + self.request_rcvd.set() + # Later events - frames. + else: + super().process_event(event) + + def recv_events(self) -> None: + """ + Read incoming data from the socket and process events. + + """ + try: + super().recv_events() + finally: + # If the connection is closed during the handshake, unblock it. + self.request_rcvd.set() + + +class Server: + """ + WebSocket server returned by :func:`serve`. + + This class mirrors the API of :class:`~socketserver.BaseServer`, notably the + :meth:`~socketserver.BaseServer.serve_forever` and + :meth:`~socketserver.BaseServer.shutdown` methods, as well as the context + manager protocol. + + Args: + socket: Server socket listening for new connections. + handler: Handler for one connection. Receives the socket and address + returned by :meth:`~socket.socket.accept`. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__( + self, + socket: socket.socket, + handler: Callable[[socket.socket, Any], None], + logger: LoggerLike | None = None, + ) -> None: + self.socket = socket + self.handler = handler + if logger is None: + logger = logging.getLogger("websockets.server") + self.logger = logger + if sys.platform != "win32": + self.shutdown_watcher, self.shutdown_notifier = os.pipe() + + def serve_forever(self) -> None: + """ + See :meth:`socketserver.BaseServer.serve_forever`. + + This method doesn't return. Calling :meth:`shutdown` from another thread + stops the server. + + Typical use:: + + with serve(...) as server: + server.serve_forever() + + """ + poller = selectors.DefaultSelector() + try: + poller.register(self.socket, selectors.EVENT_READ) + except ValueError: # pragma: no cover + # If shutdown() is called before poller.register(), + # the socket is closed and poller.register() raises + # ValueError: Invalid file descriptor: -1 + return + if sys.platform != "win32": + poller.register(self.shutdown_watcher, selectors.EVENT_READ) + + while True: + poller.select() + try: + # If the socket is closed, this will raise an exception and exit + # the loop. So we don't need to check the return value of select(). + sock, addr = self.socket.accept() + except OSError: + break + # Since there isn't a mechanism for tracking connections and waiting + # for them to terminate, we cannot use daemon threads, or else all + # connections would be terminate brutally when closing the server. + thread = threading.Thread(target=self.handler, args=(sock, addr)) + thread.start() + + def shutdown(self) -> None: + """ + See :meth:`socketserver.BaseServer.shutdown`. + + """ + self.socket.close() + if sys.platform != "win32": + os.write(self.shutdown_notifier, b"x") + + def fileno(self) -> int: + """ + See :meth:`socketserver.BaseServer.fileno`. + + """ + return self.socket.fileno() + + def __enter__(self) -> Server: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.shutdown() + + +def __getattr__(name: str) -> Any: + if name == "WebSocketServer": + warnings.warn( # deprecated in 13.0 - 2024-08-20 + "WebSocketServer was renamed to Server", + DeprecationWarning, + ) + return Server + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +def serve( + handler: Callable[[ServerConnection], None], + host: str | None = None, + port: int | None = None, + *, + # TCP/TLS + sock: socket.socket | None = None, + ssl: ssl_module.SSLContext | None = None, + # WebSocket + origins: Sequence[Origin | re.Pattern[str] | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + select_subprotocol: ( + Callable[ + [ServerConnection, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None, + compression: str | None = "deflate", + # HTTP + process_request: ( + Callable[ + [ServerConnection, Request], + Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ServerConnection] | None = None, + **kwargs: Any, +) -> Server: + """ + Create a WebSocket server listening on ``host`` and ``port``. + + Whenever a client connects, the server creates a :class:`ServerConnection`, + performs the opening handshake, and delegates to the ``handler``. + + The handler receives the :class:`ServerConnection` instance, which you can + use to send and receive messages. + + Once the handler completes, either normally or with an exception, the server + performs the closing handshake and closes the connection. + + This function returns a :class:`Server` whose API mirrors + :class:`~socketserver.BaseServer`. Treat it as a context manager to ensure + that it will be closed and call :meth:`~Server.serve_forever` to serve + requests:: + + from websockets.sync.server import serve + + def handler(websocket): + ... + + with serve(handler, ...) as server: + server.serve_forever() + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + host: Network interfaces the server binds to. + See :func:`~socket.create_server` for details. + port: TCP port the server listens on. + See :func:`~socket.create_server` for details. + sock: Preexisting TCP socket. ``sock`` replaces ``host`` and ``port``. + You may call :func:`socket.create_server` to create a suitable TCP + socket. + ssl: Configuration for enabling TLS on the connection. + origins: Acceptable values of the ``Origin`` header, for defending + against Cross-Site WebSocket Hijacking attacks. Values can be + :class:`str` to test for an exact match or regular expressions + compiled by :func:`re.compile` to test against a pattern. Include + :obj:`None` in the list if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + select_subprotocol: Callback for selecting a subprotocol among + those supported by the client and the server. It receives a + :class:`ServerConnection` (not a + :class:`~websockets.server.ServerProtocol`!) instance and a list of + subprotocols offered by the client. Other than the first argument, + it has the same behavior as the + :meth:`ServerProtocol.select_subprotocol + ` method. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + process_request: Intercept the request during the opening handshake. + Return an HTTP response to force the response. Return :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + process_response: Intercept the response during the opening handshake. + Modify the response or return a new HTTP response to force the + response. Return :obj:`None` to continue normally. When you force an + HTTP 101 Continue response, the handshake is successful. Else, the + connection is aborted. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to + :obj:`None` removes the header. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing connections in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. See the + :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ServerConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to :func:`~socket.create_server`. + + """ + + # Process parameters + + # Backwards compatibility: ssl used to be called ssl_context. + if ssl is None and "ssl_context" in kwargs: + ssl = kwargs.pop("ssl_context") + warnings.warn( # deprecated in 13.0 - 2024-08-20 + "ssl_context was renamed to ssl", + DeprecationWarning, + ) + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_server_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if create_connection is None: + create_connection = ServerConnection + + # Bind socket and listen + + # Private APIs for unix_connect() + unix: bool = kwargs.pop("unix", False) + path: str | None = kwargs.pop("path", None) + + if sock is None: + if unix: + if path is None: + raise ValueError("missing path argument") + kwargs.setdefault("family", socket.AF_UNIX) + sock = socket.create_server(path, **kwargs) + else: + sock = socket.create_server((host, port), **kwargs) + else: + if path is not None: + raise ValueError("path and sock arguments are incompatible") + + # Initialize TLS wrapper + + if ssl is not None: + sock = ssl.wrap_socket( + sock, + server_side=True, + # Delay TLS handshake until after we set a timeout on the socket. + do_handshake_on_connect=False, + ) + + # Define request handler + + def conn_handler(sock: socket.socket, addr: Any) -> None: + # Calculate timeouts on the TLS and WebSocket handshakes. + # The TLS timeout must be set on the socket, then removed + # to avoid conflicting with the WebSocket timeout in handshake(). + deadline = Deadline(open_timeout) + + try: + # Disable Nagle algorithm + + if not unix: + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) + + # Perform TLS handshake + + if ssl is not None: + sock.settimeout(deadline.timeout()) + # mypy cannot figure this out + assert isinstance(sock, ssl_module.SSLSocket) + sock.do_handshake() + sock.settimeout(None) + + # Create a closure to give select_subprotocol access to connection. + protocol_select_subprotocol: ( + Callable[ + [ServerProtocol, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None + if select_subprotocol is not None: + + def protocol_select_subprotocol( + protocol: ServerProtocol, + subprotocols: Sequence[Subprotocol], + ) -> Subprotocol | None: + # mypy doesn't know that select_subprotocol is immutable. + assert select_subprotocol is not None + # Ensure this function is only used in the intended context. + assert protocol is connection.protocol + return select_subprotocol(connection, subprotocols) + + # Initialize WebSocket protocol + + protocol = ServerProtocol( + origins=origins, + extensions=extensions, + subprotocols=subprotocols, + select_subprotocol=protocol_select_subprotocol, + max_size=max_size, + logger=logger, + ) + + # Initialize WebSocket connection + + assert create_connection is not None # help mypy + connection = create_connection( + sock, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + except Exception: + sock.close() + return + + try: + try: + connection.handshake( + process_request, + process_response, + server_header, + deadline.timeout(), + ) + except TimeoutError: + connection.close_socket() + connection.recv_events_thread.join() + return + except Exception: + connection.logger.error("opening handshake failed", exc_info=True) + connection.close_socket() + connection.recv_events_thread.join() + return + + assert connection.protocol.state is OPEN + try: + connection.start_keepalive() + handler(connection) + except Exception: + connection.logger.error("connection handler failed", exc_info=True) + connection.close(CloseCode.INTERNAL_ERROR) + else: + connection.close() + + except Exception: # pragma: no cover + # Don't leak sockets on unexpected errors. + sock.close() + + # Initialize server + + return Server(sock, conn_handler, logger) + + +def unix_serve( + handler: Callable[[ServerConnection], None], + path: str | None = None, + **kwargs: Any, +) -> Server: + """ + Create a WebSocket server listening on a Unix socket. + + This function accepts the same keyword arguments as :func:`serve`. + + It's only available on Unix. + + It's useful for deploying a server behind a reverse proxy such as nginx. + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + path: File system path to the Unix socket. + + """ + return serve(handler, unix=True, path=path, **kwargs) + + +def is_credentials(credentials: Any) -> bool: + try: + username, password = credentials + except (TypeError, ValueError): + return False + else: + return isinstance(username, str) and isinstance(password, str) + + +def basic_auth( + realm: str = "", + credentials: tuple[str, str] | Iterable[tuple[str, str]] | None = None, + check_credentials: Callable[[str, str], bool] | None = None, +) -> Callable[[ServerConnection, Request], Response | None]: + """ + Factory for ``process_request`` to enforce HTTP Basic Authentication. + + :func:`basic_auth` is designed to integrate with :func:`serve` as follows:: + + from websockets.sync.server import basic_auth, serve + + with serve( + ..., + process_request=basic_auth( + realm="my dev server", + credentials=("hello", "iloveyou"), + ), + ): + + If authentication succeeds, the connection's ``username`` attribute is set. + If it fails, the server responds with an HTTP 401 Unauthorized status. + + One of ``credentials`` or ``check_credentials`` must be provided; not both. + + Args: + realm: Scope of protection. It should contain only ASCII characters + because the encoding of non-ASCII characters is undefined. Refer to + section 2.2 of :rfc:`7235` for details. + credentials: Hard coded authorized credentials. It can be a + ``(username, password)`` pair or a list of such pairs. + check_credentials: Function that verifies credentials. + It receives ``username`` and ``password`` arguments and returns + whether they're valid. + Raises: + TypeError: If ``credentials`` or ``check_credentials`` is wrong. + ValueError: If ``credentials`` and ``check_credentials`` are both + provided or both not provided. + + """ + if (credentials is None) == (check_credentials is None): + raise ValueError("provide either credentials or check_credentials") + + if credentials is not None: + if is_credentials(credentials): + credentials_list = [cast(tuple[str, str], credentials)] + elif isinstance(credentials, Iterable): + credentials_list = list(cast(Iterable[tuple[str, str]], credentials)) + if not all(is_credentials(item) for item in credentials_list): + raise TypeError(f"invalid credentials argument: {credentials}") + else: + raise TypeError(f"invalid credentials argument: {credentials}") + + credentials_dict = dict(credentials_list) + + def check_credentials(username: str, password: str) -> bool: + try: + expected_password = credentials_dict[username] + except KeyError: + return False + return hmac.compare_digest(expected_password, password) + + assert check_credentials is not None # help mypy + + def process_request( + connection: ServerConnection, + request: Request, + ) -> Response | None: + """ + Perform HTTP Basic Authentication. + + If it succeeds, set the connection's ``username`` attribute and return + :obj:`None`. If it fails, return an HTTP 401 Unauthorized responss. + + """ + try: + authorization = request.headers["Authorization"] + except KeyError: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Missing credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + try: + username, password = parse_authorization_basic(authorization) + except InvalidHeader: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Unsupported credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + if not check_credentials(username, password): + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Invalid credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + connection.username = username + return None + + return process_request diff --git a/venv/lib/python3.10/site-packages/websockets/sync/utils.py b/venv/lib/python3.10/site-packages/websockets/sync/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..00bce2cc6bb19fa280a6ef2b3481403e6f6ba74f --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/sync/utils.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +import time + + +__all__ = ["Deadline"] + + +class Deadline: + """ + Manage timeouts across multiple steps. + + Args: + timeout: Time available in seconds or :obj:`None` if there is no limit. + + """ + + def __init__(self, timeout: float | None) -> None: + self.deadline: float | None + if timeout is None: + self.deadline = None + else: + self.deadline = time.monotonic() + timeout + + def timeout(self, *, raise_if_elapsed: bool = True) -> float | None: + """ + Calculate a timeout from a deadline. + + Args: + raise_if_elapsed: Whether to raise :exc:`TimeoutError` + if the deadline lapsed. + + Raises: + TimeoutError: If the deadline lapsed. + + Returns: + Time left in seconds or :obj:`None` if there is no limit. + + """ + if self.deadline is None: + return None + timeout = self.deadline - time.monotonic() + if raise_if_elapsed and timeout <= 0: + raise TimeoutError("timed out") + return timeout diff --git a/venv/lib/python3.10/site-packages/websockets/typing.py b/venv/lib/python3.10/site-packages/websockets/typing.py new file mode 100644 index 0000000000000000000000000000000000000000..ab7ddd33eccf9ec1b1995714143e358b99be2b1e --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/typing.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +import http +import logging +from typing import TYPE_CHECKING, Any, NewType, Optional, Sequence, Union + + +__all__ = [ + "Data", + "LoggerLike", + "StatusLike", + "Origin", + "Subprotocol", + "ExtensionName", + "ExtensionParameter", +] + + +# Public types used in the signature of public APIs + +# Change to str | bytes when dropping Python < 3.10. +Data = Union[str, bytes] +"""Types supported in a WebSocket message: +:class:`str` for a Text_ frame, :class:`bytes` for a Binary_. + +.. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 +.. _Binary : https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + +""" + + +# Change to logging.Logger | ... when dropping Python < 3.10. +if TYPE_CHECKING: + LoggerLike = Union[logging.Logger, logging.LoggerAdapter[Any]] + """Types accepted where a :class:`~logging.Logger` is expected.""" +else: # remove this branch when dropping support for Python < 3.11 + LoggerLike = Union[logging.Logger, logging.LoggerAdapter] + """Types accepted where a :class:`~logging.Logger` is expected.""" + + +# Change to http.HTTPStatus | int when dropping Python < 3.10. +StatusLike = Union[http.HTTPStatus, int] +""" +Types accepted where an :class:`~http.HTTPStatus` is expected.""" + + +Origin = NewType("Origin", str) +"""Value of a ``Origin`` header.""" + + +Subprotocol = NewType("Subprotocol", str) +"""Subprotocol in a ``Sec-WebSocket-Protocol`` header.""" + + +ExtensionName = NewType("ExtensionName", str) +"""Name of a WebSocket extension.""" + +# Change to tuple[str, str | None] when dropping Python < 3.10. +ExtensionParameter = tuple[str, Optional[str]] +"""Parameter of a WebSocket extension.""" + + +# Private types + +ExtensionHeader = tuple[ExtensionName, Sequence[ExtensionParameter]] +"""Extension in a ``Sec-WebSocket-Extensions`` header.""" + + +ConnectionOption = NewType("ConnectionOption", str) +"""Connection option in a ``Connection`` header.""" + + +UpgradeProtocol = NewType("UpgradeProtocol", str) +"""Upgrade protocol in an ``Upgrade`` header.""" diff --git a/venv/lib/python3.10/site-packages/websockets/uri.py b/venv/lib/python3.10/site-packages/websockets/uri.py new file mode 100644 index 0000000000000000000000000000000000000000..b925b99b5752bd3b2441c0b2a19b2f47c34db0a4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/uri.py @@ -0,0 +1,225 @@ +from __future__ import annotations + +import dataclasses +import urllib.parse +import urllib.request + +from .exceptions import InvalidProxy, InvalidURI + + +__all__ = ["parse_uri", "WebSocketURI"] + + +# All characters from the gen-delims and sub-delims sets in RFC 3987. +DELIMS = ":/?#[]@!$&'()*+,;=" + + +@dataclasses.dataclass +class WebSocketURI: + """ + WebSocket URI. + + Attributes: + secure: :obj:`True` for a ``wss`` URI, :obj:`False` for a ``ws`` URI. + host: Normalized to lower case. + port: Always set even if it's the default. + path: May be empty. + query: May be empty if the URI doesn't include a query component. + username: Available when the URI contains `User Information`_. + password: Available when the URI contains `User Information`_. + + .. _User Information: https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.1 + + """ + + secure: bool + host: str + port: int + path: str + query: str + username: str | None = None + password: str | None = None + + @property + def resource_name(self) -> str: + if self.path: + resource_name = self.path + else: + resource_name = "/" + if self.query: + resource_name += "?" + self.query + return resource_name + + @property + def user_info(self) -> tuple[str, str] | None: + if self.username is None: + return None + assert self.password is not None + return (self.username, self.password) + + +def parse_uri(uri: str) -> WebSocketURI: + """ + Parse and validate a WebSocket URI. + + Args: + uri: WebSocket URI. + + Returns: + Parsed WebSocket URI. + + Raises: + InvalidURI: If ``uri`` isn't a valid WebSocket URI. + + """ + parsed = urllib.parse.urlparse(uri) + if parsed.scheme not in ["ws", "wss"]: + raise InvalidURI(uri, "scheme isn't ws or wss") + if parsed.hostname is None: + raise InvalidURI(uri, "hostname isn't provided") + if parsed.fragment != "": + raise InvalidURI(uri, "fragment identifier is meaningless") + + secure = parsed.scheme == "wss" + host = parsed.hostname + port = parsed.port or (443 if secure else 80) + path = parsed.path + query = parsed.query + username = parsed.username + password = parsed.password + # urllib.parse.urlparse accepts URLs with a username but without a + # password. This doesn't make sense for HTTP Basic Auth credentials. + if username is not None and password is None: + raise InvalidURI(uri, "username provided without password") + + try: + uri.encode("ascii") + except UnicodeEncodeError: + # Input contains non-ASCII characters. + # It must be an IRI. Convert it to a URI. + host = host.encode("idna").decode() + path = urllib.parse.quote(path, safe=DELIMS) + query = urllib.parse.quote(query, safe=DELIMS) + if username is not None: + assert password is not None + username = urllib.parse.quote(username, safe=DELIMS) + password = urllib.parse.quote(password, safe=DELIMS) + + return WebSocketURI(secure, host, port, path, query, username, password) + + +@dataclasses.dataclass +class Proxy: + """ + Proxy. + + Attributes: + scheme: ``"socks5h"``, ``"socks5"``, ``"socks4a"``, ``"socks4"``, + ``"https"``, or ``"http"``. + host: Normalized to lower case. + port: Always set even if it's the default. + username: Available when the proxy address contains `User Information`_. + password: Available when the proxy address contains `User Information`_. + + .. _User Information: https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.1 + + """ + + scheme: str + host: str + port: int + username: str | None = None + password: str | None = None + + @property + def user_info(self) -> tuple[str, str] | None: + if self.username is None: + return None + assert self.password is not None + return (self.username, self.password) + + +def parse_proxy(proxy: str) -> Proxy: + """ + Parse and validate a proxy. + + Args: + proxy: proxy. + + Returns: + Parsed proxy. + + Raises: + InvalidProxy: If ``proxy`` isn't a valid proxy. + + """ + parsed = urllib.parse.urlparse(proxy) + if parsed.scheme not in ["socks5h", "socks5", "socks4a", "socks4", "https", "http"]: + raise InvalidProxy(proxy, f"scheme {parsed.scheme} isn't supported") + if parsed.hostname is None: + raise InvalidProxy(proxy, "hostname isn't provided") + if parsed.path not in ["", "/"]: + raise InvalidProxy(proxy, "path is meaningless") + if parsed.query != "": + raise InvalidProxy(proxy, "query is meaningless") + if parsed.fragment != "": + raise InvalidProxy(proxy, "fragment is meaningless") + + scheme = parsed.scheme + host = parsed.hostname + port = parsed.port or (443 if parsed.scheme == "https" else 80) + username = parsed.username + password = parsed.password + # urllib.parse.urlparse accepts URLs with a username but without a + # password. This doesn't make sense for HTTP Basic Auth credentials. + if username is not None and password is None: + raise InvalidProxy(proxy, "username provided without password") + + try: + proxy.encode("ascii") + except UnicodeEncodeError: + # Input contains non-ASCII characters. + # It must be an IRI. Convert it to a URI. + host = host.encode("idna").decode() + if username is not None: + assert password is not None + username = urllib.parse.quote(username, safe=DELIMS) + password = urllib.parse.quote(password, safe=DELIMS) + + return Proxy(scheme, host, port, username, password) + + +def get_proxy(uri: WebSocketURI) -> str | None: + """ + Return the proxy to use for connecting to the given WebSocket URI, if any. + + """ + if urllib.request.proxy_bypass(f"{uri.host}:{uri.port}"): + return None + + # According to the _Proxy Usage_ section of RFC 6455, use a SOCKS5 proxy if + # available, else favor the proxy for HTTPS connections over the proxy for + # HTTP connections. + + # The priority of a proxy for WebSocket connections is unspecified. We give + # it the highest priority. This makes it easy to configure a specific proxy + # for websockets. + + # getproxies() may return SOCKS proxies as {"socks": "http://host:port"} or + # as {"https": "socks5h://host:port"} depending on whether they're declared + # in the operating system or in environment variables. + + proxies = urllib.request.getproxies() + if uri.secure: + schemes = ["wss", "socks", "https"] + else: + schemes = ["ws", "socks", "https", "http"] + + for scheme in schemes: + proxy = proxies.get(scheme) + if proxy is not None: + if scheme == "socks" and proxy.startswith("http://"): + proxy = "socks5h://" + proxy[7:] + return proxy + else: + return None diff --git a/venv/lib/python3.10/site-packages/websockets/utils.py b/venv/lib/python3.10/site-packages/websockets/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..62d2dc177ba210c4d904e566dc801d9c5e846748 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/utils.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import base64 +import hashlib +import secrets +import sys + + +__all__ = ["accept_key", "apply_mask"] + + +GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + +def generate_key() -> str: + """ + Generate a random key for the Sec-WebSocket-Key header. + + """ + key = secrets.token_bytes(16) + return base64.b64encode(key).decode() + + +def accept_key(key: str) -> str: + """ + Compute the value of the Sec-WebSocket-Accept header. + + Args: + key: Value of the Sec-WebSocket-Key header. + + """ + sha1 = hashlib.sha1((key + GUID).encode()).digest() + return base64.b64encode(sha1).decode() + + +def apply_mask(data: bytes, mask: bytes) -> bytes: + """ + Apply masking to the data of a WebSocket message. + + Args: + data: Data to mask. + mask: 4-bytes mask. + + """ + if len(mask) != 4: + raise ValueError("mask must contain 4 bytes") + + data_int = int.from_bytes(data, sys.byteorder) + mask_repeated = mask * (len(data) // 4) + mask[: len(data) % 4] + mask_int = int.from_bytes(mask_repeated, sys.byteorder) + return (data_int ^ mask_int).to_bytes(len(data), sys.byteorder) diff --git a/venv/lib/python3.10/site-packages/websockets/version.py b/venv/lib/python3.10/site-packages/websockets/version.py new file mode 100644 index 0000000000000000000000000000000000000000..8d22f4e43b588c183e64fd13d0831030b826dff0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/websockets/version.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +import importlib.metadata + + +__all__ = ["tag", "version", "commit"] + + +# ========= =========== =================== +# release development +# ========= =========== =================== +# tag X.Y X.Y (upcoming) +# version X.Y X.Y.dev1+g5678cde +# commit X.Y 5678cde +# ========= =========== =================== + + +# When tagging a release, set `released = True`. +# After tagging a release, set `released = False` and increment `tag`. + +released = True + +tag = version = commit = "15.0.1" + + +if not released: # pragma: no cover + import pathlib + import re + import subprocess + + def get_version(tag: str) -> str: + # Since setup.py executes the contents of src/websockets/version.py, + # __file__ can point to either of these two files. + file_path = pathlib.Path(__file__) + root_dir = file_path.parents[0 if file_path.name == "setup.py" else 2] + + # Read version from package metadata if it is installed. + try: + version = importlib.metadata.version("websockets") + except ImportError: + pass + else: + # Check that this file belongs to the installed package. + files = importlib.metadata.files("websockets") + if files: + version_files = [f for f in files if f.name == file_path.name] + if version_files: + version_file = version_files[0] + if version_file.locate() == file_path: + return version + + # Read version from git if available. + try: + description = subprocess.run( + ["git", "describe", "--dirty", "--tags", "--long"], + capture_output=True, + cwd=root_dir, + timeout=1, + check=True, + text=True, + ).stdout.strip() + # subprocess.run raises FileNotFoundError if git isn't on $PATH. + except ( + FileNotFoundError, + subprocess.CalledProcessError, + subprocess.TimeoutExpired, + ): + pass + else: + description_re = r"[0-9.]+-([0-9]+)-(g[0-9a-f]{7,}(?:-dirty)?)" + match = re.fullmatch(description_re, description) + if match is None: + raise ValueError(f"Unexpected git description: {description}") + distance, remainder = match.groups() + remainder = remainder.replace("-", ".") # required by PEP 440 + return f"{tag}.dev{distance}+{remainder}" + + # Avoid crashing if the development version cannot be determined. + return f"{tag}.dev0+gunknown" + + version = get_version(tag) + + def get_commit(tag: str, version: str) -> str: + # Extract commit from version, falling back to tag if not available. + version_re = r"[0-9.]+\.dev[0-9]+\+g([0-9a-f]{7,}|unknown)(?:\.dirty)?" + match = re.fullmatch(version_re, version) + if match is None: + raise ValueError(f"Unexpected version: {version}") + (commit,) = match.groups() + return tag if commit == "unknown" else commit + + commit = get_commit(tag, version) diff --git a/venv/lib/python3.10/site-packages/xxhash/__init__.py b/venv/lib/python3.10/site-packages/xxhash/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..043c486ddf9d2770d7fbee4bff1c26985ac6cd7e --- /dev/null +++ b/venv/lib/python3.10/site-packages/xxhash/__init__.py @@ -0,0 +1,63 @@ +from ._xxhash import ( + xxh32, + xxh32_digest, + xxh32_intdigest, + xxh32_hexdigest, + xxh64, + xxh64_digest, + xxh64_intdigest, + xxh64_hexdigest, + xxh3_64, + xxh3_64_digest, + xxh3_64_intdigest, + xxh3_64_hexdigest, + xxh3_128, + xxh3_128_digest, + xxh3_128_intdigest, + xxh3_128_hexdigest, + XXHASH_VERSION, +) + +from .version import VERSION, VERSION_TUPLE + + +xxh128 = xxh3_128 +xxh128_hexdigest = xxh3_128_hexdigest +xxh128_intdigest = xxh3_128_intdigest +xxh128_digest = xxh3_128_digest + +algorithms_available = set([ + "xxh32", + "xxh64", + "xxh3_64", + "xxh128", + "xxh3_128", +]) + + +__all__ = [ + "xxh32", + "xxh32_digest", + "xxh32_intdigest", + "xxh32_hexdigest", + "xxh64", + "xxh64_digest", + "xxh64_intdigest", + "xxh64_hexdigest", + "xxh3_64", + "xxh3_64_digest", + "xxh3_64_intdigest", + "xxh3_64_hexdigest", + "xxh3_128", + "xxh3_128_digest", + "xxh3_128_intdigest", + "xxh3_128_hexdigest", + "xxh128", + "xxh128_digest", + "xxh128_intdigest", + "xxh128_hexdigest", + "VERSION", + "VERSION_TUPLE", + "XXHASH_VERSION", + "algorithms_available", +] diff --git a/venv/lib/python3.10/site-packages/xxhash/__init__.pyi b/venv/lib/python3.10/site-packages/xxhash/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..03c62497a3aba0fc5695ee033c0a402e41ae8c44 --- /dev/null +++ b/venv/lib/python3.10/site-packages/xxhash/__init__.pyi @@ -0,0 +1,62 @@ +import array +from typing import Union +from typing_extensions import final + +_InputType = Union[str, bytes, bytearray, memoryview, array.ArrayType[int]] + +VERSION: str +XXHASH_VERSION: str +VERSION_TUPLE: tuple[int, ...] + +algorithms_available: set[str] + +class _Hasher: + def __init__(self, input: _InputType = ..., seed: int = ...) -> None: ... + def update(self, input: _InputType) -> None: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def intdigest(self) -> int: ... + def copy(self) -> _Hasher: ... + def reset(self) -> None: ... + @property + def digestsize(self) -> int: ... + @property + def digest_size(self) -> int: ... + @property + def block_size(self) -> int: ... + @property + def name(self) -> str: ... + @property + def seed(self) -> int: ... + +@final +class xxh32(_Hasher): ... + +@final +class xxh3_64(_Hasher): ... + +@final +class xxh3_128(_Hasher): ... + +xxh64 = xxh3_64 +xxh128 = xxh3_128 + +def xxh32_digest(args: _InputType, seed: int = ...) -> bytes: ... +def xxh32_hexdigest(args: _InputType, seed: int = ...) -> str: ... +def xxh32_intdigest(args: _InputType, seed: int = ...) -> int: ... + +def xxh3_64_digest(args: _InputType, seed: int = ...) -> bytes: ... +def xxh3_64_hexdigest(args: _InputType, seed: int = ...) -> str: ... +def xxh3_64_intdigest(args: _InputType, seed: int = ...) -> int: ... + +def xxh3_128_digest(args: _InputType, seed: int = ...) -> bytes: ... +def xxh3_128_hexdigest(args: _InputType, seed: int = ...) -> str: ... +def xxh3_128_intdigest(args: _InputType, seed: int = ...) -> int: ... + +xxh64_digest = xxh3_64_digest +xxh64_hexdigest = xxh3_64_hexdigest +xxh64_intdigest = xxh3_64_intdigest + +xxh128_digest = xxh3_128_digest +xxh128_hexdigest = xxh3_128_hexdigest +xxh128_intdigest = xxh3_128_intdigest diff --git a/venv/lib/python3.10/site-packages/xxhash/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/xxhash/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f977b7c079cdaf991024f60ec660215578aa624a Binary files /dev/null and b/venv/lib/python3.10/site-packages/xxhash/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/xxhash/__pycache__/version.cpython-310.pyc b/venv/lib/python3.10/site-packages/xxhash/__pycache__/version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c76872514151da07f7a3360a5c9314e020c23fea Binary files /dev/null and b/venv/lib/python3.10/site-packages/xxhash/__pycache__/version.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/xxhash/py.typed b/venv/lib/python3.10/site-packages/xxhash/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/xxhash/version.py b/venv/lib/python3.10/site-packages/xxhash/version.py new file mode 100644 index 0000000000000000000000000000000000000000..91fde107bab8c18449d2fe179b3ceee4d96bdbf6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/xxhash/version.py @@ -0,0 +1,2 @@ +VERSION = "3.5.0" +VERSION_TUPLE = (3, 5, 0) diff --git a/venv/lib/python3.10/site-packages/yarl/__init__.py b/venv/lib/python3.10/site-packages/yarl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8579787df900c6ebfb09bc0d7e891387f30b8763 --- /dev/null +++ b/venv/lib/python3.10/site-packages/yarl/__init__.py @@ -0,0 +1,14 @@ +from ._query import Query, QueryVariable, SimpleQuery +from ._url import URL, cache_clear, cache_configure, cache_info + +__version__ = "1.20.1" + +__all__ = ( + "URL", + "SimpleQuery", + "QueryVariable", + "Query", + "cache_clear", + "cache_configure", + "cache_info", +) diff --git a/venv/lib/python3.10/site-packages/yarl/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/yarl/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad9c95d222ad43eb7c4c98c0888dedd50ed087c2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/yarl/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/yarl/__pycache__/_parse.cpython-310.pyc b/venv/lib/python3.10/site-packages/yarl/__pycache__/_parse.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e56775c37764ce7f0bdafb99a69929ddb25f9598 Binary files /dev/null and b/venv/lib/python3.10/site-packages/yarl/__pycache__/_parse.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/yarl/__pycache__/_path.cpython-310.pyc b/venv/lib/python3.10/site-packages/yarl/__pycache__/_path.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9d875ea481ac26dc921bbf12cd6a3c355b6c9da Binary files /dev/null and b/venv/lib/python3.10/site-packages/yarl/__pycache__/_path.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/yarl/__pycache__/_query.cpython-310.pyc b/venv/lib/python3.10/site-packages/yarl/__pycache__/_query.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa0a1e67114be957e1c3617a3973247d701f4967 Binary files /dev/null and b/venv/lib/python3.10/site-packages/yarl/__pycache__/_query.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/yarl/__pycache__/_quoters.cpython-310.pyc b/venv/lib/python3.10/site-packages/yarl/__pycache__/_quoters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4309eb87dc89d50f0eb829109e17fcd9700cf5ee Binary files /dev/null and b/venv/lib/python3.10/site-packages/yarl/__pycache__/_quoters.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/yarl/__pycache__/_quoting.cpython-310.pyc b/venv/lib/python3.10/site-packages/yarl/__pycache__/_quoting.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb4865d6a0f5c1ba854eaea7539c1f9ea6361f4b Binary files /dev/null and b/venv/lib/python3.10/site-packages/yarl/__pycache__/_quoting.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/yarl/__pycache__/_quoting_py.cpython-310.pyc b/venv/lib/python3.10/site-packages/yarl/__pycache__/_quoting_py.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9849385ac7cb0be47939a7d2d2a03ae33e7c05f8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/yarl/__pycache__/_quoting_py.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/yarl/__pycache__/_url.cpython-310.pyc b/venv/lib/python3.10/site-packages/yarl/__pycache__/_url.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb5886ef2c7338cffa58c9823764dd3da8a4f4b7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/yarl/__pycache__/_url.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/yarl/_parse.py b/venv/lib/python3.10/site-packages/yarl/_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..115d772360e61f4322eb72ced557d42a30930518 --- /dev/null +++ b/venv/lib/python3.10/site-packages/yarl/_parse.py @@ -0,0 +1,203 @@ +"""URL parsing utilities.""" + +import re +import unicodedata +from functools import lru_cache +from typing import Union +from urllib.parse import scheme_chars, uses_netloc + +from ._quoters import QUOTER, UNQUOTER_PLUS + +# Leading and trailing C0 control and space to be stripped per WHATWG spec. +# == "".join([chr(i) for i in range(0, 0x20 + 1)]) +WHATWG_C0_CONTROL_OR_SPACE = ( + "\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10" + "\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f " +) + +# Unsafe bytes to be removed per WHATWG spec +UNSAFE_URL_BYTES_TO_REMOVE = ["\t", "\r", "\n"] +USES_AUTHORITY = frozenset(uses_netloc) + +SplitURLType = tuple[str, str, str, str, str] + + +def split_url(url: str) -> SplitURLType: + """Split URL into parts.""" + # Adapted from urllib.parse.urlsplit + # Only lstrip url as some applications rely on preserving trailing space. + # (https://url.spec.whatwg.org/#concept-basic-url-parser would strip both) + url = url.lstrip(WHATWG_C0_CONTROL_OR_SPACE) + for b in UNSAFE_URL_BYTES_TO_REMOVE: + if b in url: + url = url.replace(b, "") + + scheme = netloc = query = fragment = "" + i = url.find(":") + if i > 0 and url[0] in scheme_chars: + for c in url[1:i]: + if c not in scheme_chars: + break + else: + scheme, url = url[:i].lower(), url[i + 1 :] + has_hash = "#" in url + has_question_mark = "?" in url + if url[:2] == "//": + delim = len(url) # position of end of domain part of url, default is end + if has_hash and has_question_mark: + delim_chars = "/?#" + elif has_question_mark: + delim_chars = "/?" + elif has_hash: + delim_chars = "/#" + else: + delim_chars = "/" + for c in delim_chars: # look for delimiters; the order is NOT important + wdelim = url.find(c, 2) # find first of this delim + if wdelim >= 0 and wdelim < delim: # if found + delim = wdelim # use earliest delim position + netloc = url[2:delim] + url = url[delim:] + has_left_bracket = "[" in netloc + has_right_bracket = "]" in netloc + if (has_left_bracket and not has_right_bracket) or ( + has_right_bracket and not has_left_bracket + ): + raise ValueError("Invalid IPv6 URL") + if has_left_bracket: + bracketed_host = netloc.partition("[")[2].partition("]")[0] + # Valid bracketed hosts are defined in + # https://www.rfc-editor.org/rfc/rfc3986#page-49 + # https://url.spec.whatwg.org/ + if bracketed_host and bracketed_host[0] == "v": + if not re.match(r"\Av[a-fA-F0-9]+\..+\Z", bracketed_host): + raise ValueError("IPvFuture address is invalid") + elif ":" not in bracketed_host: + raise ValueError("The IPv6 content between brackets is not valid") + if has_hash: + url, _, fragment = url.partition("#") + if has_question_mark: + url, _, query = url.partition("?") + if netloc and not netloc.isascii(): + _check_netloc(netloc) + return scheme, netloc, url, query, fragment + + +def _check_netloc(netloc: str) -> None: + # Adapted from urllib.parse._checknetloc + # looking for characters like \u2100 that expand to 'a/c' + # IDNA uses NFKC equivalence, so normalize for this check + + # ignore characters already included + # but not the surrounding text + n = netloc.replace("@", "").replace(":", "").replace("#", "").replace("?", "") + normalized_netloc = unicodedata.normalize("NFKC", n) + if n == normalized_netloc: + return + # Note that there are no unicode decompositions for the character '@' so + # its currently impossible to have test coverage for this branch, however if the + # one should be added in the future we want to make sure its still checked. + for c in "/?#@:": # pragma: no branch + if c in normalized_netloc: + raise ValueError( + f"netloc '{netloc}' contains invalid " + "characters under NFKC normalization" + ) + + +@lru_cache # match the same size as urlsplit +def split_netloc( + netloc: str, +) -> tuple[Union[str, None], Union[str, None], Union[str, None], Union[int, None]]: + """Split netloc into username, password, host and port.""" + if "@" not in netloc: + username: Union[str, None] = None + password: Union[str, None] = None + hostinfo = netloc + else: + userinfo, _, hostinfo = netloc.rpartition("@") + username, have_password, password = userinfo.partition(":") + if not have_password: + password = None + + if "[" in hostinfo: + _, _, bracketed = hostinfo.partition("[") + hostname, _, port_str = bracketed.partition("]") + _, _, port_str = port_str.partition(":") + else: + hostname, _, port_str = hostinfo.partition(":") + + if not port_str: + return username or None, password, hostname or None, None + + try: + port = int(port_str) + except ValueError: + raise ValueError("Invalid URL: port can't be converted to integer") + if not (0 <= port <= 65535): + raise ValueError("Port out of range 0-65535") + return username or None, password, hostname or None, port + + +def unsplit_result( + scheme: str, netloc: str, url: str, query: str, fragment: str +) -> str: + """Unsplit a URL without any normalization.""" + if netloc or (scheme and scheme in USES_AUTHORITY) or url[:2] == "//": + if url and url[:1] != "/": + url = f"{scheme}://{netloc}/{url}" if scheme else f"{scheme}:{url}" + else: + url = f"{scheme}://{netloc}{url}" if scheme else f"//{netloc}{url}" + elif scheme: + url = f"{scheme}:{url}" + if query: + url = f"{url}?{query}" + return f"{url}#{fragment}" if fragment else url + + +@lru_cache # match the same size as urlsplit +def make_netloc( + user: Union[str, None], + password: Union[str, None], + host: Union[str, None], + port: Union[int, None], + encode: bool = False, +) -> str: + """Make netloc from parts. + + The user and password are encoded if encode is True. + + The host must already be encoded with _encode_host. + """ + if host is None: + return "" + ret = host + if port is not None: + ret = f"{ret}:{port}" + if user is None and password is None: + return ret + if password is not None: + if not user: + user = "" + elif encode: + user = QUOTER(user) + if encode: + password = QUOTER(password) + user = f"{user}:{password}" + elif user and encode: + user = QUOTER(user) + return f"{user}@{ret}" if user else ret + + +def query_to_pairs(query_string: str) -> list[tuple[str, str]]: + """Parse a query given as a string argument. + + Works like urllib.parse.parse_qsl with keep empty values. + """ + pairs: list[tuple[str, str]] = [] + if not query_string: + return pairs + for k_v in query_string.split("&"): + k, _, v = k_v.partition("=") + pairs.append((UNQUOTER_PLUS(k), UNQUOTER_PLUS(v))) + return pairs diff --git a/venv/lib/python3.10/site-packages/yarl/_path.py b/venv/lib/python3.10/site-packages/yarl/_path.py new file mode 100644 index 0000000000000000000000000000000000000000..c22f0b4b8cdd9280fd36789e2bc052b1c4938167 --- /dev/null +++ b/venv/lib/python3.10/site-packages/yarl/_path.py @@ -0,0 +1,41 @@ +"""Utilities for working with paths.""" + +from collections.abc import Sequence +from contextlib import suppress + + +def normalize_path_segments(segments: Sequence[str]) -> list[str]: + """Drop '.' and '..' from a sequence of str segments""" + + resolved_path: list[str] = [] + + for seg in segments: + if seg == "..": + # ignore any .. segments that would otherwise cause an + # IndexError when popped from resolved_path if + # resolving for rfc3986 + with suppress(IndexError): + resolved_path.pop() + elif seg != ".": + resolved_path.append(seg) + + if segments and segments[-1] in (".", ".."): + # do some post-processing here. + # if the last segment was a relative dir, + # then we need to append the trailing '/' + resolved_path.append("") + + return resolved_path + + +def normalize_path(path: str) -> str: + # Drop '.' and '..' from str path + prefix = "" + if path and path[0] == "/": + # preserve the "/" root element of absolute paths, copying it to the + # normalised output as per sections 5.2.4 and 6.2.2.3 of rfc3986. + prefix = "/" + path = path[1:] + + segments = path.split("/") + return prefix + "/".join(normalize_path_segments(segments)) diff --git a/venv/lib/python3.10/site-packages/yarl/_query.py b/venv/lib/python3.10/site-packages/yarl/_query.py new file mode 100644 index 0000000000000000000000000000000000000000..910bc877c63254f56fe84cd0f8c7374a37511377 --- /dev/null +++ b/venv/lib/python3.10/site-packages/yarl/_query.py @@ -0,0 +1,114 @@ +"""Query string handling.""" + +import math +from collections.abc import Iterable, Mapping, Sequence +from typing import Any, SupportsInt, Union + +from multidict import istr + +from ._quoters import QUERY_PART_QUOTER, QUERY_QUOTER + +SimpleQuery = Union[str, SupportsInt, float] +QueryVariable = Union[SimpleQuery, Sequence[SimpleQuery]] +Query = Union[ + None, str, Mapping[str, QueryVariable], Sequence[tuple[str, QueryVariable]] +] + + +def query_var(v: SimpleQuery) -> str: + """Convert a query variable to a string.""" + cls = type(v) + if cls is int: # Fast path for non-subclassed int + return str(v) + if isinstance(v, str): + return v + if isinstance(v, float): + if math.isinf(v): + raise ValueError("float('inf') is not supported") + if math.isnan(v): + raise ValueError("float('nan') is not supported") + return str(float(v)) + if cls is not bool and isinstance(v, SupportsInt): + return str(int(v)) + raise TypeError( + "Invalid variable type: value " + "should be str, int or float, got {!r} " + "of type {}".format(v, cls) + ) + + +def get_str_query_from_sequence_iterable( + items: Iterable[tuple[Union[str, istr], QueryVariable]], +) -> str: + """Return a query string from a sequence of (key, value) pairs. + + value is a single value or a sequence of values for the key + + The sequence of values must be a list or tuple. + """ + quoter = QUERY_PART_QUOTER + pairs = [ + f"{quoter(k)}={quoter(v if type(v) is str else query_var(v))}" + for k, val in items + for v in ( + val if type(val) is not str and isinstance(val, (list, tuple)) else (val,) + ) + ] + return "&".join(pairs) + + +def get_str_query_from_iterable( + items: Iterable[tuple[Union[str, istr], SimpleQuery]], +) -> str: + """Return a query string from an iterable. + + The iterable must contain (key, value) pairs. + + The values are not allowed to be sequences, only single values are + allowed. For sequences, use `_get_str_query_from_sequence_iterable`. + """ + quoter = QUERY_PART_QUOTER + # A listcomp is used since listcomps are inlined on CPython 3.12+ and + # they are a bit faster than a generator expression. + pairs = [ + f"{quoter(k)}={quoter(v if type(v) is str else query_var(v))}" for k, v in items + ] + return "&".join(pairs) + + +def get_str_query(*args: Any, **kwargs: Any) -> Union[str, None]: + """Return a query string from supported args.""" + query: Union[str, Mapping[str, QueryVariable], None] + if kwargs: + if args: + msg = "Either kwargs or single query parameter must be present" + raise ValueError(msg) + query = kwargs + elif len(args) == 1: + query = args[0] + else: + raise ValueError("Either kwargs or single query parameter must be present") + + if query is None: + return None + if not query: + return "" + if type(query) is dict: + return get_str_query_from_sequence_iterable(query.items()) + if type(query) is str or isinstance(query, str): + return QUERY_QUOTER(query) + if isinstance(query, Mapping): + return get_str_query_from_sequence_iterable(query.items()) + if isinstance(query, (bytes, bytearray, memoryview)): # type: ignore[unreachable] + msg = "Invalid query type: bytes, bytearray and memoryview are forbidden" + raise TypeError(msg) + if isinstance(query, Sequence): + # We don't expect sequence values if we're given a list of pairs + # already; only mappings like builtin `dict` which can't have the + # same key pointing to multiple values are allowed to use + # `_query_seq_pairs`. + return get_str_query_from_iterable(query) + raise TypeError( + "Invalid query type: only str, mapping or " + "sequence of (key, value) pairs is allowed" + ) diff --git a/venv/lib/python3.10/site-packages/yarl/_quoters.py b/venv/lib/python3.10/site-packages/yarl/_quoters.py new file mode 100644 index 0000000000000000000000000000000000000000..0feb5b141131697a6dc87df19941ffe6714b20ff --- /dev/null +++ b/venv/lib/python3.10/site-packages/yarl/_quoters.py @@ -0,0 +1,33 @@ +"""Quoting and unquoting utilities for URL parts.""" + +from typing import Union +from urllib.parse import quote + +from ._quoting import _Quoter, _Unquoter + +QUOTER = _Quoter(requote=False) +REQUOTER = _Quoter() +PATH_QUOTER = _Quoter(safe="@:", protected="/+", requote=False) +PATH_REQUOTER = _Quoter(safe="@:", protected="/+") +QUERY_QUOTER = _Quoter(safe="?/:@", protected="=+&;", qs=True, requote=False) +QUERY_REQUOTER = _Quoter(safe="?/:@", protected="=+&;", qs=True) +QUERY_PART_QUOTER = _Quoter(safe="?/:@", qs=True, requote=False) +FRAGMENT_QUOTER = _Quoter(safe="?/:@", requote=False) +FRAGMENT_REQUOTER = _Quoter(safe="?/:@") + +UNQUOTER = _Unquoter() +PATH_UNQUOTER = _Unquoter(unsafe="+") +PATH_SAFE_UNQUOTER = _Unquoter(ignore="/%", unsafe="+") +QS_UNQUOTER = _Unquoter(qs=True) +UNQUOTER_PLUS = _Unquoter(plus=True) # to match urllib.parse.unquote_plus + + +def human_quote(s: Union[str, None], unsafe: str) -> Union[str, None]: + if not s: + return s + for c in "%" + unsafe: + if c in s: + s = s.replace(c, f"%{ord(c):02X}") + if s.isprintable(): + return s + return "".join(c if c.isprintable() else quote(c) for c in s) diff --git a/venv/lib/python3.10/site-packages/yarl/_quoting.py b/venv/lib/python3.10/site-packages/yarl/_quoting.py new file mode 100644 index 0000000000000000000000000000000000000000..25d76c885cacaa815bb7e0149aedbe76c20f2228 --- /dev/null +++ b/venv/lib/python3.10/site-packages/yarl/_quoting.py @@ -0,0 +1,19 @@ +import os +import sys +from typing import TYPE_CHECKING + +__all__ = ("_Quoter", "_Unquoter") + + +NO_EXTENSIONS = bool(os.environ.get("YARL_NO_EXTENSIONS")) # type: bool +if sys.implementation.name != "cpython": + NO_EXTENSIONS = True + + +if TYPE_CHECKING or NO_EXTENSIONS: + from ._quoting_py import _Quoter, _Unquoter +else: + try: + from ._quoting_c import _Quoter, _Unquoter + except ImportError: # pragma: no cover + from ._quoting_py import _Quoter, _Unquoter # type: ignore[assignment] diff --git a/venv/lib/python3.10/site-packages/yarl/_quoting_c.pyx b/venv/lib/python3.10/site-packages/yarl/_quoting_c.pyx new file mode 100644 index 0000000000000000000000000000000000000000..91b0644f7fafb39eeaa79efa21635ffdcea12619 --- /dev/null +++ b/venv/lib/python3.10/site-packages/yarl/_quoting_c.pyx @@ -0,0 +1,453 @@ +# cython: language_level=3, freethreading_compatible=True + +from cpython.exc cimport PyErr_NoMemory +from cpython.mem cimport PyMem_Free, PyMem_Malloc, PyMem_Realloc +from cpython.unicode cimport ( + PyUnicode_DATA, + PyUnicode_DecodeASCII, + PyUnicode_DecodeUTF8Stateful, + PyUnicode_GET_LENGTH, + PyUnicode_KIND, + PyUnicode_READ, +) +from libc.stdint cimport uint8_t, uint64_t +from libc.string cimport memcpy, memset + +from string import ascii_letters, digits + + +cdef str GEN_DELIMS = ":/?#[]@" +cdef str SUB_DELIMS_WITHOUT_QS = "!$'()*," +cdef str SUB_DELIMS = SUB_DELIMS_WITHOUT_QS + '+?=;' +cdef str RESERVED = GEN_DELIMS + SUB_DELIMS +cdef str UNRESERVED = ascii_letters + digits + '-._~' +cdef str ALLOWED = UNRESERVED + SUB_DELIMS_WITHOUT_QS +cdef str QS = '+&=;' + +DEF BUF_SIZE = 8 * 1024 # 8KiB + +cdef inline Py_UCS4 _to_hex(uint8_t v) noexcept: + if v < 10: + return (v+0x30) # ord('0') == 0x30 + else: + return (v+0x41-10) # ord('A') == 0x41 + + +cdef inline int _from_hex(Py_UCS4 v) noexcept: + if '0' <= v <= '9': + return (v) - 0x30 # ord('0') == 0x30 + elif 'A' <= v <= 'F': + return (v) - 0x41 + 10 # ord('A') == 0x41 + elif 'a' <= v <= 'f': + return (v) - 0x61 + 10 # ord('a') == 0x61 + else: + return -1 + + +cdef inline int _is_lower_hex(Py_UCS4 v) noexcept: + return 'a' <= v <= 'f' + + +cdef inline long _restore_ch(Py_UCS4 d1, Py_UCS4 d2): + cdef int digit1 = _from_hex(d1) + if digit1 < 0: + return -1 + cdef int digit2 = _from_hex(d2) + if digit2 < 0: + return -1 + return digit1 << 4 | digit2 + + +cdef uint8_t ALLOWED_TABLE[16] +cdef uint8_t ALLOWED_NOTQS_TABLE[16] + + +cdef inline bint bit_at(uint8_t array[], uint64_t ch) noexcept: + return array[ch >> 3] & (1 << (ch & 7)) + + +cdef inline void set_bit(uint8_t array[], uint64_t ch) noexcept: + array[ch >> 3] |= (1 << (ch & 7)) + + +memset(ALLOWED_TABLE, 0, sizeof(ALLOWED_TABLE)) +memset(ALLOWED_NOTQS_TABLE, 0, sizeof(ALLOWED_NOTQS_TABLE)) + +for i in range(128): + if chr(i) in ALLOWED: + set_bit(ALLOWED_TABLE, i) + set_bit(ALLOWED_NOTQS_TABLE, i) + if chr(i) in QS: + set_bit(ALLOWED_NOTQS_TABLE, i) + +# ----------------- writer --------------------------- + +cdef struct Writer: + char *buf + bint heap_allocated_buf + Py_ssize_t size + Py_ssize_t pos + bint changed + + +cdef inline void _init_writer(Writer* writer, char* buf): + writer.buf = buf + writer.heap_allocated_buf = False + writer.size = BUF_SIZE + writer.pos = 0 + writer.changed = 0 + + +cdef inline void _release_writer(Writer* writer): + if writer.heap_allocated_buf: + PyMem_Free(writer.buf) + + +cdef inline int _write_char(Writer* writer, Py_UCS4 ch, bint changed): + cdef char * buf + cdef Py_ssize_t size + + if writer.pos == writer.size: + # reallocate + size = writer.size + BUF_SIZE + if not writer.heap_allocated_buf: + buf = PyMem_Malloc(size) + if buf == NULL: + PyErr_NoMemory() + return -1 + memcpy(buf, writer.buf, writer.size) + writer.heap_allocated_buf = True + else: + buf = PyMem_Realloc(writer.buf, size) + if buf == NULL: + PyErr_NoMemory() + return -1 + writer.buf = buf + writer.size = size + writer.buf[writer.pos] = ch + writer.pos += 1 + writer.changed |= changed + return 0 + + +cdef inline int _write_pct(Writer* writer, uint8_t ch, bint changed): + if _write_char(writer, '%', changed) < 0: + return -1 + if _write_char(writer, _to_hex(ch >> 4), changed) < 0: + return -1 + return _write_char(writer, _to_hex(ch & 0x0f), changed) + + +cdef inline int _write_utf8(Writer* writer, Py_UCS4 symbol): + cdef uint64_t utf = symbol + + if utf < 0x80: + return _write_pct(writer, utf, True) + elif utf < 0x800: + if _write_pct(writer, (0xc0 | (utf >> 6)), True) < 0: + return -1 + return _write_pct(writer, (0x80 | (utf & 0x3f)), True) + elif 0xD800 <= utf <= 0xDFFF: + # surogate pair, ignored + return 0 + elif utf < 0x10000: + if _write_pct(writer, (0xe0 | (utf >> 12)), True) < 0: + return -1 + if _write_pct(writer, (0x80 | ((utf >> 6) & 0x3f)), + True) < 0: + return -1 + return _write_pct(writer, (0x80 | (utf & 0x3f)), True) + elif utf > 0x10FFFF: + # symbol is too large + return 0 + else: + if _write_pct(writer, (0xf0 | (utf >> 18)), True) < 0: + return -1 + if _write_pct(writer, (0x80 | ((utf >> 12) & 0x3f)), + True) < 0: + return -1 + if _write_pct(writer, (0x80 | ((utf >> 6) & 0x3f)), + True) < 0: + return -1 + return _write_pct(writer, (0x80 | (utf & 0x3f)), True) + + +# --------------------- end writer -------------------------- + + +cdef class _Quoter: + cdef bint _qs + cdef bint _requote + + cdef uint8_t _safe_table[16] + cdef uint8_t _protected_table[16] + + def __init__( + self, *, str safe='', str protected='', bint qs=False, bint requote=True, + ): + cdef Py_UCS4 ch + + self._qs = qs + self._requote = requote + + if not self._qs: + memcpy(self._safe_table, + ALLOWED_NOTQS_TABLE, + sizeof(self._safe_table)) + else: + memcpy(self._safe_table, + ALLOWED_TABLE, + sizeof(self._safe_table)) + for ch in safe: + if ord(ch) > 127: + raise ValueError("Only safe symbols with ORD < 128 are allowed") + set_bit(self._safe_table, ch) + + memset(self._protected_table, 0, sizeof(self._protected_table)) + for ch in protected: + if ord(ch) > 127: + raise ValueError("Only safe symbols with ORD < 128 are allowed") + set_bit(self._safe_table, ch) + set_bit(self._protected_table, ch) + + def __call__(self, val): + if val is None: + return None + if type(val) is not str: + if isinstance(val, str): + # derived from str + val = str(val) + else: + raise TypeError("Argument should be str") + return self._do_quote_or_skip(val) + + cdef str _do_quote_or_skip(self, str val): + cdef char[BUF_SIZE] buffer + cdef Py_UCS4 ch + cdef Py_ssize_t length = PyUnicode_GET_LENGTH(val) + cdef Py_ssize_t idx = length + cdef bint must_quote = 0 + cdef Writer writer + cdef int kind = PyUnicode_KIND(val) + cdef const void *data = PyUnicode_DATA(val) + + # If everything in the string is in the safe + # table and all ASCII, we can skip quoting + while idx: + idx -= 1 + ch = PyUnicode_READ(kind, data, idx) + if ch >= 128 or not bit_at(self._safe_table, ch): + must_quote = 1 + break + + if not must_quote: + return val + + _init_writer(&writer, &buffer[0]) + try: + return self._do_quote(val, length, kind, data, &writer) + finally: + _release_writer(&writer) + + cdef str _do_quote( + self, + str val, + Py_ssize_t length, + int kind, + const void *data, + Writer *writer + ): + cdef Py_UCS4 ch + cdef long chl + cdef int changed + cdef Py_ssize_t idx = 0 + + while idx < length: + ch = PyUnicode_READ(kind, data, idx) + idx += 1 + if ch == '%' and self._requote and idx <= length - 2: + chl = _restore_ch( + PyUnicode_READ(kind, data, idx), + PyUnicode_READ(kind, data, idx + 1) + ) + if chl != -1: + ch = chl + idx += 2 + if ch < 128: + if bit_at(self._protected_table, ch): + if _write_pct(writer, ch, True) < 0: + raise + continue + + if bit_at(self._safe_table, ch): + if _write_char(writer, ch, True) < 0: + raise + continue + + changed = (_is_lower_hex(PyUnicode_READ(kind, data, idx - 2)) or + _is_lower_hex(PyUnicode_READ(kind, data, idx - 1))) + if _write_pct(writer, ch, changed) < 0: + raise + continue + else: + ch = '%' + + if self._write(writer, ch) < 0: + raise + + if not writer.changed: + return val + else: + return PyUnicode_DecodeASCII(writer.buf, writer.pos, "strict") + + cdef inline int _write(self, Writer *writer, Py_UCS4 ch): + if self._qs: + if ch == ' ': + return _write_char(writer, '+', True) + + if ch < 128 and bit_at(self._safe_table, ch): + return _write_char(writer, ch, False) + + return _write_utf8(writer, ch) + + +cdef class _Unquoter: + cdef str _ignore + cdef bint _has_ignore + cdef str _unsafe + cdef bytes _unsafe_bytes + cdef Py_ssize_t _unsafe_bytes_len + cdef const unsigned char * _unsafe_bytes_char + cdef bint _qs + cdef bint _plus # to match urllib.parse.unquote_plus + cdef _Quoter _quoter + cdef _Quoter _qs_quoter + + def __init__(self, *, ignore="", unsafe="", qs=False, plus=False): + self._ignore = ignore + self._has_ignore = bool(self._ignore) + self._unsafe = unsafe + # unsafe may only be extended ascii characters (0-255) + self._unsafe_bytes = self._unsafe.encode('ascii') + self._unsafe_bytes_len = len(self._unsafe_bytes) + self._unsafe_bytes_char = self._unsafe_bytes + self._qs = qs + self._plus = plus + self._quoter = _Quoter() + self._qs_quoter = _Quoter(qs=True) + + def __call__(self, val): + if val is None: + return None + if type(val) is not str: + if isinstance(val, str): + # derived from str + val = str(val) + else: + raise TypeError("Argument should be str") + return self._do_unquote(val) + + cdef str _do_unquote(self, str val): + cdef Py_ssize_t length = PyUnicode_GET_LENGTH(val) + if length == 0: + return val + + cdef list ret = [] + cdef char buffer[4] + cdef Py_ssize_t buflen = 0 + cdef Py_ssize_t consumed + cdef str unquoted + cdef Py_UCS4 ch = 0 + cdef long chl = 0 + cdef Py_ssize_t idx = 0 + cdef Py_ssize_t start_pct + cdef int kind = PyUnicode_KIND(val) + cdef const void *data = PyUnicode_DATA(val) + cdef bint changed = 0 + while idx < length: + ch = PyUnicode_READ(kind, data, idx) + idx += 1 + if ch == '%' and idx <= length - 2: + changed = 1 + chl = _restore_ch( + PyUnicode_READ(kind, data, idx), + PyUnicode_READ(kind, data, idx + 1) + ) + if chl != -1: + ch = chl + idx += 2 + assert buflen < 4 + buffer[buflen] = ch + buflen += 1 + try: + unquoted = PyUnicode_DecodeUTF8Stateful(buffer, buflen, + NULL, &consumed) + except UnicodeDecodeError: + start_pct = idx - buflen * 3 + buffer[0] = ch + buflen = 1 + ret.append(val[start_pct : idx - 3]) + try: + unquoted = PyUnicode_DecodeUTF8Stateful(buffer, buflen, + NULL, &consumed) + except UnicodeDecodeError: + buflen = 0 + ret.append(val[idx - 3 : idx]) + continue + if not unquoted: + assert consumed == 0 + continue + assert consumed == buflen + buflen = 0 + if self._qs and unquoted in '+=&;': + ret.append(self._qs_quoter(unquoted)) + elif ( + (self._unsafe_bytes_len and unquoted in self._unsafe) or + (self._has_ignore and unquoted in self._ignore) + ): + ret.append(self._quoter(unquoted)) + else: + ret.append(unquoted) + continue + else: + ch = '%' + + if buflen: + start_pct = idx - 1 - buflen * 3 + ret.append(val[start_pct : idx - 1]) + buflen = 0 + + if ch == '+': + if ( + (not self._qs and not self._plus) or + (self._unsafe_bytes_len and self._is_char_unsafe(ch)) + ): + ret.append('+') + else: + changed = 1 + ret.append(' ') + continue + + if self._unsafe_bytes_len and self._is_char_unsafe(ch): + changed = 1 + ret.append('%') + h = hex(ord(ch)).upper()[2:] + for ch in h: + ret.append(ch) + continue + + ret.append(ch) + + if not changed: + return val + + if buflen: + ret.append(val[length - buflen * 3 : length]) + + return ''.join(ret) + + cdef inline bint _is_char_unsafe(self, Py_UCS4 ch): + for i in range(self._unsafe_bytes_len): + if ch == self._unsafe_bytes_char[i]: + return True + return False diff --git a/venv/lib/python3.10/site-packages/yarl/_quoting_py.py b/venv/lib/python3.10/site-packages/yarl/_quoting_py.py new file mode 100644 index 0000000000000000000000000000000000000000..4cc47bc675b0b34a2a11306d0bfc1cba1a04c8a8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/yarl/_quoting_py.py @@ -0,0 +1,213 @@ +import codecs +import re +from string import ascii_letters, ascii_lowercase, digits +from typing import Union, cast, overload + +BASCII_LOWERCASE = ascii_lowercase.encode("ascii") +BPCT_ALLOWED = {f"%{i:02X}".encode("ascii") for i in range(256)} +GEN_DELIMS = ":/?#[]@" +SUB_DELIMS_WITHOUT_QS = "!$'()*," +SUB_DELIMS = SUB_DELIMS_WITHOUT_QS + "+&=;" +RESERVED = GEN_DELIMS + SUB_DELIMS +UNRESERVED = ascii_letters + digits + "-._~" +ALLOWED = UNRESERVED + SUB_DELIMS_WITHOUT_QS + + +_IS_HEX = re.compile(b"[A-Z0-9][A-Z0-9]") +_IS_HEX_STR = re.compile("[A-Fa-f0-9][A-Fa-f0-9]") + +utf8_decoder = codecs.getincrementaldecoder("utf-8") + + +class _Quoter: + def __init__( + self, + *, + safe: str = "", + protected: str = "", + qs: bool = False, + requote: bool = True, + ) -> None: + self._safe = safe + self._protected = protected + self._qs = qs + self._requote = requote + + @overload + def __call__(self, val: str) -> str: ... + @overload + def __call__(self, val: None) -> None: ... + def __call__(self, val: Union[str, None]) -> Union[str, None]: + if val is None: + return None + if not isinstance(val, str): + raise TypeError("Argument should be str") + if not val: + return "" + bval = val.encode("utf8", errors="ignore") + ret = bytearray() + pct = bytearray() + safe = self._safe + safe += ALLOWED + if not self._qs: + safe += "+&=;" + safe += self._protected + bsafe = safe.encode("ascii") + idx = 0 + while idx < len(bval): + ch = bval[idx] + idx += 1 + + if pct: + if ch in BASCII_LOWERCASE: + ch = ch - 32 # convert to uppercase + pct.append(ch) + if len(pct) == 3: # pragma: no branch # peephole optimizer + buf = pct[1:] + if not _IS_HEX.match(buf): + ret.extend(b"%25") + pct.clear() + idx -= 2 + continue + try: + unquoted = chr(int(pct[1:].decode("ascii"), base=16)) + except ValueError: + ret.extend(b"%25") + pct.clear() + idx -= 2 + continue + + if unquoted in self._protected: + ret.extend(pct) + elif unquoted in safe: + ret.append(ord(unquoted)) + else: + ret.extend(pct) + pct.clear() + + # special case, if we have only one char after "%" + elif len(pct) == 2 and idx == len(bval): + ret.extend(b"%25") + pct.clear() + idx -= 1 + + continue + + elif ch == ord("%") and self._requote: + pct.clear() + pct.append(ch) + + # special case if "%" is last char + if idx == len(bval): + ret.extend(b"%25") + + continue + + if self._qs and ch == ord(" "): + ret.append(ord("+")) + continue + if ch in bsafe: + ret.append(ch) + continue + + ret.extend((f"%{ch:02X}").encode("ascii")) + + ret2 = ret.decode("ascii") + if ret2 == val: + return val + return ret2 + + +class _Unquoter: + def __init__( + self, + *, + ignore: str = "", + unsafe: str = "", + qs: bool = False, + plus: bool = False, + ) -> None: + self._ignore = ignore + self._unsafe = unsafe + self._qs = qs + self._plus = plus # to match urllib.parse.unquote_plus + self._quoter = _Quoter() + self._qs_quoter = _Quoter(qs=True) + + @overload + def __call__(self, val: str) -> str: ... + @overload + def __call__(self, val: None) -> None: ... + def __call__(self, val: Union[str, None]) -> Union[str, None]: + if val is None: + return None + if not isinstance(val, str): + raise TypeError("Argument should be str") + if not val: + return "" + decoder = cast(codecs.BufferedIncrementalDecoder, utf8_decoder()) + ret = [] + idx = 0 + while idx < len(val): + ch = val[idx] + idx += 1 + if ch == "%" and idx <= len(val) - 2: + pct = val[idx : idx + 2] + if _IS_HEX_STR.fullmatch(pct): + b = bytes([int(pct, base=16)]) + idx += 2 + try: + unquoted = decoder.decode(b) + except UnicodeDecodeError: + start_pct = idx - 3 - len(decoder.buffer) * 3 + ret.append(val[start_pct : idx - 3]) + decoder.reset() + try: + unquoted = decoder.decode(b) + except UnicodeDecodeError: + ret.append(val[idx - 3 : idx]) + continue + if not unquoted: + continue + if self._qs and unquoted in "+=&;": + to_add = self._qs_quoter(unquoted) + if to_add is None: # pragma: no cover + raise RuntimeError("Cannot quote None") + ret.append(to_add) + elif unquoted in self._unsafe or unquoted in self._ignore: + to_add = self._quoter(unquoted) + if to_add is None: # pragma: no cover + raise RuntimeError("Cannot quote None") + ret.append(to_add) + else: + ret.append(unquoted) + continue + + if decoder.buffer: + start_pct = idx - 1 - len(decoder.buffer) * 3 + ret.append(val[start_pct : idx - 1]) + decoder.reset() + + if ch == "+": + if (not self._qs and not self._plus) or ch in self._unsafe: + ret.append("+") + else: + ret.append(" ") + continue + + if ch in self._unsafe: + ret.append("%") + h = hex(ord(ch)).upper()[2:] + for ch in h: + ret.append(ch) + continue + + ret.append(ch) + + if decoder.buffer: + ret.append(val[-len(decoder.buffer) * 3 :]) + + ret2 = "".join(ret) + if ret2 == val: + return val + return ret2 diff --git a/venv/lib/python3.10/site-packages/yarl/_url.py b/venv/lib/python3.10/site-packages/yarl/_url.py new file mode 100644 index 0000000000000000000000000000000000000000..1fa347f9c193e18da4f0ebd817b4589cda291da2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/yarl/_url.py @@ -0,0 +1,1604 @@ +import re +import sys +import warnings +from collections.abc import Mapping, Sequence +from enum import Enum +from functools import _CacheInfo, lru_cache +from ipaddress import ip_address +from typing import TYPE_CHECKING, Any, NoReturn, TypedDict, TypeVar, Union, overload +from urllib.parse import SplitResult, uses_relative + +import idna +from multidict import MultiDict, MultiDictProxy +from propcache.api import under_cached_property as cached_property + +from ._parse import ( + USES_AUTHORITY, + SplitURLType, + make_netloc, + query_to_pairs, + split_netloc, + split_url, + unsplit_result, +) +from ._path import normalize_path, normalize_path_segments +from ._query import ( + Query, + QueryVariable, + SimpleQuery, + get_str_query, + get_str_query_from_iterable, + get_str_query_from_sequence_iterable, +) +from ._quoters import ( + FRAGMENT_QUOTER, + FRAGMENT_REQUOTER, + PATH_QUOTER, + PATH_REQUOTER, + PATH_SAFE_UNQUOTER, + PATH_UNQUOTER, + QS_UNQUOTER, + QUERY_QUOTER, + QUERY_REQUOTER, + QUOTER, + REQUOTER, + UNQUOTER, + human_quote, +) + +DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443, "ftp": 21} +USES_RELATIVE = frozenset(uses_relative) + +# Special schemes https://url.spec.whatwg.org/#special-scheme +# are not allowed to have an empty host https://url.spec.whatwg.org/#url-representation +SCHEME_REQUIRES_HOST = frozenset(("http", "https", "ws", "wss", "ftp")) + + +# reg-name: unreserved / pct-encoded / sub-delims +# this pattern matches anything that is *not* in those classes. and is only used +# on lower-cased ASCII values. +NOT_REG_NAME = re.compile( + r""" + # any character not in the unreserved or sub-delims sets, plus % + # (validated with the additional check for pct-encoded sequences below) + [^a-z0-9\-._~!$&'()*+,;=%] + | + # % only allowed if it is part of a pct-encoded + # sequence of 2 hex digits. + %(?![0-9a-f]{2}) + """, + re.VERBOSE, +) + +_T = TypeVar("_T") + +if sys.version_info >= (3, 11): + from typing import Self +else: + Self = Any + + +class UndefinedType(Enum): + """Singleton type for use with not set sentinel values.""" + + _singleton = 0 + + +UNDEFINED = UndefinedType._singleton + + +class CacheInfo(TypedDict): + """Host encoding cache.""" + + idna_encode: _CacheInfo + idna_decode: _CacheInfo + ip_address: _CacheInfo + host_validate: _CacheInfo + encode_host: _CacheInfo + + +class _InternalURLCache(TypedDict, total=False): + _val: SplitURLType + _origin: "URL" + absolute: bool + hash: int + scheme: str + raw_authority: str + authority: str + raw_user: Union[str, None] + user: Union[str, None] + raw_password: Union[str, None] + password: Union[str, None] + raw_host: Union[str, None] + host: Union[str, None] + host_subcomponent: Union[str, None] + host_port_subcomponent: Union[str, None] + port: Union[int, None] + explicit_port: Union[int, None] + raw_path: str + path: str + _parsed_query: list[tuple[str, str]] + query: "MultiDictProxy[str]" + raw_query_string: str + query_string: str + path_qs: str + raw_path_qs: str + raw_fragment: str + fragment: str + raw_parts: tuple[str, ...] + parts: tuple[str, ...] + parent: "URL" + raw_name: str + name: str + raw_suffix: str + suffix: str + raw_suffixes: tuple[str, ...] + suffixes: tuple[str, ...] + + +def rewrite_module(obj: _T) -> _T: + obj.__module__ = "yarl" + return obj + + +@lru_cache +def encode_url(url_str: str) -> "URL": + """Parse unencoded URL.""" + cache: _InternalURLCache = {} + host: Union[str, None] + scheme, netloc, path, query, fragment = split_url(url_str) + if not netloc: # netloc + host = "" + else: + if ":" in netloc or "@" in netloc or "[" in netloc: + # Complex netloc + username, password, host, port = split_netloc(netloc) + else: + username = password = port = None + host = netloc + if host is None: + if scheme in SCHEME_REQUIRES_HOST: + msg = ( + "Invalid URL: host is required for " + f"absolute urls with the {scheme} scheme" + ) + raise ValueError(msg) + else: + host = "" + host = _encode_host(host, validate_host=False) + # Remove brackets as host encoder adds back brackets for IPv6 addresses + cache["raw_host"] = host[1:-1] if "[" in host else host + cache["explicit_port"] = port + if password is None and username is None: + # Fast path for URLs without user, password + netloc = host if port is None else f"{host}:{port}" + cache["raw_user"] = None + cache["raw_password"] = None + else: + raw_user = REQUOTER(username) if username else username + raw_password = REQUOTER(password) if password else password + netloc = make_netloc(raw_user, raw_password, host, port) + cache["raw_user"] = raw_user + cache["raw_password"] = raw_password + + if path: + path = PATH_REQUOTER(path) + if netloc and "." in path: + path = normalize_path(path) + if query: + query = QUERY_REQUOTER(query) + if fragment: + fragment = FRAGMENT_REQUOTER(fragment) + + cache["scheme"] = scheme + cache["raw_path"] = "/" if not path and netloc else path + cache["raw_query_string"] = query + cache["raw_fragment"] = fragment + + self = object.__new__(URL) + self._scheme = scheme + self._netloc = netloc + self._path = path + self._query = query + self._fragment = fragment + self._cache = cache + return self + + +@lru_cache +def pre_encoded_url(url_str: str) -> "URL": + """Parse pre-encoded URL.""" + self = object.__new__(URL) + val = split_url(url_str) + self._scheme, self._netloc, self._path, self._query, self._fragment = val + self._cache = {} + return self + + +@lru_cache +def build_pre_encoded_url( + scheme: str, + authority: str, + user: Union[str, None], + password: Union[str, None], + host: str, + port: Union[int, None], + path: str, + query_string: str, + fragment: str, +) -> "URL": + """Build a pre-encoded URL from parts.""" + self = object.__new__(URL) + self._scheme = scheme + if authority: + self._netloc = authority + elif host: + if port is not None: + port = None if port == DEFAULT_PORTS.get(scheme) else port + if user is None and password is None: + self._netloc = host if port is None else f"{host}:{port}" + else: + self._netloc = make_netloc(user, password, host, port) + else: + self._netloc = "" + self._path = path + self._query = query_string + self._fragment = fragment + self._cache = {} + return self + + +def from_parts_uncached( + scheme: str, netloc: str, path: str, query: str, fragment: str +) -> "URL": + """Create a new URL from parts.""" + self = object.__new__(URL) + self._scheme = scheme + self._netloc = netloc + self._path = path + self._query = query + self._fragment = fragment + self._cache = {} + return self + + +from_parts = lru_cache(from_parts_uncached) + + +@rewrite_module +class URL: + # Don't derive from str + # follow pathlib.Path design + # probably URL will not suffer from pathlib problems: + # it's intended for libraries like aiohttp, + # not to be passed into standard library functions like os.open etc. + + # URL grammar (RFC 3986) + # pct-encoded = "%" HEXDIG HEXDIG + # reserved = gen-delims / sub-delims + # gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" + # sub-delims = "!" / "$" / "&" / "'" / "(" / ")" + # / "*" / "+" / "," / ";" / "=" + # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + # URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] + # hier-part = "//" authority path-abempty + # / path-absolute + # / path-rootless + # / path-empty + # scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + # authority = [ userinfo "@" ] host [ ":" port ] + # userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) + # host = IP-literal / IPv4address / reg-name + # IP-literal = "[" ( IPv6address / IPvFuture ) "]" + # IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) + # IPv6address = 6( h16 ":" ) ls32 + # / "::" 5( h16 ":" ) ls32 + # / [ h16 ] "::" 4( h16 ":" ) ls32 + # / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + # / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + # / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + # / [ *4( h16 ":" ) h16 ] "::" ls32 + # / [ *5( h16 ":" ) h16 ] "::" h16 + # / [ *6( h16 ":" ) h16 ] "::" + # ls32 = ( h16 ":" h16 ) / IPv4address + # ; least-significant 32 bits of address + # h16 = 1*4HEXDIG + # ; 16 bits of address represented in hexadecimal + # IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet + # dec-octet = DIGIT ; 0-9 + # / %x31-39 DIGIT ; 10-99 + # / "1" 2DIGIT ; 100-199 + # / "2" %x30-34 DIGIT ; 200-249 + # / "25" %x30-35 ; 250-255 + # reg-name = *( unreserved / pct-encoded / sub-delims ) + # port = *DIGIT + # path = path-abempty ; begins with "/" or is empty + # / path-absolute ; begins with "/" but not "//" + # / path-noscheme ; begins with a non-colon segment + # / path-rootless ; begins with a segment + # / path-empty ; zero characters + # path-abempty = *( "/" segment ) + # path-absolute = "/" [ segment-nz *( "/" segment ) ] + # path-noscheme = segment-nz-nc *( "/" segment ) + # path-rootless = segment-nz *( "/" segment ) + # path-empty = 0 + # segment = *pchar + # segment-nz = 1*pchar + # segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" ) + # ; non-zero-length segment without any colon ":" + # pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + # query = *( pchar / "/" / "?" ) + # fragment = *( pchar / "/" / "?" ) + # URI-reference = URI / relative-ref + # relative-ref = relative-part [ "?" query ] [ "#" fragment ] + # relative-part = "//" authority path-abempty + # / path-absolute + # / path-noscheme + # / path-empty + # absolute-URI = scheme ":" hier-part [ "?" query ] + __slots__ = ("_cache", "_scheme", "_netloc", "_path", "_query", "_fragment") + + _cache: _InternalURLCache + _scheme: str + _netloc: str + _path: str + _query: str + _fragment: str + + def __new__( + cls, + val: Union[str, SplitResult, "URL", UndefinedType] = UNDEFINED, + *, + encoded: bool = False, + strict: Union[bool, None] = None, + ) -> "URL": + if strict is not None: # pragma: no cover + warnings.warn("strict parameter is ignored") + if type(val) is str: + return pre_encoded_url(val) if encoded else encode_url(val) + if type(val) is cls: + return val + if type(val) is SplitResult: + if not encoded: + raise ValueError("Cannot apply decoding to SplitResult") + return from_parts(*val) + if isinstance(val, str): + return pre_encoded_url(str(val)) if encoded else encode_url(str(val)) + if val is UNDEFINED: + # Special case for UNDEFINED since it might be unpickling and we do + # not want to cache as the `__set_state__` call would mutate the URL + # object in the `pre_encoded_url` or `encoded_url` caches. + self = object.__new__(URL) + self._scheme = self._netloc = self._path = self._query = self._fragment = "" + self._cache = {} + return self + raise TypeError("Constructor parameter should be str") + + @classmethod + def build( + cls, + *, + scheme: str = "", + authority: str = "", + user: Union[str, None] = None, + password: Union[str, None] = None, + host: str = "", + port: Union[int, None] = None, + path: str = "", + query: Union[Query, None] = None, + query_string: str = "", + fragment: str = "", + encoded: bool = False, + ) -> "URL": + """Creates and returns a new URL""" + + if authority and (user or password or host or port): + raise ValueError( + 'Can\'t mix "authority" with "user", "password", "host" or "port".' + ) + if port is not None and not isinstance(port, int): + raise TypeError(f"The port is required to be int, got {type(port)!r}.") + if port and not host: + raise ValueError('Can\'t build URL with "port" but without "host".') + if query and query_string: + raise ValueError('Only one of "query" or "query_string" should be passed') + if ( + scheme is None # type: ignore[redundant-expr] + or authority is None # type: ignore[redundant-expr] + or host is None # type: ignore[redundant-expr] + or path is None # type: ignore[redundant-expr] + or query_string is None # type: ignore[redundant-expr] + or fragment is None + ): + raise TypeError( + 'NoneType is illegal for "scheme", "authority", "host", "path", ' + '"query_string", and "fragment" args, use empty string instead.' + ) + + if query: + query_string = get_str_query(query) or "" + + if encoded: + return build_pre_encoded_url( + scheme, + authority, + user, + password, + host, + port, + path, + query_string, + fragment, + ) + + self = object.__new__(URL) + self._scheme = scheme + _host: Union[str, None] = None + if authority: + user, password, _host, port = split_netloc(authority) + _host = _encode_host(_host, validate_host=False) if _host else "" + elif host: + _host = _encode_host(host, validate_host=True) + else: + self._netloc = "" + + if _host is not None: + if port is not None: + port = None if port == DEFAULT_PORTS.get(scheme) else port + if user is None and password is None: + self._netloc = _host if port is None else f"{_host}:{port}" + else: + self._netloc = make_netloc(user, password, _host, port, True) + + path = PATH_QUOTER(path) if path else path + if path and self._netloc: + if "." in path: + path = normalize_path(path) + if path[0] != "/": + msg = ( + "Path in a URL with authority should " + "start with a slash ('/') if set" + ) + raise ValueError(msg) + + self._path = path + if not query and query_string: + query_string = QUERY_QUOTER(query_string) + self._query = query_string + self._fragment = FRAGMENT_QUOTER(fragment) if fragment else fragment + self._cache = {} + return self + + def __init_subclass__(cls) -> NoReturn: + raise TypeError(f"Inheriting a class {cls!r} from URL is forbidden") + + def __str__(self) -> str: + if not self._path and self._netloc and (self._query or self._fragment): + path = "/" + else: + path = self._path + if (port := self.explicit_port) is not None and port == DEFAULT_PORTS.get( + self._scheme + ): + # port normalization - using None for default ports to remove from rendering + # https://datatracker.ietf.org/doc/html/rfc3986.html#section-6.2.3 + host = self.host_subcomponent + netloc = make_netloc(self.raw_user, self.raw_password, host, None) + else: + netloc = self._netloc + return unsplit_result(self._scheme, netloc, path, self._query, self._fragment) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}('{str(self)}')" + + def __bytes__(self) -> bytes: + return str(self).encode("ascii") + + def __eq__(self, other: object) -> bool: + if type(other) is not URL: + return NotImplemented + + path1 = "/" if not self._path and self._netloc else self._path + path2 = "/" if not other._path and other._netloc else other._path + return ( + self._scheme == other._scheme + and self._netloc == other._netloc + and path1 == path2 + and self._query == other._query + and self._fragment == other._fragment + ) + + def __hash__(self) -> int: + if (ret := self._cache.get("hash")) is None: + path = "/" if not self._path and self._netloc else self._path + ret = self._cache["hash"] = hash( + (self._scheme, self._netloc, path, self._query, self._fragment) + ) + return ret + + def __le__(self, other: object) -> bool: + if type(other) is not URL: + return NotImplemented + return self._val <= other._val + + def __lt__(self, other: object) -> bool: + if type(other) is not URL: + return NotImplemented + return self._val < other._val + + def __ge__(self, other: object) -> bool: + if type(other) is not URL: + return NotImplemented + return self._val >= other._val + + def __gt__(self, other: object) -> bool: + if type(other) is not URL: + return NotImplemented + return self._val > other._val + + def __truediv__(self, name: str) -> "URL": + if not isinstance(name, str): + return NotImplemented # type: ignore[unreachable] + return self._make_child((str(name),)) + + def __mod__(self, query: Query) -> "URL": + return self.update_query(query) + + def __bool__(self) -> bool: + return bool(self._netloc or self._path or self._query or self._fragment) + + def __getstate__(self) -> tuple[SplitResult]: + return (tuple.__new__(SplitResult, self._val),) + + def __setstate__( + self, state: Union[tuple[SplitURLType], tuple[None, _InternalURLCache]] + ) -> None: + if state[0] is None and isinstance(state[1], dict): + # default style pickle + val = state[1]["_val"] + else: + unused: list[object] + val, *unused = state + self._scheme, self._netloc, self._path, self._query, self._fragment = val + self._cache = {} + + def _cache_netloc(self) -> None: + """Cache the netloc parts of the URL.""" + c = self._cache + split_loc = split_netloc(self._netloc) + c["raw_user"], c["raw_password"], c["raw_host"], c["explicit_port"] = split_loc + + def is_absolute(self) -> bool: + """A check for absolute URLs. + + Return True for absolute ones (having scheme or starting + with //), False otherwise. + + Is is preferred to call the .absolute property instead + as it is cached. + """ + return self.absolute + + def is_default_port(self) -> bool: + """A check for default port. + + Return True if port is default for specified scheme, + e.g. 'http://python.org' or 'http://python.org:80', False + otherwise. + + Return False for relative URLs. + + """ + if (explicit := self.explicit_port) is None: + # If the explicit port is None, then the URL must be + # using the default port unless its a relative URL + # which does not have an implicit port / default port + return self._netloc != "" + return explicit == DEFAULT_PORTS.get(self._scheme) + + def origin(self) -> "URL": + """Return an URL with scheme, host and port parts only. + + user, password, path, query and fragment are removed. + + """ + # TODO: add a keyword-only option for keeping user/pass maybe? + return self._origin + + @cached_property + def _val(self) -> SplitURLType: + return (self._scheme, self._netloc, self._path, self._query, self._fragment) + + @cached_property + def _origin(self) -> "URL": + """Return an URL with scheme, host and port parts only. + + user, password, path, query and fragment are removed. + """ + if not (netloc := self._netloc): + raise ValueError("URL should be absolute") + if not (scheme := self._scheme): + raise ValueError("URL should have scheme") + if "@" in netloc: + encoded_host = self.host_subcomponent + netloc = make_netloc(None, None, encoded_host, self.explicit_port) + elif not self._path and not self._query and not self._fragment: + return self + return from_parts(scheme, netloc, "", "", "") + + def relative(self) -> "URL": + """Return a relative part of the URL. + + scheme, user, password, host and port are removed. + + """ + if not self._netloc: + raise ValueError("URL should be absolute") + return from_parts("", "", self._path, self._query, self._fragment) + + @cached_property + def absolute(self) -> bool: + """A check for absolute URLs. + + Return True for absolute ones (having scheme or starting + with //), False otherwise. + + """ + # `netloc`` is an empty string for relative URLs + # Checking `netloc` is faster than checking `hostname` + # because `hostname` is a property that does some extra work + # to parse the host from the `netloc` + return self._netloc != "" + + @cached_property + def scheme(self) -> str: + """Scheme for absolute URLs. + + Empty string for relative URLs or URLs starting with // + + """ + return self._scheme + + @cached_property + def raw_authority(self) -> str: + """Encoded authority part of URL. + + Empty string for relative URLs. + + """ + return self._netloc + + @cached_property + def authority(self) -> str: + """Decoded authority part of URL. + + Empty string for relative URLs. + + """ + return make_netloc(self.user, self.password, self.host, self.port) + + @cached_property + def raw_user(self) -> Union[str, None]: + """Encoded user part of URL. + + None if user is missing. + + """ + # not .username + self._cache_netloc() + return self._cache["raw_user"] + + @cached_property + def user(self) -> Union[str, None]: + """Decoded user part of URL. + + None if user is missing. + + """ + if (raw_user := self.raw_user) is None: + return None + return UNQUOTER(raw_user) + + @cached_property + def raw_password(self) -> Union[str, None]: + """Encoded password part of URL. + + None if password is missing. + + """ + self._cache_netloc() + return self._cache["raw_password"] + + @cached_property + def password(self) -> Union[str, None]: + """Decoded password part of URL. + + None if password is missing. + + """ + if (raw_password := self.raw_password) is None: + return None + return UNQUOTER(raw_password) + + @cached_property + def raw_host(self) -> Union[str, None]: + """Encoded host part of URL. + + None for relative URLs. + + When working with IPv6 addresses, use the `host_subcomponent` property instead + as it will return the host subcomponent with brackets. + """ + # Use host instead of hostname for sake of shortness + # May add .hostname prop later + self._cache_netloc() + return self._cache["raw_host"] + + @cached_property + def host(self) -> Union[str, None]: + """Decoded host part of URL. + + None for relative URLs. + + """ + if (raw := self.raw_host) is None: + return None + if raw and raw[-1].isdigit() or ":" in raw: + # IP addresses are never IDNA encoded + return raw + return _idna_decode(raw) + + @cached_property + def host_subcomponent(self) -> Union[str, None]: + """Return the host subcomponent part of URL. + + None for relative URLs. + + https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2 + + `IP-literal = "[" ( IPv6address / IPvFuture ) "]"` + + Examples: + - `http://example.com:8080` -> `example.com` + - `http://example.com:80` -> `example.com` + - `https://127.0.0.1:8443` -> `127.0.0.1` + - `https://[::1]:8443` -> `[::1]` + - `http://[::1]` -> `[::1]` + + """ + if (raw := self.raw_host) is None: + return None + return f"[{raw}]" if ":" in raw else raw + + @cached_property + def host_port_subcomponent(self) -> Union[str, None]: + """Return the host and port subcomponent part of URL. + + Trailing dots are removed from the host part. + + This value is suitable for use in the Host header of an HTTP request. + + None for relative URLs. + + https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2 + `IP-literal = "[" ( IPv6address / IPvFuture ) "]"` + https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.3 + port = *DIGIT + + Examples: + - `http://example.com:8080` -> `example.com:8080` + - `http://example.com:80` -> `example.com` + - `http://example.com.:80` -> `example.com` + - `https://127.0.0.1:8443` -> `127.0.0.1:8443` + - `https://[::1]:8443` -> `[::1]:8443` + - `http://[::1]` -> `[::1]` + + """ + if (raw := self.raw_host) is None: + return None + if raw[-1] == ".": + # Remove all trailing dots from the netloc as while + # they are valid FQDNs in DNS, TLS validation fails. + # See https://github.com/aio-libs/aiohttp/issues/3636. + # To avoid string manipulation we only call rstrip if + # the last character is a dot. + raw = raw.rstrip(".") + port = self.explicit_port + if port is None or port == DEFAULT_PORTS.get(self._scheme): + return f"[{raw}]" if ":" in raw else raw + return f"[{raw}]:{port}" if ":" in raw else f"{raw}:{port}" + + @cached_property + def port(self) -> Union[int, None]: + """Port part of URL, with scheme-based fallback. + + None for relative URLs or URLs without explicit port and + scheme without default port substitution. + + """ + if (explicit_port := self.explicit_port) is not None: + return explicit_port + return DEFAULT_PORTS.get(self._scheme) + + @cached_property + def explicit_port(self) -> Union[int, None]: + """Port part of URL, without scheme-based fallback. + + None for relative URLs or URLs without explicit port. + + """ + self._cache_netloc() + return self._cache["explicit_port"] + + @cached_property + def raw_path(self) -> str: + """Encoded path of URL. + + / for absolute URLs without path part. + + """ + return self._path if self._path or not self._netloc else "/" + + @cached_property + def path(self) -> str: + """Decoded path of URL. + + / for absolute URLs without path part. + + """ + return PATH_UNQUOTER(self._path) if self._path else "/" if self._netloc else "" + + @cached_property + def path_safe(self) -> str: + """Decoded path of URL. + + / for absolute URLs without path part. + + / (%2F) and % (%25) are not decoded + + """ + if self._path: + return PATH_SAFE_UNQUOTER(self._path) + return "/" if self._netloc else "" + + @cached_property + def _parsed_query(self) -> list[tuple[str, str]]: + """Parse query part of URL.""" + return query_to_pairs(self._query) + + @cached_property + def query(self) -> "MultiDictProxy[str]": + """A MultiDictProxy representing parsed query parameters in decoded + representation. + + Empty value if URL has no query part. + + """ + return MultiDictProxy(MultiDict(self._parsed_query)) + + @cached_property + def raw_query_string(self) -> str: + """Encoded query part of URL. + + Empty string if query is missing. + + """ + return self._query + + @cached_property + def query_string(self) -> str: + """Decoded query part of URL. + + Empty string if query is missing. + + """ + return QS_UNQUOTER(self._query) if self._query else "" + + @cached_property + def path_qs(self) -> str: + """Decoded path of URL with query.""" + return self.path if not (q := self.query_string) else f"{self.path}?{q}" + + @cached_property + def raw_path_qs(self) -> str: + """Encoded path of URL with query.""" + if q := self._query: + return f"{self._path}?{q}" if self._path or not self._netloc else f"/?{q}" + return self._path if self._path or not self._netloc else "/" + + @cached_property + def raw_fragment(self) -> str: + """Encoded fragment part of URL. + + Empty string if fragment is missing. + + """ + return self._fragment + + @cached_property + def fragment(self) -> str: + """Decoded fragment part of URL. + + Empty string if fragment is missing. + + """ + return UNQUOTER(self._fragment) if self._fragment else "" + + @cached_property + def raw_parts(self) -> tuple[str, ...]: + """A tuple containing encoded *path* parts. + + ('/',) for absolute URLs if *path* is missing. + + """ + path = self._path + if self._netloc: + return ("/", *path[1:].split("/")) if path else ("/",) + if path and path[0] == "/": + return ("/", *path[1:].split("/")) + return tuple(path.split("/")) + + @cached_property + def parts(self) -> tuple[str, ...]: + """A tuple containing decoded *path* parts. + + ('/',) for absolute URLs if *path* is missing. + + """ + return tuple(UNQUOTER(part) for part in self.raw_parts) + + @cached_property + def parent(self) -> "URL": + """A new URL with last part of path removed and cleaned up query and + fragment. + + """ + path = self._path + if not path or path == "/": + if self._fragment or self._query: + return from_parts(self._scheme, self._netloc, path, "", "") + return self + parts = path.split("/") + return from_parts(self._scheme, self._netloc, "/".join(parts[:-1]), "", "") + + @cached_property + def raw_name(self) -> str: + """The last part of raw_parts.""" + parts = self.raw_parts + if not self._netloc: + return parts[-1] + parts = parts[1:] + return parts[-1] if parts else "" + + @cached_property + def name(self) -> str: + """The last part of parts.""" + return UNQUOTER(self.raw_name) + + @cached_property + def raw_suffix(self) -> str: + name = self.raw_name + i = name.rfind(".") + return name[i:] if 0 < i < len(name) - 1 else "" + + @cached_property + def suffix(self) -> str: + return UNQUOTER(self.raw_suffix) + + @cached_property + def raw_suffixes(self) -> tuple[str, ...]: + name = self.raw_name + if name.endswith("."): + return () + name = name.lstrip(".") + return tuple("." + suffix for suffix in name.split(".")[1:]) + + @cached_property + def suffixes(self) -> tuple[str, ...]: + return tuple(UNQUOTER(suffix) for suffix in self.raw_suffixes) + + def _make_child(self, paths: "Sequence[str]", encoded: bool = False) -> "URL": + """ + add paths to self._path, accounting for absolute vs relative paths, + keep existing, but do not create new, empty segments + """ + parsed: list[str] = [] + needs_normalize: bool = False + for idx, path in enumerate(reversed(paths)): + # empty segment of last is not removed + last = idx == 0 + if path and path[0] == "/": + raise ValueError( + f"Appending path {path!r} starting from slash is forbidden" + ) + # We need to quote the path if it is not already encoded + # This cannot be done at the end because the existing + # path is already quoted and we do not want to double quote + # the existing path. + path = path if encoded else PATH_QUOTER(path) + needs_normalize |= "." in path + segments = path.split("/") + segments.reverse() + # remove trailing empty segment for all but the last path + parsed += segments[1:] if not last and segments[0] == "" else segments + + if (path := self._path) and (old_segments := path.split("/")): + # If the old path ends with a slash, the last segment is an empty string + # and should be removed before adding the new path segments. + old = old_segments[:-1] if old_segments[-1] == "" else old_segments + old.reverse() + parsed += old + + # If the netloc is present, inject a leading slash when adding a + # path to an absolute URL where there was none before. + if (netloc := self._netloc) and parsed and parsed[-1] != "": + parsed.append("") + + parsed.reverse() + if not netloc or not needs_normalize: + return from_parts(self._scheme, netloc, "/".join(parsed), "", "") + + path = "/".join(normalize_path_segments(parsed)) + # If normalizing the path segments removed the leading slash, add it back. + if path and path[0] != "/": + path = f"/{path}" + return from_parts(self._scheme, netloc, path, "", "") + + def with_scheme(self, scheme: str) -> "URL": + """Return a new URL with scheme replaced.""" + # N.B. doesn't cleanup query/fragment + if not isinstance(scheme, str): + raise TypeError("Invalid scheme type") + lower_scheme = scheme.lower() + netloc = self._netloc + if not netloc and lower_scheme in SCHEME_REQUIRES_HOST: + msg = ( + "scheme replacement is not allowed for " + f"relative URLs for the {lower_scheme} scheme" + ) + raise ValueError(msg) + return from_parts(lower_scheme, netloc, self._path, self._query, self._fragment) + + def with_user(self, user: Union[str, None]) -> "URL": + """Return a new URL with user replaced. + + Autoencode user if needed. + + Clear user/password if user is None. + + """ + # N.B. doesn't cleanup query/fragment + if user is None: + password = None + elif isinstance(user, str): + user = QUOTER(user) + password = self.raw_password + else: + raise TypeError("Invalid user type") + if not (netloc := self._netloc): + raise ValueError("user replacement is not allowed for relative URLs") + encoded_host = self.host_subcomponent or "" + netloc = make_netloc(user, password, encoded_host, self.explicit_port) + return from_parts(self._scheme, netloc, self._path, self._query, self._fragment) + + def with_password(self, password: Union[str, None]) -> "URL": + """Return a new URL with password replaced. + + Autoencode password if needed. + + Clear password if argument is None. + + """ + # N.B. doesn't cleanup query/fragment + if password is None: + pass + elif isinstance(password, str): + password = QUOTER(password) + else: + raise TypeError("Invalid password type") + if not (netloc := self._netloc): + raise ValueError("password replacement is not allowed for relative URLs") + encoded_host = self.host_subcomponent or "" + port = self.explicit_port + netloc = make_netloc(self.raw_user, password, encoded_host, port) + return from_parts(self._scheme, netloc, self._path, self._query, self._fragment) + + def with_host(self, host: str) -> "URL": + """Return a new URL with host replaced. + + Autoencode host if needed. + + Changing host for relative URLs is not allowed, use .join() + instead. + + """ + # N.B. doesn't cleanup query/fragment + if not isinstance(host, str): + raise TypeError("Invalid host type") + if not (netloc := self._netloc): + raise ValueError("host replacement is not allowed for relative URLs") + if not host: + raise ValueError("host removing is not allowed") + encoded_host = _encode_host(host, validate_host=True) if host else "" + port = self.explicit_port + netloc = make_netloc(self.raw_user, self.raw_password, encoded_host, port) + return from_parts(self._scheme, netloc, self._path, self._query, self._fragment) + + def with_port(self, port: Union[int, None]) -> "URL": + """Return a new URL with port replaced. + + Clear port to default if None is passed. + + """ + # N.B. doesn't cleanup query/fragment + if port is not None: + if isinstance(port, bool) or not isinstance(port, int): + raise TypeError(f"port should be int or None, got {type(port)}") + if not (0 <= port <= 65535): + raise ValueError(f"port must be between 0 and 65535, got {port}") + if not (netloc := self._netloc): + raise ValueError("port replacement is not allowed for relative URLs") + encoded_host = self.host_subcomponent or "" + netloc = make_netloc(self.raw_user, self.raw_password, encoded_host, port) + return from_parts(self._scheme, netloc, self._path, self._query, self._fragment) + + def with_path( + self, + path: str, + *, + encoded: bool = False, + keep_query: bool = False, + keep_fragment: bool = False, + ) -> "URL": + """Return a new URL with path replaced.""" + netloc = self._netloc + if not encoded: + path = PATH_QUOTER(path) + if netloc: + path = normalize_path(path) if "." in path else path + if path and path[0] != "/": + path = f"/{path}" + query = self._query if keep_query else "" + fragment = self._fragment if keep_fragment else "" + return from_parts(self._scheme, netloc, path, query, fragment) + + @overload + def with_query(self, query: Query) -> "URL": ... + + @overload + def with_query(self, **kwargs: QueryVariable) -> "URL": ... + + def with_query(self, *args: Any, **kwargs: Any) -> "URL": + """Return a new URL with query part replaced. + + Accepts any Mapping (e.g. dict, multidict.MultiDict instances) + or str, autoencode the argument if needed. + + A sequence of (key, value) pairs is supported as well. + + It also can take an arbitrary number of keyword arguments. + + Clear query if None is passed. + + """ + # N.B. doesn't cleanup query/fragment + query = get_str_query(*args, **kwargs) or "" + return from_parts_uncached( + self._scheme, self._netloc, self._path, query, self._fragment + ) + + @overload + def extend_query(self, query: Query) -> "URL": ... + + @overload + def extend_query(self, **kwargs: QueryVariable) -> "URL": ... + + def extend_query(self, *args: Any, **kwargs: Any) -> "URL": + """Return a new URL with query part combined with the existing. + + This method will not remove existing query parameters. + + Example: + >>> url = URL('http://example.com/?a=1&b=2') + >>> url.extend_query(a=3, c=4) + URL('http://example.com/?a=1&b=2&a=3&c=4') + """ + if not (new_query := get_str_query(*args, **kwargs)): + return self + if query := self._query: + # both strings are already encoded so we can use a simple + # string join + query += new_query if query[-1] == "&" else f"&{new_query}" + else: + query = new_query + return from_parts_uncached( + self._scheme, self._netloc, self._path, query, self._fragment + ) + + @overload + def update_query(self, query: Query) -> "URL": ... + + @overload + def update_query(self, **kwargs: QueryVariable) -> "URL": ... + + def update_query(self, *args: Any, **kwargs: Any) -> "URL": + """Return a new URL with query part updated. + + This method will overwrite existing query parameters. + + Example: + >>> url = URL('http://example.com/?a=1&b=2') + >>> url.update_query(a=3, c=4) + URL('http://example.com/?a=3&b=2&c=4') + """ + in_query: Union[str, Mapping[str, QueryVariable], None] + if kwargs: + if args: + msg = "Either kwargs or single query parameter must be present" + raise ValueError(msg) + in_query = kwargs + elif len(args) == 1: + in_query = args[0] + else: + raise ValueError("Either kwargs or single query parameter must be present") + + if in_query is None: + query = "" + elif not in_query: + query = self._query + elif isinstance(in_query, Mapping): + qm: MultiDict[QueryVariable] = MultiDict(self._parsed_query) + qm.update(in_query) + query = get_str_query_from_sequence_iterable(qm.items()) + elif isinstance(in_query, str): + qstr: MultiDict[str] = MultiDict(self._parsed_query) + qstr.update(query_to_pairs(in_query)) + query = get_str_query_from_iterable(qstr.items()) + elif isinstance(in_query, (bytes, bytearray, memoryview)): # type: ignore[unreachable] + msg = "Invalid query type: bytes, bytearray and memoryview are forbidden" + raise TypeError(msg) + elif isinstance(in_query, Sequence): + # We don't expect sequence values if we're given a list of pairs + # already; only mappings like builtin `dict` which can't have the + # same key pointing to multiple values are allowed to use + # `_query_seq_pairs`. + qs: MultiDict[SimpleQuery] = MultiDict(self._parsed_query) + qs.update(in_query) + query = get_str_query_from_iterable(qs.items()) + else: + raise TypeError( + "Invalid query type: only str, mapping or " + "sequence of (key, value) pairs is allowed" + ) + return from_parts_uncached( + self._scheme, self._netloc, self._path, query, self._fragment + ) + + def without_query_params(self, *query_params: str) -> "URL": + """Remove some keys from query part and return new URL.""" + params_to_remove = set(query_params) & self.query.keys() + if not params_to_remove: + return self + return self.with_query( + tuple( + (name, value) + for name, value in self.query.items() + if name not in params_to_remove + ) + ) + + def with_fragment(self, fragment: Union[str, None]) -> "URL": + """Return a new URL with fragment replaced. + + Autoencode fragment if needed. + + Clear fragment to default if None is passed. + + """ + # N.B. doesn't cleanup query/fragment + if fragment is None: + raw_fragment = "" + elif not isinstance(fragment, str): + raise TypeError("Invalid fragment type") + else: + raw_fragment = FRAGMENT_QUOTER(fragment) + if self._fragment == raw_fragment: + return self + return from_parts( + self._scheme, self._netloc, self._path, self._query, raw_fragment + ) + + def with_name( + self, + name: str, + *, + keep_query: bool = False, + keep_fragment: bool = False, + ) -> "URL": + """Return a new URL with name (last part of path) replaced. + + Query and fragment parts are cleaned up. + + Name is encoded if needed. + + """ + # N.B. DOES cleanup query/fragment + if not isinstance(name, str): + raise TypeError("Invalid name type") + if "/" in name: + raise ValueError("Slash in name is not allowed") + name = PATH_QUOTER(name) + if name in (".", ".."): + raise ValueError(". and .. values are forbidden") + parts = list(self.raw_parts) + if netloc := self._netloc: + if len(parts) == 1: + parts.append(name) + else: + parts[-1] = name + parts[0] = "" # replace leading '/' + else: + parts[-1] = name + if parts[0] == "/": + parts[0] = "" # replace leading '/' + + query = self._query if keep_query else "" + fragment = self._fragment if keep_fragment else "" + return from_parts(self._scheme, netloc, "/".join(parts), query, fragment) + + def with_suffix( + self, + suffix: str, + *, + keep_query: bool = False, + keep_fragment: bool = False, + ) -> "URL": + """Return a new URL with suffix (file extension of name) replaced. + + Query and fragment parts are cleaned up. + + suffix is encoded if needed. + """ + if not isinstance(suffix, str): + raise TypeError("Invalid suffix type") + if suffix and not suffix[0] == "." or suffix == "." or "/" in suffix: + raise ValueError(f"Invalid suffix {suffix!r}") + name = self.raw_name + if not name: + raise ValueError(f"{self!r} has an empty name") + old_suffix = self.raw_suffix + suffix = PATH_QUOTER(suffix) + name = name + suffix if not old_suffix else name[: -len(old_suffix)] + suffix + if name in (".", ".."): + raise ValueError(". and .. values are forbidden") + parts = list(self.raw_parts) + if netloc := self._netloc: + if len(parts) == 1: + parts.append(name) + else: + parts[-1] = name + parts[0] = "" # replace leading '/' + else: + parts[-1] = name + if parts[0] == "/": + parts[0] = "" # replace leading '/' + + query = self._query if keep_query else "" + fragment = self._fragment if keep_fragment else "" + return from_parts(self._scheme, netloc, "/".join(parts), query, fragment) + + def join(self, url: "URL") -> "URL": + """Join URLs + + Construct a full (“absolute”) URL by combining a “base URL” + (self) with another URL (url). + + Informally, this uses components of the base URL, in + particular the addressing scheme, the network location and + (part of) the path, to provide missing components in the + relative URL. + + """ + if type(url) is not URL: + raise TypeError("url should be URL") + + scheme = url._scheme or self._scheme + if scheme != self._scheme or scheme not in USES_RELATIVE: + return url + + # scheme is in uses_authority as uses_authority is a superset of uses_relative + if (join_netloc := url._netloc) and scheme in USES_AUTHORITY: + return from_parts(scheme, join_netloc, url._path, url._query, url._fragment) + + orig_path = self._path + if join_path := url._path: + if join_path[0] == "/": + path = join_path + elif not orig_path: + path = f"/{join_path}" + elif orig_path[-1] == "/": + path = f"{orig_path}{join_path}" + else: + # … + # and relativizing ".." + # parts[0] is / for absolute urls, + # this join will add a double slash there + path = "/".join([*self.parts[:-1], ""]) + join_path + # which has to be removed + if orig_path[0] == "/": + path = path[1:] + path = normalize_path(path) if "." in path else path + else: + path = orig_path + + return from_parts( + scheme, + self._netloc, + path, + url._query if join_path or url._query else self._query, + url._fragment if join_path or url._fragment else self._fragment, + ) + + def joinpath(self, *other: str, encoded: bool = False) -> "URL": + """Return a new URL with the elements in other appended to the path.""" + return self._make_child(other, encoded=encoded) + + def human_repr(self) -> str: + """Return decoded human readable string for URL representation.""" + user = human_quote(self.user, "#/:?@[]") + password = human_quote(self.password, "#/:?@[]") + if (host := self.host) and ":" in host: + host = f"[{host}]" + path = human_quote(self.path, "#?") + if TYPE_CHECKING: + assert path is not None + query_string = "&".join( + "{}={}".format(human_quote(k, "#&+;="), human_quote(v, "#&+;=")) + for k, v in self.query.items() + ) + fragment = human_quote(self.fragment, "") + if TYPE_CHECKING: + assert fragment is not None + netloc = make_netloc(user, password, host, self.explicit_port) + return unsplit_result(self._scheme, netloc, path, query_string, fragment) + + +_DEFAULT_IDNA_SIZE = 256 +_DEFAULT_ENCODE_SIZE = 512 + + +@lru_cache(_DEFAULT_IDNA_SIZE) +def _idna_decode(raw: str) -> str: + try: + return idna.decode(raw.encode("ascii")) + except UnicodeError: # e.g. '::1' + return raw.encode("ascii").decode("idna") + + +@lru_cache(_DEFAULT_IDNA_SIZE) +def _idna_encode(host: str) -> str: + try: + return idna.encode(host, uts46=True).decode("ascii") + except UnicodeError: + return host.encode("idna").decode("ascii") + + +@lru_cache(_DEFAULT_ENCODE_SIZE) +def _encode_host(host: str, validate_host: bool) -> str: + """Encode host part of URL.""" + # If the host ends with a digit or contains a colon, its likely + # an IP address. + if host and (host[-1].isdigit() or ":" in host): + raw_ip, sep, zone = host.partition("%") + # If it looks like an IP, we check with _ip_compressed_version + # and fall-through if its not an IP address. This is a performance + # optimization to avoid parsing IP addresses as much as possible + # because it is orders of magnitude slower than almost any other + # operation this library does. + # Might be an IP address, check it + # + # IP Addresses can look like: + # https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2 + # - 127.0.0.1 (last character is a digit) + # - 2001:db8::ff00:42:8329 (contains a colon) + # - 2001:db8::ff00:42:8329%eth0 (contains a colon) + # - [2001:db8::ff00:42:8329] (contains a colon -- brackets should + # have been removed before it gets here) + # Rare IP Address formats are not supported per: + # https://datatracker.ietf.org/doc/html/rfc3986#section-7.4 + # + # IP parsing is slow, so its wrapped in an LRU + try: + ip = ip_address(raw_ip) + except ValueError: + pass + else: + # These checks should not happen in the + # LRU to keep the cache size small + host = ip.compressed + if ip.version == 6: + return f"[{host}%{zone}]" if sep else f"[{host}]" + return f"{host}%{zone}" if sep else host + + # IDNA encoding is slow, skip it for ASCII-only strings + if host.isascii(): + # Check for invalid characters explicitly; _idna_encode() does this + # for non-ascii host names. + host = host.lower() + if validate_host and (invalid := NOT_REG_NAME.search(host)): + value, pos, extra = invalid.group(), invalid.start(), "" + if value == "@" or (value == ":" and "@" in host[pos:]): + # this looks like an authority string + extra = ( + ", if the value includes a username or password, " + "use 'authority' instead of 'host'" + ) + raise ValueError( + f"Host {host!r} cannot contain {value!r} (at position {pos}){extra}" + ) from None + return host + + return _idna_encode(host) + + +@rewrite_module +def cache_clear() -> None: + """Clear all LRU caches.""" + _idna_encode.cache_clear() + _idna_decode.cache_clear() + _encode_host.cache_clear() + + +@rewrite_module +def cache_info() -> CacheInfo: + """Report cache statistics.""" + return { + "idna_encode": _idna_encode.cache_info(), + "idna_decode": _idna_decode.cache_info(), + "ip_address": _encode_host.cache_info(), + "host_validate": _encode_host.cache_info(), + "encode_host": _encode_host.cache_info(), + } + + +@rewrite_module +def cache_configure( + *, + idna_encode_size: Union[int, None] = _DEFAULT_IDNA_SIZE, + idna_decode_size: Union[int, None] = _DEFAULT_IDNA_SIZE, + ip_address_size: Union[int, None, UndefinedType] = UNDEFINED, + host_validate_size: Union[int, None, UndefinedType] = UNDEFINED, + encode_host_size: Union[int, None, UndefinedType] = UNDEFINED, +) -> None: + """Configure LRU cache sizes.""" + global _idna_decode, _idna_encode, _encode_host + # ip_address_size, host_validate_size are no longer + # used, but are kept for backwards compatibility. + if ip_address_size is not UNDEFINED or host_validate_size is not UNDEFINED: + warnings.warn( + "cache_configure() no longer accepts the " + "ip_address_size or host_validate_size arguments, " + "they are used to set the encode_host_size instead " + "and will be removed in the future", + DeprecationWarning, + stacklevel=2, + ) + + if encode_host_size is not None: + for size in (ip_address_size, host_validate_size): + if size is None: + encode_host_size = None + elif encode_host_size is UNDEFINED: + if size is not UNDEFINED: + encode_host_size = size + elif size is not UNDEFINED: + if TYPE_CHECKING: + assert isinstance(size, int) + assert isinstance(encode_host_size, int) + encode_host_size = max(size, encode_host_size) + if encode_host_size is UNDEFINED: + encode_host_size = _DEFAULT_ENCODE_SIZE + + _encode_host = lru_cache(encode_host_size)(_encode_host.__wrapped__) + _idna_decode = lru_cache(idna_decode_size)(_idna_decode.__wrapped__) + _idna_encode = lru_cache(idna_encode_size)(_idna_encode.__wrapped__) diff --git a/venv/lib/python3.10/site-packages/yarl/py.typed b/venv/lib/python3.10/site-packages/yarl/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..dcf2c804da5e19d617a03a6c68aa128d1d1f89a0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/yarl/py.typed @@ -0,0 +1 @@ +# Placeholder diff --git a/venv/lib/python3.10/site-packages/zipp/__init__.py b/venv/lib/python3.10/site-packages/zipp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ed5b21463295b8cee93d855316fb5e9000f9b8ec --- /dev/null +++ b/venv/lib/python3.10/site-packages/zipp/__init__.py @@ -0,0 +1,456 @@ +""" +A Path-like interface for zipfiles. + +This codebase is shared between zipfile.Path in the stdlib +and zipp in PyPI. See +https://github.com/python/importlib_metadata/wiki/Development-Methodology +for more detail. +""" + +import functools +import io +import itertools +import pathlib +import posixpath +import re +import stat +import sys +import zipfile + +from ._functools import save_method_args +from .compat.py310 import text_encoding +from .glob import Translator + +__all__ = ['Path'] + + +def _parents(path): + """ + Given a path with elements separated by + posixpath.sep, generate all parents of that path. + + >>> list(_parents('b/d')) + ['b'] + >>> list(_parents('/b/d/')) + ['/b'] + >>> list(_parents('b/d/f/')) + ['b/d', 'b'] + >>> list(_parents('b')) + [] + >>> list(_parents('')) + [] + """ + return itertools.islice(_ancestry(path), 1, None) + + +def _ancestry(path): + """ + Given a path with elements separated by + posixpath.sep, generate all elements of that path. + + >>> list(_ancestry('b/d')) + ['b/d', 'b'] + >>> list(_ancestry('/b/d/')) + ['/b/d', '/b'] + >>> list(_ancestry('b/d/f/')) + ['b/d/f', 'b/d', 'b'] + >>> list(_ancestry('b')) + ['b'] + >>> list(_ancestry('')) + [] + + Multiple separators are treated like a single. + + >>> list(_ancestry('//b//d///f//')) + ['//b//d///f', '//b//d', '//b'] + """ + path = path.rstrip(posixpath.sep) + while path.rstrip(posixpath.sep): + yield path + path, tail = posixpath.split(path) + + +_dedupe = dict.fromkeys +"""Deduplicate an iterable in original order""" + + +def _difference(minuend, subtrahend): + """ + Return items in minuend not in subtrahend, retaining order + with O(1) lookup. + """ + return itertools.filterfalse(set(subtrahend).__contains__, minuend) + + +class InitializedState: + """ + Mix-in to save the initialization state for pickling. + """ + + @save_method_args + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def __getstate__(self): + return self._saved___init__.args, self._saved___init__.kwargs + + def __setstate__(self, state): + args, kwargs = state + super().__init__(*args, **kwargs) + + +class CompleteDirs(InitializedState, zipfile.ZipFile): + """ + A ZipFile subclass that ensures that implied directories + are always included in the namelist. + + >>> list(CompleteDirs._implied_dirs(['foo/bar.txt', 'foo/bar/baz.txt'])) + ['foo/', 'foo/bar/'] + >>> list(CompleteDirs._implied_dirs(['foo/bar.txt', 'foo/bar/baz.txt', 'foo/bar/'])) + ['foo/'] + """ + + @staticmethod + def _implied_dirs(names): + parents = itertools.chain.from_iterable(map(_parents, names)) + as_dirs = (p + posixpath.sep for p in parents) + return _dedupe(_difference(as_dirs, names)) + + def namelist(self): + names = super().namelist() + return names + list(self._implied_dirs(names)) + + def _name_set(self): + return set(self.namelist()) + + def resolve_dir(self, name): + """ + If the name represents a directory, return that name + as a directory (with the trailing slash). + """ + names = self._name_set() + dirname = name + '/' + dir_match = name not in names and dirname in names + return dirname if dir_match else name + + def getinfo(self, name): + """ + Supplement getinfo for implied dirs. + """ + try: + return super().getinfo(name) + except KeyError: + if not name.endswith('/') or name not in self._name_set(): + raise + return zipfile.ZipInfo(filename=name) + + @classmethod + def make(cls, source): + """ + Given a source (filename or zipfile), return an + appropriate CompleteDirs subclass. + """ + if isinstance(source, CompleteDirs): + return source + + if not isinstance(source, zipfile.ZipFile): + return cls(source) + + # Only allow for FastLookup when supplied zipfile is read-only + if 'r' not in source.mode: + cls = CompleteDirs + + source.__class__ = cls + return source + + @classmethod + def inject(cls, zf: zipfile.ZipFile) -> zipfile.ZipFile: + """ + Given a writable zip file zf, inject directory entries for + any directories implied by the presence of children. + """ + for name in cls._implied_dirs(zf.namelist()): + zf.writestr(name, b"") + return zf + + +class FastLookup(CompleteDirs): + """ + ZipFile subclass to ensure implicit + dirs exist and are resolved rapidly. + """ + + def namelist(self): + return self._namelist + + @functools.cached_property + def _namelist(self): + return super().namelist() + + def _name_set(self): + return self._name_set_prop + + @functools.cached_property + def _name_set_prop(self): + return super()._name_set() + + +def _extract_text_encoding(encoding=None, *args, **kwargs): + # compute stack level so that the caller of the caller sees any warning. + is_pypy = sys.implementation.name == 'pypy' + # PyPy no longer special cased after 7.3.19 (or maybe 7.3.18) + # See jaraco/zipp#143 + is_old_pypi = is_pypy and sys.pypy_version_info < (7, 3, 19) + stack_level = 3 + is_old_pypi + return text_encoding(encoding, stack_level), args, kwargs + + +class Path: + """ + A :class:`importlib.resources.abc.Traversable` interface for zip files. + + Implements many of the features users enjoy from + :class:`pathlib.Path`. + + Consider a zip file with this structure:: + + . + ├── a.txt + └── b + ├── c.txt + └── d + └── e.txt + + >>> data = io.BytesIO() + >>> zf = zipfile.ZipFile(data, 'w') + >>> zf.writestr('a.txt', 'content of a') + >>> zf.writestr('b/c.txt', 'content of c') + >>> zf.writestr('b/d/e.txt', 'content of e') + >>> zf.filename = 'mem/abcde.zip' + + Path accepts the zipfile object itself or a filename + + >>> path = Path(zf) + + From there, several path operations are available. + + Directory iteration (including the zip file itself): + + >>> a, b = path.iterdir() + >>> a + Path('mem/abcde.zip', 'a.txt') + >>> b + Path('mem/abcde.zip', 'b/') + + name property: + + >>> b.name + 'b' + + join with divide operator: + + >>> c = b / 'c.txt' + >>> c + Path('mem/abcde.zip', 'b/c.txt') + >>> c.name + 'c.txt' + + Read text: + + >>> c.read_text(encoding='utf-8') + 'content of c' + + existence: + + >>> c.exists() + True + >>> (b / 'missing.txt').exists() + False + + Coercion to string: + + >>> import os + >>> str(c).replace(os.sep, posixpath.sep) + 'mem/abcde.zip/b/c.txt' + + At the root, ``name``, ``filename``, and ``parent`` + resolve to the zipfile. + + >>> str(path) + 'mem/abcde.zip/' + >>> path.name + 'abcde.zip' + >>> path.filename == pathlib.Path('mem/abcde.zip') + True + >>> str(path.parent) + 'mem' + + If the zipfile has no filename, such attributes are not + valid and accessing them will raise an Exception. + + >>> zf.filename = None + >>> path.name + Traceback (most recent call last): + ... + TypeError: ... + + >>> path.filename + Traceback (most recent call last): + ... + TypeError: ... + + >>> path.parent + Traceback (most recent call last): + ... + TypeError: ... + + # workaround python/cpython#106763 + >>> pass + """ + + __repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})" + + def __init__(self, root, at=""): + """ + Construct a Path from a ZipFile or filename. + + Note: When the source is an existing ZipFile object, + its type (__class__) will be mutated to a + specialized type. If the caller wishes to retain the + original type, the caller should either create a + separate ZipFile object or pass a filename. + """ + self.root = FastLookup.make(root) + self.at = at + + def __eq__(self, other): + """ + >>> Path(zipfile.ZipFile(io.BytesIO(), 'w')) == 'foo' + False + """ + if self.__class__ is not other.__class__: + return NotImplemented + return (self.root, self.at) == (other.root, other.at) + + def __hash__(self): + return hash((self.root, self.at)) + + def open(self, mode='r', *args, pwd=None, **kwargs): + """ + Open this entry as text or binary following the semantics + of ``pathlib.Path.open()`` by passing arguments through + to io.TextIOWrapper(). + """ + if self.is_dir(): + raise IsADirectoryError(self) + zip_mode = mode[0] + if zip_mode == 'r' and not self.exists(): + raise FileNotFoundError(self) + stream = self.root.open(self.at, zip_mode, pwd=pwd) + if 'b' in mode: + if args or kwargs: + raise ValueError("encoding args invalid for binary operation") + return stream + # Text mode: + encoding, args, kwargs = _extract_text_encoding(*args, **kwargs) + return io.TextIOWrapper(stream, encoding, *args, **kwargs) + + def _base(self): + return pathlib.PurePosixPath(self.at) if self.at else self.filename + + @property + def name(self): + return self._base().name + + @property + def suffix(self): + return self._base().suffix + + @property + def suffixes(self): + return self._base().suffixes + + @property + def stem(self): + return self._base().stem + + @property + def filename(self): + return pathlib.Path(self.root.filename).joinpath(self.at) + + def read_text(self, *args, **kwargs): + encoding, args, kwargs = _extract_text_encoding(*args, **kwargs) + with self.open('r', encoding, *args, **kwargs) as strm: + return strm.read() + + def read_bytes(self): + with self.open('rb') as strm: + return strm.read() + + def _is_child(self, path): + return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/") + + def _next(self, at): + return self.__class__(self.root, at) + + def is_dir(self): + return not self.at or self.at.endswith("/") + + def is_file(self): + return self.exists() and not self.is_dir() + + def exists(self): + return self.at in self.root._name_set() + + def iterdir(self): + if not self.is_dir(): + raise ValueError("Can't listdir a file") + subs = map(self._next, self.root.namelist()) + return filter(self._is_child, subs) + + def match(self, path_pattern): + return pathlib.PurePosixPath(self.at).match(path_pattern) + + def is_symlink(self): + """ + Return whether this path is a symlink. + """ + info = self.root.getinfo(self.at) + mode = info.external_attr >> 16 + return stat.S_ISLNK(mode) + + def glob(self, pattern): + if not pattern: + raise ValueError(f"Unacceptable pattern: {pattern!r}") + + prefix = re.escape(self.at) + tr = Translator(seps='/') + matches = re.compile(prefix + tr.translate(pattern)).fullmatch + return map(self._next, filter(matches, self.root.namelist())) + + def rglob(self, pattern): + return self.glob(f'**/{pattern}') + + def relative_to(self, other, *extra): + return posixpath.relpath(str(self), str(other.joinpath(*extra))) + + def __str__(self): + return posixpath.join(self.root.filename, self.at) + + def __repr__(self): + return self.__repr.format(self=self) + + def joinpath(self, *other): + next = posixpath.join(self.at, *other) + return self._next(self.root.resolve_dir(next)) + + __truediv__ = joinpath + + @property + def parent(self): + if not self.at: + return self.filename.parent + parent_at = posixpath.dirname(self.at.rstrip('/')) + if parent_at: + parent_at += '/' + return self._next(parent_at) diff --git a/venv/lib/python3.10/site-packages/zipp/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zipp/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc2bff068dbdb2ef5ecfce9ade92b00fd8b7841d Binary files /dev/null and b/venv/lib/python3.10/site-packages/zipp/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zipp/__pycache__/_functools.cpython-310.pyc b/venv/lib/python3.10/site-packages/zipp/__pycache__/_functools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1c0221761b61ba1c9dfcee960fccacfe9464660 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zipp/__pycache__/_functools.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zipp/__pycache__/glob.cpython-310.pyc b/venv/lib/python3.10/site-packages/zipp/__pycache__/glob.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..366bcabbbe17580373b5e759eeddcdb04cb74dc7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zipp/__pycache__/glob.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zipp/_functools.py b/venv/lib/python3.10/site-packages/zipp/_functools.py new file mode 100644 index 0000000000000000000000000000000000000000..7390be21873e4ba439bde0553e4c0dcde8eb7d74 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zipp/_functools.py @@ -0,0 +1,20 @@ +import collections +import functools + + +# from jaraco.functools 4.0.2 +def save_method_args(method): + """ + Wrap a method such that when it is called, the args and kwargs are + saved on the method. + """ + args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs') # noqa: PYI024 + + @functools.wraps(method) + def wrapper(self, /, *args, **kwargs): + attr_name = '_saved_' + method.__name__ + attr = args_and_kwargs(args, kwargs) + setattr(self, attr_name, attr) + return method(self, *args, **kwargs) + + return wrapper diff --git a/venv/lib/python3.10/site-packages/zipp/compat/__init__.py b/venv/lib/python3.10/site-packages/zipp/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/zipp/compat/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zipp/compat/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aea24ffaa0f921c4a59674225f3a08d8eb93aa93 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zipp/compat/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zipp/compat/__pycache__/overlay.cpython-310.pyc b/venv/lib/python3.10/site-packages/zipp/compat/__pycache__/overlay.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..797e871b4cd3798ff0d0be95d0dd08fdd267f328 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zipp/compat/__pycache__/overlay.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zipp/compat/__pycache__/py310.cpython-310.pyc b/venv/lib/python3.10/site-packages/zipp/compat/__pycache__/py310.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2946ad6d0d694cdc27af3a91c700ea6cb17470c1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zipp/compat/__pycache__/py310.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zipp/compat/__pycache__/py313.cpython-310.pyc b/venv/lib/python3.10/site-packages/zipp/compat/__pycache__/py313.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f5fa4738458f31e86701ddb01328800da2b3037 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zipp/compat/__pycache__/py313.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zipp/compat/overlay.py b/venv/lib/python3.10/site-packages/zipp/compat/overlay.py new file mode 100644 index 0000000000000000000000000000000000000000..5a97ee7cd8b98f3a5487c0a0b0a80ffde5ff4dfd --- /dev/null +++ b/venv/lib/python3.10/site-packages/zipp/compat/overlay.py @@ -0,0 +1,37 @@ +""" +Expose zipp.Path as .zipfile.Path. + +Includes everything else in ``zipfile`` to match future usage. Just +use: + +>>> from zipp.compat.overlay import zipfile + +in place of ``import zipfile``. + +Relative imports are supported too. + +>>> from zipp.compat.overlay.zipfile import ZipInfo + +The ``zipfile`` object added to ``sys.modules`` needs to be +hashable (#126). + +>>> _ = hash(sys.modules['zipp.compat.overlay.zipfile']) +""" + +import importlib +import sys +import types + +import zipp + + +class HashableNamespace(types.SimpleNamespace): + def __hash__(self): + return hash(tuple(vars(self))) + + +zipfile = HashableNamespace(**vars(importlib.import_module('zipfile'))) +zipfile.Path = zipp.Path +zipfile._path = zipp + +sys.modules[__name__ + '.zipfile'] = zipfile # type: ignore[assignment] diff --git a/venv/lib/python3.10/site-packages/zipp/compat/py310.py b/venv/lib/python3.10/site-packages/zipp/compat/py310.py new file mode 100644 index 0000000000000000000000000000000000000000..e1e7ec229062b8556cdd85f530d1ff301b2e6845 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zipp/compat/py310.py @@ -0,0 +1,13 @@ +import io +import sys + + +def _text_encoding(encoding, stacklevel=2, /): # pragma: no cover + return encoding + + +text_encoding = ( + io.text_encoding # type: ignore[unused-ignore, attr-defined] + if sys.version_info > (3, 10) + else _text_encoding +) diff --git a/venv/lib/python3.10/site-packages/zipp/compat/py313.py b/venv/lib/python3.10/site-packages/zipp/compat/py313.py new file mode 100644 index 0000000000000000000000000000000000000000..ae458690553f92107ce296adf4bb49add8e78250 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zipp/compat/py313.py @@ -0,0 +1,34 @@ +import functools +import sys + + +# from jaraco.functools 4.1 +def identity(x): + return x + + +# from jaraco.functools 4.1 +def apply(transform): + def wrap(func): + return functools.wraps(func)(compose(transform, func)) + + return wrap + + +# from jaraco.functools 4.1 +def compose(*funcs): + def compose_two(f1, f2): + return lambda *args, **kwargs: f1(f2(*args, **kwargs)) + + return functools.reduce(compose_two, funcs) + + +def replace(pattern): + r""" + >>> replace(r'foo\z') + 'foo\\Z' + """ + return pattern[:-2] + pattern[-2:].replace(r'\z', r'\Z') + + +legacy_end_marker = apply(replace) if sys.version_info < (3, 14) else identity diff --git a/venv/lib/python3.10/site-packages/zipp/glob.py b/venv/lib/python3.10/site-packages/zipp/glob.py new file mode 100644 index 0000000000000000000000000000000000000000..1b4ffb33187b65b4378925c472071c845bcecc26 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zipp/glob.py @@ -0,0 +1,116 @@ +import os +import re + +from .compat.py313 import legacy_end_marker + +_default_seps = os.sep + str(os.altsep) * bool(os.altsep) + + +class Translator: + """ + >>> Translator('xyz') + Traceback (most recent call last): + ... + AssertionError: Invalid separators + + >>> Translator('') + Traceback (most recent call last): + ... + AssertionError: Invalid separators + """ + + seps: str + + def __init__(self, seps: str = _default_seps): + assert seps and set(seps) <= set(_default_seps), "Invalid separators" + self.seps = seps + + def translate(self, pattern): + """ + Given a glob pattern, produce a regex that matches it. + """ + return self.extend(self.match_dirs(self.translate_core(pattern))) + + @legacy_end_marker + def extend(self, pattern): + r""" + Extend regex for pattern-wide concerns. + + Apply '(?s:)' to create a non-matching group that + matches newlines (valid on Unix). + + Append '\z' to imply fullmatch even when match is used. + """ + return rf'(?s:{pattern})\z' + + def match_dirs(self, pattern): + """ + Ensure that zipfile.Path directory names are matched. + + zipfile.Path directory names always end in a slash. + """ + return rf'{pattern}[/]?' + + def translate_core(self, pattern): + r""" + Given a glob pattern, produce a regex that matches it. + + >>> t = Translator() + >>> t.translate_core('*.txt').replace('\\\\', '') + '[^/]*\\.txt' + >>> t.translate_core('a?txt') + 'a[^/]txt' + >>> t.translate_core('**/*').replace('\\\\', '') + '.*/[^/][^/]*' + """ + self.restrict_rglob(pattern) + return ''.join(map(self.replace, separate(self.star_not_empty(pattern)))) + + def replace(self, match): + """ + Perform the replacements for a match from :func:`separate`. + """ + return match.group('set') or ( + re.escape(match.group(0)) + .replace('\\*\\*', r'.*') + .replace('\\*', rf'[^{re.escape(self.seps)}]*') + .replace('\\?', r'[^/]') + ) + + def restrict_rglob(self, pattern): + """ + Raise ValueError if ** appears in anything but a full path segment. + + >>> Translator().translate('**foo') + Traceback (most recent call last): + ... + ValueError: ** must appear alone in a path segment + """ + seps_pattern = rf'[{re.escape(self.seps)}]+' + segments = re.split(seps_pattern, pattern) + if any('**' in segment and segment != '**' for segment in segments): + raise ValueError("** must appear alone in a path segment") + + def star_not_empty(self, pattern): + """ + Ensure that * will not match an empty segment. + """ + + def handle_segment(match): + segment = match.group(0) + return '?*' if segment == '*' else segment + + not_seps_pattern = rf'[^{re.escape(self.seps)}]+' + return re.sub(not_seps_pattern, handle_segment, pattern) + + +def separate(pattern): + """ + Separate out character sets to avoid translating their contents. + + >>> [m.group(0) for m in separate('*.txt')] + ['*.txt'] + >>> [m.group(0) for m in separate('a[?]txt')] + ['a', '[?]', 'txt'] + """ + return re.finditer(r'([^\[]+)|(?P[\[].*?[\]])|([\[][^\]]*$)', pattern) diff --git a/venv/lib/python3.10/site-packages/zmq/__init__.pxd b/venv/lib/python3.10/site-packages/zmq/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..37b8362e2a07a77d41ff9f6d3b589364a5e00a05 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/__init__.pxd @@ -0,0 +1 @@ +from zmq.backend.cython cimport Context, Frame, Socket, libzmq diff --git a/venv/lib/python3.10/site-packages/zmq/__init__.py b/venv/lib/python3.10/site-packages/zmq/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f1149c580d9d9f5c802286d28b19c6c76be81efe --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/__init__.py @@ -0,0 +1,94 @@ +"""Python bindings for 0MQ""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from __future__ import annotations + +import os +import sys +from contextlib import contextmanager + + +@contextmanager +def _libs_on_path(): + """context manager for libs directory on $PATH + + Works around mysterious issue where os.add_dll_directory + does not resolve imports (conda-forge Python >= 3.8) + """ + + if not sys.platform.startswith("win"): + yield + return + + libs_dir = os.path.abspath( + os.path.join( + os.path.dirname(__file__), + os.pardir, + "pyzmq.libs", + ) + ) + if not os.path.exists(libs_dir): + # no bundled libs + yield + return + + path_before = os.environ.get("PATH") + try: + os.environ["PATH"] = os.pathsep.join([path_before or "", libs_dir]) + yield + finally: + if path_before is None: + os.environ.pop("PATH") + else: + os.environ["PATH"] = path_before + + +# zmq top-level imports + +# workaround for Windows +with _libs_on_path(): + from zmq import backend + +from . import constants # noqa +from .constants import * # noqa +from zmq.backend import * # noqa +from zmq import sugar +from zmq.sugar import * # noqa + + +def get_includes(): + """Return a list of directories to include for linking against pyzmq with cython.""" + from os.path import abspath, dirname, exists, join, pardir + + base = dirname(__file__) + parent = abspath(join(base, pardir)) + includes = [parent] + [join(parent, base, subdir) for subdir in ('utils',)] + if exists(join(parent, base, 'include')): + includes.append(join(parent, base, 'include')) + return includes + + +def get_library_dirs(): + """Return a list of directories used to link against pyzmq's bundled libzmq.""" + from os.path import abspath, dirname, join, pardir + + base = dirname(__file__) + parent = abspath(join(base, pardir)) + return [join(parent, base)] + + +COPY_THRESHOLD = 65536 +DRAFT_API = backend.has("draft") + +__all__ = ( + [ + 'get_includes', + 'COPY_THRESHOLD', + 'DRAFT_API', + ] + + constants.__all__ + + sugar.__all__ + + backend.__all__ +) diff --git a/venv/lib/python3.10/site-packages/zmq/__init__.pyi b/venv/lib/python3.10/site-packages/zmq/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..56f4bdcaf0c08c199b0da853bae063d5d392fe5a --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/__init__.pyi @@ -0,0 +1,28 @@ +from typing import List + +from . import backend, sugar + +COPY_THRESHOLD: int +DRAFT_API: bool +__version__: str + +# mypy doesn't like overwriting symbols with * so be explicit +# about what comes from backend, not from sugar +# see tools/backend_imports.py to generate this list +# note: `x as x` is required for re-export +# see https://github.com/python/mypy/issues/2190 +from .backend import IPC_PATH_MAX_LEN as IPC_PATH_MAX_LEN +from .backend import curve_keypair as curve_keypair +from .backend import curve_public as curve_public +from .backend import has as has +from .backend import proxy as proxy +from .backend import proxy_steerable as proxy_steerable +from .backend import strerror as strerror +from .backend import zmq_errno as zmq_errno +from .backend import zmq_poll as zmq_poll +from .constants import * +from .error import * +from .sugar import * + +def get_includes() -> list[str]: ... +def get_library_dirs() -> list[str]: ... diff --git a/venv/lib/python3.10/site-packages/zmq/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0f1d695e3444d813937e10083a0baed8cc9509e Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/__pycache__/_future.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/__pycache__/_future.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..545a250652743990307cb01a3b3831459cb22eec Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/__pycache__/_future.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/__pycache__/_typing.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/__pycache__/_typing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cfd88e44709ab3dae97930e3441df1eef4940dd Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/__pycache__/_typing.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/__pycache__/asyncio.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/__pycache__/asyncio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a249698039faf79326b66ad5cb00561406faffa Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/__pycache__/asyncio.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/__pycache__/constants.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/__pycache__/constants.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1f8d1f0aa234834346b9d1ef7a662b60ef34cb8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/__pycache__/constants.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/__pycache__/decorators.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/__pycache__/decorators.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44d7385b544aa863097f076070a71bb74b778a57 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/__pycache__/decorators.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/__pycache__/error.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/__pycache__/error.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5f1b82251b5002df5a38a5905b847b8b63ea81d Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/__pycache__/error.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/_future.py b/venv/lib/python3.10/site-packages/zmq/_future.py new file mode 100644 index 0000000000000000000000000000000000000000..e598de14f768dc8540684bfa79589c00eeeceed0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/_future.py @@ -0,0 +1,737 @@ +"""Future-returning APIs for coroutines.""" + +# Copyright (c) PyZMQ Developers. +# Distributed under the terms of the Modified BSD License. +from __future__ import annotations + +import warnings +from asyncio import Future +from collections import deque +from functools import partial +from itertools import chain +from typing import ( + Any, + Awaitable, + Callable, + NamedTuple, + TypeVar, + cast, +) + +import zmq as _zmq +from zmq import EVENTS, POLLIN, POLLOUT + + +class _FutureEvent(NamedTuple): + future: Future + kind: str + args: tuple + kwargs: dict + msg: Any + timer: Any + + +# These are incomplete classes and need a Mixin for compatibility with an eventloop +# defining the following attributes: +# +# _Future +# _READ +# _WRITE +# _default_loop() + + +class _Async: + """Mixin for common async logic""" + + _current_loop: Any = None + _Future: type[Future] + + def _get_loop(self) -> Any: + """Get event loop + + Notice if event loop has changed, + and register init_io_state on activation of a new event loop + """ + if self._current_loop is None: + self._current_loop = self._default_loop() + self._init_io_state(self._current_loop) + return self._current_loop + current_loop = self._default_loop() + if current_loop is not self._current_loop: + # warn? This means a socket is being used in multiple loops! + self._current_loop = current_loop + self._init_io_state(current_loop) + return current_loop + + def _default_loop(self) -> Any: + raise NotImplementedError("Must be implemented in a subclass") + + def _init_io_state(self, loop=None) -> None: + pass + + +class _AsyncPoller(_Async, _zmq.Poller): + """Poller that returns a Future on poll, instead of blocking.""" + + _socket_class: type[_AsyncSocket] + _READ: int + _WRITE: int + raw_sockets: list[Any] + + def _watch_raw_socket(self, loop: Any, socket: Any, evt: int, f: Callable) -> None: + """Schedule callback for a raw socket""" + raise NotImplementedError() + + def _unwatch_raw_sockets(self, loop: Any, *sockets: Any) -> None: + """Unschedule callback for a raw socket""" + raise NotImplementedError() + + def poll(self, timeout=-1) -> Awaitable[list[tuple[Any, int]]]: # type: ignore + """Return a Future for a poll event""" + future = self._Future() + if timeout == 0: + try: + result = super().poll(0) + except Exception as e: + future.set_exception(e) + else: + future.set_result(result) + return future + + loop = self._get_loop() + + # register Future to be called as soon as any event is available on any socket + watcher = self._Future() + + # watch raw sockets: + raw_sockets: list[Any] = [] + + def wake_raw(*args): + if not watcher.done(): + watcher.set_result(None) + + watcher.add_done_callback( + lambda f: self._unwatch_raw_sockets(loop, *raw_sockets) + ) + + wrapped_sockets: list[_AsyncSocket] = [] + + def _clear_wrapper_io(f): + for s in wrapped_sockets: + s._clear_io_state() + + for socket, mask in self.sockets: + if isinstance(socket, _zmq.Socket): + if not isinstance(socket, self._socket_class): + # it's a blocking zmq.Socket, wrap it in async + socket = self._socket_class.from_socket(socket) + wrapped_sockets.append(socket) + if mask & _zmq.POLLIN: + socket._add_recv_event('poll', future=watcher) + if mask & _zmq.POLLOUT: + socket._add_send_event('poll', future=watcher) + else: + raw_sockets.append(socket) + evt = 0 + if mask & _zmq.POLLIN: + evt |= self._READ + if mask & _zmq.POLLOUT: + evt |= self._WRITE + self._watch_raw_socket(loop, socket, evt, wake_raw) + + def on_poll_ready(f): + if future.done(): + return + if watcher.cancelled(): + try: + future.cancel() + except RuntimeError: + # RuntimeError may be called during teardown + pass + return + if watcher.exception(): + future.set_exception(watcher.exception()) + else: + try: + result = super(_AsyncPoller, self).poll(0) + except Exception as e: + future.set_exception(e) + else: + future.set_result(result) + + watcher.add_done_callback(on_poll_ready) + + if wrapped_sockets: + watcher.add_done_callback(_clear_wrapper_io) + + if timeout is not None and timeout > 0: + # schedule cancel to fire on poll timeout, if any + def trigger_timeout(): + if not watcher.done(): + watcher.set_result(None) + + timeout_handle = loop.call_later(1e-3 * timeout, trigger_timeout) + + def cancel_timeout(f): + if hasattr(timeout_handle, 'cancel'): + timeout_handle.cancel() + else: + loop.remove_timeout(timeout_handle) + + future.add_done_callback(cancel_timeout) + + def cancel_watcher(f): + if not watcher.done(): + watcher.cancel() + + future.add_done_callback(cancel_watcher) + + return future + + +class _NoTimer: + @staticmethod + def cancel(): + pass + + +T = TypeVar("T", bound="_AsyncSocket") + + +class _AsyncSocket(_Async, _zmq.Socket[Future]): + # Warning : these class variables are only here to allow to call super().__setattr__. + # They be overridden at instance initialization and not shared in the whole class + _recv_futures = None + _send_futures = None + _state = 0 + _shadow_sock: _zmq.Socket + _poller_class = _AsyncPoller + _fd = None + + def __init__( + self, + context=None, + socket_type=-1, + io_loop=None, + _from_socket: _zmq.Socket | None = None, + **kwargs, + ) -> None: + if isinstance(context, _zmq.Socket): + context, _from_socket = (None, context) + if _from_socket is not None: + super().__init__(shadow=_from_socket.underlying) # type: ignore + self._shadow_sock = _from_socket + else: + super().__init__(context, socket_type, **kwargs) # type: ignore + self._shadow_sock = _zmq.Socket.shadow(self.underlying) + + if io_loop is not None: + warnings.warn( + f"{self.__class__.__name__}(io_loop) argument is deprecated in pyzmq 22.2." + " The currently active loop will always be used.", + DeprecationWarning, + stacklevel=3, + ) + self._recv_futures = deque() + self._send_futures = deque() + self._state = 0 + self._fd = self._shadow_sock.FD + + @classmethod + def from_socket(cls: type[T], socket: _zmq.Socket, io_loop: Any = None) -> T: + """Create an async socket from an existing Socket""" + return cls(_from_socket=socket, io_loop=io_loop) + + def close(self, linger: int | None = None) -> None: + if not self.closed and self._fd is not None: + event_list: list[_FutureEvent] = list( + chain(self._recv_futures or [], self._send_futures or []) + ) + for event in event_list: + if not event.future.done(): + try: + event.future.cancel() + except RuntimeError: + # RuntimeError may be called during teardown + pass + self._clear_io_state() + super().close(linger=linger) + + close.__doc__ = _zmq.Socket.close.__doc__ + + def get(self, key): + result = super().get(key) + if key == EVENTS: + self._schedule_remaining_events(result) + return result + + get.__doc__ = _zmq.Socket.get.__doc__ + + def recv_multipart( + self, flags: int = 0, copy: bool = True, track: bool = False + ) -> Awaitable[list[bytes] | list[_zmq.Frame]]: + """Receive a complete multipart zmq message. + + Returns a Future whose result will be a multipart message. + """ + return self._add_recv_event( + 'recv_multipart', kwargs=dict(flags=flags, copy=copy, track=track) + ) + + def recv( # type: ignore + self, flags: int = 0, copy: bool = True, track: bool = False + ) -> Awaitable[bytes | _zmq.Frame]: + """Receive a single zmq frame. + + Returns a Future, whose result will be the received frame. + + Recommend using recv_multipart instead. + """ + return self._add_recv_event( + 'recv', kwargs=dict(flags=flags, copy=copy, track=track) + ) + + def recv_into( # type: ignore + self, buf, /, *, nbytes: int = 0, flags: int = 0 + ) -> Awaitable[int]: + """Receive a single zmq frame into a pre-allocated buffer. + + Returns a Future, whose result will be the number of bytes received. + """ + return self._add_recv_event( + 'recv_into', args=(buf,), kwargs=dict(nbytes=nbytes, flags=flags) + ) + + def send_multipart( # type: ignore + self, msg_parts: Any, flags: int = 0, copy: bool = True, track=False, **kwargs + ) -> Awaitable[_zmq.MessageTracker | None]: + """Send a complete multipart zmq message. + + Returns a Future that resolves when sending is complete. + """ + kwargs['flags'] = flags + kwargs['copy'] = copy + kwargs['track'] = track + return self._add_send_event('send_multipart', msg=msg_parts, kwargs=kwargs) + + def send( # type: ignore + self, + data: Any, + flags: int = 0, + copy: bool = True, + track: bool = False, + **kwargs: Any, + ) -> Awaitable[_zmq.MessageTracker | None]: + """Send a single zmq frame. + + Returns a Future that resolves when sending is complete. + + Recommend using send_multipart instead. + """ + kwargs['flags'] = flags + kwargs['copy'] = copy + kwargs['track'] = track + kwargs.update(dict(flags=flags, copy=copy, track=track)) + return self._add_send_event('send', msg=data, kwargs=kwargs) + + def _deserialize(self, recvd, load): + """Deserialize with Futures""" + f = self._Future() + + def _chain(_): + """Chain result through serialization to recvd""" + if f.done(): + # chained future may be cancelled, which means nobody is going to get this result + # if it's an error, that's no big deal (probably zmq.Again), + # but if it's a successful recv, this is a dropped message! + if not recvd.cancelled() and recvd.exception() is None: + warnings.warn( + # is there a useful stacklevel? + # ideally, it would point to where `f.cancel()` was called + f"Future {f} completed while awaiting {recvd}. A message has been dropped!", + RuntimeWarning, + ) + return + if recvd.exception(): + f.set_exception(recvd.exception()) + else: + buf = recvd.result() + try: + loaded = load(buf) + except Exception as e: + f.set_exception(e) + else: + f.set_result(loaded) + + recvd.add_done_callback(_chain) + + def _chain_cancel(_): + """Chain cancellation from f to recvd""" + if recvd.done(): + return + if f.cancelled(): + recvd.cancel() + + f.add_done_callback(_chain_cancel) + + return f + + def poll(self, timeout=None, flags=_zmq.POLLIN) -> Awaitable[int]: # type: ignore + """poll the socket for events + + returns a Future for the poll results. + """ + + if self.closed: + raise _zmq.ZMQError(_zmq.ENOTSUP) + + p = self._poller_class() + p.register(self, flags) + poll_future = cast(Future, p.poll(timeout)) + + future = self._Future() + + def unwrap_result(f): + if future.done(): + return + if poll_future.cancelled(): + try: + future.cancel() + except RuntimeError: + # RuntimeError may be called during teardown + pass + return + if f.exception(): + future.set_exception(poll_future.exception()) + else: + evts = dict(poll_future.result()) + future.set_result(evts.get(self, 0)) + + if poll_future.done(): + # hook up result if already done + unwrap_result(poll_future) + else: + poll_future.add_done_callback(unwrap_result) + + def cancel_poll(future): + """Cancel underlying poll if request has been cancelled""" + if not poll_future.done(): + try: + poll_future.cancel() + except RuntimeError: + # RuntimeError may be called during teardown + pass + + future.add_done_callback(cancel_poll) + + return future + + def _add_timeout(self, future, timeout): + """Add a timeout for a send or recv Future""" + + def future_timeout(): + if future.done(): + # future already resolved, do nothing + return + + # raise EAGAIN + future.set_exception(_zmq.Again()) + + return self._call_later(timeout, future_timeout) + + def _call_later(self, delay, callback): + """Schedule a function to be called later + + Override for different IOLoop implementations + + Tornado and asyncio happen to both have ioloop.call_later + with the same signature. + """ + return self._get_loop().call_later(delay, callback) + + @staticmethod + def _remove_finished_future(future, event_list, event=None): + """Make sure that futures are removed from the event list when they resolve + + Avoids delaying cleanup until the next send/recv event, + which may never come. + """ + # "future" instance is shared between sockets, but each socket has its own event list. + if not event_list: + return + # only unconsumed events (e.g. cancelled calls) + # will be present when this happens + try: + event_list.remove(event) + except ValueError: + # usually this will have been removed by being consumed + return + + def _add_recv_event( + self, + kind: str, + *, + args: tuple | None = None, + kwargs: dict[str, Any] | None = None, + future: Future | None = None, + ) -> Future: + """Add a recv event, returning the corresponding Future""" + f = future or self._Future() + if args is None: + args = () + if kwargs is None: + kwargs = {} + if kind.startswith('recv') and kwargs.get('flags', 0) & _zmq.DONTWAIT: + # short-circuit non-blocking calls + recv = getattr(self._shadow_sock, kind) + try: + r = recv(*args, **kwargs) + except Exception as e: + f.set_exception(e) + else: + f.set_result(r) + return f + + timer = _NoTimer + if hasattr(_zmq, 'RCVTIMEO'): + timeout_ms = self._shadow_sock.rcvtimeo + if timeout_ms >= 0: + timer = self._add_timeout(f, timeout_ms * 1e-3) + + # we add it to the list of futures before we add the timeout as the + # timeout will remove the future from recv_futures to avoid leaks + _future_event = _FutureEvent( + f, kind, args=args, kwargs=kwargs, msg=None, timer=timer + ) + self._recv_futures.append(_future_event) + + if self._shadow_sock.get(EVENTS) & POLLIN: + # recv immediately, if we can + self._handle_recv() + if self._recv_futures and _future_event in self._recv_futures: + # Don't let the Future sit in _recv_events after it's done + # no need to register this if we've already been handled + # (i.e. immediately-resolved recv) + f.add_done_callback( + partial( + self._remove_finished_future, + event_list=self._recv_futures, + event=_future_event, + ) + ) + self._add_io_state(POLLIN) + return f + + def _add_send_event(self, kind, msg=None, kwargs=None, future=None): + """Add a send event, returning the corresponding Future""" + f = future or self._Future() + # attempt send with DONTWAIT if no futures are waiting + # short-circuit for sends that will resolve immediately + # only call if no send Futures are waiting + if kind in ('send', 'send_multipart') and not self._send_futures: + flags = kwargs.get('flags', 0) + nowait_kwargs = kwargs.copy() + nowait_kwargs['flags'] = flags | _zmq.DONTWAIT + + # short-circuit non-blocking calls + send = getattr(self._shadow_sock, kind) + # track if the send resolved or not + # (EAGAIN if DONTWAIT is not set should proceed with) + finish_early = True + try: + r = send(msg, **nowait_kwargs) + except _zmq.Again as e: + if flags & _zmq.DONTWAIT: + f.set_exception(e) + else: + # EAGAIN raised and DONTWAIT not requested, + # proceed with async send + finish_early = False + except Exception as e: + f.set_exception(e) + else: + f.set_result(r) + + if finish_early: + # short-circuit resolved, return finished Future + # schedule wake for recv if there are any receivers waiting + if self._recv_futures: + self._schedule_remaining_events() + return f + + timer = _NoTimer + if hasattr(_zmq, 'SNDTIMEO'): + timeout_ms = self._shadow_sock.get(_zmq.SNDTIMEO) + if timeout_ms >= 0: + timer = self._add_timeout(f, timeout_ms * 1e-3) + + # we add it to the list of futures before we add the timeout as the + # timeout will remove the future from recv_futures to avoid leaks + _future_event = _FutureEvent( + f, kind, args=(), kwargs=kwargs, msg=msg, timer=timer + ) + self._send_futures.append(_future_event) + # Don't let the Future sit in _send_futures after it's done + f.add_done_callback( + partial( + self._remove_finished_future, + event_list=self._send_futures, + event=_future_event, + ) + ) + + self._add_io_state(POLLOUT) + return f + + def _handle_recv(self): + """Handle recv events""" + if not self._shadow_sock.get(EVENTS) & POLLIN: + # event triggered, but state may have been changed between trigger and callback + return + f = None + while self._recv_futures: + f, kind, args, kwargs, _, timer = self._recv_futures.popleft() + # skip any cancelled futures + if f.done(): + f = None + else: + break + + if not self._recv_futures: + self._drop_io_state(POLLIN) + + if f is None: + return + + timer.cancel() + + if kind == 'poll': + # on poll event, just signal ready, nothing else. + f.set_result(None) + return + elif kind == 'recv_multipart': + recv = self._shadow_sock.recv_multipart + elif kind == 'recv': + recv = self._shadow_sock.recv + elif kind == 'recv_into': + recv = self._shadow_sock.recv_into + else: + raise ValueError(f"Unhandled recv event type: {kind!r}") + + kwargs['flags'] |= _zmq.DONTWAIT + try: + result = recv(*args, **kwargs) + except Exception as e: + f.set_exception(e) + else: + f.set_result(result) + + def _handle_send(self): + if not self._shadow_sock.get(EVENTS) & POLLOUT: + # event triggered, but state may have been changed between trigger and callback + return + f = None + while self._send_futures: + f, kind, args, kwargs, msg, timer = self._send_futures.popleft() + # skip any cancelled futures + if f.done(): + f = None + else: + break + + if not self._send_futures: + self._drop_io_state(POLLOUT) + + if f is None: + return + + timer.cancel() + + if kind == 'poll': + # on poll event, just signal ready, nothing else. + f.set_result(None) + return + elif kind == 'send_multipart': + send = self._shadow_sock.send_multipart + elif kind == 'send': + send = self._shadow_sock.send + else: + raise ValueError(f"Unhandled send event type: {kind!r}") + + kwargs['flags'] |= _zmq.DONTWAIT + try: + result = send(msg, **kwargs) + except Exception as e: + f.set_exception(e) + else: + f.set_result(result) + + # event masking from ZMQStream + def _handle_events(self, fd=0, events=0): + """Dispatch IO events to _handle_recv, etc.""" + if self._shadow_sock.closed: + return + + zmq_events = self._shadow_sock.get(EVENTS) + if zmq_events & _zmq.POLLIN: + self._handle_recv() + if zmq_events & _zmq.POLLOUT: + self._handle_send() + self._schedule_remaining_events() + + def _schedule_remaining_events(self, events=None): + """Schedule a call to handle_events next loop iteration + + If there are still events to handle. + """ + # edge-triggered handling + # allow passing events in, in case this is triggered by retrieving events, + # so we don't have to retrieve it twice. + if self._state == 0: + # not watching for anything, nothing to schedule + return + if events is None: + events = self._shadow_sock.get(EVENTS) + if events & self._state: + self._call_later(0, self._handle_events) + + def _add_io_state(self, state): + """Add io_state to poller.""" + if self._state != state: + state = self._state = self._state | state + self._update_handler(self._state) + + def _drop_io_state(self, state): + """Stop poller from watching an io_state.""" + if self._state & state: + self._state = self._state & (~state) + self._update_handler(self._state) + + def _update_handler(self, state): + """Update IOLoop handler with state. + + zmq FD is always read-only. + """ + # ensure loop is registered and init_io has been called + # if there are any events to watch for + if state: + self._get_loop() + self._schedule_remaining_events() + + def _init_io_state(self, loop=None): + """initialize the ioloop event handler""" + if loop is None: + loop = self._get_loop() + loop.add_handler(self._shadow_sock, self._handle_events, self._READ) + self._call_later(0, self._handle_events) + + def _clear_io_state(self): + """unregister the ioloop event handler + + called once during close + """ + fd = self._shadow_sock + if self._shadow_sock.closed: + fd = self._fd + if self._current_loop is not None: + self._current_loop.remove_handler(fd) diff --git a/venv/lib/python3.10/site-packages/zmq/_future.pyi b/venv/lib/python3.10/site-packages/zmq/_future.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e22315e82598249391a3bbffbbf2ecc5dd0d12d5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/_future.pyi @@ -0,0 +1,95 @@ +"""type annotations for async sockets""" + +from __future__ import annotations + +from asyncio import Future +from pickle import DEFAULT_PROTOCOL +from typing import Any, Awaitable, Literal, Sequence, TypeVar, overload + +import zmq as _zmq + +class _AsyncPoller(_zmq.Poller): + _socket_class: type[_AsyncSocket] + + def poll(self, timeout=-1) -> Awaitable[list[tuple[Any, int]]]: ... # type: ignore + +T = TypeVar("T", bound="_AsyncSocket") + +class _AsyncSocket(_zmq.Socket[Future]): + @classmethod + def from_socket(cls: type[T], socket: _zmq.Socket, io_loop: Any = None) -> T: ... + def send( # type: ignore + self, + data: Any, + flags: int = 0, + copy: bool = True, + track: bool = False, + routing_id: int | None = None, + group: str | None = None, + ) -> Awaitable[_zmq.MessageTracker | None]: ... + @overload # type: ignore + def recv(self, flags: int = 0, *, track: bool = False) -> Awaitable[bytes]: ... + @overload + def recv( + self, flags: int = 0, *, copy: Literal[True], track: bool = False + ) -> Awaitable[bytes]: ... + @overload + def recv( + self, flags: int = 0, *, copy: Literal[False], track: bool = False + ) -> Awaitable[_zmq.Frame]: ... + @overload + def recv( + self, flags: int = 0, copy: bool = True, track: bool = False + ) -> Awaitable[bytes | _zmq.Frame]: ... + def recv_into( # type: ignore + self, buffer: Any, /, *, nbytes: int = 0, flags: int = 0 + ) -> Awaitable[int]: ... + def send_multipart( # type: ignore + self, + msg_parts: Sequence, + flags: int = 0, + copy: bool = True, + track: bool = False, + routing_id: int | None = None, + group: str | None = None, + ) -> Awaitable[_zmq.MessageTracker | None]: ... + @overload # type: ignore + def recv_multipart( + self, flags: int = 0, *, track: bool = False + ) -> Awaitable[list[bytes]]: ... + @overload + def recv_multipart( + self, flags: int = 0, *, copy: Literal[True], track: bool = False + ) -> Awaitable[list[bytes]]: ... + @overload + def recv_multipart( + self, flags: int = 0, *, copy: Literal[False], track: bool = False + ) -> Awaitable[list[_zmq.Frame]]: ... + @overload + def recv_multipart( + self, flags: int = 0, copy: bool = True, track: bool = False + ) -> Awaitable[list[bytes] | list[_zmq.Frame]]: ... + + # serialization wrappers + + def send_string( # type: ignore + self, + u: str, + flags: int = 0, + copy: bool = True, + *, + encoding: str = 'utf-8', + **kwargs, + ) -> Awaitable[_zmq.Frame | None]: ... + def recv_string( # type: ignore + self, flags: int = 0, encoding: str = 'utf-8' + ) -> Awaitable[str]: ... + def send_pyobj( # type: ignore + self, obj: Any, flags: int = 0, protocol: int = DEFAULT_PROTOCOL, **kwargs + ) -> Awaitable[_zmq.Frame | None]: ... + def recv_pyobj(self, flags: int = 0) -> Awaitable[Any]: ... # type: ignore + def send_json( # type: ignore + self, obj: Any, flags: int = 0, **kwargs + ) -> Awaitable[_zmq.Frame | None]: ... + def recv_json(self, flags: int = 0, **kwargs) -> Awaitable[Any]: ... # type: ignore + def poll(self, timeout=-1) -> Awaitable[list[tuple[Any, int]]]: ... # type: ignore diff --git a/venv/lib/python3.10/site-packages/zmq/_typing.py b/venv/lib/python3.10/site-packages/zmq/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..9833a1b9d2bc5d66207e782773c2a09d8878ebcf --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/_typing.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +import sys + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + try: + from typing_extensions import TypeAlias + except ImportError: + TypeAlias = type # type: ignore diff --git a/venv/lib/python3.10/site-packages/zmq/asyncio.py b/venv/lib/python3.10/site-packages/zmq/asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..22bbd14d423cc2fb31efa7846681ab4420a2a6fd --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/asyncio.py @@ -0,0 +1,224 @@ +"""AsyncIO support for zmq + +Requires asyncio and Python 3. +""" + +# Copyright (c) PyZMQ Developers. +# Distributed under the terms of the Modified BSD License. +from __future__ import annotations + +import asyncio +import selectors +import sys +import warnings +from asyncio import Future, SelectorEventLoop +from weakref import WeakKeyDictionary + +import zmq as _zmq +from zmq import _future + +# registry of asyncio loop : selector thread +_selectors: WeakKeyDictionary = WeakKeyDictionary() + + +class ProactorSelectorThreadWarning(RuntimeWarning): + """Warning class for notifying about the extra thread spawned by tornado + + We automatically support proactor via tornado's AddThreadSelectorEventLoop""" + + +def _get_selector_windows( + asyncio_loop, +) -> asyncio.AbstractEventLoop: + """Get selector-compatible loop + + Returns an object with ``add_reader`` family of methods, + either the loop itself or a SelectorThread instance. + + Workaround Windows proactor removal of + *reader methods, which we need for zmq sockets. + """ + + if asyncio_loop in _selectors: + return _selectors[asyncio_loop] + + # detect add_reader instead of checking for proactor? + if hasattr(asyncio, "ProactorEventLoop") and isinstance( + asyncio_loop, + asyncio.ProactorEventLoop, # type: ignore + ): + try: + from tornado.platform.asyncio import AddThreadSelectorEventLoop + except ImportError: + raise RuntimeError( + "Proactor event loop does not implement add_reader family of methods required for zmq." + " zmq will work with proactor if tornado >= 6.1 can be found." + " Use `asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())`" + " or install 'tornado>=6.1' to avoid this error." + ) + + warnings.warn( + "Proactor event loop does not implement add_reader family of methods required for zmq." + " Registering an additional selector thread for add_reader support via tornado." + " Use `asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())`" + " to avoid this warning.", + RuntimeWarning, + # stacklevel 5 matches most likely zmq.asyncio.Context().socket() + stacklevel=5, + ) + + selector_loop = _selectors[asyncio_loop] = AddThreadSelectorEventLoop( + asyncio_loop + ) # type: ignore + + # patch loop.close to also close the selector thread + loop_close = asyncio_loop.close + + def _close_selector_and_loop(): + # restore original before calling selector.close, + # which in turn calls eventloop.close! + asyncio_loop.close = loop_close + _selectors.pop(asyncio_loop, None) + selector_loop.close() + + asyncio_loop.close = _close_selector_and_loop # type: ignore # mypy bug - assign a function to method + return selector_loop + else: + return asyncio_loop + + +def _get_selector_noop(loop) -> asyncio.AbstractEventLoop: + """no-op on non-Windows""" + return loop + + +if sys.platform == "win32": + _get_selector = _get_selector_windows +else: + _get_selector = _get_selector_noop + + +class _AsyncIO: + _Future = Future + _WRITE = selectors.EVENT_WRITE + _READ = selectors.EVENT_READ + + def _default_loop(self): + try: + return asyncio.get_running_loop() + except RuntimeError: + warnings.warn( + "No running event loop. zmq.asyncio should be used from within an asyncio loop.", + RuntimeWarning, + stacklevel=4, + ) + # get_event_loop deprecated in 3.10: + return asyncio.get_event_loop() + + +class Poller(_AsyncIO, _future._AsyncPoller): + """Poller returning asyncio.Future for poll results.""" + + def _watch_raw_socket(self, loop, socket, evt, f): + """Schedule callback for a raw socket""" + selector = _get_selector(loop) + if evt & self._READ: + selector.add_reader(socket, lambda *args: f()) + if evt & self._WRITE: + selector.add_writer(socket, lambda *args: f()) + + def _unwatch_raw_sockets(self, loop, *sockets): + """Unschedule callback for a raw socket""" + selector = _get_selector(loop) + for socket in sockets: + selector.remove_reader(socket) + selector.remove_writer(socket) + + +class Socket(_AsyncIO, _future._AsyncSocket): + """Socket returning asyncio Futures for send/recv/poll methods.""" + + _poller_class = Poller + + def _get_selector(self, io_loop=None): + if io_loop is None: + io_loop = self._get_loop() + return _get_selector(io_loop) + + def _init_io_state(self, io_loop=None): + """initialize the ioloop event handler""" + self._get_selector(io_loop).add_reader( + self._fd, lambda: self._handle_events(0, 0) + ) + + def _clear_io_state(self): + """clear any ioloop event handler + + called once at close + """ + loop = self._current_loop + if loop and not loop.is_closed() and self._fd != -1: + self._get_selector(loop).remove_reader(self._fd) + + +Poller._socket_class = Socket + + +class Context(_zmq.Context[Socket]): + """Context for creating asyncio-compatible Sockets""" + + _socket_class = Socket + + # avoid sharing instance with base Context class + _instance = None + + # overload with no changes to satisfy pyright + def __init__( + self: Context, + io_threads: int | _zmq.Context = 1, + shadow: _zmq.Context | int = 0, + ) -> None: + super().__init__(io_threads, shadow) # type: ignore + + +class ZMQEventLoop(SelectorEventLoop): + """DEPRECATED: AsyncIO eventloop using zmq_poll. + + pyzmq sockets should work with any asyncio event loop as of pyzmq 17. + """ + + def __init__(self, selector=None): + _deprecated() + return super().__init__(selector) + + +_loop = None + + +def _deprecated(): + if _deprecated.called: # type: ignore + return + _deprecated.called = True # type: ignore + + warnings.warn( + "ZMQEventLoop and zmq.asyncio.install are deprecated in pyzmq 17. Special eventloop integration is no longer needed.", + DeprecationWarning, + stacklevel=3, + ) + + +_deprecated.called = False # type: ignore + + +def install(): + """DEPRECATED: No longer needed in pyzmq 17""" + _deprecated() + + +__all__ = [ + "Context", + "Socket", + "Poller", + "ZMQEventLoop", + "install", +] diff --git a/venv/lib/python3.10/site-packages/zmq/auth/__init__.py b/venv/lib/python3.10/site-packages/zmq/auth/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ebacab71272ab4e1b7999ea8d6a875c08c6b861b --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/auth/__init__.py @@ -0,0 +1,13 @@ +"""Utilities for ZAP authentication. + +To run authentication in a background thread, see :mod:`zmq.auth.thread`. +For integration with the asyncio event loop, see :mod:`zmq.auth.asyncio`. + +Authentication examples are provided in the pyzmq codebase, under +`/examples/security/`. + +.. versionadded:: 14.1 +""" + +from .base import * +from .certs import * diff --git a/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..322102bfbbe04259deb224ab6adf733e02d71598 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/asyncio.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/asyncio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3824c519929eab6fe0d9cec8809b73c24c27f8c1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/asyncio.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/base.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c81b5f7ac0df40d6d2360b7c9407e66cb5d9b4a Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/base.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/certs.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/certs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da60b9f613f3cbf18196425345aba9c4caaa5271 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/certs.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/ioloop.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/ioloop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7091f70ae8df7c4753f07073c250c489eeac81e Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/ioloop.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/thread.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/thread.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35c8ebd32c7a11a220c47d5bf79ca2210fb07b02 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/auth/__pycache__/thread.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/auth/asyncio.py b/venv/lib/python3.10/site-packages/zmq/auth/asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..8b4915c12784538761dab70cee8e34395a1df066 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/auth/asyncio.py @@ -0,0 +1,66 @@ +"""ZAP Authenticator integrated with the asyncio IO loop. + +.. versionadded:: 15.2 +""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import asyncio +import warnings +from typing import Any, Optional + +import zmq +from zmq.asyncio import Poller + +from .base import Authenticator + + +class AsyncioAuthenticator(Authenticator): + """ZAP authentication for use in the asyncio IO loop""" + + __poller: Optional[Poller] + __task: Any + + def __init__( + self, + context: Optional["zmq.Context"] = None, + loop: Any = None, + encoding: str = 'utf-8', + log: Any = None, + ): + super().__init__(context, encoding, log) + if loop is not None: + warnings.warn( + f"{self.__class__.__name__}(loop) is deprecated and ignored", + DeprecationWarning, + stacklevel=2, + ) + self.__poller = None + self.__task = None + + async def __handle_zap(self) -> None: + while self.__poller is not None: + events = await self.__poller.poll() + if self.zap_socket in dict(events): + msg = self.zap_socket.recv_multipart() + await self.handle_zap_message(msg) + + def start(self) -> None: + """Start ZAP authentication""" + super().start() + self.__poller = Poller() + self.__poller.register(self.zap_socket, zmq.POLLIN) + self.__task = asyncio.ensure_future(self.__handle_zap()) + + def stop(self) -> None: + """Stop ZAP authentication""" + if self.__task: + self.__task.cancel() + if self.__poller: + self.__poller.unregister(self.zap_socket) + self.__poller = None + super().stop() + + +__all__ = ["AsyncioAuthenticator"] diff --git a/venv/lib/python3.10/site-packages/zmq/auth/base.py b/venv/lib/python3.10/site-packages/zmq/auth/base.py new file mode 100644 index 0000000000000000000000000000000000000000..c862b60c14f0625de1cf8c0006357760dce88d29 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/auth/base.py @@ -0,0 +1,445 @@ +"""Base implementation of 0MQ authentication.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import logging +import os +from typing import Any, Awaitable, Dict, List, Optional, Set, Tuple, Union + +import zmq +from zmq.error import _check_version +from zmq.utils import z85 + +from .certs import load_certificates + +CURVE_ALLOW_ANY = '*' +VERSION = b'1.0' + + +class Authenticator: + """Implementation of ZAP authentication for zmq connections. + + This authenticator class does not register with an event loop. As a result, + you will need to manually call `handle_zap_message`:: + + auth = zmq.Authenticator() + auth.allow("127.0.0.1") + auth.start() + while True: + await auth.handle_zap_msg(auth.zap_socket.recv_multipart()) + + Alternatively, you can register `auth.zap_socket` with a poller. + + Since many users will want to run ZAP in a way that does not block the + main thread, other authentication classes (such as :mod:`zmq.auth.thread`) + are provided. + + Note: + + - libzmq provides four levels of security: default NULL (which the Authenticator does + not see), and authenticated NULL, PLAIN, CURVE, and GSSAPI, which the Authenticator can see. + - until you add policies, all incoming NULL connections are allowed. + (classic ZeroMQ behavior), and all PLAIN and CURVE connections are denied. + - GSSAPI requires no configuration. + """ + + context: "zmq.Context" + encoding: str + allow_any: bool + credentials_providers: Dict[str, Any] + zap_socket: "zmq.Socket" + _allowed: Set[str] + _denied: Set[str] + passwords: Dict[str, Dict[str, str]] + certs: Dict[str, Dict[bytes, Any]] + log: Any + + def __init__( + self, + context: Optional["zmq.Context"] = None, + encoding: str = 'utf-8', + log: Any = None, + ): + _check_version((4, 0), "security") + self.context = context or zmq.Context.instance() + self.encoding = encoding + self.allow_any = False + self.credentials_providers = {} + self.zap_socket = None # type: ignore + self._allowed = set() + self._denied = set() + # passwords is a dict keyed by domain and contains values + # of dicts with username:password pairs. + self.passwords = {} + # certs is dict keyed by domain and contains values + # of dicts keyed by the public keys from the specified location. + self.certs = {} + self.log = log or logging.getLogger('zmq.auth') + + def start(self) -> None: + """Create and bind the ZAP socket""" + self.zap_socket = self.context.socket(zmq.REP, socket_class=zmq.Socket) + self.zap_socket.linger = 1 + self.zap_socket.bind("inproc://zeromq.zap.01") + self.log.debug("Starting") + + def stop(self) -> None: + """Close the ZAP socket""" + if self.zap_socket: + self.zap_socket.close() + self.zap_socket = None # type: ignore + + def allow(self, *addresses: str) -> None: + """Allow IP address(es). + + Connections from addresses not explicitly allowed will be rejected. + + - For NULL, all clients from this address will be accepted. + - For real auth setups, they will be allowed to continue with authentication. + + allow is mutually exclusive with deny. + """ + if self._denied: + raise ValueError("Only use allow or deny, not both") + self.log.debug("Allowing %s", ','.join(addresses)) + self._allowed.update(addresses) + + def deny(self, *addresses: str) -> None: + """Deny IP address(es). + + Addresses not explicitly denied will be allowed to continue with authentication. + + deny is mutually exclusive with allow. + """ + if self._allowed: + raise ValueError("Only use a allow or deny, not both") + self.log.debug("Denying %s", ','.join(addresses)) + self._denied.update(addresses) + + def configure_plain( + self, domain: str = '*', passwords: Optional[Dict[str, str]] = None + ) -> None: + """Configure PLAIN authentication for a given domain. + + PLAIN authentication uses a plain-text password file. + To cover all domains, use "*". + You can modify the password file at any time; it is reloaded automatically. + """ + if passwords: + self.passwords[domain] = passwords + self.log.debug("Configure plain: %s", domain) + + def configure_curve( + self, domain: str = '*', location: Union[str, os.PathLike] = "." + ) -> None: + """Configure CURVE authentication for a given domain. + + CURVE authentication uses a directory that holds all public client certificates, + i.e. their public keys. + + To cover all domains, use "*". + + You can add and remove certificates in that directory at any time. configure_curve must be called + every time certificates are added or removed, in order to update the Authenticator's state + + To allow all client keys without checking, specify CURVE_ALLOW_ANY for the location. + """ + # If location is CURVE_ALLOW_ANY then allow all clients. Otherwise + # treat location as a directory that holds the certificates. + self.log.debug("Configure curve: %s[%s]", domain, location) + if location == CURVE_ALLOW_ANY: + self.allow_any = True + else: + self.allow_any = False + try: + self.certs[domain] = load_certificates(location) + except Exception as e: + self.log.error("Failed to load CURVE certs from %s: %s", location, e) + + def configure_curve_callback( + self, domain: str = '*', credentials_provider: Any = None + ) -> None: + """Configure CURVE authentication for a given domain. + + CURVE authentication using a callback function validating + the client public key according to a custom mechanism, e.g. checking the + key against records in a db. credentials_provider is an object of a class which + implements a callback method accepting two parameters (domain and key), e.g.:: + + class CredentialsProvider(object): + + def __init__(self): + ...e.g. db connection + + def callback(self, domain, key): + valid = ...lookup key and/or domain in db + if valid: + logging.info('Authorizing: {0}, {1}'.format(domain, key)) + return True + else: + logging.warning('NOT Authorizing: {0}, {1}'.format(domain, key)) + return False + + To cover all domains, use "*". + """ + + self.allow_any = False + + if credentials_provider is not None: + self.credentials_providers[domain] = credentials_provider + else: + self.log.error("None credentials_provider provided for domain:%s", domain) + + def curve_user_id(self, client_public_key: bytes) -> str: + """Return the User-Id corresponding to a CURVE client's public key + + Default implementation uses the z85-encoding of the public key. + + Override to define a custom mapping of public key : user-id + + This is only called on successful authentication. + + Parameters + ---------- + client_public_key: bytes + The client public key used for the given message + + Returns + ------- + user_id: unicode + The user ID as text + """ + return z85.encode(client_public_key).decode('ascii') + + def configure_gssapi( + self, domain: str = '*', location: Optional[str] = None + ) -> None: + """Configure GSSAPI authentication + + Currently this is a no-op because there is nothing to configure with GSSAPI. + """ + + async def handle_zap_message(self, msg: List[bytes]): + """Perform ZAP authentication""" + if len(msg) < 6: + self.log.error("Invalid ZAP message, not enough frames: %r", msg) + if len(msg) < 2: + self.log.error("Not enough information to reply") + else: + self._send_zap_reply(msg[1], b"400", b"Not enough frames") + return + + version, request_id, domain, address, identity, mechanism = msg[:6] + credentials = msg[6:] + + domain = domain.decode(self.encoding, 'replace') + address = address.decode(self.encoding, 'replace') + + if version != VERSION: + self.log.error("Invalid ZAP version: %r", msg) + self._send_zap_reply(request_id, b"400", b"Invalid version") + return + + self.log.debug( + "version: %r, request_id: %r, domain: %r," + " address: %r, identity: %r, mechanism: %r", + version, + request_id, + domain, + address, + identity, + mechanism, + ) + + # Is address is explicitly allowed or _denied? + allowed = False + denied = False + reason = b"NO ACCESS" + + if self._allowed: + if address in self._allowed: + allowed = True + self.log.debug("PASSED (allowed) address=%s", address) + else: + denied = True + reason = b"Address not allowed" + self.log.debug("DENIED (not allowed) address=%s", address) + + elif self._denied: + if address in self._denied: + denied = True + reason = b"Address denied" + self.log.debug("DENIED (denied) address=%s", address) + else: + allowed = True + self.log.debug("PASSED (not denied) address=%s", address) + + # Perform authentication mechanism-specific checks if necessary + username = "anonymous" + if not denied: + if mechanism == b'NULL' and not allowed: + # For NULL, we allow if the address wasn't denied + self.log.debug("ALLOWED (NULL)") + allowed = True + + elif mechanism == b'PLAIN': + # For PLAIN, even a _alloweded address must authenticate + if len(credentials) != 2: + self.log.error("Invalid PLAIN credentials: %r", credentials) + self._send_zap_reply(request_id, b"400", b"Invalid credentials") + return + username, password = ( + c.decode(self.encoding, 'replace') for c in credentials + ) + allowed, reason = self._authenticate_plain(domain, username, password) + + elif mechanism == b'CURVE': + # For CURVE, even a _alloweded address must authenticate + if len(credentials) != 1: + self.log.error("Invalid CURVE credentials: %r", credentials) + self._send_zap_reply(request_id, b"400", b"Invalid credentials") + return + key = credentials[0] + allowed, reason = await self._authenticate_curve(domain, key) + if allowed: + username = self.curve_user_id(key) + + elif mechanism == b'GSSAPI': + if len(credentials) != 1: + self.log.error("Invalid GSSAPI credentials: %r", credentials) + self._send_zap_reply(request_id, b"400", b"Invalid credentials") + return + # use principal as user-id for now + principal = credentials[0] + username = principal.decode("utf8") + allowed, reason = self._authenticate_gssapi(domain, principal) + + if allowed: + self._send_zap_reply(request_id, b"200", b"OK", username) + else: + self._send_zap_reply(request_id, b"400", reason) + + def _authenticate_plain( + self, domain: str, username: str, password: str + ) -> Tuple[bool, bytes]: + """PLAIN ZAP authentication""" + allowed = False + reason = b"" + if self.passwords: + # If no domain is not specified then use the default domain + if not domain: + domain = '*' + + if domain in self.passwords: + if username in self.passwords[domain]: + if password == self.passwords[domain][username]: + allowed = True + else: + reason = b"Invalid password" + else: + reason = b"Invalid username" + else: + reason = b"Invalid domain" + + if allowed: + self.log.debug( + "ALLOWED (PLAIN) domain=%s username=%s password=%s", + domain, + username, + password, + ) + else: + self.log.debug("DENIED %s", reason) + + else: + reason = b"No passwords defined" + self.log.debug("DENIED (PLAIN) %s", reason) + + return allowed, reason + + async def _authenticate_curve( + self, domain: str, client_key: bytes + ) -> Tuple[bool, bytes]: + """CURVE ZAP authentication""" + allowed = False + reason = b"" + if self.allow_any: + allowed = True + reason = b"OK" + self.log.debug("ALLOWED (CURVE allow any client)") + elif self.credentials_providers != {}: + # If no explicit domain is specified then use the default domain + if not domain: + domain = '*' + + if domain in self.credentials_providers: + z85_client_key = z85.encode(client_key) + # Callback to check if key is Allowed + r = self.credentials_providers[domain].callback(domain, z85_client_key) + if isinstance(r, Awaitable): + r = await r + if r: + allowed = True + reason = b"OK" + else: + reason = b"Unknown key" + + status = "ALLOWED" if allowed else "DENIED" + self.log.debug( + "%s (CURVE auth_callback) domain=%s client_key=%s", + status, + domain, + z85_client_key, + ) + else: + reason = b"Unknown domain" + else: + # If no explicit domain is specified then use the default domain + if not domain: + domain = '*' + + if domain in self.certs: + # The certs dict stores keys in z85 format, convert binary key to z85 bytes + z85_client_key = z85.encode(client_key) + if self.certs[domain].get(z85_client_key): + allowed = True + reason = b"OK" + else: + reason = b"Unknown key" + + status = "ALLOWED" if allowed else "DENIED" + self.log.debug( + "%s (CURVE) domain=%s client_key=%s", + status, + domain, + z85_client_key, + ) + else: + reason = b"Unknown domain" + + return allowed, reason + + def _authenticate_gssapi(self, domain: str, principal: bytes) -> Tuple[bool, bytes]: + """Nothing to do for GSSAPI, which has already been handled by an external service.""" + self.log.debug("ALLOWED (GSSAPI) domain=%s principal=%s", domain, principal) + return True, b'OK' + + def _send_zap_reply( + self, + request_id: bytes, + status_code: bytes, + status_text: bytes, + user_id: str = 'anonymous', + ) -> None: + """Send a ZAP reply to finish the authentication.""" + user_id = user_id if status_code == b'200' else b'' + if isinstance(user_id, str): + user_id = user_id.encode(self.encoding, 'replace') + metadata = b'' # not currently used + self.log.debug("ZAP reply code=%s text=%s", status_code, status_text) + reply = [VERSION, request_id, status_code, status_text, user_id, metadata] + self.zap_socket.send_multipart(reply) + + +__all__ = ['Authenticator', 'CURVE_ALLOW_ANY'] diff --git a/venv/lib/python3.10/site-packages/zmq/auth/certs.py b/venv/lib/python3.10/site-packages/zmq/auth/certs.py new file mode 100644 index 0000000000000000000000000000000000000000..d60ae005dc111da80576adcdc378390ba6026527 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/auth/certs.py @@ -0,0 +1,140 @@ +"""0MQ authentication related functions and classes.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import datetime +import glob +import os +from typing import Dict, Optional, Tuple, Union + +import zmq + +_cert_secret_banner = """# **** Generated on {0} by pyzmq **** +# ZeroMQ CURVE **Secret** Certificate +# DO NOT PROVIDE THIS FILE TO OTHER USERS nor change its permissions. + +""" + + +_cert_public_banner = """# **** Generated on {0} by pyzmq **** +# ZeroMQ CURVE Public Certificate +# Exchange securely, or use a secure mechanism to verify the contents +# of this file after exchange. Store public certificates in your home +# directory, in the .curve subdirectory. + +""" + + +def _write_key_file( + key_filename: Union[str, os.PathLike], + banner: str, + public_key: Union[str, bytes], + secret_key: Optional[Union[str, bytes]] = None, + metadata: Optional[Dict[str, str]] = None, + encoding: str = 'utf-8', +) -> None: + """Create a certificate file""" + if isinstance(public_key, bytes): + public_key = public_key.decode(encoding) + if isinstance(secret_key, bytes): + secret_key = secret_key.decode(encoding) + with open(key_filename, 'w', encoding='utf8') as f: + f.write(banner.format(datetime.datetime.now())) + + f.write('metadata\n') + if metadata: + for k, v in metadata.items(): + if isinstance(k, bytes): + k = k.decode(encoding) + if isinstance(v, bytes): + v = v.decode(encoding) + f.write(f" {k} = {v}\n") + + f.write('curve\n') + f.write(f" public-key = \"{public_key}\"\n") + + if secret_key: + f.write(f" secret-key = \"{secret_key}\"\n") + + +def create_certificates( + key_dir: Union[str, os.PathLike], + name: str, + metadata: Optional[Dict[str, str]] = None, +) -> Tuple[str, str]: + """Create zmq certificates. + + Returns the file paths to the public and secret certificate files. + """ + public_key, secret_key = zmq.curve_keypair() + base_filename = os.path.join(key_dir, name) + secret_key_file = f"{base_filename}.key_secret" + public_key_file = f"{base_filename}.key" + now = datetime.datetime.now() + + _write_key_file(public_key_file, _cert_public_banner.format(now), public_key) + + _write_key_file( + secret_key_file, + _cert_secret_banner.format(now), + public_key, + secret_key=secret_key, + metadata=metadata, + ) + + return public_key_file, secret_key_file + + +def load_certificate( + filename: Union[str, os.PathLike], +) -> Tuple[bytes, Optional[bytes]]: + """Load public and secret key from a zmq certificate. + + Returns (public_key, secret_key) + + If the certificate file only contains the public key, + secret_key will be None. + + If there is no public key found in the file, ValueError will be raised. + """ + public_key = None + secret_key = None + if not os.path.exists(filename): + raise OSError(f"Invalid certificate file: {filename}") + + with open(filename, 'rb') as f: + for line in f: + line = line.strip() + if line.startswith(b'#'): + continue + if line.startswith(b'public-key'): + public_key = line.split(b"=", 1)[1].strip(b' \t\'"') + if line.startswith(b'secret-key'): + secret_key = line.split(b"=", 1)[1].strip(b' \t\'"') + if public_key and secret_key: + break + + if public_key is None: + raise ValueError(f"No public key found in {filename}") + + return public_key, secret_key + + +def load_certificates(directory: Union[str, os.PathLike] = '.') -> Dict[bytes, bool]: + """Load public keys from all certificates in a directory""" + certs = {} + if not os.path.isdir(directory): + raise OSError(f"Invalid certificate directory: {directory}") + # Follow czmq pattern of public keys stored in *.key files. + glob_string = os.path.join(directory, "*.key") + + cert_files = glob.glob(glob_string) + for cert_file in cert_files: + public_key, _ = load_certificate(cert_file) + if public_key: + certs[public_key] = True + return certs + + +__all__ = ['create_certificates', 'load_certificate', 'load_certificates'] diff --git a/venv/lib/python3.10/site-packages/zmq/auth/ioloop.py b/venv/lib/python3.10/site-packages/zmq/auth/ioloop.py new file mode 100644 index 0000000000000000000000000000000000000000..f87f068e7ef92004a7bbad93e77e445a607e0093 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/auth/ioloop.py @@ -0,0 +1,48 @@ +"""ZAP Authenticator integrated with the tornado IOLoop. + +.. versionadded:: 14.1 +.. deprecated:: 25 + Use asyncio.AsyncioAuthenticator instead. + Since tornado runs on asyncio, the asyncio authenticator + offers the same functionality in tornado. +""" + +import warnings + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. +from typing import Any, Optional + +import zmq + +from .asyncio import AsyncioAuthenticator + +warnings.warn( + "zmq.auth.ioloop.IOLoopAuthenticator is deprecated. Use zmq.auth.asyncio.AsyncioAuthenticator", + DeprecationWarning, + stacklevel=2, +) + + +class IOLoopAuthenticator(AsyncioAuthenticator): + """ZAP authentication for use in the tornado IOLoop""" + + def __init__( + self, + context: Optional["zmq.Context"] = None, + encoding: str = 'utf-8', + log: Any = None, + io_loop: Any = None, + ): + loop = None + if io_loop is not None: + warnings.warn( + f"{self.__class__.__name__}(io_loop) is deprecated and ignored", + DeprecationWarning, + stacklevel=2, + ) + loop = io_loop.asyncio_loop + super().__init__(context=context, encoding=encoding, log=log, loop=loop) + + +__all__ = ['IOLoopAuthenticator'] diff --git a/venv/lib/python3.10/site-packages/zmq/auth/thread.py b/venv/lib/python3.10/site-packages/zmq/auth/thread.py new file mode 100644 index 0000000000000000000000000000000000000000..a227c4bd5974f95e3b5b844a1ce0de34f9454f10 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/auth/thread.py @@ -0,0 +1,139 @@ +"""ZAP Authenticator in a Python Thread. + +.. versionadded:: 14.1 +""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import asyncio +from threading import Event, Thread +from typing import Any, List, Optional + +import zmq +import zmq.asyncio + +from .base import Authenticator + + +class AuthenticationThread(Thread): + """A Thread for running a zmq Authenticator + + This is run in the background by ThreadAuthenticator + """ + + pipe: zmq.Socket + loop: asyncio.AbstractEventLoop + authenticator: Authenticator + poller: Optional[zmq.asyncio.Poller] = None + + def __init__( + self, + authenticator: Authenticator, + pipe: zmq.Socket, + ) -> None: + super().__init__(daemon=True) + self.authenticator = authenticator + self.log = authenticator.log + self.pipe = pipe + + self.started = Event() + + def run(self) -> None: + """Start the Authentication Agent thread task""" + + loop = asyncio.new_event_loop() + try: + loop.run_until_complete(self._run()) + finally: + if self.pipe: + self.pipe.close() + self.pipe = None # type: ignore + + loop.close() + + async def _run(self): + self.poller = zmq.asyncio.Poller() + self.poller.register(self.pipe, zmq.POLLIN) + self.poller.register(self.authenticator.zap_socket, zmq.POLLIN) + self.started.set() + + while True: + events = dict(await self.poller.poll()) + if self.pipe in events: + msg = self.pipe.recv_multipart() + if self._handle_pipe_message(msg): + return + if self.authenticator.zap_socket in events: + msg = self.authenticator.zap_socket.recv_multipart() + await self.authenticator.handle_zap_message(msg) + + def _handle_pipe_message(self, msg: List[bytes]) -> bool: + command = msg[0] + self.log.debug("auth received API command %r", command) + + if command == b'TERMINATE': + return True + + else: + self.log.error("Invalid auth command from API: %r", command) + self.pipe.send(b'ERROR') + + return False + + +class ThreadAuthenticator(Authenticator): + """Run ZAP authentication in a background thread""" + + pipe: "zmq.Socket" + pipe_endpoint: str = '' + thread: AuthenticationThread + + def __init__( + self, + context: Optional["zmq.Context"] = None, + encoding: str = 'utf-8', + log: Any = None, + ): + super().__init__(context=context, encoding=encoding, log=log) + self.pipe = None # type: ignore + self.pipe_endpoint = f"inproc://{id(self)}.inproc" + self.thread = None # type: ignore + + def start(self) -> None: + """Start the authentication thread""" + # start the Authenticator + super().start() + + # create a socket pair to communicate with auth thread. + self.pipe = self.context.socket(zmq.PAIR, socket_class=zmq.Socket) + self.pipe.linger = 1 + self.pipe.bind(self.pipe_endpoint) + thread_pipe = self.context.socket(zmq.PAIR, socket_class=zmq.Socket) + thread_pipe.linger = 1 + thread_pipe.connect(self.pipe_endpoint) + self.thread = AuthenticationThread(authenticator=self, pipe=thread_pipe) + self.thread.start() + if not self.thread.started.wait(timeout=10): + raise RuntimeError("Authenticator thread failed to start") + + def stop(self) -> None: + """Stop the authentication thread""" + if self.pipe: + self.pipe.send(b'TERMINATE') + if self.is_alive(): + self.thread.join() + self.thread = None # type: ignore + self.pipe.close() + self.pipe = None # type: ignore + super().stop() + + def is_alive(self) -> bool: + """Is the ZAP thread currently running?""" + return bool(self.thread and self.thread.is_alive()) + + def __del__(self) -> None: + self.stop() + + +__all__ = ['ThreadAuthenticator'] diff --git a/venv/lib/python3.10/site-packages/zmq/backend/__init__.py b/venv/lib/python3.10/site-packages/zmq/backend/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..15f696d9d3ad5275443eb3145b9c4087f1e6609f --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/__init__.py @@ -0,0 +1,34 @@ +"""Import basic exposure of libzmq C API as a backend""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import os +import platform + +from .select import public_api, select_backend + +if 'PYZMQ_BACKEND' in os.environ: + backend = os.environ['PYZMQ_BACKEND'] + if backend in ('cython', 'cffi'): + backend = f'zmq.backend.{backend}' + _ns = select_backend(backend) +else: + # default to cython, fallback to cffi + # (reverse on PyPy) + if platform.python_implementation() == 'PyPy': + first, second = ('zmq.backend.cffi', 'zmq.backend.cython') + else: + first, second = ('zmq.backend.cython', 'zmq.backend.cffi') + + try: + _ns = select_backend(first) + except Exception as original_error: + try: + _ns = select_backend(second) + except ImportError: + raise original_error from None + +globals().update(_ns) + +__all__ = public_api diff --git a/venv/lib/python3.10/site-packages/zmq/backend/__init__.pyi b/venv/lib/python3.10/site-packages/zmq/backend/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..72b6e802b63eabf6e5f9b3727086798e027abc76 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/__init__.pyi @@ -0,0 +1,122 @@ +from typing import Any, Callable, List, Optional, Set, Tuple, TypeVar, Union, overload + +from typing_extensions import Literal + +import zmq + +from .select import select_backend + +# avoid collision in Frame.bytes +_bytestr = bytes + +T = TypeVar("T") + +class Frame: + buffer: Any + bytes: bytes + more: bool + tracker: Any + def __init__( + self, + data: Any = None, + track: bool = False, + copy: bool | None = None, + copy_threshold: int | None = None, + ): ... + def copy_fast(self: T) -> T: ... + def get(self, option: int) -> int | _bytestr | str: ... + def set(self, option: int, value: int | _bytestr | str) -> None: ... + +class Socket: + underlying: int + context: zmq.Context + copy_threshold: int + + # specific option types + FD: int + + def __init__( + self, + context: Context | None = None, + socket_type: int = 0, + shadow: int = 0, + copy_threshold: int | None = zmq.COPY_THRESHOLD, + ) -> None: ... + def close(self, linger: int | None = ...) -> None: ... + def get(self, option: int) -> int | bytes | str: ... + def set(self, option: int, value: int | bytes | str) -> None: ... + def connect(self, url: str): ... + def disconnect(self, url: str) -> None: ... + def bind(self, url: str): ... + def unbind(self, url: str) -> None: ... + def send( + self, + data: Any, + flags: int = ..., + copy: bool = ..., + track: bool = ..., + ) -> zmq.MessageTracker | None: ... + @overload + def recv( + self, + flags: int = ..., + *, + copy: Literal[False], + track: bool = ..., + ) -> zmq.Frame: ... + @overload + def recv( + self, + flags: int = ..., + *, + copy: Literal[True], + track: bool = ..., + ) -> bytes: ... + @overload + def recv( + self, + flags: int = ..., + track: bool = False, + ) -> bytes: ... + @overload + def recv( + self, + flags: int | None = ..., + copy: bool = ..., + track: bool | None = False, + ) -> zmq.Frame | bytes: ... + def recv_into(self, buf, /, *, nbytes: int = 0, flags: int = 0) -> int: ... + def monitor(self, addr: str | None, events: int) -> None: ... + # draft methods + def join(self, group: str) -> None: ... + def leave(self, group: str) -> None: ... + +class Context: + underlying: int + def __init__(self, io_threads: int = 1, shadow: int = 0): ... + def get(self, option: int) -> int | bytes | str: ... + def set(self, option: int, value: int | bytes | str) -> None: ... + def socket(self, socket_type: int) -> Socket: ... + def term(self) -> None: ... + +IPC_PATH_MAX_LEN: int + +def has(capability: str) -> bool: ... +def curve_keypair() -> tuple[bytes, bytes]: ... +def curve_public(secret_key: bytes) -> bytes: ... +def strerror(errno: int | None = ...) -> str: ... +def zmq_errno() -> int: ... +def zmq_version() -> str: ... +def zmq_version_info() -> tuple[int, int, int]: ... +def zmq_poll( + sockets: list[Any], timeout: int | None = ... +) -> list[tuple[Socket, int]]: ... +def proxy(frontend: Socket, backend: Socket, capture: Socket | None = None) -> int: ... +def proxy_steerable( + frontend: Socket, + backend: Socket, + capture: Socket | None = ..., + control: Socket | None = ..., +) -> int: ... + +monitored_queue = Callable | None diff --git a/venv/lib/python3.10/site-packages/zmq/backend/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/backend/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2391acc5501352c61a8d57519fcc5b7b743fe73 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/backend/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/backend/__pycache__/select.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/backend/__pycache__/select.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4d7fa2ff56c3ced9ee438c98ffe36dacfc06c74 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/backend/__pycache__/select.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/README.md b/venv/lib/python3.10/site-packages/zmq/backend/cffi/README.md new file mode 100644 index 0000000000000000000000000000000000000000..00bb32989dcfbc787760075fd6dc4801568ab0a2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cffi/README.md @@ -0,0 +1 @@ +PyZMQ's CFFI support is designed only for (Unix) systems conforming to `have_sys_un_h = True`. diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/__init__.py b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ce929a7a6a6bbe84c6a1cdd873095152837cd44c --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__init__.py @@ -0,0 +1,38 @@ +"""CFFI backend (for PyPy)""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +# for clearer error message on missing cffi +import cffi # noqa + +from zmq.backend.cffi import _poll, context, devices, error, message, socket, utils + +from ._cffi import ffi +from ._cffi import lib as C + + +def zmq_version_info(): + """Get libzmq version as tuple of ints""" + major = ffi.new('int*') + minor = ffi.new('int*') + patch = ffi.new('int*') + + C.zmq_version(major, minor, patch) + + return (int(major[0]), int(minor[0]), int(patch[0])) + + +__all__ = ["zmq_version_info"] +for submod in (error, message, context, socket, _poll, devices, utils): + __all__.extend(submod.__all__) + +from ._poll import * +from .context import * +from .devices import * +from .error import * +from .message import * +from .socket import * +from .utils import * + +monitored_queue = None diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62b05042d3fab30875c3b4e57e56ad907fe6a1ef Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/_poll.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/_poll.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c6c8d2ee34ceb3cae480512ed08e36703e4e013 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/_poll.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/context.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/context.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edae07d5634af21b1bf4f7cbfdaa41bb9e90a528 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/context.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/devices.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/devices.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7df2fde94feba1a6ea20aa25333cba3661bcfbac Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/devices.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/error.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/error.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..829e56c7e6cd2c55bf7c79af5845c8d04495d386 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/error.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/message.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/message.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b964e88cfe99a3afaeb6a928cad1dced010785ce Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/message.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/socket.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/socket.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f525b7bad2891580e7174cc3de5454b44e94d39 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/socket.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4ee9229f70eff7f3309ab6b2425571003677132 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/backend/cffi/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/_cdefs.h b/venv/lib/python3.10/site-packages/zmq/backend/cffi/_cdefs.h new file mode 100644 index 0000000000000000000000000000000000000000..56193342237bdcff5ea21b6b137bf6dbbeea5b00 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cffi/_cdefs.h @@ -0,0 +1,96 @@ +void zmq_version(int *major, int *minor, int *patch); + +void* zmq_socket(void *context, int type); +int zmq_close(void *socket); + +int zmq_bind(void *socket, const char *endpoint); +int zmq_connect(void *socket, const char *endpoint); + +int zmq_errno(void); +const char * zmq_strerror(int errnum); + +int zmq_unbind(void *socket, const char *endpoint); +int zmq_disconnect(void *socket, const char *endpoint); +void* zmq_ctx_new(); +int zmq_ctx_destroy(void *context); +int zmq_ctx_get(void *context, int opt); +int zmq_ctx_set(void *context, int opt, int optval); +int zmq_proxy(void *frontend, void *backend, void *capture); +int zmq_proxy_steerable(void *frontend, + void *backend, + void *capture, + void *control); +int zmq_socket_monitor(void *socket, const char *addr, int events); + +int zmq_curve_keypair (char *z85_public_key, char *z85_secret_key); +int zmq_curve_public (char *z85_public_key, char *z85_secret_key); +int zmq_has (const char *capability); + +typedef struct { ...; } zmq_msg_t; +typedef ... zmq_free_fn; + +int zmq_msg_init(zmq_msg_t *msg); +int zmq_msg_init_size(zmq_msg_t *msg, size_t size); +int zmq_msg_init_data(zmq_msg_t *msg, + void *data, + size_t size, + zmq_free_fn *ffn, + void *hint); + +size_t zmq_msg_size(zmq_msg_t *msg); +void *zmq_msg_data(zmq_msg_t *msg); +int zmq_msg_close(zmq_msg_t *msg); + +int zmq_msg_copy(zmq_msg_t *dst, zmq_msg_t *src); +int zmq_msg_send(zmq_msg_t *msg, void *socket, int flags); +int zmq_msg_recv(zmq_msg_t *msg, void *socket, int flags); +int zmq_recv(void *socket, void *buf, int nbytes, int flags); + +int zmq_getsockopt(void *socket, + int option_name, + void *option_value, + size_t *option_len); + +int zmq_setsockopt(void *socket, + int option_name, + const void *option_value, + size_t option_len); + +typedef int... ZMQ_FD_T; + +typedef struct +{ + void *socket; + ZMQ_FD_T fd; + short events; + short revents; +} zmq_pollitem_t; + +int zmq_poll(zmq_pollitem_t *items, int nitems, long timeout); + +// draft poller +void *zmq_poller_new (); +int zmq_poller_destroy (void **poller_p_); +int zmq_poller_add (void *poller_, void *socket_, void *user_data_, short events_); +int zmq_poller_fd (void *poller_, ZMQ_FD_T *fd_); + +// miscellany +void * memcpy(void *restrict s1, const void *restrict s2, size_t n); +void * malloc(size_t sz); +void free(void *p); +int get_ipc_path_max_len(void); + +typedef struct { ...; } mutex_t; + +typedef struct _zhint { + void *sock; + mutex_t *mutex; + size_t id; +} zhint; + +mutex_t* mutex_allocate(); + +int zmq_wrap_msg_init_data(zmq_msg_t *msg, + void *data, + size_t size, + void *hint); diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/_cffi_src.c b/venv/lib/python3.10/site-packages/zmq/backend/cffi/_cffi_src.c new file mode 100644 index 0000000000000000000000000000000000000000..691be3c782d3d8209dc67e12d241e749e08440cb --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cffi/_cffi_src.c @@ -0,0 +1,50 @@ +#include +#include + +#include "pyversion_compat.h" +#include "mutex.h" +#include "ipcmaxlen.h" +#include "zmq_compat.h" +#include + +typedef struct _zhint { + void *sock; + mutex_t *mutex; + size_t id; +} zhint; + +void free_python_msg(void *data, void *vhint) { + zmq_msg_t msg; + zhint *hint = (zhint *)vhint; + int rc; + if (hint != NULL) { + zmq_msg_init_size(&msg, sizeof(size_t)); + memcpy(zmq_msg_data(&msg), &hint->id, sizeof(size_t)); + rc = mutex_lock(hint->mutex); + if (rc != 0) { + fprintf(stderr, "pyzmq-gc mutex lock failed rc=%d\n", rc); + } + rc = zmq_msg_send(&msg, hint->sock, 0); + if (rc < 0) { + /* + * gc socket could have been closed, e.g. during process teardown. + * If so, ignore the failure because there's nothing to do. + */ + if (zmq_errno() != ENOTSOCK) { + fprintf(stderr, "pyzmq-gc send failed: %s\n", + zmq_strerror(zmq_errno())); + } + } + rc = mutex_unlock(hint->mutex); + if (rc != 0) { + fprintf(stderr, "pyzmq-gc mutex unlock failed rc=%d\n", rc); + } + zmq_msg_close(&msg); + free(hint); + } +} + +int zmq_wrap_msg_init_data(zmq_msg_t *msg, void *data, size_t size, + void *hint) { + return zmq_msg_init_data(msg, data, size, free_python_msg, hint); +} diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/_poll.py b/venv/lib/python3.10/site-packages/zmq/backend/cffi/_poll.py new file mode 100644 index 0000000000000000000000000000000000000000..63e2763b9c57b065b963df9b0a1f86cd9fe30af0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cffi/_poll.py @@ -0,0 +1,92 @@ +"""zmq poll function""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +try: + from time import monotonic +except ImportError: + from time import clock as monotonic + +import warnings + +from zmq.error import InterruptedSystemCall, _check_rc + +from ._cffi import ffi +from ._cffi import lib as C + + +def _make_zmq_pollitem(socket, flags): + zmq_socket = socket._zmq_socket + zmq_pollitem = ffi.new('zmq_pollitem_t*') + zmq_pollitem.socket = zmq_socket + zmq_pollitem.fd = 0 + zmq_pollitem.events = flags + zmq_pollitem.revents = 0 + return zmq_pollitem[0] + + +def _make_zmq_pollitem_fromfd(socket_fd, flags): + zmq_pollitem = ffi.new('zmq_pollitem_t*') + zmq_pollitem.socket = ffi.NULL + zmq_pollitem.fd = socket_fd + zmq_pollitem.events = flags + zmq_pollitem.revents = 0 + return zmq_pollitem[0] + + +def zmq_poll(sockets, timeout): + cffi_pollitem_list = [] + low_level_to_socket_obj = {} + from zmq import Socket + + for item in sockets: + if isinstance(item[0], Socket): + low_level_to_socket_obj[item[0]._zmq_socket] = item + cffi_pollitem_list.append(_make_zmq_pollitem(item[0], item[1])) + else: + if not isinstance(item[0], int): + # not an FD, get it from fileno() + item = (item[0].fileno(), item[1]) + low_level_to_socket_obj[item[0]] = item + cffi_pollitem_list.append(_make_zmq_pollitem_fromfd(item[0], item[1])) + items = ffi.new('zmq_pollitem_t[]', cffi_pollitem_list) + list_length = ffi.cast('int', len(cffi_pollitem_list)) + while True: + c_timeout = ffi.cast('long', timeout) + start = monotonic() + rc = C.zmq_poll(items, list_length, c_timeout) + try: + _check_rc(rc) + except InterruptedSystemCall: + if timeout > 0: + ms_passed = int(1000 * (monotonic() - start)) + if ms_passed < 0: + # don't allow negative ms_passed, + # which can happen on old Python versions without time.monotonic. + warnings.warn( + f"Negative elapsed time for interrupted poll: {ms_passed}." + " Did the clock change?", + RuntimeWarning, + ) + ms_passed = 0 + timeout = max(0, timeout - ms_passed) + continue + else: + break + result = [] + for item in items: + if item.revents > 0: + if item.socket != ffi.NULL: + result.append( + ( + low_level_to_socket_obj[item.socket][0], + item.revents, + ) + ) + else: + result.append((item.fd, item.revents)) + return result + + +__all__ = ['zmq_poll'] diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/context.py b/venv/lib/python3.10/site-packages/zmq/backend/cffi/context.py new file mode 100644 index 0000000000000000000000000000000000000000..23a69ecf1d97c1353470ebec03601370b8a5eb73 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cffi/context.py @@ -0,0 +1,77 @@ +"""zmq Context class""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from zmq.constants import EINVAL, IO_THREADS +from zmq.error import InterruptedSystemCall, ZMQError, _check_rc + +from ._cffi import ffi +from ._cffi import lib as C + + +class Context: + _zmq_ctx = None + _iothreads = None + _closed = True + _shadow = False + + def __init__(self, io_threads=1, shadow=None): + if shadow: + self._zmq_ctx = ffi.cast("void *", shadow) + self._shadow = True + else: + self._shadow = False + if not io_threads >= 0: + raise ZMQError(EINVAL) + + self._zmq_ctx = C.zmq_ctx_new() + if self._zmq_ctx == ffi.NULL: + raise ZMQError(C.zmq_errno()) + if not shadow: + C.zmq_ctx_set(self._zmq_ctx, IO_THREADS, io_threads) + self._closed = False + + @property + def underlying(self): + """The address of the underlying libzmq context""" + return int(ffi.cast('size_t', self._zmq_ctx)) + + @property + def closed(self): + return self._closed + + def set(self, option, value): + """set a context option + + see zmq_ctx_set + """ + rc = C.zmq_ctx_set(self._zmq_ctx, option, value) + _check_rc(rc) + + def get(self, option): + """get context option + + see zmq_ctx_get + """ + rc = C.zmq_ctx_get(self._zmq_ctx, option) + _check_rc(rc, error_without_errno=False) + return rc + + def term(self): + if self.closed: + return + + rc = C.zmq_ctx_destroy(self._zmq_ctx) + try: + _check_rc(rc) + except InterruptedSystemCall: + # ignore interrupted term + # see PEP 475 notes about close & EINTR for why + pass + + self._zmq_ctx = None + self._closed = True + + +__all__ = ['Context'] diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/devices.py b/venv/lib/python3.10/site-packages/zmq/backend/cffi/devices.py new file mode 100644 index 0000000000000000000000000000000000000000..a906be6e8709ce1e16ffedd231d2aff872978ba2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cffi/devices.py @@ -0,0 +1,59 @@ +"""zmq device functions""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from ._cffi import ffi +from ._cffi import lib as C +from .socket import Socket +from .utils import _retry_sys_call + + +def proxy(frontend, backend, capture=None): + if isinstance(capture, Socket): + capture = capture._zmq_socket + else: + capture = ffi.NULL + + _retry_sys_call(C.zmq_proxy, frontend._zmq_socket, backend._zmq_socket, capture) + + +def proxy_steerable(frontend, backend, capture=None, control=None): + """proxy_steerable(frontend, backend, capture, control) + + Start a zeromq proxy with control flow. + + .. versionadded:: libzmq-4.1 + .. versionadded:: 18.0 + + Parameters + ---------- + frontend : Socket + The Socket instance for the incoming traffic. + backend : Socket + The Socket instance for the outbound traffic. + capture : Socket (optional) + The Socket instance for capturing traffic. + control : Socket (optional) + The Socket instance for control flow. + """ + if isinstance(capture, Socket): + capture = capture._zmq_socket + else: + capture = ffi.NULL + + if isinstance(control, Socket): + control = control._zmq_socket + else: + control = ffi.NULL + + _retry_sys_call( + C.zmq_proxy_steerable, + frontend._zmq_socket, + backend._zmq_socket, + capture, + control, + ) + + +__all__ = ['proxy', 'proxy_steerable'] diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/error.py b/venv/lib/python3.10/site-packages/zmq/backend/cffi/error.py new file mode 100644 index 0000000000000000000000000000000000000000..5561394ddecc5a47c3767f6921cfa80df5f6a3c1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cffi/error.py @@ -0,0 +1,16 @@ +"""zmq error functions""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from ._cffi import ffi +from ._cffi import lib as C + + +def strerror(errno): + return ffi.string(C.zmq_strerror(errno)).decode() + + +zmq_errno = C.zmq_errno + +__all__ = ['strerror', 'zmq_errno'] diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/message.py b/venv/lib/python3.10/site-packages/zmq/backend/cffi/message.py new file mode 100644 index 0000000000000000000000000000000000000000..94bb8c96fc7c2a79cd0b20dda2abca5643599c4b --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cffi/message.py @@ -0,0 +1,225 @@ +"""Dummy Frame object""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import errno +from threading import Event + +import zmq +import zmq.error +from zmq.constants import ETERM + +from ._cffi import ffi +from ._cffi import lib as C + +zmq_gc = None + +try: + from __pypy__.bufferable import bufferable as maybe_bufferable +except ImportError: + maybe_bufferable = object + + +def _content(obj): + """Return content of obj as bytes""" + if type(obj) is bytes: + return obj + if not isinstance(obj, memoryview): + obj = memoryview(obj) + return obj.tobytes() + + +def _check_rc(rc): + err = C.zmq_errno() + if rc == -1: + if err == errno.EINTR: + raise zmq.error.InterrruptedSystemCall(err) + elif err == errno.EAGAIN: + raise zmq.error.Again(errno) + elif err == ETERM: + raise zmq.error.ContextTerminated(err) + else: + raise zmq.error.ZMQError(err) + return 0 + + +class Frame(maybe_bufferable): + _data = None + tracker = None + closed = False + more = False + _buffer = None + _bytes = None + _failed_init = False + tracker_event = None + zmq_msg = None + + def __init__(self, data=None, track=False, copy=None, copy_threshold=None): + self._failed_init = True + + self.zmq_msg = ffi.cast('zmq_msg_t[1]', C.malloc(ffi.sizeof("zmq_msg_t"))) + + # self.tracker should start finished + # except in the case where we are sharing memory with libzmq + if track: + self.tracker = zmq._FINISHED_TRACKER + + if isinstance(data, str): + raise TypeError( + "Unicode strings are not allowed. Only: bytes, buffer interfaces." + ) + + if data is None: + rc = C.zmq_msg_init(self.zmq_msg) + _check_rc(rc) + self._failed_init = False + return + + self._data = data + if type(data) is bytes: + # avoid unnecessary copy on .bytes access + self._bytes = data + + self._buffer = memoryview(data) + if not self._buffer.contiguous: + raise BufferError("memoryview: underlying buffer is not contiguous") + # from_buffer silently copies if memory is not contiguous + c_data = ffi.from_buffer(self._buffer) + data_len_c = self._buffer.nbytes + + if copy is None: + if copy_threshold and data_len_c < copy_threshold: + copy = True + else: + copy = False + + if copy: + # copy message data instead of sharing memory + rc = C.zmq_msg_init_size(self.zmq_msg, data_len_c) + _check_rc(rc) + ffi.buffer(C.zmq_msg_data(self.zmq_msg), data_len_c)[:] = self._buffer + self._failed_init = False + return + + # Getting here means that we are doing a true zero-copy Frame, + # where libzmq and Python are sharing memory. + # Hook up garbage collection with MessageTracker and zmq_free_fn + + # Event and MessageTracker for monitoring when zmq is done with data: + if track: + evt = Event() + self.tracker_event = evt + self.tracker = zmq.MessageTracker(evt) + # create the hint for zmq_free_fn + # two pointers: the zmq_gc context and a message to be sent to the zmq_gc PULL socket + # allows libzmq to signal to Python when it is done with Python-owned memory. + global zmq_gc + if zmq_gc is None: + from zmq.utils.garbage import gc as zmq_gc + # can't use ffi.new because it will be freed at the wrong time! + hint = ffi.cast("zhint[1]", C.malloc(ffi.sizeof("zhint"))) + hint[0].id = zmq_gc.store(data, self.tracker_event) + if not zmq_gc._push_mutex: + zmq_gc._push_mutex = C.mutex_allocate() + + hint[0].mutex = ffi.cast("mutex_t*", zmq_gc._push_mutex) + hint[0].sock = ffi.cast("void*", zmq_gc._push_socket.underlying) + + # calls zmq_wrap_msg_init_data with the C.free_python_msg callback + rc = C.zmq_wrap_msg_init_data( + self.zmq_msg, + c_data, + data_len_c, + hint, + ) + if rc != 0: + C.free(hint) + C.free(self.zmq_msg) + _check_rc(rc) + self._failed_init = False + + def __del__(self): + if not self.closed and not self._failed_init: + self.close() + + def close(self): + if self.closed or self._failed_init or self.zmq_msg is None: + return + self.closed = True + rc = C.zmq_msg_close(self.zmq_msg) + C.free(self.zmq_msg) + self.zmq_msg = None + if rc != 0: + _check_rc(rc) + + def _buffer_from_zmq_msg(self): + """one-time extract buffer from zmq_msg + + for Frames created by recv + """ + if self._data is None: + self._data = ffi.buffer( + C.zmq_msg_data(self.zmq_msg), C.zmq_msg_size(self.zmq_msg) + ) + if self._buffer is None: + self._buffer = memoryview(self._data) + + @property + def buffer(self): + if self._buffer is None: + self._buffer_from_zmq_msg() + return self._buffer + + @property + def bytes(self): + if self._bytes is None: + self._bytes = self.buffer.tobytes() + return self._bytes + + def __len__(self): + return self.buffer.nbytes + + def __eq__(self, other): + return self.bytes == _content(other) + + @property + def done(self): + return self.tracker.done() + + def __buffer__(self, flags): + return self.buffer + + def __copy__(self): + """Create a shallow copy of the message. + + This does not copy the contents of the Frame, just the pointer. + This will increment the 0MQ ref count of the message, but not + the ref count of the Python object. That is only done once when + the Python is first turned into a 0MQ message. + """ + return self.fast_copy() + + def fast_copy(self): + """Fast shallow copy of the Frame. + + Does not copy underlying data. + """ + new_msg = Frame() + # This does not copy the contents, but just increases the ref-count + # of the zmq_msg by one. + C.zmq_msg_copy(new_msg.zmq_msg, self.zmq_msg) + # Copy the ref to underlying data + new_msg._data = self._data + new_msg._buffer = self._buffer + + # Frame copies share the tracker and tracker_event + new_msg.tracker_event = self.tracker_event + new_msg.tracker = self.tracker + + return new_msg + + +Message = Frame + +__all__ = ['Frame', 'Message'] diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/socket.py b/venv/lib/python3.10/site-packages/zmq/backend/cffi/socket.py new file mode 100644 index 0000000000000000000000000000000000000000..2ef0b8bfb315c39fa9990e52511b4f8d6929e08d --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cffi/socket.py @@ -0,0 +1,435 @@ +"""zmq Socket class""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import errno as errno_mod +import warnings + +import zmq +from zmq.constants import SocketOption, _OptType +from zmq.error import ZMQError, _check_rc, _check_version + +from ._cffi import ffi +from ._cffi import lib as C +from .message import Frame +from .utils import _retry_sys_call + +nsp = new_sizet_pointer = lambda length: ffi.new('size_t*', length) + + +def new_uint64_pointer(): + return ffi.new('uint64_t*'), nsp(ffi.sizeof('uint64_t')) + + +def new_int64_pointer(): + return ffi.new('int64_t*'), nsp(ffi.sizeof('int64_t')) + + +def new_int_pointer(): + return ffi.new('int*'), nsp(ffi.sizeof('int')) + + +def new_binary_data(length): + return ffi.new(f'char[{length:d}]'), nsp(ffi.sizeof('char') * length) + + +def value_uint64_pointer(val): + return ffi.new('uint64_t*', val), ffi.sizeof('uint64_t') + + +def value_int64_pointer(val): + return ffi.new('int64_t*', val), ffi.sizeof('int64_t') + + +def value_int_pointer(val): + return ffi.new('int*', val), ffi.sizeof('int') + + +def value_binary_data(val, length): + return ffi.new(f'char[{length + 1:d}]', val), ffi.sizeof('char') * length + + +_fd_size = ffi.sizeof('ZMQ_FD_T') +ZMQ_FD_64BIT = _fd_size == 8 + +IPC_PATH_MAX_LEN = C.get_ipc_path_max_len() + + +def new_pointer_from_opt(option, length=0): + opt_type = getattr(option, "_opt_type", _OptType.int) + + if opt_type == _OptType.int64 or (ZMQ_FD_64BIT and opt_type == _OptType.fd): + return new_int64_pointer() + elif opt_type == _OptType.bytes: + return new_binary_data(length) + else: + # default + return new_int_pointer() + + +def value_from_opt_pointer(option, opt_pointer, length=0): + try: + option = SocketOption(option) + except ValueError: + # unrecognized option, + # assume from the future, + # let EINVAL raise + opt_type = _OptType.int + else: + opt_type = option._opt_type + + if opt_type == _OptType.bytes: + return ffi.buffer(opt_pointer, length)[:] + else: + return int(opt_pointer[0]) + + +def initialize_opt_pointer(option, value, length=0): + opt_type = getattr(option, "_opt_type", _OptType.int) + if opt_type == _OptType.int64 or (ZMQ_FD_64BIT and opt_type == _OptType.fd): + return value_int64_pointer(value) + elif opt_type == _OptType.bytes: + return value_binary_data(value, length) + else: + return value_int_pointer(value) + + +class Socket: + context = None + socket_type = None + _zmq_socket = None + _closed = None + _ref = None + _shadow = False + _draft_poller = None + _draft_poller_ptr = None + copy_threshold = 0 + + def __init__(self, context=None, socket_type=None, shadow=0, copy_threshold=None): + if copy_threshold is None: + copy_threshold = zmq.COPY_THRESHOLD + self.copy_threshold = copy_threshold + + self.context = context + self._draft_poller = self._draft_poller_ptr = None + if shadow: + self._zmq_socket = ffi.cast("void *", shadow) + self._shadow = True + else: + self._shadow = False + self._zmq_socket = C.zmq_socket(context._zmq_ctx, socket_type) + if self._zmq_socket == ffi.NULL: + raise ZMQError() + self._closed = False + + @property + def underlying(self): + """The address of the underlying libzmq socket""" + return int(ffi.cast('size_t', self._zmq_socket)) + + def _check_closed_deep(self): + """thorough check of whether the socket has been closed, + even if by another entity (e.g. ctx.destroy). + + Only used by the `closed` property. + + returns True if closed, False otherwise + """ + if self._closed: + return True + try: + self.get(zmq.TYPE) + except ZMQError as e: + if e.errno == zmq.ENOTSOCK: + self._closed = True + return True + elif e.errno == zmq.ETERM: + pass + else: + raise + return False + + @property + def closed(self): + return self._check_closed_deep() + + def close(self, linger=None): + rc = 0 + if not self._closed and hasattr(self, '_zmq_socket'): + if self._draft_poller_ptr is not None: + rc = C.zmq_poller_destroy(self._draft_poller_ptr) + self._draft_poller = self._draft_poller_ptr = None + + if self._zmq_socket is not None: + if linger is not None: + self.set(zmq.LINGER, linger) + rc = C.zmq_close(self._zmq_socket) + self._closed = True + if rc < 0: + _check_rc(rc) + + def bind(self, address): + if isinstance(address, str): + address_b = address.encode('utf8') + else: + address_b = address + if isinstance(address, bytes): + address = address_b.decode('utf8') + rc = C.zmq_bind(self._zmq_socket, address_b) + if rc < 0: + if IPC_PATH_MAX_LEN and C.zmq_errno() == errno_mod.ENAMETOOLONG: + path = address.split('://', 1)[-1] + msg = ( + f'ipc path "{path}" is longer than {IPC_PATH_MAX_LEN} ' + 'characters (sizeof(sockaddr_un.sun_path)).' + ) + raise ZMQError(C.zmq_errno(), msg=msg) + elif C.zmq_errno() == errno_mod.ENOENT: + path = address.split('://', 1)[-1] + msg = f'No such file or directory for ipc path "{path}".' + raise ZMQError(C.zmq_errno(), msg=msg) + else: + _check_rc(rc) + + def unbind(self, address): + if isinstance(address, str): + address = address.encode('utf8') + rc = C.zmq_unbind(self._zmq_socket, address) + _check_rc(rc) + + def connect(self, address): + if isinstance(address, str): + address = address.encode('utf8') + rc = C.zmq_connect(self._zmq_socket, address) + _check_rc(rc) + + def disconnect(self, address): + if isinstance(address, str): + address = address.encode('utf8') + rc = C.zmq_disconnect(self._zmq_socket, address) + _check_rc(rc) + + def set(self, option, value): + length = None + if isinstance(value, str): + raise TypeError("unicode not allowed, use bytes") + + try: + option = SocketOption(option) + except ValueError: + # unrecognized option, + # assume from the future, + # let EINVAL raise + opt_type = _OptType.int + else: + opt_type = option._opt_type + + if isinstance(value, bytes): + if opt_type != _OptType.bytes: + raise TypeError(f"not a bytes sockopt: {option}") + length = len(value) + + c_value_pointer, c_sizet = initialize_opt_pointer(option, value, length) + + _retry_sys_call( + C.zmq_setsockopt, + self._zmq_socket, + option, + ffi.cast('void*', c_value_pointer), + c_sizet, + ) + + def get(self, option): + try: + option = SocketOption(option) + except ValueError: + # unrecognized option, + # assume from the future, + # let EINVAL raise + opt_type = _OptType.int + else: + opt_type = option._opt_type + + if option == zmq.FD and self._draft_poller is not None: + c_value_pointer, _ = new_pointer_from_opt(option) + C.zmq_poller_fd(self._draft_poller, ffi.cast('void*', c_value_pointer)) + return int(c_value_pointer[0]) + + c_value_pointer, c_sizet_pointer = new_pointer_from_opt(option, length=255) + + try: + _retry_sys_call( + C.zmq_getsockopt, + self._zmq_socket, + option, + c_value_pointer, + c_sizet_pointer, + ) + except ZMQError as e: + if ( + option == SocketOption.FD + and e.errno == zmq.Errno.EINVAL + and self.get(SocketOption.THREAD_SAFE) + ): + _check_version((4, 3, 2), "draft socket FD support via zmq_poller_fd") + if not zmq.has('draft'): + raise RuntimeError("libzmq must be built with draft support") + warnings.warn(zmq.error.DraftFDWarning(), stacklevel=2) + + # create a poller and retrieve its fd + self._draft_poller_ptr = ffi.new("void*[1]") + self._draft_poller_ptr[0] = self._draft_poller = C.zmq_poller_new() + if self._draft_poller == ffi.NULL: + # failed (why?), raise original error + self._draft_poller_ptr = self._draft_poller = None + raise + # register self with poller + rc = C.zmq_poller_add( + self._draft_poller, + self._zmq_socket, + ffi.NULL, + zmq.POLLIN | zmq.POLLOUT, + ) + _check_rc(rc) + # use poller fd as proxy for ours + rc = C.zmq_poller_fd( + self._draft_poller, ffi.cast('void *', c_value_pointer) + ) + _check_rc(rc) + return int(c_value_pointer[0]) + else: + raise + + sz = c_sizet_pointer[0] + v = value_from_opt_pointer(option, c_value_pointer, sz) + if ( + option != zmq.SocketOption.ROUTING_ID + and opt_type == _OptType.bytes + and v.endswith(b'\0') + ): + v = v[:-1] + return v + + def _send_copy(self, buf, flags): + """Send a copy of a bufferable""" + zmq_msg = ffi.new('zmq_msg_t*') + if not isinstance(buf, bytes): + # cast any bufferable data to bytes via memoryview + buf = memoryview(buf).tobytes() + + c_message = ffi.new('char[]', buf) + rc = C.zmq_msg_init_size(zmq_msg, len(buf)) + _check_rc(rc) + C.memcpy(C.zmq_msg_data(zmq_msg), c_message, len(buf)) + _retry_sys_call(C.zmq_msg_send, zmq_msg, self._zmq_socket, flags) + rc2 = C.zmq_msg_close(zmq_msg) + _check_rc(rc2) + + def _send_frame(self, frame, flags): + """Send a Frame on this socket in a non-copy manner.""" + # Always copy the Frame so the original message isn't garbage collected. + # This doesn't do a real copy, just a reference. + frame_copy = frame.fast_copy() + zmq_msg = frame_copy.zmq_msg + _retry_sys_call(C.zmq_msg_send, zmq_msg, self._zmq_socket, flags) + tracker = frame_copy.tracker + frame_copy.close() + return tracker + + def send(self, data, flags=0, copy=False, track=False): + if isinstance(data, str): + raise TypeError("Message must be in bytes, not a unicode object") + + if copy and not isinstance(data, Frame): + return self._send_copy(data, flags) + else: + close_frame = False + if isinstance(data, Frame): + if track and not data.tracker: + raise ValueError('Not a tracked message') + frame = data + else: + if self.copy_threshold: + buf = memoryview(data) + # always copy messages smaller than copy_threshold + if buf.nbytes < self.copy_threshold: + self._send_copy(buf, flags) + return zmq._FINISHED_TRACKER + frame = Frame(data, track=track, copy_threshold=self.copy_threshold) + close_frame = True + + tracker = self._send_frame(frame, flags) + if close_frame: + frame.close() + return tracker + + def recv(self, flags=0, copy=True, track=False): + if copy: + zmq_msg = ffi.new('zmq_msg_t*') + C.zmq_msg_init(zmq_msg) + else: + frame = zmq.Frame(track=track) + zmq_msg = frame.zmq_msg + + try: + _retry_sys_call(C.zmq_msg_recv, zmq_msg, self._zmq_socket, flags) + except Exception: + if copy: + C.zmq_msg_close(zmq_msg) + raise + + if not copy: + return frame + + _buffer = ffi.buffer(C.zmq_msg_data(zmq_msg), C.zmq_msg_size(zmq_msg)) + _bytes = _buffer[:] + rc = C.zmq_msg_close(zmq_msg) + _check_rc(rc) + return _bytes + + def recv_into(self, buffer, /, *, nbytes: int = 0, flags: int = 0) -> int: + view = memoryview(buffer) + if not view.contiguous: + raise BufferError("Can only recv_into contiguous buffers") + if view.readonly: + raise BufferError("Cannot recv_into readonly buffer") + if nbytes < 0: + raise ValueError(f"{nbytes=} must be non-negative") + view_bytes = view.nbytes + if nbytes == 0: + nbytes = view_bytes + elif nbytes > view_bytes: + raise ValueError(f"{nbytes=} too big for memoryview of {view_bytes}B") + c_buf = ffi.from_buffer(view) + rc: int = _retry_sys_call(C.zmq_recv, self._zmq_socket, c_buf, nbytes, flags) + _check_rc(rc) + return rc + + def monitor(self, addr, events=-1): + """s.monitor(addr, flags) + + Start publishing socket events on inproc. + See libzmq docs for zmq_monitor for details. + + Note: requires libzmq >= 3.2 + + Parameters + ---------- + addr : str + The inproc url used for monitoring. Passing None as + the addr will cause an existing socket monitor to be + deregistered. + events : int [default: zmq.EVENT_ALL] + The zmq event bitmask for which events will be sent to the monitor. + """ + if events < 0: + events = zmq.EVENT_ALL + if addr is None: + addr = ffi.NULL + if isinstance(addr, str): + addr = addr.encode('utf8') + C.zmq_socket_monitor(self._zmq_socket, addr, events) + + +__all__ = ['Socket', 'IPC_PATH_MAX_LEN'] diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cffi/utils.py b/venv/lib/python3.10/site-packages/zmq/backend/cffi/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2ebc8dea2ea7f6d82c88c15fe53632bde97393a5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cffi/utils.py @@ -0,0 +1,78 @@ +"""miscellaneous zmq_utils wrapping""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from zmq.error import InterruptedSystemCall, _check_rc, _check_version + +from ._cffi import ffi +from ._cffi import lib as C + + +def has(capability): + """Check for zmq capability by name (e.g. 'ipc', 'curve') + + .. versionadded:: libzmq-4.1 + .. versionadded:: 14.1 + """ + _check_version((4, 1), 'zmq.has') + if isinstance(capability, str): + capability = capability.encode('utf8') + return bool(C.zmq_has(capability)) + + +def curve_keypair(): + """generate a Z85 key pair for use with zmq.CURVE security + + Requires libzmq (≥ 4.0) to have been built with CURVE support. + + Returns + ------- + (public, secret) : two bytestrings + The public and private key pair as 40 byte z85-encoded bytestrings. + """ + public = ffi.new('char[64]') + private = ffi.new('char[64]') + rc = C.zmq_curve_keypair(public, private) + _check_rc(rc) + return ffi.buffer(public)[:40], ffi.buffer(private)[:40] + + +def curve_public(private): + """Compute the public key corresponding to a private key for use + with zmq.CURVE security + + Requires libzmq (≥ 4.2) to have been built with CURVE support. + + Parameters + ---------- + private + The private key as a 40 byte z85-encoded bytestring + Returns + ------- + bytestring + The public key as a 40 byte z85-encoded bytestring. + """ + if isinstance(private, str): + private = private.encode('utf8') + _check_version((4, 2), "curve_public") + public = ffi.new('char[64]') + rc = C.zmq_curve_public(public, private) + _check_rc(rc) + return ffi.buffer(public)[:40] + + +def _retry_sys_call(f, *args, **kwargs): + """make a call, retrying if interrupted with EINTR""" + while True: + rc = f(*args) + try: + _check_rc(rc) + except InterruptedSystemCall: + continue + else: + break + return rc + + +__all__ = ['has', 'curve_keypair', 'curve_public'] diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cython/__init__.pxd b/venv/lib/python3.10/site-packages/zmq/backend/cython/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..94c7f8a3fb3b246dec15c64768147889f6593579 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cython/__init__.pxd @@ -0,0 +1 @@ +from zmq.backend.cython._zmq cimport Context, Frame, Socket diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cython/__init__.py b/venv/lib/python3.10/site-packages/zmq/backend/cython/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6c4179a80a3165e15a6f01b602d0281e64254e06 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cython/__init__.py @@ -0,0 +1,15 @@ +"""Python bindings for core 0MQ objects.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from . import _zmq + +# mq not in __all__ +from ._zmq import * # noqa +from ._zmq import monitored_queue # noqa + +Message = _zmq.Frame + +__all__ = ["Message"] +__all__.extend(_zmq.__all__) diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cython/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/backend/cython/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8ee1d82cfaab97079c18ee4bda0d32620dfaee7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/backend/cython/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cython/__pycache__/_zmq.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/backend/cython/__pycache__/_zmq.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bc32f0f0402d12c7269a20cc1d91eecccbc703b Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/backend/cython/__pycache__/_zmq.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cython/_externs.pxd b/venv/lib/python3.10/site-packages/zmq/backend/cython/_externs.pxd new file mode 100644 index 0000000000000000000000000000000000000000..dfe0744ddf1da8f8e25bd948d5bcc9517197fbde --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cython/_externs.pxd @@ -0,0 +1,13 @@ +cdef extern from "mutex.h" nogil: + ctypedef struct mutex_t: + pass + cdef mutex_t* mutex_allocate() + cdef void mutex_dallocate(mutex_t*) + cdef int mutex_lock(mutex_t*) + cdef int mutex_unlock(mutex_t*) + +cdef extern from "getpid_compat.h": + cdef int getpid() + +cdef extern from "ipcmaxlen.h": + cdef int get_ipc_path_max_len() diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cython/_zmq.pxd b/venv/lib/python3.10/site-packages/zmq/backend/cython/_zmq.pxd new file mode 100644 index 0000000000000000000000000000000000000000..a7e4f244294c6d954fb8989bb161dd25dcb36a6f --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cython/_zmq.pxd @@ -0,0 +1,52 @@ +# cython: language_level = 3str +"""zmq Cython backend augmented declarations""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from zmq.backend.cython.libzmq cimport zmq_msg_t + +cdef class Context: + + cdef object __weakref__ # enable weakref + cdef void *handle # The C handle for the underlying zmq object. + cdef bint _shadow # whether the Context is a shadow wrapper of another + cdef int _pid # the pid of the process which created me (for fork safety) + + cdef public bint closed # bool property for a closed context. + cdef inline int _term(self) + +cdef class MessageTracker(object): + cdef set events # Message Event objects to track. + cdef set peers # Other Message or MessageTracker objects. + +cdef class Frame: + + cdef zmq_msg_t zmq_msg + cdef object _data # The actual message data as a Python object. + cdef object _buffer # A Python memoryview of the message contents + cdef object _bytes # A bytes copy of the message. + cdef bint _failed_init # flag to hold failed init + cdef public object tracker_event # Event for use with zmq_free_fn. + cdef public object tracker # MessageTracker object. + cdef public bint more # whether RCVMORE was set + + cdef Frame fast_copy(self) # Create shallow copy of Message object. + +cdef class Socket: + + cdef object __weakref__ # enable weakref + cdef void *handle # The C handle for the underlying zmq object. + cdef bint _shadow # whether the Socket is a shadow wrapper of another + # Hold on to a reference to the context to make sure it is not garbage + # collected until the socket it done with it. + cdef public Context context # The zmq Context object that owns this. + cdef public bint _closed # bool property for a closed socket. + cdef public int copy_threshold # threshold below which pyzmq will always copy messages + cdef int _pid # the pid of the process which created me (for fork safety) + cdef void *_draft_poller # The C handle for the zmq poller for draft socket zmq.FD support + + # cpdef methods for direct-cython access: + cpdef object send(self, data, int flags=*, bint copy=*, bint track=*) + cpdef object recv(self, int flags=*, bint copy=*, bint track=*) + cpdef int recv_into(self, buffer, int nbytes=*, int flags=*) diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cython/_zmq.py b/venv/lib/python3.10/site-packages/zmq/backend/cython/_zmq.py new file mode 100644 index 0000000000000000000000000000000000000000..7deaf1e1de0f7c4436b68eec7b452704b1d32ab1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cython/_zmq.py @@ -0,0 +1,2032 @@ +# cython: language_level = 3str +# cython: freethreading_compatible = True +"""Cython backend for pyzmq""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from __future__ import annotations + +try: + import cython + + if not cython.compiled: + raise ImportError() +except ImportError: + from pathlib import Path + + zmq_root = Path(__file__).parents[3] + msg = f""" + Attempting to import zmq Cython backend, which has not been compiled. + + This probably means you are importing zmq from its source tree. + if this is what you want, make sure to do an in-place build first: + + pip install -e '{zmq_root}' + + If it is not, then '{zmq_root}' is probably on your sys.path, + when it shouldn't be. Is that your current working directory? + + If neither of those is true and this file is actually installed, + something seems to have gone wrong with the install! + Please report at https://github.com/zeromq/pyzmq/issues + """ + raise ImportError(msg) + +import warnings +from threading import Event +from time import monotonic +from weakref import ref + +import cython as C +from cython import ( + NULL, + Py_ssize_t, + address, + bint, + cast, + cclass, + cfunc, + char, + declare, + inline, + nogil, + p_char, + p_void, + pointer, + size_t, + sizeof, +) +from cython.cimports.cpython.buffer import ( + Py_buffer, + PyBUF_ANY_CONTIGUOUS, + PyBUF_WRITABLE, + PyBuffer_Release, + PyObject_GetBuffer, +) +from cython.cimports.cpython.bytes import ( + PyBytes_AsString, + PyBytes_FromStringAndSize, + PyBytes_Size, +) +from cython.cimports.cpython.exc import PyErr_CheckSignals +from cython.cimports.libc.errno import EAGAIN, EINTR, ENAMETOOLONG, ENOENT, ENOTSOCK +from cython.cimports.libc.stdint import uint32_t +from cython.cimports.libc.stdio import fprintf +from cython.cimports.libc.stdio import stderr as cstderr +from cython.cimports.libc.stdlib import free, malloc +from cython.cimports.libc.string import memcpy +from cython.cimports.zmq.backend.cython._externs import ( + get_ipc_path_max_len, + getpid, + mutex_allocate, + mutex_lock, + mutex_t, + mutex_unlock, +) +from cython.cimports.zmq.backend.cython.libzmq import ( + ZMQ_ENOTSOCK, + ZMQ_ETERM, + ZMQ_EVENT_ALL, + ZMQ_FD, + ZMQ_IDENTITY, + ZMQ_IO_THREADS, + ZMQ_LINGER, + ZMQ_POLLIN, + ZMQ_POLLOUT, + ZMQ_RCVMORE, + ZMQ_ROUTER, + ZMQ_SNDMORE, + ZMQ_THREAD_SAFE, + ZMQ_TYPE, + _zmq_version, + fd_t, + int64_t, + zmq_bind, + zmq_close, + zmq_connect, + zmq_ctx_destroy, + zmq_ctx_get, + zmq_ctx_new, + zmq_ctx_set, + zmq_curve_keypair, + zmq_curve_public, + zmq_disconnect, + zmq_free_fn, + zmq_getsockopt, + zmq_has, + zmq_join, + zmq_leave, + zmq_msg_close, + zmq_msg_copy, + zmq_msg_data, + zmq_msg_get, + zmq_msg_gets, + zmq_msg_group, + zmq_msg_init, + zmq_msg_init_data, + zmq_msg_init_size, + zmq_msg_recv, + zmq_msg_routing_id, + zmq_msg_send, + zmq_msg_set, + zmq_msg_set_group, + zmq_msg_set_routing_id, + zmq_msg_size, + zmq_msg_t, + zmq_poller_add, + zmq_poller_destroy, + zmq_poller_fd, + zmq_poller_new, + zmq_pollitem_t, + zmq_proxy, + zmq_proxy_steerable, + zmq_recv, + zmq_setsockopt, + zmq_socket, + zmq_socket_monitor, + zmq_strerror, + zmq_unbind, +) +from cython.cimports.zmq.backend.cython.libzmq import zmq_errno as _zmq_errno +from cython.cimports.zmq.backend.cython.libzmq import zmq_poll as zmq_poll_c + +import zmq +from zmq.constants import SocketOption, _OptType +from zmq.error import ( + Again, + ContextTerminated, + InterruptedSystemCall, + ZMQError, + _check_version, +) + +IPC_PATH_MAX_LEN: int = get_ipc_path_max_len() + + +@cfunc +@inline +@C.exceptval(-1) +def _check_rc(rc: C.int, error_without_errno: bint = False) -> C.int: + """internal utility for checking zmq return condition + + and raising the appropriate Exception class + """ + errno: C.int = _zmq_errno() + PyErr_CheckSignals() + if errno == 0 and not error_without_errno: + return 0 + if rc == -1: # if rc < -1, it's a bug in libzmq. Should we warn? + if errno == EINTR: + raise InterruptedSystemCall(errno) + elif errno == EAGAIN: + raise Again(errno) + elif errno == ZMQ_ETERM: + raise ContextTerminated(errno) + else: + raise ZMQError(errno) + return 0 + + +# message Frame class + +_zhint = C.struct( + sock=p_void, + mutex=pointer(mutex_t), + id=size_t, +) + + +@cfunc +@nogil +def free_python_msg(data: p_void, vhint: p_void) -> C.int: + """A pure-C function for DECREF'ing Python-owned message data. + + Sends a message on a PUSH socket + + The hint is a `zhint` struct with two values: + + sock (void *): pointer to the Garbage Collector's PUSH socket + id (size_t): the id to be used to construct a zmq_msg_t that should be sent on a PUSH socket, + signaling the Garbage Collector to remove its reference to the object. + + When the Garbage Collector's PULL socket receives the message, + it deletes its reference to the object, + allowing Python to free the memory. + """ + msg = declare(zmq_msg_t) + msg_ptr: pointer(zmq_msg_t) = address(msg) + hint: pointer(_zhint) = cast(pointer(_zhint), vhint) + rc: C.int + + if hint != NULL: + zmq_msg_init_size(msg_ptr, sizeof(size_t)) + memcpy(zmq_msg_data(msg_ptr), address(hint.id), sizeof(size_t)) + rc = mutex_lock(hint.mutex) + if rc != 0: + fprintf(cstderr, "pyzmq-gc mutex lock failed rc=%d\n", rc) + rc = zmq_msg_send(msg_ptr, hint.sock, 0) + if rc < 0: + # gc socket could have been closed, e.g. during process teardown. + # If so, ignore the failure because there's nothing to do. + if _zmq_errno() != ZMQ_ENOTSOCK: + fprintf( + cstderr, "pyzmq-gc send failed: %s\n", zmq_strerror(_zmq_errno()) + ) + rc = mutex_unlock(hint.mutex) + if rc != 0: + fprintf(cstderr, "pyzmq-gc mutex unlock failed rc=%d\n", rc) + + zmq_msg_close(msg_ptr) + free(hint) + return 0 + + +@cfunc +@inline +def _copy_zmq_msg_bytes(zmq_msg: pointer(zmq_msg_t)) -> bytes: + """Copy the data from a zmq_msg_t""" + data_c: p_char = NULL + data_len_c: Py_ssize_t + data_c = cast(p_char, zmq_msg_data(zmq_msg)) + data_len_c = zmq_msg_size(zmq_msg) + return PyBytes_FromStringAndSize(data_c, data_len_c) + + +@cfunc +@inline +def _asbuffer(obj, data_c: pointer(p_void), writable: bint = False) -> size_t: + """Get a C buffer from a memoryview""" + pybuf = declare(Py_buffer) + flags: C.int = PyBUF_ANY_CONTIGUOUS + if writable: + flags |= PyBUF_WRITABLE + rc: C.int = PyObject_GetBuffer(obj, address(pybuf), flags) + if rc < 0: + raise ValueError("Couldn't create buffer") + data_c[0] = pybuf.buf + data_size: size_t = pybuf.len + PyBuffer_Release(address(pybuf)) + return data_size + + +_gc = None + + +@cclass +class Frame: + def __init__( + self, data=None, track=False, copy=None, copy_threshold=None, **kwargs + ): + rc: C.int + data_c: p_char = NULL + data_len_c: Py_ssize_t = 0 + hint: pointer(_zhint) + if copy_threshold is None: + copy_threshold = zmq.COPY_THRESHOLD + + c_copy_threshold: C.size_t = 0 + if copy_threshold is not None: + c_copy_threshold = copy_threshold + + zmq_msg_ptr: pointer(zmq_msg_t) = address(self.zmq_msg) + # init more as False + self.more = False + + # Save the data object in case the user wants the the data as a str. + self._data = data + self._failed_init = True # bool switch for dealloc + self._buffer = None # buffer view of data + self._bytes = None # bytes copy of data + + self.tracker_event = None + self.tracker = None + # self.tracker should start finished + # except in the case where we are sharing memory with libzmq + if track: + self.tracker = zmq._FINISHED_TRACKER + + if isinstance(data, str): + raise TypeError("Str objects not allowed. Only: bytes, buffer interfaces.") + + if data is None: + rc = zmq_msg_init(zmq_msg_ptr) + _check_rc(rc) + self._failed_init = False + return + + data_len_c = _asbuffer(data, cast(pointer(p_void), address(data_c))) + + # copy unspecified, apply copy_threshold + c_copy: bint = True + if copy is None: + if c_copy_threshold and data_len_c < c_copy_threshold: + c_copy = True + else: + c_copy = False + else: + c_copy = copy + + if c_copy: + # copy message data instead of sharing memory + rc = zmq_msg_init_size(zmq_msg_ptr, data_len_c) + _check_rc(rc) + memcpy(zmq_msg_data(zmq_msg_ptr), data_c, data_len_c) + self._failed_init = False + return + + # Getting here means that we are doing a true zero-copy Frame, + # where libzmq and Python are sharing memory. + # Hook up garbage collection with MessageTracker and zmq_free_fn + + # Event and MessageTracker for monitoring when zmq is done with data: + if track: + evt = Event() + self.tracker_event = evt + self.tracker = zmq.MessageTracker(evt) + # create the hint for zmq_free_fn + # two pointers: the gc context and a message to be sent to the gc PULL socket + # allows libzmq to signal to Python when it is done with Python-owned memory. + global _gc + if _gc is None: + from zmq.utils.garbage import gc as _gc + + hint: pointer(_zhint) = cast(pointer(_zhint), malloc(sizeof(_zhint))) + hint.id = _gc.store(data, self.tracker_event) + if not _gc._push_mutex: + hint.mutex = mutex_allocate() + _gc._push_mutex = cast(size_t, hint.mutex) + else: + hint.mutex = cast(pointer(mutex_t), cast(size_t, _gc._push_mutex)) + hint.sock = cast(p_void, cast(size_t, _gc._push_socket.underlying)) + + rc = zmq_msg_init_data( + zmq_msg_ptr, + cast(p_void, data_c), + data_len_c, + cast(pointer(zmq_free_fn), free_python_msg), + cast(p_void, hint), + ) + if rc != 0: + free(hint) + _check_rc(rc) + self._failed_init = False + + def __dealloc__(self): + if self._failed_init: + return + # decrease the 0MQ ref-count of zmq_msg + with nogil: + rc: C.int = zmq_msg_close(address(self.zmq_msg)) + _check_rc(rc) + + def __copy__(self): + return self.fast_copy() + + def fast_copy(self) -> Frame: + new_msg: Frame = Frame() + # This does not copy the contents, but just increases the ref-count + # of the zmq_msg by one. + zmq_msg_copy(address(new_msg.zmq_msg), address(self.zmq_msg)) + # Copy the ref to data so the copy won't create a copy when str is + # called. + if self._data is not None: + new_msg._data = self._data + if self._buffer is not None: + new_msg._buffer = self._buffer + if self._bytes is not None: + new_msg._bytes = self._bytes + + # Frame copies share the tracker and tracker_event + new_msg.tracker_event = self.tracker_event + new_msg.tracker = self.tracker + + return new_msg + + # buffer interface code adapted from petsc4py by Lisandro Dalcin, a BSD project + + def __getbuffer__(self, buffer: pointer(Py_buffer), flags: C.int): # noqa: F821 + # new-style (memoryview) buffer interface + buffer.buf = zmq_msg_data(address(self.zmq_msg)) + buffer.len = zmq_msg_size(address(self.zmq_msg)) + + buffer.obj = self + buffer.readonly = 0 + buffer.format = "B" + buffer.ndim = 1 + buffer.shape = address(buffer.len) + buffer.strides = NULL + buffer.suboffsets = NULL + buffer.itemsize = 1 + buffer.internal = NULL + + def __len__(self) -> size_t: + """Return the length of the message in bytes.""" + sz: size_t = zmq_msg_size(address(self.zmq_msg)) + return sz + + @property + def buffer(self): + """A memoryview of the message contents.""" + _buffer = self._buffer and self._buffer() + if _buffer is not None: + return _buffer + _buffer = memoryview(self) + self._buffer = ref(_buffer) + return _buffer + + @property + def bytes(self): + """The message content as a Python bytes object. + + The first time this property is accessed, a copy of the message + contents is made. From then on that same copy of the message is + returned. + """ + if self._bytes is None: + self._bytes = _copy_zmq_msg_bytes(address(self.zmq_msg)) + return self._bytes + + def get(self, option): + """ + Get a Frame option or property. + + See the 0MQ API documentation for zmq_msg_get and zmq_msg_gets + for details on specific options. + + .. versionadded:: libzmq-3.2 + .. versionadded:: 13.0 + + .. versionchanged:: 14.3 + add support for zmq_msg_gets (requires libzmq-4.1) + All message properties are strings. + + .. versionchanged:: 17.0 + Added support for `routing_id` and `group`. + Only available if draft API is enabled + with libzmq >= 4.2. + """ + rc: C.int = 0 + property_c: p_char = NULL + + # zmq_msg_get + if isinstance(option, int): + rc = zmq_msg_get(address(self.zmq_msg), option) + _check_rc(rc) + return rc + + if option == 'routing_id': + routing_id: uint32_t = zmq_msg_routing_id(address(self.zmq_msg)) + if routing_id == 0: + _check_rc(-1) + return routing_id + elif option == 'group': + buf = zmq_msg_group(address(self.zmq_msg)) + if buf == NULL: + _check_rc(-1) + return buf.decode('utf8') + + # zmq_msg_gets + _check_version((4, 1), "get string properties") + if isinstance(option, str): + option = option.encode('utf8') + + if not isinstance(option, bytes): + raise TypeError(f"expected str, got: {option!r}") + + property_c = option + + result: p_char = cast(p_char, zmq_msg_gets(address(self.zmq_msg), property_c)) + if result == NULL: + _check_rc(-1) + return result.decode('utf8') + + def set(self, option, value): + """Set a Frame option. + + See the 0MQ API documentation for zmq_msg_set + for details on specific options. + + .. versionadded:: libzmq-3.2 + .. versionadded:: 13.0 + .. versionchanged:: 17.0 + Added support for `routing_id` and `group`. + Only available if draft API is enabled + with libzmq >= 4.2. + """ + rc: C.int + + if option == 'routing_id': + routing_id: uint32_t = value + rc = zmq_msg_set_routing_id(address(self.zmq_msg), routing_id) + _check_rc(rc) + return + elif option == 'group': + if isinstance(value, str): + value = value.encode('utf8') + rc = zmq_msg_set_group(address(self.zmq_msg), value) + _check_rc(rc) + return + + rc = zmq_msg_set(address(self.zmq_msg), option, value) + _check_rc(rc) + + +@cclass +class Context: + """ + Manage the lifecycle of a 0MQ context. + + Parameters + ---------- + io_threads : int + The number of IO threads. + """ + + def __init__(self, io_threads: C.int = 1, shadow: size_t = 0): + self.handle = NULL + self._pid = 0 + self._shadow = False + + if shadow: + self.handle = cast(p_void, shadow) + self._shadow = True + else: + self._shadow = False + self.handle = zmq_ctx_new() + + if self.handle == NULL: + raise ZMQError() + + rc: C.int = 0 + if not self._shadow: + rc = zmq_ctx_set(self.handle, ZMQ_IO_THREADS, io_threads) + _check_rc(rc) + + self.closed = False + self._pid = getpid() + + @property + def underlying(self): + """The address of the underlying libzmq context""" + return cast(size_t, self.handle) + + @cfunc + @inline + def _term(self) -> C.int: + rc: C.int = 0 + if self.handle != NULL and not self.closed and getpid() == self._pid: + with nogil: + rc = zmq_ctx_destroy(self.handle) + self.handle = NULL + return rc + + def term(self): + """ + Close or terminate the context. + + This can be called to close the context by hand. If this is not called, + the context will automatically be closed when it is garbage collected. + """ + rc: C.int = self._term() + try: + _check_rc(rc) + except InterruptedSystemCall: + # ignore interrupted term + # see PEP 475 notes about close & EINTR for why + pass + + self.closed = True + + def set(self, option: C.int, optval): + """ + Set a context option. + + See the 0MQ API documentation for zmq_ctx_set + for details on specific options. + + .. versionadded:: libzmq-3.2 + .. versionadded:: 13.0 + + Parameters + ---------- + option : int + The option to set. Available values will depend on your + version of libzmq. Examples include:: + + zmq.IO_THREADS, zmq.MAX_SOCKETS + + optval : int + The value of the option to set. + """ + optval_int_c: C.int + rc: C.int + + if self.closed: + raise RuntimeError("Context has been destroyed") + + if not isinstance(optval, int): + raise TypeError(f'expected int, got: {optval!r}') + optval_int_c = optval + rc = zmq_ctx_set(self.handle, option, optval_int_c) + _check_rc(rc) + + def get(self, option: C.int): + """ + Get the value of a context option. + + See the 0MQ API documentation for zmq_ctx_get + for details on specific options. + + .. versionadded:: libzmq-3.2 + .. versionadded:: 13.0 + + Parameters + ---------- + option : int + The option to get. Available values will depend on your + version of libzmq. Examples include:: + + zmq.IO_THREADS, zmq.MAX_SOCKETS + + Returns + ------- + optval : int + The value of the option as an integer. + """ + rc: C.int + + if self.closed: + raise RuntimeError("Context has been destroyed") + + rc = zmq_ctx_get(self.handle, option) + _check_rc(rc, error_without_errno=False) + return rc + + +@cfunc +@inline +def _c_addr(addr) -> p_char: + if isinstance(addr, str): + addr = addr.encode('utf-8') + try: + c_addr: p_char = addr + except TypeError: + raise TypeError(f"Expected addr to be str, got addr={addr!r}") + return c_addr + + +@cclass +class Socket: + """ + A 0MQ socket. + + These objects will generally be constructed via the socket() method of a Context object. + + Note: 0MQ Sockets are *not* threadsafe. **DO NOT** share them across threads. + + Parameters + ---------- + context : Context + The 0MQ Context this Socket belongs to. + socket_type : int + The socket type, which can be any of the 0MQ socket types: + REQ, REP, PUB, SUB, PAIR, DEALER, ROUTER, PULL, PUSH, XPUB, XSUB. + + See Also + -------- + .Context.socket : method for creating a socket bound to a Context. + """ + + def __init__( + self, + context=None, + socket_type: C.int = -1, + shadow: size_t = 0, + copy_threshold=None, + ): + # pre-init + self.handle = NULL + self._draft_poller = NULL + self._pid = 0 + self._shadow = False + self.context = None + + if copy_threshold is None: + copy_threshold = zmq.COPY_THRESHOLD + self.copy_threshold = copy_threshold + + self.handle = NULL + self.context = context + if shadow: + self._shadow = True + self.handle = cast(p_void, shadow) + else: + if context is None: + raise TypeError("context must be specified") + if socket_type < 0: + raise TypeError("socket_type must be specified") + self._shadow = False + self.handle = zmq_socket(self.context.handle, socket_type) + if self.handle == NULL: + raise ZMQError() + self._closed = False + self._pid = getpid() + + @property + def underlying(self): + """The address of the underlying libzmq socket""" + return cast(size_t, self.handle) + + @property + def closed(self): + """Whether the socket is closed""" + return _check_closed_deep(self) + + def close(self, linger: int | None = None): + """ + Close the socket. + + If linger is specified, LINGER sockopt will be set prior to closing. + + This can be called to close the socket by hand. If this is not + called, the socket will automatically be closed when it is + garbage collected. + """ + rc: C.int = 0 + linger_c: C.int + setlinger: bint = False + + if linger is not None: + linger_c = linger + setlinger = True + + if self.handle != NULL and not self._closed and getpid() == self._pid: + if setlinger: + zmq_setsockopt(self.handle, ZMQ_LINGER, address(linger_c), sizeof(int)) + + # teardown draft poller + if self._draft_poller != NULL: + zmq_poller_destroy(address(self._draft_poller)) + self._draft_poller = NULL + + rc = zmq_close(self.handle) + if rc < 0 and _zmq_errno() != ENOTSOCK: + # ignore ENOTSOCK (closed by Context) + _check_rc(rc) + self._closed = True + self.handle = NULL + + def set(self, option: C.int, optval): + """ + Set socket options. + + See the 0MQ API documentation for details on specific options. + + Parameters + ---------- + option : int + The option to set. Available values will depend on your + version of libzmq. Examples include:: + + zmq.SUBSCRIBE, UNSUBSCRIBE, IDENTITY, HWM, LINGER, FD + + optval : int or bytes + The value of the option to set. + + Notes + ----- + .. warning:: + + All options other than zmq.SUBSCRIBE, zmq.UNSUBSCRIBE and + zmq.LINGER only take effect for subsequent socket bind/connects. + """ + optval_int64_c: int64_t + optval_int_c: C.int + optval_c: p_char + sz: Py_ssize_t + + _check_closed(self) + if isinstance(optval, str): + raise TypeError("unicode not allowed, use setsockopt_string") + + try: + sopt = SocketOption(option) + except ValueError: + # unrecognized option, + # assume from the future, + # let EINVAL raise + opt_type = _OptType.int + else: + opt_type = sopt._opt_type + + if opt_type == _OptType.bytes: + if not isinstance(optval, bytes): + raise TypeError(f'expected bytes, got: {optval!r}') + optval_c = PyBytes_AsString(optval) + sz = PyBytes_Size(optval) + _setsockopt(self.handle, option, optval_c, sz) + elif opt_type == _OptType.int64: + if not isinstance(optval, int): + raise TypeError(f'expected int, got: {optval!r}') + optval_int64_c = optval + _setsockopt(self.handle, option, address(optval_int64_c), sizeof(int64_t)) + else: + # default is to assume int, which is what most new sockopts will be + # this lets pyzmq work with newer libzmq which may add constants + # pyzmq has not yet added, rather than artificially raising. Invalid + # sockopts will still raise just the same, but it will be libzmq doing + # the raising. + if not isinstance(optval, int): + raise TypeError(f'expected int, got: {optval!r}') + optval_int_c = optval + _setsockopt(self.handle, option, address(optval_int_c), sizeof(int)) + + def get(self, option: C.int): + """ + Get the value of a socket option. + + See the 0MQ API documentation for details on specific options. + + .. versionchanged:: 27 + Added experimental support for ZMQ_FD for draft sockets via `zmq_poller_fd`. + Requires libzmq >=4.3.2 built with draft support. + + Parameters + ---------- + option : int + The option to get. Available values will depend on your + version of libzmq. Examples include:: + + zmq.IDENTITY, HWM, LINGER, FD, EVENTS + + Returns + ------- + optval : int or bytes + The value of the option as a bytestring or int. + """ + optval_int64_c = declare(int64_t) + optval_int_c = declare(C.int) + optval_fd_c = declare(fd_t) + identity_str_c = declare(char[255]) + sz: size_t + + _check_closed(self) + + try: + sopt = SocketOption(option) + except ValueError: + # unrecognized option, + # assume from the future, + # let EINVAL raise + opt_type = _OptType.int + else: + opt_type = sopt._opt_type + + if opt_type == _OptType.bytes: + sz = 255 + _getsockopt(self.handle, option, cast(p_void, identity_str_c), address(sz)) + # strip null-terminated strings *except* identity + if ( + option != ZMQ_IDENTITY + and sz > 0 + and (cast(p_char, identity_str_c))[sz - 1] == b'\0' + ): + sz -= 1 + result = PyBytes_FromStringAndSize(cast(p_char, identity_str_c), sz) + elif opt_type == _OptType.int64: + sz = sizeof(int64_t) + _getsockopt( + self.handle, option, cast(p_void, address(optval_int64_c)), address(sz) + ) + result = optval_int64_c + elif option == ZMQ_FD and self._draft_poller != NULL: + # draft sockets use FD of a draft zmq_poller as proxy + rc = zmq_poller_fd(self._draft_poller, address(optval_fd_c)) + _check_rc(rc) + result = optval_fd_c + elif opt_type == _OptType.fd: + sz = sizeof(fd_t) + try: + _getsockopt( + self.handle, option, cast(p_void, address(optval_fd_c)), address(sz) + ) + except ZMQError as e: + # threadsafe sockets don't support ZMQ_FD (yet!) + # fallback on zmq_poller_fd as proxy with the same behavior + # until libzmq fixes this. + # if upstream fixes it, this branch will never be taken + if ( + option == ZMQ_FD + and e.errno == zmq.Errno.EINVAL + and self.get(ZMQ_THREAD_SAFE) + ): + _check_version( + (4, 3, 2), "draft socket FD support via zmq_poller_fd" + ) + if not zmq.has('draft'): + raise RuntimeError("libzmq must be built with draft support") + warnings.warn(zmq.error.DraftFDWarning(), stacklevel=2) + + # create a poller and retrieve its fd + self._draft_poller = zmq_poller_new() + if self._draft_poller == NULL: + # failed (why?), raise original error + raise + # register self with poller + rc = zmq_poller_add( + self._draft_poller, self.handle, NULL, ZMQ_POLLIN | ZMQ_POLLOUT + ) + _check_rc(rc) + # use poller fd as proxy for ours + rc = zmq_poller_fd(self._draft_poller, address(optval_fd_c)) + _check_rc(rc) + else: + raise + result = optval_fd_c + else: + # default is to assume int, which is what most new sockopts will be + # this lets pyzmq work with newer libzmq which may add constants + # pyzmq has not yet added, rather than artificially raising. Invalid + # sockopts will still raise just the same, but it will be libzmq doing + # the raising. + sz = sizeof(int) + _getsockopt( + self.handle, option, cast(p_void, address(optval_int_c)), address(sz) + ) + result = optval_int_c + + return result + + def bind(self, addr: str | bytes): + """ + Bind the socket to an address. + + This causes the socket to listen on a network port. Sockets on the + other side of this connection will use ``Socket.connect(addr)`` to + connect to this socket. + + Parameters + ---------- + addr : str + The address string. This has the form 'protocol://interface:port', + for example 'tcp://127.0.0.1:5555'. Protocols supported include + tcp, udp, pgm, epgm, inproc and ipc. If the address is unicode, it is + encoded to utf-8 first. + """ + c_addr: p_char = _c_addr(addr) + _check_closed(self) + rc: C.int = zmq_bind(self.handle, c_addr) + if rc != 0: + _errno: C.int = _zmq_errno() + _ipc_max: C.int = get_ipc_path_max_len() + if _ipc_max and _errno == ENAMETOOLONG: + path = addr.split('://', 1)[-1] + msg = ( + f'ipc path "{path}" is longer than {_ipc_max} ' + 'characters (sizeof(sockaddr_un.sun_path)). ' + 'zmq.IPC_PATH_MAX_LEN constant can be used ' + 'to check addr length (if it is defined).' + ) + raise ZMQError(msg=msg) + elif _errno == ENOENT: + path = addr.split('://', 1)[-1] + msg = f'No such file or directory for ipc path "{path}".' + raise ZMQError(msg=msg) + while True: + try: + _check_rc(rc) + except InterruptedSystemCall: + rc = zmq_bind(self.handle, c_addr) + continue + else: + break + + def connect(self, addr: str | bytes) -> None: + """ + Connect to a remote 0MQ socket. + + Parameters + ---------- + addr : str + The address string. This has the form 'protocol://interface:port', + for example 'tcp://127.0.0.1:5555'. Protocols supported are + tcp, udp, pgm, inproc and ipc. If the address is unicode, it is + encoded to utf-8 first. + """ + rc: C.int + c_addr: p_char = _c_addr(addr) + _check_closed(self) + + while True: + try: + rc = zmq_connect(self.handle, c_addr) + _check_rc(rc) + except InterruptedSystemCall: + # retry syscall + continue + else: + break + + def unbind(self, addr: str | bytes): + """ + Unbind from an address (undoes a call to bind). + + .. versionadded:: libzmq-3.2 + .. versionadded:: 13.0 + + Parameters + ---------- + addr : str + The address string. This has the form 'protocol://interface:port', + for example 'tcp://127.0.0.1:5555'. Protocols supported are + tcp, udp, pgm, inproc and ipc. If the address is unicode, it is + encoded to utf-8 first. + """ + c_addr: p_char = _c_addr(addr) + _check_closed(self) + rc: C.int = zmq_unbind(self.handle, c_addr) + if rc != 0: + raise ZMQError() + + def disconnect(self, addr: str | bytes): + """ + Disconnect from a remote 0MQ socket (undoes a call to connect). + + .. versionadded:: libzmq-3.2 + .. versionadded:: 13.0 + + Parameters + ---------- + addr : str + The address string. This has the form 'protocol://interface:port', + for example 'tcp://127.0.0.1:5555'. Protocols supported are + tcp, udp, pgm, inproc and ipc. If the address is unicode, it is + encoded to utf-8 first. + """ + c_addr: p_char = _c_addr(addr) + _check_closed(self) + + rc: C.int = zmq_disconnect(self.handle, c_addr) + if rc != 0: + raise ZMQError() + + def monitor(self, addr: str | bytes | None, events: C.int = ZMQ_EVENT_ALL): + """ + Start publishing socket events on inproc. + See libzmq docs for zmq_monitor for details. + + While this function is available from libzmq 3.2, + pyzmq cannot parse monitor messages from libzmq prior to 4.0. + + .. versionadded: libzmq-3.2 + .. versionadded: 14.0 + + Parameters + ---------- + addr : str | None + The inproc url used for monitoring. Passing None as + the addr will cause an existing socket monitor to be + deregistered. + events : int + default: zmq.EVENT_ALL + The zmq event bitmask for which events will be sent to the monitor. + """ + c_addr: p_char = NULL + if addr is not None: + c_addr = _c_addr(addr) + _check_closed(self) + + _check_rc(zmq_socket_monitor(self.handle, c_addr, events)) + + def join(self, group: str | bytes): + """ + Join a RADIO-DISH group + + Only for DISH sockets. + + libzmq and pyzmq must have been built with ZMQ_BUILD_DRAFT_API + + .. versionadded:: 17 + """ + _check_version((4, 2), "RADIO-DISH") + if not zmq.has('draft'): + raise RuntimeError("libzmq must be built with draft support") + if isinstance(group, str): + group = group.encode('utf8') + c_group: bytes = group + rc: C.int = zmq_join(self.handle, c_group) + _check_rc(rc) + + def leave(self, group): + """ + Leave a RADIO-DISH group + + Only for DISH sockets. + + libzmq and pyzmq must have been built with ZMQ_BUILD_DRAFT_API + + .. versionadded:: 17 + """ + _check_version((4, 2), "RADIO-DISH") + if not zmq.has('draft'): + raise RuntimeError("libzmq must be built with draft support") + rc: C.int = zmq_leave(self.handle, group) + _check_rc(rc) + + def send(self, data, flags=0, copy: bint = True, track: bint = False): + """ + Send a single zmq message frame on this socket. + + This queues the message to be sent by the IO thread at a later time. + + With flags=NOBLOCK, this raises :class:`ZMQError` if the queue is full; + otherwise, this waits until space is available. + See :class:`Poller` for more general non-blocking I/O. + + Parameters + ---------- + data : bytes, Frame, memoryview + The content of the message. This can be any object that provides + the Python buffer API (`memoryview(data)` can be called). + flags : int + 0, NOBLOCK, SNDMORE, or NOBLOCK|SNDMORE. + copy : bool + Should the message be sent in a copying or non-copying manner. + track : bool + Should the message be tracked for notification that ZMQ has + finished with it? (ignored if copy=True) + + Returns + ------- + None : if `copy` or not track + None if message was sent, raises an exception otherwise. + MessageTracker : if track and not copy + a MessageTracker object, whose `done` property will + be False until the send is completed. + + Raises + ------ + TypeError + If a unicode object is passed + ValueError + If `track=True`, but an untracked Frame is passed. + ZMQError + for any of the reasons zmq_msg_send might fail (including + if NOBLOCK is set and the outgoing queue is full). + + """ + _check_closed(self) + + if isinstance(data, str): + raise TypeError("unicode not allowed, use send_string") + + if copy and not isinstance(data, Frame): + return _send_copy(self.handle, data, flags) + else: + if isinstance(data, Frame): + if track and not data.tracker: + raise ValueError('Not a tracked message') + msg = data + else: + if self.copy_threshold: + buf = memoryview(data) + nbytes: size_t = buf.nbytes + copy_threshold: size_t = self.copy_threshold + # always copy messages smaller than copy_threshold + if nbytes < copy_threshold: + _send_copy(self.handle, buf, flags) + return zmq._FINISHED_TRACKER + msg = Frame(data, track=track, copy_threshold=self.copy_threshold) + return _send_frame(self.handle, msg, flags) + + def recv(self, flags=0, copy: bint = True, track: bint = False): + """ + Receive a message. + + With flags=NOBLOCK, this raises :class:`ZMQError` if no messages have + arrived; otherwise, this waits until a message arrives. + See :class:`Poller` for more general non-blocking I/O. + + Parameters + ---------- + flags : int + 0 or NOBLOCK. + copy : bool + Should the message be received in a copying or non-copying manner? + If False a Frame object is returned, if True a string copy of + message is returned. + track : bool + Should the message be tracked for notification that ZMQ has + finished with it? (ignored if copy=True) + + Returns + ------- + msg : bytes or Frame + The received message frame. If `copy` is False, then it will be a Frame, + otherwise it will be bytes. + + Raises + ------ + ZMQError + for any of the reasons zmq_msg_recv might fail (including if + NOBLOCK is set and no new messages have arrived). + """ + _check_closed(self) + + if copy: + return _recv_copy(self.handle, flags) + else: + frame = _recv_frame(self.handle, flags, track) + more: bint = False + sz: size_t = sizeof(bint) + _getsockopt( + self.handle, ZMQ_RCVMORE, cast(p_void, address(more)), address(sz) + ) + frame.more = more + return frame + + def recv_into(self, buffer, /, *, nbytes=0, flags=0) -> C.int: + """ + Receive up to nbytes bytes from the socket, + storing the data into a buffer rather than allocating a new Frame. + + The next message frame can be discarded by receiving into an empty buffer:: + + sock.recv_into(bytearray()) + + .. versionadded:: 26.4 + + Parameters + ---------- + buffer : memoryview + Any object providing the buffer interface (i.e. `memoryview(buffer)` works), + where the memoryview is contiguous and writable. + nbytes: int, default=0 + The maximum number of bytes to receive. + If nbytes is not specified (or 0), receive up to the size available in the given buffer. + If the next frame is larger than this, the frame will be truncated and message content discarded. + flags: int, default=0 + See `socket.recv` + + Returns + ------- + bytes_received: int + Returns the number of bytes received. + This is always the size of the received frame. + If the returned `bytes_received` is larger than `nbytes` (or size of `buffer` if `nbytes=0`), + the message has been truncated and the rest of the frame discarded. + Truncated data cannot be recovered. + + Raises + ------ + ZMQError + for any of the reasons `zmq_recv` might fail. + BufferError + for invalid buffers, such as readonly or not contiguous. + """ + c_flags: C.int = flags + _check_closed(self) + c_nbytes: size_t = nbytes + if c_nbytes < 0: + raise ValueError(f"{nbytes=} must be non-negative") + view = memoryview(buffer) + c_data = declare(pointer(C.void)) + view_bytes: C.size_t = _asbuffer(view, address(c_data), True) + if nbytes == 0: + c_nbytes = view_bytes + elif c_nbytes > view_bytes: + raise ValueError(f"{nbytes=} too big for memoryview of {view_bytes}B") + + # call zmq_recv, with retries + while True: + with nogil: + rc: C.int = zmq_recv(self.handle, c_data, c_nbytes, c_flags) + try: + _check_rc(rc) + except InterruptedSystemCall: + continue + else: + return rc + + +# inline socket methods + + +@inline +@cfunc +def _check_closed(s: Socket): + """raise ENOTSUP if socket is closed + + Does not do a deep check + """ + if s._closed: + raise ZMQError(ENOTSOCK) + + +@inline +@cfunc +def _check_closed_deep(s: Socket) -> bint: + """thorough check of whether the socket has been closed, + even if by another entity (e.g. ctx.destroy). + + Only used by the `closed` property. + + returns True if closed, False otherwise + """ + rc: C.int + errno: C.int + stype = declare(C.int) + sz: size_t = sizeof(int) + + if s._closed: + return True + else: + rc = zmq_getsockopt( + s.handle, ZMQ_TYPE, cast(p_void, address(stype)), address(sz) + ) + if rc < 0: + errno = _zmq_errno() + if errno == ENOTSOCK: + s._closed = True + return True + elif errno == ZMQ_ETERM: + # don't raise ETERM when checking if we're closed + return False + else: + _check_rc(rc) + return False + + +@cfunc +@inline +def _recv_frame(handle: p_void, flags: C.int = 0, track: bint = False) -> Frame: + """Receive a message in a non-copying manner and return a Frame.""" + rc: C.int + msg = zmq.Frame(track=track) + cmsg: Frame = msg + + while True: + with nogil: + rc = zmq_msg_recv(address(cmsg.zmq_msg), handle, flags) + try: + _check_rc(rc) + except InterruptedSystemCall: + continue + else: + break + return msg + + +@cfunc +@inline +def _recv_copy(handle: p_void, flags: C.int = 0): + """Receive a message and return a copy""" + zmq_msg = declare(zmq_msg_t) + zmq_msg_p: pointer(zmq_msg_t) = address(zmq_msg) + rc: C.int = zmq_msg_init(zmq_msg_p) + _check_rc(rc) + while True: + with nogil: + rc = zmq_msg_recv(zmq_msg_p, handle, flags) + try: + _check_rc(rc) + except InterruptedSystemCall: + continue + except Exception: + zmq_msg_close(zmq_msg_p) # ensure msg is closed on failure + raise + else: + break + + msg_bytes = _copy_zmq_msg_bytes(zmq_msg_p) + zmq_msg_close(zmq_msg_p) + return msg_bytes + + +@cfunc +@inline +def _send_frame(handle: p_void, msg: Frame, flags: C.int = 0): + """Send a Frame on this socket in a non-copy manner.""" + rc: C.int + msg_copy: Frame + + # Always copy so the original message isn't garbage collected. + # This doesn't do a real copy, just a reference. + msg_copy = msg.fast_copy() + + while True: + with nogil: + rc = zmq_msg_send(address(msg_copy.zmq_msg), handle, flags) + try: + _check_rc(rc) + except InterruptedSystemCall: + continue + else: + break + + return msg.tracker + + +@cfunc +@inline +def _send_copy(handle: p_void, buf, flags: C.int = 0): + """Send a message on this socket by copying its content.""" + rc: C.int + msg = declare(zmq_msg_t) + c_bytes = declare(p_void) + + # copy to c array: + c_bytes_len = _asbuffer(buf, address(c_bytes)) + + # Copy the msg before sending. This avoids any complications with + # the GIL, etc. + # If zmq_msg_init_* fails we must not call zmq_msg_close (Bus Error) + rc = zmq_msg_init_size(address(msg), c_bytes_len) + _check_rc(rc) + + while True: + with nogil: + memcpy(zmq_msg_data(address(msg)), c_bytes, zmq_msg_size(address(msg))) + rc = zmq_msg_send(address(msg), handle, flags) + try: + _check_rc(rc) + except InterruptedSystemCall: + continue + except Exception: + zmq_msg_close(address(msg)) # close the unused msg + raise # raise original exception + else: + rc = zmq_msg_close(address(msg)) + _check_rc(rc) + break + + +@cfunc +@inline +def _getsockopt(handle: p_void, option: C.int, optval: p_void, sz: pointer(size_t)): + """getsockopt, retrying interrupted calls + + checks rc, raising ZMQError on failure. + """ + rc: C.int = 0 + while True: + rc = zmq_getsockopt(handle, option, optval, sz) + try: + _check_rc(rc) + except InterruptedSystemCall: + continue + else: + break + + +@cfunc +@inline +def _setsockopt(handle: p_void, option: C.int, optval: p_void, sz: size_t): + """setsockopt, retrying interrupted calls + + checks rc, raising ZMQError on failure. + """ + rc: C.int = 0 + while True: + rc = zmq_setsockopt(handle, option, optval, sz) + try: + _check_rc(rc) + except InterruptedSystemCall: + continue + else: + break + + +# General utility functions + + +def zmq_errno() -> C.int: + """Return the integer errno of the most recent zmq error.""" + return _zmq_errno() + + +def strerror(errno: C.int) -> str: + """ + Return the error string given the error number. + """ + str_e: bytes = zmq_strerror(errno) + return str_e.decode("utf8", "replace") + + +def zmq_version_info() -> tuple[int, int, int]: + """Return the version of ZeroMQ itself as a 3-tuple of ints.""" + major: C.int = 0 + minor: C.int = 0 + patch: C.int = 0 + _zmq_version(address(major), address(minor), address(patch)) + return (major, minor, patch) + + +def has(capability: str) -> bool: + """Check for zmq capability by name (e.g. 'ipc', 'curve') + + .. versionadded:: libzmq-4.1 + .. versionadded:: 14.1 + """ + _check_version((4, 1), 'zmq.has') + ccap: bytes = capability.encode('utf8') + return bool(zmq_has(ccap)) + + +def curve_keypair() -> tuple[bytes, bytes]: + """generate a Z85 key pair for use with zmq.CURVE security + + Requires libzmq (≥ 4.0) to have been built with CURVE support. + + .. versionadded:: libzmq-4.0 + .. versionadded:: 14.0 + + Returns + ------- + public: bytes + The public key as 40 byte z85-encoded bytestring. + private: bytes + The private key as 40 byte z85-encoded bytestring. + """ + rc: C.int + public_key = declare(char[64]) + secret_key = declare(char[64]) + _check_version((4, 0), "curve_keypair") + # see huge comment in libzmq/src/random.cpp + # about threadsafety of random initialization + rc = zmq_curve_keypair(public_key, secret_key) + _check_rc(rc) + return public_key, secret_key + + +def curve_public(secret_key) -> bytes: + """Compute the public key corresponding to a secret key for use + with zmq.CURVE security + + Requires libzmq (≥ 4.2) to have been built with CURVE support. + + Parameters + ---------- + private + The private key as a 40 byte z85-encoded bytestring + + Returns + ------- + bytes + The public key as a 40 byte z85-encoded bytestring + """ + if isinstance(secret_key, str): + secret_key = secret_key.encode('utf8') + if not len(secret_key) == 40: + raise ValueError('secret key must be a 40 byte z85 encoded string') + + rc: C.int + public_key = declare(char[64]) + c_secret_key: pointer(char) = secret_key + _check_version((4, 2), "curve_public") + # see huge comment in libzmq/src/random.cpp + # about threadsafety of random initialization + rc = zmq_curve_public(public_key, c_secret_key) + _check_rc(rc) + return public_key[:40] + + +# polling +def zmq_poll(sockets, timeout: C.int = -1): + """zmq_poll(sockets, timeout=-1) + + Poll a set of 0MQ sockets, native file descs. or sockets. + + Parameters + ---------- + sockets : list of tuples of (socket, flags) + Each element of this list is a two-tuple containing a socket + and a flags. The socket may be a 0MQ socket or any object with + a ``fileno()`` method. The flags can be zmq.POLLIN (for detecting + for incoming messages), zmq.POLLOUT (for detecting that send is OK) + or zmq.POLLIN|zmq.POLLOUT for detecting both. + timeout : int + The number of milliseconds to poll for. Negative means no timeout. + """ + rc: C.int + i: C.int + fileno: fd_t + events: C.int + pollitems: pointer(zmq_pollitem_t) = NULL + nsockets: C.int = len(sockets) + + if nsockets == 0: + return [] + + pollitems = cast(pointer(zmq_pollitem_t), malloc(nsockets * sizeof(zmq_pollitem_t))) + if pollitems == NULL: + raise MemoryError("Could not allocate poll items") + + for i in range(nsockets): + s, events = sockets[i] + if isinstance(s, Socket): + pollitems[i].socket = cast(Socket, s).handle + pollitems[i].fd = 0 + pollitems[i].events = events + pollitems[i].revents = 0 + elif isinstance(s, int): + fileno = s + pollitems[i].socket = NULL + pollitems[i].fd = fileno + pollitems[i].events = events + pollitems[i].revents = 0 + elif hasattr(s, 'fileno'): + try: + fileno = int(s.fileno()) + except Exception: + free(pollitems) + raise ValueError('fileno() must return a valid integer fd') + else: + pollitems[i].socket = NULL + pollitems[i].fd = fileno + pollitems[i].events = events + pollitems[i].revents = 0 + else: + free(pollitems) + raise TypeError( + "Socket must be a 0MQ socket, an integer fd or have " + f"a fileno() method: {s!r}" + ) + + ms_passed: C.int = 0 + tic: C.int + try: + while True: + start: C.int = monotonic() + with nogil: + rc = zmq_poll_c(pollitems, nsockets, timeout) + try: + _check_rc(rc) + except InterruptedSystemCall: + if timeout > 0: + tic = monotonic() + ms_passed = int(1000 * (tic - start)) + if ms_passed < 0: + # don't allow negative ms_passed, + # which can happen on old Python versions without time.monotonic. + warnings.warn( + f"Negative elapsed time for interrupted poll: {ms_passed}." + " Did the clock change?", + RuntimeWarning, + ) + # treat this case the same as no time passing, + # since it should be rare and not happen twice in a row. + ms_passed = 0 + timeout = max(0, timeout - ms_passed) + continue + else: + break + except Exception: + free(pollitems) + raise + + results = [] + for i in range(nsockets): + revents = pollitems[i].revents + # for compatibility with select.poll: + # - only return sockets with non-zero status + # - return the fd for plain sockets + if revents > 0: + if pollitems[i].socket != NULL: + s = sockets[i][0] + else: + s = pollitems[i].fd + results.append((s, revents)) + + free(pollitems) + return results + + +def proxy(frontend: Socket, backend: Socket, capture: Socket = None): + """ + Start a zeromq proxy (replacement for device). + + .. versionadded:: libzmq-3.2 + .. versionadded:: 13.0 + + Parameters + ---------- + frontend : Socket + The Socket instance for the incoming traffic. + backend : Socket + The Socket instance for the outbound traffic. + capture : Socket (optional) + The Socket instance for capturing traffic. + """ + rc: C.int = 0 + capture_handle: p_void + if isinstance(capture, Socket): + capture_handle = capture.handle + else: + capture_handle = NULL + while True: + with nogil: + rc = zmq_proxy(frontend.handle, backend.handle, capture_handle) + try: + _check_rc(rc) + except InterruptedSystemCall: + continue + else: + break + return rc + + +def proxy_steerable( + frontend: Socket, + backend: Socket, + capture: Socket = None, + control: Socket = None, +): + """ + Start a zeromq proxy with control flow. + + .. versionadded:: libzmq-4.1 + .. versionadded:: 18.0 + + Parameters + ---------- + frontend : Socket + The Socket instance for the incoming traffic. + backend : Socket + The Socket instance for the outbound traffic. + capture : Socket (optional) + The Socket instance for capturing traffic. + control : Socket (optional) + The Socket instance for control flow. + """ + rc: C.int = 0 + capture_handle: p_void + if isinstance(capture, Socket): + capture_handle = capture.handle + else: + capture_handle = NULL + if isinstance(control, Socket): + control_handle = control.handle + else: + control_handle = NULL + while True: + with nogil: + rc = zmq_proxy_steerable( + frontend.handle, backend.handle, capture_handle, control_handle + ) + try: + _check_rc(rc) + except InterruptedSystemCall: + continue + else: + break + return rc + + +# monitored queue - like proxy (predates libzmq proxy) +# but supports ROUTER-ROUTER devices +@cfunc +@inline +@nogil +def _mq_relay( + in_socket: p_void, + out_socket: p_void, + side_socket: p_void, + msg: zmq_msg_t, + side_msg: zmq_msg_t, + id_msg: zmq_msg_t, + swap_ids: bint, +) -> C.int: + rc: C.int + flags: C.int + flagsz = declare(size_t) + more = declare(int) + flagsz = sizeof(int) + + if swap_ids: # both router, must send second identity first + # recv two ids into msg, id_msg + rc = zmq_msg_recv(address(msg), in_socket, 0) + if rc < 0: + return rc + + rc = zmq_msg_recv(address(id_msg), in_socket, 0) + if rc < 0: + return rc + + # send second id (id_msg) first + # !!!! always send a copy before the original !!!! + rc = zmq_msg_copy(address(side_msg), address(id_msg)) + if rc < 0: + return rc + rc = zmq_msg_send(address(side_msg), out_socket, ZMQ_SNDMORE) + if rc < 0: + return rc + rc = zmq_msg_send(address(id_msg), side_socket, ZMQ_SNDMORE) + if rc < 0: + return rc + # send first id (msg) second + rc = zmq_msg_copy(address(side_msg), address(msg)) + if rc < 0: + return rc + rc = zmq_msg_send(address(side_msg), out_socket, ZMQ_SNDMORE) + if rc < 0: + return rc + rc = zmq_msg_send(address(msg), side_socket, ZMQ_SNDMORE) + if rc < 0: + return rc + while True: + rc = zmq_msg_recv(address(msg), in_socket, 0) + if rc < 0: + return rc + # assert (rc == 0) + rc = zmq_getsockopt(in_socket, ZMQ_RCVMORE, address(more), address(flagsz)) + if rc < 0: + return rc + flags = 0 + if more: + flags |= ZMQ_SNDMORE + + rc = zmq_msg_copy(address(side_msg), address(msg)) + if rc < 0: + return rc + if flags: + rc = zmq_msg_send(address(side_msg), out_socket, flags) + if rc < 0: + return rc + # only SNDMORE for side-socket + rc = zmq_msg_send(address(msg), side_socket, ZMQ_SNDMORE) + if rc < 0: + return rc + else: + rc = zmq_msg_send(address(side_msg), out_socket, 0) + if rc < 0: + return rc + rc = zmq_msg_send(address(msg), side_socket, 0) + if rc < 0: + return rc + break + return rc + + +@cfunc +@inline +@nogil +def _mq_inline( + in_socket: p_void, + out_socket: p_void, + side_socket: p_void, + in_msg_ptr: pointer(zmq_msg_t), + out_msg_ptr: pointer(zmq_msg_t), + swap_ids: bint, +) -> C.int: + """ + inner C function for monitored_queue + """ + + msg: zmq_msg_t = declare(zmq_msg_t) + rc: C.int = zmq_msg_init(address(msg)) + id_msg = declare(zmq_msg_t) + rc = zmq_msg_init(address(id_msg)) + if rc < 0: + return rc + side_msg = declare(zmq_msg_t) + rc = zmq_msg_init(address(side_msg)) + if rc < 0: + return rc + + items = declare(zmq_pollitem_t[2]) + items[0].socket = in_socket + items[0].events = ZMQ_POLLIN + items[0].fd = items[0].revents = 0 + items[1].socket = out_socket + items[1].events = ZMQ_POLLIN + items[1].fd = items[1].revents = 0 + + while True: + # wait for the next message to process + rc = zmq_poll_c(address(items[0]), 2, -1) + if rc < 0: + return rc + if items[0].revents & ZMQ_POLLIN: + # send in_prefix to side socket + rc = zmq_msg_copy(address(side_msg), in_msg_ptr) + if rc < 0: + return rc + rc = zmq_msg_send(address(side_msg), side_socket, ZMQ_SNDMORE) + if rc < 0: + return rc + # relay the rest of the message + rc = _mq_relay( + in_socket, out_socket, side_socket, msg, side_msg, id_msg, swap_ids + ) + if rc < 0: + return rc + if items[1].revents & ZMQ_POLLIN: + # send out_prefix to side socket + rc = zmq_msg_copy(address(side_msg), out_msg_ptr) + if rc < 0: + return rc + rc = zmq_msg_send(address(side_msg), side_socket, ZMQ_SNDMORE) + if rc < 0: + return rc + # relay the rest of the message + rc = _mq_relay( + out_socket, in_socket, side_socket, msg, side_msg, id_msg, swap_ids + ) + if rc < 0: + return rc + return rc + + +def monitored_queue( + in_socket: Socket, + out_socket: Socket, + mon_socket: Socket, + in_prefix: bytes = b'in', + out_prefix: bytes = b'out', +): + """ + Start a monitored queue device. + + A monitored queue is very similar to the zmq.proxy device (monitored queue came first). + + Differences from zmq.proxy: + + - monitored_queue supports both in and out being ROUTER sockets + (via swapping IDENTITY prefixes). + - monitor messages are prefixed, making in and out messages distinguishable. + + Parameters + ---------- + in_socket : zmq.Socket + One of the sockets to the Queue. Its messages will be prefixed with + 'in'. + out_socket : zmq.Socket + One of the sockets to the Queue. Its messages will be prefixed with + 'out'. The only difference between in/out socket is this prefix. + mon_socket : zmq.Socket + This socket sends out every message received by each of the others + with an in/out prefix specifying which one it was. + in_prefix : str + Prefix added to broadcast messages from in_socket. + out_prefix : str + Prefix added to broadcast messages from out_socket. + """ + ins: p_void = in_socket.handle + outs: p_void = out_socket.handle + mons: p_void = mon_socket.handle + in_msg = declare(zmq_msg_t) + out_msg = declare(zmq_msg_t) + swap_ids: bint + msg_c: p_void = NULL + msg_c_len = declare(Py_ssize_t) + rc: C.int + + # force swap_ids if both ROUTERs + swap_ids = in_socket.type == ZMQ_ROUTER and out_socket.type == ZMQ_ROUTER + + # build zmq_msg objects from str prefixes + msg_c_len = _asbuffer(in_prefix, address(msg_c)) + rc = zmq_msg_init_size(address(in_msg), msg_c_len) + _check_rc(rc) + + memcpy(zmq_msg_data(address(in_msg)), msg_c, zmq_msg_size(address(in_msg))) + + msg_c_len = _asbuffer(out_prefix, address(msg_c)) + + rc = zmq_msg_init_size(address(out_msg), msg_c_len) + _check_rc(rc) + + while True: + with nogil: + memcpy( + zmq_msg_data(address(out_msg)), msg_c, zmq_msg_size(address(out_msg)) + ) + rc = _mq_inline( + ins, outs, mons, address(in_msg), address(out_msg), swap_ids + ) + try: + _check_rc(rc) + except InterruptedSystemCall: + continue + else: + break + return rc + + +__all__ = [ + 'IPC_PATH_MAX_LEN', + 'Context', + 'Socket', + 'Frame', + 'has', + 'curve_keypair', + 'curve_public', + 'zmq_version_info', + 'zmq_errno', + 'zmq_poll', + 'strerror', + 'proxy', + 'proxy_steerable', +] diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cython/constant_enums.pxi b/venv/lib/python3.10/site-packages/zmq/backend/cython/constant_enums.pxi new file mode 100644 index 0000000000000000000000000000000000000000..811d2a84f56f1b96d98a3f4a57cfbacf50c69a08 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cython/constant_enums.pxi @@ -0,0 +1,250 @@ +cdef extern from "zmq.h" nogil: + enum: PYZMQ_DRAFT_API + enum: ZMQ_VERSION + enum: ZMQ_VERSION_MAJOR + enum: ZMQ_VERSION_MINOR + enum: ZMQ_VERSION_PATCH + enum: ZMQ_IO_THREADS + enum: ZMQ_MAX_SOCKETS + enum: ZMQ_SOCKET_LIMIT + enum: ZMQ_THREAD_PRIORITY + enum: ZMQ_THREAD_SCHED_POLICY + enum: ZMQ_MAX_MSGSZ + enum: ZMQ_MSG_T_SIZE + enum: ZMQ_THREAD_AFFINITY_CPU_ADD + enum: ZMQ_THREAD_AFFINITY_CPU_REMOVE + enum: ZMQ_THREAD_NAME_PREFIX + enum: ZMQ_STREAMER + enum: ZMQ_FORWARDER + enum: ZMQ_QUEUE + enum: ZMQ_EAGAIN "EAGAIN" + enum: ZMQ_EFAULT "EFAULT" + enum: ZMQ_EINVAL "EINVAL" + enum: ZMQ_ENOTSUP "ENOTSUP" + enum: ZMQ_EPROTONOSUPPORT "EPROTONOSUPPORT" + enum: ZMQ_ENOBUFS "ENOBUFS" + enum: ZMQ_ENETDOWN "ENETDOWN" + enum: ZMQ_EADDRINUSE "EADDRINUSE" + enum: ZMQ_EADDRNOTAVAIL "EADDRNOTAVAIL" + enum: ZMQ_ECONNREFUSED "ECONNREFUSED" + enum: ZMQ_EINPROGRESS "EINPROGRESS" + enum: ZMQ_ENOTSOCK "ENOTSOCK" + enum: ZMQ_EMSGSIZE "EMSGSIZE" + enum: ZMQ_EAFNOSUPPORT "EAFNOSUPPORT" + enum: ZMQ_ENETUNREACH "ENETUNREACH" + enum: ZMQ_ECONNABORTED "ECONNABORTED" + enum: ZMQ_ECONNRESET "ECONNRESET" + enum: ZMQ_ENOTCONN "ENOTCONN" + enum: ZMQ_ETIMEDOUT "ETIMEDOUT" + enum: ZMQ_EHOSTUNREACH "EHOSTUNREACH" + enum: ZMQ_ENETRESET "ENETRESET" + enum: ZMQ_EFSM "EFSM" + enum: ZMQ_ENOCOMPATPROTO "ENOCOMPATPROTO" + enum: ZMQ_ETERM "ETERM" + enum: ZMQ_EMTHREAD "EMTHREAD" + enum: ZMQ_PROTOCOL_ERROR_WS_UNSPECIFIED + enum: ZMQ_PROTOCOL_ERROR_ZMTP_UNSPECIFIED + enum: ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND + enum: ZMQ_PROTOCOL_ERROR_ZMTP_INVALID_SEQUENCE + enum: ZMQ_PROTOCOL_ERROR_ZMTP_KEY_EXCHANGE + enum: ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_UNSPECIFIED + enum: ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_MESSAGE + enum: ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO + enum: ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_INITIATE + enum: ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_ERROR + enum: ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_READY + enum: ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_WELCOME + enum: ZMQ_PROTOCOL_ERROR_ZMTP_INVALID_METADATA + enum: ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC + enum: ZMQ_PROTOCOL_ERROR_ZMTP_MECHANISM_MISMATCH + enum: ZMQ_PROTOCOL_ERROR_ZAP_UNSPECIFIED + enum: ZMQ_PROTOCOL_ERROR_ZAP_MALFORMED_REPLY + enum: ZMQ_PROTOCOL_ERROR_ZAP_BAD_REQUEST_ID + enum: ZMQ_PROTOCOL_ERROR_ZAP_BAD_VERSION + enum: ZMQ_PROTOCOL_ERROR_ZAP_INVALID_STATUS_CODE + enum: ZMQ_PROTOCOL_ERROR_ZAP_INVALID_METADATA + enum: ZMQ_EVENT_CONNECTED + enum: ZMQ_EVENT_CONNECT_DELAYED + enum: ZMQ_EVENT_CONNECT_RETRIED + enum: ZMQ_EVENT_LISTENING + enum: ZMQ_EVENT_BIND_FAILED + enum: ZMQ_EVENT_ACCEPTED + enum: ZMQ_EVENT_ACCEPT_FAILED + enum: ZMQ_EVENT_CLOSED + enum: ZMQ_EVENT_CLOSE_FAILED + enum: ZMQ_EVENT_DISCONNECTED + enum: ZMQ_EVENT_MONITOR_STOPPED + enum: ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL + enum: ZMQ_EVENT_HANDSHAKE_SUCCEEDED + enum: ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL + enum: ZMQ_EVENT_HANDSHAKE_FAILED_AUTH + enum: ZMQ_EVENT_ALL_V1 + enum: ZMQ_EVENT_ALL + enum: ZMQ_EVENT_PIPES_STATS + enum: ZMQ_EVENT_ALL_V2 + enum: ZMQ_DONTWAIT + enum: ZMQ_SNDMORE + enum: ZMQ_NOBLOCK + enum: ZMQ_MORE + enum: ZMQ_SHARED + enum: ZMQ_SRCFD + enum: ZMQ_NORM_FIXED + enum: ZMQ_NORM_CC + enum: ZMQ_NORM_CCL + enum: ZMQ_NORM_CCE + enum: ZMQ_NORM_CCE_ECNONLY + enum: ZMQ_POLLIN + enum: ZMQ_POLLOUT + enum: ZMQ_POLLERR + enum: ZMQ_POLLPRI + enum: ZMQ_RECONNECT_STOP_CONN_REFUSED + enum: ZMQ_RECONNECT_STOP_HANDSHAKE_FAILED + enum: ZMQ_RECONNECT_STOP_AFTER_DISCONNECT + enum: ZMQ_NOTIFY_CONNECT + enum: ZMQ_NOTIFY_DISCONNECT + enum: ZMQ_NULL + enum: ZMQ_PLAIN + enum: ZMQ_CURVE + enum: ZMQ_GSSAPI + enum: ZMQ_HWM + enum: ZMQ_AFFINITY + enum: ZMQ_ROUTING_ID + enum: ZMQ_SUBSCRIBE + enum: ZMQ_UNSUBSCRIBE + enum: ZMQ_RATE + enum: ZMQ_RECOVERY_IVL + enum: ZMQ_SNDBUF + enum: ZMQ_RCVBUF + enum: ZMQ_RCVMORE + enum: ZMQ_FD + enum: ZMQ_EVENTS + enum: ZMQ_TYPE + enum: ZMQ_LINGER + enum: ZMQ_RECONNECT_IVL + enum: ZMQ_BACKLOG + enum: ZMQ_RECONNECT_IVL_MAX + enum: ZMQ_MAXMSGSIZE + enum: ZMQ_SNDHWM + enum: ZMQ_RCVHWM + enum: ZMQ_MULTICAST_HOPS + enum: ZMQ_RCVTIMEO + enum: ZMQ_SNDTIMEO + enum: ZMQ_LAST_ENDPOINT + enum: ZMQ_ROUTER_MANDATORY + enum: ZMQ_TCP_KEEPALIVE + enum: ZMQ_TCP_KEEPALIVE_CNT + enum: ZMQ_TCP_KEEPALIVE_IDLE + enum: ZMQ_TCP_KEEPALIVE_INTVL + enum: ZMQ_IMMEDIATE + enum: ZMQ_XPUB_VERBOSE + enum: ZMQ_ROUTER_RAW + enum: ZMQ_IPV6 + enum: ZMQ_MECHANISM + enum: ZMQ_PLAIN_SERVER + enum: ZMQ_PLAIN_USERNAME + enum: ZMQ_PLAIN_PASSWORD + enum: ZMQ_CURVE_SERVER + enum: ZMQ_CURVE_PUBLICKEY + enum: ZMQ_CURVE_SECRETKEY + enum: ZMQ_CURVE_SERVERKEY + enum: ZMQ_PROBE_ROUTER + enum: ZMQ_REQ_CORRELATE + enum: ZMQ_REQ_RELAXED + enum: ZMQ_CONFLATE + enum: ZMQ_ZAP_DOMAIN + enum: ZMQ_ROUTER_HANDOVER + enum: ZMQ_TOS + enum: ZMQ_CONNECT_ROUTING_ID + enum: ZMQ_GSSAPI_SERVER + enum: ZMQ_GSSAPI_PRINCIPAL + enum: ZMQ_GSSAPI_SERVICE_PRINCIPAL + enum: ZMQ_GSSAPI_PLAINTEXT + enum: ZMQ_HANDSHAKE_IVL + enum: ZMQ_SOCKS_PROXY + enum: ZMQ_XPUB_NODROP + enum: ZMQ_BLOCKY + enum: ZMQ_XPUB_MANUAL + enum: ZMQ_XPUB_WELCOME_MSG + enum: ZMQ_STREAM_NOTIFY + enum: ZMQ_INVERT_MATCHING + enum: ZMQ_HEARTBEAT_IVL + enum: ZMQ_HEARTBEAT_TTL + enum: ZMQ_HEARTBEAT_TIMEOUT + enum: ZMQ_XPUB_VERBOSER + enum: ZMQ_CONNECT_TIMEOUT + enum: ZMQ_TCP_MAXRT + enum: ZMQ_THREAD_SAFE + enum: ZMQ_MULTICAST_MAXTPDU + enum: ZMQ_VMCI_BUFFER_SIZE + enum: ZMQ_VMCI_BUFFER_MIN_SIZE + enum: ZMQ_VMCI_BUFFER_MAX_SIZE + enum: ZMQ_VMCI_CONNECT_TIMEOUT + enum: ZMQ_USE_FD + enum: ZMQ_GSSAPI_PRINCIPAL_NAMETYPE + enum: ZMQ_GSSAPI_SERVICE_PRINCIPAL_NAMETYPE + enum: ZMQ_BINDTODEVICE + enum: ZMQ_IDENTITY + enum: ZMQ_CONNECT_RID + enum: ZMQ_TCP_ACCEPT_FILTER + enum: ZMQ_IPC_FILTER_PID + enum: ZMQ_IPC_FILTER_UID + enum: ZMQ_IPC_FILTER_GID + enum: ZMQ_IPV4ONLY + enum: ZMQ_DELAY_ATTACH_ON_CONNECT + enum: ZMQ_FAIL_UNROUTABLE + enum: ZMQ_ROUTER_BEHAVIOR + enum: ZMQ_ZAP_ENFORCE_DOMAIN + enum: ZMQ_LOOPBACK_FASTPATH + enum: ZMQ_METADATA + enum: ZMQ_MULTICAST_LOOP + enum: ZMQ_ROUTER_NOTIFY + enum: ZMQ_XPUB_MANUAL_LAST_VALUE + enum: ZMQ_SOCKS_USERNAME + enum: ZMQ_SOCKS_PASSWORD + enum: ZMQ_IN_BATCH_SIZE + enum: ZMQ_OUT_BATCH_SIZE + enum: ZMQ_WSS_KEY_PEM + enum: ZMQ_WSS_CERT_PEM + enum: ZMQ_WSS_TRUST_PEM + enum: ZMQ_WSS_HOSTNAME + enum: ZMQ_WSS_TRUST_SYSTEM + enum: ZMQ_ONLY_FIRST_SUBSCRIBE + enum: ZMQ_RECONNECT_STOP + enum: ZMQ_HELLO_MSG + enum: ZMQ_DISCONNECT_MSG + enum: ZMQ_PRIORITY + enum: ZMQ_BUSY_POLL + enum: ZMQ_HICCUP_MSG + enum: ZMQ_XSUB_VERBOSE_UNSUBSCRIBE + enum: ZMQ_TOPICS_COUNT + enum: ZMQ_NORM_MODE + enum: ZMQ_NORM_UNICAST_NACK + enum: ZMQ_NORM_BUFFER_SIZE + enum: ZMQ_NORM_SEGMENT_SIZE + enum: ZMQ_NORM_BLOCK_SIZE + enum: ZMQ_NORM_NUM_PARITY + enum: ZMQ_NORM_NUM_AUTOPARITY + enum: ZMQ_NORM_PUSH + enum: ZMQ_PAIR + enum: ZMQ_PUB + enum: ZMQ_SUB + enum: ZMQ_REQ + enum: ZMQ_REP + enum: ZMQ_DEALER + enum: ZMQ_ROUTER + enum: ZMQ_PULL + enum: ZMQ_PUSH + enum: ZMQ_XPUB + enum: ZMQ_XSUB + enum: ZMQ_STREAM + enum: ZMQ_XREQ + enum: ZMQ_XREP + enum: ZMQ_SERVER + enum: ZMQ_CLIENT + enum: ZMQ_RADIO + enum: ZMQ_DISH + enum: ZMQ_GATHER + enum: ZMQ_SCATTER + enum: ZMQ_DGRAM + enum: ZMQ_PEER + enum: ZMQ_CHANNEL diff --git a/venv/lib/python3.10/site-packages/zmq/backend/cython/libzmq.pxd b/venv/lib/python3.10/site-packages/zmq/backend/cython/libzmq.pxd new file mode 100644 index 0000000000000000000000000000000000000000..2e88f58ebf39ca3044668cafa663b632faf17a2c --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/cython/libzmq.pxd @@ -0,0 +1,128 @@ +"""All the C imports for 0MQ""" + +# +# Copyright (c) 2010 Brian E. Granger & Min Ragan-Kelley +# +# This file is part of pyzmq. +# +# pyzmq is free software; you can redistribute it and/or modify it under +# the terms of the Lesser GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# pyzmq is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# Lesser GNU General Public License for more details. +# +# You should have received a copy of the Lesser GNU General Public License +# along with this program. If not, see . +# + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Import the C header files +#----------------------------------------------------------------------------- + +# common includes, such as zmq compat, pyversion_compat +# make sure we load pyversion compat in every Cython module +cdef extern from "pyversion_compat.h": + pass + +# were it not for Windows, +# we could cimport these from libc.stdint +cdef extern from "zmq_compat.h": + ctypedef signed long long int64_t "pyzmq_int64_t" + ctypedef unsigned int uint32_t "pyzmq_uint32_t" + +include "constant_enums.pxi" + +cdef extern from "zmq.h" nogil: + + void _zmq_version "zmq_version"(int *major, int *minor, int *patch) + + ctypedef int fd_t "ZMQ_FD_T" + + enum: errno + const char *zmq_strerror (int errnum) + int zmq_errno() + + void *zmq_ctx_new () + int zmq_ctx_destroy (void *context) + int zmq_ctx_set (void *context, int option, int optval) + int zmq_ctx_get (void *context, int option) + void *zmq_init (int io_threads) + int zmq_term (void *context) + + # blackbox def for zmq_msg_t + ctypedef void * zmq_msg_t "zmq_msg_t" + + ctypedef void zmq_free_fn(void *data, void *hint) + + int zmq_msg_init (zmq_msg_t *msg) + int zmq_msg_init_size (zmq_msg_t *msg, size_t size) + int zmq_msg_init_data (zmq_msg_t *msg, void *data, + size_t size, zmq_free_fn *ffn, void *hint) + int zmq_msg_send (zmq_msg_t *msg, void *s, int flags) + int zmq_msg_recv (zmq_msg_t *msg, void *s, int flags) + int zmq_msg_close (zmq_msg_t *msg) + int zmq_msg_move (zmq_msg_t *dest, zmq_msg_t *src) + int zmq_msg_copy (zmq_msg_t *dest, zmq_msg_t *src) + void *zmq_msg_data (zmq_msg_t *msg) + size_t zmq_msg_size (zmq_msg_t *msg) + int zmq_msg_more (zmq_msg_t *msg) + int zmq_msg_get (zmq_msg_t *msg, int option) + int zmq_msg_set (zmq_msg_t *msg, int option, int optval) + const char *zmq_msg_gets (zmq_msg_t *msg, const char *property) + int zmq_has (const char *capability) + + void *zmq_socket (void *context, int type) + int zmq_close (void *s) + int zmq_setsockopt (void *s, int option, void *optval, size_t optvallen) + int zmq_getsockopt (void *s, int option, void *optval, size_t *optvallen) + int zmq_bind (void *s, char *addr) + int zmq_connect (void *s, char *addr) + int zmq_unbind (void *s, char *addr) + int zmq_disconnect (void *s, char *addr) + + int zmq_socket_monitor (void *s, char *addr, int flags) + + # send/recv + int zmq_send (void *s, const void *buf, size_t n, int flags) + int zmq_recv (void *s, void *buf, size_t n, int flags) + + ctypedef struct zmq_pollitem_t: + void *socket + fd_t fd + short events + short revents + + int zmq_poll (zmq_pollitem_t *items, int nitems, long timeout) + + int zmq_proxy (void *frontend, void *backend, void *capture) + int zmq_proxy_steerable (void *frontend, + void *backend, + void *capture, + void *control) + + int zmq_curve_keypair (char *z85_public_key, char *z85_secret_key) + int zmq_curve_public (char *z85_public_key, char *z85_secret_key) + + # 4.2 draft + int zmq_join (void *s, const char *group) + int zmq_leave (void *s, const char *group) + + int zmq_msg_set_routing_id(zmq_msg_t *msg, uint32_t routing_id) + uint32_t zmq_msg_routing_id(zmq_msg_t *msg) + int zmq_msg_set_group(zmq_msg_t *msg, const char *group) + const char *zmq_msg_group(zmq_msg_t *msg) + + void *zmq_poller_new () + int zmq_poller_destroy (void **poller_p_) + int zmq_poller_add (void *poller_, void *socket_, void *user_data_, short events_) + int zmq_poller_modify (void *poller_, void *socket_, short events_) + int zmq_poller_remove (void *poller_, void *socket_) + int zmq_poller_fd (void *poller_, fd_t *fd_) diff --git a/venv/lib/python3.10/site-packages/zmq/backend/select.py b/venv/lib/python3.10/site-packages/zmq/backend/select.py new file mode 100644 index 0000000000000000000000000000000000000000..ebc8b485200e921c348ae3f3ce0f3883256613d6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/backend/select.py @@ -0,0 +1,40 @@ +"""Import basic exposure of libzmq C API as a backend""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from importlib import import_module +from typing import Dict + +public_api = [ + 'Context', + 'Socket', + 'Frame', + 'Message', + 'proxy', + 'proxy_steerable', + 'zmq_poll', + 'strerror', + 'zmq_errno', + 'has', + 'curve_keypair', + 'curve_public', + 'zmq_version_info', + 'IPC_PATH_MAX_LEN', +] + + +def select_backend(name: str) -> Dict: + """Select the pyzmq backend""" + try: + mod = import_module(name) + except ImportError: + raise + except Exception as e: + raise ImportError(f"Importing {name} failed with {e}") from e + ns = { + # private API + 'monitored_queue': mod.monitored_queue, + } + ns.update({key: getattr(mod, key) for key in public_api}) + return ns diff --git a/venv/lib/python3.10/site-packages/zmq/constants.py b/venv/lib/python3.10/site-packages/zmq/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..cddf433a15d9102b9162425f8d8a54aa125f783e --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/constants.py @@ -0,0 +1,974 @@ +"""zmq constants as enums""" + +from __future__ import annotations + +import errno +import sys +from enum import Enum, IntEnum, IntFlag + +_HAUSNUMERO = 156384712 + + +class Errno(IntEnum): + """libzmq error codes + + .. versionadded:: 23 + """ + + EAGAIN = errno.EAGAIN + EFAULT = errno.EFAULT + EINVAL = errno.EINVAL + + if sys.platform.startswith("win"): + # Windows: libzmq uses errno.h + # while Python errno prefers WSA* variants + # many of these were introduced to errno.h in vs2010 + # ref: https://github.com/python/cpython/blob/3.9/Modules/errnomodule.c#L10-L37 + # source: https://docs.microsoft.com/en-us/cpp/c-runtime-library/errno-constants + ENOTSUP = 129 + EPROTONOSUPPORT = 135 + ENOBUFS = 119 + ENETDOWN = 116 + EADDRINUSE = 100 + EADDRNOTAVAIL = 101 + ECONNREFUSED = 107 + EINPROGRESS = 112 + ENOTSOCK = 128 + EMSGSIZE = 115 + EAFNOSUPPORT = 102 + ENETUNREACH = 118 + ECONNABORTED = 106 + ECONNRESET = 108 + ENOTCONN = 126 + ETIMEDOUT = 138 + EHOSTUNREACH = 110 + ENETRESET = 117 + + else: + ENOTSUP = getattr(errno, "ENOTSUP", _HAUSNUMERO + 1) + EPROTONOSUPPORT = getattr(errno, "EPROTONOSUPPORT", _HAUSNUMERO + 2) + ENOBUFS = getattr(errno, "ENOBUFS", _HAUSNUMERO + 3) + ENETDOWN = getattr(errno, "ENETDOWN", _HAUSNUMERO + 4) + EADDRINUSE = getattr(errno, "EADDRINUSE", _HAUSNUMERO + 5) + EADDRNOTAVAIL = getattr(errno, "EADDRNOTAVAIL", _HAUSNUMERO + 6) + ECONNREFUSED = getattr(errno, "ECONNREFUSED", _HAUSNUMERO + 7) + EINPROGRESS = getattr(errno, "EINPROGRESS", _HAUSNUMERO + 8) + ENOTSOCK = getattr(errno, "ENOTSOCK", _HAUSNUMERO + 9) + EMSGSIZE = getattr(errno, "EMSGSIZE", _HAUSNUMERO + 10) + EAFNOSUPPORT = getattr(errno, "EAFNOSUPPORT", _HAUSNUMERO + 11) + ENETUNREACH = getattr(errno, "ENETUNREACH", _HAUSNUMERO + 12) + ECONNABORTED = getattr(errno, "ECONNABORTED", _HAUSNUMERO + 13) + ECONNRESET = getattr(errno, "ECONNRESET", _HAUSNUMERO + 14) + ENOTCONN = getattr(errno, "ENOTCONN", _HAUSNUMERO + 15) + ETIMEDOUT = getattr(errno, "ETIMEDOUT", _HAUSNUMERO + 16) + EHOSTUNREACH = getattr(errno, "EHOSTUNREACH", _HAUSNUMERO + 17) + ENETRESET = getattr(errno, "ENETRESET", _HAUSNUMERO + 18) + + # Native 0MQ error codes + EFSM = _HAUSNUMERO + 51 + ENOCOMPATPROTO = _HAUSNUMERO + 52 + ETERM = _HAUSNUMERO + 53 + EMTHREAD = _HAUSNUMERO + 54 + + +class ContextOption(IntEnum): + """Options for Context.get/set + + .. versionadded:: 23 + """ + + IO_THREADS = 1 + MAX_SOCKETS = 2 + SOCKET_LIMIT = 3 + THREAD_PRIORITY = 3 + THREAD_SCHED_POLICY = 4 + MAX_MSGSZ = 5 + MSG_T_SIZE = 6 + THREAD_AFFINITY_CPU_ADD = 7 + THREAD_AFFINITY_CPU_REMOVE = 8 + THREAD_NAME_PREFIX = 9 + + +class SocketType(IntEnum): + """zmq socket types + + .. versionadded:: 23 + """ + + PAIR = 0 + PUB = 1 + SUB = 2 + REQ = 3 + REP = 4 + DEALER = 5 + ROUTER = 6 + PULL = 7 + PUSH = 8 + XPUB = 9 + XSUB = 10 + STREAM = 11 + + # deprecated aliases + XREQ = DEALER + XREP = ROUTER + + # DRAFT socket types + SERVER = 12 + CLIENT = 13 + RADIO = 14 + DISH = 15 + GATHER = 16 + SCATTER = 17 + DGRAM = 18 + PEER = 19 + CHANNEL = 20 + + +class _OptType(Enum): + int = 'int' + int64 = 'int64' + bytes = 'bytes' + fd = 'fd' + + +class SocketOption(IntEnum): + """Options for Socket.get/set + + .. versionadded:: 23 + """ + + _opt_type: _OptType + + def __new__(cls, value: int, opt_type: _OptType = _OptType.int): + """Attach option type as `._opt_type`""" + obj = int.__new__(cls, value) + obj._value_ = value + obj._opt_type = opt_type + return obj + + HWM = 1 + AFFINITY = 4, _OptType.int64 + ROUTING_ID = 5, _OptType.bytes + SUBSCRIBE = 6, _OptType.bytes + UNSUBSCRIBE = 7, _OptType.bytes + RATE = 8 + RECOVERY_IVL = 9 + SNDBUF = 11 + RCVBUF = 12 + RCVMORE = 13 + FD = 14, _OptType.fd + EVENTS = 15 + TYPE = 16 + LINGER = 17 + RECONNECT_IVL = 18 + BACKLOG = 19 + RECONNECT_IVL_MAX = 21 + MAXMSGSIZE = 22, _OptType.int64 + SNDHWM = 23 + RCVHWM = 24 + MULTICAST_HOPS = 25 + RCVTIMEO = 27 + SNDTIMEO = 28 + LAST_ENDPOINT = 32, _OptType.bytes + ROUTER_MANDATORY = 33 + TCP_KEEPALIVE = 34 + TCP_KEEPALIVE_CNT = 35 + TCP_KEEPALIVE_IDLE = 36 + TCP_KEEPALIVE_INTVL = 37 + IMMEDIATE = 39 + XPUB_VERBOSE = 40 + ROUTER_RAW = 41 + IPV6 = 42 + MECHANISM = 43 + PLAIN_SERVER = 44 + PLAIN_USERNAME = 45, _OptType.bytes + PLAIN_PASSWORD = 46, _OptType.bytes + CURVE_SERVER = 47 + CURVE_PUBLICKEY = 48, _OptType.bytes + CURVE_SECRETKEY = 49, _OptType.bytes + CURVE_SERVERKEY = 50, _OptType.bytes + PROBE_ROUTER = 51 + REQ_CORRELATE = 52 + REQ_RELAXED = 53 + CONFLATE = 54 + ZAP_DOMAIN = 55, _OptType.bytes + ROUTER_HANDOVER = 56 + TOS = 57 + CONNECT_ROUTING_ID = 61, _OptType.bytes + GSSAPI_SERVER = 62 + GSSAPI_PRINCIPAL = 63, _OptType.bytes + GSSAPI_SERVICE_PRINCIPAL = 64, _OptType.bytes + GSSAPI_PLAINTEXT = 65 + HANDSHAKE_IVL = 66 + SOCKS_PROXY = 68, _OptType.bytes + XPUB_NODROP = 69 + BLOCKY = 70 + XPUB_MANUAL = 71 + XPUB_WELCOME_MSG = 72, _OptType.bytes + STREAM_NOTIFY = 73 + INVERT_MATCHING = 74 + HEARTBEAT_IVL = 75 + HEARTBEAT_TTL = 76 + HEARTBEAT_TIMEOUT = 77 + XPUB_VERBOSER = 78 + CONNECT_TIMEOUT = 79 + TCP_MAXRT = 80 + THREAD_SAFE = 81 + MULTICAST_MAXTPDU = 84 + VMCI_BUFFER_SIZE = 85, _OptType.int64 + VMCI_BUFFER_MIN_SIZE = 86, _OptType.int64 + VMCI_BUFFER_MAX_SIZE = 87, _OptType.int64 + VMCI_CONNECT_TIMEOUT = 88 + USE_FD = 89 + GSSAPI_PRINCIPAL_NAMETYPE = 90 + GSSAPI_SERVICE_PRINCIPAL_NAMETYPE = 91 + BINDTODEVICE = 92, _OptType.bytes + + # Deprecated options and aliases + # must not use name-assignment, must have the same value + IDENTITY = ROUTING_ID + CONNECT_RID = CONNECT_ROUTING_ID + TCP_ACCEPT_FILTER = 38, _OptType.bytes + IPC_FILTER_PID = 58 + IPC_FILTER_UID = 59 + IPC_FILTER_GID = 60 + IPV4ONLY = 31 + DELAY_ATTACH_ON_CONNECT = IMMEDIATE + FAIL_UNROUTABLE = ROUTER_MANDATORY + ROUTER_BEHAVIOR = ROUTER_MANDATORY + + # Draft socket options + ZAP_ENFORCE_DOMAIN = 93 + LOOPBACK_FASTPATH = 94 + METADATA = 95, _OptType.bytes + MULTICAST_LOOP = 96 + ROUTER_NOTIFY = 97 + XPUB_MANUAL_LAST_VALUE = 98 + SOCKS_USERNAME = 99, _OptType.bytes + SOCKS_PASSWORD = 100, _OptType.bytes + IN_BATCH_SIZE = 101 + OUT_BATCH_SIZE = 102 + WSS_KEY_PEM = 103, _OptType.bytes + WSS_CERT_PEM = 104, _OptType.bytes + WSS_TRUST_PEM = 105, _OptType.bytes + WSS_HOSTNAME = 106, _OptType.bytes + WSS_TRUST_SYSTEM = 107 + ONLY_FIRST_SUBSCRIBE = 108 + RECONNECT_STOP = 109 + HELLO_MSG = 110, _OptType.bytes + DISCONNECT_MSG = 111, _OptType.bytes + PRIORITY = 112 + # 4.3.5 + BUSY_POLL = 113 + HICCUP_MSG = 114, _OptType.bytes + XSUB_VERBOSE_UNSUBSCRIBE = 115 + TOPICS_COUNT = 116 + NORM_MODE = 117 + NORM_UNICAST_NACK = 118 + NORM_BUFFER_SIZE = 119 + NORM_SEGMENT_SIZE = 120 + NORM_BLOCK_SIZE = 121 + NORM_NUM_PARITY = 122 + NORM_NUM_AUTOPARITY = 123 + NORM_PUSH = 124 + + +class MessageOption(IntEnum): + """Options on zmq.Frame objects + + .. versionadded:: 23 + """ + + MORE = 1 + SHARED = 3 + # Deprecated message options + SRCFD = 2 + + +class Flag(IntFlag): + """Send/recv flags + + .. versionadded:: 23 + """ + + DONTWAIT = 1 + SNDMORE = 2 + NOBLOCK = DONTWAIT + + +class RouterNotify(IntEnum): + """Values for zmq.ROUTER_NOTIFY socket option + + .. versionadded:: 26 + .. versionadded:: libzmq-4.3.0 (draft) + """ + + @staticmethod + def _global_name(name): + return f"NOTIFY_{name}" + + CONNECT = 1 + DISCONNECT = 2 + + +class NormMode(IntEnum): + """Values for zmq.NORM_MODE socket option + + .. versionadded:: 26 + .. versionadded:: libzmq-4.3.5 (draft) + """ + + @staticmethod + def _global_name(name): + return f"NORM_{name}" + + FIXED = 0 + CC = 1 + CCL = 2 + CCE = 3 + CCE_ECNONLY = 4 + + +class SecurityMechanism(IntEnum): + """Security mechanisms (as returned by ``socket.get(zmq.MECHANISM)``) + + .. versionadded:: 23 + """ + + NULL = 0 + PLAIN = 1 + CURVE = 2 + GSSAPI = 3 + + +class ReconnectStop(IntEnum): + """Select behavior for socket.reconnect_stop + + .. versionadded:: 25 + """ + + @staticmethod + def _global_name(name): + return f"RECONNECT_STOP_{name}" + + CONN_REFUSED = 0x1 + HANDSHAKE_FAILED = 0x2 + AFTER_DISCONNECT = 0x4 + + +class Event(IntFlag): + """Socket monitoring events + + .. versionadded:: 23 + """ + + @staticmethod + def _global_name(name): + if name.startswith("PROTOCOL_ERROR_"): + return name + else: + # add EVENT_ prefix + return "EVENT_" + name + + PROTOCOL_ERROR_WS_UNSPECIFIED = 0x30000000 + PROTOCOL_ERROR_ZMTP_UNSPECIFIED = 0x10000000 + PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND = 0x10000001 + PROTOCOL_ERROR_ZMTP_INVALID_SEQUENCE = 0x10000002 + PROTOCOL_ERROR_ZMTP_KEY_EXCHANGE = 0x10000003 + PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_UNSPECIFIED = 0x10000011 + PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_MESSAGE = 0x10000012 + PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO = 0x10000013 + PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_INITIATE = 0x10000014 + PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_ERROR = 0x10000015 + PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_READY = 0x10000016 + PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_WELCOME = 0x10000017 + PROTOCOL_ERROR_ZMTP_INVALID_METADATA = 0x10000018 + + PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC = 0x11000001 + PROTOCOL_ERROR_ZMTP_MECHANISM_MISMATCH = 0x11000002 + PROTOCOL_ERROR_ZAP_UNSPECIFIED = 0x20000000 + PROTOCOL_ERROR_ZAP_MALFORMED_REPLY = 0x20000001 + PROTOCOL_ERROR_ZAP_BAD_REQUEST_ID = 0x20000002 + PROTOCOL_ERROR_ZAP_BAD_VERSION = 0x20000003 + PROTOCOL_ERROR_ZAP_INVALID_STATUS_CODE = 0x20000004 + PROTOCOL_ERROR_ZAP_INVALID_METADATA = 0x20000005 + + # define event types _after_ overlapping protocol error masks + CONNECTED = 0x0001 + CONNECT_DELAYED = 0x0002 + CONNECT_RETRIED = 0x0004 + LISTENING = 0x0008 + BIND_FAILED = 0x0010 + ACCEPTED = 0x0020 + ACCEPT_FAILED = 0x0040 + CLOSED = 0x0080 + CLOSE_FAILED = 0x0100 + DISCONNECTED = 0x0200 + MONITOR_STOPPED = 0x0400 + + HANDSHAKE_FAILED_NO_DETAIL = 0x0800 + HANDSHAKE_SUCCEEDED = 0x1000 + HANDSHAKE_FAILED_PROTOCOL = 0x2000 + HANDSHAKE_FAILED_AUTH = 0x4000 + + ALL_V1 = 0xFFFF + ALL = ALL_V1 + + # DRAFT Socket monitoring events + PIPES_STATS = 0x10000 + ALL_V2 = ALL_V1 | PIPES_STATS + + +class PollEvent(IntFlag): + """Which events to poll for in poll methods + + .. versionadded: 23 + """ + + POLLIN = 1 + POLLOUT = 2 + POLLERR = 4 + POLLPRI = 8 + + +class DeviceType(IntEnum): + """Device type constants for zmq.device + + .. versionadded: 23 + """ + + STREAMER = 1 + FORWARDER = 2 + QUEUE = 3 + + +# AUTOGENERATED_BELOW_HERE + + +IO_THREADS: int = ContextOption.IO_THREADS +MAX_SOCKETS: int = ContextOption.MAX_SOCKETS +SOCKET_LIMIT: int = ContextOption.SOCKET_LIMIT +THREAD_PRIORITY: int = ContextOption.THREAD_PRIORITY +THREAD_SCHED_POLICY: int = ContextOption.THREAD_SCHED_POLICY +MAX_MSGSZ: int = ContextOption.MAX_MSGSZ +MSG_T_SIZE: int = ContextOption.MSG_T_SIZE +THREAD_AFFINITY_CPU_ADD: int = ContextOption.THREAD_AFFINITY_CPU_ADD +THREAD_AFFINITY_CPU_REMOVE: int = ContextOption.THREAD_AFFINITY_CPU_REMOVE +THREAD_NAME_PREFIX: int = ContextOption.THREAD_NAME_PREFIX +STREAMER: int = DeviceType.STREAMER +FORWARDER: int = DeviceType.FORWARDER +QUEUE: int = DeviceType.QUEUE +EAGAIN: int = Errno.EAGAIN +EFAULT: int = Errno.EFAULT +EINVAL: int = Errno.EINVAL +ENOTSUP: int = Errno.ENOTSUP +EPROTONOSUPPORT: int = Errno.EPROTONOSUPPORT +ENOBUFS: int = Errno.ENOBUFS +ENETDOWN: int = Errno.ENETDOWN +EADDRINUSE: int = Errno.EADDRINUSE +EADDRNOTAVAIL: int = Errno.EADDRNOTAVAIL +ECONNREFUSED: int = Errno.ECONNREFUSED +EINPROGRESS: int = Errno.EINPROGRESS +ENOTSOCK: int = Errno.ENOTSOCK +EMSGSIZE: int = Errno.EMSGSIZE +EAFNOSUPPORT: int = Errno.EAFNOSUPPORT +ENETUNREACH: int = Errno.ENETUNREACH +ECONNABORTED: int = Errno.ECONNABORTED +ECONNRESET: int = Errno.ECONNRESET +ENOTCONN: int = Errno.ENOTCONN +ETIMEDOUT: int = Errno.ETIMEDOUT +EHOSTUNREACH: int = Errno.EHOSTUNREACH +ENETRESET: int = Errno.ENETRESET +EFSM: int = Errno.EFSM +ENOCOMPATPROTO: int = Errno.ENOCOMPATPROTO +ETERM: int = Errno.ETERM +EMTHREAD: int = Errno.EMTHREAD +PROTOCOL_ERROR_WS_UNSPECIFIED: int = Event.PROTOCOL_ERROR_WS_UNSPECIFIED +PROTOCOL_ERROR_ZMTP_UNSPECIFIED: int = Event.PROTOCOL_ERROR_ZMTP_UNSPECIFIED +PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND: int = ( + Event.PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND +) +PROTOCOL_ERROR_ZMTP_INVALID_SEQUENCE: int = Event.PROTOCOL_ERROR_ZMTP_INVALID_SEQUENCE +PROTOCOL_ERROR_ZMTP_KEY_EXCHANGE: int = Event.PROTOCOL_ERROR_ZMTP_KEY_EXCHANGE +PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_UNSPECIFIED: int = ( + Event.PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_UNSPECIFIED +) +PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_MESSAGE: int = ( + Event.PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_MESSAGE +) +PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO: int = ( + Event.PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO +) +PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_INITIATE: int = ( + Event.PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_INITIATE +) +PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_ERROR: int = ( + Event.PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_ERROR +) +PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_READY: int = ( + Event.PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_READY +) +PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_WELCOME: int = ( + Event.PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_WELCOME +) +PROTOCOL_ERROR_ZMTP_INVALID_METADATA: int = Event.PROTOCOL_ERROR_ZMTP_INVALID_METADATA +PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC: int = Event.PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC +PROTOCOL_ERROR_ZMTP_MECHANISM_MISMATCH: int = ( + Event.PROTOCOL_ERROR_ZMTP_MECHANISM_MISMATCH +) +PROTOCOL_ERROR_ZAP_UNSPECIFIED: int = Event.PROTOCOL_ERROR_ZAP_UNSPECIFIED +PROTOCOL_ERROR_ZAP_MALFORMED_REPLY: int = Event.PROTOCOL_ERROR_ZAP_MALFORMED_REPLY +PROTOCOL_ERROR_ZAP_BAD_REQUEST_ID: int = Event.PROTOCOL_ERROR_ZAP_BAD_REQUEST_ID +PROTOCOL_ERROR_ZAP_BAD_VERSION: int = Event.PROTOCOL_ERROR_ZAP_BAD_VERSION +PROTOCOL_ERROR_ZAP_INVALID_STATUS_CODE: int = ( + Event.PROTOCOL_ERROR_ZAP_INVALID_STATUS_CODE +) +PROTOCOL_ERROR_ZAP_INVALID_METADATA: int = Event.PROTOCOL_ERROR_ZAP_INVALID_METADATA +EVENT_CONNECTED: int = Event.CONNECTED +EVENT_CONNECT_DELAYED: int = Event.CONNECT_DELAYED +EVENT_CONNECT_RETRIED: int = Event.CONNECT_RETRIED +EVENT_LISTENING: int = Event.LISTENING +EVENT_BIND_FAILED: int = Event.BIND_FAILED +EVENT_ACCEPTED: int = Event.ACCEPTED +EVENT_ACCEPT_FAILED: int = Event.ACCEPT_FAILED +EVENT_CLOSED: int = Event.CLOSED +EVENT_CLOSE_FAILED: int = Event.CLOSE_FAILED +EVENT_DISCONNECTED: int = Event.DISCONNECTED +EVENT_MONITOR_STOPPED: int = Event.MONITOR_STOPPED +EVENT_HANDSHAKE_FAILED_NO_DETAIL: int = Event.HANDSHAKE_FAILED_NO_DETAIL +EVENT_HANDSHAKE_SUCCEEDED: int = Event.HANDSHAKE_SUCCEEDED +EVENT_HANDSHAKE_FAILED_PROTOCOL: int = Event.HANDSHAKE_FAILED_PROTOCOL +EVENT_HANDSHAKE_FAILED_AUTH: int = Event.HANDSHAKE_FAILED_AUTH +EVENT_ALL_V1: int = Event.ALL_V1 +EVENT_ALL: int = Event.ALL +EVENT_PIPES_STATS: int = Event.PIPES_STATS +EVENT_ALL_V2: int = Event.ALL_V2 +DONTWAIT: int = Flag.DONTWAIT +SNDMORE: int = Flag.SNDMORE +NOBLOCK: int = Flag.NOBLOCK +MORE: int = MessageOption.MORE +SHARED: int = MessageOption.SHARED +SRCFD: int = MessageOption.SRCFD +NORM_FIXED: int = NormMode.FIXED +NORM_CC: int = NormMode.CC +NORM_CCL: int = NormMode.CCL +NORM_CCE: int = NormMode.CCE +NORM_CCE_ECNONLY: int = NormMode.CCE_ECNONLY +POLLIN: int = PollEvent.POLLIN +POLLOUT: int = PollEvent.POLLOUT +POLLERR: int = PollEvent.POLLERR +POLLPRI: int = PollEvent.POLLPRI +RECONNECT_STOP_CONN_REFUSED: int = ReconnectStop.CONN_REFUSED +RECONNECT_STOP_HANDSHAKE_FAILED: int = ReconnectStop.HANDSHAKE_FAILED +RECONNECT_STOP_AFTER_DISCONNECT: int = ReconnectStop.AFTER_DISCONNECT +NOTIFY_CONNECT: int = RouterNotify.CONNECT +NOTIFY_DISCONNECT: int = RouterNotify.DISCONNECT +NULL: int = SecurityMechanism.NULL +PLAIN: int = SecurityMechanism.PLAIN +CURVE: int = SecurityMechanism.CURVE +GSSAPI: int = SecurityMechanism.GSSAPI +HWM: int = SocketOption.HWM +AFFINITY: int = SocketOption.AFFINITY +ROUTING_ID: int = SocketOption.ROUTING_ID +SUBSCRIBE: int = SocketOption.SUBSCRIBE +UNSUBSCRIBE: int = SocketOption.UNSUBSCRIBE +RATE: int = SocketOption.RATE +RECOVERY_IVL: int = SocketOption.RECOVERY_IVL +SNDBUF: int = SocketOption.SNDBUF +RCVBUF: int = SocketOption.RCVBUF +RCVMORE: int = SocketOption.RCVMORE +FD: int = SocketOption.FD +EVENTS: int = SocketOption.EVENTS +TYPE: int = SocketOption.TYPE +LINGER: int = SocketOption.LINGER +RECONNECT_IVL: int = SocketOption.RECONNECT_IVL +BACKLOG: int = SocketOption.BACKLOG +RECONNECT_IVL_MAX: int = SocketOption.RECONNECT_IVL_MAX +MAXMSGSIZE: int = SocketOption.MAXMSGSIZE +SNDHWM: int = SocketOption.SNDHWM +RCVHWM: int = SocketOption.RCVHWM +MULTICAST_HOPS: int = SocketOption.MULTICAST_HOPS +RCVTIMEO: int = SocketOption.RCVTIMEO +SNDTIMEO: int = SocketOption.SNDTIMEO +LAST_ENDPOINT: int = SocketOption.LAST_ENDPOINT +ROUTER_MANDATORY: int = SocketOption.ROUTER_MANDATORY +TCP_KEEPALIVE: int = SocketOption.TCP_KEEPALIVE +TCP_KEEPALIVE_CNT: int = SocketOption.TCP_KEEPALIVE_CNT +TCP_KEEPALIVE_IDLE: int = SocketOption.TCP_KEEPALIVE_IDLE +TCP_KEEPALIVE_INTVL: int = SocketOption.TCP_KEEPALIVE_INTVL +IMMEDIATE: int = SocketOption.IMMEDIATE +XPUB_VERBOSE: int = SocketOption.XPUB_VERBOSE +ROUTER_RAW: int = SocketOption.ROUTER_RAW +IPV6: int = SocketOption.IPV6 +MECHANISM: int = SocketOption.MECHANISM +PLAIN_SERVER: int = SocketOption.PLAIN_SERVER +PLAIN_USERNAME: int = SocketOption.PLAIN_USERNAME +PLAIN_PASSWORD: int = SocketOption.PLAIN_PASSWORD +CURVE_SERVER: int = SocketOption.CURVE_SERVER +CURVE_PUBLICKEY: int = SocketOption.CURVE_PUBLICKEY +CURVE_SECRETKEY: int = SocketOption.CURVE_SECRETKEY +CURVE_SERVERKEY: int = SocketOption.CURVE_SERVERKEY +PROBE_ROUTER: int = SocketOption.PROBE_ROUTER +REQ_CORRELATE: int = SocketOption.REQ_CORRELATE +REQ_RELAXED: int = SocketOption.REQ_RELAXED +CONFLATE: int = SocketOption.CONFLATE +ZAP_DOMAIN: int = SocketOption.ZAP_DOMAIN +ROUTER_HANDOVER: int = SocketOption.ROUTER_HANDOVER +TOS: int = SocketOption.TOS +CONNECT_ROUTING_ID: int = SocketOption.CONNECT_ROUTING_ID +GSSAPI_SERVER: int = SocketOption.GSSAPI_SERVER +GSSAPI_PRINCIPAL: int = SocketOption.GSSAPI_PRINCIPAL +GSSAPI_SERVICE_PRINCIPAL: int = SocketOption.GSSAPI_SERVICE_PRINCIPAL +GSSAPI_PLAINTEXT: int = SocketOption.GSSAPI_PLAINTEXT +HANDSHAKE_IVL: int = SocketOption.HANDSHAKE_IVL +SOCKS_PROXY: int = SocketOption.SOCKS_PROXY +XPUB_NODROP: int = SocketOption.XPUB_NODROP +BLOCKY: int = SocketOption.BLOCKY +XPUB_MANUAL: int = SocketOption.XPUB_MANUAL +XPUB_WELCOME_MSG: int = SocketOption.XPUB_WELCOME_MSG +STREAM_NOTIFY: int = SocketOption.STREAM_NOTIFY +INVERT_MATCHING: int = SocketOption.INVERT_MATCHING +HEARTBEAT_IVL: int = SocketOption.HEARTBEAT_IVL +HEARTBEAT_TTL: int = SocketOption.HEARTBEAT_TTL +HEARTBEAT_TIMEOUT: int = SocketOption.HEARTBEAT_TIMEOUT +XPUB_VERBOSER: int = SocketOption.XPUB_VERBOSER +CONNECT_TIMEOUT: int = SocketOption.CONNECT_TIMEOUT +TCP_MAXRT: int = SocketOption.TCP_MAXRT +THREAD_SAFE: int = SocketOption.THREAD_SAFE +MULTICAST_MAXTPDU: int = SocketOption.MULTICAST_MAXTPDU +VMCI_BUFFER_SIZE: int = SocketOption.VMCI_BUFFER_SIZE +VMCI_BUFFER_MIN_SIZE: int = SocketOption.VMCI_BUFFER_MIN_SIZE +VMCI_BUFFER_MAX_SIZE: int = SocketOption.VMCI_BUFFER_MAX_SIZE +VMCI_CONNECT_TIMEOUT: int = SocketOption.VMCI_CONNECT_TIMEOUT +USE_FD: int = SocketOption.USE_FD +GSSAPI_PRINCIPAL_NAMETYPE: int = SocketOption.GSSAPI_PRINCIPAL_NAMETYPE +GSSAPI_SERVICE_PRINCIPAL_NAMETYPE: int = SocketOption.GSSAPI_SERVICE_PRINCIPAL_NAMETYPE +BINDTODEVICE: int = SocketOption.BINDTODEVICE +IDENTITY: int = SocketOption.IDENTITY +CONNECT_RID: int = SocketOption.CONNECT_RID +TCP_ACCEPT_FILTER: int = SocketOption.TCP_ACCEPT_FILTER +IPC_FILTER_PID: int = SocketOption.IPC_FILTER_PID +IPC_FILTER_UID: int = SocketOption.IPC_FILTER_UID +IPC_FILTER_GID: int = SocketOption.IPC_FILTER_GID +IPV4ONLY: int = SocketOption.IPV4ONLY +DELAY_ATTACH_ON_CONNECT: int = SocketOption.DELAY_ATTACH_ON_CONNECT +FAIL_UNROUTABLE: int = SocketOption.FAIL_UNROUTABLE +ROUTER_BEHAVIOR: int = SocketOption.ROUTER_BEHAVIOR +ZAP_ENFORCE_DOMAIN: int = SocketOption.ZAP_ENFORCE_DOMAIN +LOOPBACK_FASTPATH: int = SocketOption.LOOPBACK_FASTPATH +METADATA: int = SocketOption.METADATA +MULTICAST_LOOP: int = SocketOption.MULTICAST_LOOP +ROUTER_NOTIFY: int = SocketOption.ROUTER_NOTIFY +XPUB_MANUAL_LAST_VALUE: int = SocketOption.XPUB_MANUAL_LAST_VALUE +SOCKS_USERNAME: int = SocketOption.SOCKS_USERNAME +SOCKS_PASSWORD: int = SocketOption.SOCKS_PASSWORD +IN_BATCH_SIZE: int = SocketOption.IN_BATCH_SIZE +OUT_BATCH_SIZE: int = SocketOption.OUT_BATCH_SIZE +WSS_KEY_PEM: int = SocketOption.WSS_KEY_PEM +WSS_CERT_PEM: int = SocketOption.WSS_CERT_PEM +WSS_TRUST_PEM: int = SocketOption.WSS_TRUST_PEM +WSS_HOSTNAME: int = SocketOption.WSS_HOSTNAME +WSS_TRUST_SYSTEM: int = SocketOption.WSS_TRUST_SYSTEM +ONLY_FIRST_SUBSCRIBE: int = SocketOption.ONLY_FIRST_SUBSCRIBE +RECONNECT_STOP: int = SocketOption.RECONNECT_STOP +HELLO_MSG: int = SocketOption.HELLO_MSG +DISCONNECT_MSG: int = SocketOption.DISCONNECT_MSG +PRIORITY: int = SocketOption.PRIORITY +BUSY_POLL: int = SocketOption.BUSY_POLL +HICCUP_MSG: int = SocketOption.HICCUP_MSG +XSUB_VERBOSE_UNSUBSCRIBE: int = SocketOption.XSUB_VERBOSE_UNSUBSCRIBE +TOPICS_COUNT: int = SocketOption.TOPICS_COUNT +NORM_MODE: int = SocketOption.NORM_MODE +NORM_UNICAST_NACK: int = SocketOption.NORM_UNICAST_NACK +NORM_BUFFER_SIZE: int = SocketOption.NORM_BUFFER_SIZE +NORM_SEGMENT_SIZE: int = SocketOption.NORM_SEGMENT_SIZE +NORM_BLOCK_SIZE: int = SocketOption.NORM_BLOCK_SIZE +NORM_NUM_PARITY: int = SocketOption.NORM_NUM_PARITY +NORM_NUM_AUTOPARITY: int = SocketOption.NORM_NUM_AUTOPARITY +NORM_PUSH: int = SocketOption.NORM_PUSH +PAIR: int = SocketType.PAIR +PUB: int = SocketType.PUB +SUB: int = SocketType.SUB +REQ: int = SocketType.REQ +REP: int = SocketType.REP +DEALER: int = SocketType.DEALER +ROUTER: int = SocketType.ROUTER +PULL: int = SocketType.PULL +PUSH: int = SocketType.PUSH +XPUB: int = SocketType.XPUB +XSUB: int = SocketType.XSUB +STREAM: int = SocketType.STREAM +XREQ: int = SocketType.XREQ +XREP: int = SocketType.XREP +SERVER: int = SocketType.SERVER +CLIENT: int = SocketType.CLIENT +RADIO: int = SocketType.RADIO +DISH: int = SocketType.DISH +GATHER: int = SocketType.GATHER +SCATTER: int = SocketType.SCATTER +DGRAM: int = SocketType.DGRAM +PEER: int = SocketType.PEER +CHANNEL: int = SocketType.CHANNEL + +__all__: list[str] = [ + "ContextOption", + "IO_THREADS", + "MAX_SOCKETS", + "SOCKET_LIMIT", + "THREAD_PRIORITY", + "THREAD_SCHED_POLICY", + "MAX_MSGSZ", + "MSG_T_SIZE", + "THREAD_AFFINITY_CPU_ADD", + "THREAD_AFFINITY_CPU_REMOVE", + "THREAD_NAME_PREFIX", + "DeviceType", + "STREAMER", + "FORWARDER", + "QUEUE", + "Enum", + "Errno", + "EAGAIN", + "EFAULT", + "EINVAL", + "ENOTSUP", + "EPROTONOSUPPORT", + "ENOBUFS", + "ENETDOWN", + "EADDRINUSE", + "EADDRNOTAVAIL", + "ECONNREFUSED", + "EINPROGRESS", + "ENOTSOCK", + "EMSGSIZE", + "EAFNOSUPPORT", + "ENETUNREACH", + "ECONNABORTED", + "ECONNRESET", + "ENOTCONN", + "ETIMEDOUT", + "EHOSTUNREACH", + "ENETRESET", + "EFSM", + "ENOCOMPATPROTO", + "ETERM", + "EMTHREAD", + "Event", + "PROTOCOL_ERROR_WS_UNSPECIFIED", + "PROTOCOL_ERROR_ZMTP_UNSPECIFIED", + "PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND", + "PROTOCOL_ERROR_ZMTP_INVALID_SEQUENCE", + "PROTOCOL_ERROR_ZMTP_KEY_EXCHANGE", + "PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_UNSPECIFIED", + "PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_MESSAGE", + "PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO", + "PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_INITIATE", + "PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_ERROR", + "PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_READY", + "PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_WELCOME", + "PROTOCOL_ERROR_ZMTP_INVALID_METADATA", + "PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC", + "PROTOCOL_ERROR_ZMTP_MECHANISM_MISMATCH", + "PROTOCOL_ERROR_ZAP_UNSPECIFIED", + "PROTOCOL_ERROR_ZAP_MALFORMED_REPLY", + "PROTOCOL_ERROR_ZAP_BAD_REQUEST_ID", + "PROTOCOL_ERROR_ZAP_BAD_VERSION", + "PROTOCOL_ERROR_ZAP_INVALID_STATUS_CODE", + "PROTOCOL_ERROR_ZAP_INVALID_METADATA", + "EVENT_CONNECTED", + "EVENT_CONNECT_DELAYED", + "EVENT_CONNECT_RETRIED", + "EVENT_LISTENING", + "EVENT_BIND_FAILED", + "EVENT_ACCEPTED", + "EVENT_ACCEPT_FAILED", + "EVENT_CLOSED", + "EVENT_CLOSE_FAILED", + "EVENT_DISCONNECTED", + "EVENT_MONITOR_STOPPED", + "EVENT_HANDSHAKE_FAILED_NO_DETAIL", + "EVENT_HANDSHAKE_SUCCEEDED", + "EVENT_HANDSHAKE_FAILED_PROTOCOL", + "EVENT_HANDSHAKE_FAILED_AUTH", + "EVENT_ALL_V1", + "EVENT_ALL", + "EVENT_PIPES_STATS", + "EVENT_ALL_V2", + "Flag", + "DONTWAIT", + "SNDMORE", + "NOBLOCK", + "IntEnum", + "IntFlag", + "MessageOption", + "MORE", + "SHARED", + "SRCFD", + "NormMode", + "NORM_FIXED", + "NORM_CC", + "NORM_CCL", + "NORM_CCE", + "NORM_CCE_ECNONLY", + "PollEvent", + "POLLIN", + "POLLOUT", + "POLLERR", + "POLLPRI", + "ReconnectStop", + "RECONNECT_STOP_CONN_REFUSED", + "RECONNECT_STOP_HANDSHAKE_FAILED", + "RECONNECT_STOP_AFTER_DISCONNECT", + "RouterNotify", + "NOTIFY_CONNECT", + "NOTIFY_DISCONNECT", + "SecurityMechanism", + "NULL", + "PLAIN", + "CURVE", + "GSSAPI", + "SocketOption", + "HWM", + "AFFINITY", + "ROUTING_ID", + "SUBSCRIBE", + "UNSUBSCRIBE", + "RATE", + "RECOVERY_IVL", + "SNDBUF", + "RCVBUF", + "RCVMORE", + "FD", + "EVENTS", + "TYPE", + "LINGER", + "RECONNECT_IVL", + "BACKLOG", + "RECONNECT_IVL_MAX", + "MAXMSGSIZE", + "SNDHWM", + "RCVHWM", + "MULTICAST_HOPS", + "RCVTIMEO", + "SNDTIMEO", + "LAST_ENDPOINT", + "ROUTER_MANDATORY", + "TCP_KEEPALIVE", + "TCP_KEEPALIVE_CNT", + "TCP_KEEPALIVE_IDLE", + "TCP_KEEPALIVE_INTVL", + "IMMEDIATE", + "XPUB_VERBOSE", + "ROUTER_RAW", + "IPV6", + "MECHANISM", + "PLAIN_SERVER", + "PLAIN_USERNAME", + "PLAIN_PASSWORD", + "CURVE_SERVER", + "CURVE_PUBLICKEY", + "CURVE_SECRETKEY", + "CURVE_SERVERKEY", + "PROBE_ROUTER", + "REQ_CORRELATE", + "REQ_RELAXED", + "CONFLATE", + "ZAP_DOMAIN", + "ROUTER_HANDOVER", + "TOS", + "CONNECT_ROUTING_ID", + "GSSAPI_SERVER", + "GSSAPI_PRINCIPAL", + "GSSAPI_SERVICE_PRINCIPAL", + "GSSAPI_PLAINTEXT", + "HANDSHAKE_IVL", + "SOCKS_PROXY", + "XPUB_NODROP", + "BLOCKY", + "XPUB_MANUAL", + "XPUB_WELCOME_MSG", + "STREAM_NOTIFY", + "INVERT_MATCHING", + "HEARTBEAT_IVL", + "HEARTBEAT_TTL", + "HEARTBEAT_TIMEOUT", + "XPUB_VERBOSER", + "CONNECT_TIMEOUT", + "TCP_MAXRT", + "THREAD_SAFE", + "MULTICAST_MAXTPDU", + "VMCI_BUFFER_SIZE", + "VMCI_BUFFER_MIN_SIZE", + "VMCI_BUFFER_MAX_SIZE", + "VMCI_CONNECT_TIMEOUT", + "USE_FD", + "GSSAPI_PRINCIPAL_NAMETYPE", + "GSSAPI_SERVICE_PRINCIPAL_NAMETYPE", + "BINDTODEVICE", + "IDENTITY", + "CONNECT_RID", + "TCP_ACCEPT_FILTER", + "IPC_FILTER_PID", + "IPC_FILTER_UID", + "IPC_FILTER_GID", + "IPV4ONLY", + "DELAY_ATTACH_ON_CONNECT", + "FAIL_UNROUTABLE", + "ROUTER_BEHAVIOR", + "ZAP_ENFORCE_DOMAIN", + "LOOPBACK_FASTPATH", + "METADATA", + "MULTICAST_LOOP", + "ROUTER_NOTIFY", + "XPUB_MANUAL_LAST_VALUE", + "SOCKS_USERNAME", + "SOCKS_PASSWORD", + "IN_BATCH_SIZE", + "OUT_BATCH_SIZE", + "WSS_KEY_PEM", + "WSS_CERT_PEM", + "WSS_TRUST_PEM", + "WSS_HOSTNAME", + "WSS_TRUST_SYSTEM", + "ONLY_FIRST_SUBSCRIBE", + "RECONNECT_STOP", + "HELLO_MSG", + "DISCONNECT_MSG", + "PRIORITY", + "BUSY_POLL", + "HICCUP_MSG", + "XSUB_VERBOSE_UNSUBSCRIBE", + "TOPICS_COUNT", + "NORM_MODE", + "NORM_UNICAST_NACK", + "NORM_BUFFER_SIZE", + "NORM_SEGMENT_SIZE", + "NORM_BLOCK_SIZE", + "NORM_NUM_PARITY", + "NORM_NUM_AUTOPARITY", + "NORM_PUSH", + "SocketType", + "PAIR", + "PUB", + "SUB", + "REQ", + "REP", + "DEALER", + "ROUTER", + "PULL", + "PUSH", + "XPUB", + "XSUB", + "STREAM", + "XREQ", + "XREP", + "SERVER", + "CLIENT", + "RADIO", + "DISH", + "GATHER", + "SCATTER", + "DGRAM", + "PEER", + "CHANNEL", +] diff --git a/venv/lib/python3.10/site-packages/zmq/decorators.py b/venv/lib/python3.10/site-packages/zmq/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..7cd80ebc764fb0b83146821ea85af3ce4aad8196 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/decorators.py @@ -0,0 +1,190 @@ +"""Decorators for running functions with context/sockets. + +.. versionadded:: 15.3 + +Like using Contexts and Sockets as context managers, but with decorator syntax. +Context and sockets are closed at the end of the function. + +For example:: + + from zmq.decorators import context, socket + + @context() + @socket(zmq.PUSH) + def work(ctx, push): + ... +""" + +from __future__ import annotations + +# Copyright (c) PyZMQ Developers. +# Distributed under the terms of the Modified BSD License. + +__all__ = ( + 'context', + 'socket', +) + +from functools import wraps + +import zmq + + +class _Decorator: + '''The mini decorator factory''' + + def __init__(self, target=None): + self._target = target + + def __call__(self, *dec_args, **dec_kwargs): + """ + The main logic of decorator + + Here is how those arguments works:: + + @out_decorator(*dec_args, *dec_kwargs) + def func(*wrap_args, **wrap_kwargs): + ... + + And in the ``wrapper``, we simply create ``self.target`` instance via + ``with``:: + + target = self.get_target(*args, **kwargs) + with target(*dec_args, **dec_kwargs) as obj: + ... + + """ + kw_name, dec_args, dec_kwargs = self.process_decorator_args( + *dec_args, **dec_kwargs + ) + + def decorator(func): + @wraps(func) + def wrapper(*args, **kwargs): + target = self.get_target(*args, **kwargs) + + with target(*dec_args, **dec_kwargs) as obj: + # insert our object into args + if kw_name and kw_name not in kwargs: + kwargs[kw_name] = obj + elif kw_name and kw_name in kwargs: + raise TypeError( + f"{func.__name__}() got multiple values for" + f" argument '{kw_name}'" + ) + else: + args = args + (obj,) + + return func(*args, **kwargs) + + return wrapper + + return decorator + + def get_target(self, *args, **kwargs): + """Return the target function + + Allows modifying args/kwargs to be passed. + """ + return self._target + + def process_decorator_args(self, *args, **kwargs): + """Process args passed to the decorator. + + args not consumed by the decorator will be passed to the target factory + (Context/Socket constructor). + """ + kw_name = None + + if isinstance(kwargs.get('name'), str): + kw_name = kwargs.pop('name') + elif len(args) >= 1 and isinstance(args[0], str): + kw_name = args[0] + args = args[1:] + + return kw_name, args, kwargs + + +class _ContextDecorator(_Decorator): + """Decorator subclass for Contexts""" + + def __init__(self): + super().__init__(zmq.Context) + + +class _SocketDecorator(_Decorator): + """Decorator subclass for sockets + + Gets the context from other args. + """ + + def process_decorator_args(self, *args, **kwargs): + """Also grab context_name out of kwargs""" + kw_name, args, kwargs = super().process_decorator_args(*args, **kwargs) + self.context_name = kwargs.pop('context_name', 'context') + return kw_name, args, kwargs + + def get_target(self, *args, **kwargs): + """Get context, based on call-time args""" + context = self._get_context(*args, **kwargs) + return context.socket + + def _get_context(self, *args, **kwargs): + """ + Find the ``zmq.Context`` from ``args`` and ``kwargs`` at call time. + + First, if there is an keyword argument named ``context`` and it is a + ``zmq.Context`` instance , we will take it. + + Second, we check all the ``args``, take the first ``zmq.Context`` + instance. + + Finally, we will provide default Context -- ``zmq.Context.instance`` + + :return: a ``zmq.Context`` instance + """ + if self.context_name in kwargs: + ctx = kwargs[self.context_name] + + if isinstance(ctx, zmq.Context): + return ctx + + for arg in args: + if isinstance(arg, zmq.Context): + return arg + # not specified by any decorator + return zmq.Context.instance() + + +def context(*args, **kwargs): + """Decorator for adding a Context to a function. + + Usage:: + + @context() + def foo(ctx): + ... + + .. versionadded:: 15.3 + + :param str name: the keyword argument passed to decorated function + """ + return _ContextDecorator()(*args, **kwargs) + + +def socket(*args, **kwargs): + """Decorator for adding a socket to a function. + + Usage:: + + @socket(zmq.PUSH) + def foo(push): + ... + + .. versionadded:: 15.3 + + :param str name: the keyword argument passed to decorated function + :param str context_name: the keyword only argument to identify context + object + """ + return _SocketDecorator()(*args, **kwargs) diff --git a/venv/lib/python3.10/site-packages/zmq/devices/__init__.py b/venv/lib/python3.10/site-packages/zmq/devices/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ccf2aa471104cccb82fe55e91a14ce81e1b25a --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/devices/__init__.py @@ -0,0 +1,30 @@ +"""0MQ Device classes for running in background threads or processes.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from __future__ import annotations + +from zmq import DeviceType, proxy +from zmq.devices import ( + basedevice, + monitoredqueue, + monitoredqueuedevice, + proxydevice, + proxysteerabledevice, +) +from zmq.devices.basedevice import * +from zmq.devices.monitoredqueue import * +from zmq.devices.monitoredqueuedevice import * +from zmq.devices.proxydevice import * +from zmq.devices.proxysteerabledevice import * + +__all__ = [] +for submod in ( + basedevice, + proxydevice, + proxysteerabledevice, + monitoredqueue, + monitoredqueuedevice, +): + __all__.extend(submod.__all__) # type: ignore diff --git a/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fce3c1c5ee57e747a979252fd508334dc49b95fc Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/basedevice.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/basedevice.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..761abe1fe026ec435e21139bbfbf1d97e777e7e1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/basedevice.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/monitoredqueue.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/monitoredqueue.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33a699c96b13b820b3307062d8b55c6d87bce174 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/monitoredqueue.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/monitoredqueuedevice.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/monitoredqueuedevice.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be7c911cf9b905247ae0324100db5ce60dab17ae Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/monitoredqueuedevice.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/proxydevice.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/proxydevice.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b00b16e2d2cc9e9e262e48dbe9fcc6f80d1e4fa Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/proxydevice.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/proxysteerabledevice.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/proxysteerabledevice.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c72333bd6929592a1a4a343271486594bade7ba Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/devices/__pycache__/proxysteerabledevice.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/devices/basedevice.py b/venv/lib/python3.10/site-packages/zmq/devices/basedevice.py new file mode 100644 index 0000000000000000000000000000000000000000..5039fd70d03e9713beb6954016f4946e11052e75 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/devices/basedevice.py @@ -0,0 +1,310 @@ +"""Classes for running 0MQ Devices in the background.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import time +from multiprocessing import Process +from threading import Thread +from typing import Any, Callable, List, Optional, Tuple + +import zmq +from zmq import ENOTSOCK, ETERM, PUSH, QUEUE, Context, ZMQBindError, ZMQError, proxy + + +class Device: + """A 0MQ Device to be run in the background. + + You do not pass Socket instances to this, but rather Socket types:: + + Device(device_type, in_socket_type, out_socket_type) + + For instance:: + + dev = Device(zmq.QUEUE, zmq.DEALER, zmq.ROUTER) + + Similar to zmq.device, but socket types instead of sockets themselves are + passed, and the sockets are created in the work thread, to avoid issues + with thread safety. As a result, additional bind_{in|out} and + connect_{in|out} methods and setsockopt_{in|out} allow users to specify + connections for the sockets. + + Parameters + ---------- + device_type : int + The 0MQ Device type + {in|out}_type : int + zmq socket types, to be passed later to context.socket(). e.g. + zmq.PUB, zmq.SUB, zmq.REQ. If out_type is < 0, then in_socket is used + for both in_socket and out_socket. + + Methods + ------- + bind_{in_out}(iface) + passthrough for ``{in|out}_socket.bind(iface)``, to be called in the thread + connect_{in_out}(iface) + passthrough for ``{in|out}_socket.connect(iface)``, to be called in the + thread + setsockopt_{in_out}(opt,value) + passthrough for ``{in|out}_socket.setsockopt(opt, value)``, to be called in + the thread + + Attributes + ---------- + daemon : bool + sets whether the thread should be run as a daemon + Default is true, because if it is false, the thread will not + exit unless it is killed + context_factory : callable + This is a class attribute. + Function for creating the Context. This will be Context.instance + in ThreadDevices, and Context in ProcessDevices. The only reason + it is not instance() in ProcessDevices is that there may be a stale + Context instance already initialized, and the forked environment + should *never* try to use it. + """ + + context_factory: Callable[[], zmq.Context] = Context.instance + """Callable that returns a context. Typically either Context.instance or Context, + depending on whether the device should share the global instance or not. + """ + + daemon: bool + device_type: int + in_type: int + out_type: int + + _in_binds: List[str] + _in_connects: List[str] + _in_sockopts: List[Tuple[int, Any]] + _out_binds: List[str] + _out_connects: List[str] + _out_sockopts: List[Tuple[int, Any]] + _random_addrs: List[str] + _sockets: List[zmq.Socket] + + def __init__( + self, + device_type: int = QUEUE, + in_type: Optional[int] = None, + out_type: Optional[int] = None, + ) -> None: + self.device_type = device_type + if in_type is None: + raise TypeError("in_type must be specified") + if out_type is None: + raise TypeError("out_type must be specified") + self.in_type = in_type + self.out_type = out_type + self._in_binds = [] + self._in_connects = [] + self._in_sockopts = [] + self._out_binds = [] + self._out_connects = [] + self._out_sockopts = [] + self._random_addrs = [] + self.daemon = True + self.done = False + self._sockets = [] + + def bind_in(self, addr: str) -> None: + """Enqueue ZMQ address for binding on in_socket. + + See zmq.Socket.bind for details. + """ + self._in_binds.append(addr) + + def bind_in_to_random_port(self, addr: str, *args, **kwargs) -> int: + """Enqueue a random port on the given interface for binding on + in_socket. + + See zmq.Socket.bind_to_random_port for details. + + .. versionadded:: 18.0 + """ + port = self._reserve_random_port(addr, *args, **kwargs) + + self.bind_in(f'{addr}:{port}') + + return port + + def connect_in(self, addr: str) -> None: + """Enqueue ZMQ address for connecting on in_socket. + + See zmq.Socket.connect for details. + """ + self._in_connects.append(addr) + + def setsockopt_in(self, opt: int, value: Any) -> None: + """Enqueue setsockopt(opt, value) for in_socket + + See zmq.Socket.setsockopt for details. + """ + self._in_sockopts.append((opt, value)) + + def bind_out(self, addr: str) -> None: + """Enqueue ZMQ address for binding on out_socket. + + See zmq.Socket.bind for details. + """ + self._out_binds.append(addr) + + def bind_out_to_random_port(self, addr: str, *args, **kwargs) -> int: + """Enqueue a random port on the given interface for binding on + out_socket. + + See zmq.Socket.bind_to_random_port for details. + + .. versionadded:: 18.0 + """ + port = self._reserve_random_port(addr, *args, **kwargs) + + self.bind_out(f'{addr}:{port}') + + return port + + def connect_out(self, addr: str): + """Enqueue ZMQ address for connecting on out_socket. + + See zmq.Socket.connect for details. + """ + self._out_connects.append(addr) + + def setsockopt_out(self, opt: int, value: Any): + """Enqueue setsockopt(opt, value) for out_socket + + See zmq.Socket.setsockopt for details. + """ + self._out_sockopts.append((opt, value)) + + def _reserve_random_port(self, addr: str, *args, **kwargs) -> int: + with Context() as ctx: + with ctx.socket(PUSH) as binder: + for i in range(5): + port = binder.bind_to_random_port(addr, *args, **kwargs) + + new_addr = f'{addr}:{port}' + + if new_addr in self._random_addrs: + continue + else: + break + else: + raise ZMQBindError("Could not reserve random port.") + + self._random_addrs.append(new_addr) + + return port + + def _setup_sockets(self) -> Tuple[zmq.Socket, zmq.Socket]: + ctx: zmq.Context[zmq.Socket] = self.context_factory() # type: ignore + self._context = ctx + + # create the sockets + ins = ctx.socket(self.in_type) + self._sockets.append(ins) + if self.out_type < 0: + outs = ins + else: + outs = ctx.socket(self.out_type) + self._sockets.append(outs) + + # set sockopts (must be done first, in case of zmq.IDENTITY) + for opt, value in self._in_sockopts: + ins.setsockopt(opt, value) + for opt, value in self._out_sockopts: + outs.setsockopt(opt, value) + + for iface in self._in_binds: + ins.bind(iface) + for iface in self._out_binds: + outs.bind(iface) + + for iface in self._in_connects: + ins.connect(iface) + for iface in self._out_connects: + outs.connect(iface) + + return ins, outs + + def run_device(self) -> None: + """The runner method. + + Do not call me directly, instead call ``self.start()``, just like a Thread. + """ + ins, outs = self._setup_sockets() + proxy(ins, outs) + + def _close_sockets(self): + """Cleanup sockets we created""" + for s in self._sockets: + if s and not s.closed: + s.close() + + def run(self) -> None: + """wrap run_device in try/catch ETERM""" + try: + self.run_device() + except ZMQError as e: + if e.errno in {ETERM, ENOTSOCK}: + # silence TERM, ENOTSOCK errors, because this should be a clean shutdown + pass + else: + raise + finally: + self.done = True + self._close_sockets() + + def start(self) -> None: + """Start the device. Override me in subclass for other launchers.""" + return self.run() + + def join(self, timeout: Optional[float] = None) -> None: + """wait for me to finish, like Thread.join. + + Reimplemented appropriately by subclasses.""" + tic = time.monotonic() + toc = tic + while not self.done and not (timeout is not None and toc - tic > timeout): + time.sleep(0.001) + toc = time.monotonic() + + +class BackgroundDevice(Device): + """Base class for launching Devices in background processes and threads.""" + + launcher: Any = None + _launch_class: Any = None + + def start(self) -> None: + self.launcher = self._launch_class(target=self.run) + self.launcher.daemon = self.daemon + return self.launcher.start() + + def join(self, timeout: Optional[float] = None) -> None: + return self.launcher.join(timeout=timeout) + + +class ThreadDevice(BackgroundDevice): + """A Device that will be run in a background Thread. + + See Device for details. + """ + + _launch_class = Thread + + +class ProcessDevice(BackgroundDevice): + """A Device that will be run in a background Process. + + See Device for details. + """ + + _launch_class = Process + context_factory = Context + """Callable that returns a context. Typically either Context.instance or Context, + depending on whether the device should share the global instance or not. + """ + + +__all__ = ['Device', 'ThreadDevice', 'ProcessDevice'] diff --git a/venv/lib/python3.10/site-packages/zmq/devices/monitoredqueue.py b/venv/lib/python3.10/site-packages/zmq/devices/monitoredqueue.py new file mode 100644 index 0000000000000000000000000000000000000000..f590457a8696979889fe3b5f4b7604f6149d69b7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/devices/monitoredqueue.py @@ -0,0 +1,51 @@ +"""pure Python monitored_queue function + +For use when Cython extension is unavailable (PyPy). + +Authors +------- +* MinRK +""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from typing import Callable + +import zmq +from zmq.backend import monitored_queue as _backend_mq + + +def _relay(ins, outs, sides, prefix, swap_ids): + msg = ins.recv_multipart() + if swap_ids: + msg[:2] = msg[:2][::-1] + outs.send_multipart(msg) + sides.send_multipart([prefix] + msg) + + +def _monitored_queue( + in_socket, out_socket, mon_socket, in_prefix=b'in', out_prefix=b'out' +): + swap_ids = in_socket.type == zmq.ROUTER and out_socket.type == zmq.ROUTER + + poller = zmq.Poller() + poller.register(in_socket, zmq.POLLIN) + poller.register(out_socket, zmq.POLLIN) + while True: + events = dict(poller.poll()) + if in_socket in events: + _relay(in_socket, out_socket, mon_socket, in_prefix, swap_ids) + if out_socket in events: + _relay(out_socket, in_socket, mon_socket, out_prefix, swap_ids) + + +monitored_queue: Callable +if _backend_mq is not None: + monitored_queue = _backend_mq # type: ignore +else: + # backend has no monitored_queue + monitored_queue = _monitored_queue + + +__all__ = ['monitored_queue'] diff --git a/venv/lib/python3.10/site-packages/zmq/devices/monitoredqueuedevice.py b/venv/lib/python3.10/site-packages/zmq/devices/monitoredqueuedevice.py new file mode 100644 index 0000000000000000000000000000000000000000..7bcc5629964e3c1fb19cf042c4ec4e16444ac8aa --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/devices/monitoredqueuedevice.py @@ -0,0 +1,60 @@ +"""MonitoredQueue classes and functions.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from zmq import PUB +from zmq.devices.monitoredqueue import monitored_queue +from zmq.devices.proxydevice import ProcessProxy, Proxy, ProxyBase, ThreadProxy + + +class MonitoredQueueBase(ProxyBase): + """Base class for overriding methods.""" + + _in_prefix = b'' + _out_prefix = b'' + + def __init__( + self, in_type, out_type, mon_type=PUB, in_prefix=b'in', out_prefix=b'out' + ): + ProxyBase.__init__(self, in_type=in_type, out_type=out_type, mon_type=mon_type) + + self._in_prefix = in_prefix + self._out_prefix = out_prefix + + def run_device(self): + ins, outs, mons = self._setup_sockets() + monitored_queue(ins, outs, mons, self._in_prefix, self._out_prefix) + + +class MonitoredQueue(MonitoredQueueBase, Proxy): + """Class for running monitored_queue in the background. + + See zmq.devices.Device for most of the spec. MonitoredQueue differs from Proxy, + only in that it adds a ``prefix`` to messages sent on the monitor socket, + with a different prefix for each direction. + + MQ also supports ROUTER on both sides, which zmq.proxy does not. + + If a message arrives on `in_sock`, it will be prefixed with `in_prefix` on the monitor socket. + If it arrives on out_sock, it will be prefixed with `out_prefix`. + + A PUB socket is the most logical choice for the mon_socket, but it is not required. + """ + + +class ThreadMonitoredQueue(MonitoredQueueBase, ThreadProxy): + """Run zmq.monitored_queue in a background thread. + + See MonitoredQueue and Proxy for details. + """ + + +class ProcessMonitoredQueue(MonitoredQueueBase, ProcessProxy): + """Run zmq.monitored_queue in a separate process. + + See MonitoredQueue and Proxy for details. + """ + + +__all__ = ['MonitoredQueue', 'ThreadMonitoredQueue', 'ProcessMonitoredQueue'] diff --git a/venv/lib/python3.10/site-packages/zmq/devices/proxydevice.py b/venv/lib/python3.10/site-packages/zmq/devices/proxydevice.py new file mode 100644 index 0000000000000000000000000000000000000000..f2af06793c27bbf4c9a9c33a377e2acd6ded5c09 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/devices/proxydevice.py @@ -0,0 +1,104 @@ +"""Proxy classes and functions.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import zmq +from zmq.devices.basedevice import Device, ProcessDevice, ThreadDevice + + +class ProxyBase: + """Base class for overriding methods.""" + + def __init__(self, in_type, out_type, mon_type=zmq.PUB): + Device.__init__(self, in_type=in_type, out_type=out_type) + self.mon_type = mon_type + self._mon_binds = [] + self._mon_connects = [] + self._mon_sockopts = [] + + def bind_mon(self, addr): + """Enqueue ZMQ address for binding on mon_socket. + + See zmq.Socket.bind for details. + """ + self._mon_binds.append(addr) + + def bind_mon_to_random_port(self, addr, *args, **kwargs): + """Enqueue a random port on the given interface for binding on + mon_socket. + + See zmq.Socket.bind_to_random_port for details. + + .. versionadded:: 18.0 + """ + port = self._reserve_random_port(addr, *args, **kwargs) + + self.bind_mon(f'{addr}:{port}') + + return port + + def connect_mon(self, addr): + """Enqueue ZMQ address for connecting on mon_socket. + + See zmq.Socket.connect for details. + """ + self._mon_connects.append(addr) + + def setsockopt_mon(self, opt, value): + """Enqueue setsockopt(opt, value) for mon_socket + + See zmq.Socket.setsockopt for details. + """ + self._mon_sockopts.append((opt, value)) + + def _setup_sockets(self): + ins, outs = Device._setup_sockets(self) + ctx = self._context + mons = ctx.socket(self.mon_type) + self._sockets.append(mons) + + # set sockopts (must be done first, in case of zmq.IDENTITY) + for opt, value in self._mon_sockopts: + mons.setsockopt(opt, value) + + for iface in self._mon_binds: + mons.bind(iface) + + for iface in self._mon_connects: + mons.connect(iface) + + return ins, outs, mons + + def run_device(self): + ins, outs, mons = self._setup_sockets() + zmq.proxy(ins, outs, mons) + + +class Proxy(ProxyBase, Device): + """Threadsafe Proxy object. + + See zmq.devices.Device for most of the spec. This subclass adds a + _mon version of each _{in|out} method, for configuring the + monitor socket. + + A Proxy is a 3-socket ZMQ Device that functions just like a + QUEUE, except each message is also sent out on the monitor socket. + + A PUB socket is the most logical choice for the mon_socket, but it is not required. + """ + + +class ThreadProxy(ProxyBase, ThreadDevice): + """Proxy in a Thread. See Proxy for more.""" + + +class ProcessProxy(ProxyBase, ProcessDevice): + """Proxy in a Process. See Proxy for more.""" + + +__all__ = [ + 'Proxy', + 'ThreadProxy', + 'ProcessProxy', +] diff --git a/venv/lib/python3.10/site-packages/zmq/devices/proxysteerabledevice.py b/venv/lib/python3.10/site-packages/zmq/devices/proxysteerabledevice.py new file mode 100644 index 0000000000000000000000000000000000000000..256a1e0498c907791da79935c7ed0f35faf90ce0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/devices/proxysteerabledevice.py @@ -0,0 +1,106 @@ +"""Classes for running a steerable ZMQ proxy""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import zmq +from zmq.devices.proxydevice import ProcessProxy, Proxy, ThreadProxy + + +class ProxySteerableBase: + """Base class for overriding methods.""" + + def __init__(self, in_type, out_type, mon_type=zmq.PUB, ctrl_type=None): + super().__init__(in_type=in_type, out_type=out_type, mon_type=mon_type) + self.ctrl_type = ctrl_type + self._ctrl_binds = [] + self._ctrl_connects = [] + self._ctrl_sockopts = [] + + def bind_ctrl(self, addr): + """Enqueue ZMQ address for binding on ctrl_socket. + + See zmq.Socket.bind for details. + """ + self._ctrl_binds.append(addr) + + def bind_ctrl_to_random_port(self, addr, *args, **kwargs): + """Enqueue a random port on the given interface for binding on + ctrl_socket. + + See zmq.Socket.bind_to_random_port for details. + """ + port = self._reserve_random_port(addr, *args, **kwargs) + + self.bind_ctrl(f'{addr}:{port}') + + return port + + def connect_ctrl(self, addr): + """Enqueue ZMQ address for connecting on ctrl_socket. + + See zmq.Socket.connect for details. + """ + self._ctrl_connects.append(addr) + + def setsockopt_ctrl(self, opt, value): + """Enqueue setsockopt(opt, value) for ctrl_socket + + See zmq.Socket.setsockopt for details. + """ + self._ctrl_sockopts.append((opt, value)) + + def _setup_sockets(self): + ins, outs, mons = super()._setup_sockets() + ctx = self._context + ctrls = ctx.socket(self.ctrl_type) + self._sockets.append(ctrls) + + for opt, value in self._ctrl_sockopts: + ctrls.setsockopt(opt, value) + + for iface in self._ctrl_binds: + ctrls.bind(iface) + + for iface in self._ctrl_connects: + ctrls.connect(iface) + + return ins, outs, mons, ctrls + + def run_device(self): + ins, outs, mons, ctrls = self._setup_sockets() + zmq.proxy_steerable(ins, outs, mons, ctrls) + + +class ProxySteerable(ProxySteerableBase, Proxy): + """Class for running a steerable proxy in the background. + + See zmq.devices.Proxy for most of the spec. If the control socket is not + NULL, the proxy supports control flow, provided by the socket. + + If PAUSE is received on this socket, the proxy suspends its activities. If + RESUME is received, it goes on. If TERMINATE is received, it terminates + smoothly. If the control socket is NULL, the proxy behave exactly as if + zmq.devices.Proxy had been used. + + This subclass adds a _ctrl version of each _{in|out} + method, for configuring the control socket. + + .. versionadded:: libzmq-4.1 + .. versionadded:: 18.0 + """ + + +class ThreadProxySteerable(ProxySteerableBase, ThreadProxy): + """ProxySteerable in a Thread. See ProxySteerable for details.""" + + +class ProcessProxySteerable(ProxySteerableBase, ProcessProxy): + """ProxySteerable in a Process. See ProxySteerable for details.""" + + +__all__ = [ + 'ProxySteerable', + 'ThreadProxySteerable', + 'ProcessProxySteerable', +] diff --git a/venv/lib/python3.10/site-packages/zmq/error.py b/venv/lib/python3.10/site-packages/zmq/error.py new file mode 100644 index 0000000000000000000000000000000000000000..8a07a51fe1fc55aaeb0e1908d5f2251b0d32e9ac --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/error.py @@ -0,0 +1,229 @@ +"""0MQ Error classes and functions.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. +from __future__ import annotations + +from errno import EINTR + + +class DraftFDWarning(RuntimeWarning): + """Warning for using experimental FD on draft sockets. + + .. versionadded:: 27 + """ + + def __init__(self, msg=""): + if not msg: + msg = ( + "pyzmq's back-fill socket.FD support on thread-safe sockets is experimental, and may be removed." + " This warning will go away automatically if/when libzmq implements socket.FD on thread-safe sockets." + " You can suppress this warning with `warnings.simplefilter('ignore', zmq.error.DraftFDWarning)" + ) + super().__init__(msg) + + +class ZMQBaseError(Exception): + """Base exception class for 0MQ errors in Python.""" + + +class ZMQError(ZMQBaseError): + """Wrap an errno style error. + + Parameters + ---------- + errno : int + The ZMQ errno or None. If None, then ``zmq_errno()`` is called and + used. + msg : str + Description of the error or None. + """ + + errno: int | None = None + strerror: str + + def __init__(self, errno: int | None = None, msg: str | None = None): + """Wrap an errno style error. + + Parameters + ---------- + errno : int + The ZMQ errno or None. If None, then ``zmq_errno()`` is called and + used. + msg : string + Description of the error or None. + """ + from zmq.backend import strerror, zmq_errno + + if errno is None: + errno = zmq_errno() + if isinstance(errno, int): + self.errno = errno + if msg is None: + self.strerror = strerror(errno) + else: + self.strerror = msg + else: + if msg is None: + self.strerror = str(errno) + else: + self.strerror = msg + # flush signals, because there could be a SIGINT + # waiting to pounce, resulting in uncaught exceptions. + # Doing this here means getting SIGINT during a blocking + # libzmq call will raise a *catchable* KeyboardInterrupt + # PyErr_CheckSignals() + + def __str__(self) -> str: + return self.strerror + + def __repr__(self) -> str: + return f"{self.__class__.__name__}('{str(self)}')" + + +class ZMQBindError(ZMQBaseError): + """An error for ``Socket.bind_to_random_port()``. + + See Also + -------- + .Socket.bind_to_random_port + """ + + +class NotDone(ZMQBaseError): + """Raised when timeout is reached while waiting for 0MQ to finish with a Message + + See Also + -------- + .MessageTracker.wait : object for tracking when ZeroMQ is done + """ + + +class ContextTerminated(ZMQError): + """Wrapper for zmq.ETERM + + .. versionadded:: 13.0 + """ + + def __init__(self, errno="ignored", msg="ignored"): + from zmq import ETERM + + super().__init__(ETERM) + + +class Again(ZMQError): + """Wrapper for zmq.EAGAIN + + .. versionadded:: 13.0 + """ + + def __init__(self, errno="ignored", msg="ignored"): + from zmq import EAGAIN + + super().__init__(EAGAIN) + + +class InterruptedSystemCall(ZMQError, InterruptedError): + """Wrapper for EINTR + + This exception should be caught internally in pyzmq + to retry system calls, and not propagate to the user. + + .. versionadded:: 14.7 + """ + + errno = EINTR + strerror: str + + def __init__(self, errno="ignored", msg="ignored"): + super().__init__(EINTR) + + def __str__(self): + s = super().__str__() + return s + ": This call should have been retried. Please report this to pyzmq." + + +def _check_rc(rc, errno=None, error_without_errno=True): + """internal utility for checking zmq return condition + + and raising the appropriate Exception class + """ + if rc == -1: + if errno is None: + from zmq.backend import zmq_errno + + errno = zmq_errno() + if errno == 0 and not error_without_errno: + return + from zmq import EAGAIN, ETERM + + if errno == EINTR: + raise InterruptedSystemCall(errno) + elif errno == EAGAIN: + raise Again(errno) + elif errno == ETERM: + raise ContextTerminated(errno) + else: + raise ZMQError(errno) + + +_zmq_version_info = None +_zmq_version = None + + +class ZMQVersionError(NotImplementedError): + """Raised when a feature is not provided by the linked version of libzmq. + + .. versionadded:: 14.2 + """ + + min_version = None + + def __init__(self, min_version: str, msg: str = "Feature"): + global _zmq_version + if _zmq_version is None: + from zmq import zmq_version + + _zmq_version = zmq_version() + self.msg = msg + self.min_version = min_version + self.version = _zmq_version + + def __repr__(self): + return f"ZMQVersionError('{str(self)}')" + + def __str__(self): + return f"{self.msg} requires libzmq >= {self.min_version}, have {self.version}" + + +def _check_version( + min_version_info: tuple[int] | tuple[int, int] | tuple[int, int, int], + msg: str = "Feature", +): + """Check for libzmq + + raises ZMQVersionError if current zmq version is not at least min_version + + min_version_info is a tuple of integers, and will be compared against zmq.zmq_version_info(). + """ + global _zmq_version_info + if _zmq_version_info is None: + from zmq import zmq_version_info + + _zmq_version_info = zmq_version_info() + if _zmq_version_info < min_version_info: + min_version = ".".join(str(v) for v in min_version_info) + raise ZMQVersionError(min_version, msg) + + +__all__ = [ + "DraftFDWarning", + "ZMQBaseError", + "ZMQBindError", + "ZMQError", + "NotDone", + "ContextTerminated", + "InterruptedSystemCall", + "Again", + "ZMQVersionError", +] diff --git a/venv/lib/python3.10/site-packages/zmq/eventloop/__init__.py b/venv/lib/python3.10/site-packages/zmq/eventloop/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a99e143ccf3035db55cb5a34caa13e98ba793e9a --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/eventloop/__init__.py @@ -0,0 +1,5 @@ +"""Tornado eventloop integration for pyzmq""" + +from tornado.ioloop import IOLoop + +__all__ = ['IOLoop'] diff --git a/venv/lib/python3.10/site-packages/zmq/eventloop/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/eventloop/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b7a5adb37c1f8654b2ce181d2e7ed311eba5ac8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/eventloop/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/eventloop/__pycache__/_deprecated.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/eventloop/__pycache__/_deprecated.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0b74b4fb91d5947b2b7485f6c378fe0b429e28c Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/eventloop/__pycache__/_deprecated.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/eventloop/__pycache__/future.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/eventloop/__pycache__/future.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0eafaaae5dca1960b75d2b01078d47a55c9ea5f Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/eventloop/__pycache__/future.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/eventloop/__pycache__/ioloop.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/eventloop/__pycache__/ioloop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50892f4eaf9c912dc9866803567a75aa2b9f3991 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/eventloop/__pycache__/ioloop.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/eventloop/__pycache__/zmqstream.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/eventloop/__pycache__/zmqstream.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5efb48b9ea9a0efb4f4cf47ee0d57f8444700b04 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/eventloop/__pycache__/zmqstream.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/eventloop/_deprecated.py b/venv/lib/python3.10/site-packages/zmq/eventloop/_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..06bce13c199bcdc58dc611f661dc348b71e272cf --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/eventloop/_deprecated.py @@ -0,0 +1,212 @@ +"""tornado IOLoop API with zmq compatibility + +If you have tornado ≥ 3.0, this is a subclass of tornado's IOLoop, +otherwise we ship a minimal subset of tornado in zmq.eventloop.minitornado. + +The minimal shipped version of tornado's IOLoop does not include +support for concurrent futures - this will only be available if you +have tornado ≥ 3.0. +""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import time +import warnings +from typing import Tuple + +from zmq import ETERM, POLLERR, POLLIN, POLLOUT, Poller, ZMQError + +tornado_version: Tuple = () +try: + import tornado + + tornado_version = tornado.version_info +except (ImportError, AttributeError): + pass + +from .minitornado.ioloop import PeriodicCallback, PollIOLoop +from .minitornado.log import gen_log + + +class DelayedCallback(PeriodicCallback): + """Schedules the given callback to be called once. + + The callback is called once, after callback_time milliseconds. + + `start` must be called after the DelayedCallback is created. + + The timeout is calculated from when `start` is called. + """ + + def __init__(self, callback, callback_time, io_loop=None): + # PeriodicCallback require callback_time to be positive + warnings.warn( + """DelayedCallback is deprecated. + Use loop.add_timeout instead.""", + DeprecationWarning, + ) + callback_time = max(callback_time, 1e-3) + super().__init__(callback, callback_time, io_loop) + + def start(self): + """Starts the timer.""" + self._running = True + self._firstrun = True + self._next_timeout = time.time() + self.callback_time / 1000.0 + self.io_loop.add_timeout(self._next_timeout, self._run) + + def _run(self): + if not self._running: + return + self._running = False + try: + self.callback() + except Exception: + gen_log.error("Error in delayed callback", exc_info=True) + + +class ZMQPoller: + """A poller that can be used in the tornado IOLoop. + + This simply wraps a regular zmq.Poller, scaling the timeout + by 1000, so that it is in seconds rather than milliseconds. + """ + + def __init__(self): + self._poller = Poller() + + @staticmethod + def _map_events(events): + """translate IOLoop.READ/WRITE/ERROR event masks into zmq.POLLIN/OUT/ERR""" + z_events = 0 + if events & IOLoop.READ: + z_events |= POLLIN + if events & IOLoop.WRITE: + z_events |= POLLOUT + if events & IOLoop.ERROR: + z_events |= POLLERR + return z_events + + @staticmethod + def _remap_events(z_events): + """translate zmq.POLLIN/OUT/ERR event masks into IOLoop.READ/WRITE/ERROR""" + events = 0 + if z_events & POLLIN: + events |= IOLoop.READ + if z_events & POLLOUT: + events |= IOLoop.WRITE + if z_events & POLLERR: + events |= IOLoop.ERROR + return events + + def register(self, fd, events): + return self._poller.register(fd, self._map_events(events)) + + def modify(self, fd, events): + return self._poller.modify(fd, self._map_events(events)) + + def unregister(self, fd): + return self._poller.unregister(fd) + + def poll(self, timeout): + """poll in seconds rather than milliseconds. + + Event masks will be IOLoop.READ/WRITE/ERROR + """ + z_events = self._poller.poll(1000 * timeout) + return [(fd, self._remap_events(evt)) for (fd, evt) in z_events] + + def close(self): + pass + + +class ZMQIOLoop(PollIOLoop): + """ZMQ subclass of tornado's IOLoop + + Minor modifications, so that .current/.instance return self + """ + + _zmq_impl = ZMQPoller + + def initialize(self, impl=None, **kwargs): + impl = self._zmq_impl() if impl is None else impl + super().initialize(impl=impl, **kwargs) + + @classmethod + def instance(cls, *args, **kwargs): + """Returns a global `IOLoop` instance. + + Most applications have a single, global `IOLoop` running on the + main thread. Use this method to get this instance from + another thread. To get the current thread's `IOLoop`, use `current()`. + """ + # install ZMQIOLoop as the active IOLoop implementation + # when using tornado 3 + if tornado_version >= (3,): + PollIOLoop.configure(cls) + loop = PollIOLoop.instance(*args, **kwargs) + if not isinstance(loop, cls): + warnings.warn( + f"IOLoop.current expected instance of {cls!r}, got {loop!r}", + RuntimeWarning, + stacklevel=2, + ) + return loop + + @classmethod + def current(cls, *args, **kwargs): + """Returns the current thread’s IOLoop.""" + # install ZMQIOLoop as the active IOLoop implementation + # when using tornado 3 + if tornado_version >= (3,): + PollIOLoop.configure(cls) + loop = PollIOLoop.current(*args, **kwargs) + if not isinstance(loop, cls): + warnings.warn( + f"IOLoop.current expected instance of {cls!r}, got {loop!r}", + RuntimeWarning, + stacklevel=2, + ) + return loop + + def start(self): + try: + super().start() + except ZMQError as e: + if e.errno == ETERM: + # quietly return on ETERM + pass + else: + raise + + +# public API name +IOLoop = ZMQIOLoop + + +def install(): + """set the tornado IOLoop instance with the pyzmq IOLoop. + + After calling this function, tornado's IOLoop.instance() and pyzmq's + IOLoop.instance() will return the same object. + + An assertion error will be raised if tornado's IOLoop has been initialized + prior to calling this function. + """ + from tornado import ioloop + + # check if tornado's IOLoop is already initialized to something other + # than the pyzmq IOLoop instance: + assert ( + not ioloop.IOLoop.initialized() + ) or ioloop.IOLoop.instance() is IOLoop.instance(), ( + "tornado IOLoop already initialized" + ) + + if tornado_version >= (3,): + # tornado 3 has an official API for registering new defaults, yay! + ioloop.IOLoop.configure(ZMQIOLoop) + else: + # we have to set the global instance explicitly + ioloop.IOLoop._instance = IOLoop.instance() diff --git a/venv/lib/python3.10/site-packages/zmq/eventloop/future.py b/venv/lib/python3.10/site-packages/zmq/eventloop/future.py new file mode 100644 index 0000000000000000000000000000000000000000..0f34f0ef93a8947e622b74e8ebedf79003727e0a --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/eventloop/future.py @@ -0,0 +1,104 @@ +"""Future-returning APIs for tornado coroutines. + +.. seealso:: + + :mod:`zmq.asyncio` + +""" + +# Copyright (c) PyZMQ Developers. +# Distributed under the terms of the Modified BSD License. +from __future__ import annotations + +import asyncio +import warnings +from typing import Any + +from tornado.concurrent import Future +from tornado.ioloop import IOLoop + +import zmq as _zmq +from zmq._future import _AsyncPoller, _AsyncSocket + + +class CancelledError(Exception): + pass + + +class _TornadoFuture(Future): + """Subclass Tornado Future, reinstating cancellation.""" + + def cancel(self): + if self.done(): + return False + self.set_exception(CancelledError()) + return True + + def cancelled(self): + return self.done() and isinstance(self.exception(), CancelledError) + + +class _CancellableTornadoTimeout: + def __init__(self, loop, timeout): + self.loop = loop + self.timeout = timeout + + def cancel(self): + self.loop.remove_timeout(self.timeout) + + +# mixin for tornado/asyncio compatibility + + +class _AsyncTornado: + _Future: type[asyncio.Future] = _TornadoFuture + _READ = IOLoop.READ + _WRITE = IOLoop.WRITE + + def _default_loop(self): + return IOLoop.current() + + def _call_later(self, delay, callback): + io_loop = self._get_loop() + timeout = io_loop.call_later(delay, callback) + return _CancellableTornadoTimeout(io_loop, timeout) + + +class Poller(_AsyncTornado, _AsyncPoller): + def _watch_raw_socket(self, loop, socket, evt, f): + """Schedule callback for a raw socket""" + loop.add_handler(socket, lambda *args: f(), evt) + + def _unwatch_raw_sockets(self, loop, *sockets): + """Unschedule callback for a raw socket""" + for socket in sockets: + loop.remove_handler(socket) + + +class Socket(_AsyncTornado, _AsyncSocket): + _poller_class = Poller + + +Poller._socket_class = Socket + + +class Context(_zmq.Context[Socket]): + # avoid sharing instance with base Context class + _instance = None + + io_loop = None + + @staticmethod + def _socket_class(self, socket_type): + return Socket(self, socket_type) + + def __init__(self: Context, *args: Any, **kwargs: Any) -> None: + io_loop = kwargs.pop('io_loop', None) + if io_loop is not None: + warnings.warn( + f"{self.__class__.__name__}(io_loop) argument is deprecated in pyzmq 22.2." + " The currently active loop will always be used.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) # type: ignore diff --git a/venv/lib/python3.10/site-packages/zmq/eventloop/ioloop.py b/venv/lib/python3.10/site-packages/zmq/eventloop/ioloop.py new file mode 100644 index 0000000000000000000000000000000000000000..dccb92a14eba7190c8571c0ee880ab5542e31bb7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/eventloop/ioloop.py @@ -0,0 +1,37 @@ +"""tornado IOLoop API with zmq compatibility + +This module is deprecated in pyzmq 17. +To use zmq with tornado, +eventloop integration is no longer required +and tornado itself should be used. +""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import warnings + + +def _deprecated(): + warnings.warn( + "zmq.eventloop.ioloop is deprecated in pyzmq 17." + " pyzmq now works with default tornado and asyncio eventloops.", + DeprecationWarning, + stacklevel=3, + ) + + +_deprecated() + +from tornado.ioloop import * # noqa +from tornado.ioloop import IOLoop + +ZMQIOLoop = IOLoop + + +def install(): + """DEPRECATED + + pyzmq 17 no longer needs any special integration for tornado. + """ + _deprecated() diff --git a/venv/lib/python3.10/site-packages/zmq/eventloop/zmqstream.py b/venv/lib/python3.10/site-packages/zmq/eventloop/zmqstream.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b5d297b19f973d19271625a2508ec6f24ee858 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/eventloop/zmqstream.py @@ -0,0 +1,688 @@ +# Derived from iostream.py from tornado 1.0, Copyright 2009 Facebook +# Used under Apache License Version 2.0 +# +# Modifications are Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. +"""A utility class for event-based messaging on a zmq socket using tornado. + +.. seealso:: + + - :mod:`zmq.asyncio` + - :mod:`zmq.eventloop.future` +""" + +from __future__ import annotations + +import asyncio +import pickle +import warnings +from queue import Queue +from typing import Any, Awaitable, Callable, Literal, Sequence, cast, overload + +from tornado.ioloop import IOLoop +from tornado.log import gen_log + +import zmq +import zmq._future +from zmq import POLLIN, POLLOUT +from zmq.utils import jsonapi + + +class ZMQStream: + """A utility class to register callbacks when a zmq socket sends and receives + + For use with tornado IOLoop. + + There are three main methods + + Methods: + + * **on_recv(callback, copy=True):** + register a callback to be run every time the socket has something to receive + * **on_send(callback):** + register a callback to be run every time you call send + * **send_multipart(self, msg, flags=0, copy=False, callback=None):** + perform a send that will trigger the callback + if callback is passed, on_send is also called. + + There are also send_multipart(), send_json(), send_pyobj() + + Three other methods for deactivating the callbacks: + + * **stop_on_recv():** + turn off the recv callback + * **stop_on_send():** + turn off the send callback + + which simply call ``on_(None)``. + + The entire socket interface, excluding direct recv methods, is also + provided, primarily through direct-linking the methods. + e.g. + + >>> stream.bind is stream.socket.bind + True + + + .. versionadded:: 25 + + send/recv callbacks can be coroutines. + + .. versionchanged:: 25 + + ZMQStreams only support base zmq.Socket classes (this has always been true, but not enforced). + If ZMQStreams are created with e.g. async Socket subclasses, + a RuntimeWarning will be shown, + and the socket cast back to the default zmq.Socket + before connecting events. + + Previously, using async sockets (or any zmq.Socket subclass) would result in undefined behavior for the + arguments passed to callback functions. + Now, the callback functions reliably get the return value of the base `zmq.Socket` send/recv_multipart methods + (the list of message frames). + """ + + socket: zmq.Socket + io_loop: IOLoop + poller: zmq.Poller + _send_queue: Queue + _recv_callback: Callable | None + _send_callback: Callable | None + _close_callback: Callable | None + _state: int = 0 + _flushed: bool = False + _recv_copy: bool = False + _fd: int + + def __init__(self, socket: zmq.Socket, io_loop: IOLoop | None = None): + if isinstance(socket, zmq._future._AsyncSocket): + warnings.warn( + f"""ZMQStream only supports the base zmq.Socket class. + + Use zmq.Socket(shadow=other_socket) + or `ctx.socket(zmq.{socket._type_name}, socket_class=zmq.Socket)` + to create a base zmq.Socket object, + no matter what other kind of socket your Context creates. + """, + RuntimeWarning, + stacklevel=2, + ) + # shadow back to base zmq.Socket, + # otherwise callbacks like `on_recv` will get the wrong types. + socket = zmq.Socket(shadow=socket) + self.socket = socket + + # IOLoop.current() is deprecated if called outside the event loop + # that means + self.io_loop = io_loop or IOLoop.current() + self.poller = zmq.Poller() + self._fd = cast(int, self.socket.FD) + + self._send_queue = Queue() + self._recv_callback = None + self._send_callback = None + self._close_callback = None + self._recv_copy = False + self._flushed = False + + self._state = 0 + self._init_io_state() + + # shortcircuit some socket methods + self.bind = self.socket.bind + self.bind_to_random_port = self.socket.bind_to_random_port + self.connect = self.socket.connect + self.setsockopt = self.socket.setsockopt + self.getsockopt = self.socket.getsockopt + self.setsockopt_string = self.socket.setsockopt_string + self.getsockopt_string = self.socket.getsockopt_string + self.setsockopt_unicode = self.socket.setsockopt_unicode + self.getsockopt_unicode = self.socket.getsockopt_unicode + + def stop_on_recv(self): + """Disable callback and automatic receiving.""" + return self.on_recv(None) + + def stop_on_send(self): + """Disable callback on sending.""" + return self.on_send(None) + + def stop_on_err(self): + """DEPRECATED, does nothing""" + gen_log.warn("on_err does nothing, and will be removed") + + def on_err(self, callback: Callable): + """DEPRECATED, does nothing""" + gen_log.warn("on_err does nothing, and will be removed") + + @overload + def on_recv( + self, + callback: Callable[[list[bytes]], Any], + ) -> None: ... + + @overload + def on_recv( + self, + callback: Callable[[list[bytes]], Any], + copy: Literal[True], + ) -> None: ... + + @overload + def on_recv( + self, + callback: Callable[[list[zmq.Frame]], Any], + copy: Literal[False], + ) -> None: ... + + @overload + def on_recv( + self, + callback: Callable[[list[zmq.Frame]], Any] | Callable[[list[bytes]], Any], + copy: bool = ..., + ): ... + + def on_recv( + self, + callback: Callable[[list[zmq.Frame]], Any] | Callable[[list[bytes]], Any], + copy: bool = True, + ) -> None: + """Register a callback for when a message is ready to recv. + + There can be only one callback registered at a time, so each + call to `on_recv` replaces previously registered callbacks. + + on_recv(None) disables recv event polling. + + Use on_recv_stream(callback) instead, to register a callback that will receive + both this ZMQStream and the message, instead of just the message. + + Parameters + ---------- + + callback : callable + callback must take exactly one argument, which will be a + list, as returned by socket.recv_multipart() + if callback is None, recv callbacks are disabled. + copy : bool + copy is passed directly to recv, so if copy is False, + callback will receive Message objects. If copy is True, + then callback will receive bytes/str objects. + + Returns : None + """ + + self._check_closed() + assert callback is None or callable(callback) + self._recv_callback = callback + self._recv_copy = copy + if callback is None: + self._drop_io_state(zmq.POLLIN) + else: + self._add_io_state(zmq.POLLIN) + + @overload + def on_recv_stream( + self, + callback: Callable[[ZMQStream, list[bytes]], Any], + ) -> None: ... + + @overload + def on_recv_stream( + self, + callback: Callable[[ZMQStream, list[bytes]], Any], + copy: Literal[True], + ) -> None: ... + + @overload + def on_recv_stream( + self, + callback: Callable[[ZMQStream, list[zmq.Frame]], Any], + copy: Literal[False], + ) -> None: ... + + @overload + def on_recv_stream( + self, + callback: ( + Callable[[ZMQStream, list[zmq.Frame]], Any] + | Callable[[ZMQStream, list[bytes]], Any] + ), + copy: bool = ..., + ): ... + + def on_recv_stream( + self, + callback: ( + Callable[[ZMQStream, list[zmq.Frame]], Any] + | Callable[[ZMQStream, list[bytes]], Any] + ), + copy: bool = True, + ): + """Same as on_recv, but callback will get this stream as first argument + + callback must take exactly two arguments, as it will be called as:: + + callback(stream, msg) + + Useful when a single callback should be used with multiple streams. + """ + if callback is None: + self.stop_on_recv() + else: + + def stream_callback(msg): + return callback(self, msg) + + self.on_recv(stream_callback, copy=copy) + + def on_send( + self, callback: Callable[[Sequence[Any], zmq.MessageTracker | None], Any] + ): + """Register a callback to be called on each send + + There will be two arguments:: + + callback(msg, status) + + * `msg` will be the list of sendable objects that was just sent + * `status` will be the return result of socket.send_multipart(msg) - + MessageTracker or None. + + Non-copying sends return a MessageTracker object whose + `done` attribute will be True when the send is complete. + This allows users to track when an object is safe to write to + again. + + The second argument will always be None if copy=True + on the send. + + Use on_send_stream(callback) to register a callback that will be passed + this ZMQStream as the first argument, in addition to the other two. + + on_send(None) disables recv event polling. + + Parameters + ---------- + + callback : callable + callback must take exactly two arguments, which will be + the message being sent (always a list), + and the return result of socket.send_multipart(msg) - + MessageTracker or None. + + if callback is None, send callbacks are disabled. + """ + + self._check_closed() + assert callback is None or callable(callback) + self._send_callback = callback + + def on_send_stream( + self, + callback: Callable[[ZMQStream, Sequence[Any], zmq.MessageTracker | None], Any], + ): + """Same as on_send, but callback will get this stream as first argument + + Callback will be passed three arguments:: + + callback(stream, msg, status) + + Useful when a single callback should be used with multiple streams. + """ + if callback is None: + self.stop_on_send() + else: + self.on_send(lambda msg, status: callback(self, msg, status)) + + def send(self, msg, flags=0, copy=True, track=False, callback=None, **kwargs): + """Send a message, optionally also register a new callback for sends. + See zmq.socket.send for details. + """ + return self.send_multipart( + [msg], flags=flags, copy=copy, track=track, callback=callback, **kwargs + ) + + def send_multipart( + self, + msg: Sequence[Any], + flags: int = 0, + copy: bool = True, + track: bool = False, + callback: Callable | None = None, + **kwargs: Any, + ) -> None: + """Send a multipart message, optionally also register a new callback for sends. + See zmq.socket.send_multipart for details. + """ + kwargs.update(dict(flags=flags, copy=copy, track=track)) + self._send_queue.put((msg, kwargs)) + callback = callback or self._send_callback + if callback is not None: + self.on_send(callback) + else: + # noop callback + self.on_send(lambda *args: None) + self._add_io_state(zmq.POLLOUT) + + def send_string( + self, + u: str, + flags: int = 0, + encoding: str = 'utf-8', + callback: Callable | None = None, + **kwargs: Any, + ): + """Send a unicode message with an encoding. + See zmq.socket.send_unicode for details. + """ + if not isinstance(u, str): + raise TypeError("unicode/str objects only") + return self.send(u.encode(encoding), flags=flags, callback=callback, **kwargs) + + send_unicode = send_string + + def send_json( + self, + obj: Any, + flags: int = 0, + callback: Callable | None = None, + **kwargs: Any, + ): + """Send json-serialized version of an object. + See zmq.socket.send_json for details. + """ + msg = jsonapi.dumps(obj) + return self.send(msg, flags=flags, callback=callback, **kwargs) + + def send_pyobj( + self, + obj: Any, + flags: int = 0, + protocol: int = -1, + callback: Callable | None = None, + **kwargs: Any, + ): + """Send a Python object as a message using pickle to serialize. + + See zmq.socket.send_json for details. + """ + msg = pickle.dumps(obj, protocol) + return self.send(msg, flags, callback=callback, **kwargs) + + def _finish_flush(self): + """callback for unsetting _flushed flag.""" + self._flushed = False + + def flush(self, flag: int = zmq.POLLIN | zmq.POLLOUT, limit: int | None = None): + """Flush pending messages. + + This method safely handles all pending incoming and/or outgoing messages, + bypassing the inner loop, passing them to the registered callbacks. + + A limit can be specified, to prevent blocking under high load. + + flush will return the first time ANY of these conditions are met: + * No more events matching the flag are pending. + * the total number of events handled reaches the limit. + + Note that if ``flag|POLLIN != 0``, recv events will be flushed even if no callback + is registered, unlike normal IOLoop operation. This allows flush to be + used to remove *and ignore* incoming messages. + + Parameters + ---------- + flag : int + default=POLLIN|POLLOUT + 0MQ poll flags. + If flag|POLLIN, recv events will be flushed. + If flag|POLLOUT, send events will be flushed. + Both flags can be set at once, which is the default. + limit : None or int, optional + The maximum number of messages to send or receive. + Both send and recv count against this limit. + + Returns + ------- + int : + count of events handled (both send and recv) + """ + self._check_closed() + # unset self._flushed, so callbacks will execute, in case flush has + # already been called this iteration + already_flushed = self._flushed + self._flushed = False + # initialize counters + count = 0 + + def update_flag(): + """Update the poll flag, to prevent registering POLLOUT events + if we don't have pending sends.""" + return flag & zmq.POLLIN | (self.sending() and flag & zmq.POLLOUT) + + flag = update_flag() + if not flag: + # nothing to do + return 0 + self.poller.register(self.socket, flag) + events = self.poller.poll(0) + while events and (not limit or count < limit): + s, event = events[0] + if event & POLLIN: # receiving + self._handle_recv() + count += 1 + if self.socket is None: + # break if socket was closed during callback + break + if event & POLLOUT and self.sending(): + self._handle_send() + count += 1 + if self.socket is None: + # break if socket was closed during callback + break + + flag = update_flag() + if flag: + self.poller.register(self.socket, flag) + events = self.poller.poll(0) + else: + events = [] + if count: # only bypass loop if we actually flushed something + # skip send/recv callbacks this iteration + self._flushed = True + # reregister them at the end of the loop + if not already_flushed: # don't need to do it again + self.io_loop.add_callback(self._finish_flush) + elif already_flushed: + self._flushed = True + + # update ioloop poll state, which may have changed + self._rebuild_io_state() + return count + + def set_close_callback(self, callback: Callable | None): + """Call the given callback when the stream is closed.""" + self._close_callback = callback + + def close(self, linger: int | None = None) -> None: + """Close this stream.""" + if self.socket is not None: + if self.socket.closed: + # fallback on raw fd for closed sockets + # hopefully this happened promptly after close, + # otherwise somebody else may have the FD + warnings.warn( + f"Unregistering FD {self._fd} after closing socket. " + "This could result in unregistering handlers for the wrong socket. " + "Please use stream.close() instead of closing the socket directly.", + stacklevel=2, + ) + self.io_loop.remove_handler(self._fd) + else: + self.io_loop.remove_handler(self.socket) + self.socket.close(linger) + self.socket = None # type: ignore + if self._close_callback: + self._run_callback(self._close_callback) + + def receiving(self) -> bool: + """Returns True if we are currently receiving from the stream.""" + return self._recv_callback is not None + + def sending(self) -> bool: + """Returns True if we are currently sending to the stream.""" + return not self._send_queue.empty() + + def closed(self) -> bool: + if self.socket is None: + return True + if self.socket.closed: + # underlying socket has been closed, but not by us! + # trigger our cleanup + self.close() + return True + return False + + def _run_callback(self, callback, *args, **kwargs): + """Wrap running callbacks in try/except to allow us to + close our socket.""" + try: + f = callback(*args, **kwargs) + if isinstance(f, Awaitable): + f = asyncio.ensure_future(f) + else: + f = None + except Exception: + gen_log.error("Uncaught exception in ZMQStream callback", exc_info=True) + # Re-raise the exception so that IOLoop.handle_callback_exception + # can see it and log the error + raise + + if f is not None: + # handle async callbacks + def _log_error(f): + try: + f.result() + except Exception: + gen_log.error( + "Uncaught exception in ZMQStream callback", exc_info=True + ) + + f.add_done_callback(_log_error) + + def _handle_events(self, fd, events): + """This method is the actual handler for IOLoop, that gets called whenever + an event on my socket is posted. It dispatches to _handle_recv, etc.""" + if not self.socket: + gen_log.warning("Got events for closed stream %s", self) + return + try: + zmq_events = self.socket.EVENTS + except zmq.ContextTerminated: + gen_log.warning("Got events for stream %s after terminating context", self) + # trigger close check, this will unregister callbacks + self.closed() + return + except zmq.ZMQError as e: + # run close check + # shadow sockets may have been closed elsewhere, + # which should show up as ENOTSOCK here + if self.closed(): + gen_log.warning( + "Got events for stream %s attached to closed socket: %s", self, e + ) + else: + gen_log.error("Error getting events for %s: %s", self, e) + return + try: + # dispatch events: + if zmq_events & zmq.POLLIN and self.receiving(): + self._handle_recv() + if not self.socket: + return + if zmq_events & zmq.POLLOUT and self.sending(): + self._handle_send() + if not self.socket: + return + + # rebuild the poll state + self._rebuild_io_state() + except Exception: + gen_log.error("Uncaught exception in zmqstream callback", exc_info=True) + raise + + def _handle_recv(self): + """Handle a recv event.""" + if self._flushed: + return + try: + msg = self.socket.recv_multipart(zmq.NOBLOCK, copy=self._recv_copy) + except zmq.ZMQError as e: + if e.errno == zmq.EAGAIN: + # state changed since poll event + pass + else: + raise + else: + if self._recv_callback: + callback = self._recv_callback + self._run_callback(callback, msg) + + def _handle_send(self): + """Handle a send event.""" + if self._flushed: + return + if not self.sending(): + gen_log.error("Shouldn't have handled a send event") + return + + msg, kwargs = self._send_queue.get() + try: + status = self.socket.send_multipart(msg, **kwargs) + except zmq.ZMQError as e: + gen_log.error("SEND Error: %s", e) + status = e + if self._send_callback: + callback = self._send_callback + self._run_callback(callback, msg, status) + + def _check_closed(self): + if not self.socket: + raise OSError("Stream is closed") + + def _rebuild_io_state(self): + """rebuild io state based on self.sending() and receiving()""" + if self.socket is None: + return + state = 0 + if self.receiving(): + state |= zmq.POLLIN + if self.sending(): + state |= zmq.POLLOUT + + self._state = state + self._update_handler(state) + + def _add_io_state(self, state): + """Add io_state to poller.""" + self._state = self._state | state + self._update_handler(self._state) + + def _drop_io_state(self, state): + """Stop poller from watching an io_state.""" + self._state = self._state & (~state) + self._update_handler(self._state) + + def _update_handler(self, state): + """Update IOLoop handler with state.""" + if self.socket is None: + return + + if state & self.socket.events: + # events still exist that haven't been processed + # explicitly schedule handling to avoid missing events due to edge-triggered FDs + self.io_loop.add_callback(lambda: self._handle_events(self.socket, 0)) + + def _init_io_state(self): + """initialize the ioloop event handler""" + self.io_loop.add_handler(self.socket, self._handle_events, self.io_loop.READ) diff --git a/venv/lib/python3.10/site-packages/zmq/green/__init__.py b/venv/lib/python3.10/site-packages/zmq/green/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8543864b00d60f236c05463f62494a483c739871 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/green/__init__.py @@ -0,0 +1,48 @@ +# ----------------------------------------------------------------------------- +# Copyright (C) 2011-2012 Travis Cline +# +# This file is part of pyzmq +# It is adapted from upstream project zeromq_gevent under the New BSD License +# +# Distributed under the terms of the New BSD License. The full license is in +# the file LICENSE.BSD, distributed as part of this software. +# ----------------------------------------------------------------------------- + +"""zmq.green - gevent compatibility with zeromq. + +Usage +----- + +Instead of importing zmq directly, do so in the following manner: + +.. + + import zmq.green as zmq + + +Any calls that would have blocked the current thread will now only block the +current green thread. + +This compatibility is accomplished by ensuring the nonblocking flag is set +before any blocking operation and the ØMQ file descriptor is polled internally +to trigger needed events. +""" + +from __future__ import annotations + +from typing import List + +import zmq as _zmq +from zmq import * +from zmq.green.core import _Context, _Socket +from zmq.green.poll import _Poller + +Context = _Context # type: ignore +Socket = _Socket # type: ignore +Poller = _Poller # type: ignore + +from zmq.green.device import device # type: ignore + +__all__: list[str] = [] +# adding `__all__` to __init__.pyi gets mypy all confused +__all__.extend(_zmq.__all__) # type: ignore diff --git a/venv/lib/python3.10/site-packages/zmq/green/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/green/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33d0af40e2a3c42d91fec53bbd4b803acb97f355 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/green/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/green/__pycache__/core.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/green/__pycache__/core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99c6a62352ac462cef8c38db84dc6482bc9eee6a Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/green/__pycache__/core.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/green/__pycache__/device.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/green/__pycache__/device.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1953c92be7fe49bcec192cceaf1644ab221693d1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/green/__pycache__/device.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/green/__pycache__/poll.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/green/__pycache__/poll.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..387ef821b80b6355bc08ca94878afbf5afe5e2fc Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/green/__pycache__/poll.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/green/core.py b/venv/lib/python3.10/site-packages/zmq/green/core.py new file mode 100644 index 0000000000000000000000000000000000000000..ddfccc205a6500eaf3e81df77bd35f4af274fac5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/green/core.py @@ -0,0 +1,334 @@ +# ----------------------------------------------------------------------------- +# Copyright (C) 2011-2012 Travis Cline +# +# This file is part of pyzmq +# It is adapted from upstream project zeromq_gevent under the New BSD License +# +# Distributed under the terms of the New BSD License. The full license is in +# the file LICENSE.BSD, distributed as part of this software. +# ----------------------------------------------------------------------------- + +"""This module wraps the :class:`Socket` and :class:`Context` found in :mod:`pyzmq ` to be non blocking""" + +from __future__ import annotations + +import sys +import time +import warnings + +import gevent +from gevent.event import AsyncResult +from gevent.hub import get_hub + +import zmq +from zmq import Context as _original_Context +from zmq import Socket as _original_Socket + +from .poll import _Poller + +if hasattr(zmq, 'RCVTIMEO'): + TIMEOS: tuple = (zmq.RCVTIMEO, zmq.SNDTIMEO) +else: + TIMEOS = () + + +def _stop(evt): + """simple wrapper for stopping an Event, allowing for method rename in gevent 1.0""" + try: + evt.stop() + except AttributeError: + # gevent<1.0 compat + evt.cancel() + + +class _Socket(_original_Socket): + """Green version of :class:`zmq.Socket` + + The following methods are overridden: + + * send + * recv + + To ensure that the ``zmq.NOBLOCK`` flag is set and that sending or receiving + is deferred to the hub if a ``zmq.EAGAIN`` (retry) error is raised. + + The `__state_changed` method is triggered when the zmq.FD for the socket is + marked as readable and triggers the necessary read and write events (which + are waited for in the recv and send methods). + + Some double underscore prefixes are used to minimize pollution of + :class:`zmq.Socket`'s namespace. + """ + + __in_send_multipart = False + __in_recv_multipart = False + __writable = None + __readable = None + _state_event = None + _gevent_bug_timeout = 11.6 # timeout for not trusting gevent + _debug_gevent = False # turn on if you think gevent is missing events + _poller_class = _Poller + _repr_cls = "zmq.green.Socket" + + def __init__(self, *a, **kw): + super().__init__(*a, **kw) + self.__in_send_multipart = False + self.__in_recv_multipart = False + self.__setup_events() + + def __del__(self): + self.close() + + def close(self, linger=None): + super().close(linger) + self.__cleanup_events() + + def __cleanup_events(self): + # close the _state_event event, keeps the number of active file descriptors down + if getattr(self, '_state_event', None): + _stop(self._state_event) + self._state_event = None + # if the socket has entered a close state resume any waiting greenlets + self.__writable.set() + self.__readable.set() + + def __setup_events(self): + self.__readable = AsyncResult() + self.__writable = AsyncResult() + self.__readable.set() + self.__writable.set() + + try: + self._state_event = get_hub().loop.io( + self.getsockopt(zmq.FD), 1 + ) # read state watcher + self._state_event.start(self.__state_changed) + except AttributeError: + # for gevent<1.0 compatibility + from gevent.core import read_event + + self._state_event = read_event( + self.getsockopt(zmq.FD), self.__state_changed, persist=True + ) + + def __state_changed(self, event=None, _evtype=None): + if self.closed: + self.__cleanup_events() + return + try: + # avoid triggering __state_changed from inside __state_changed + events = super().getsockopt(zmq.EVENTS) + except zmq.ZMQError as exc: + self.__writable.set_exception(exc) + self.__readable.set_exception(exc) + else: + if events & zmq.POLLOUT: + self.__writable.set() + if events & zmq.POLLIN: + self.__readable.set() + + def _wait_write(self): + assert self.__writable.ready(), "Only one greenlet can be waiting on this event" + self.__writable = AsyncResult() + # timeout is because libzmq cannot be trusted to properly signal a new send event: + # this is effectively a maximum poll interval of 1s + tic = time.time() + dt = self._gevent_bug_timeout + if dt: + timeout = gevent.Timeout(seconds=dt) + else: + timeout = None + try: + if timeout: + timeout.start() + self.__writable.get(block=True) + except gevent.Timeout as t: + if t is not timeout: + raise + toc = time.time() + # gevent bug: get can raise timeout even on clean return + # don't display zmq bug warning for gevent bug (this is getting ridiculous) + if ( + self._debug_gevent + and timeout + and toc - tic > dt + and self.getsockopt(zmq.EVENTS) & zmq.POLLOUT + ): + print( + f"BUG: gevent may have missed a libzmq send event on {self.FD}!", + file=sys.stderr, + ) + finally: + if timeout: + timeout.close() + self.__writable.set() + + def _wait_read(self): + assert self.__readable.ready(), "Only one greenlet can be waiting on this event" + self.__readable = AsyncResult() + # timeout is because libzmq cannot always be trusted to play nice with libevent. + # I can only confirm that this actually happens for send, but lets be symmetrical + # with our dirty hacks. + # this is effectively a maximum poll interval of 1s + tic = time.time() + dt = self._gevent_bug_timeout + if dt: + timeout = gevent.Timeout(seconds=dt) + else: + timeout = None + try: + if timeout: + timeout.start() + self.__readable.get(block=True) + except gevent.Timeout as t: + if t is not timeout: + raise + toc = time.time() + # gevent bug: get can raise timeout even on clean return + # don't display zmq bug warning for gevent bug (this is getting ridiculous) + if ( + self._debug_gevent + and timeout + and toc - tic > dt + and self.getsockopt(zmq.EVENTS) & zmq.POLLIN + ): + print( + f"BUG: gevent may have missed a libzmq recv event on {self.FD}!", + file=sys.stderr, + ) + finally: + if timeout: + timeout.close() + self.__readable.set() + + def send(self, data, flags=0, copy=True, track=False, **kwargs): + """send, which will only block current greenlet + + state_changed always fires exactly once (success or fail) at the + end of this method. + """ + + # if we're given the NOBLOCK flag act as normal and let the EAGAIN get raised + if flags & zmq.NOBLOCK: + try: + msg = super().send(data, flags, copy, track, **kwargs) + finally: + if not self.__in_send_multipart: + self.__state_changed() + return msg + # ensure the zmq.NOBLOCK flag is part of flags + flags |= zmq.NOBLOCK + while True: # Attempt to complete this operation indefinitely, blocking the current greenlet + try: + # attempt the actual call + msg = super().send(data, flags, copy, track) + except zmq.ZMQError as e: + # if the raised ZMQError is not EAGAIN, reraise + if e.errno != zmq.EAGAIN: + if not self.__in_send_multipart: + self.__state_changed() + raise + else: + if not self.__in_send_multipart: + self.__state_changed() + return msg + # defer to the event loop until we're notified the socket is writable + self._wait_write() + + def recv(self, flags=0, copy=True, track=False): + """recv, which will only block current greenlet + + state_changed always fires exactly once (success or fail) at the + end of this method. + """ + if flags & zmq.NOBLOCK: + try: + msg = super().recv(flags, copy, track) + finally: + if not self.__in_recv_multipart: + self.__state_changed() + return msg + + flags |= zmq.NOBLOCK + while True: + try: + msg = super().recv(flags, copy, track) + except zmq.ZMQError as e: + if e.errno != zmq.EAGAIN: + if not self.__in_recv_multipart: + self.__state_changed() + raise + else: + if not self.__in_recv_multipart: + self.__state_changed() + return msg + self._wait_read() + + def recv_into(self, buffer, /, *, nbytes=0, flags=0): + """recv_into, which will only block current greenlet""" + if flags & zmq.DONTWAIT: + return super().recv_into(buffer, nbytes=nbytes, flags=flags) + flags |= zmq.DONTWAIT + while True: + try: + recvd = super().recv_into(buffer, nbytes=nbytes, flags=flags) + except zmq.ZMQError as e: + if e.errno != zmq.EAGAIN: + self.__state_changed() + raise + else: + self.__state_changed() + return recvd + self._wait_read() + + def send_multipart(self, *args, **kwargs): + """wrap send_multipart to prevent state_changed on each partial send""" + self.__in_send_multipart = True + try: + msg = super().send_multipart(*args, **kwargs) + finally: + self.__in_send_multipart = False + self.__state_changed() + return msg + + def recv_multipart(self, *args, **kwargs): + """wrap recv_multipart to prevent state_changed on each partial recv""" + self.__in_recv_multipart = True + try: + msg = super().recv_multipart(*args, **kwargs) + finally: + self.__in_recv_multipart = False + self.__state_changed() + return msg + + def get(self, opt): + """trigger state_changed on getsockopt(EVENTS)""" + if opt in TIMEOS: + warnings.warn( + "TIMEO socket options have no effect in zmq.green", UserWarning + ) + optval = super().get(opt) + if opt == zmq.EVENTS: + self.__state_changed() + return optval + + def set(self, opt, val): + """set socket option""" + if opt in TIMEOS: + warnings.warn( + "TIMEO socket options have no effect in zmq.green", UserWarning + ) + return super().set(opt, val) + + +class _Context(_original_Context[_Socket]): + """Replacement for :class:`zmq.Context` + + Ensures that the greened Socket above is used in calls to `socket`. + """ + + _socket_class = _Socket + _repr_cls = "zmq.green.Context" + + # avoid sharing instance with base Context class + _instance = None diff --git a/venv/lib/python3.10/site-packages/zmq/green/device.py b/venv/lib/python3.10/site-packages/zmq/green/device.py new file mode 100644 index 0000000000000000000000000000000000000000..f9beae39eff8f023997aa075afd2a1baf80ac196 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/green/device.py @@ -0,0 +1,34 @@ +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. +from __future__ import annotations + +import zmq +from zmq.green import Poller + + +def device(device_type, isocket, osocket): + """Start a zeromq device (gevent-compatible). + + Unlike the true zmq.device, this does not release the GIL. + + Parameters + ---------- + device_type : (QUEUE, FORWARDER, STREAMER) + The type of device to start (ignored). + isocket : Socket + The Socket instance for the incoming traffic. + osocket : Socket + The Socket instance for the outbound traffic. + """ + p = Poller() + if osocket == -1: + osocket = isocket + p.register(isocket, zmq.POLLIN) + p.register(osocket, zmq.POLLIN) + + while True: + events = dict(p.poll()) + if isocket in events: + osocket.send_multipart(isocket.recv_multipart()) + if osocket in events: + isocket.send_multipart(osocket.recv_multipart()) diff --git a/venv/lib/python3.10/site-packages/zmq/green/eventloop/__init__.py b/venv/lib/python3.10/site-packages/zmq/green/eventloop/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b0ef0272c4e93a6f7a9955e9ac16f9a6ddf148e2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/green/eventloop/__init__.py @@ -0,0 +1,3 @@ +from zmq.green.eventloop.ioloop import IOLoop + +__all__ = ['IOLoop'] diff --git a/venv/lib/python3.10/site-packages/zmq/green/eventloop/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/green/eventloop/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ceb2dc9c9e18fa333fd82be407012785e023a1e Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/green/eventloop/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/green/eventloop/__pycache__/ioloop.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/green/eventloop/__pycache__/ioloop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fe455b268de7852747a972c6a9fc719c4087de6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/green/eventloop/__pycache__/ioloop.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/green/eventloop/__pycache__/zmqstream.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/green/eventloop/__pycache__/zmqstream.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68c7e03eb8d69d80caf2a72e9a69e7fd1e6501a9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/green/eventloop/__pycache__/zmqstream.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/green/eventloop/ioloop.py b/venv/lib/python3.10/site-packages/zmq/green/eventloop/ioloop.py new file mode 100644 index 0000000000000000000000000000000000000000..50e9151469570311c2fbc6af9fbb8d04b2d594f4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/green/eventloop/ioloop.py @@ -0,0 +1 @@ +from zmq.eventloop.ioloop import * # noqa diff --git a/venv/lib/python3.10/site-packages/zmq/green/eventloop/zmqstream.py b/venv/lib/python3.10/site-packages/zmq/green/eventloop/zmqstream.py new file mode 100644 index 0000000000000000000000000000000000000000..c06c2ab50e1b7e4ef1501e78a7ac85f2fa43d6c3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/green/eventloop/zmqstream.py @@ -0,0 +1,11 @@ +from zmq.eventloop import zmqstream +from zmq.green.eventloop.ioloop import IOLoop + + +class ZMQStream(zmqstream.ZMQStream): + def __init__(self, socket, io_loop=None): + io_loop = io_loop or IOLoop.instance() + super().__init__(socket, io_loop=io_loop) + + +__all__ = ["ZMQStream"] diff --git a/venv/lib/python3.10/site-packages/zmq/green/poll.py b/venv/lib/python3.10/site-packages/zmq/green/poll.py new file mode 100644 index 0000000000000000000000000000000000000000..7aa1bedd461aac26c26978b29e6e92ec0242dbf0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/green/poll.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import gevent +from gevent import select + +import zmq +from zmq import Poller as _original_Poller + + +class _Poller(_original_Poller): + """Replacement for :class:`zmq.Poller` + + Ensures that the greened Poller below is used in calls to + :meth:`zmq.Poller.poll`. + """ + + _gevent_bug_timeout = 1.33 # minimum poll interval, for working around gevent bug + + def _get_descriptors(self): + """Returns three elements tuple with socket descriptors ready + for gevent.select.select + """ + rlist = [] + wlist = [] + xlist = [] + + for socket, flags in self.sockets: + if isinstance(socket, zmq.Socket): + rlist.append(socket.getsockopt(zmq.FD)) + continue + elif isinstance(socket, int): + fd = socket + elif hasattr(socket, 'fileno'): + try: + fd = int(socket.fileno()) + except Exception: + raise ValueError('fileno() must return an valid integer fd') + else: + raise TypeError( + 'Socket must be a 0MQ socket, an integer fd ' + f'or have a fileno() method: {socket!r}' + ) + + if flags & zmq.POLLIN: + rlist.append(fd) + if flags & zmq.POLLOUT: + wlist.append(fd) + if flags & zmq.POLLERR: + xlist.append(fd) + + return (rlist, wlist, xlist) + + def poll(self, timeout=-1): + """Overridden method to ensure that the green version of + Poller is used. + + Behaves the same as :meth:`zmq.core.Poller.poll` + """ + + if timeout is None: + timeout = -1 + + if timeout < 0: + timeout = -1 + + rlist = None + wlist = None + xlist = None + + if timeout > 0: + tout = gevent.Timeout.start_new(timeout / 1000.0) + else: + tout = None + + try: + # Loop until timeout or events available + rlist, wlist, xlist = self._get_descriptors() + while True: + events = super().poll(0) + if events or timeout == 0: + return events + + # wait for activity on sockets in a green way + # set a minimum poll frequency, + # because gevent < 1.0 cannot be trusted to catch edge-triggered FD events + _bug_timeout = gevent.Timeout.start_new(self._gevent_bug_timeout) + try: + select.select(rlist, wlist, xlist) + except gevent.Timeout as t: + if t is not _bug_timeout: + raise + finally: + _bug_timeout.cancel() + + except gevent.Timeout as t: + if t is not tout: + raise + return [] + finally: + if timeout > 0: + tout.cancel() diff --git a/venv/lib/python3.10/site-packages/zmq/log/__init__.py b/venv/lib/python3.10/site-packages/zmq/log/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/zmq/log/__main__.py b/venv/lib/python3.10/site-packages/zmq/log/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..98c6b97c47381d413fa861702a926e1d57d39a8a --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/log/__main__.py @@ -0,0 +1,135 @@ +"""pyzmq log watcher. + +Easily view log messages published by the PUBHandler in zmq.log.handlers + +Designed to be run as an executable module - try this to see options: + python -m zmq.log -h + +Subscribes to the '' (empty string) topic by default which means it will work +out-of-the-box with a PUBHandler object instantiated with default settings. +If you change the root topic with PUBHandler.setRootTopic() you must pass +the value to this script with the --topic argument. + +Note that the default formats for the PUBHandler object selectively include +the log level in the message. This creates redundancy in this script as it +always prints the topic of the message, which includes the log level. +Consider overriding the default formats with PUBHandler.setFormat() to +avoid this issue. + +""" + +# encoding: utf-8 + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import argparse +from datetime import datetime +from typing import Dict + +import zmq + +parser = argparse.ArgumentParser('ZMQ Log Watcher') +parser.add_argument('zmq_pub_url', type=str, help='URL to a ZMQ publisher socket.') +parser.add_argument( + '-t', + '--topic', + type=str, + default='', + help='Only receive messages that start with this topic.', +) +parser.add_argument( + '--timestamp', action='store_true', help='Append local time to the log messages.' +) +parser.add_argument( + '--separator', + type=str, + default=' | ', + help='String to print between topic and message.', +) +parser.add_argument( + '--dateformat', + type=str, + default='%Y-%d-%m %H:%M', + help='Set alternative date format for use with --timestamp.', +) +parser.add_argument( + '--align', + action='store_true', + default=False, + help='Try to align messages by the width of their topics.', +) +parser.add_argument( + '--color', + action='store_true', + default=False, + help='Color the output based on the error level. Requires the colorama module.', +) +args = parser.parse_args() + + +if args.color: + import colorama + + colorama.init() + colors = { + 'DEBUG': colorama.Fore.LIGHTCYAN_EX, + 'INFO': colorama.Fore.LIGHTWHITE_EX, + 'WARNING': colorama.Fore.YELLOW, + 'ERROR': colorama.Fore.LIGHTRED_EX, + 'CRITICAL': colorama.Fore.LIGHTRED_EX, + '__RESET__': colorama.Fore.RESET, + } +else: + colors = {} + + +ctx = zmq.Context() +sub = ctx.socket(zmq.SUB) +sub.subscribe(args.topic.encode("utf8")) +sub.connect(args.zmq_pub_url) + +topic_widths: Dict[int, int] = {} + +while True: + try: + if sub.poll(10, zmq.POLLIN): + topic, msg = sub.recv_multipart() + topics = topic.decode('utf8').strip().split('.') + + if args.align: + topics.extend(' ' for extra in range(len(topics), len(topic_widths))) + aligned_parts = [] + for key, part in enumerate(topics): + topic_widths[key] = max(len(part), topic_widths.get(key, 0)) + fmt = ''.join(('{:<', str(topic_widths[key]), '}')) + aligned_parts.append(fmt.format(part)) + + if len(topics) == 1: + level = topics[0] + else: + level = topics[1] + + fields = { + 'msg': msg.decode('utf8').strip(), + 'ts': ( + datetime.now().strftime(args.dateformat) + ' ' + if args.timestamp + else '' + ), + 'aligned': ( + '.'.join(aligned_parts) + if args.align + else topic.decode('utf8').strip() + ), + 'color': colors.get(level, ''), + 'color_rst': colors.get('__RESET__', ''), + 'sep': args.separator, + } + print('{ts}{color}{aligned}{sep}{msg}{color_rst}'.format(**fields)) + except KeyboardInterrupt: + break + +sub.disconnect(args.zmq_pub_url) +if args.color: + print(colorama.Fore.RESET) diff --git a/venv/lib/python3.10/site-packages/zmq/log/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/log/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cd853411b5c4b6efa344674c2f1adc991cc8a6e Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/log/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/log/__pycache__/__main__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/log/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99b95bed9307effebf881c6d1e42af312abed386 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/log/__pycache__/__main__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/log/__pycache__/handlers.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/log/__pycache__/handlers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47715a63bd6ae473d22a4552aa33aa490c56c649 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/log/__pycache__/handlers.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/log/handlers.py b/venv/lib/python3.10/site-packages/zmq/log/handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..8138d2eed96c676261688f74ba9fe91dbc29d9c0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/log/handlers.py @@ -0,0 +1,232 @@ +"""pyzmq logging handlers. + +This mainly defines the PUBHandler object for publishing logging messages over +a zmq.PUB socket. + +The PUBHandler can be used with the regular logging module, as in:: + + >>> import logging + >>> handler = PUBHandler('tcp://127.0.0.1:12345') + >>> handler.root_topic = 'foo' + >>> logger = logging.getLogger('foobar') + >>> logger.setLevel(logging.DEBUG) + >>> logger.addHandler(handler) + +Or using ``dictConfig``, as in:: + + >>> from logging.config import dictConfig + >>> socket = Context.instance().socket(PUB) + >>> socket.connect('tcp://127.0.0.1:12345') + >>> dictConfig({ + >>> 'version': 1, + >>> 'handlers': { + >>> 'zmq': { + >>> 'class': 'zmq.log.handlers.PUBHandler', + >>> 'level': logging.DEBUG, + >>> 'root_topic': 'foo', + >>> 'interface_or_socket': socket + >>> } + >>> }, + >>> 'root': { + >>> 'level': 'DEBUG', + >>> 'handlers': ['zmq'], + >>> } + >>> }) + + +After this point, all messages logged by ``logger`` will be published on the +PUB socket. + +Code adapted from StarCluster: + + https://github.com/jtriley/StarCluster/blob/StarCluster-0.91/starcluster/logger.py +""" + +from __future__ import annotations + +import logging +from copy import copy + +import zmq + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + + +TOPIC_DELIM = "::" # delimiter for splitting topics on the receiving end. + + +class PUBHandler(logging.Handler): + """A basic logging handler that emits log messages through a PUB socket. + + Takes a PUB socket already bound to interfaces or an interface to bind to. + + Example:: + + sock = context.socket(zmq.PUB) + sock.bind('inproc://log') + handler = PUBHandler(sock) + + Or:: + + handler = PUBHandler('inproc://loc') + + These are equivalent. + + Log messages handled by this handler are broadcast with ZMQ topics + ``this.root_topic`` comes first, followed by the log level + (DEBUG,INFO,etc.), followed by any additional subtopics specified in the + message by: log.debug("subtopic.subsub::the real message") + """ + + ctx: zmq.Context + socket: zmq.Socket + + def __init__( + self, + interface_or_socket: str | zmq.Socket, + context: zmq.Context | None = None, + root_topic: str = '', + ) -> None: + logging.Handler.__init__(self) + self.root_topic = root_topic + self.formatters = { + logging.DEBUG: logging.Formatter( + "%(levelname)s %(filename)s:%(lineno)d - %(message)s\n" + ), + logging.INFO: logging.Formatter("%(message)s\n"), + logging.WARN: logging.Formatter( + "%(levelname)s %(filename)s:%(lineno)d - %(message)s\n" + ), + logging.ERROR: logging.Formatter( + "%(levelname)s %(filename)s:%(lineno)d - %(message)s - %(exc_info)s\n" + ), + logging.CRITICAL: logging.Formatter( + "%(levelname)s %(filename)s:%(lineno)d - %(message)s\n" + ), + } + if isinstance(interface_or_socket, zmq.Socket): + self.socket = interface_or_socket + self.ctx = self.socket.context + else: + self.ctx = context or zmq.Context() + self.socket = self.ctx.socket(zmq.PUB) + self.socket.bind(interface_or_socket) + + @property + def root_topic(self) -> str: + return self._root_topic + + @root_topic.setter + def root_topic(self, value: str): + self.setRootTopic(value) + + def setRootTopic(self, root_topic: str): + """Set the root topic for this handler. + + This value is prepended to all messages published by this handler, and it + defaults to the empty string ''. When you subscribe to this socket, you must + set your subscription to an empty string, or to at least the first letter of + the binary representation of this string to ensure you receive any messages + from this handler. + + If you use the default empty string root topic, messages will begin with + the binary representation of the log level string (INFO, WARN, etc.). + Note that ZMQ SUB sockets can have multiple subscriptions. + """ + if isinstance(root_topic, bytes): + root_topic = root_topic.decode("utf8") + self._root_topic = root_topic + + def setFormatter(self, fmt, level=logging.NOTSET): + """Set the Formatter for this handler. + + If no level is provided, the same format is used for all levels. This + will overwrite all selective formatters set in the object constructor. + """ + if level == logging.NOTSET: + for fmt_level in self.formatters.keys(): + self.formatters[fmt_level] = fmt + else: + self.formatters[level] = fmt + + def format(self, record): + """Format a record.""" + return self.formatters[record.levelno].format(record) + + def emit(self, record): + """Emit a log message on my socket.""" + + # LogRecord.getMessage explicitly allows msg to be anything _castable_ to a str + try: + topic, msg = str(record.msg).split(TOPIC_DELIM, 1) + except ValueError: + topic = "" + else: + # copy to avoid mutating LogRecord in-place + record = copy(record) + record.msg = msg + + try: + bmsg = self.format(record).encode("utf8") + except Exception: + self.handleError(record) + return + + topic_list = [] + + if self.root_topic: + topic_list.append(self.root_topic) + + topic_list.append(record.levelname) + + if topic: + topic_list.append(topic) + + btopic = '.'.join(topic_list).encode("utf8", "replace") + + self.socket.send_multipart([btopic, bmsg]) + + +class TopicLogger(logging.Logger): + """A simple wrapper that takes an additional argument to log methods. + + All the regular methods exist, but instead of one msg argument, two + arguments: topic, msg are passed. + + That is:: + + logger.debug('msg') + + Would become:: + + logger.debug('topic.sub', 'msg') + """ + + def log(self, level, topic, msg, *args, **kwargs): + """Log 'msg % args' with level and topic. + + To pass exception information, use the keyword argument exc_info + with a True value:: + + logger.log(level, "zmq.fun", "We have a %s", + "mysterious problem", exc_info=1) + """ + logging.Logger.log(self, level, f'{topic}{TOPIC_DELIM}{msg}', *args, **kwargs) + + +# Generate the methods of TopicLogger, since they are just adding a +# topic prefix to a message. +for name in "debug warn warning error critical fatal".split(): + try: + meth = getattr(logging.Logger, name) + except AttributeError: + # some methods are missing, e.g. Logger.warn was removed from Python 3.13 + continue + setattr( + TopicLogger, + name, + lambda self, level, topic, msg, *args, **kwargs: meth( + self, level, topic + TOPIC_DELIM + msg, *args, **kwargs + ), + ) diff --git a/venv/lib/python3.10/site-packages/zmq/py.typed b/venv/lib/python3.10/site-packages/zmq/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/zmq/ssh/__init__.py b/venv/lib/python3.10/site-packages/zmq/ssh/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..57f09568223c48babf9c9d7745218f7e33290eaa --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/ssh/__init__.py @@ -0,0 +1 @@ +from zmq.ssh.tunnel import * diff --git a/venv/lib/python3.10/site-packages/zmq/ssh/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/ssh/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a3364684ab98113cf1dad327bc7d98fd6de029a Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/ssh/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/ssh/__pycache__/forward.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/ssh/__pycache__/forward.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96e2b0fd82d697b205ef1bfb47fc310aa6ff2622 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/ssh/__pycache__/forward.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/ssh/__pycache__/tunnel.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/ssh/__pycache__/tunnel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6deb7a92a4dfa82869aea64d1a9b8dd4eb32e356 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/ssh/__pycache__/tunnel.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/ssh/forward.py b/venv/lib/python3.10/site-packages/zmq/ssh/forward.py new file mode 100644 index 0000000000000000000000000000000000000000..074a98f23c43930a47f2aa6b59259a849df2d5e9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/ssh/forward.py @@ -0,0 +1,95 @@ +# +# This file is adapted from a paramiko demo, and thus licensed under LGPL 2.1. +# Original Copyright (C) 2003-2007 Robey Pointer +# Edits Copyright (C) 2010 The IPython Team +# +# Paramiko is free software; you can redistribute it and/or modify it under the +# terms of the GNU Lesser General Public License as published by the Free +# Software Foundation; either version 2.1 of the License, or (at your option) +# any later version. +# +# Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR +# A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +# details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with Paramiko; if not, see . + +""" +Sample script showing how to do local port forwarding over paramiko. + +This script connects to the requested SSH server and sets up local port +forwarding (the openssh -L option) from a local port through a tunneled +connection to a destination reachable from the SSH server machine. +""" + +import logging +import select +import socketserver + +logger = logging.getLogger('ssh') + + +class ForwardServer(socketserver.ThreadingTCPServer): + daemon_threads = True + allow_reuse_address = True + + +class Handler(socketserver.BaseRequestHandler): + def handle(self): + try: + chan = self.ssh_transport.open_channel( + 'direct-tcpip', + (self.chain_host, self.chain_port), + self.request.getpeername(), + ) + except Exception as e: + logger.debug( + 'Incoming request to %s:%d failed: %r', + self.chain_host, + self.chain_port, + e, + ) + return + if chan is None: + logger.debug( + 'Incoming request to %s:%d was rejected by the SSH server.', + self.chain_host, + self.chain_port, + ) + return + + logger.debug( + f'Connected! Tunnel open {self.request.getpeername()!r} -> {chan.getpeername()!r} -> {(self.chain_host, self.chain_port)!r}' + ) + while True: + r, w, x = select.select([self.request, chan], [], []) + if self.request in r: + data = self.request.recv(1024) + if len(data) == 0: + break + chan.send(data) + if chan in r: + data = chan.recv(1024) + if len(data) == 0: + break + self.request.send(data) + chan.close() + self.request.close() + logger.debug('Tunnel closed ') + + +def forward_tunnel(local_port, remote_host, remote_port, transport): + # this is a little convoluted, but lets me configure things for the Handler + # object. (SocketServer doesn't give Handlers any way to access the outer + # server normally.) + class SubHander(Handler): + chain_host = remote_host + chain_port = remote_port + ssh_transport = transport + + ForwardServer(('127.0.0.1', local_port), SubHander).serve_forever() + + +__all__ = ['forward_tunnel'] diff --git a/venv/lib/python3.10/site-packages/zmq/ssh/tunnel.py b/venv/lib/python3.10/site-packages/zmq/ssh/tunnel.py new file mode 100644 index 0000000000000000000000000000000000000000..0e9c88e8a1acd88ad3aca4495d9632591cb7d336 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/ssh/tunnel.py @@ -0,0 +1,430 @@ +"""Basic ssh tunnel utilities, and convenience functions for tunneling +zeromq connections. +""" + +# Copyright (C) 2010-2011 IPython Development Team +# Copyright (C) 2011- PyZMQ Developers +# +# Redistributed from IPython under the terms of the BSD License. + +import atexit +import os +import re +import signal +import socket +import sys +import warnings +from getpass import getpass, getuser +from multiprocessing import Process + +try: + with warnings.catch_warnings(): + warnings.simplefilter('ignore', DeprecationWarning) + import paramiko + + SSHException = paramiko.ssh_exception.SSHException +except ImportError: + paramiko = None # type: ignore + + class SSHException(Exception): # type: ignore + pass + +else: + from .forward import forward_tunnel + +try: + import pexpect +except ImportError: + pexpect = None + + +class MaxRetryExceeded(Exception): + pass + + +def select_random_ports(n): + """Select and return n random ports that are available.""" + ports = [] + sockets = [] + for i in range(n): + sock = socket.socket() + sock.bind(('', 0)) + ports.append(sock.getsockname()[1]) + sockets.append(sock) + for sock in sockets: + sock.close() + return ports + + +# ----------------------------------------------------------------------------- +# Check for passwordless login +# ----------------------------------------------------------------------------- +_password_pat = re.compile(rb'pass(word|phrase)', re.IGNORECASE) + + +def try_passwordless_ssh(server, keyfile, paramiko=None): + """Attempt to make an ssh connection without a password. + This is mainly used for requiring password input only once + when many tunnels may be connected to the same server. + + If paramiko is None, the default for the platform is chosen. + """ + if paramiko is None: + paramiko = sys.platform == 'win32' + if not paramiko: + f = _try_passwordless_openssh + else: + f = _try_passwordless_paramiko + return f(server, keyfile) + + +def _try_passwordless_openssh(server, keyfile): + """Try passwordless login with shell ssh command.""" + if pexpect is None: + raise ImportError("pexpect unavailable, use paramiko") + cmd = 'ssh -f ' + server + if keyfile: + cmd += ' -i ' + keyfile + cmd += ' exit' + + # pop SSH_ASKPASS from env + env = os.environ.copy() + env.pop('SSH_ASKPASS', None) + + ssh_newkey = 'Are you sure you want to continue connecting' + p = pexpect.spawn(cmd, env=env) + + MAX_RETRY = 10 + + for _ in range(MAX_RETRY): + try: + i = p.expect([ssh_newkey, _password_pat], timeout=0.1) + if i == 0: + raise SSHException( + 'The authenticity of the host can\'t be established.' + ) + except pexpect.TIMEOUT: + continue + except pexpect.EOF: + return True + else: + return False + + raise MaxRetryExceeded(f"Failed after {MAX_RETRY} attempts") + + +def _try_passwordless_paramiko(server, keyfile): + """Try passwordless login with paramiko.""" + if paramiko is None: + msg = "Paramiko unavailable, " + if sys.platform == 'win32': + msg += "Paramiko is required for ssh tunneled connections on Windows." + else: + msg += "use OpenSSH." + raise ImportError(msg) + username, server, port = _split_server(server) + client = paramiko.SSHClient() + known_hosts = os.path.expanduser("~/.ssh/known_hosts") + try: + client.load_host_keys(known_hosts) + except FileNotFoundError: + pass + + policy_name = os.environ.get("PYZMQ_PARAMIKO_HOST_KEY_POLICY", None) + if policy_name: + policy = getattr(paramiko, f"{policy_name}Policy") + client.set_missing_host_key_policy(policy()) + try: + client.connect( + server, port, username=username, key_filename=keyfile, look_for_keys=True + ) + except paramiko.AuthenticationException: + return False + else: + client.close() + return True + + +def tunnel_connection( + socket, addr, server, keyfile=None, password=None, paramiko=None, timeout=60 +): + """Connect a socket to an address via an ssh tunnel. + + This is a wrapper for socket.connect(addr), when addr is not accessible + from the local machine. It simply creates an ssh tunnel using the remaining args, + and calls socket.connect('tcp://localhost:lport') where lport is the randomly + selected local port of the tunnel. + + """ + new_url, tunnel = open_tunnel( + addr, + server, + keyfile=keyfile, + password=password, + paramiko=paramiko, + timeout=timeout, + ) + socket.connect(new_url) + return tunnel + + +def open_tunnel(addr, server, keyfile=None, password=None, paramiko=None, timeout=60): + """Open a tunneled connection from a 0MQ url. + + For use inside tunnel_connection. + + Returns + ------- + + (url, tunnel) : (str, object) + The 0MQ url that has been forwarded, and the tunnel object + """ + + lport = select_random_ports(1)[0] + transport, addr = addr.split('://') + ip, rport = addr.split(':') + rport = int(rport) + if paramiko is None: + paramiko = sys.platform == 'win32' + if paramiko: + tunnelf = paramiko_tunnel + else: + tunnelf = openssh_tunnel + + tunnel = tunnelf( + lport, + rport, + server, + remoteip=ip, + keyfile=keyfile, + password=password, + timeout=timeout, + ) + return f'tcp://127.0.0.1:{lport}', tunnel + + +def openssh_tunnel( + lport, rport, server, remoteip='127.0.0.1', keyfile=None, password=None, timeout=60 +): + """Create an ssh tunnel using command-line ssh that connects port lport + on this machine to localhost:rport on server. The tunnel + will automatically close when not in use, remaining open + for a minimum of timeout seconds for an initial connection. + + This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`, + as seen from `server`. + + keyfile and password may be specified, but ssh config is checked for defaults. + + Parameters + ---------- + + lport : int + local port for connecting to the tunnel from this machine. + rport : int + port on the remote machine to connect to. + server : str + The ssh server to connect to. The full ssh server string will be parsed. + user@server:port + remoteip : str [Default: 127.0.0.1] + The remote ip, specifying the destination of the tunnel. + Default is localhost, which means that the tunnel would redirect + localhost:lport on this machine to localhost:rport on the *server*. + + keyfile : str; path to private key file + This specifies a key to be used in ssh login, default None. + Regular default ssh keys will be used without specifying this argument. + password : str; + Your ssh password to the ssh server. Note that if this is left None, + you will be prompted for it if passwordless key based login is unavailable. + timeout : int [default: 60] + The time (in seconds) after which no activity will result in the tunnel + closing. This prevents orphaned tunnels from running forever. + """ + if pexpect is None: + raise ImportError("pexpect unavailable, use paramiko_tunnel") + ssh = "ssh " + if keyfile: + ssh += "-i " + keyfile + + if ':' in server: + server, port = server.split(':') + ssh += f" -p {port}" + + cmd = f"{ssh} -O check {server}" + (output, exitstatus) = pexpect.run(cmd, withexitstatus=True) + if not exitstatus: + pid = int(output[output.find(b"(pid=") + 5 : output.find(b")")]) + cmd = f"{ssh} -O forward -L 127.0.0.1:{lport}:{remoteip}:{rport} {server}" + (output, exitstatus) = pexpect.run(cmd, withexitstatus=True) + if not exitstatus: + atexit.register(_stop_tunnel, cmd.replace("-O forward", "-O cancel", 1)) + return pid + cmd = f"{ssh} -f -S none -L 127.0.0.1:{lport}:{remoteip}:{rport} {server} sleep {timeout}" + + # pop SSH_ASKPASS from env + env = os.environ.copy() + env.pop('SSH_ASKPASS', None) + + ssh_newkey = 'Are you sure you want to continue connecting' + tunnel = pexpect.spawn(cmd, env=env) + failed = False + MAX_RETRY = 10 + for _ in range(MAX_RETRY): + try: + i = tunnel.expect([ssh_newkey, _password_pat], timeout=0.1) + if i == 0: + raise SSHException( + 'The authenticity of the host can\'t be established.' + ) + except pexpect.TIMEOUT: + continue + except pexpect.EOF: + if tunnel.exitstatus: + print(tunnel.exitstatus) + print(tunnel.before) + print(tunnel.after) + raise RuntimeError(f"tunnel '{cmd}' failed to start") + else: + return tunnel.pid + else: + if failed: + print("Password rejected, try again") + password = None + if password is None: + password = getpass(f"{server}'s password: ") + tunnel.sendline(password) + failed = True + raise MaxRetryExceeded(f"Failed after {MAX_RETRY} attempts") + + +def _stop_tunnel(cmd): + pexpect.run(cmd) + + +def _split_server(server): + if '@' in server: + username, server = server.split('@', 1) + else: + username = getuser() + if ':' in server: + server, port = server.split(':') + port = int(port) + else: + port = 22 + return username, server, port + + +def paramiko_tunnel( + lport, rport, server, remoteip='127.0.0.1', keyfile=None, password=None, timeout=60 +): + """launch a tunner with paramiko in a subprocess. This should only be used + when shell ssh is unavailable (e.g. Windows). + + This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`, + as seen from `server`. + + If you are familiar with ssh tunnels, this creates the tunnel: + + ssh server -L localhost:lport:remoteip:rport + + keyfile and password may be specified, but ssh config is checked for defaults. + + + Parameters + ---------- + + lport : int + local port for connecting to the tunnel from this machine. + rport : int + port on the remote machine to connect to. + server : str + The ssh server to connect to. The full ssh server string will be parsed. + user@server:port + remoteip : str [Default: 127.0.0.1] + The remote ip, specifying the destination of the tunnel. + Default is localhost, which means that the tunnel would redirect + localhost:lport on this machine to localhost:rport on the *server*. + + keyfile : str; path to private key file + This specifies a key to be used in ssh login, default None. + Regular default ssh keys will be used without specifying this argument. + password : str; + Your ssh password to the ssh server. Note that if this is left None, + you will be prompted for it if passwordless key based login is unavailable. + timeout : int [default: 60] + The time (in seconds) after which no activity will result in the tunnel + closing. This prevents orphaned tunnels from running forever. + + """ + if paramiko is None: + raise ImportError("Paramiko not available") + + if password is None: + if not _try_passwordless_paramiko(server, keyfile): + password = getpass(f"{server}'s password: ") + + p = Process( + target=_paramiko_tunnel, + args=(lport, rport, server, remoteip), + kwargs=dict(keyfile=keyfile, password=password), + ) + p.daemon = True + p.start() + return p + + +def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None): + """Function for actually starting a paramiko tunnel, to be passed + to multiprocessing.Process(target=this), and not called directly. + """ + username, server, port = _split_server(server) + client = paramiko.SSHClient() + client.load_system_host_keys() + client.set_missing_host_key_policy(paramiko.WarningPolicy()) + + try: + client.connect( + server, + port, + username=username, + key_filename=keyfile, + look_for_keys=True, + password=password, + ) + # except paramiko.AuthenticationException: + # if password is None: + # password = getpass("%s@%s's password: "%(username, server)) + # client.connect(server, port, username=username, password=password) + # else: + # raise + except Exception as e: + print(f'*** Failed to connect to {server}:{port}: {e!r}') + sys.exit(1) + + # Don't let SIGINT kill the tunnel subprocess + signal.signal(signal.SIGINT, signal.SIG_IGN) + + try: + forward_tunnel(lport, remoteip, rport, client.get_transport()) + except KeyboardInterrupt: + print('SIGINT: Port forwarding stopped cleanly') + sys.exit(0) + except Exception as e: + print(f"Port forwarding stopped uncleanly: {e}") + sys.exit(255) + + +if sys.platform == 'win32': + ssh_tunnel = paramiko_tunnel +else: + ssh_tunnel = openssh_tunnel + + +__all__ = [ + 'tunnel_connection', + 'ssh_tunnel', + 'openssh_tunnel', + 'paramiko_tunnel', + 'try_passwordless_ssh', +] diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/__init__.py b/venv/lib/python3.10/site-packages/zmq/sugar/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..88e755682c1096272830c01e37ef71d822ec1b05 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/sugar/__init__.py @@ -0,0 +1,39 @@ +"""pure-Python sugar wrappers for core 0MQ objects.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from __future__ import annotations + +from zmq import error +from zmq.backend import proxy +from zmq.constants import DeviceType +from zmq.sugar import context, frame, poll, socket, tracker, version + + +def device(device_type: DeviceType, frontend: socket.Socket, backend: socket.Socket): + """Deprecated alias for zmq.proxy + + .. deprecated:: libzmq-3.2 + .. deprecated:: 13.0 + """ + + return proxy(frontend, backend) + + +__all__ = ["device"] +for submod in (context, error, frame, poll, socket, tracker, version): + __all__.extend(submod.__all__) + +from zmq.error import * # noqa +from zmq.sugar.context import * # noqa +from zmq.sugar.frame import * # noqa +from zmq.sugar.poll import * # noqa +from zmq.sugar.socket import * # noqa + +# deprecated: +from zmq.sugar.stopwatch import Stopwatch # noqa +from zmq.sugar.tracker import * # noqa +from zmq.sugar.version import * # noqa + +__all__.append('Stopwatch') diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/__init__.pyi b/venv/lib/python3.10/site-packages/zmq/sugar/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..732f605017a063e9b66403921623a468f1ea0abe --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/sugar/__init__.pyi @@ -0,0 +1,10 @@ +from zmq.error import * + +from . import constants as constants +from .constants import * +from .context import * +from .frame import * +from .poll import * +from .socket import * +from .tracker import * +from .version import * diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9896dedd48059968f6312f8d18def75c5a590a3e Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/attrsettr.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/attrsettr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e695e3004c9da9ae5fefc99a2d62e651aaa82b07 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/attrsettr.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/context.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/context.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc6a613296f5367890220540ec7d17e06b041c5e Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/context.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/frame.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/frame.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d448a0fff80fcc157c39afb83bbf672c644598e2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/frame.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/poll.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/poll.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f58b6956c2a9f3fd1c59ad68980e3fa82803f189 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/poll.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/socket.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/socket.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..416b17740eec1584325c6f59719b0ea7cce66ca9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/socket.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/stopwatch.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/stopwatch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1e9fb7050ba86f619e0ae20dd1dae62fa8bd199 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/stopwatch.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/tracker.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/tracker.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39c61459214363cf4f79968f4ea7090ac58a6f05 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/tracker.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/version.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad63c9e0619ea47bfe986e60105a54c1e8a276a4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/sugar/__pycache__/version.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/attrsettr.py b/venv/lib/python3.10/site-packages/zmq/sugar/attrsettr.py new file mode 100644 index 0000000000000000000000000000000000000000..844fce606e53def45930d2e3a19873b4e8b4aeac --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/sugar/attrsettr.py @@ -0,0 +1,79 @@ +"""Mixin for mapping set/getattr to self.set/get""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. +from __future__ import annotations + +import errno +from typing import TypeVar, Union + +from .. import constants + +T = TypeVar("T") +OptValT = Union[str, bytes, int] + + +class AttributeSetter: + def __setattr__(self, key: str, value: OptValT) -> None: + """set zmq options by attribute""" + + if key in self.__dict__: + object.__setattr__(self, key, value) + return + # regular setattr only allowed for class-defined attributes + for cls in self.__class__.mro(): + if key in cls.__dict__ or key in getattr(cls, "__annotations__", {}): + object.__setattr__(self, key, value) + return + + upper_key = key.upper() + try: + opt = getattr(constants, upper_key) + except AttributeError: + raise AttributeError( + f"{self.__class__.__name__} has no such option: {upper_key}" + ) + else: + self._set_attr_opt(upper_key, opt, value) + + def _set_attr_opt(self, name: str, opt: int, value: OptValT) -> None: + """override if setattr should do something other than call self.set""" + self.set(opt, value) + + def __getattr__(self, key: str) -> OptValT: + """get zmq options by attribute""" + upper_key = key.upper() + try: + opt = getattr(constants, upper_key) + except AttributeError: + raise AttributeError( + f"{self.__class__.__name__} has no such option: {upper_key}" + ) from None + else: + from zmq import ZMQError + + try: + return self._get_attr_opt(upper_key, opt) + except ZMQError as e: + # EINVAL will be raised on access for write-only attributes. + # Turn that into an AttributeError + # necessary for mocking + if e.errno in {errno.EINVAL, errno.EFAULT}: + raise AttributeError(f"{key} attribute is write-only") + else: + raise + + def _get_attr_opt(self, name, opt) -> OptValT: + """override if getattr should do something other than call self.get""" + return self.get(opt) + + def get(self, opt: int) -> OptValT: + """Override in subclass""" + raise NotImplementedError("override in subclass") + + def set(self, opt: int, val: OptValT) -> None: + """Override in subclass""" + raise NotImplementedError("override in subclass") + + +__all__ = ['AttributeSetter'] diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/context.py b/venv/lib/python3.10/site-packages/zmq/sugar/context.py new file mode 100644 index 0000000000000000000000000000000000000000..21bc2cdda9d9319b03a6a0b45d791a6c5e2c3e8a --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/sugar/context.py @@ -0,0 +1,420 @@ +"""Python bindings for 0MQ.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from __future__ import annotations + +import atexit +import os +from threading import Lock +from typing import Any, Callable, Generic, TypeVar, overload +from warnings import warn +from weakref import WeakSet + +import zmq +from zmq._typing import TypeAlias +from zmq.backend import Context as ContextBase +from zmq.constants import ContextOption, Errno, SocketOption +from zmq.error import ZMQError +from zmq.utils.interop import cast_int_addr + +from .attrsettr import AttributeSetter, OptValT +from .socket import Socket, SyncSocket + +# notice when exiting, to avoid triggering term on exit +_exiting = False + + +def _notice_atexit() -> None: + global _exiting + _exiting = True + + +atexit.register(_notice_atexit) + +_ContextType = TypeVar('_ContextType', bound='Context') +_SocketType = TypeVar('_SocketType', bound='Socket', covariant=True) + + +class Context(ContextBase, AttributeSetter, Generic[_SocketType]): + """Create a zmq Context + + A zmq Context creates sockets via its ``ctx.socket`` method. + + .. versionchanged:: 24 + + When using a Context as a context manager (``with zmq.Context()``), + or deleting a context without closing it first, + ``ctx.destroy()`` is called, + closing any leftover sockets, + instead of `ctx.term()` which requires sockets to be closed first. + + This prevents hangs caused by `ctx.term()` if sockets are left open, + but means that unclean destruction of contexts + (with sockets left open) is not safe + if sockets are managed in other threads. + + .. versionadded:: 25 + + Contexts can now be shadowed by passing another Context. + This helps in creating an async copy of a sync context or vice versa:: + + ctx = zmq.Context(async_ctx) + + Which previously had to be:: + + ctx = zmq.Context.shadow(async_ctx.underlying) + """ + + sockopts: dict[int, Any] + _instance: Any = None + _instance_lock = Lock() + _instance_pid: int | None = None + _shadow = False + _shadow_obj = None + _warn_destroy_close = False + _sockets: WeakSet + # mypy doesn't like a default value here + _socket_class: type[_SocketType] = Socket # type: ignore + + @overload + def __init__(self: SyncContext, io_threads: int = 1): ... + + @overload + def __init__(self: SyncContext, io_threads: Context, /): ... + + @overload + def __init__(self: SyncContext, *, shadow: Context | int): ... + + def __init__( + self: SyncContext, + io_threads: int | Context = 1, + shadow: Context | int = 0, + ) -> None: + if isinstance(io_threads, Context): + # allow positional shadow `zmq.Context(zmq.asyncio.Context())` + # this s + shadow = io_threads + io_threads = 1 + + shadow_address: int = 0 + if shadow: + self._shadow = True + # hold a reference to the shadow object + self._shadow_obj = shadow + if not isinstance(shadow, int): + try: + shadow = shadow.underlying + except AttributeError: + pass + shadow_address = cast_int_addr(shadow) + else: + self._shadow = False + super().__init__(io_threads=io_threads, shadow=shadow_address) + self.sockopts = {} + self._sockets = WeakSet() + + def __del__(self) -> None: + """Deleting a Context without closing it destroys it and all sockets. + + .. versionchanged:: 24 + Switch from threadsafe `term()` which hangs in the event of open sockets + to less safe `destroy()` which + warns about any leftover sockets and closes them. + """ + + # Calling locals() here conceals issue #1167 on Windows CPython 3.5.4. + locals() + + if not self._shadow and not _exiting and not self.closed: + self._warn_destroy_close = True + if warn is not None and getattr(self, "_sockets", None) is not None: + # warn can be None during process teardown + warn( + f"Unclosed context {self}", + ResourceWarning, + stacklevel=2, + source=self, + ) + self.destroy() + + _repr_cls = "zmq.Context" + + def __repr__(self) -> str: + cls = self.__class__ + # look up _repr_cls on exact class, not inherited + _repr_cls = cls.__dict__.get("_repr_cls", None) + if _repr_cls is None: + _repr_cls = f"{cls.__module__}.{cls.__name__}" + + closed = ' closed' if self.closed else '' + if getattr(self, "_sockets", None): + n_sockets = len(self._sockets) + s = 's' if n_sockets > 1 else '' + sockets = f"{n_sockets} socket{s}" + else: + sockets = "" + return f"<{_repr_cls}({sockets}) at {hex(id(self))}{closed}>" + + def __enter__(self: _ContextType) -> _ContextType: + return self + + def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: + # warn about any leftover sockets before closing them + self._warn_destroy_close = True + self.destroy() + + def __copy__(self: _ContextType, memo: Any = None) -> _ContextType: + """Copying a Context creates a shadow copy""" + return self.__class__.shadow(self.underlying) + + __deepcopy__ = __copy__ + + @classmethod + def shadow(cls: type[_ContextType], address: int | zmq.Context) -> _ContextType: + """Shadow an existing libzmq context + + address is a zmq.Context or an integer (or FFI pointer) + representing the address of the libzmq context. + + .. versionadded:: 14.1 + + .. versionadded:: 25 + Support for shadowing `zmq.Context` objects, + instead of just integer addresses. + """ + return cls(shadow=address) + + @classmethod + def shadow_pyczmq(cls: type[_ContextType], ctx: Any) -> _ContextType: + """Shadow an existing pyczmq context + + ctx is the FFI `zctx_t *` pointer + + .. versionadded:: 14.1 + """ + from pyczmq import zctx # type: ignore + + from zmq.utils.interop import cast_int_addr + + underlying = zctx.underlying(ctx) + address = cast_int_addr(underlying) + return cls(shadow=address) + + # static method copied from tornado IOLoop.instance + @classmethod + def instance(cls: type[_ContextType], io_threads: int = 1) -> _ContextType: + """Returns a global Context instance. + + Most single-process applications have a single, global Context. + Use this method instead of passing around Context instances + throughout your code. + + A common pattern for classes that depend on Contexts is to use + a default argument to enable programs with multiple Contexts + but not require the argument for simpler applications:: + + class MyClass(object): + def __init__(self, context=None): + self.context = context or Context.instance() + + .. versionchanged:: 18.1 + + When called in a subprocess after forking, + a new global instance is created instead of inheriting + a Context that won't work from the parent process. + """ + if ( + cls._instance is None + or cls._instance_pid != os.getpid() + or cls._instance.closed + ): + with cls._instance_lock: + if ( + cls._instance is None + or cls._instance_pid != os.getpid() + or cls._instance.closed + ): + cls._instance = cls(io_threads=io_threads) + cls._instance_pid = os.getpid() + return cls._instance + + def term(self) -> None: + """Close or terminate the context. + + Context termination is performed in the following steps: + + - Any blocking operations currently in progress on sockets open within context shall + raise :class:`zmq.ContextTerminated`. + With the exception of socket.close(), any further operations on sockets open within this context + shall raise :class:`zmq.ContextTerminated`. + - After interrupting all blocking calls, term shall block until the following conditions are satisfied: + - All sockets open within context have been closed. + - For each socket within context, all messages sent on the socket have either been + physically transferred to a network peer, + or the socket's linger period set with the zmq.LINGER socket option has expired. + + For further details regarding socket linger behaviour refer to libzmq documentation for ZMQ_LINGER. + + This can be called to close the context by hand. If this is not called, + the context will automatically be closed when it is garbage collected, + in which case you may see a ResourceWarning about the unclosed context. + """ + super().term() + + # ------------------------------------------------------------------------- + # Hooks for ctxopt completion + # ------------------------------------------------------------------------- + + def __dir__(self) -> list[str]: + keys = dir(self.__class__) + keys.extend(ContextOption.__members__) + return keys + + # ------------------------------------------------------------------------- + # Creating Sockets + # ------------------------------------------------------------------------- + + def _add_socket(self, socket: Any) -> None: + """Add a weakref to a socket for Context.destroy / reference counting""" + self._sockets.add(socket) + + def _rm_socket(self, socket: Any) -> None: + """Remove a socket for Context.destroy / reference counting""" + # allow _sockets to be None in case of process teardown + if getattr(self, "_sockets", None) is not None: + self._sockets.discard(socket) + + def destroy(self, linger: int | None = None) -> None: + """Close all sockets associated with this context and then terminate + the context. + + .. warning:: + + destroy involves calling :meth:`Socket.close`, which is **NOT** threadsafe. + If there are active sockets in other threads, this must not be called. + + Parameters + ---------- + + linger : int, optional + If specified, set LINGER on sockets prior to closing them. + """ + if self.closed: + return + + sockets: list[_SocketType] = list(getattr(self, "_sockets", None) or []) + for s in sockets: + if s and not s.closed: + if self._warn_destroy_close and warn is not None: + # warn can be None during process teardown + warn( + f"Destroying context with unclosed socket {s}", + ResourceWarning, + stacklevel=3, + source=s, + ) + if linger is not None: + s.setsockopt(SocketOption.LINGER, linger) + s.close() + + self.term() + + def socket( + self: _ContextType, + socket_type: int, + socket_class: Callable[[_ContextType, int], _SocketType] | None = None, + **kwargs: Any, + ) -> _SocketType: + """Create a Socket associated with this Context. + + Parameters + ---------- + socket_type : int + The socket type, which can be any of the 0MQ socket types: + REQ, REP, PUB, SUB, PAIR, DEALER, ROUTER, PULL, PUSH, etc. + + socket_class: zmq.Socket + The socket class to instantiate, if different from the default for this Context. + e.g. for creating an asyncio socket attached to a default Context or vice versa. + + .. versionadded:: 25 + + kwargs: + will be passed to the __init__ method of the socket class. + """ + if self.closed: + raise ZMQError(Errno.ENOTSUP) + if socket_class is None: + socket_class = self._socket_class + s: _SocketType = ( + socket_class( # set PYTHONTRACEMALLOC=2 to get the calling frame + self, socket_type, **kwargs + ) + ) + for opt, value in self.sockopts.items(): + try: + s.setsockopt(opt, value) + except ZMQError: + # ignore ZMQErrors, which are likely for socket options + # that do not apply to a particular socket type, e.g. + # SUBSCRIBE for non-SUB sockets. + pass + self._add_socket(s) + return s + + def setsockopt(self, opt: int, value: Any) -> None: + """set default socket options for new sockets created by this Context + + .. versionadded:: 13.0 + """ + self.sockopts[opt] = value + + def getsockopt(self, opt: int) -> OptValT: + """get default socket options for new sockets created by this Context + + .. versionadded:: 13.0 + """ + return self.sockopts[opt] + + def _set_attr_opt(self, name: str, opt: int, value: OptValT) -> None: + """set default sockopts as attributes""" + if name in ContextOption.__members__: + return self.set(opt, value) + elif name in SocketOption.__members__: + self.sockopts[opt] = value + else: + raise AttributeError(f"No such context or socket option: {name}") + + def _get_attr_opt(self, name: str, opt: int) -> OptValT: + """get default sockopts as attributes""" + if name in ContextOption.__members__: + return self.get(opt) + else: + if opt not in self.sockopts: + raise AttributeError(name) + else: + return self.sockopts[opt] + + def __delattr__(self, key: str) -> None: + """delete default sockopts as attributes""" + if key in self.__dict__: + self.__dict__.pop(key) + return + key = key.upper() + try: + opt = getattr(SocketOption, key) + except AttributeError: + raise AttributeError(f"No such socket option: {key!r}") + else: + if opt not in self.sockopts: + raise AttributeError(key) + else: + del self.sockopts[opt] + + +SyncContext: TypeAlias = Context[SyncSocket] + + +__all__ = ['Context', 'SyncContext'] diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/frame.py b/venv/lib/python3.10/site-packages/zmq/sugar/frame.py new file mode 100644 index 0000000000000000000000000000000000000000..3239d357e1c67bc0bc41b3e01b479f3c893544f2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/sugar/frame.py @@ -0,0 +1,134 @@ +"""0MQ Frame pure Python methods.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import zmq +from zmq.backend import Frame as FrameBase + +from .attrsettr import AttributeSetter + + +def _draft(v, feature): + zmq.error._check_version(v, feature) + if not zmq.DRAFT_API: + raise RuntimeError( + f"libzmq and pyzmq must be built with draft support for {feature}" + ) + + +class Frame(FrameBase, AttributeSetter): + """ + A zmq message Frame class for non-copying send/recvs and access to message properties. + + A ``zmq.Frame`` wraps an underlying ``zmq_msg_t``. + + Message *properties* can be accessed by treating a Frame like a dictionary (``frame["User-Id"]``). + + .. versionadded:: 14.4, libzmq 4 + + Frames created by ``recv(copy=False)`` can be used to access message properties and attributes, + such as the CURVE User-Id. + + For example:: + + frames = socket.recv_multipart(copy=False) + user_id = frames[0]["User-Id"] + + This class is used if you want to do non-copying send and recvs. + When you pass a chunk of bytes to this class, e.g. ``Frame(buf)``, the + ref-count of `buf` is increased by two: once because the Frame saves `buf` as + an instance attribute and another because a ZMQ message is created that + points to the buffer of `buf`. This second ref-count increase makes sure + that `buf` lives until all messages that use it have been sent. + Once 0MQ sends all the messages and it doesn't need the buffer of ``buf``, + 0MQ will call ``Py_DECREF(s)``. + + Parameters + ---------- + + data : object, optional + any object that provides the buffer interface will be used to + construct the 0MQ message data. + track : bool + whether a MessageTracker_ should be created to track this object. + Tracking a message has a cost at creation, because it creates a threadsafe + Event object. + copy : bool + default: use copy_threshold + Whether to create a copy of the data to pass to libzmq + or share the memory with libzmq. + If unspecified, copy_threshold is used. + copy_threshold: int + default: :const:`zmq.COPY_THRESHOLD` + If copy is unspecified, messages smaller than this many bytes + will be copied and messages larger than this will be shared with libzmq. + """ + + def __getitem__(self, key): + # map Frame['User-Id'] to Frame.get('User-Id') + return self.get(key) + + def __repr__(self): + """Return the str form of the message.""" + nbytes = len(self) + msg_suffix = "" + if nbytes > 16: + msg_bytes = bytes(memoryview(self.buffer)[:12]) + if nbytes >= 1e9: + unit = "GB" + n = nbytes // 1e9 + elif nbytes >= 2**20: + unit = "MB" + n = nbytes // 1e6 + elif nbytes >= 1e3: + unit = "kB" + n = nbytes // 1e3 + else: + unit = "B" + n = nbytes + msg_suffix = f'...{n:.0f}{unit}' + else: + msg_bytes = self.bytes + + _module = self.__class__.__module__ + if _module == "zmq.sugar.frame": + _module = "zmq" + return f"<{_module}.{self.__class__.__name__}({msg_bytes!r}{msg_suffix})>" + + @property + def group(self): + """The RADIO-DISH group of the message. + + Requires libzmq >= 4.2 and pyzmq built with draft APIs enabled. + + .. versionadded:: 17 + """ + _draft((4, 2), "RADIO-DISH") + return self.get('group') + + @group.setter + def group(self, group): + _draft((4, 2), "RADIO-DISH") + self.set('group', group) + + @property + def routing_id(self): + """The CLIENT-SERVER routing id of the message. + + Requires libzmq >= 4.2 and pyzmq built with draft APIs enabled. + + .. versionadded:: 17 + """ + _draft((4, 2), "CLIENT-SERVER") + return self.get('routing_id') + + @routing_id.setter + def routing_id(self, routing_id): + _draft((4, 2), "CLIENT-SERVER") + self.set('routing_id', routing_id) + + +# keep deprecated alias +Message = Frame +__all__ = ['Frame', 'Message'] diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/poll.py b/venv/lib/python3.10/site-packages/zmq/sugar/poll.py new file mode 100644 index 0000000000000000000000000000000000000000..27baad46e75626d68a0691b6c89ba0fbd7c353e2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/sugar/poll.py @@ -0,0 +1,172 @@ +"""0MQ polling related functions and classes.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from __future__ import annotations + +from typing import Any + +from zmq.backend import zmq_poll +from zmq.constants import POLLERR, POLLIN, POLLOUT + +# ----------------------------------------------------------------------------- +# Polling related methods +# ----------------------------------------------------------------------------- + + +class Poller: + """A stateful poll interface that mirrors Python's built-in poll.""" + + sockets: list[tuple[Any, int]] + _map: dict + + def __init__(self) -> None: + self.sockets = [] + self._map = {} + + def __contains__(self, socket: Any) -> bool: + return socket in self._map + + def register(self, socket: Any, flags: int = POLLIN | POLLOUT): + """p.register(socket, flags=POLLIN|POLLOUT) + + Register a 0MQ socket or native fd for I/O monitoring. + + register(s,0) is equivalent to unregister(s). + + Parameters + ---------- + socket : zmq.Socket or native socket + A zmq.Socket or any Python object having a ``fileno()`` + method that returns a valid file descriptor. + flags : int + The events to watch for. Can be POLLIN, POLLOUT or POLLIN|POLLOUT. + If `flags=0`, socket will be unregistered. + """ + if flags: + if socket in self._map: + idx = self._map[socket] + self.sockets[idx] = (socket, flags) + else: + idx = len(self.sockets) + self.sockets.append((socket, flags)) + self._map[socket] = idx + elif socket in self._map: + # uregister sockets registered with no events + self.unregister(socket) + else: + # ignore new sockets with no events + pass + + def modify(self, socket, flags=POLLIN | POLLOUT): + """Modify the flags for an already registered 0MQ socket or native fd.""" + self.register(socket, flags) + + def unregister(self, socket: Any): + """Remove a 0MQ socket or native fd for I/O monitoring. + + Parameters + ---------- + socket : Socket + The socket instance to stop polling. + """ + idx = self._map.pop(socket) + self.sockets.pop(idx) + # shift indices after deletion + for socket, flags in self.sockets[idx:]: + self._map[socket] -= 1 + + def poll(self, timeout: int | None = None) -> list[tuple[Any, int]]: + """Poll the registered 0MQ or native fds for I/O. + + If there are currently events ready to be processed, this function will return immediately. + Otherwise, this function will return as soon the first event is available or after timeout + milliseconds have elapsed. + + Parameters + ---------- + timeout : int + The timeout in milliseconds. If None, no `timeout` (infinite). This + is in milliseconds to be compatible with ``select.poll()``. + + Returns + ------- + events : list + The list of events that are ready to be processed. + This is a list of tuples of the form ``(socket, event_mask)``, where the 0MQ Socket + or integer fd is the first element, and the poll event mask (POLLIN, POLLOUT) is the second. + It is common to call ``events = dict(poller.poll())``, + which turns the list of tuples into a mapping of ``socket : event_mask``. + """ + if timeout is None or timeout < 0: + timeout = -1 + elif isinstance(timeout, float): + timeout = int(timeout) + return zmq_poll(self.sockets, timeout=timeout) + + +def select( + rlist: list, wlist: list, xlist: list, timeout: float | None = None +) -> tuple[list, list, list]: + """select(rlist, wlist, xlist, timeout=None) -> (rlist, wlist, xlist) + + Return the result of poll as a lists of sockets ready for r/w/exception. + + This has the same interface as Python's built-in ``select.select()`` function. + + Parameters + ---------- + timeout : float, optional + The timeout in seconds. If None, no timeout (infinite). This is in seconds to be + compatible with ``select.select()``. + rlist : list + sockets/FDs to be polled for read events + wlist : list + sockets/FDs to be polled for write events + xlist : list + sockets/FDs to be polled for error events + + Returns + ------- + rlist: list + list of sockets or FDs that are readable + wlist: list + list of sockets or FDs that are writable + xlist: list + list of sockets or FDs that had error events (rare) + """ + if timeout is None: + timeout = -1 + # Convert from sec -> ms for zmq_poll. + # zmq_poll accepts 3.x style timeout in ms + timeout = int(timeout * 1000.0) + if timeout < 0: + timeout = -1 + sockets = [] + for s in set(rlist + wlist + xlist): + flags = 0 + if s in rlist: + flags |= POLLIN + if s in wlist: + flags |= POLLOUT + if s in xlist: + flags |= POLLERR + sockets.append((s, flags)) + return_sockets = zmq_poll(sockets, timeout) + rlist, wlist, xlist = [], [], [] + for s, flags in return_sockets: + if flags & POLLIN: + rlist.append(s) + if flags & POLLOUT: + wlist.append(s) + if flags & POLLERR: + xlist.append(s) + return rlist, wlist, xlist + + +# ----------------------------------------------------------------------------- +# Symbols to export +# ----------------------------------------------------------------------------- + +__all__ = ['Poller', 'select'] diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/socket.py b/venv/lib/python3.10/site-packages/zmq/sugar/socket.py new file mode 100644 index 0000000000000000000000000000000000000000..168fcaa116174f679a1d3a317b783690e1ac4967 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/sugar/socket.py @@ -0,0 +1,1125 @@ +"""0MQ Socket pure Python methods.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from __future__ import annotations + +import errno +import pickle +import random +import sys +from typing import ( + Any, + Callable, + Generic, + List, + Literal, + Sequence, + TypeVar, + Union, + cast, + overload, +) +from warnings import warn + +import zmq +from zmq._typing import TypeAlias +from zmq.backend import Socket as SocketBase +from zmq.error import ZMQBindError, ZMQError +from zmq.utils import jsonapi +from zmq.utils.interop import cast_int_addr + +from ..constants import SocketOption, SocketType, _OptType +from .attrsettr import AttributeSetter +from .poll import Poller + +try: + DEFAULT_PROTOCOL = pickle.DEFAULT_PROTOCOL +except AttributeError: + DEFAULT_PROTOCOL = pickle.HIGHEST_PROTOCOL + +_SocketType = TypeVar("_SocketType", bound="Socket") + +_JSONType: TypeAlias = "int | str | bool | list[_JSONType] | dict[str, _JSONType]" + + +class _SocketContext(Generic[_SocketType]): + """Context Manager for socket bind/unbind""" + + socket: _SocketType + kind: str + addr: str + + def __repr__(self): + return f"" + + def __init__( + self: _SocketContext[_SocketType], socket: _SocketType, kind: str, addr: str + ): + assert kind in {"bind", "connect"} + self.socket = socket + self.kind = kind + self.addr = addr + + def __enter__(self: _SocketContext[_SocketType]) -> _SocketType: + return self.socket + + def __exit__(self, *args): + if self.socket.closed: + return + if self.kind == "bind": + self.socket.unbind(self.addr) + elif self.kind == "connect": + self.socket.disconnect(self.addr) + + +SocketReturnType = TypeVar("SocketReturnType") + + +class Socket(SocketBase, AttributeSetter, Generic[SocketReturnType]): + """The ZMQ socket object + + To create a Socket, first create a Context:: + + ctx = zmq.Context.instance() + + then call ``ctx.socket(socket_type)``:: + + s = ctx.socket(zmq.ROUTER) + + .. versionadded:: 25 + + Sockets can now be shadowed by passing another Socket. + This helps in creating an async copy of a sync socket or vice versa:: + + s = zmq.Socket(async_socket) + + Which previously had to be:: + + s = zmq.Socket.shadow(async_socket.underlying) + """ + + _shadow = False + _shadow_obj = None + _monitor_socket = None + _type_name = 'UNKNOWN' + + @overload + def __init__( + self: Socket[bytes], + ctx_or_socket: zmq.Context, + socket_type: int, + *, + copy_threshold: int | None = None, + ): ... + + @overload + def __init__( + self: Socket[bytes], + *, + shadow: Socket | int, + copy_threshold: int | None = None, + ): ... + + @overload + def __init__( + self: Socket[bytes], + ctx_or_socket: Socket, + ): ... + + def __init__( + self: Socket[bytes], + ctx_or_socket: zmq.Context | Socket | None = None, + socket_type: int = 0, + *, + shadow: Socket | int = 0, + copy_threshold: int | None = None, + ): + shadow_context: zmq.Context | None = None + if isinstance(ctx_or_socket, zmq.Socket): + # positional Socket(other_socket) + shadow = ctx_or_socket + ctx_or_socket = None + + shadow_address: int = 0 + + if shadow: + self._shadow = True + # hold a reference to the shadow object + self._shadow_obj = shadow + if not isinstance(shadow, int): + if isinstance(shadow, zmq.Socket): + shadow_context = shadow.context + try: + shadow = cast(int, shadow.underlying) + except AttributeError: + pass + shadow_address = cast_int_addr(shadow) + else: + self._shadow = False + + super().__init__( + ctx_or_socket, + socket_type, + shadow=shadow_address, + copy_threshold=copy_threshold, + ) + if self._shadow_obj and shadow_context: + # keep self.context reference if shadowing a Socket object + self.context = shadow_context + + try: + socket_type = cast(int, self.get(zmq.TYPE)) + except Exception: + pass + else: + try: + self.__dict__["type"] = stype = SocketType(socket_type) + except ValueError: + self._type_name = str(socket_type) + else: + self._type_name = stype.name + + def __del__(self): + if not self._shadow and not self.closed: + if warn is not None: + # warn can be None during process teardown + warn( + f"Unclosed socket {self}", + ResourceWarning, + stacklevel=2, + source=self, + ) + self.close() + + _repr_cls = "zmq.Socket" + + def __repr__(self): + cls = self.__class__ + # look up _repr_cls on exact class, not inherited + _repr_cls = cls.__dict__.get("_repr_cls", None) + if _repr_cls is None: + _repr_cls = f"{cls.__module__}.{cls.__name__}" + + closed = ' closed' if self._closed else '' + + return f"<{_repr_cls}(zmq.{self._type_name}) at {hex(id(self))}{closed}>" + + # socket as context manager: + def __enter__(self: _SocketType) -> _SocketType: + """Sockets are context managers + + .. versionadded:: 14.4 + """ + return self + + def __exit__(self, *args, **kwargs): + self.close() + + # ------------------------------------------------------------------------- + # Socket creation + # ------------------------------------------------------------------------- + + def __copy__(self: _SocketType, memo=None) -> _SocketType: + """Copying a Socket creates a shadow copy""" + return self.__class__.shadow(self.underlying) + + __deepcopy__ = __copy__ + + @classmethod + def shadow(cls: type[_SocketType], address: int | zmq.Socket) -> _SocketType: + """Shadow an existing libzmq socket + + address is a zmq.Socket or an integer (or FFI pointer) + representing the address of the libzmq socket. + + .. versionadded:: 14.1 + + .. versionadded:: 25 + Support for shadowing `zmq.Socket` objects, + instead of just integer addresses. + """ + return cls(shadow=address) + + def close(self, linger=None) -> None: + """ + Close the socket. + + If linger is specified, LINGER sockopt will be set prior to closing. + + Note: closing a zmq Socket may not close the underlying sockets + if there are undelivered messages. + Only after all messages are delivered or discarded by reaching the socket's LINGER timeout + (default: forever) + will the underlying sockets be closed. + + This can be called to close the socket by hand. If this is not + called, the socket will automatically be closed when it is + garbage collected, + in which case you may see a ResourceWarning about the unclosed socket. + """ + if self.context: + self.context._rm_socket(self) + super().close(linger=linger) + + # ------------------------------------------------------------------------- + # Connect/Bind context managers + # ------------------------------------------------------------------------- + + def _connect_cm(self: _SocketType, addr: str) -> _SocketContext[_SocketType]: + """Context manager to disconnect on exit + + .. versionadded:: 20.0 + """ + return _SocketContext(self, 'connect', addr) + + def _bind_cm(self: _SocketType, addr: str) -> _SocketContext[_SocketType]: + """Context manager to unbind on exit + + .. versionadded:: 20.0 + """ + try: + # retrieve last_endpoint + # to support binding on random ports via + # `socket.bind('tcp://127.0.0.1:0')` + addr = cast(bytes, self.get(zmq.LAST_ENDPOINT)).decode("utf8") + except (AttributeError, ZMQError, UnicodeDecodeError): + pass + return _SocketContext(self, 'bind', addr) + + def bind(self: _SocketType, addr: str) -> _SocketContext[_SocketType]: + """s.bind(addr) + + Bind the socket to an address. + + This causes the socket to listen on a network port. Sockets on the + other side of this connection will use ``Socket.connect(addr)`` to + connect to this socket. + + Returns a context manager which will call unbind on exit. + + .. versionadded:: 20.0 + Can be used as a context manager. + + .. versionadded:: 26.0 + binding to port 0 can be used as a context manager + for binding to a random port. + The URL can be retrieved as `socket.last_endpoint`. + + Parameters + ---------- + addr : str + The address string. This has the form 'protocol://interface:port', + for example 'tcp://127.0.0.1:5555'. Protocols supported include + tcp, udp, pgm, epgm, inproc and ipc. If the address is unicode, it is + encoded to utf-8 first. + + """ + try: + super().bind(addr) + except ZMQError as e: + e.strerror += f" (addr={addr!r})" + raise + return self._bind_cm(addr) + + def connect(self: _SocketType, addr: str) -> _SocketContext[_SocketType]: + """s.connect(addr) + + Connect to a remote 0MQ socket. + + Returns a context manager which will call disconnect on exit. + + .. versionadded:: 20.0 + Can be used as a context manager. + + Parameters + ---------- + addr : str + The address string. This has the form 'protocol://interface:port', + for example 'tcp://127.0.0.1:5555'. Protocols supported are + tcp, udp, pgm, inproc and ipc. If the address is unicode, it is + encoded to utf-8 first. + + """ + try: + super().connect(addr) + except ZMQError as e: + e.strerror += f" (addr={addr!r})" + raise + return self._connect_cm(addr) + + # ------------------------------------------------------------------------- + # Deprecated aliases + # ------------------------------------------------------------------------- + + @property + def socket_type(self) -> int: + warn("Socket.socket_type is deprecated, use Socket.type", DeprecationWarning) + return cast(int, self.type) + + # ------------------------------------------------------------------------- + # Hooks for sockopt completion + # ------------------------------------------------------------------------- + + def __dir__(self): + keys = dir(self.__class__) + keys.extend(SocketOption.__members__) + return keys + + # ------------------------------------------------------------------------- + # Getting/Setting options + # ------------------------------------------------------------------------- + setsockopt = SocketBase.set + getsockopt = SocketBase.get + + def __setattr__(self, key, value): + """Override to allow setting zmq.[UN]SUBSCRIBE even though we have a subscribe method""" + if key in self.__dict__: + object.__setattr__(self, key, value) + return + _key = key.lower() + if _key in ('subscribe', 'unsubscribe'): + if isinstance(value, str): + value = value.encode('utf8') + if _key == 'subscribe': + self.set(zmq.SUBSCRIBE, value) + else: + self.set(zmq.UNSUBSCRIBE, value) + return + super().__setattr__(key, value) + + def fileno(self) -> int: + """Return edge-triggered file descriptor for this socket. + + This is a read-only edge-triggered file descriptor for both read and write events on this socket. + It is important that all available events be consumed when an event is detected, + otherwise the read event will not trigger again. + + .. versionadded:: 17.0 + """ + return self.FD + + def subscribe(self, topic: str | bytes) -> None: + """Subscribe to a topic + + Only for SUB sockets. + + .. versionadded:: 15.3 + """ + if isinstance(topic, str): + topic = topic.encode('utf8') + self.set(zmq.SUBSCRIBE, topic) + + def unsubscribe(self, topic: str | bytes) -> None: + """Unsubscribe from a topic + + Only for SUB sockets. + + .. versionadded:: 15.3 + """ + if isinstance(topic, str): + topic = topic.encode('utf8') + self.set(zmq.UNSUBSCRIBE, topic) + + def set_string(self, option: int, optval: str, encoding='utf-8') -> None: + """Set socket options with a unicode object. + + This is simply a wrapper for setsockopt to protect from encoding ambiguity. + + See the 0MQ documentation for details on specific options. + + Parameters + ---------- + option : int + The name of the option to set. Can be any of: SUBSCRIBE, + UNSUBSCRIBE, IDENTITY + optval : str + The value of the option to set. + encoding : str + The encoding to be used, default is utf8 + """ + if not isinstance(optval, str): + raise TypeError(f"strings only, not {type(optval)}: {optval!r}") + return self.set(option, optval.encode(encoding)) + + setsockopt_unicode = setsockopt_string = set_string + + def get_string(self, option: int, encoding='utf-8') -> str: + """Get the value of a socket option. + + See the 0MQ documentation for details on specific options. + + Parameters + ---------- + option : int + The option to retrieve. + + Returns + ------- + optval : str + The value of the option as a unicode string. + """ + if SocketOption(option)._opt_type != _OptType.bytes: + raise TypeError(f"option {option} will not return a string to be decoded") + return cast(bytes, self.get(option)).decode(encoding) + + getsockopt_unicode = getsockopt_string = get_string + + def bind_to_random_port( + self: _SocketType, + addr: str, + min_port: int = 49152, + max_port: int = 65536, + max_tries: int = 100, + ) -> int: + """Bind this socket to a random port in a range. + + If the port range is unspecified, the system will choose the port. + + Parameters + ---------- + addr : str + The address string without the port to pass to ``Socket.bind()``. + min_port : int, optional + The minimum port in the range of ports to try (inclusive). + max_port : int, optional + The maximum port in the range of ports to try (exclusive). + max_tries : int, optional + The maximum number of bind attempts to make. + + Returns + ------- + port : int + The port the socket was bound to. + + Raises + ------ + ZMQBindError + if `max_tries` reached before successful bind + """ + if min_port == 49152 and max_port == 65536: + # if LAST_ENDPOINT is supported, and min_port / max_port weren't specified, + # we can bind to port 0 and let the OS do the work + self.bind(f"{addr}:*") + url = cast(bytes, self.last_endpoint).decode('ascii', 'replace') + _, port_s = url.rsplit(':', 1) + return int(port_s) + + for i in range(max_tries): + try: + port = random.randrange(min_port, max_port) + self.bind(f'{addr}:{port}') + except ZMQError as exception: + en = exception.errno + if en == zmq.EADDRINUSE: + continue + elif sys.platform == 'win32' and en == errno.EACCES: + continue + else: + raise + else: + return port + raise ZMQBindError("Could not bind socket to random port.") + + def get_hwm(self) -> int: + """Get the High Water Mark. + + On libzmq ≥ 3, this gets SNDHWM if available, otherwise RCVHWM + """ + # return sndhwm, fallback on rcvhwm + try: + return cast(int, self.get(zmq.SNDHWM)) + except zmq.ZMQError: + pass + + return cast(int, self.get(zmq.RCVHWM)) + + def set_hwm(self, value: int) -> None: + """Set the High Water Mark. + + On libzmq ≥ 3, this sets both SNDHWM and RCVHWM + + + .. warning:: + + New values only take effect for subsequent socket + bind/connects. + """ + raised = None + try: + self.sndhwm = value + except Exception as e: + raised = e + try: + self.rcvhwm = value + except Exception as e: + raised = e + + if raised: + raise raised + + hwm = property( + get_hwm, + set_hwm, + None, + """Property for High Water Mark. + + Setting hwm sets both SNDHWM and RCVHWM as appropriate. + It gets SNDHWM if available, otherwise RCVHWM. + """, + ) + + # ------------------------------------------------------------------------- + # Sending and receiving messages + # ------------------------------------------------------------------------- + + @overload + def send( + self, + data: Any, + flags: int = ..., + copy: bool = ..., + *, + track: Literal[True], + routing_id: int | None = ..., + group: str | None = ..., + ) -> zmq.MessageTracker: ... + + @overload + def send( + self, + data: Any, + flags: int = ..., + copy: bool = ..., + *, + track: Literal[False], + routing_id: int | None = ..., + group: str | None = ..., + ) -> None: ... + + @overload + def send( + self, + data: Any, + flags: int = ..., + *, + copy: bool = ..., + routing_id: int | None = ..., + group: str | None = ..., + ) -> None: ... + + @overload + def send( + self, + data: Any, + flags: int = ..., + copy: bool = ..., + track: bool = ..., + routing_id: int | None = ..., + group: str | None = ..., + ) -> zmq.MessageTracker | None: ... + + def send( + self, + data: Any, + flags: int = 0, + copy: bool = True, + track: bool = False, + routing_id: int | None = None, + group: str | None = None, + ) -> zmq.MessageTracker | None: + """Send a single zmq message frame on this socket. + + This queues the message to be sent by the IO thread at a later time. + + With flags=NOBLOCK, this raises :class:`ZMQError` if the queue is full; + otherwise, this waits until space is available. + See :class:`Poller` for more general non-blocking I/O. + + Parameters + ---------- + data : bytes, Frame, memoryview + The content of the message. This can be any object that provides + the Python buffer API (i.e. `memoryview(data)` can be called). + flags : int + 0, NOBLOCK, SNDMORE, or NOBLOCK|SNDMORE. + copy : bool + Should the message be sent in a copying or non-copying manner. + track : bool + Should the message be tracked for notification that ZMQ has + finished with it? (ignored if copy=True) + routing_id : int + For use with SERVER sockets + group : str + For use with RADIO sockets + + Returns + ------- + None : if `copy` or not track + None if message was sent, raises an exception otherwise. + MessageTracker : if track and not copy + a MessageTracker object, whose `done` property will + be False until the send is completed. + + Raises + ------ + TypeError + If a unicode object is passed + ValueError + If `track=True`, but an untracked Frame is passed. + ZMQError + If the send does not succeed for any reason (including + if NOBLOCK is set and the outgoing queue is full). + + + .. versionchanged:: 17.0 + + DRAFT support for routing_id and group arguments. + """ + if routing_id is not None: + if not isinstance(data, zmq.Frame): + data = zmq.Frame( + data, + track=track, + copy=copy or None, + copy_threshold=self.copy_threshold, + ) + data.routing_id = routing_id + if group is not None: + if not isinstance(data, zmq.Frame): + data = zmq.Frame( + data, + track=track, + copy=copy or None, + copy_threshold=self.copy_threshold, + ) + data.group = group + return super().send(data, flags=flags, copy=copy, track=track) + + def send_multipart( + self, + msg_parts: Sequence, + flags: int = 0, + copy: bool = True, + track: bool = False, + **kwargs, + ): + """Send a sequence of buffers as a multipart message. + + The zmq.SNDMORE flag is added to all msg parts before the last. + + Parameters + ---------- + msg_parts : iterable + A sequence of objects to send as a multipart message. Each element + can be any sendable object (Frame, bytes, buffer-providers) + flags : int, optional + Any valid flags for :func:`Socket.send`. + SNDMORE is added automatically for frames before the last. + copy : bool, optional + Should the frame(s) be sent in a copying or non-copying manner. + If copy=False, frames smaller than self.copy_threshold bytes + will be copied anyway. + track : bool, optional + Should the frame(s) be tracked for notification that ZMQ has + finished with it (ignored if copy=True). + + Returns + ------- + None : if copy or not track + MessageTracker : if track and not copy + a MessageTracker object, whose `done` property will + be False until the last send is completed. + """ + # typecheck parts before sending: + for i, msg in enumerate(msg_parts): + if isinstance(msg, (zmq.Frame, bytes, memoryview)): + continue + try: + memoryview(msg) + except Exception: + rmsg = repr(msg) + if len(rmsg) > 32: + rmsg = rmsg[:32] + '...' + raise TypeError( + f"Frame {i} ({rmsg}) does not support the buffer interface." + ) + for msg in msg_parts[:-1]: + self.send(msg, zmq.SNDMORE | flags, copy=copy, track=track) + # Send the last part without the extra SNDMORE flag. + return self.send(msg_parts[-1], flags, copy=copy, track=track) + + @overload + def recv_multipart( + self, flags: int = ..., *, copy: Literal[True], track: bool = ... + ) -> list[bytes]: ... + + @overload + def recv_multipart( + self, flags: int = ..., *, copy: Literal[False], track: bool = ... + ) -> list[zmq.Frame]: ... + + @overload + def recv_multipart(self, flags: int = ..., *, track: bool = ...) -> list[bytes]: ... + + @overload + def recv_multipart( + self, flags: int = 0, copy: bool = True, track: bool = False + ) -> list[zmq.Frame] | list[bytes]: ... + + def recv_multipart( + self, flags: int = 0, copy: bool = True, track: bool = False + ) -> list[zmq.Frame] | list[bytes]: + """Receive a multipart message as a list of bytes or Frame objects + + Parameters + ---------- + flags : int, optional + Any valid flags for :func:`Socket.recv`. + copy : bool, optional + Should the message frame(s) be received in a copying or non-copying manner? + If False a Frame object is returned for each part, if True a copy of + the bytes is made for each frame. + track : bool, optional + Should the message frame(s) be tracked for notification that ZMQ has + finished with it? (ignored if copy=True) + + Returns + ------- + msg_parts : list + A list of frames in the multipart message; either Frames or bytes, + depending on `copy`. + + Raises + ------ + ZMQError + for any of the reasons :func:`~Socket.recv` might fail + """ + parts = [self.recv(flags, copy=copy, track=track)] + # have first part already, only loop while more to receive + while self.getsockopt(zmq.RCVMORE): + part = self.recv(flags, copy=copy, track=track) + parts.append(part) + # cast List[Union] to Union[List] + # how do we get mypy to recognize that return type is invariant on `copy`? + return cast(Union[List[zmq.Frame], List[bytes]], parts) + + def _deserialize( + self, + recvd: bytes, + load: Callable[[bytes], Any], + ) -> Any: + """Deserialize a received message + + Override in subclass (e.g. Futures) if recvd is not the raw bytes. + + The default implementation expects bytes and returns the deserialized message immediately. + + Parameters + ---------- + + load: callable + Callable that deserializes bytes + recvd: + The object returned by self.recv + + """ + return load(recvd) + + def send_serialized(self, msg, serialize, flags=0, copy=True, **kwargs): + """Send a message with a custom serialization function. + + .. versionadded:: 17 + + Parameters + ---------- + msg : The message to be sent. Can be any object serializable by `serialize`. + serialize : callable + The serialization function to use. + serialize(msg) should return an iterable of sendable message frames + (e.g. bytes objects), which will be passed to send_multipart. + flags : int, optional + Any valid flags for :func:`Socket.send`. + copy : bool, optional + Whether to copy the frames. + + """ + frames = serialize(msg) + return self.send_multipart(frames, flags=flags, copy=copy, **kwargs) + + def recv_serialized(self, deserialize, flags=0, copy=True): + """Receive a message with a custom deserialization function. + + .. versionadded:: 17 + + Parameters + ---------- + deserialize : callable + The deserialization function to use. + deserialize will be called with one argument: the list of frames + returned by recv_multipart() and can return any object. + flags : int, optional + Any valid flags for :func:`Socket.recv`. + copy : bool, optional + Whether to recv bytes or Frame objects. + + Returns + ------- + obj : object + The object returned by the deserialization function. + + Raises + ------ + ZMQError + for any of the reasons :func:`~Socket.recv` might fail + """ + frames = self.recv_multipart(flags=flags, copy=copy) + return self._deserialize(frames, deserialize) + + def send_string( + self, + u: str, + flags: int = 0, + copy: bool = True, + encoding: str = 'utf-8', + **kwargs, + ) -> zmq.Frame | None: + """Send a Python unicode string as a message with an encoding. + + 0MQ communicates with raw bytes, so you must encode/decode + text (str) around 0MQ. + + Parameters + ---------- + u : str + The unicode string to send. + flags : int, optional + Any valid flags for :func:`Socket.send`. + encoding : str + The encoding to be used + """ + if not isinstance(u, str): + raise TypeError("str objects only") + return self.send(u.encode(encoding), flags=flags, copy=copy, **kwargs) + + send_unicode = send_string + + def recv_string(self, flags: int = 0, encoding: str = 'utf-8') -> str: + """Receive a unicode string, as sent by send_string. + + Parameters + ---------- + flags : int + Any valid flags for :func:`Socket.recv`. + encoding : str + The encoding to be used + + Returns + ------- + s : str + The Python unicode string that arrives as encoded bytes. + + Raises + ------ + ZMQError + for any of the reasons :func:`Socket.recv` might fail + """ + msg = self.recv(flags=flags) + return self._deserialize(msg, lambda buf: buf.decode(encoding)) + + recv_unicode = recv_string + + def send_pyobj( + self, obj: Any, flags: int = 0, protocol: int = DEFAULT_PROTOCOL, **kwargs + ) -> zmq.Frame | None: + """ + Send a Python object as a message using pickle to serialize. + + .. warning:: + + Never deserialize an untrusted message with pickle, + which can involve arbitrary code execution. + Make sure to authenticate the sources of messages + before unpickling them, e.g. with transport-level security + (e.g. CURVE, ZAP, or IPC permissions) + or signed messages. + + Parameters + ---------- + obj : Python object + The Python object to send. + flags : int + Any valid flags for :func:`Socket.send`. + protocol : int + The pickle protocol number to use. The default is pickle.DEFAULT_PROTOCOL + where defined, and pickle.HIGHEST_PROTOCOL elsewhere. + """ + msg = pickle.dumps(obj, protocol) + return self.send(msg, flags=flags, **kwargs) + + def recv_pyobj(self, flags: int = 0) -> Any: + """ + Receive a Python object as a message using UNSAFE pickle to serialize. + + .. warning:: + + Never deserialize an untrusted message with pickle, + which can involve arbitrary code execution. + Make sure to authenticate the sources of messages + before unpickling them, e.g. with transport-level security + (such as CURVE or IPC permissions) + or authenticating messages themselves before deserializing. + + Parameters + ---------- + flags : int + Any valid flags for :func:`Socket.recv`. + + Returns + ------- + obj : Python object + The Python object that arrives as a message. + + Raises + ------ + ZMQError + for any of the reasons :func:`~Socket.recv` might fail + """ + msg = self.recv(flags) + return self._deserialize(msg, pickle.loads) + + def send_json(self, obj: Any, flags: int = 0, **kwargs) -> None: + """Send a Python object as a message using json to serialize. + + Keyword arguments are passed on to json.dumps + + Parameters + ---------- + obj : Python object + The Python object to send + flags : int + Any valid flags for :func:`Socket.send` + """ + send_kwargs = {} + for key in ('routing_id', 'group'): + if key in kwargs: + send_kwargs[key] = kwargs.pop(key) + msg = jsonapi.dumps(obj, **kwargs) + return self.send(msg, flags=flags, **send_kwargs) + + def recv_json(self, flags: int = 0, **kwargs) -> _JSONType: + """Receive a Python object as a message using json to serialize. + + Keyword arguments are passed on to json.loads + + Parameters + ---------- + flags : int + Any valid flags for :func:`Socket.recv`. + + Returns + ------- + obj : Python object + The Python object that arrives as a message. + + Raises + ------ + ZMQError + for any of the reasons :func:`~Socket.recv` might fail + """ + msg = self.recv(flags) + return self._deserialize(msg, lambda buf: jsonapi.loads(buf, **kwargs)) + + _poller_class = Poller + + def poll(self, timeout: int | None = None, flags: int = zmq.POLLIN) -> int: + """Poll the socket for events. + + See :class:`Poller` to wait for multiple sockets at once. + + Parameters + ---------- + timeout : int + The timeout (in milliseconds) to wait for an event. If unspecified + (or specified None), will wait forever for an event. + flags : int + default: POLLIN. + POLLIN, POLLOUT, or POLLIN|POLLOUT. The event flags to poll for. + + Returns + ------- + event_mask : int + The poll event mask (POLLIN, POLLOUT), + 0 if the timeout was reached without an event. + """ + + if self.closed: + raise ZMQError(zmq.ENOTSUP) + + p = self._poller_class() + p.register(self, flags) + evts = dict(p.poll(timeout)) + # return 0 if no events, otherwise return event bitfield + return evts.get(self, 0) + + def get_monitor_socket( + self: _SocketType, events: int | None = None, addr: str | None = None + ) -> _SocketType: + """Return a connected PAIR socket ready to receive the event notifications. + + .. versionadded:: libzmq-4.0 + .. versionadded:: 14.0 + + Parameters + ---------- + events : int + default: `zmq.EVENT_ALL` + The bitmask defining which events are wanted. + addr : str + The optional endpoint for the monitoring sockets. + + Returns + ------- + socket : zmq.Socket + The PAIR socket, connected and ready to receive messages. + """ + # safe-guard, method only available on libzmq >= 4 + if zmq.zmq_version_info() < (4,): + raise NotImplementedError( + f"get_monitor_socket requires libzmq >= 4, have {zmq.zmq_version()}" + ) + + # if already monitoring, return existing socket + if self._monitor_socket: + if self._monitor_socket.closed: + self._monitor_socket = None + else: + return self._monitor_socket + + if addr is None: + # create endpoint name from internal fd + addr = f"inproc://monitor.s-{self.FD}" + if events is None: + # use all events + events = zmq.EVENT_ALL + # attach monitoring socket + self.monitor(addr, events) + # create new PAIR socket and connect it + self._monitor_socket = self.context.socket(zmq.PAIR) + self._monitor_socket.connect(addr) + return self._monitor_socket + + def disable_monitor(self) -> None: + """Shutdown the PAIR socket (created using get_monitor_socket) + that is serving socket events. + + .. versionadded:: 14.4 + """ + self._monitor_socket = None + self.monitor(None, 0) + + +SyncSocket: TypeAlias = Socket[bytes] + +__all__ = ['Socket', 'SyncSocket'] diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/stopwatch.py b/venv/lib/python3.10/site-packages/zmq/sugar/stopwatch.py new file mode 100644 index 0000000000000000000000000000000000000000..2001e670a92761a5c3a10e40d93f39e2c21a3a10 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/sugar/stopwatch.py @@ -0,0 +1,36 @@ +"""Deprecated Stopwatch implementation""" + +# Copyright (c) PyZMQ Development Team. +# Distributed under the terms of the Modified BSD License. + + +class Stopwatch: + """Deprecated zmq.Stopwatch implementation + + You can use Python's builtin timers (time.monotonic, etc.). + """ + + def __init__(self): + import warnings + + warnings.warn( + "zmq.Stopwatch is deprecated. Use stdlib time.monotonic and friends instead", + DeprecationWarning, + stacklevel=2, + ) + self._start = 0 + import time + + try: + self._monotonic = time.monotonic + except AttributeError: + self._monotonic = time.time + + def start(self): + """Start the counter""" + self._start = self._monotonic() + + def stop(self): + """Return time since start in microseconds""" + stop = self._monotonic() + return int(1e6 * (stop - self._start)) diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/tracker.py b/venv/lib/python3.10/site-packages/zmq/sugar/tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..973fdbd6e2740951969e0f071dd07837cad1d632 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/sugar/tracker.py @@ -0,0 +1,116 @@ +"""Tracker for zero-copy messages with 0MQ.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from __future__ import annotations + +import time +from threading import Event + +from zmq.backend import Frame +from zmq.error import NotDone + + +class MessageTracker: + """A class for tracking if 0MQ is done using one or more messages. + + When you send a 0MQ message, it is not sent immediately. The 0MQ IO thread + sends the message at some later time. Often you want to know when 0MQ has + actually sent the message though. This is complicated by the fact that + a single 0MQ message can be sent multiple times using different sockets. + This class allows you to track all of the 0MQ usages of a message. + + Parameters + ---------- + towatch : Event, MessageTracker, zmq.Frame + This objects to track. This class can track the low-level + Events used by the Message class, other MessageTrackers or + actual Messages. + """ + + events: set[Event] + peers: set[MessageTracker] + + def __init__(self, *towatch: tuple[MessageTracker | Event | Frame]): + """Create a message tracker to track a set of messages. + + Parameters + ---------- + *towatch : tuple of Event, MessageTracker, Message instances. + This list of objects to track. This class can track the low-level + Events used by the Message class, other MessageTrackers or + actual Messages. + """ + self.events = set() + self.peers = set() + for obj in towatch: + if isinstance(obj, Event): + self.events.add(obj) + elif isinstance(obj, MessageTracker): + self.peers.add(obj) + elif isinstance(obj, Frame): + if not obj.tracker: + raise ValueError("Not a tracked message") + self.peers.add(obj.tracker) + else: + raise TypeError(f"Require Events or Message Frames, not {type(obj)}") + + @property + def done(self): + """Is 0MQ completely done with the message(s) being tracked?""" + for evt in self.events: + if not evt.is_set(): + return False + for pm in self.peers: + if not pm.done: + return False + return True + + def wait(self, timeout: float | int = -1): + """Wait for 0MQ to be done with the message or until `timeout`. + + Parameters + ---------- + timeout : float + default: -1, which means wait forever. + Maximum time in (s) to wait before raising NotDone. + + Returns + ------- + None + if done before `timeout` + + Raises + ------ + NotDone + if `timeout` reached before I am done. + """ + tic = time.time() + remaining: float + if timeout is False or timeout < 0: + remaining = 3600 * 24 * 7 # a week + else: + remaining = timeout + for evt in self.events: + if remaining < 0: + raise NotDone + evt.wait(timeout=remaining) + if not evt.is_set(): + raise NotDone + toc = time.time() + remaining -= toc - tic + tic = toc + + for peer in self.peers: + if remaining < 0: + raise NotDone + peer.wait(timeout=remaining) + toc = time.time() + remaining -= toc - tic + tic = toc + + +_FINISHED_TRACKER = MessageTracker() + +__all__ = ['MessageTracker', '_FINISHED_TRACKER'] diff --git a/venv/lib/python3.10/site-packages/zmq/sugar/version.py b/venv/lib/python3.10/site-packages/zmq/sugar/version.py new file mode 100644 index 0000000000000000000000000000000000000000..cd699cecc2fc743fc17ed2b456f22bc53b0dca71 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/sugar/version.py @@ -0,0 +1,67 @@ +"""PyZMQ and 0MQ version functions.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. +from __future__ import annotations + +import re +from typing import Match, cast + +from zmq.backend import zmq_version_info + +__version__: str = "27.0.1" +_version_pat = re.compile(r"(\d+)\.(\d+)\.(\d+)(.*)") +_match = cast(Match, _version_pat.match(__version__)) +_version_groups = _match.groups() + +VERSION_MAJOR = int(_version_groups[0]) +VERSION_MINOR = int(_version_groups[1]) +VERSION_PATCH = int(_version_groups[2]) +VERSION_EXTRA = _version_groups[3].lstrip(".") + +version_info: tuple[int, int, int] | tuple[int, int, int, float] = ( + VERSION_MAJOR, + VERSION_MINOR, + VERSION_PATCH, +) + +if VERSION_EXTRA: + version_info = ( + VERSION_MAJOR, + VERSION_MINOR, + VERSION_PATCH, + float('inf'), + ) + +__revision__: str = '' + + +def pyzmq_version() -> str: + """return the version of pyzmq as a string""" + if __revision__: + return '+'.join([__version__, __revision__[:6]]) + else: + return __version__ + + +def pyzmq_version_info() -> tuple[int, int, int] | tuple[int, int, int, float]: + """return the pyzmq version as a tuple of at least three numbers + + If pyzmq is a development version, `inf` will be appended after the third integer. + """ + return version_info + + +def zmq_version() -> str: + """return the version of libzmq as a string""" + return "{}.{}.{}".format(*zmq_version_info()) + + +__all__ = [ + 'zmq_version', + 'zmq_version_info', + 'pyzmq_version', + 'pyzmq_version_info', + '__version__', + '__revision__', +] diff --git a/venv/lib/python3.10/site-packages/zmq/tests/__init__.py b/venv/lib/python3.10/site-packages/zmq/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5be08c6a8a2c01f8bcce399252a7794d646a670d --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/tests/__init__.py @@ -0,0 +1,262 @@ +# Copyright (c) PyZMQ Developers. +# Distributed under the terms of the Modified BSD License. + +import os +import platform +import signal +import sys +import time +import warnings +from functools import partial +from threading import Thread +from typing import List +from unittest import SkipTest, TestCase + +from pytest import mark + +import zmq +from zmq.utils import jsonapi + +try: + import gevent + + from zmq import green as gzmq + + have_gevent = True +except ImportError: + have_gevent = False + + +PYPY = platform.python_implementation() == 'PyPy' + +# ----------------------------------------------------------------------------- +# skip decorators (directly from unittest) +# ----------------------------------------------------------------------------- +warnings.warn( + "zmq.tests is deprecated in pyzmq 25, we recommend managing your own contexts and sockets.", + DeprecationWarning, +) + + +def _id(x): + return x + + +skip_pypy = mark.skipif(PYPY, reason="Doesn't work on PyPy") +require_zmq_4 = mark.skipif(zmq.zmq_version_info() < (4,), reason="requires zmq >= 4") + +# ----------------------------------------------------------------------------- +# Base test class +# ----------------------------------------------------------------------------- + + +def term_context(ctx, timeout): + """Terminate a context with a timeout""" + t = Thread(target=ctx.term) + t.daemon = True + t.start() + t.join(timeout=timeout) + if t.is_alive(): + # reset Context.instance, so the failure to term doesn't corrupt subsequent tests + zmq.sugar.context.Context._instance = None + raise RuntimeError( + "context could not terminate, open sockets likely remain in test" + ) + + +class BaseZMQTestCase(TestCase): + green = False + teardown_timeout = 10 + test_timeout_seconds = int(os.environ.get("ZMQ_TEST_TIMEOUT") or 60) + sockets: List[zmq.Socket] + + @property + def _is_pyzmq_test(self): + return self.__class__.__module__.split(".", 1)[0] == __name__.split(".", 1)[0] + + @property + def _should_test_timeout(self): + return ( + self._is_pyzmq_test + and hasattr(signal, 'SIGALRM') + and self.test_timeout_seconds + ) + + @property + def Context(self): + if self.green: + return gzmq.Context + else: + return zmq.Context + + def socket(self, socket_type): + s = self.context.socket(socket_type) + self.sockets.append(s) + return s + + def _alarm_timeout(self, timeout, *args): + raise TimeoutError(f"Test did not complete in {timeout} seconds") + + def setUp(self): + super().setUp() + if self.green and not have_gevent: + raise SkipTest("requires gevent") + + self.context = self.Context.instance() + self.sockets = [] + if self._should_test_timeout: + # use SIGALRM to avoid test hangs + signal.signal( + signal.SIGALRM, partial(self._alarm_timeout, self.test_timeout_seconds) + ) + signal.alarm(self.test_timeout_seconds) + + def tearDown(self): + if self._should_test_timeout: + # cancel the timeout alarm, if there was one + signal.alarm(0) + contexts = {self.context} + while self.sockets: + sock = self.sockets.pop() + contexts.add(sock.context) # in case additional contexts are created + sock.close(0) + for ctx in contexts: + try: + term_context(ctx, self.teardown_timeout) + except Exception: + # reset Context.instance, so the failure to term doesn't corrupt subsequent tests + zmq.sugar.context.Context._instance = None + raise + + super().tearDown() + + def create_bound_pair( + self, type1=zmq.PAIR, type2=zmq.PAIR, interface='tcp://127.0.0.1' + ): + """Create a bound socket pair using a random port.""" + s1 = self.context.socket(type1) + s1.setsockopt(zmq.LINGER, 0) + port = s1.bind_to_random_port(interface) + s2 = self.context.socket(type2) + s2.setsockopt(zmq.LINGER, 0) + s2.connect(f'{interface}:{port}') + self.sockets.extend([s1, s2]) + return s1, s2 + + def ping_pong(self, s1, s2, msg): + s1.send(msg) + msg2 = s2.recv() + s2.send(msg2) + msg3 = s1.recv() + return msg3 + + def ping_pong_json(self, s1, s2, o): + if jsonapi.jsonmod is None: + raise SkipTest("No json library") + s1.send_json(o) + o2 = s2.recv_json() + s2.send_json(o2) + o3 = s1.recv_json() + return o3 + + def ping_pong_pyobj(self, s1, s2, o): + s1.send_pyobj(o) + o2 = s2.recv_pyobj() + s2.send_pyobj(o2) + o3 = s1.recv_pyobj() + return o3 + + def assertRaisesErrno(self, errno, func, *args, **kwargs): + try: + func(*args, **kwargs) + except zmq.ZMQError as e: + self.assertEqual( + e.errno, + errno, + f"wrong error raised, expected '{zmq.ZMQError(errno)}' \ +got '{zmq.ZMQError(e.errno)}'", + ) + else: + self.fail("Function did not raise any error") + + def _select_recv(self, multipart, socket, **kwargs): + """call recv[_multipart] in a way that raises if there is nothing to receive""" + # zmq 3.1 has a bug, where poll can return false positives, + # so we wait a little bit just in case + # See LIBZMQ-280 on JIRA + time.sleep(0.1) + + r, w, x = zmq.select([socket], [], [], timeout=kwargs.pop('timeout', 5)) + assert len(r) > 0, "Should have received a message" + kwargs['flags'] = zmq.DONTWAIT | kwargs.get('flags', 0) + + recv = socket.recv_multipart if multipart else socket.recv + return recv(**kwargs) + + def recv(self, socket, **kwargs): + """call recv in a way that raises if there is nothing to receive""" + return self._select_recv(False, socket, **kwargs) + + def recv_multipart(self, socket, **kwargs): + """call recv_multipart in a way that raises if there is nothing to receive""" + return self._select_recv(True, socket, **kwargs) + + +class PollZMQTestCase(BaseZMQTestCase): + pass + + +class GreenTest: + """Mixin for making green versions of test classes""" + + green = True + teardown_timeout = 10 + + def assertRaisesErrno(self, errno, func, *args, **kwargs): + if errno == zmq.EAGAIN: + raise SkipTest("Skipping because we're green.") + try: + func(*args, **kwargs) + except zmq.ZMQError: + e = sys.exc_info()[1] + self.assertEqual( + e.errno, + errno, + f"wrong error raised, expected '{zmq.ZMQError(errno)}' \ +got '{zmq.ZMQError(e.errno)}'", + ) + else: + self.fail("Function did not raise any error") + + def tearDown(self): + if self._should_test_timeout: + # cancel the timeout alarm, if there was one + signal.alarm(0) + contexts = {self.context} + while self.sockets: + sock = self.sockets.pop() + contexts.add(sock.context) # in case additional contexts are created + sock.close() + try: + gevent.joinall( + [gevent.spawn(ctx.term) for ctx in contexts], + timeout=self.teardown_timeout, + raise_error=True, + ) + except gevent.Timeout: + raise RuntimeError( + "context could not terminate, open sockets likely remain in test" + ) + + def skip_green(self): + raise SkipTest("Skipping because we are green") + + +def skip_green(f): + def skipping_test(self, *args, **kwargs): + if self.green: + raise SkipTest("Skipping because we are green") + else: + return f(self, *args, **kwargs) + + return skipping_test diff --git a/venv/lib/python3.10/site-packages/zmq/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f97f3d3e2f37ba3aa201230610bcca12909b129 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/utils/__init__.py b/venv/lib/python3.10/site-packages/zmq/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..961a84c13fd937ad9e86ff7413cc56d7e3deff4a Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/garbage.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/garbage.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b4a415c790f2d8e4d70b49f35a7339cbb97c971 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/garbage.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/interop.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/interop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..534871f4325339c430cca04c80c9c8798950ef26 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/interop.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/jsonapi.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/jsonapi.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e11700f7082b4491c189196761f76d463c7f182 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/jsonapi.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/monitor.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/monitor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..978fe4e555f97b52a3527c22f18728c3be823114 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/monitor.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/strtypes.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/strtypes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91314717891f43b3f6b39e8a079d70ef07fca4d6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/strtypes.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/win32.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/win32.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90ac18d8971c7441eb9fa387303a1ba37915914c Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/win32.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/z85.cpython-310.pyc b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/z85.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdf2cdfea503007e06e350e86bb3111a71da91d9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/zmq/utils/__pycache__/z85.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/zmq/utils/garbage.py b/venv/lib/python3.10/site-packages/zmq/utils/garbage.py new file mode 100644 index 0000000000000000000000000000000000000000..2c700313d917f2dd44a3d62b4a2a79bb0a1f9de0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/utils/garbage.py @@ -0,0 +1,213 @@ +"""Garbage collection thread for representing zmq refcount of Python objects +used in zero-copy sends. +""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import atexit +import struct +import warnings +from collections import namedtuple +from os import getpid +from threading import Event, Lock, Thread + +import zmq + +gcref = namedtuple('gcref', ['obj', 'event']) + + +class GarbageCollectorThread(Thread): + """Thread in which garbage collection actually happens.""" + + def __init__(self, gc): + super().__init__() + self.gc = gc + self.daemon = True + self.pid = getpid() + self.ready = Event() + + def run(self): + # detect fork at beginning of the thread + if getpid is None or getpid() != self.pid: + self.ready.set() + return + try: + s = self.gc.context.socket(zmq.PULL) + s.linger = 0 + s.bind(self.gc.url) + finally: + self.ready.set() + + while True: + # detect fork + if getpid is None or getpid() != self.pid: + return + msg = s.recv() + if msg == b'DIE': + break + fmt = 'L' if len(msg) == 4 else 'Q' + key = struct.unpack(fmt, msg)[0] + tup = self.gc.refs.pop(key, None) + if tup and tup.event: + tup.event.set() + del tup + s.close() + + +class GarbageCollector: + """PyZMQ Garbage Collector + + Used for representing the reference held by libzmq during zero-copy sends. + This object holds a dictionary, keyed by Python id, + of the Python objects whose memory are currently in use by zeromq. + + When zeromq is done with the memory, it sends a message on an inproc PUSH socket + containing the packed size_t (32 or 64-bit unsigned int), + which is the key in the dict. + When the PULL socket in the gc thread receives that message, + the reference is popped from the dict, + and any tracker events that should be signaled fire. + """ + + refs = None + _context = None + _lock = None + url = "inproc://pyzmq.gc.01" + + def __init__(self, context=None): + super().__init__() + self.refs = {} + self.pid = None + self.thread = None + self._context = context + self._lock = Lock() + self._stay_down = False + self._push = None + self._push_mutex = None + atexit.register(self._atexit) + + @property + def context(self): + if self._context is None: + if Thread.__module__.startswith('gevent'): + # gevent has monkey-patched Thread, use green Context + from zmq import green + + self._context = green.Context() + else: + self._context = zmq.Context() + return self._context + + @context.setter + def context(self, ctx): + if self.is_alive(): + if self.refs: + warnings.warn( + "Replacing gc context while gc is running", RuntimeWarning + ) + self.stop() + self._context = ctx + + def _atexit(self): + """atexit callback + + sets _stay_down flag so that gc doesn't try to start up again in other atexit handlers + """ + self._stay_down = True + self.stop() + + def stop(self): + """stop the garbage-collection thread""" + if not self.is_alive(): + return + self._stop() + + def _clear(self): + """Clear state + + called after stop or when setting up a new subprocess + """ + self._push = None + self._push_mutex = None + self.thread = None + self.refs.clear() + self.context = None + + def _stop(self): + push = self.context.socket(zmq.PUSH) + push.connect(self.url) + push.send(b'DIE') + push.close() + if self._push: + self._push.close() + self.thread.join() + self.context.term() + self._clear() + + @property + def _push_socket(self): + """The PUSH socket for use in the zmq message destructor callback.""" + if getattr(self, "_stay_down", False): + raise RuntimeError("zmq gc socket requested during shutdown") + if not self.is_alive() or self._push is None: + self._push = self.context.socket(zmq.PUSH) + self._push.connect(self.url) + return self._push + + def start(self): + """Start a new garbage collection thread. + + Creates a new zmq Context used for garbage collection. + Under most circumstances, this will only be called once per process. + """ + if self.thread is not None and self.pid != getpid(): + # It's re-starting, must free earlier thread's context + # since a fork probably broke it + self._clear() + self.pid = getpid() + self.refs = {} + self.thread = GarbageCollectorThread(self) + self.thread.start() + self.thread.ready.wait() + + def is_alive(self): + """Is the garbage collection thread currently running? + + Includes checks for process shutdown or fork. + """ + if ( + getpid is None + or getpid() != self.pid + or self.thread is None + or not self.thread.is_alive() + ): + return False + return True + + def store(self, obj, event=None): + """store an object and (optionally) event for zero-copy""" + if not self.is_alive(): + if self._stay_down: + return 0 + # safely start the gc thread + # use lock and double check, + # so we don't start multiple threads + with self._lock: + if not self.is_alive(): + self.start() + tup = gcref(obj, event) + theid = id(tup) + self.refs[theid] = tup + return theid + + def __del__(self): + if not self.is_alive(): + return + try: + self.stop() + except Exception as e: + raise (e) + + +gc = GarbageCollector() diff --git a/venv/lib/python3.10/site-packages/zmq/utils/getpid_compat.h b/venv/lib/python3.10/site-packages/zmq/utils/getpid_compat.h new file mode 100644 index 0000000000000000000000000000000000000000..3fe1bec4c24ac472fb9ab8940da43adc1de60257 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/utils/getpid_compat.h @@ -0,0 +1,7 @@ +#pragma once +#ifdef _WIN32 + #include + #define getpid _getpid +#else + #include +#endif diff --git a/venv/lib/python3.10/site-packages/zmq/utils/interop.py b/venv/lib/python3.10/site-packages/zmq/utils/interop.py new file mode 100644 index 0000000000000000000000000000000000000000..ab4ffd9a813c7c0e490428123b08b9e38c85d52b --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/utils/interop.py @@ -0,0 +1,29 @@ +"""Utils for interoperability with other libraries. + +Just CFFI pointer casting for now. +""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from typing import Any + + +def cast_int_addr(n: Any) -> int: + """Cast an address to a Python int + + This could be a Python integer or a CFFI pointer + """ + if isinstance(n, int): + return n + try: + import cffi # type: ignore + except ImportError: + pass + else: + # from pyzmq, this is an FFI void * + ffi = cffi.FFI() + if isinstance(n, ffi.CData): + return int(ffi.cast("size_t", n)) + + raise ValueError(f"Cannot cast {n!r} to int") diff --git a/venv/lib/python3.10/site-packages/zmq/utils/ipcmaxlen.h b/venv/lib/python3.10/site-packages/zmq/utils/ipcmaxlen.h new file mode 100644 index 0000000000000000000000000000000000000000..7af9a261be4be890aab7df2b570d59e09ff2a3e2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/utils/ipcmaxlen.h @@ -0,0 +1,27 @@ +/* + +Platform-independant detection of IPC path max length + +Copyright (c) 2012 Godefroid Chapelle + +Distributed under the terms of the New BSD License. The full license is in +the file LICENSE.BSD, distributed as part of this software. + */ + +#pragma once + +#if defined(HAVE_SYS_UN_H) +#if defined _MSC_VER +#include +#else +#include +#endif +int get_ipc_path_max_len(void) { + struct sockaddr_un *dummy; + return sizeof(dummy->sun_path) - 1; +} +#else +int get_ipc_path_max_len(void) { + return 0; +} +#endif diff --git a/venv/lib/python3.10/site-packages/zmq/utils/jsonapi.py b/venv/lib/python3.10/site-packages/zmq/utils/jsonapi.py new file mode 100644 index 0000000000000000000000000000000000000000..6a6ee0785229f449ccc9efc3e778909699866de0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/utils/jsonapi.py @@ -0,0 +1,38 @@ +"""JSON serialize to/from utf8 bytes + +.. versionchanged:: 22.2 + Remove optional imports of different JSON implementations. + Now that we require recent Python, unconditionally use the standard library. + Custom JSON libraries can be used via custom serialization functions. +""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. +from __future__ import annotations + +import json +from typing import Any + +# backward-compatibility, unused +jsonmod = json + + +def dumps(o: Any, **kwargs) -> bytes: + """Serialize object to JSON bytes (utf-8). + + Keyword arguments are passed along to :py:func:`json.dumps`. + """ + return json.dumps(o, **kwargs).encode("utf8") + + +def loads(s: bytes | str, **kwargs) -> dict | list | str | int | float: + """Load object from JSON bytes (utf-8). + + Keyword arguments are passed along to :py:func:`json.loads`. + """ + if isinstance(s, bytes): + s = s.decode("utf8") + return json.loads(s, **kwargs) + + +__all__ = ['dumps', 'loads'] diff --git a/venv/lib/python3.10/site-packages/zmq/utils/monitor.py b/venv/lib/python3.10/site-packages/zmq/utils/monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..872e24dc2953ba17877d39c1628d3f38d53484d6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/utils/monitor.py @@ -0,0 +1,128 @@ +"""Module holding utility and convenience functions for zmq event monitoring.""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +from __future__ import annotations + +import struct +from typing import Awaitable, TypedDict, overload + +import zmq +import zmq.asyncio +from zmq.error import _check_version + + +class _MonitorMessage(TypedDict): + event: int + value: int + endpoint: bytes + + +def parse_monitor_message(msg: list[bytes]) -> _MonitorMessage: + """decode zmq_monitor event messages. + + Parameters + ---------- + msg : list(bytes) + zmq multipart message that has arrived on a monitor PAIR socket. + + First frame is:: + + 16 bit event id + 32 bit event value + no padding + + Second frame is the endpoint as a bytestring + + Returns + ------- + event : dict + event description as dict with the keys `event`, `value`, and `endpoint`. + """ + if len(msg) != 2 or len(msg[0]) != 6: + raise RuntimeError(f"Invalid event message format: {msg}") + event_id, value = struct.unpack("=hi", msg[0]) + event: _MonitorMessage = { + 'event': zmq.Event(event_id), + 'value': zmq.Event(value), + 'endpoint': msg[1], + } + return event + + +async def _parse_monitor_msg_async( + awaitable_msg: Awaitable[list[bytes]], +) -> _MonitorMessage: + """Like parse_monitor_msg, but awaitable + + Given awaitable message, return awaitable for the parsed monitor message. + """ + + msg = await awaitable_msg + # 4.0-style event API + return parse_monitor_message(msg) + + +@overload +def recv_monitor_message( + socket: zmq.asyncio.Socket, + flags: int = 0, +) -> Awaitable[_MonitorMessage]: ... + + +@overload +def recv_monitor_message( + socket: zmq.Socket[bytes], + flags: int = 0, +) -> _MonitorMessage: ... + + +def recv_monitor_message( + socket: zmq.Socket, + flags: int = 0, +) -> _MonitorMessage | Awaitable[_MonitorMessage]: + """Receive and decode the given raw message from the monitoring socket and return a dict. + + Requires libzmq ≥ 4.0 + + The returned dict will have the following entries: + event : int + the event id as described in `libzmq.zmq_socket_monitor` + value : int + the event value associated with the event, see `libzmq.zmq_socket_monitor` + endpoint : str + the affected endpoint + + .. versionchanged:: 23.1 + Support for async sockets added. + When called with a async socket, + returns an awaitable for the monitor message. + + Parameters + ---------- + socket : zmq.Socket + The PAIR socket (created by other.get_monitor_socket()) on which to recv the message + flags : int + standard zmq recv flags + + Returns + ------- + event : dict + event description as dict with the keys `event`, `value`, and `endpoint`. + """ + + _check_version((4, 0), 'libzmq event API') + # will always return a list + msg = socket.recv_multipart(flags) + + # transparently handle asyncio socket, + # returns a Future instead of a dict + if isinstance(msg, Awaitable): + return _parse_monitor_msg_async(msg) + + # 4.0-style event API + return parse_monitor_message(msg) + + +__all__ = ['parse_monitor_message', 'recv_monitor_message'] diff --git a/venv/lib/python3.10/site-packages/zmq/utils/mutex.h b/venv/lib/python3.10/site-packages/zmq/utils/mutex.h new file mode 100644 index 0000000000000000000000000000000000000000..b6275ea28b0799607b93a69679a86f51a95fbb28 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/utils/mutex.h @@ -0,0 +1,84 @@ +/* +* simplified from mutex.c from Foundation Library, in the Public Domain +* https://github.com/rampantpixels/foundation_lib/blob/master/foundation/mutex.c +* +* This file is Copyright (C) PyZMQ Developers +* Distributed under the terms of the Modified BSD License. +* +*/ + +#pragma once + +#include + +#if defined(_WIN32) +# include +#else +# include +#endif + +typedef struct { +#if defined(_WIN32) + CRITICAL_SECTION csection; +#else + pthread_mutex_t mutex; +#endif +} mutex_t; + + +static void +_mutex_initialize(mutex_t* mutex) { +#if defined(_WIN32) + InitializeCriticalSectionAndSpinCount(&mutex->csection, 4000); +#else + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&mutex->mutex, &attr); + pthread_mutexattr_destroy(&attr); +#endif +} + +static void +_mutex_finalize(mutex_t* mutex) { +#if defined(_WIN32) + DeleteCriticalSection(&mutex->csection); +#else + pthread_mutex_destroy(&mutex->mutex); +#endif +} + +mutex_t* +mutex_allocate(void) { + mutex_t* mutex = (mutex_t*)malloc(sizeof(mutex_t)); + _mutex_initialize(mutex); + return mutex; +} + +void +mutex_deallocate(mutex_t* mutex) { + if (!mutex) + return; + _mutex_finalize(mutex); + free(mutex); +} + +int +mutex_lock(mutex_t* mutex) { +#if defined(_WIN32) + EnterCriticalSection(&mutex->csection); + return 0; +#else + return pthread_mutex_lock(&mutex->mutex); +#endif +} + +int +mutex_unlock(mutex_t* mutex) { +#if defined(_WIN32) + LeaveCriticalSection(&mutex->csection); + return 0; +#else + return pthread_mutex_unlock(&mutex->mutex); +#endif +} diff --git a/venv/lib/python3.10/site-packages/zmq/utils/pyversion_compat.h b/venv/lib/python3.10/site-packages/zmq/utils/pyversion_compat.h new file mode 100644 index 0000000000000000000000000000000000000000..fb19dcf09d6840ac12e995a308bb96838813797a --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/utils/pyversion_compat.h @@ -0,0 +1,12 @@ +#include "Python.h" + +// default to Python's own target Windows version(s) +// override by setting WINVER, _WIN32_WINNT, (maybe also NTDDI_VERSION?) macros +#ifdef Py_WINVER +#ifndef WINVER +#define WINVER Py_WINVER +#endif +#ifndef _WIN32_WINNT +#define _WIN32_WINNT Py_WINVER +#endif +#endif diff --git a/venv/lib/python3.10/site-packages/zmq/utils/strtypes.py b/venv/lib/python3.10/site-packages/zmq/utils/strtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..3d90a04809ca4f29e1457099b63c03302e837a1e --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/utils/strtypes.py @@ -0,0 +1,62 @@ +"""Declare basic string types unambiguously for various Python versions. + +Authors +------- +* MinRK +""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. + +import warnings + +bytes = bytes +unicode = str +basestring = (str,) + + +def cast_bytes(s, encoding='utf8', errors='strict'): + """cast unicode or bytes to bytes""" + warnings.warn( + "zmq.utils.strtypes is deprecated in pyzmq 23.", + DeprecationWarning, + stacklevel=2, + ) + if isinstance(s, bytes): + return s + elif isinstance(s, str): + return s.encode(encoding, errors) + else: + raise TypeError(f"Expected unicode or bytes, got {s!r}") + + +def cast_unicode(s, encoding='utf8', errors='strict'): + """cast bytes or unicode to unicode""" + warnings.warn( + "zmq.utils.strtypes is deprecated in pyzmq 23.", + DeprecationWarning, + stacklevel=2, + ) + if isinstance(s, bytes): + return s.decode(encoding, errors) + elif isinstance(s, str): + return s + else: + raise TypeError(f"Expected unicode or bytes, got {s!r}") + + +# give short 'b' alias for cast_bytes, so that we can use fake b'stuff' +# to simulate b'stuff' +b = asbytes = cast_bytes +u = cast_unicode + +__all__ = [ + 'asbytes', + 'bytes', + 'unicode', + 'basestring', + 'b', + 'u', + 'cast_bytes', + 'cast_unicode', +] diff --git a/venv/lib/python3.10/site-packages/zmq/utils/win32.py b/venv/lib/python3.10/site-packages/zmq/utils/win32.py new file mode 100644 index 0000000000000000000000000000000000000000..019d429715af914d4aeb508bda342f764a74e9d0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/utils/win32.py @@ -0,0 +1,130 @@ +"""Win32 compatibility utilities.""" + +# ----------------------------------------------------------------------------- +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. +# ----------------------------------------------------------------------------- +from __future__ import annotations + +import os +from typing import Any, Callable + + +class allow_interrupt: + """Utility for fixing CTRL-C events on Windows. + + On Windows, the Python interpreter intercepts CTRL-C events in order to + translate them into ``KeyboardInterrupt`` exceptions. It (presumably) + does this by setting a flag in its "console control handler" and + checking it later at a convenient location in the interpreter. + + However, when the Python interpreter is blocked waiting for the ZMQ + poll operation to complete, it must wait for ZMQ's ``select()`` + operation to complete before translating the CTRL-C event into the + ``KeyboardInterrupt`` exception. + + The only way to fix this seems to be to add our own "console control + handler" and perform some application-defined operation that will + unblock the ZMQ polling operation in order to force ZMQ to pass control + back to the Python interpreter. + + This context manager performs all that Windows-y stuff, providing you + with a hook that is called when a CTRL-C event is intercepted. This + hook allows you to unblock your ZMQ poll operation immediately, which + will then result in the expected ``KeyboardInterrupt`` exception. + + Without this context manager, your ZMQ-based application will not + respond normally to CTRL-C events on Windows. If a CTRL-C event occurs + while blocked on ZMQ socket polling, the translation to a + ``KeyboardInterrupt`` exception will be delayed until the I/O completes + and control returns to the Python interpreter (this may never happen if + you use an infinite timeout). + + A no-op implementation is provided on non-Win32 systems to avoid the + application from having to conditionally use it. + + Example usage: + + .. sourcecode:: python + + def stop_my_application(): + # ... + + with allow_interrupt(stop_my_application): + # main polling loop. + + In a typical ZMQ application, you would use the "self pipe trick" to + send message to a ``PAIR`` socket in order to interrupt your blocking + socket polling operation. + + In a Tornado event loop, you can use the ``IOLoop.stop`` method to + unblock your I/O loop. + """ + + def __init__(self, action: Callable[[], Any] | None = None) -> None: + """Translate ``action`` into a CTRL-C handler. + + ``action`` is a callable that takes no arguments and returns no + value (returned value is ignored). It must *NEVER* raise an + exception. + + If unspecified, a no-op will be used. + """ + if os.name != "nt": + return + self._init_action(action) + + def _init_action(self, action): + from ctypes import WINFUNCTYPE, windll + from ctypes.wintypes import BOOL, DWORD + + kernel32 = windll.LoadLibrary('kernel32') + + # + PHANDLER_ROUTINE = WINFUNCTYPE(BOOL, DWORD) + SetConsoleCtrlHandler = self._SetConsoleCtrlHandler = ( + kernel32.SetConsoleCtrlHandler + ) + SetConsoleCtrlHandler.argtypes = (PHANDLER_ROUTINE, BOOL) + SetConsoleCtrlHandler.restype = BOOL + + if action is None: + + def action(): + return None + + self.action = action + + @PHANDLER_ROUTINE + def handle(event): + if event == 0: # CTRL_C_EVENT + action() + # Typical C implementations would return 1 to indicate that + # the event was processed and other control handlers in the + # stack should not be executed. However, that would + # prevent the Python interpreter's handler from translating + # CTRL-C to a `KeyboardInterrupt` exception, so we pretend + # that we didn't handle it. + return 0 + + self.handle = handle + + def __enter__(self): + """Install the custom CTRL-C handler.""" + if os.name != "nt": + return + result = self._SetConsoleCtrlHandler(self.handle, 1) + if result == 0: + # Have standard library automatically call `GetLastError()` and + # `FormatMessage()` into a nice exception object :-) + raise OSError() + + def __exit__(self, *args): + """Remove the custom CTRL-C handler.""" + if os.name != "nt": + return + result = self._SetConsoleCtrlHandler(self.handle, 0) + if result == 0: + # Have standard library automatically call `GetLastError()` and + # `FormatMessage()` into a nice exception object :-) + raise OSError() diff --git a/venv/lib/python3.10/site-packages/zmq/utils/z85.py b/venv/lib/python3.10/site-packages/zmq/utils/z85.py new file mode 100644 index 0000000000000000000000000000000000000000..016bdfe12f303f1542fe00fc92ab1a72a20a20b9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/utils/z85.py @@ -0,0 +1,58 @@ +"""Python implementation of Z85 85-bit encoding + +Z85 encoding is a plaintext encoding for a bytestring interpreted as 32bit integers. +Since the chunks are 32bit, a bytestring must be a multiple of 4 bytes. +See ZMQ RFC 32 for details. + + +""" + +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. +from __future__ import annotations + +import struct + +# Z85CHARS is the base 85 symbol table +Z85CHARS = b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#" +# Z85MAP maps integers in [0,84] to the appropriate character in Z85CHARS +Z85MAP = {c: idx for idx, c in enumerate(Z85CHARS)} + +_85s = [85**i for i in range(5)][::-1] + + +def encode(rawbytes): + """encode raw bytes into Z85""" + # Accepts only byte arrays bounded to 4 bytes + if len(rawbytes) % 4: + raise ValueError(f"length must be multiple of 4, not {len(rawbytes)}") + + nvalues = len(rawbytes) // 4 + values = struct.unpack(f'>{nvalues:d}I', rawbytes) + encoded = [] + for v in values: + for offset in _85s: + encoded.append(Z85CHARS[(v // offset) % 85]) + + return bytes(encoded) + + +def decode(z85bytes): + """decode Z85 bytes to raw bytes, accepts ASCII string""" + if isinstance(z85bytes, str): + try: + z85bytes = z85bytes.encode('ascii') + except UnicodeEncodeError: + raise ValueError('string argument should contain only ASCII characters') + + if len(z85bytes) % 5: + raise ValueError(f"Z85 length must be multiple of 5, not {len(z85bytes)}") + + nvalues = len(z85bytes) // 5 + values = [] + for i in range(0, len(z85bytes), 5): + value = 0 + for j, offset in enumerate(_85s): + value += Z85MAP[z85bytes[i + j]] * offset + values.append(value) + return struct.pack(f'>{nvalues:d}I', *values) diff --git a/venv/lib/python3.10/site-packages/zmq/utils/zmq_compat.h b/venv/lib/python3.10/site-packages/zmq/utils/zmq_compat.h new file mode 100644 index 0000000000000000000000000000000000000000..a3c9dae19a581f60217eb26cc4e6353ce3bf1ecf --- /dev/null +++ b/venv/lib/python3.10/site-packages/zmq/utils/zmq_compat.h @@ -0,0 +1,96 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2010 Brian Granger, Min Ragan-Kelley +// +// Distributed under the terms of the New BSD License. The full license is in +// the file LICENSE.BSD, distributed as part of this software. +//----------------------------------------------------------------------------- + +#pragma once + +#if defined(_MSC_VER) +#define pyzmq_int64_t __int64 +#define pyzmq_uint32_t unsigned __int32 +#else +#include +#define pyzmq_int64_t int64_t +#define pyzmq_uint32_t uint32_t +#endif + + +#include "zmq.h" + +#define _missing (-1) + +#if (ZMQ_VERSION >= 40303) + // libzmq >= 4.3.3 defines zmq_fd_t for us + #define ZMQ_FD_T zmq_fd_t +#else + #ifdef _WIN32 + #if defined(_MSC_VER) && _MSC_VER <= 1400 + #define ZMQ_FD_T UINT_PTR + #else + #define ZMQ_FD_T SOCKET + #endif + #else + #define ZMQ_FD_T int + #endif +#endif + +#if (ZMQ_VERSION >= 40200) + // Nothing to remove +#else + #define zmq_curve_public(z85_public_key, z85_secret_key) _missing +#endif + +// use unambiguous aliases for zmq_send/recv functions + +#if ZMQ_VERSION_MAJOR >= 4 +// nothing to remove + #if ZMQ_VERSION_MAJOR == 4 && ZMQ_VERSION_MINOR == 0 + // zmq 4.1 deprecates zmq_utils.h + // we only get zmq_curve_keypair from it + #include "zmq_utils.h" + #endif +#else + #define zmq_curve_keypair(z85_public_key, z85_secret_key) _missing +#endif + +// libzmq 4.2 draft API +#ifdef ZMQ_BUILD_DRAFT_API + #if ZMQ_VERSION >= 40200 + #define PYZMQ_DRAFT_42 + #endif + #if ZMQ_VERSION >= 40302 + #define PYZMQ_DRAFT_432 + #endif +#endif +#ifndef PYZMQ_DRAFT_42 + #define zmq_join(s, group) _missing + #define zmq_leave(s, group) _missing + #define zmq_msg_set_routing_id(msg, routing_id) _missing + #define zmq_msg_routing_id(msg) 0 + #define zmq_msg_set_group(msg, group) _missing + #define zmq_msg_group(msg) NULL + #define zmq_poller_new() NULL + #define zmq_poller_destroy(poller_p) _missing + #define zmq_poller_add(poller, socket, userdata, events) _missing + #define zmq_poller_modify(poller, socket, events) _missing + #define zmq_poller_remove(poller, socket) _missing +#endif +#ifndef PYZMQ_DRAFT_432 + #define zmq_poller_fd(poller, fd) _missing +#endif + +#if ZMQ_VERSION >= 40100 +// nothing to remove +#else + #define zmq_msg_gets(msg, prop) _missing + #define zmq_has(capability) _missing + #define zmq_proxy_steerable(in, out, mon, ctrl) _missing +#endif + +// 3.x deprecations - these symbols haven't been removed, +// but let's protect against their planned removal +#define zmq_device(device_type, isocket, osocket) _missing +#define zmq_init(io_threads) ((void*)NULL) +#define zmq_term zmq_ctx_destroy