content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
# pyright: reportIncompatibleMethodOverride=false\n# ruff: noqa: ANN001, ANN002, ANN003, ANN201, ANN202 ANN204, ANN401\n\nfrom collections.abc import Sequence\nfrom typing import Any, Literal, Self, SupportsIndex, TypeAlias, overload\n\nfrom _typeshed import Incomplete\nfrom typing_extensions import TypeIs, TypeVar\n\nimport numpy as np\nfrom numpy import (\n _HasDTypeWithRealAndImag,\n _ModeKind,\n _OrderKACF,\n _PartitionKind,\n _SortKind,\n amax,\n amin,\n bool_,\n bytes_,\n character,\n complexfloating,\n datetime64,\n dtype,\n dtypes,\n expand_dims,\n float64,\n floating,\n generic,\n int_,\n integer,\n intp,\n ndarray,\n object_,\n str_,\n timedelta64,\n)\nfrom numpy._globals import _NoValueType\nfrom numpy._typing import (\n ArrayLike,\n NDArray,\n _AnyShape,\n _ArrayLike,\n _ArrayLikeBool_co,\n _ArrayLikeBytes_co,\n _ArrayLikeComplex_co,\n _ArrayLikeFloat_co,\n _ArrayLikeInt,\n _ArrayLikeInt_co,\n _ArrayLikeStr_co,\n _ArrayLikeString_co,\n _ArrayLikeTD64_co,\n _DTypeLikeBool,\n _IntLike_co,\n _ScalarLike_co,\n _Shape,\n _ShapeLike,\n)\n\n__all__ = [\n "MAError",\n "MaskError",\n "MaskType",\n "MaskedArray",\n "abs",\n "absolute",\n "add",\n "all",\n "allclose",\n "allequal",\n "alltrue",\n "amax",\n "amin",\n "angle",\n "anom",\n "anomalies",\n "any",\n "append",\n "arange",\n "arccos",\n "arccosh",\n "arcsin",\n "arcsinh",\n "arctan",\n "arctan2",\n "arctanh",\n "argmax",\n "argmin",\n "argsort",\n "around",\n "array",\n "asanyarray",\n "asarray",\n "bitwise_and",\n "bitwise_or",\n "bitwise_xor",\n "bool_",\n "ceil",\n "choose",\n "clip",\n "common_fill_value",\n "compress",\n "compressed",\n "concatenate",\n "conjugate",\n "convolve",\n "copy",\n "correlate",\n "cos",\n "cosh",\n "count",\n "cumprod",\n "cumsum",\n "default_fill_value",\n "diag",\n "diagonal",\n "diff",\n "divide",\n "empty",\n "empty_like",\n "equal",\n "exp",\n "expand_dims",\n "fabs",\n "filled",\n "fix_invalid",\n "flatten_mask",\n "flatten_structured_array",\n "floor",\n "floor_divide",\n "fmod",\n "frombuffer",\n "fromflex",\n "fromfunction",\n "getdata",\n "getmask",\n "getmaskarray",\n "greater",\n "greater_equal",\n "harden_mask",\n "hypot",\n "identity",\n "ids",\n "indices",\n "inner",\n "innerproduct",\n "isMA",\n "isMaskedArray",\n "is_mask",\n "is_masked",\n "isarray",\n "left_shift",\n "less",\n "less_equal",\n "log",\n "log2",\n "log10",\n "logical_and",\n "logical_not",\n "logical_or",\n "logical_xor",\n "make_mask",\n "make_mask_descr",\n "make_mask_none",\n "mask_or",\n "masked",\n "masked_array",\n "masked_equal",\n "masked_greater",\n "masked_greater_equal",\n "masked_inside",\n "masked_invalid",\n "masked_less",\n "masked_less_equal",\n "masked_not_equal",\n "masked_object",\n "masked_outside",\n "masked_print_option",\n "masked_singleton",\n "masked_values",\n "masked_where",\n "max",\n "maximum",\n "maximum_fill_value",\n "mean",\n "min",\n "minimum",\n "minimum_fill_value",\n "mod",\n "multiply",\n "mvoid",\n "ndim",\n "negative",\n "nomask",\n "nonzero",\n "not_equal",\n "ones",\n "ones_like",\n "outer",\n "outerproduct",\n "power",\n "prod",\n "product",\n "ptp",\n "put",\n "putmask",\n "ravel",\n "remainder",\n "repeat",\n "reshape",\n "resize",\n "right_shift",\n "round",\n "round_",\n "set_fill_value",\n "shape",\n "sin",\n "sinh",\n "size",\n "soften_mask",\n "sometrue",\n "sort",\n "sqrt",\n "squeeze",\n "std",\n "subtract",\n "sum",\n "swapaxes",\n "take",\n "tan",\n "tanh",\n "trace",\n "transpose",\n "true_divide",\n "var",\n "where",\n "zeros",\n "zeros_like",\n]\n\n_ShapeT = TypeVar("_ShapeT", bound=_Shape)\n_ShapeT_co = TypeVar("_ShapeT_co", bound=_Shape, default=_AnyShape, covariant=True)\n_DTypeT = TypeVar("_DTypeT", bound=dtype)\n_DTypeT_co = TypeVar("_DTypeT_co", bound=dtype, default=dtype, covariant=True)\n_ArrayT = TypeVar("_ArrayT", bound=ndarray[Any, Any])\n_ScalarT = TypeVar("_ScalarT", bound=generic)\n_ScalarT_co = TypeVar("_ScalarT_co", bound=generic, covariant=True)\n# A subset of `MaskedArray` that can be parametrized w.r.t. `np.generic`\n_MaskedArray: TypeAlias = MaskedArray[_AnyShape, dtype[_ScalarT]]\n_Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_ScalarT]]\n\nMaskType = bool_\nnomask: bool_[Literal[False]]\n\nclass MaskedArrayFutureWarning(FutureWarning): ...\nclass MAError(Exception): ...\nclass MaskError(MAError): ...\n\ndef default_fill_value(obj): ...\ndef minimum_fill_value(obj): ...\ndef maximum_fill_value(obj): ...\ndef set_fill_value(a, fill_value): ...\ndef common_fill_value(a, b): ...\n@overload\ndef filled(a: ndarray[_ShapeT_co, _DTypeT_co], fill_value: _ScalarLike_co | None = None) -> ndarray[_ShapeT_co, _DTypeT_co]: ...\n@overload\ndef filled(a: _ArrayLike[_ScalarT_co], fill_value: _ScalarLike_co | None = None) -> NDArray[_ScalarT_co]: ...\n@overload\ndef filled(a: ArrayLike, fill_value: _ScalarLike_co | None = None) -> NDArray[Any]: ...\ndef getdata(a, subok=...): ...\nget_data = getdata\n\ndef fix_invalid(a, mask=..., copy=..., fill_value=...): ...\n\nclass _MaskedUFunc:\n f: Any\n __doc__: Any\n __name__: Any\n def __init__(self, ufunc): ...\n\nclass _MaskedUnaryOperation(_MaskedUFunc):\n fill: Any\n domain: Any\n def __init__(self, mufunc, fill=..., domain=...): ...\n def __call__(self, a, *args, **kwargs): ...\n\nclass _MaskedBinaryOperation(_MaskedUFunc):\n fillx: Any\n filly: Any\n def __init__(self, mbfunc, fillx=..., filly=...): ...\n def __call__(self, a, b, *args, **kwargs): ...\n def reduce(self, target, axis=..., dtype=...): ...\n def outer(self, a, b): ...\n def accumulate(self, target, axis=...): ...\n\nclass _DomainedBinaryOperation(_MaskedUFunc):\n domain: Any\n fillx: Any\n filly: Any\n def __init__(self, dbfunc, domain, fillx=..., filly=...): ...\n def __call__(self, a, b, *args, **kwargs): ...\n\nexp: _MaskedUnaryOperation\nconjugate: _MaskedUnaryOperation\nsin: _MaskedUnaryOperation\ncos: _MaskedUnaryOperation\narctan: _MaskedUnaryOperation\narcsinh: _MaskedUnaryOperation\nsinh: _MaskedUnaryOperation\ncosh: _MaskedUnaryOperation\ntanh: _MaskedUnaryOperation\nabs: _MaskedUnaryOperation\nabsolute: _MaskedUnaryOperation\nangle: _MaskedUnaryOperation\nfabs: _MaskedUnaryOperation\nnegative: _MaskedUnaryOperation\nfloor: _MaskedUnaryOperation\nceil: _MaskedUnaryOperation\naround: _MaskedUnaryOperation\nlogical_not: _MaskedUnaryOperation\nsqrt: _MaskedUnaryOperation\nlog: _MaskedUnaryOperation\nlog2: _MaskedUnaryOperation\nlog10: _MaskedUnaryOperation\ntan: _MaskedUnaryOperation\narcsin: _MaskedUnaryOperation\narccos: _MaskedUnaryOperation\narccosh: _MaskedUnaryOperation\narctanh: _MaskedUnaryOperation\n\nadd: _MaskedBinaryOperation\nsubtract: _MaskedBinaryOperation\nmultiply: _MaskedBinaryOperation\narctan2: _MaskedBinaryOperation\nequal: _MaskedBinaryOperation\nnot_equal: _MaskedBinaryOperation\nless_equal: _MaskedBinaryOperation\ngreater_equal: _MaskedBinaryOperation\nless: _MaskedBinaryOperation\ngreater: _MaskedBinaryOperation\nlogical_and: _MaskedBinaryOperation\ndef alltrue(target: ArrayLike, axis: SupportsIndex | None = 0, dtype: _DTypeLikeBool | None = None) -> Incomplete: ...\nlogical_or: _MaskedBinaryOperation\ndef sometrue(target: ArrayLike, axis: SupportsIndex | None = 0, dtype: _DTypeLikeBool | None = None) -> Incomplete: ...\nlogical_xor: _MaskedBinaryOperation\nbitwise_and: _MaskedBinaryOperation\nbitwise_or: _MaskedBinaryOperation\nbitwise_xor: _MaskedBinaryOperation\nhypot: _MaskedBinaryOperation\n\ndivide: _DomainedBinaryOperation\ntrue_divide: _DomainedBinaryOperation\nfloor_divide: _DomainedBinaryOperation\nremainder: _DomainedBinaryOperation\nfmod: _DomainedBinaryOperation\nmod: _DomainedBinaryOperation\n\ndef make_mask_descr(ndtype): ...\n\n@overload\ndef getmask(a: _ScalarLike_co) -> bool_: ...\n@overload\ndef getmask(a: MaskedArray[_ShapeT_co, Any]) -> np.ndarray[_ShapeT_co, dtype[bool_]] | bool_: ...\n@overload\ndef getmask(a: ArrayLike) -> NDArray[bool_] | bool_: ...\n\nget_mask = getmask\n\ndef getmaskarray(arr): ...\n\n# It's sufficient for `m` to have dtype with type: `type[np.bool_]`,\n# which isn't necessarily a ndarray. Please open an issue if this causes issues.\ndef is_mask(m: object) -> TypeIs[NDArray[bool_]]: ...\n\ndef make_mask(m, copy=..., shrink=..., dtype=...): ...\ndef make_mask_none(newshape, dtype=...): ...\ndef mask_or(m1, m2, copy=..., shrink=...): ...\ndef flatten_mask(mask): ...\ndef masked_where(condition, a, copy=...): ...\ndef masked_greater(x, value, copy=...): ...\ndef masked_greater_equal(x, value, copy=...): ...\ndef masked_less(x, value, copy=...): ...\ndef masked_less_equal(x, value, copy=...): ...\ndef masked_not_equal(x, value, copy=...): ...\ndef masked_equal(x, value, copy=...): ...\ndef masked_inside(x, v1, v2, copy=...): ...\ndef masked_outside(x, v1, v2, copy=...): ...\ndef masked_object(x, value, copy=..., shrink=...): ...\ndef masked_values(x, value, rtol=..., atol=..., copy=..., shrink=...): ...\ndef masked_invalid(a, copy=...): ...\n\nclass _MaskedPrintOption:\n def __init__(self, display): ...\n def display(self): ...\n def set_display(self, s): ...\n def enabled(self): ...\n def enable(self, shrink=...): ...\n\nmasked_print_option: _MaskedPrintOption\n\ndef flatten_structured_array(a): ...\n\nclass MaskedIterator:\n ma: Any\n dataiter: Any\n maskiter: Any\n def __init__(self, ma): ...\n def __iter__(self): ...\n def __getitem__(self, indx): ...\n def __setitem__(self, index, value): ...\n def __next__(self): ...\n\nclass MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):\n __array_priority__: Any\n def __new__(cls, data=..., mask=..., dtype=..., copy=..., subok=..., ndmin=..., fill_value=..., keep_mask=..., hard_mask=..., shrink=..., order=...): ...\n def __array_finalize__(self, obj): ...\n def __array_wrap__(self, obj, context=..., return_scalar=...): ...\n def view(self, dtype=..., type=..., fill_value=...): ...\n def __getitem__(self, indx): ...\n def __setitem__(self, indx, value): ...\n @property\n def shape(self) -> _ShapeT_co: ...\n @shape.setter\n def shape(self: MaskedArray[_ShapeT, Any], shape: _ShapeT, /) -> None: ...\n def __setmask__(self, mask: _ArrayLikeBool_co, copy: bool = False) -> None: ...\n @property\n def mask(self) -> NDArray[MaskType] | MaskType: ...\n @mask.setter\n def mask(self, value: _ArrayLikeBool_co, /) -> None: ...\n @property\n def recordmask(self): ...\n @recordmask.setter\n def recordmask(self, mask): ...\n def harden_mask(self) -> Self: ...\n def soften_mask(self) -> Self: ...\n @property\n def hardmask(self) -> bool: ...\n def unshare_mask(self) -> Self: ...\n @property\n def sharedmask(self) -> bool: ...\n def shrink_mask(self) -> Self: ...\n @property\n def baseclass(self) -> type[NDArray[Any]]: ...\n data: Any\n @property\n def flat(self): ...\n @flat.setter\n def flat(self, value): ...\n @property\n def fill_value(self): ...\n @fill_value.setter\n def fill_value(self, value=...): ...\n get_fill_value: Any\n set_fill_value: Any\n def filled(self, /, fill_value: _ScalarLike_co | None = None) -> ndarray[_ShapeT_co, _DTypeT_co]: ...\n def compressed(self) -> ndarray[tuple[int], _DTypeT_co]: ...\n def compress(self, condition, axis=..., out=...): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __ge__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... # type: ignore[override]\n def __gt__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... # type: ignore[override]\n def __le__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... # type: ignore[override]\n def __lt__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... # type: ignore[override]\n def __add__(self, other): ...\n def __radd__(self, other): ...\n def __sub__(self, other): ...\n def __rsub__(self, other): ...\n def __mul__(self, other): ...\n def __rmul__(self, other): ...\n def __truediv__(self, other): ...\n def __rtruediv__(self, other): ...\n def __floordiv__(self, other): ...\n def __rfloordiv__(self, other): ...\n def __pow__(self, other, mod: None = None, /): ...\n def __rpow__(self, other, mod: None = None, /): ...\n\n # Keep in sync with `ndarray.__iadd__`\n @overload\n def __iadd__(\n self: _MaskedArray[np.bool], other: _ArrayLikeBool_co, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __iadd__(self: _MaskedArray[integer], other: _ArrayLikeInt_co, /) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __iadd__(\n self: _MaskedArray[floating], other: _ArrayLikeFloat_co, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __iadd__(\n self: _MaskedArray[complexfloating], other: _ArrayLikeComplex_co, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __iadd__(\n self: _MaskedArray[timedelta64 | datetime64], other: _ArrayLikeTD64_co, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __iadd__(self: _MaskedArray[bytes_], other: _ArrayLikeBytes_co, /) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __iadd__(\n self: MaskedArray[Any, dtype[str_] | dtypes.StringDType],\n other: _ArrayLikeStr_co | _ArrayLikeString_co,\n /,\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __iadd__(\n self: _MaskedArray[object_], other: Any, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n\n # Keep in sync with `ndarray.__isub__`\n @overload\n def __isub__(self: _MaskedArray[integer], other: _ArrayLikeInt_co, /) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __isub__(\n self: _MaskedArray[floating], other: _ArrayLikeFloat_co, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __isub__(\n self: _MaskedArray[complexfloating], other: _ArrayLikeComplex_co, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __isub__(\n self: _MaskedArray[timedelta64 | datetime64], other: _ArrayLikeTD64_co, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __isub__(\n self: _MaskedArray[object_], other: Any, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n\n # Keep in sync with `ndarray.__imul__`\n @overload\n def __imul__(\n self: _MaskedArray[np.bool], other: _ArrayLikeBool_co, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __imul__(\n self: MaskedArray[Any, dtype[integer] | dtype[character] | dtypes.StringDType], other: _ArrayLikeInt_co, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __imul__(\n self: _MaskedArray[floating | timedelta64], other: _ArrayLikeFloat_co, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __imul__(\n self: _MaskedArray[complexfloating], other: _ArrayLikeComplex_co, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __imul__(\n self: _MaskedArray[object_], other: Any, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n\n # Keep in sync with `ndarray.__ifloordiv__`\n @overload\n def __ifloordiv__(self: _MaskedArray[integer], other: _ArrayLikeInt_co, /) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __ifloordiv__(\n self: _MaskedArray[floating | timedelta64], other: _ArrayLikeFloat_co, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __ifloordiv__(\n self: _MaskedArray[object_], other: Any, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n\n # Keep in sync with `ndarray.__itruediv__`\n @overload\n def __itruediv__(\n self: _MaskedArray[floating | timedelta64], other: _ArrayLikeFloat_co, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __itruediv__(\n self: _MaskedArray[complexfloating],\n other: _ArrayLikeComplex_co,\n /,\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __itruediv__(\n self: _MaskedArray[object_], other: Any, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n\n # Keep in sync with `ndarray.__ipow__`\n @overload\n def __ipow__(self: _MaskedArray[integer], other: _ArrayLikeInt_co, /) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __ipow__(\n self: _MaskedArray[floating], other: _ArrayLikeFloat_co, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __ipow__(\n self: _MaskedArray[complexfloating], other: _ArrayLikeComplex_co, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n @overload\n def __ipow__(\n self: _MaskedArray[object_], other: Any, /\n ) -> MaskedArray[_ShapeT_co, _DTypeT_co]: ...\n\n #\n @property # type: ignore[misc]\n def imag(self: _HasDTypeWithRealAndImag[object, _ScalarT], /) -> MaskedArray[_ShapeT_co, dtype[_ScalarT]]: ...\n get_imag: Any\n @property # type: ignore[misc]\n def real(self: _HasDTypeWithRealAndImag[_ScalarT, object], /) -> MaskedArray[_ShapeT_co, dtype[_ScalarT]]: ...\n get_real: Any\n\n # keep in sync with `np.ma.count`\n @overload\n def count(self, axis: None = None, keepdims: Literal[False] | _NoValueType = ...) -> int: ...\n @overload\n def count(self, axis: _ShapeLike, keepdims: bool | _NoValueType = ...) -> NDArray[int_]: ...\n @overload\n def count(self, axis: _ShapeLike | None = ..., *, keepdims: Literal[True]) -> NDArray[int_]: ...\n @overload\n def count(self, axis: _ShapeLike | None, keepdims: Literal[True]) -> NDArray[int_]: ...\n\n def ravel(self, order: _OrderKACF = "C") -> MaskedArray[tuple[int], _DTypeT_co]: ...\n def reshape(self, *s, **kwargs): ...\n def resize(self, newshape, refcheck=..., order=...): ...\n def put(self, indices: _ArrayLikeInt_co, values: ArrayLike, mode: _ModeKind = "raise") -> None: ...\n def ids(self) -> tuple[int, int]: ...\n def iscontiguous(self) -> bool: ...\n\n @overload\n def all(\n self,\n axis: None = None,\n out: None = None,\n keepdims: Literal[False] | _NoValueType = ...,\n ) -> bool_: ...\n @overload\n def all(\n self,\n axis: _ShapeLike | None = None,\n out: None = None,\n *,\n keepdims: Literal[True],\n ) -> _MaskedArray[bool_]: ...\n @overload\n def all(\n self,\n axis: _ShapeLike | None,\n out: None,\n keepdims: Literal[True],\n ) -> _MaskedArray[bool_]: ...\n @overload\n def all(\n self,\n axis: _ShapeLike | None = None,\n out: None = None,\n keepdims: bool | _NoValueType = ...,\n ) -> bool_ | _MaskedArray[bool_]: ...\n @overload\n def all(\n self,\n axis: _ShapeLike | None = None,\n *,\n out: _ArrayT,\n keepdims: bool | _NoValueType = ...,\n ) -> _ArrayT: ...\n @overload\n def all(\n self,\n axis: _ShapeLike | None,\n out: _ArrayT,\n keepdims: bool | _NoValueType = ...,\n ) -> _ArrayT: ...\n\n @overload\n def any(\n self,\n axis: None = None,\n out: None = None,\n keepdims: Literal[False] | _NoValueType = ...,\n ) -> bool_: ...\n @overload\n def any(\n self,\n axis: _ShapeLike | None = None,\n out: None = None,\n *,\n keepdims: Literal[True],\n ) -> _MaskedArray[bool_]: ...\n @overload\n def any(\n self,\n axis: _ShapeLike | None,\n out: None,\n keepdims: Literal[True],\n ) -> _MaskedArray[bool_]: ...\n @overload\n def any(\n self,\n axis: _ShapeLike | None = None,\n out: None = None,\n keepdims: bool | _NoValueType = ...,\n ) -> bool_ | _MaskedArray[bool_]: ...\n @overload\n def any(\n self,\n axis: _ShapeLike | None = None,\n *,\n out: _ArrayT,\n keepdims: bool | _NoValueType = ...,\n ) -> _ArrayT: ...\n @overload\n def any(\n self,\n axis: _ShapeLike | None,\n out: _ArrayT,\n keepdims: bool | _NoValueType = ...,\n ) -> _ArrayT: ...\n\n def nonzero(self) -> tuple[_Array1D[intp], *tuple[_Array1D[intp], ...]]: ...\n def trace(self, offset=..., axis1=..., axis2=..., dtype=..., out=...): ...\n def dot(self, b, out=..., strict=...): ...\n def sum(self, axis=..., dtype=..., out=..., keepdims=...): ...\n def cumsum(self, axis=..., dtype=..., out=...): ...\n def prod(self, axis=..., dtype=..., out=..., keepdims=...): ...\n product: Any\n def cumprod(self, axis=..., dtype=..., out=...): ...\n def mean(self, axis=..., dtype=..., out=..., keepdims=...): ...\n def anom(self, axis=..., dtype=...): ...\n def var(self, axis=..., dtype=..., out=..., ddof=..., keepdims=...): ...\n def std(self, axis=..., dtype=..., out=..., ddof=..., keepdims=...): ...\n def round(self, decimals=..., out=...): ...\n def argsort(self, axis=..., kind=..., order=..., endwith=..., fill_value=..., *, stable=...): ...\n\n # Keep in-sync with np.ma.argmin\n @overload # type: ignore[override]\n def argmin(\n self,\n axis: None = None,\n fill_value: _ScalarLike_co | None = None,\n out: None = None,\n *,\n keepdims: Literal[False] | _NoValueType = ...,\n ) -> intp: ...\n @overload\n def argmin(\n self,\n axis: SupportsIndex | None = None,\n fill_value: _ScalarLike_co | None = None,\n out: None = None,\n *,\n keepdims: bool | _NoValueType = ...,\n ) -> Any: ...\n @overload\n def argmin(\n self,\n axis: SupportsIndex | None = None,\n fill_value: _ScalarLike_co | None = None,\n *,\n out: _ArrayT,\n keepdims: bool | _NoValueType = ...,\n ) -> _ArrayT: ...\n @overload\n def argmin(\n self,\n axis: SupportsIndex | None,\n fill_value: _ScalarLike_co | None,\n out: _ArrayT,\n *,\n keepdims: bool | _NoValueType = ...,\n ) -> _ArrayT: ...\n\n # Keep in-sync with np.ma.argmax\n @overload # type: ignore[override]\n def argmax(\n self,\n axis: None = None,\n fill_value: _ScalarLike_co | None = None,\n out: None = None,\n *,\n keepdims: Literal[False] | _NoValueType = ...,\n ) -> intp: ...\n @overload\n def argmax(\n self,\n axis: SupportsIndex | None = None,\n fill_value: _ScalarLike_co | None = None,\n out: None = None,\n *,\n keepdims: bool | _NoValueType = ...,\n ) -> Any: ...\n @overload\n def argmax(\n self,\n axis: SupportsIndex | None = None,\n fill_value: _ScalarLike_co | None = None,\n *,\n out: _ArrayT,\n keepdims: bool | _NoValueType = ...,\n ) -> _ArrayT: ...\n @overload\n def argmax(\n self,\n axis: SupportsIndex | None,\n fill_value: _ScalarLike_co | None,\n out: _ArrayT,\n *,\n keepdims: bool | _NoValueType = ...,\n ) -> _ArrayT: ...\n\n #\n def sort( # type: ignore[override]\n self,\n axis: SupportsIndex = -1,\n kind: _SortKind | None = None,\n order: str | Sequence[str] | None = None,\n endwith: bool | None = True,\n fill_value: _ScalarLike_co | None = None,\n *,\n stable: Literal[False] | None = False,\n ) -> None: ...\n\n #\n @overload # type: ignore[override]\n def min(\n self: _MaskedArray[_ScalarT],\n axis: None = None,\n out: None = None,\n fill_value: _ScalarLike_co | None = None,\n keepdims: Literal[False] | _NoValueType = ...,\n ) -> _ScalarT: ...\n @overload\n def min(\n self,\n axis: _ShapeLike | None = None,\n out: None = None,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool | _NoValueType = ...\n ) -> Any: ...\n @overload\n def min(\n self,\n axis: _ShapeLike | None,\n out: _ArrayT,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool | _NoValueType = ...,\n ) -> _ArrayT: ...\n @overload\n def min(\n self,\n axis: _ShapeLike | None = None,\n *,\n out: _ArrayT,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool | _NoValueType = ...,\n ) -> _ArrayT: ...\n\n #\n @overload # type: ignore[override]\n def max(\n self: _MaskedArray[_ScalarT],\n axis: None = None,\n out: None = None,\n fill_value: _ScalarLike_co | None = None,\n keepdims: Literal[False] | _NoValueType = ...,\n ) -> _ScalarT: ...\n @overload\n def max(\n self,\n axis: _ShapeLike | None = None,\n out: None = None,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool | _NoValueType = ...\n ) -> Any: ...\n @overload\n def max(\n self,\n axis: _ShapeLike | None,\n out: _ArrayT,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool | _NoValueType = ...,\n ) -> _ArrayT: ...\n @overload\n def max(\n self,\n axis: _ShapeLike | None = None,\n *,\n out: _ArrayT,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool | _NoValueType = ...,\n ) -> _ArrayT: ...\n\n #\n @overload\n def ptp(\n self: _MaskedArray[_ScalarT],\n axis: None = None,\n out: None = None,\n fill_value: _ScalarLike_co | None = None,\n keepdims: Literal[False] = False,\n ) -> _ScalarT: ...\n @overload\n def ptp(\n self,\n axis: _ShapeLike | None = None,\n out: None = None,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool = False,\n ) -> Any: ...\n @overload\n def ptp(\n self,\n axis: _ShapeLike | None,\n out: _ArrayT,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool = False,\n ) -> _ArrayT: ...\n @overload\n def ptp(\n self,\n axis: _ShapeLike | None = None,\n *,\n out: _ArrayT,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool = False,\n ) -> _ArrayT: ...\n\n #\n @overload\n def partition(\n self,\n /,\n kth: _ArrayLikeInt,\n axis: SupportsIndex = -1,\n kind: _PartitionKind = "introselect",\n order: None = None\n ) -> None: ...\n @overload\n def partition(\n self: _MaskedArray[np.void],\n /,\n kth: _ArrayLikeInt,\n axis: SupportsIndex = -1,\n kind: _PartitionKind = "introselect",\n order: str | Sequence[str] | None = None,\n ) -> None: ...\n\n #\n @overload\n def argpartition(\n self,\n /,\n kth: _ArrayLikeInt,\n axis: SupportsIndex | None = -1,\n kind: _PartitionKind = "introselect",\n order: None = None,\n ) -> _MaskedArray[intp]: ...\n @overload\n def argpartition(\n self: _MaskedArray[np.void],\n /,\n kth: _ArrayLikeInt,\n axis: SupportsIndex | None = -1,\n kind: _PartitionKind = "introselect",\n order: str | Sequence[str] | None = None,\n ) -> _MaskedArray[intp]: ...\n\n # Keep in-sync with np.ma.take\n @overload\n def take( # type: ignore[overload-overlap]\n self: _MaskedArray[_ScalarT],\n indices: _IntLike_co,\n axis: None = None,\n out: None = None,\n mode: _ModeKind = 'raise'\n ) -> _ScalarT: ...\n @overload\n def take(\n self: _MaskedArray[_ScalarT],\n indices: _ArrayLikeInt_co,\n axis: SupportsIndex | None = None,\n out: None = None,\n mode: _ModeKind = 'raise',\n ) -> _MaskedArray[_ScalarT]: ...\n @overload\n def take(\n self,\n indices: _ArrayLikeInt_co,\n axis: SupportsIndex | None,\n out: _ArrayT,\n mode: _ModeKind = 'raise',\n ) -> _ArrayT: ...\n @overload\n def take(\n self,\n indices: _ArrayLikeInt_co,\n axis: SupportsIndex | None = None,\n *,\n out: _ArrayT,\n mode: _ModeKind = 'raise',\n ) -> _ArrayT: ...\n\n copy: Any\n diagonal: Any\n flatten: Any\n\n @overload\n def repeat(\n self,\n repeats: _ArrayLikeInt_co,\n axis: None = None,\n ) -> MaskedArray[tuple[int], _DTypeT_co]: ...\n @overload\n def repeat(\n self,\n repeats: _ArrayLikeInt_co,\n axis: SupportsIndex,\n ) -> MaskedArray[_AnyShape, _DTypeT_co]: ...\n\n squeeze: Any\n\n def swapaxes(\n self,\n axis1: SupportsIndex,\n axis2: SupportsIndex,\n /\n ) -> MaskedArray[_AnyShape, _DTypeT_co]: ...\n\n #\n def toflex(self) -> Incomplete: ...\n def torecords(self) -> Incomplete: ...\n def tolist(self, fill_value: Incomplete | None = None) -> Incomplete: ...\n def tobytes(self, /, fill_value: Incomplete | None = None, order: _OrderKACF = "C") -> bytes: ... # type: ignore[override]\n def tofile(self, /, fid: Incomplete, sep: str = "", format: str = "%s") -> Incomplete: ...\n\n #\n def __reduce__(self): ...\n def __deepcopy__(self, memo=...): ...\n\n # Keep `dtype` at the bottom to avoid name conflicts with `np.dtype`\n @property\n def dtype(self) -> _DTypeT_co: ...\n @dtype.setter\n def dtype(self: MaskedArray[_AnyShape, _DTypeT], dtype: _DTypeT, /) -> None: ...\n\nclass mvoid(MaskedArray[_ShapeT_co, _DTypeT_co]):\n def __new__(\n self, # pyright: ignore[reportSelfClsParameterName]\n data,\n mask=...,\n dtype=...,\n fill_value=...,\n hardmask=...,\n copy=...,\n subok=...,\n ): ...\n def __getitem__(self, indx): ...\n def __setitem__(self, indx, value): ...\n def __iter__(self): ...\n def __len__(self): ...\n def filled(self, fill_value=...): ...\n def tolist(self): ...\n\ndef isMaskedArray(x): ...\nisarray = isMaskedArray\nisMA = isMaskedArray\n\n# 0D float64 array\nclass MaskedConstant(MaskedArray[_AnyShape, dtype[float64]]):\n def __new__(cls): ...\n __class__: Any\n def __array_finalize__(self, obj): ...\n def __array_wrap__(self, obj, context=..., return_scalar=...): ...\n def __format__(self, format_spec): ...\n def __reduce__(self): ...\n def __iop__(self, other): ...\n __iadd__: Any\n __isub__: Any\n __imul__: Any\n __ifloordiv__: Any\n __itruediv__: Any\n __ipow__: Any\n def copy(self, *args, **kwargs): ...\n def __copy__(self): ...\n def __deepcopy__(self, memo): ...\n def __setattr__(self, attr, value): ...\n\nmasked: MaskedConstant\nmasked_singleton: MaskedConstant\nmasked_array = MaskedArray\n\ndef array(\n data,\n dtype=...,\n copy=...,\n order=...,\n mask=...,\n fill_value=...,\n keep_mask=...,\n hard_mask=...,\n shrink=...,\n subok=...,\n ndmin=...,\n): ...\ndef is_masked(x: object) -> bool: ...\n\nclass _extrema_operation(_MaskedUFunc):\n compare: Any\n fill_value_func: Any\n def __init__(self, ufunc, compare, fill_value): ...\n # NOTE: in practice `b` has a default value, but users should\n # explicitly provide a value here as the default is deprecated\n def __call__(self, a, b): ...\n def reduce(self, target, axis=...): ...\n def outer(self, a, b): ...\n\n@overload\ndef min(\n obj: _ArrayLike[_ScalarT],\n axis: None = None,\n out: None = None,\n fill_value: _ScalarLike_co | None = None,\n keepdims: Literal[False] | _NoValueType = ...,\n) -> _ScalarT: ...\n@overload\ndef min(\n obj: ArrayLike,\n axis: _ShapeLike | None = None,\n out: None = None,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool | _NoValueType = ...\n) -> Any: ...\n@overload\ndef min(\n obj: ArrayLike,\n axis: _ShapeLike | None,\n out: _ArrayT,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool | _NoValueType = ...,\n) -> _ArrayT: ...\n@overload\ndef min(\n obj: ArrayLike,\n axis: _ShapeLike | None = None,\n *,\n out: _ArrayT,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool | _NoValueType = ...,\n) -> _ArrayT: ...\n\n@overload\ndef max(\n obj: _ArrayLike[_ScalarT],\n axis: None = None,\n out: None = None,\n fill_value: _ScalarLike_co | None = None,\n keepdims: Literal[False] | _NoValueType = ...,\n) -> _ScalarT: ...\n@overload\ndef max(\n obj: ArrayLike,\n axis: _ShapeLike | None = None,\n out: None = None,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool | _NoValueType = ...\n) -> Any: ...\n@overload\ndef max(\n obj: ArrayLike,\n axis: _ShapeLike | None,\n out: _ArrayT,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool | _NoValueType = ...,\n) -> _ArrayT: ...\n@overload\ndef max(\n obj: ArrayLike,\n axis: _ShapeLike | None = None,\n *,\n out: _ArrayT,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool | _NoValueType = ...,\n) -> _ArrayT: ...\n\n@overload\ndef ptp(\n obj: _ArrayLike[_ScalarT],\n axis: None = None,\n out: None = None,\n fill_value: _ScalarLike_co | None = None,\n keepdims: Literal[False] | _NoValueType = ...,\n) -> _ScalarT: ...\n@overload\ndef ptp(\n obj: ArrayLike,\n axis: _ShapeLike | None = None,\n out: None = None,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool | _NoValueType = ...\n) -> Any: ...\n@overload\ndef ptp(\n obj: ArrayLike,\n axis: _ShapeLike | None,\n out: _ArrayT,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool | _NoValueType = ...,\n) -> _ArrayT: ...\n@overload\ndef ptp(\n obj: ArrayLike,\n axis: _ShapeLike | None = None,\n *,\n out: _ArrayT,\n fill_value: _ScalarLike_co | None = None,\n keepdims: bool | _NoValueType = ...,\n) -> _ArrayT: ...\n\nclass _frommethod:\n __name__: Any\n __doc__: Any\n reversed: Any\n def __init__(self, methodname, reversed=...): ...\n def getdoc(self): ...\n def __call__(self, a, *args, **params): ...\n\nall: _frommethod\nanomalies: _frommethod\nanom: _frommethod\nany: _frommethod\ncompress: _frommethod\ncumprod: _frommethod\ncumsum: _frommethod\ncopy: _frommethod\ndiagonal: _frommethod\nharden_mask: _frommethod\nids: _frommethod\nmean: _frommethod\nnonzero: _frommethod\nprod: _frommethod\nproduct: _frommethod\nravel: _frommethod\nrepeat: _frommethod\nsoften_mask: _frommethod\nstd: _frommethod\nsum: _frommethod\nswapaxes: _frommethod\ntrace: _frommethod\nvar: _frommethod\n\n@overload\ndef count(self: ArrayLike, axis: None = None, keepdims: Literal[False] | _NoValueType = ...) -> int: ...\n@overload\ndef count(self: ArrayLike, axis: _ShapeLike, keepdims: bool | _NoValueType = ...) -> NDArray[int_]: ...\n@overload\ndef count(self: ArrayLike, axis: _ShapeLike | None = ..., *, keepdims: Literal[True]) -> NDArray[int_]: ...\n@overload\ndef count(self: ArrayLike, axis: _ShapeLike | None, keepdims: Literal[True]) -> NDArray[int_]: ...\n\n@overload\ndef argmin(\n self: ArrayLike,\n axis: None = None,\n fill_value: _ScalarLike_co | None = None,\n out: None = None,\n *,\n keepdims: Literal[False] | _NoValueType = ...,\n) -> intp: ...\n@overload\ndef argmin(\n self: ArrayLike,\n axis: SupportsIndex | None = None,\n fill_value: _ScalarLike_co | None = None,\n out: None = None,\n *,\n keepdims: bool | _NoValueType = ...,\n) -> Any: ...\n@overload\ndef argmin(\n self: ArrayLike,\n axis: SupportsIndex | None = None,\n fill_value: _ScalarLike_co | None = None,\n *,\n out: _ArrayT,\n keepdims: bool | _NoValueType = ...,\n) -> _ArrayT: ...\n@overload\ndef argmin(\n self: ArrayLike,\n axis: SupportsIndex | None,\n fill_value: _ScalarLike_co | None,\n out: _ArrayT,\n *,\n keepdims: bool | _NoValueType = ...,\n) -> _ArrayT: ...\n\n#\n@overload\ndef argmax(\n self: ArrayLike,\n axis: None = None,\n fill_value: _ScalarLike_co | None = None,\n out: None = None,\n *,\n keepdims: Literal[False] | _NoValueType = ...,\n) -> intp: ...\n@overload\ndef argmax(\n self: ArrayLike,\n axis: SupportsIndex | None = None,\n fill_value: _ScalarLike_co | None = None,\n out: None = None,\n *,\n keepdims: bool | _NoValueType = ...,\n) -> Any: ...\n@overload\ndef argmax(\n self: ArrayLike,\n axis: SupportsIndex | None = None,\n fill_value: _ScalarLike_co | None = None,\n *,\n out: _ArrayT,\n keepdims: bool | _NoValueType = ...,\n) -> _ArrayT: ...\n@overload\ndef argmax(\n self: ArrayLike,\n axis: SupportsIndex | None,\n fill_value: _ScalarLike_co | None,\n out: _ArrayT,\n *,\n keepdims: bool | _NoValueType = ...,\n) -> _ArrayT: ...\n\nminimum: _extrema_operation\nmaximum: _extrema_operation\n\n@overload\ndef take(\n a: _ArrayLike[_ScalarT],\n indices: _IntLike_co,\n axis: None = None,\n out: None = None,\n mode: _ModeKind = 'raise'\n) -> _ScalarT: ...\n@overload\ndef take(\n a: _ArrayLike[_ScalarT],\n indices: _ArrayLikeInt_co,\n axis: SupportsIndex | None = None,\n out: None = None,\n mode: _ModeKind = 'raise',\n) -> _MaskedArray[_ScalarT]: ...\n@overload\ndef take(\n a: ArrayLike,\n indices: _IntLike_co,\n axis: SupportsIndex | None = None,\n out: None = None,\n mode: _ModeKind = 'raise',\n) -> Any: ...\n@overload\ndef take(\n a: ArrayLike,\n indices: _ArrayLikeInt_co,\n axis: SupportsIndex | None = None,\n out: None = None,\n mode: _ModeKind = 'raise',\n) -> _MaskedArray[Any]: ...\n@overload\ndef take(\n a: ArrayLike,\n indices: _ArrayLikeInt_co,\n axis: SupportsIndex | None,\n out: _ArrayT,\n mode: _ModeKind = 'raise',\n) -> _ArrayT: ...\n@overload\ndef take(\n a: ArrayLike,\n indices: _ArrayLikeInt_co,\n axis: SupportsIndex | None = None,\n *,\n out: _ArrayT,\n mode: _ModeKind = 'raise',\n) -> _ArrayT: ...\n\ndef power(a, b, third=...): ...\ndef argsort(a, axis=..., kind=..., order=..., endwith=..., fill_value=..., *, stable=...): ...\n@overload\ndef sort(\n a: _ArrayT,\n axis: SupportsIndex = -1,\n kind: _SortKind | None = None,\n order: str | Sequence[str] | None = None,\n endwith: bool | None = True,\n fill_value: _ScalarLike_co | None = None,\n *,\n stable: Literal[False] | None = False,\n) -> _ArrayT: ...\n@overload\ndef sort(\n a: ArrayLike,\n axis: SupportsIndex = -1,\n kind: _SortKind | None = None,\n order: str | Sequence[str] | None = None,\n endwith: bool | None = True,\n fill_value: _ScalarLike_co | None = None,\n *,\n stable: Literal[False] | None = False,\n) -> NDArray[Any]: ...\n@overload\ndef compressed(x: _ArrayLike[_ScalarT_co]) -> _Array1D[_ScalarT_co]: ...\n@overload\ndef compressed(x: ArrayLike) -> _Array1D[Any]: ...\ndef concatenate(arrays, axis=...): ...\ndef diag(v, k=...): ...\ndef left_shift(a, n): ...\ndef right_shift(a, n): ...\ndef put(a: NDArray[Any], indices: _ArrayLikeInt_co, values: ArrayLike, mode: _ModeKind = 'raise') -> None: ...\ndef putmask(a: NDArray[Any], mask: _ArrayLikeBool_co, values: ArrayLike) -> None: ...\ndef transpose(a, axes=...): ...\ndef reshape(a, new_shape, order=...): ...\ndef resize(x, new_shape): ...\ndef ndim(obj: ArrayLike) -> int: ...\ndef shape(obj): ...\ndef size(obj: ArrayLike, axis: SupportsIndex | None = None) -> int: ...\ndef diff(a, /, n=..., axis=..., prepend=..., append=...): ...\ndef where(condition, x=..., y=...): ...\ndef choose(indices, choices, out=..., mode=...): ...\ndef round_(a, decimals=..., out=...): ...\nround = round_\n\ndef inner(a, b): ...\ninnerproduct = inner\n\ndef outer(a, b): ...\nouterproduct = outer\n\ndef correlate(a, v, mode=..., propagate_mask=...): ...\ndef convolve(a, v, mode=..., propagate_mask=...): ...\n\ndef allequal(a: ArrayLike, b: ArrayLike, fill_value: bool = True) -> bool: ...\n\ndef allclose(a: ArrayLike, b: ArrayLike, masked_equal: bool = True, rtol: float = 1e-5, atol: float = 1e-8) -> bool: ...\n\ndef asarray(a, dtype=..., order=...): ...\ndef asanyarray(a, dtype=...): ...\ndef fromflex(fxarray): ...\n\nclass _convert2ma:\n def __init__(self, /, funcname: str, np_ret: str, np_ma_ret: str, params: dict[str, Any] | None = None) -> None: ...\n def __call__(self, /, *args: object, **params: object) -> Any: ...\n def getdoc(self, /, np_ret: str, np_ma_ret: str) -> str | None: ...\n\narange: _convert2ma\nclip: _convert2ma\nempty: _convert2ma\nempty_like: _convert2ma\nfrombuffer: _convert2ma\nfromfunction: _convert2ma\nidentity: _convert2ma\nindices: _convert2ma\nones: _convert2ma\nones_like: _convert2ma\nsqueeze: _convert2ma\nzeros: _convert2ma\nzeros_like: _convert2ma\n\ndef append(a, b, axis=...): ...\ndef dot(a, b, strict=..., out=...): ...\ndef mask_rowcols(a, axis=...): ...\n | .venv\Lib\site-packages\numpy\ma\core.pyi | core.pyi | Other | 41,921 | 0.95 | 0.216826 | 0.043447 | node-utils | 639 | 2025-05-23T15:36:27.364172 | MIT | false | d774717a75ef5d8871eab0bc7fc75c90 |
"""\nMasked arrays add-ons.\n\nA collection of utilities for `numpy.ma`.\n\n:author: Pierre Gerard-Marchant\n:contact: pierregm_at_uga_dot_edu\n\n"""\n__all__ = [\n 'apply_along_axis', 'apply_over_axes', 'atleast_1d', 'atleast_2d',\n 'atleast_3d', 'average', 'clump_masked', 'clump_unmasked', 'column_stack',\n 'compress_cols', 'compress_nd', 'compress_rowcols', 'compress_rows',\n 'count_masked', 'corrcoef', 'cov', 'diagflat', 'dot', 'dstack', 'ediff1d',\n 'flatnotmasked_contiguous', 'flatnotmasked_edges', 'hsplit', 'hstack',\n 'isin', 'in1d', 'intersect1d', 'mask_cols', 'mask_rowcols', 'mask_rows',\n 'masked_all', 'masked_all_like', 'median', 'mr_', 'ndenumerate',\n 'notmasked_contiguous', 'notmasked_edges', 'polyfit', 'row_stack',\n 'setdiff1d', 'setxor1d', 'stack', 'unique', 'union1d', 'vander', 'vstack',\n ]\n\nimport itertools\nimport warnings\n\nimport numpy as np\nfrom numpy import array as nxarray\nfrom numpy import ndarray\nfrom numpy.lib._function_base_impl import _ureduce\nfrom numpy.lib._index_tricks_impl import AxisConcatenator\nfrom numpy.lib.array_utils import normalize_axis_index, normalize_axis_tuple\n\nfrom . import core as ma\nfrom .core import ( # noqa: F401\n MAError,\n MaskedArray,\n add,\n array,\n asarray,\n concatenate,\n count,\n dot,\n filled,\n get_masked_subclass,\n getdata,\n getmask,\n getmaskarray,\n make_mask_descr,\n mask_or,\n masked,\n masked_array,\n nomask,\n ones,\n sort,\n zeros,\n)\n\n\ndef issequence(seq):\n """\n Is seq a sequence (ndarray, list or tuple)?\n\n """\n return isinstance(seq, (ndarray, tuple, list))\n\n\ndef count_masked(arr, axis=None):\n """\n Count the number of masked elements along the given axis.\n\n Parameters\n ----------\n arr : array_like\n An array with (possibly) masked elements.\n axis : int, optional\n Axis along which to count. If None (default), a flattened\n version of the array is used.\n\n Returns\n -------\n count : int, ndarray\n The total number of masked elements (axis=None) or the number\n of masked elements along each slice of the given axis.\n\n See Also\n --------\n MaskedArray.count : Count non-masked elements.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.arange(9).reshape((3,3))\n >>> a = np.ma.array(a)\n >>> a[1, 0] = np.ma.masked\n >>> a[1, 2] = np.ma.masked\n >>> a[2, 1] = np.ma.masked\n >>> a\n masked_array(\n data=[[0, 1, 2],\n [--, 4, --],\n [6, --, 8]],\n mask=[[False, False, False],\n [ True, False, True],\n [False, True, False]],\n fill_value=999999)\n >>> np.ma.count_masked(a)\n 3\n\n When the `axis` keyword is used an array is returned.\n\n >>> np.ma.count_masked(a, axis=0)\n array([1, 1, 1])\n >>> np.ma.count_masked(a, axis=1)\n array([0, 2, 1])\n\n """\n m = getmaskarray(arr)\n return m.sum(axis)\n\n\ndef masked_all(shape, dtype=float):\n """\n Empty masked array with all elements masked.\n\n Return an empty masked array of the given shape and dtype, where all the\n data are masked.\n\n Parameters\n ----------\n shape : int or tuple of ints\n Shape of the required MaskedArray, e.g., ``(2, 3)`` or ``2``.\n dtype : dtype, optional\n Data type of the output.\n\n Returns\n -------\n a : MaskedArray\n A masked array with all data masked.\n\n See Also\n --------\n masked_all_like : Empty masked array modelled on an existing array.\n\n Notes\n -----\n Unlike other masked array creation functions (e.g. `numpy.ma.zeros`,\n `numpy.ma.ones`, `numpy.ma.full`), `masked_all` does not initialize the\n values of the array, and may therefore be marginally faster. However,\n the values stored in the newly allocated array are arbitrary. For\n reproducible behavior, be sure to set each element of the array before\n reading.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.ma.masked_all((3, 3))\n masked_array(\n data=[[--, --, --],\n [--, --, --],\n [--, --, --]],\n mask=[[ True, True, True],\n [ True, True, True],\n [ True, True, True]],\n fill_value=1e+20,\n dtype=float64)\n\n The `dtype` parameter defines the underlying data type.\n\n >>> a = np.ma.masked_all((3, 3))\n >>> a.dtype\n dtype('float64')\n >>> a = np.ma.masked_all((3, 3), dtype=np.int32)\n >>> a.dtype\n dtype('int32')\n\n """\n a = masked_array(np.empty(shape, dtype),\n mask=np.ones(shape, make_mask_descr(dtype)))\n return a\n\n\ndef masked_all_like(arr):\n """\n Empty masked array with the properties of an existing array.\n\n Return an empty masked array of the same shape and dtype as\n the array `arr`, where all the data are masked.\n\n Parameters\n ----------\n arr : ndarray\n An array describing the shape and dtype of the required MaskedArray.\n\n Returns\n -------\n a : MaskedArray\n A masked array with all data masked.\n\n Raises\n ------\n AttributeError\n If `arr` doesn't have a shape attribute (i.e. not an ndarray)\n\n See Also\n --------\n masked_all : Empty masked array with all elements masked.\n\n Notes\n -----\n Unlike other masked array creation functions (e.g. `numpy.ma.zeros_like`,\n `numpy.ma.ones_like`, `numpy.ma.full_like`), `masked_all_like` does not\n initialize the values of the array, and may therefore be marginally\n faster. However, the values stored in the newly allocated array are\n arbitrary. For reproducible behavior, be sure to set each element of the\n array before reading.\n\n Examples\n --------\n >>> import numpy as np\n >>> arr = np.zeros((2, 3), dtype=np.float32)\n >>> arr\n array([[0., 0., 0.],\n [0., 0., 0.]], dtype=float32)\n >>> np.ma.masked_all_like(arr)\n masked_array(\n data=[[--, --, --],\n [--, --, --]],\n mask=[[ True, True, True],\n [ True, True, True]],\n fill_value=np.float64(1e+20),\n dtype=float32)\n\n The dtype of the masked array matches the dtype of `arr`.\n\n >>> arr.dtype\n dtype('float32')\n >>> np.ma.masked_all_like(arr).dtype\n dtype('float32')\n\n """\n a = np.empty_like(arr).view(MaskedArray)\n a._mask = np.ones(a.shape, dtype=make_mask_descr(a.dtype))\n return a\n\n\n#####--------------------------------------------------------------------------\n#---- --- Standard functions ---\n#####--------------------------------------------------------------------------\nclass _fromnxfunction:\n """\n Defines a wrapper to adapt NumPy functions to masked arrays.\n\n\n An instance of `_fromnxfunction` can be called with the same parameters\n as the wrapped NumPy function. The docstring of `newfunc` is adapted from\n the wrapped function as well, see `getdoc`.\n\n This class should not be used directly. Instead, one of its extensions that\n provides support for a specific type of input should be used.\n\n Parameters\n ----------\n funcname : str\n The name of the function to be adapted. The function should be\n in the NumPy namespace (i.e. ``np.funcname``).\n\n """\n\n def __init__(self, funcname):\n self.__name__ = funcname\n self.__qualname__ = funcname\n self.__doc__ = self.getdoc()\n\n def getdoc(self):\n """\n Retrieve the docstring and signature from the function.\n\n The ``__doc__`` attribute of the function is used as the docstring for\n the new masked array version of the function. A note on application\n of the function to the mask is appended.\n\n Parameters\n ----------\n None\n\n """\n npfunc = getattr(np, self.__name__, None)\n doc = getattr(npfunc, '__doc__', None)\n if doc:\n sig = ma.get_object_signature(npfunc)\n doc = ma.doc_note(doc, "The function is applied to both the _data "\n "and the _mask, if any.")\n if sig:\n sig = self.__name__ + sig + "\n\n"\n return sig + doc\n return\n\n def __call__(self, *args, **params):\n pass\n\n\nclass _fromnxfunction_single(_fromnxfunction):\n """\n A version of `_fromnxfunction` that is called with a single array\n argument followed by auxiliary args that are passed verbatim for\n both the data and mask calls.\n """\n def __call__(self, x, *args, **params):\n func = getattr(np, self.__name__)\n if isinstance(x, ndarray):\n _d = func(x.__array__(), *args, **params)\n _m = func(getmaskarray(x), *args, **params)\n return masked_array(_d, mask=_m)\n else:\n _d = func(np.asarray(x), *args, **params)\n _m = func(getmaskarray(x), *args, **params)\n return masked_array(_d, mask=_m)\n\n\nclass _fromnxfunction_seq(_fromnxfunction):\n """\n A version of `_fromnxfunction` that is called with a single sequence\n of arrays followed by auxiliary args that are passed verbatim for\n both the data and mask calls.\n """\n def __call__(self, x, *args, **params):\n func = getattr(np, self.__name__)\n _d = func(tuple(np.asarray(a) for a in x), *args, **params)\n _m = func(tuple(getmaskarray(a) for a in x), *args, **params)\n return masked_array(_d, mask=_m)\n\n\nclass _fromnxfunction_args(_fromnxfunction):\n """\n A version of `_fromnxfunction` that is called with multiple array\n arguments. The first non-array-like input marks the beginning of the\n arguments that are passed verbatim for both the data and mask calls.\n Array arguments are processed independently and the results are\n returned in a list. If only one array is found, the return value is\n just the processed array instead of a list.\n """\n def __call__(self, *args, **params):\n func = getattr(np, self.__name__)\n arrays = []\n args = list(args)\n while len(args) > 0 and issequence(args[0]):\n arrays.append(args.pop(0))\n res = []\n for x in arrays:\n _d = func(np.asarray(x), *args, **params)\n _m = func(getmaskarray(x), *args, **params)\n res.append(masked_array(_d, mask=_m))\n if len(arrays) == 1:\n return res[0]\n return res\n\n\nclass _fromnxfunction_allargs(_fromnxfunction):\n """\n A version of `_fromnxfunction` that is called with multiple array\n arguments. Similar to `_fromnxfunction_args` except that all args\n are converted to arrays even if they are not so already. This makes\n it possible to process scalars as 1-D arrays. Only keyword arguments\n are passed through verbatim for the data and mask calls. Arrays\n arguments are processed independently and the results are returned\n in a list. If only one arg is present, the return value is just the\n processed array instead of a list.\n """\n def __call__(self, *args, **params):\n func = getattr(np, self.__name__)\n res = []\n for x in args:\n _d = func(np.asarray(x), **params)\n _m = func(getmaskarray(x), **params)\n res.append(masked_array(_d, mask=_m))\n if len(args) == 1:\n return res[0]\n return res\n\n\natleast_1d = _fromnxfunction_allargs('atleast_1d')\natleast_2d = _fromnxfunction_allargs('atleast_2d')\natleast_3d = _fromnxfunction_allargs('atleast_3d')\n\nvstack = row_stack = _fromnxfunction_seq('vstack')\nhstack = _fromnxfunction_seq('hstack')\ncolumn_stack = _fromnxfunction_seq('column_stack')\ndstack = _fromnxfunction_seq('dstack')\nstack = _fromnxfunction_seq('stack')\n\nhsplit = _fromnxfunction_single('hsplit')\n\ndiagflat = _fromnxfunction_single('diagflat')\n\n\n#####--------------------------------------------------------------------------\n#----\n#####--------------------------------------------------------------------------\ndef flatten_inplace(seq):\n """Flatten a sequence in place."""\n k = 0\n while (k != len(seq)):\n while hasattr(seq[k], '__iter__'):\n seq[k:(k + 1)] = seq[k]\n k += 1\n return seq\n\n\ndef apply_along_axis(func1d, axis, arr, *args, **kwargs):\n """\n (This docstring should be overwritten)\n """\n arr = array(arr, copy=False, subok=True)\n nd = arr.ndim\n axis = normalize_axis_index(axis, nd)\n ind = [0] * (nd - 1)\n i = np.zeros(nd, 'O')\n indlist = list(range(nd))\n indlist.remove(axis)\n i[axis] = slice(None, None)\n outshape = np.asarray(arr.shape).take(indlist)\n i.put(indlist, ind)\n res = func1d(arr[tuple(i.tolist())], *args, **kwargs)\n # if res is a number, then we have a smaller output array\n asscalar = np.isscalar(res)\n if not asscalar:\n try:\n len(res)\n except TypeError:\n asscalar = True\n # Note: we shouldn't set the dtype of the output from the first result\n # so we force the type to object, and build a list of dtypes. We'll\n # just take the largest, to avoid some downcasting\n dtypes = []\n if asscalar:\n dtypes.append(np.asarray(res).dtype)\n outarr = zeros(outshape, object)\n outarr[tuple(ind)] = res\n Ntot = np.prod(outshape)\n k = 1\n while k < Ntot:\n # increment the index\n ind[-1] += 1\n n = -1\n while (ind[n] >= outshape[n]) and (n > (1 - nd)):\n ind[n - 1] += 1\n ind[n] = 0\n n -= 1\n i.put(indlist, ind)\n res = func1d(arr[tuple(i.tolist())], *args, **kwargs)\n outarr[tuple(ind)] = res\n dtypes.append(asarray(res).dtype)\n k += 1\n else:\n res = array(res, copy=False, subok=True)\n j = i.copy()\n j[axis] = ([slice(None, None)] * res.ndim)\n j.put(indlist, ind)\n Ntot = np.prod(outshape)\n holdshape = outshape\n outshape = list(arr.shape)\n outshape[axis] = res.shape\n dtypes.append(asarray(res).dtype)\n outshape = flatten_inplace(outshape)\n outarr = zeros(outshape, object)\n outarr[tuple(flatten_inplace(j.tolist()))] = res\n k = 1\n while k < Ntot:\n # increment the index\n ind[-1] += 1\n n = -1\n while (ind[n] >= holdshape[n]) and (n > (1 - nd)):\n ind[n - 1] += 1\n ind[n] = 0\n n -= 1\n i.put(indlist, ind)\n j.put(indlist, ind)\n res = func1d(arr[tuple(i.tolist())], *args, **kwargs)\n outarr[tuple(flatten_inplace(j.tolist()))] = res\n dtypes.append(asarray(res).dtype)\n k += 1\n max_dtypes = np.dtype(np.asarray(dtypes).max())\n if not hasattr(arr, '_mask'):\n result = np.asarray(outarr, dtype=max_dtypes)\n else:\n result = asarray(outarr, dtype=max_dtypes)\n result.fill_value = ma.default_fill_value(result)\n return result\n\n\napply_along_axis.__doc__ = np.apply_along_axis.__doc__\n\n\ndef apply_over_axes(func, a, axes):\n """\n (This docstring will be overwritten)\n """\n val = asarray(a)\n N = a.ndim\n if array(axes).ndim == 0:\n axes = (axes,)\n for axis in axes:\n if axis < 0:\n axis = N + axis\n args = (val, axis)\n res = func(*args)\n if res.ndim == val.ndim:\n val = res\n else:\n res = ma.expand_dims(res, axis)\n if res.ndim == val.ndim:\n val = res\n else:\n raise ValueError("function is not returning "\n "an array of the correct shape")\n return val\n\n\nif apply_over_axes.__doc__ is not None:\n apply_over_axes.__doc__ = np.apply_over_axes.__doc__[\n :np.apply_over_axes.__doc__.find('Notes')].rstrip() + \\n """\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.ma.arange(24).reshape(2,3,4)\n >>> a[:,0,1] = np.ma.masked\n >>> a[:,1,:] = np.ma.masked\n >>> a\n masked_array(\n data=[[[0, --, 2, 3],\n [--, --, --, --],\n [8, 9, 10, 11]],\n [[12, --, 14, 15],\n [--, --, --, --],\n [20, 21, 22, 23]]],\n mask=[[[False, True, False, False],\n [ True, True, True, True],\n [False, False, False, False]],\n [[False, True, False, False],\n [ True, True, True, True],\n [False, False, False, False]]],\n fill_value=999999)\n >>> np.ma.apply_over_axes(np.ma.sum, a, [0,2])\n masked_array(\n data=[[[46],\n [--],\n [124]]],\n mask=[[[False],\n [ True],\n [False]]],\n fill_value=999999)\n\n Tuple axis arguments to ufuncs are equivalent:\n\n >>> np.ma.sum(a, axis=(0,2)).reshape((1,-1,1))\n masked_array(\n data=[[[46],\n [--],\n [124]]],\n mask=[[[False],\n [ True],\n [False]]],\n fill_value=999999)\n """\n\n\ndef average(a, axis=None, weights=None, returned=False, *,\n keepdims=np._NoValue):\n """\n Return the weighted average of array over the given axis.\n\n Parameters\n ----------\n a : array_like\n Data to be averaged.\n Masked entries are not taken into account in the computation.\n axis : None or int or tuple of ints, optional\n Axis or axes along which to average `a`. The default,\n `axis=None`, will average over all of the elements of the input array.\n If axis is a tuple of ints, averaging is performed on all of the axes\n specified in the tuple instead of a single axis or all the axes as\n before.\n weights : array_like, optional\n An array of weights associated with the values in `a`. Each value in\n `a` contributes to the average according to its associated weight.\n The array of weights must be the same shape as `a` if no axis is\n specified, otherwise the weights must have dimensions and shape\n consistent with `a` along the specified axis.\n If `weights=None`, then all data in `a` are assumed to have a\n weight equal to one.\n The calculation is::\n\n avg = sum(a * weights) / sum(weights)\n\n where the sum is over all included elements.\n The only constraint on the values of `weights` is that `sum(weights)`\n must not be 0.\n returned : bool, optional\n Flag indicating whether a tuple ``(result, sum of weights)``\n should be returned as output (True), or just the result (False).\n Default is False.\n keepdims : bool, optional\n If this is set to True, the axes which are reduced are left\n in the result as dimensions with size one. With this option,\n the result will broadcast correctly against the original `a`.\n *Note:* `keepdims` will not work with instances of `numpy.matrix`\n or other classes whose methods do not support `keepdims`.\n\n .. versionadded:: 1.23.0\n\n Returns\n -------\n average, [sum_of_weights] : (tuple of) scalar or MaskedArray\n The average along the specified axis. When returned is `True`,\n return a tuple with the average as the first element and the sum\n of the weights as the second element. The return type is `np.float64`\n if `a` is of integer type and floats smaller than `float64`, or the\n input data-type, otherwise. If returned, `sum_of_weights` is always\n `float64`.\n\n Raises\n ------\n ZeroDivisionError\n When all weights along axis are zero. See `numpy.ma.average` for a\n version robust to this type of error.\n TypeError\n When `weights` does not have the same shape as `a`, and `axis=None`.\n ValueError\n When `weights` does not have dimensions and shape consistent with `a`\n along specified `axis`.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.ma.array([1., 2., 3., 4.], mask=[False, False, True, True])\n >>> np.ma.average(a, weights=[3, 1, 0, 0])\n 1.25\n\n >>> x = np.ma.arange(6.).reshape(3, 2)\n >>> x\n masked_array(\n data=[[0., 1.],\n [2., 3.],\n [4., 5.]],\n mask=False,\n fill_value=1e+20)\n >>> data = np.arange(8).reshape((2, 2, 2))\n >>> data\n array([[[0, 1],\n [2, 3]],\n [[4, 5],\n [6, 7]]])\n >>> np.ma.average(data, axis=(0, 1), weights=[[1./4, 3./4], [1., 1./2]])\n masked_array(data=[3.4, 4.4],\n mask=[False, False],\n fill_value=1e+20)\n >>> np.ma.average(data, axis=0, weights=[[1./4, 3./4], [1., 1./2]])\n Traceback (most recent call last):\n ...\n ValueError: Shape of weights must be consistent\n with shape of a along specified axis.\n\n >>> avg, sumweights = np.ma.average(x, axis=0, weights=[1, 2, 3],\n ... returned=True)\n >>> avg\n masked_array(data=[2.6666666666666665, 3.6666666666666665],\n mask=[False, False],\n fill_value=1e+20)\n\n With ``keepdims=True``, the following result has shape (3, 1).\n\n >>> np.ma.average(x, axis=1, keepdims=True)\n masked_array(\n data=[[0.5],\n [2.5],\n [4.5]],\n mask=False,\n fill_value=1e+20)\n """\n a = asarray(a)\n m = getmask(a)\n\n if axis is not None:\n axis = normalize_axis_tuple(axis, a.ndim, argname="axis")\n\n if keepdims is np._NoValue:\n # Don't pass on the keepdims argument if one wasn't given.\n keepdims_kw = {}\n else:\n keepdims_kw = {'keepdims': keepdims}\n\n if weights is None:\n avg = a.mean(axis, **keepdims_kw)\n scl = avg.dtype.type(a.count(axis))\n else:\n wgt = asarray(weights)\n\n if issubclass(a.dtype.type, (np.integer, np.bool)):\n result_dtype = np.result_type(a.dtype, wgt.dtype, 'f8')\n else:\n result_dtype = np.result_type(a.dtype, wgt.dtype)\n\n # Sanity checks\n if a.shape != wgt.shape:\n if axis is None:\n raise TypeError(\n "Axis must be specified when shapes of a and weights "\n "differ.")\n if wgt.shape != tuple(a.shape[ax] for ax in axis):\n raise ValueError(\n "Shape of weights must be consistent with "\n "shape of a along specified axis.")\n\n # setup wgt to broadcast along axis\n wgt = wgt.transpose(np.argsort(axis))\n wgt = wgt.reshape(tuple((s if ax in axis else 1)\n for ax, s in enumerate(a.shape)))\n\n if m is not nomask:\n wgt = wgt * (~a.mask)\n wgt.mask |= a.mask\n\n scl = wgt.sum(axis=axis, dtype=result_dtype, **keepdims_kw)\n avg = np.multiply(a, wgt,\n dtype=result_dtype).sum(axis, **keepdims_kw) / scl\n\n if returned:\n if scl.shape != avg.shape:\n scl = np.broadcast_to(scl, avg.shape).copy()\n return avg, scl\n else:\n return avg\n\n\ndef median(a, axis=None, out=None, overwrite_input=False, keepdims=False):\n """\n Compute the median along the specified axis.\n\n Returns the median of the array elements.\n\n Parameters\n ----------\n a : array_like\n Input array or object that can be converted to an array.\n axis : int, optional\n Axis along which the medians are computed. The default (None) is\n to compute the median along a flattened version of the array.\n out : ndarray, optional\n Alternative output array in which to place the result. It must\n have the same shape and buffer length as the expected output\n but the type will be cast if necessary.\n overwrite_input : bool, optional\n If True, then allow use of memory of input array (a) for\n calculations. The input array will be modified by the call to\n median. This will save memory when you do not need to preserve\n the contents of the input array. Treat the input as undefined,\n but it will probably be fully or partially sorted. Default is\n False. Note that, if `overwrite_input` is True, and the input\n is not already an `ndarray`, an error will be raised.\n keepdims : bool, optional\n If this is set to True, the axes which are reduced are left\n in the result as dimensions with size one. With this option,\n the result will broadcast correctly against the input array.\n\n Returns\n -------\n median : ndarray\n A new array holding the result is returned unless out is\n specified, in which case a reference to out is returned.\n Return data-type is `float64` for integers and floats smaller than\n `float64`, or the input data-type, otherwise.\n\n See Also\n --------\n mean\n\n Notes\n -----\n Given a vector ``V`` with ``N`` non masked values, the median of ``V``\n is the middle value of a sorted copy of ``V`` (``Vs``) - i.e.\n ``Vs[(N-1)/2]``, when ``N`` is odd, or ``{Vs[N/2 - 1] + Vs[N/2]}/2``\n when ``N`` is even.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.ma.array(np.arange(8), mask=[0]*4 + [1]*4)\n >>> np.ma.median(x)\n 1.5\n\n >>> x = np.ma.array(np.arange(10).reshape(2, 5), mask=[0]*6 + [1]*4)\n >>> np.ma.median(x)\n 2.5\n >>> np.ma.median(x, axis=-1, overwrite_input=True)\n masked_array(data=[2.0, 5.0],\n mask=[False, False],\n fill_value=1e+20)\n\n """\n if not hasattr(a, 'mask'):\n m = np.median(getdata(a, subok=True), axis=axis,\n out=out, overwrite_input=overwrite_input,\n keepdims=keepdims)\n if isinstance(m, np.ndarray) and 1 <= m.ndim:\n return masked_array(m, copy=False)\n else:\n return m\n\n return _ureduce(a, func=_median, keepdims=keepdims, axis=axis, out=out,\n overwrite_input=overwrite_input)\n\n\ndef _median(a, axis=None, out=None, overwrite_input=False):\n # when an unmasked NaN is present return it, so we need to sort the NaN\n # values behind the mask\n if np.issubdtype(a.dtype, np.inexact):\n fill_value = np.inf\n else:\n fill_value = None\n if overwrite_input:\n if axis is None:\n asorted = a.ravel()\n asorted.sort(fill_value=fill_value)\n else:\n a.sort(axis=axis, fill_value=fill_value)\n asorted = a\n else:\n asorted = sort(a, axis=axis, fill_value=fill_value)\n\n if axis is None:\n axis = 0\n else:\n axis = normalize_axis_index(axis, asorted.ndim)\n\n if asorted.shape[axis] == 0:\n # for empty axis integer indices fail so use slicing to get same result\n # as median (which is mean of empty slice = nan)\n indexer = [slice(None)] * asorted.ndim\n indexer[axis] = slice(0, 0)\n indexer = tuple(indexer)\n return np.ma.mean(asorted[indexer], axis=axis, out=out)\n\n if asorted.ndim == 1:\n idx, odd = divmod(count(asorted), 2)\n mid = asorted[idx + odd - 1:idx + 1]\n if np.issubdtype(asorted.dtype, np.inexact) and asorted.size > 0:\n # avoid inf / x = masked\n s = mid.sum(out=out)\n if not odd:\n s = np.true_divide(s, 2., casting='safe', out=out)\n s = np.lib._utils_impl._median_nancheck(asorted, s, axis)\n else:\n s = mid.mean(out=out)\n\n # if result is masked either the input contained enough\n # minimum_fill_value so that it would be the median or all values\n # masked\n if np.ma.is_masked(s) and not np.all(asorted.mask):\n return np.ma.minimum_fill_value(asorted)\n return s\n\n counts = count(asorted, axis=axis, keepdims=True)\n h = counts // 2\n\n # duplicate high if odd number of elements so mean does nothing\n odd = counts % 2 == 1\n l = np.where(odd, h, h - 1)\n\n lh = np.concatenate([l, h], axis=axis)\n\n # get low and high median\n low_high = np.take_along_axis(asorted, lh, axis=axis)\n\n def replace_masked(s):\n # Replace masked entries with minimum_full_value unless it all values\n # are masked. This is required as the sort order of values equal or\n # larger than the fill value is undefined and a valid value placed\n # elsewhere, e.g. [4, --, inf].\n if np.ma.is_masked(s):\n rep = (~np.all(asorted.mask, axis=axis, keepdims=True)) & s.mask\n s.data[rep] = np.ma.minimum_fill_value(asorted)\n s.mask[rep] = False\n\n replace_masked(low_high)\n\n if np.issubdtype(asorted.dtype, np.inexact):\n # avoid inf / x = masked\n s = np.ma.sum(low_high, axis=axis, out=out)\n np.true_divide(s.data, 2., casting='unsafe', out=s.data)\n\n s = np.lib._utils_impl._median_nancheck(asorted, s, axis)\n else:\n s = np.ma.mean(low_high, axis=axis, out=out)\n\n return s\n\n\ndef compress_nd(x, axis=None):\n """Suppress slices from multiple dimensions which contain masked values.\n\n Parameters\n ----------\n x : array_like, MaskedArray\n The array to operate on. If not a MaskedArray instance (or if no array\n elements are masked), `x` is interpreted as a MaskedArray with `mask`\n set to `nomask`.\n axis : tuple of ints or int, optional\n Which dimensions to suppress slices from can be configured with this\n parameter.\n - If axis is a tuple of ints, those are the axes to suppress slices from.\n - If axis is an int, then that is the only axis to suppress slices from.\n - If axis is None, all axis are selected.\n\n Returns\n -------\n compress_array : ndarray\n The compressed array.\n\n Examples\n --------\n >>> import numpy as np\n >>> arr = [[1, 2], [3, 4]]\n >>> mask = [[0, 1], [0, 0]]\n >>> x = np.ma.array(arr, mask=mask)\n >>> np.ma.compress_nd(x, axis=0)\n array([[3, 4]])\n >>> np.ma.compress_nd(x, axis=1)\n array([[1],\n [3]])\n >>> np.ma.compress_nd(x)\n array([[3]])\n\n """\n x = asarray(x)\n m = getmask(x)\n # Set axis to tuple of ints\n if axis is None:\n axis = tuple(range(x.ndim))\n else:\n axis = normalize_axis_tuple(axis, x.ndim)\n\n # Nothing is masked: return x\n if m is nomask or not m.any():\n return x._data\n # All is masked: return empty\n if m.all():\n return nxarray([])\n # Filter elements through boolean indexing\n data = x._data\n for ax in axis:\n axes = tuple(list(range(ax)) + list(range(ax + 1, x.ndim)))\n data = data[(slice(None),) * ax + (~m.any(axis=axes),)]\n return data\n\n\ndef compress_rowcols(x, axis=None):\n """\n Suppress the rows and/or columns of a 2-D array that contain\n masked values.\n\n The suppression behavior is selected with the `axis` parameter.\n\n - If axis is None, both rows and columns are suppressed.\n - If axis is 0, only rows are suppressed.\n - If axis is 1 or -1, only columns are suppressed.\n\n Parameters\n ----------\n x : array_like, MaskedArray\n The array to operate on. If not a MaskedArray instance (or if no array\n elements are masked), `x` is interpreted as a MaskedArray with\n `mask` set to `nomask`. Must be a 2D array.\n axis : int, optional\n Axis along which to perform the operation. Default is None.\n\n Returns\n -------\n compressed_array : ndarray\n The compressed array.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],\n ... [1, 0, 0],\n ... [0, 0, 0]])\n >>> x\n masked_array(\n data=[[--, 1, 2],\n [--, 4, 5],\n [6, 7, 8]],\n mask=[[ True, False, False],\n [ True, False, False],\n [False, False, False]],\n fill_value=999999)\n\n >>> np.ma.compress_rowcols(x)\n array([[7, 8]])\n >>> np.ma.compress_rowcols(x, 0)\n array([[6, 7, 8]])\n >>> np.ma.compress_rowcols(x, 1)\n array([[1, 2],\n [4, 5],\n [7, 8]])\n\n """\n if asarray(x).ndim != 2:\n raise NotImplementedError("compress_rowcols works for 2D arrays only.")\n return compress_nd(x, axis=axis)\n\n\ndef compress_rows(a):\n """\n Suppress whole rows of a 2-D array that contain masked values.\n\n This is equivalent to ``np.ma.compress_rowcols(a, 0)``, see\n `compress_rowcols` for details.\n\n Parameters\n ----------\n x : array_like, MaskedArray\n The array to operate on. If not a MaskedArray instance (or if no array\n elements are masked), `x` is interpreted as a MaskedArray with\n `mask` set to `nomask`. Must be a 2D array.\n\n Returns\n -------\n compressed_array : ndarray\n The compressed array.\n\n See Also\n --------\n compress_rowcols\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],\n ... [1, 0, 0],\n ... [0, 0, 0]])\n >>> np.ma.compress_rows(a)\n array([[6, 7, 8]])\n\n """\n a = asarray(a)\n if a.ndim != 2:\n raise NotImplementedError("compress_rows works for 2D arrays only.")\n return compress_rowcols(a, 0)\n\n\ndef compress_cols(a):\n """\n Suppress whole columns of a 2-D array that contain masked values.\n\n This is equivalent to ``np.ma.compress_rowcols(a, 1)``, see\n `compress_rowcols` for details.\n\n Parameters\n ----------\n x : array_like, MaskedArray\n The array to operate on. If not a MaskedArray instance (or if no array\n elements are masked), `x` is interpreted as a MaskedArray with\n `mask` set to `nomask`. Must be a 2D array.\n\n Returns\n -------\n compressed_array : ndarray\n The compressed array.\n\n See Also\n --------\n compress_rowcols\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],\n ... [1, 0, 0],\n ... [0, 0, 0]])\n >>> np.ma.compress_cols(a)\n array([[1, 2],\n [4, 5],\n [7, 8]])\n\n """\n a = asarray(a)\n if a.ndim != 2:\n raise NotImplementedError("compress_cols works for 2D arrays only.")\n return compress_rowcols(a, 1)\n\n\ndef mask_rowcols(a, axis=None):\n """\n Mask rows and/or columns of a 2D array that contain masked values.\n\n Mask whole rows and/or columns of a 2D array that contain\n masked values. The masking behavior is selected using the\n `axis` parameter.\n\n - If `axis` is None, rows *and* columns are masked.\n - If `axis` is 0, only rows are masked.\n - If `axis` is 1 or -1, only columns are masked.\n\n Parameters\n ----------\n a : array_like, MaskedArray\n The array to mask. If not a MaskedArray instance (or if no array\n elements are masked), the result is a MaskedArray with `mask` set\n to `nomask` (False). Must be a 2D array.\n axis : int, optional\n Axis along which to perform the operation. If None, applies to a\n flattened version of the array.\n\n Returns\n -------\n a : MaskedArray\n A modified version of the input array, masked depending on the value\n of the `axis` parameter.\n\n Raises\n ------\n NotImplementedError\n If input array `a` is not 2D.\n\n See Also\n --------\n mask_rows : Mask rows of a 2D array that contain masked values.\n mask_cols : Mask cols of a 2D array that contain masked values.\n masked_where : Mask where a condition is met.\n\n Notes\n -----\n The input array's mask is modified by this function.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.zeros((3, 3), dtype=int)\n >>> a[1, 1] = 1\n >>> a\n array([[0, 0, 0],\n [0, 1, 0],\n [0, 0, 0]])\n >>> a = np.ma.masked_equal(a, 1)\n >>> a\n masked_array(\n data=[[0, 0, 0],\n [0, --, 0],\n [0, 0, 0]],\n mask=[[False, False, False],\n [False, True, False],\n [False, False, False]],\n fill_value=1)\n >>> np.ma.mask_rowcols(a)\n masked_array(\n data=[[0, --, 0],\n [--, --, --],\n [0, --, 0]],\n mask=[[False, True, False],\n [ True, True, True],\n [False, True, False]],\n fill_value=1)\n\n """\n a = array(a, subok=False)\n if a.ndim != 2:\n raise NotImplementedError("mask_rowcols works for 2D arrays only.")\n m = getmask(a)\n # Nothing is masked: return a\n if m is nomask or not m.any():\n return a\n maskedval = m.nonzero()\n a._mask = a._mask.copy()\n if not axis:\n a[np.unique(maskedval[0])] = masked\n if axis in [None, 1, -1]:\n a[:, np.unique(maskedval[1])] = masked\n return a\n\n\ndef mask_rows(a, axis=np._NoValue):\n """\n Mask rows of a 2D array that contain masked values.\n\n This function is a shortcut to ``mask_rowcols`` with `axis` equal to 0.\n\n See Also\n --------\n mask_rowcols : Mask rows and/or columns of a 2D array.\n masked_where : Mask where a condition is met.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.zeros((3, 3), dtype=int)\n >>> a[1, 1] = 1\n >>> a\n array([[0, 0, 0],\n [0, 1, 0],\n [0, 0, 0]])\n >>> a = np.ma.masked_equal(a, 1)\n >>> a\n masked_array(\n data=[[0, 0, 0],\n [0, --, 0],\n [0, 0, 0]],\n mask=[[False, False, False],\n [False, True, False],\n [False, False, False]],\n fill_value=1)\n\n >>> np.ma.mask_rows(a)\n masked_array(\n data=[[0, 0, 0],\n [--, --, --],\n [0, 0, 0]],\n mask=[[False, False, False],\n [ True, True, True],\n [False, False, False]],\n fill_value=1)\n\n """\n if axis is not np._NoValue:\n # remove the axis argument when this deprecation expires\n # NumPy 1.18.0, 2019-11-28\n warnings.warn(\n "The axis argument has always been ignored, in future passing it "\n "will raise TypeError", DeprecationWarning, stacklevel=2)\n return mask_rowcols(a, 0)\n\n\ndef mask_cols(a, axis=np._NoValue):\n """\n Mask columns of a 2D array that contain masked values.\n\n This function is a shortcut to ``mask_rowcols`` with `axis` equal to 1.\n\n See Also\n --------\n mask_rowcols : Mask rows and/or columns of a 2D array.\n masked_where : Mask where a condition is met.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.zeros((3, 3), dtype=int)\n >>> a[1, 1] = 1\n >>> a\n array([[0, 0, 0],\n [0, 1, 0],\n [0, 0, 0]])\n >>> a = np.ma.masked_equal(a, 1)\n >>> a\n masked_array(\n data=[[0, 0, 0],\n [0, --, 0],\n [0, 0, 0]],\n mask=[[False, False, False],\n [False, True, False],\n [False, False, False]],\n fill_value=1)\n >>> np.ma.mask_cols(a)\n masked_array(\n data=[[0, --, 0],\n [0, --, 0],\n [0, --, 0]],\n mask=[[False, True, False],\n [False, True, False],\n [False, True, False]],\n fill_value=1)\n\n """\n if axis is not np._NoValue:\n # remove the axis argument when this deprecation expires\n # NumPy 1.18.0, 2019-11-28\n warnings.warn(\n "The axis argument has always been ignored, in future passing it "\n "will raise TypeError", DeprecationWarning, stacklevel=2)\n return mask_rowcols(a, 1)\n\n\n#####--------------------------------------------------------------------------\n#---- --- arraysetops ---\n#####--------------------------------------------------------------------------\n\ndef ediff1d(arr, to_end=None, to_begin=None):\n """\n Compute the differences between consecutive elements of an array.\n\n This function is the equivalent of `numpy.ediff1d` that takes masked\n values into account, see `numpy.ediff1d` for details.\n\n See Also\n --------\n numpy.ediff1d : Equivalent function for ndarrays.\n\n Examples\n --------\n >>> import numpy as np\n >>> arr = np.ma.array([1, 2, 4, 7, 0])\n >>> np.ma.ediff1d(arr)\n masked_array(data=[ 1, 2, 3, -7],\n mask=False,\n fill_value=999999)\n\n """\n arr = ma.asanyarray(arr).flat\n ed = arr[1:] - arr[:-1]\n arrays = [ed]\n #\n if to_begin is not None:\n arrays.insert(0, to_begin)\n if to_end is not None:\n arrays.append(to_end)\n #\n if len(arrays) != 1:\n # We'll save ourselves a copy of a potentially large array in the common\n # case where neither to_begin or to_end was given.\n ed = hstack(arrays)\n #\n return ed\n\n\ndef unique(ar1, return_index=False, return_inverse=False):\n """\n Finds the unique elements of an array.\n\n Masked values are considered the same element (masked). The output array\n is always a masked array. See `numpy.unique` for more details.\n\n See Also\n --------\n numpy.unique : Equivalent function for ndarrays.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = [1, 2, 1000, 2, 3]\n >>> mask = [0, 0, 1, 0, 0]\n >>> masked_a = np.ma.masked_array(a, mask)\n >>> masked_a\n masked_array(data=[1, 2, --, 2, 3],\n mask=[False, False, True, False, False],\n fill_value=999999)\n >>> np.ma.unique(masked_a)\n masked_array(data=[1, 2, 3, --],\n mask=[False, False, False, True],\n fill_value=999999)\n >>> np.ma.unique(masked_a, return_index=True)\n (masked_array(data=[1, 2, 3, --],\n mask=[False, False, False, True],\n fill_value=999999), array([0, 1, 4, 2]))\n >>> np.ma.unique(masked_a, return_inverse=True)\n (masked_array(data=[1, 2, 3, --],\n mask=[False, False, False, True],\n fill_value=999999), array([0, 1, 3, 1, 2]))\n >>> np.ma.unique(masked_a, return_index=True, return_inverse=True)\n (masked_array(data=[1, 2, 3, --],\n mask=[False, False, False, True],\n fill_value=999999), array([0, 1, 4, 2]), array([0, 1, 3, 1, 2]))\n """\n output = np.unique(ar1,\n return_index=return_index,\n return_inverse=return_inverse)\n if isinstance(output, tuple):\n output = list(output)\n output[0] = output[0].view(MaskedArray)\n output = tuple(output)\n else:\n output = output.view(MaskedArray)\n return output\n\n\ndef intersect1d(ar1, ar2, assume_unique=False):\n """\n Returns the unique elements common to both arrays.\n\n Masked values are considered equal one to the other.\n The output is always a masked array.\n\n See `numpy.intersect1d` for more details.\n\n See Also\n --------\n numpy.intersect1d : Equivalent function for ndarrays.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.ma.array([1, 3, 3, 3], mask=[0, 0, 0, 1])\n >>> y = np.ma.array([3, 1, 1, 1], mask=[0, 0, 0, 1])\n >>> np.ma.intersect1d(x, y)\n masked_array(data=[1, 3, --],\n mask=[False, False, True],\n fill_value=999999)\n\n """\n if assume_unique:\n aux = ma.concatenate((ar1, ar2))\n else:\n # Might be faster than unique( intersect1d( ar1, ar2 ) )?\n aux = ma.concatenate((unique(ar1), unique(ar2)))\n aux.sort()\n return aux[:-1][aux[1:] == aux[:-1]]\n\n\ndef setxor1d(ar1, ar2, assume_unique=False):\n """\n Set exclusive-or of 1-D arrays with unique elements.\n\n The output is always a masked array. See `numpy.setxor1d` for more details.\n\n See Also\n --------\n numpy.setxor1d : Equivalent function for ndarrays.\n\n Examples\n --------\n >>> import numpy as np\n >>> ar1 = np.ma.array([1, 2, 3, 2, 4])\n >>> ar2 = np.ma.array([2, 3, 5, 7, 5])\n >>> np.ma.setxor1d(ar1, ar2)\n masked_array(data=[1, 4, 5, 7],\n mask=False,\n fill_value=999999)\n\n """\n if not assume_unique:\n ar1 = unique(ar1)\n ar2 = unique(ar2)\n\n aux = ma.concatenate((ar1, ar2), axis=None)\n if aux.size == 0:\n return aux\n aux.sort()\n auxf = aux.filled()\n# flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0\n flag = ma.concatenate(([True], (auxf[1:] != auxf[:-1]), [True]))\n# flag2 = ediff1d( flag ) == 0\n flag2 = (flag[1:] == flag[:-1])\n return aux[flag2]\n\n\ndef in1d(ar1, ar2, assume_unique=False, invert=False):\n """\n Test whether each element of an array is also present in a second\n array.\n\n The output is always a masked array. See `numpy.in1d` for more details.\n\n We recommend using :func:`isin` instead of `in1d` for new code.\n\n See Also\n --------\n isin : Version of this function that preserves the shape of ar1.\n numpy.in1d : Equivalent function for ndarrays.\n\n Examples\n --------\n >>> import numpy as np\n >>> ar1 = np.ma.array([0, 1, 2, 5, 0])\n >>> ar2 = [0, 2]\n >>> np.ma.in1d(ar1, ar2)\n masked_array(data=[ True, False, True, False, True],\n mask=False,\n fill_value=True)\n\n """\n if not assume_unique:\n ar1, rev_idx = unique(ar1, return_inverse=True)\n ar2 = unique(ar2)\n\n ar = ma.concatenate((ar1, ar2))\n # We need this to be a stable sort, so always use 'mergesort'\n # here. The values from the first array should always come before\n # the values from the second array.\n order = ar.argsort(kind='mergesort')\n sar = ar[order]\n if invert:\n bool_ar = (sar[1:] != sar[:-1])\n else:\n bool_ar = (sar[1:] == sar[:-1])\n flag = ma.concatenate((bool_ar, [invert]))\n indx = order.argsort(kind='mergesort')[:len(ar1)]\n\n if assume_unique:\n return flag[indx]\n else:\n return flag[indx][rev_idx]\n\n\ndef isin(element, test_elements, assume_unique=False, invert=False):\n """\n Calculates `element in test_elements`, broadcasting over\n `element` only.\n\n The output is always a masked array of the same shape as `element`.\n See `numpy.isin` for more details.\n\n See Also\n --------\n in1d : Flattened version of this function.\n numpy.isin : Equivalent function for ndarrays.\n\n Examples\n --------\n >>> import numpy as np\n >>> element = np.ma.array([1, 2, 3, 4, 5, 6])\n >>> test_elements = [0, 2]\n >>> np.ma.isin(element, test_elements)\n masked_array(data=[False, True, False, False, False, False],\n mask=False,\n fill_value=True)\n\n """\n element = ma.asarray(element)\n return in1d(element, test_elements, assume_unique=assume_unique,\n invert=invert).reshape(element.shape)\n\n\ndef union1d(ar1, ar2):\n """\n Union of two arrays.\n\n The output is always a masked array. See `numpy.union1d` for more details.\n\n See Also\n --------\n numpy.union1d : Equivalent function for ndarrays.\n\n Examples\n --------\n >>> import numpy as np\n >>> ar1 = np.ma.array([1, 2, 3, 4])\n >>> ar2 = np.ma.array([3, 4, 5, 6])\n >>> np.ma.union1d(ar1, ar2)\n masked_array(data=[1, 2, 3, 4, 5, 6],\n mask=False,\n fill_value=999999)\n\n """\n return unique(ma.concatenate((ar1, ar2), axis=None))\n\n\ndef setdiff1d(ar1, ar2, assume_unique=False):\n """\n Set difference of 1D arrays with unique elements.\n\n The output is always a masked array. See `numpy.setdiff1d` for more\n details.\n\n See Also\n --------\n numpy.setdiff1d : Equivalent function for ndarrays.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1])\n >>> np.ma.setdiff1d(x, [1, 2])\n masked_array(data=[3, --],\n mask=[False, True],\n fill_value=999999)\n\n """\n if assume_unique:\n ar1 = ma.asarray(ar1).ravel()\n else:\n ar1 = unique(ar1)\n ar2 = unique(ar2)\n return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)]\n\n\n###############################################################################\n# Covariance #\n###############################################################################\n\n\ndef _covhelper(x, y=None, rowvar=True, allow_masked=True):\n """\n Private function for the computation of covariance and correlation\n coefficients.\n\n """\n x = ma.array(x, ndmin=2, copy=True, dtype=float)\n xmask = ma.getmaskarray(x)\n # Quick exit if we can't process masked data\n if not allow_masked and xmask.any():\n raise ValueError("Cannot process masked data.")\n #\n if x.shape[0] == 1:\n rowvar = True\n # Make sure that rowvar is either 0 or 1\n rowvar = int(bool(rowvar))\n axis = 1 - rowvar\n if rowvar:\n tup = (slice(None), None)\n else:\n tup = (None, slice(None))\n #\n if y is None:\n # Check if we can guarantee that the integers in the (N - ddof)\n # normalisation can be accurately represented with single-precision\n # before computing the dot product.\n if x.shape[0] > 2 ** 24 or x.shape[1] > 2 ** 24:\n xnm_dtype = np.float64\n else:\n xnm_dtype = np.float32\n xnotmask = np.logical_not(xmask).astype(xnm_dtype)\n else:\n y = array(y, copy=False, ndmin=2, dtype=float)\n ymask = ma.getmaskarray(y)\n if not allow_masked and ymask.any():\n raise ValueError("Cannot process masked data.")\n if xmask.any() or ymask.any():\n if y.shape == x.shape:\n # Define some common mask\n common_mask = np.logical_or(xmask, ymask)\n if common_mask is not nomask:\n xmask = x._mask = y._mask = ymask = common_mask\n x._sharedmask = False\n y._sharedmask = False\n x = ma.concatenate((x, y), axis)\n # Check if we can guarantee that the integers in the (N - ddof)\n # normalisation can be accurately represented with single-precision\n # before computing the dot product.\n if x.shape[0] > 2 ** 24 or x.shape[1] > 2 ** 24:\n xnm_dtype = np.float64\n else:\n xnm_dtype = np.float32\n xnotmask = np.logical_not(np.concatenate((xmask, ymask), axis)).astype(\n xnm_dtype\n )\n x -= x.mean(axis=rowvar)[tup]\n return (x, xnotmask, rowvar)\n\n\ndef cov(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None):\n """\n Estimate the covariance matrix.\n\n Except for the handling of missing data this function does the same as\n `numpy.cov`. For more details and examples, see `numpy.cov`.\n\n By default, masked values are recognized as such. If `x` and `y` have the\n same shape, a common mask is allocated: if ``x[i,j]`` is masked, then\n ``y[i,j]`` will also be masked.\n Setting `allow_masked` to False will raise an exception if values are\n missing in either of the input arrays.\n\n Parameters\n ----------\n x : array_like\n A 1-D or 2-D array containing multiple variables and observations.\n Each row of `x` represents a variable, and each column a single\n observation of all those variables. Also see `rowvar` below.\n y : array_like, optional\n An additional set of variables and observations. `y` has the same\n shape as `x`.\n rowvar : bool, optional\n If `rowvar` is True (default), then each row represents a\n variable, with observations in the columns. Otherwise, the relationship\n is transposed: each column represents a variable, while the rows\n contain observations.\n bias : bool, optional\n Default normalization (False) is by ``(N-1)``, where ``N`` is the\n number of observations given (unbiased estimate). If `bias` is True,\n then normalization is by ``N``. This keyword can be overridden by\n the keyword ``ddof`` in numpy versions >= 1.5.\n allow_masked : bool, optional\n If True, masked values are propagated pair-wise: if a value is masked\n in `x`, the corresponding value is masked in `y`.\n If False, raises a `ValueError` exception when some values are missing.\n ddof : {None, int}, optional\n If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is\n the number of observations; this overrides the value implied by\n ``bias``. The default value is ``None``.\n\n Raises\n ------\n ValueError\n Raised if some values are missing and `allow_masked` is False.\n\n See Also\n --------\n numpy.cov\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.ma.array([[0, 1], [1, 1]], mask=[0, 1, 0, 1])\n >>> y = np.ma.array([[1, 0], [0, 1]], mask=[0, 0, 1, 1])\n >>> np.ma.cov(x, y)\n masked_array(\n data=[[--, --, --, --],\n [--, --, --, --],\n [--, --, --, --],\n [--, --, --, --]],\n mask=[[ True, True, True, True],\n [ True, True, True, True],\n [ True, True, True, True],\n [ True, True, True, True]],\n fill_value=1e+20,\n dtype=float64)\n\n """\n # Check inputs\n if ddof is not None and ddof != int(ddof):\n raise ValueError("ddof must be an integer")\n # Set up ddof\n if ddof is None:\n if bias:\n ddof = 0\n else:\n ddof = 1\n\n (x, xnotmask, rowvar) = _covhelper(x, y, rowvar, allow_masked)\n if not rowvar:\n fact = np.dot(xnotmask.T, xnotmask) - ddof\n mask = np.less_equal(fact, 0, dtype=bool)\n with np.errstate(divide="ignore", invalid="ignore"):\n data = np.dot(filled(x.T, 0), filled(x.conj(), 0)) / fact\n result = ma.array(data, mask=mask).squeeze()\n else:\n fact = np.dot(xnotmask, xnotmask.T) - ddof\n mask = np.less_equal(fact, 0, dtype=bool)\n with np.errstate(divide="ignore", invalid="ignore"):\n data = np.dot(filled(x, 0), filled(x.T.conj(), 0)) / fact\n result = ma.array(data, mask=mask).squeeze()\n return result\n\n\ndef corrcoef(x, y=None, rowvar=True, bias=np._NoValue, allow_masked=True,\n ddof=np._NoValue):\n """\n Return Pearson product-moment correlation coefficients.\n\n Except for the handling of missing data this function does the same as\n `numpy.corrcoef`. For more details and examples, see `numpy.corrcoef`.\n\n Parameters\n ----------\n x : array_like\n A 1-D or 2-D array containing multiple variables and observations.\n Each row of `x` represents a variable, and each column a single\n observation of all those variables. Also see `rowvar` below.\n y : array_like, optional\n An additional set of variables and observations. `y` has the same\n shape as `x`.\n rowvar : bool, optional\n If `rowvar` is True (default), then each row represents a\n variable, with observations in the columns. Otherwise, the relationship\n is transposed: each column represents a variable, while the rows\n contain observations.\n bias : _NoValue, optional\n Has no effect, do not use.\n\n .. deprecated:: 1.10.0\n allow_masked : bool, optional\n If True, masked values are propagated pair-wise: if a value is masked\n in `x`, the corresponding value is masked in `y`.\n If False, raises an exception. Because `bias` is deprecated, this\n argument needs to be treated as keyword only to avoid a warning.\n ddof : _NoValue, optional\n Has no effect, do not use.\n\n .. deprecated:: 1.10.0\n\n See Also\n --------\n numpy.corrcoef : Equivalent function in top-level NumPy module.\n cov : Estimate the covariance matrix.\n\n Notes\n -----\n This function accepts but discards arguments `bias` and `ddof`. This is\n for backwards compatibility with previous versions of this function. These\n arguments had no effect on the return values of the function and can be\n safely ignored in this and previous versions of numpy.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.ma.array([[0, 1], [1, 1]], mask=[0, 1, 0, 1])\n >>> np.ma.corrcoef(x)\n masked_array(\n data=[[--, --],\n [--, --]],\n mask=[[ True, True],\n [ True, True]],\n fill_value=1e+20,\n dtype=float64)\n\n """\n msg = 'bias and ddof have no effect and are deprecated'\n if bias is not np._NoValue or ddof is not np._NoValue:\n # 2015-03-15, 1.10\n warnings.warn(msg, DeprecationWarning, stacklevel=2)\n # Estimate the covariance matrix.\n corr = cov(x, y, rowvar, allow_masked=allow_masked)\n # The non-masked version returns a masked value for a scalar.\n try:\n std = ma.sqrt(ma.diagonal(corr))\n except ValueError:\n return ma.MaskedConstant()\n corr /= ma.multiply.outer(std, std)\n return corr\n\n#####--------------------------------------------------------------------------\n#---- --- Concatenation helpers ---\n#####--------------------------------------------------------------------------\n\nclass MAxisConcatenator(AxisConcatenator):\n """\n Translate slice objects to concatenation along an axis.\n\n For documentation on usage, see `mr_class`.\n\n See Also\n --------\n mr_class\n\n """\n __slots__ = ()\n\n concatenate = staticmethod(concatenate)\n\n @classmethod\n def makemat(cls, arr):\n # There used to be a view as np.matrix here, but we may eventually\n # deprecate that class. In preparation, we use the unmasked version\n # to construct the matrix (with copy=False for backwards compatibility\n # with the .view)\n data = super().makemat(arr.data, copy=False)\n return array(data, mask=arr.mask)\n\n def __getitem__(self, key):\n # matrix builder syntax, like 'a, b; c, d'\n if isinstance(key, str):\n raise MAError("Unavailable for masked array.")\n\n return super().__getitem__(key)\n\n\nclass mr_class(MAxisConcatenator):\n """\n Translate slice objects to concatenation along the first axis.\n\n This is the masked array version of `r_`.\n\n See Also\n --------\n r_\n\n Examples\n --------\n >>> import numpy as np\n >>> np.ma.mr_[np.ma.array([1,2,3]), 0, 0, np.ma.array([4,5,6])]\n masked_array(data=[1, 2, 3, ..., 4, 5, 6],\n mask=False,\n fill_value=999999)\n\n """\n __slots__ = ()\n\n def __init__(self):\n MAxisConcatenator.__init__(self, 0)\n\n\nmr_ = mr_class()\n\n\n#####--------------------------------------------------------------------------\n#---- Find unmasked data ---\n#####--------------------------------------------------------------------------\n\ndef ndenumerate(a, compressed=True):\n """\n Multidimensional index iterator.\n\n Return an iterator yielding pairs of array coordinates and values,\n skipping elements that are masked. With `compressed=False`,\n `ma.masked` is yielded as the value of masked elements. This\n behavior differs from that of `numpy.ndenumerate`, which yields the\n value of the underlying data array.\n\n Notes\n -----\n .. versionadded:: 1.23.0\n\n Parameters\n ----------\n a : array_like\n An array with (possibly) masked elements.\n compressed : bool, optional\n If True (default), masked elements are skipped.\n\n See Also\n --------\n numpy.ndenumerate : Equivalent function ignoring any mask.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.ma.arange(9).reshape((3, 3))\n >>> a[1, 0] = np.ma.masked\n >>> a[1, 2] = np.ma.masked\n >>> a[2, 1] = np.ma.masked\n >>> a\n masked_array(\n data=[[0, 1, 2],\n [--, 4, --],\n [6, --, 8]],\n mask=[[False, False, False],\n [ True, False, True],\n [False, True, False]],\n fill_value=999999)\n >>> for index, x in np.ma.ndenumerate(a):\n ... print(index, x)\n (0, 0) 0\n (0, 1) 1\n (0, 2) 2\n (1, 1) 4\n (2, 0) 6\n (2, 2) 8\n\n >>> for index, x in np.ma.ndenumerate(a, compressed=False):\n ... print(index, x)\n (0, 0) 0\n (0, 1) 1\n (0, 2) 2\n (1, 0) --\n (1, 1) 4\n (1, 2) --\n (2, 0) 6\n (2, 1) --\n (2, 2) 8\n """\n for it, mask in zip(np.ndenumerate(a), getmaskarray(a).flat):\n if not mask:\n yield it\n elif not compressed:\n yield it[0], masked\n\n\ndef flatnotmasked_edges(a):\n """\n Find the indices of the first and last unmasked values.\n\n Expects a 1-D `MaskedArray`, returns None if all values are masked.\n\n Parameters\n ----------\n a : array_like\n Input 1-D `MaskedArray`\n\n Returns\n -------\n edges : ndarray or None\n The indices of first and last non-masked value in the array.\n Returns None if all values are masked.\n\n See Also\n --------\n flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges\n clump_masked, clump_unmasked\n\n Notes\n -----\n Only accepts 1-D arrays.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.ma.arange(10)\n >>> np.ma.flatnotmasked_edges(a)\n array([0, 9])\n\n >>> mask = (a < 3) | (a > 8) | (a == 5)\n >>> a[mask] = np.ma.masked\n >>> np.array(a[~a.mask])\n array([3, 4, 6, 7, 8])\n\n >>> np.ma.flatnotmasked_edges(a)\n array([3, 8])\n\n >>> a[:] = np.ma.masked\n >>> print(np.ma.flatnotmasked_edges(a))\n None\n\n """\n m = getmask(a)\n if m is nomask or not np.any(m):\n return np.array([0, a.size - 1])\n unmasked = np.flatnonzero(~m)\n if len(unmasked) > 0:\n return unmasked[[0, -1]]\n else:\n return None\n\n\ndef notmasked_edges(a, axis=None):\n """\n Find the indices of the first and last unmasked values along an axis.\n\n If all values are masked, return None. Otherwise, return a list\n of two tuples, corresponding to the indices of the first and last\n unmasked values respectively.\n\n Parameters\n ----------\n a : array_like\n The input array.\n axis : int, optional\n Axis along which to perform the operation.\n If None (default), applies to a flattened version of the array.\n\n Returns\n -------\n edges : ndarray or list\n An array of start and end indexes if there are any masked data in\n the array. If there are no masked data in the array, `edges` is a\n list of the first and last index.\n\n See Also\n --------\n flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous\n clump_masked, clump_unmasked\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.arange(9).reshape((3, 3))\n >>> m = np.zeros_like(a)\n >>> m[1:, 1:] = 1\n\n >>> am = np.ma.array(a, mask=m)\n >>> np.array(am[~am.mask])\n array([0, 1, 2, 3, 6])\n\n >>> np.ma.notmasked_edges(am)\n array([0, 6])\n\n """\n a = asarray(a)\n if axis is None or a.ndim == 1:\n return flatnotmasked_edges(a)\n m = getmaskarray(a)\n idx = array(np.indices(a.shape), mask=np.asarray([m] * a.ndim))\n return [tuple(idx[i].min(axis).compressed() for i in range(a.ndim)),\n tuple(idx[i].max(axis).compressed() for i in range(a.ndim)), ]\n\n\ndef flatnotmasked_contiguous(a):\n """\n Find contiguous unmasked data in a masked array.\n\n Parameters\n ----------\n a : array_like\n The input array.\n\n Returns\n -------\n slice_list : list\n A sorted sequence of `slice` objects (start index, end index).\n\n See Also\n --------\n flatnotmasked_edges, notmasked_contiguous, notmasked_edges\n clump_masked, clump_unmasked\n\n Notes\n -----\n Only accepts 2-D arrays at most.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.ma.arange(10)\n >>> np.ma.flatnotmasked_contiguous(a)\n [slice(0, 10, None)]\n\n >>> mask = (a < 3) | (a > 8) | (a == 5)\n >>> a[mask] = np.ma.masked\n >>> np.array(a[~a.mask])\n array([3, 4, 6, 7, 8])\n\n >>> np.ma.flatnotmasked_contiguous(a)\n [slice(3, 5, None), slice(6, 9, None)]\n >>> a[:] = np.ma.masked\n >>> np.ma.flatnotmasked_contiguous(a)\n []\n\n """\n m = getmask(a)\n if m is nomask:\n return [slice(0, a.size)]\n i = 0\n result = []\n for (k, g) in itertools.groupby(m.ravel()):\n n = len(list(g))\n if not k:\n result.append(slice(i, i + n))\n i += n\n return result\n\n\ndef notmasked_contiguous(a, axis=None):\n """\n Find contiguous unmasked data in a masked array along the given axis.\n\n Parameters\n ----------\n a : array_like\n The input array.\n axis : int, optional\n Axis along which to perform the operation.\n If None (default), applies to a flattened version of the array, and this\n is the same as `flatnotmasked_contiguous`.\n\n Returns\n -------\n endpoints : list\n A list of slices (start and end indexes) of unmasked indexes\n in the array.\n\n If the input is 2d and axis is specified, the result is a list of lists.\n\n See Also\n --------\n flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges\n clump_masked, clump_unmasked\n\n Notes\n -----\n Only accepts 2-D arrays at most.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.arange(12).reshape((3, 4))\n >>> mask = np.zeros_like(a)\n >>> mask[1:, :-1] = 1; mask[0, 1] = 1; mask[-1, 0] = 0\n >>> ma = np.ma.array(a, mask=mask)\n >>> ma\n masked_array(\n data=[[0, --, 2, 3],\n [--, --, --, 7],\n [8, --, --, 11]],\n mask=[[False, True, False, False],\n [ True, True, True, False],\n [False, True, True, False]],\n fill_value=999999)\n >>> np.array(ma[~ma.mask])\n array([ 0, 2, 3, 7, 8, 11])\n\n >>> np.ma.notmasked_contiguous(ma)\n [slice(0, 1, None), slice(2, 4, None), slice(7, 9, None), slice(11, 12, None)]\n\n >>> np.ma.notmasked_contiguous(ma, axis=0)\n [[slice(0, 1, None), slice(2, 3, None)], [], [slice(0, 1, None)], [slice(0, 3, None)]]\n\n >>> np.ma.notmasked_contiguous(ma, axis=1)\n [[slice(0, 1, None), slice(2, 4, None)], [slice(3, 4, None)], [slice(0, 1, None), slice(3, 4, None)]]\n\n """ # noqa: E501\n a = asarray(a)\n nd = a.ndim\n if nd > 2:\n raise NotImplementedError("Currently limited to at most 2D array.")\n if axis is None or nd == 1:\n return flatnotmasked_contiguous(a)\n #\n result = []\n #\n other = (axis + 1) % 2\n idx = [0, 0]\n idx[axis] = slice(None, None)\n #\n for i in range(a.shape[other]):\n idx[other] = i\n result.append(flatnotmasked_contiguous(a[tuple(idx)]))\n return result\n\n\ndef _ezclump(mask):\n """\n Finds the clumps (groups of data with the same values) for a 1D bool array.\n\n Returns a series of slices.\n """\n if mask.ndim > 1:\n mask = mask.ravel()\n idx = (mask[1:] ^ mask[:-1]).nonzero()\n idx = idx[0] + 1\n\n if mask[0]:\n if len(idx) == 0:\n return [slice(0, mask.size)]\n\n r = [slice(0, idx[0])]\n r.extend((slice(left, right)\n for left, right in zip(idx[1:-1:2], idx[2::2])))\n else:\n if len(idx) == 0:\n return []\n\n r = [slice(left, right) for left, right in zip(idx[:-1:2], idx[1::2])]\n\n if mask[-1]:\n r.append(slice(idx[-1], mask.size))\n return r\n\n\ndef clump_unmasked(a):\n """\n Return list of slices corresponding to the unmasked clumps of a 1-D array.\n (A "clump" is defined as a contiguous region of the array).\n\n Parameters\n ----------\n a : ndarray\n A one-dimensional masked array.\n\n Returns\n -------\n slices : list of slice\n The list of slices, one for each continuous region of unmasked\n elements in `a`.\n\n See Also\n --------\n flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges\n notmasked_contiguous, clump_masked\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.ma.masked_array(np.arange(10))\n >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked\n >>> np.ma.clump_unmasked(a)\n [slice(3, 6, None), slice(7, 8, None)]\n\n """\n mask = getattr(a, '_mask', nomask)\n if mask is nomask:\n return [slice(0, a.size)]\n return _ezclump(~mask)\n\n\ndef clump_masked(a):\n """\n Returns a list of slices corresponding to the masked clumps of a 1-D array.\n (A "clump" is defined as a contiguous region of the array).\n\n Parameters\n ----------\n a : ndarray\n A one-dimensional masked array.\n\n Returns\n -------\n slices : list of slice\n The list of slices, one for each continuous region of masked elements\n in `a`.\n\n See Also\n --------\n flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges\n notmasked_contiguous, clump_unmasked\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.ma.masked_array(np.arange(10))\n >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked\n >>> np.ma.clump_masked(a)\n [slice(0, 3, None), slice(6, 7, None), slice(8, 10, None)]\n\n """\n mask = ma.getmask(a)\n if mask is nomask:\n return []\n return _ezclump(mask)\n\n\n###############################################################################\n# Polynomial fit #\n###############################################################################\n\n\ndef vander(x, n=None):\n """\n Masked values in the input array result in rows of zeros.\n\n """\n _vander = np.vander(x, n)\n m = getmask(x)\n if m is not nomask:\n _vander[m] = 0\n return _vander\n\n\nvander.__doc__ = ma.doc_note(np.vander.__doc__, vander.__doc__)\n\n\ndef polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):\n """\n Any masked values in x is propagated in y, and vice-versa.\n\n """\n x = asarray(x)\n y = asarray(y)\n\n m = getmask(x)\n if y.ndim == 1:\n m = mask_or(m, getmask(y))\n elif y.ndim == 2:\n my = getmask(mask_rows(y))\n if my is not nomask:\n m = mask_or(m, my[:, 0])\n else:\n raise TypeError("Expected a 1D or 2D array for y!")\n\n if w is not None:\n w = asarray(w)\n if w.ndim != 1:\n raise TypeError("expected a 1-d array for weights")\n if w.shape[0] != y.shape[0]:\n raise TypeError("expected w and y to have the same length")\n m = mask_or(m, getmask(w))\n\n if m is not nomask:\n not_m = ~m\n if w is not None:\n w = w[not_m]\n return np.polyfit(x[not_m], y[not_m], deg, rcond, full, w, cov)\n else:\n return np.polyfit(x, y, deg, rcond, full, w, cov)\n\n\npolyfit.__doc__ = ma.doc_note(np.polyfit.__doc__, polyfit.__doc__)\n | .venv\Lib\site-packages\numpy\ma\extras.py | extras.py | Python | 73,024 | 0.75 | 0.123294 | 0.04557 | awesome-app | 135 | 2023-08-01T02:40:19.479964 | Apache-2.0 | false | 5191cd3f7284a78e03b63bc2b1eaa952 |
from _typeshed import Incomplete\n\nimport numpy as np\nfrom numpy.lib._function_base_impl import average\nfrom numpy.lib._index_tricks_impl import AxisConcatenator\n\nfrom .core import MaskedArray, dot\n\n__all__ = [\n "apply_along_axis",\n "apply_over_axes",\n "atleast_1d",\n "atleast_2d",\n "atleast_3d",\n "average",\n "clump_masked",\n "clump_unmasked",\n "column_stack",\n "compress_cols",\n "compress_nd",\n "compress_rowcols",\n "compress_rows",\n "corrcoef",\n "count_masked",\n "cov",\n "diagflat",\n "dot",\n "dstack",\n "ediff1d",\n "flatnotmasked_contiguous",\n "flatnotmasked_edges",\n "hsplit",\n "hstack",\n "in1d",\n "intersect1d",\n "isin",\n "mask_cols",\n "mask_rowcols",\n "mask_rows",\n "masked_all",\n "masked_all_like",\n "median",\n "mr_",\n "ndenumerate",\n "notmasked_contiguous",\n "notmasked_edges",\n "polyfit",\n "row_stack",\n "setdiff1d",\n "setxor1d",\n "stack",\n "union1d",\n "unique",\n "vander",\n "vstack",\n]\n\ndef count_masked(arr, axis=...): ...\ndef masked_all(shape, dtype=...): ...\ndef masked_all_like(arr): ...\n\nclass _fromnxfunction:\n __name__: Incomplete\n __doc__: Incomplete\n def __init__(self, funcname) -> None: ...\n def getdoc(self): ...\n def __call__(self, *args, **params): ...\n\nclass _fromnxfunction_single(_fromnxfunction):\n def __call__(self, x, *args, **params): ...\n\nclass _fromnxfunction_seq(_fromnxfunction):\n def __call__(self, x, *args, **params): ...\n\nclass _fromnxfunction_allargs(_fromnxfunction):\n def __call__(self, *args, **params): ...\n\natleast_1d: _fromnxfunction_allargs\natleast_2d: _fromnxfunction_allargs\natleast_3d: _fromnxfunction_allargs\n\nvstack: _fromnxfunction_seq\nrow_stack: _fromnxfunction_seq\nhstack: _fromnxfunction_seq\ncolumn_stack: _fromnxfunction_seq\ndstack: _fromnxfunction_seq\nstack: _fromnxfunction_seq\n\nhsplit: _fromnxfunction_single\ndiagflat: _fromnxfunction_single\n\ndef apply_along_axis(func1d, axis, arr, *args, **kwargs): ...\ndef apply_over_axes(func, a, axes): ...\ndef median(a, axis=..., out=..., overwrite_input=..., keepdims=...): ...\ndef compress_nd(x, axis=...): ...\ndef compress_rowcols(x, axis=...): ...\ndef compress_rows(a): ...\ndef compress_cols(a): ...\ndef mask_rows(a, axis=...): ...\ndef mask_cols(a, axis=...): ...\ndef ediff1d(arr, to_end=..., to_begin=...): ...\ndef unique(ar1, return_index=..., return_inverse=...): ...\ndef intersect1d(ar1, ar2, assume_unique=...): ...\ndef setxor1d(ar1, ar2, assume_unique=...): ...\ndef in1d(ar1, ar2, assume_unique=..., invert=...): ...\ndef isin(element, test_elements, assume_unique=..., invert=...): ...\ndef union1d(ar1, ar2): ...\ndef setdiff1d(ar1, ar2, assume_unique=...): ...\ndef cov(x, y=..., rowvar=..., bias=..., allow_masked=..., ddof=...): ...\ndef corrcoef(x, y=..., rowvar=..., bias=..., allow_masked=..., ddof=...): ...\n\nclass MAxisConcatenator(AxisConcatenator):\n @staticmethod\n def concatenate(arrays: Incomplete, axis: int = 0) -> Incomplete: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]\n @classmethod\n def makemat(cls, arr: Incomplete) -> Incomplete: ... # type: ignore[override] # pyright: ignore[reportIncompatibleVariableOverride]\n\nclass mr_class(MAxisConcatenator):\n def __init__(self) -> None: ...\n\nmr_: mr_class\n\ndef ndenumerate(a, compressed=...): ...\ndef flatnotmasked_edges(a): ...\ndef notmasked_edges(a, axis=...): ...\ndef flatnotmasked_contiguous(a): ...\ndef notmasked_contiguous(a, axis=...): ...\ndef clump_unmasked(a): ...\ndef clump_masked(a): ...\ndef vander(x, n=...): ...\ndef polyfit(x, y, deg, rcond=..., full=..., w=..., cov=...): ...\n\n#\ndef mask_rowcols(a: Incomplete, axis: Incomplete | None = None) -> MaskedArray[Incomplete, np.dtype[Incomplete]]: ...\n | .venv\Lib\site-packages\numpy\ma\extras.pyi | extras.pyi | Other | 3,928 | 0.95 | 0.350746 | 0.008547 | node-utils | 0 | 2024-12-01T06:51:58.057769 | MIT | false | d1187e8d7d671789d20c3c405c2411cf |
* Copyright (c) 2006, University of Georgia and Pierre G.F. Gerard-Marchant\n* All rights reserved.\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in the\n* documentation and/or other materials provided with the distribution.\n* * Neither the name of the University of Georgia nor the\n* names of its contributors may be used to endorse or promote products\n* derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY\n* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY\n* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | .venv\Lib\site-packages\numpy\ma\LICENSE | LICENSE | Other | 1,616 | 0.7 | 0 | 1 | node-utils | 90 | 2024-11-20T19:22:58.462194 | GPL-3.0 | false | 560a44ba225da50f5d488426818c8474 |
""":mod:`numpy.ma..mrecords`\n\nDefines the equivalent of :class:`numpy.recarrays` for masked arrays,\nwhere fields can be accessed as attributes.\nNote that :class:`numpy.ma.MaskedArray` already supports structured datatypes\nand the masking of individual fields.\n\n.. moduleauthor:: Pierre Gerard-Marchant\n\n"""\n# We should make sure that no field is called '_mask','mask','_fieldmask',\n# or whatever restricted keywords. An idea would be to no bother in the\n# first place, and then rename the invalid fields with a trailing\n# underscore. Maybe we could just overload the parser function ?\n\nimport warnings\n\nimport numpy as np\nimport numpy.ma as ma\n\n_byteorderconv = np._core.records._byteorderconv\n\n\n_check_fill_value = ma.core._check_fill_value\n\n\n__all__ = [\n 'MaskedRecords', 'mrecarray', 'fromarrays', 'fromrecords',\n 'fromtextfile', 'addfield',\n]\n\nreserved_fields = ['_data', '_mask', '_fieldmask', 'dtype']\n\n\ndef _checknames(descr, names=None):\n """\n Checks that field names ``descr`` are not reserved keywords.\n\n If this is the case, a default 'f%i' is substituted. If the argument\n `names` is not None, updates the field names to valid names.\n\n """\n ndescr = len(descr)\n default_names = [f'f{i}' for i in range(ndescr)]\n if names is None:\n new_names = default_names\n else:\n if isinstance(names, (tuple, list)):\n new_names = names\n elif isinstance(names, str):\n new_names = names.split(',')\n else:\n raise NameError(f'illegal input names {names!r}')\n nnames = len(new_names)\n if nnames < ndescr:\n new_names += default_names[nnames:]\n ndescr = []\n for (n, d, t) in zip(new_names, default_names, descr.descr):\n if n in reserved_fields:\n if t[0] in reserved_fields:\n ndescr.append((d, t[1]))\n else:\n ndescr.append(t)\n else:\n ndescr.append((n, t[1]))\n return np.dtype(ndescr)\n\n\ndef _get_fieldmask(self):\n mdescr = [(n, '|b1') for n in self.dtype.names]\n fdmask = np.empty(self.shape, dtype=mdescr)\n fdmask.flat = tuple([False] * len(mdescr))\n return fdmask\n\n\nclass MaskedRecords(ma.MaskedArray):\n """\n\n Attributes\n ----------\n _data : recarray\n Underlying data, as a record array.\n _mask : boolean array\n Mask of the records. A record is masked when all its fields are\n masked.\n _fieldmask : boolean recarray\n Record array of booleans, setting the mask of each individual field\n of each record.\n _fill_value : record\n Filling values for each field.\n\n """\n\n def __new__(cls, shape, dtype=None, buf=None, offset=0, strides=None,\n formats=None, names=None, titles=None,\n byteorder=None, aligned=False,\n mask=ma.nomask, hard_mask=False, fill_value=None, keep_mask=True,\n copy=False,\n **options):\n\n self = np.recarray.__new__(cls, shape, dtype=dtype, buf=buf, offset=offset,\n strides=strides, formats=formats, names=names,\n titles=titles, byteorder=byteorder,\n aligned=aligned,)\n\n mdtype = ma.make_mask_descr(self.dtype)\n if mask is ma.nomask or not np.size(mask):\n if not keep_mask:\n self._mask = tuple([False] * len(mdtype))\n else:\n mask = np.array(mask, copy=copy)\n if mask.shape != self.shape:\n (nd, nm) = (self.size, mask.size)\n if nm == 1:\n mask = np.resize(mask, self.shape)\n elif nm == nd:\n mask = np.reshape(mask, self.shape)\n else:\n msg = (f"Mask and data not compatible: data size is {nd},"\n " mask size is {nm}.")\n raise ma.MAError(msg)\n if not keep_mask:\n self.__setmask__(mask)\n self._sharedmask = True\n else:\n if mask.dtype == mdtype:\n _mask = mask\n else:\n _mask = np.array([tuple([m] * len(mdtype)) for m in mask],\n dtype=mdtype)\n self._mask = _mask\n return self\n\n def __array_finalize__(self, obj):\n # Make sure we have a _fieldmask by default\n _mask = getattr(obj, '_mask', None)\n if _mask is None:\n objmask = getattr(obj, '_mask', ma.nomask)\n _dtype = np.ndarray.__getattribute__(self, 'dtype')\n if objmask is ma.nomask:\n _mask = ma.make_mask_none(self.shape, dtype=_dtype)\n else:\n mdescr = ma.make_mask_descr(_dtype)\n _mask = np.array([tuple([m] * len(mdescr)) for m in objmask],\n dtype=mdescr).view(np.recarray)\n # Update some of the attributes\n _dict = self.__dict__\n _dict.update(_mask=_mask)\n self._update_from(obj)\n if _dict['_baseclass'] == np.ndarray:\n _dict['_baseclass'] = np.recarray\n\n @property\n def _data(self):\n """\n Returns the data as a recarray.\n\n """\n return np.ndarray.view(self, np.recarray)\n\n @property\n def _fieldmask(self):\n """\n Alias to mask.\n\n """\n return self._mask\n\n def __len__(self):\n """\n Returns the length\n\n """\n # We have more than one record\n if self.ndim:\n return len(self._data)\n # We have only one record: return the nb of fields\n return len(self.dtype)\n\n def __getattribute__(self, attr):\n try:\n return object.__getattribute__(self, attr)\n except AttributeError:\n # attr must be a fieldname\n pass\n fielddict = np.ndarray.__getattribute__(self, 'dtype').fields\n try:\n res = fielddict[attr][:2]\n except (TypeError, KeyError) as e:\n raise AttributeError(\n f'record array has no attribute {attr}') from e\n # So far, so good\n _localdict = np.ndarray.__getattribute__(self, '__dict__')\n _data = np.ndarray.view(self, _localdict['_baseclass'])\n obj = _data.getfield(*res)\n if obj.dtype.names is not None:\n raise NotImplementedError("MaskedRecords is currently limited to"\n "simple records.")\n # Get some special attributes\n # Reset the object's mask\n hasmasked = False\n _mask = _localdict.get('_mask', None)\n if _mask is not None:\n try:\n _mask = _mask[attr]\n except IndexError:\n # Couldn't find a mask: use the default (nomask)\n pass\n tp_len = len(_mask.dtype)\n hasmasked = _mask.view((bool, ((tp_len,) if tp_len else ()))).any()\n if (obj.shape or hasmasked):\n obj = obj.view(ma.MaskedArray)\n obj._baseclass = np.ndarray\n obj._isfield = True\n obj._mask = _mask\n # Reset the field values\n _fill_value = _localdict.get('_fill_value', None)\n if _fill_value is not None:\n try:\n obj._fill_value = _fill_value[attr]\n except ValueError:\n obj._fill_value = None\n else:\n obj = obj.item()\n return obj\n\n def __setattr__(self, attr, val):\n """\n Sets the attribute attr to the value val.\n\n """\n # Should we call __setmask__ first ?\n if attr in ['mask', 'fieldmask']:\n self.__setmask__(val)\n return\n # Create a shortcut (so that we don't have to call getattr all the time)\n _localdict = object.__getattribute__(self, '__dict__')\n # Check whether we're creating a new field\n newattr = attr not in _localdict\n try:\n # Is attr a generic attribute ?\n ret = object.__setattr__(self, attr, val)\n except Exception:\n # Not a generic attribute: exit if it's not a valid field\n fielddict = np.ndarray.__getattribute__(self, 'dtype').fields or {}\n optinfo = np.ndarray.__getattribute__(self, '_optinfo') or {}\n if not (attr in fielddict or attr in optinfo):\n raise\n else:\n # Get the list of names\n fielddict = np.ndarray.__getattribute__(self, 'dtype').fields or {}\n # Check the attribute\n if attr not in fielddict:\n return ret\n if newattr:\n # We just added this one or this setattr worked on an\n # internal attribute.\n try:\n object.__delattr__(self, attr)\n except Exception:\n return ret\n # Let's try to set the field\n try:\n res = fielddict[attr][:2]\n except (TypeError, KeyError) as e:\n raise AttributeError(\n f'record array has no attribute {attr}') from e\n\n if val is ma.masked:\n _fill_value = _localdict['_fill_value']\n if _fill_value is not None:\n dval = _localdict['_fill_value'][attr]\n else:\n dval = val\n mval = True\n else:\n dval = ma.filled(val)\n mval = ma.getmaskarray(val)\n obj = np.ndarray.__getattribute__(self, '_data').setfield(dval, *res)\n _localdict['_mask'].__setitem__(attr, mval)\n return obj\n\n def __getitem__(self, indx):\n """\n Returns all the fields sharing the same fieldname base.\n\n The fieldname base is either `_data` or `_mask`.\n\n """\n _localdict = self.__dict__\n _mask = np.ndarray.__getattribute__(self, '_mask')\n _data = np.ndarray.view(self, _localdict['_baseclass'])\n # We want a field\n if isinstance(indx, str):\n # Make sure _sharedmask is True to propagate back to _fieldmask\n # Don't use _set_mask, there are some copies being made that\n # break propagation Don't force the mask to nomask, that wreaks\n # easy masking\n obj = _data[indx].view(ma.MaskedArray)\n obj._mask = _mask[indx]\n obj._sharedmask = True\n fval = _localdict['_fill_value']\n if fval is not None:\n obj._fill_value = fval[indx]\n # Force to masked if the mask is True\n if not obj.ndim and obj._mask:\n return ma.masked\n return obj\n # We want some elements.\n # First, the data.\n obj = np.asarray(_data[indx]).view(mrecarray)\n obj._mask = np.asarray(_mask[indx]).view(np.recarray)\n return obj\n\n def __setitem__(self, indx, value):\n """\n Sets the given record to value.\n\n """\n ma.MaskedArray.__setitem__(self, indx, value)\n if isinstance(indx, str):\n self._mask[indx] = ma.getmaskarray(value)\n\n def __str__(self):\n """\n Calculates the string representation.\n\n """\n if self.size > 1:\n mstr = [f"({','.join([str(i) for i in s])})"\n for s in zip(*[getattr(self, f) for f in self.dtype.names])]\n return f"[{', '.join(mstr)}]"\n else:\n mstr = [f"{','.join([str(i) for i in s])}"\n for s in zip([getattr(self, f) for f in self.dtype.names])]\n return f"({', '.join(mstr)})"\n\n def __repr__(self):\n """\n Calculates the repr representation.\n\n """\n _names = self.dtype.names\n fmt = f"%{max(len(n) for n in _names) + 4}s : %s"\n reprstr = [fmt % (f, getattr(self, f)) for f in self.dtype.names]\n reprstr.insert(0, 'masked_records(')\n reprstr.extend([fmt % (' fill_value', self.fill_value),\n ' )'])\n return str("\n".join(reprstr))\n\n def view(self, dtype=None, type=None):\n """\n Returns a view of the mrecarray.\n\n """\n # OK, basic copy-paste from MaskedArray.view.\n if dtype is None:\n if type is None:\n output = np.ndarray.view(self)\n else:\n output = np.ndarray.view(self, type)\n # Here again.\n elif type is None:\n try:\n if issubclass(dtype, np.ndarray):\n output = np.ndarray.view(self, dtype)\n else:\n output = np.ndarray.view(self, dtype)\n # OK, there's the change\n except TypeError:\n dtype = np.dtype(dtype)\n # we need to revert to MaskedArray, but keeping the possibility\n # of subclasses (eg, TimeSeriesRecords), so we'll force a type\n # set to the first parent\n if dtype.fields is None:\n basetype = self.__class__.__bases__[0]\n output = self.__array__().view(dtype, basetype)\n output._update_from(self)\n else:\n output = np.ndarray.view(self, dtype)\n output._fill_value = None\n else:\n output = np.ndarray.view(self, dtype, type)\n # Update the mask, just like in MaskedArray.view\n if (getattr(output, '_mask', ma.nomask) is not ma.nomask):\n mdtype = ma.make_mask_descr(output.dtype)\n output._mask = self._mask.view(mdtype, np.ndarray)\n output._mask.shape = output.shape\n return output\n\n def harden_mask(self):\n """\n Forces the mask to hard.\n\n """\n self._hardmask = True\n\n def soften_mask(self):\n """\n Forces the mask to soft\n\n """\n self._hardmask = False\n\n def copy(self):\n """\n Returns a copy of the masked record.\n\n """\n copied = self._data.copy().view(type(self))\n copied._mask = self._mask.copy()\n return copied\n\n def tolist(self, fill_value=None):\n """\n Return the data portion of the array as a list.\n\n Data items are converted to the nearest compatible Python type.\n Masked values are converted to fill_value. If fill_value is None,\n the corresponding entries in the output list will be ``None``.\n\n """\n if fill_value is not None:\n return self.filled(fill_value).tolist()\n result = np.array(self.filled().tolist(), dtype=object)\n mask = np.array(self._mask.tolist())\n result[mask] = None\n return result.tolist()\n\n def __getstate__(self):\n """Return the internal state of the masked array.\n\n This is for pickling.\n\n """\n state = (1,\n self.shape,\n self.dtype,\n self.flags.fnc,\n self._data.tobytes(),\n self._mask.tobytes(),\n self._fill_value,\n )\n return state\n\n def __setstate__(self, state):\n """\n Restore the internal state of the masked array.\n\n This is for pickling. ``state`` is typically the output of the\n ``__getstate__`` output, and is a 5-tuple:\n\n - class name\n - a tuple giving the shape of the data\n - a typecode for the data\n - a binary string for the data\n - a binary string for the mask.\n\n """\n (ver, shp, typ, isf, raw, msk, flv) = state\n np.ndarray.__setstate__(self, (shp, typ, isf, raw))\n mdtype = np.dtype([(k, np.bool) for (k, _) in self.dtype.descr])\n self.__dict__['_mask'].__setstate__((shp, mdtype, isf, msk))\n self.fill_value = flv\n\n def __reduce__(self):\n """\n Return a 3-tuple for pickling a MaskedArray.\n\n """\n return (_mrreconstruct,\n (self.__class__, self._baseclass, (0,), 'b',),\n self.__getstate__())\n\n\ndef _mrreconstruct(subtype, baseclass, baseshape, basetype,):\n """\n Build a new MaskedArray from the information stored in a pickle.\n\n """\n _data = np.ndarray.__new__(baseclass, baseshape, basetype).view(subtype)\n _mask = np.ndarray.__new__(np.ndarray, baseshape, 'b1')\n return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype,)\n\n\nmrecarray = MaskedRecords\n\n\n###############################################################################\n# Constructors #\n###############################################################################\n\n\ndef fromarrays(arraylist, dtype=None, shape=None, formats=None,\n names=None, titles=None, aligned=False, byteorder=None,\n fill_value=None):\n """\n Creates a mrecarray from a (flat) list of masked arrays.\n\n Parameters\n ----------\n arraylist : sequence\n A list of (masked) arrays. Each element of the sequence is first converted\n to a masked array if needed. If a 2D array is passed as argument, it is\n processed line by line\n dtype : {None, dtype}, optional\n Data type descriptor.\n shape : {None, integer}, optional\n Number of records. If None, shape is defined from the shape of the\n first array in the list.\n formats : {None, sequence}, optional\n Sequence of formats for each individual field. If None, the formats will\n be autodetected by inspecting the fields and selecting the highest dtype\n possible.\n names : {None, sequence}, optional\n Sequence of the names of each field.\n fill_value : {None, sequence}, optional\n Sequence of data to be used as filling values.\n\n Notes\n -----\n Lists of tuples should be preferred over lists of lists for faster processing.\n\n """\n datalist = [ma.getdata(x) for x in arraylist]\n masklist = [np.atleast_1d(ma.getmaskarray(x)) for x in arraylist]\n _array = np.rec.fromarrays(datalist,\n dtype=dtype, shape=shape, formats=formats,\n names=names, titles=titles, aligned=aligned,\n byteorder=byteorder).view(mrecarray)\n _array._mask.flat = list(zip(*masklist))\n if fill_value is not None:\n _array.fill_value = fill_value\n return _array\n\n\ndef fromrecords(reclist, dtype=None, shape=None, formats=None, names=None,\n titles=None, aligned=False, byteorder=None,\n fill_value=None, mask=ma.nomask):\n """\n Creates a MaskedRecords from a list of records.\n\n Parameters\n ----------\n reclist : sequence\n A list of records. Each element of the sequence is first converted\n to a masked array if needed. If a 2D array is passed as argument, it is\n processed line by line\n dtype : {None, dtype}, optional\n Data type descriptor.\n shape : {None,int}, optional\n Number of records. If None, ``shape`` is defined from the shape of the\n first array in the list.\n formats : {None, sequence}, optional\n Sequence of formats for each individual field. If None, the formats will\n be autodetected by inspecting the fields and selecting the highest dtype\n possible.\n names : {None, sequence}, optional\n Sequence of the names of each field.\n fill_value : {None, sequence}, optional\n Sequence of data to be used as filling values.\n mask : {nomask, sequence}, optional.\n External mask to apply on the data.\n\n Notes\n -----\n Lists of tuples should be preferred over lists of lists for faster processing.\n\n """\n # Grab the initial _fieldmask, if needed:\n _mask = getattr(reclist, '_mask', None)\n # Get the list of records.\n if isinstance(reclist, np.ndarray):\n # Make sure we don't have some hidden mask\n if isinstance(reclist, ma.MaskedArray):\n reclist = reclist.filled().view(np.ndarray)\n # Grab the initial dtype, just in case\n if dtype is None:\n dtype = reclist.dtype\n reclist = reclist.tolist()\n mrec = np.rec.fromrecords(reclist, dtype=dtype, shape=shape, formats=formats,\n names=names, titles=titles,\n aligned=aligned, byteorder=byteorder).view(mrecarray)\n # Set the fill_value if needed\n if fill_value is not None:\n mrec.fill_value = fill_value\n # Now, let's deal w/ the mask\n if mask is not ma.nomask:\n mask = np.asarray(mask)\n maskrecordlength = len(mask.dtype)\n if maskrecordlength:\n mrec._mask.flat = mask\n elif mask.ndim == 2:\n mrec._mask.flat = [tuple(m) for m in mask]\n else:\n mrec.__setmask__(mask)\n if _mask is not None:\n mrec._mask[:] = _mask\n return mrec\n\n\ndef _guessvartypes(arr):\n """\n Tries to guess the dtypes of the str_ ndarray `arr`.\n\n Guesses by testing element-wise conversion. Returns a list of dtypes.\n The array is first converted to ndarray. If the array is 2D, the test\n is performed on the first line. An exception is raised if the file is\n 3D or more.\n\n """\n vartypes = []\n arr = np.asarray(arr)\n if arr.ndim == 2:\n arr = arr[0]\n elif arr.ndim > 2:\n raise ValueError("The array should be 2D at most!")\n # Start the conversion loop.\n for f in arr:\n try:\n int(f)\n except (ValueError, TypeError):\n try:\n float(f)\n except (ValueError, TypeError):\n try:\n complex(f)\n except (ValueError, TypeError):\n vartypes.append(arr.dtype)\n else:\n vartypes.append(np.dtype(complex))\n else:\n vartypes.append(np.dtype(float))\n else:\n vartypes.append(np.dtype(int))\n return vartypes\n\n\ndef openfile(fname):\n """\n Opens the file handle of file `fname`.\n\n """\n # A file handle\n if hasattr(fname, 'readline'):\n return fname\n # Try to open the file and guess its type\n try:\n f = open(fname)\n except FileNotFoundError as e:\n raise FileNotFoundError(f"No such file: '{fname}'") from e\n if f.readline()[:2] != "\\x":\n f.seek(0, 0)\n return f\n f.close()\n raise NotImplementedError("Wow, binary file")\n\n\ndef fromtextfile(fname, delimiter=None, commentchar='#', missingchar='',\n varnames=None, vartypes=None,\n *, delimitor=np._NoValue): # backwards compatibility\n """\n Creates a mrecarray from data stored in the file `filename`.\n\n Parameters\n ----------\n fname : {file name/handle}\n Handle of an opened file.\n delimiter : {None, string}, optional\n Alphanumeric character used to separate columns in the file.\n If None, any (group of) white spacestring(s) will be used.\n commentchar : {'#', string}, optional\n Alphanumeric character used to mark the start of a comment.\n missingchar : {'', string}, optional\n String indicating missing data, and used to create the masks.\n varnames : {None, sequence}, optional\n Sequence of the variable names. If None, a list will be created from\n the first non empty line of the file.\n vartypes : {None, sequence}, optional\n Sequence of the variables dtypes. If None, it will be estimated from\n the first non-commented line.\n\n\n Ultra simple: the varnames are in the header, one line"""\n if delimitor is not np._NoValue:\n if delimiter is not None:\n raise TypeError("fromtextfile() got multiple values for argument "\n "'delimiter'")\n # NumPy 1.22.0, 2021-09-23\n warnings.warn("The 'delimitor' keyword argument of "\n "numpy.ma.mrecords.fromtextfile() is deprecated "\n "since NumPy 1.22.0, use 'delimiter' instead.",\n DeprecationWarning, stacklevel=2)\n delimiter = delimitor\n\n # Try to open the file.\n ftext = openfile(fname)\n\n # Get the first non-empty line as the varnames\n while True:\n line = ftext.readline()\n firstline = line[:line.find(commentchar)].strip()\n _varnames = firstline.split(delimiter)\n if len(_varnames) > 1:\n break\n if varnames is None:\n varnames = _varnames\n\n # Get the data.\n _variables = ma.masked_array([line.strip().split(delimiter) for line in ftext\n if line[0] != commentchar and len(line) > 1])\n (_, nfields) = _variables.shape\n ftext.close()\n\n # Try to guess the dtype.\n if vartypes is None:\n vartypes = _guessvartypes(_variables[0])\n else:\n vartypes = [np.dtype(v) for v in vartypes]\n if len(vartypes) != nfields:\n msg = f"Attempting to {len(vartypes)} dtypes for {nfields} fields!"\n msg += " Reverting to default."\n warnings.warn(msg, stacklevel=2)\n vartypes = _guessvartypes(_variables[0])\n\n # Construct the descriptor.\n mdescr = list(zip(varnames, vartypes))\n mfillv = [ma.default_fill_value(f) for f in vartypes]\n\n # Get the data and the mask.\n # We just need a list of masked_arrays. It's easier to create it like that:\n _mask = (_variables.T == missingchar)\n _datalist = [ma.masked_array(a, mask=m, dtype=t, fill_value=f)\n for (a, m, t, f) in zip(_variables.T, _mask, vartypes, mfillv)]\n\n return fromarrays(_datalist, dtype=mdescr)\n\n\ndef addfield(mrecord, newfield, newfieldname=None):\n """Adds a new field to the masked record array\n\n Uses `newfield` as data and `newfieldname` as name. If `newfieldname`\n is None, the new field name is set to 'fi', where `i` is the number of\n existing fields.\n\n """\n _data = mrecord._data\n _mask = mrecord._mask\n if newfieldname is None or newfieldname in reserved_fields:\n newfieldname = f'f{len(_data.dtype)}'\n newfield = ma.array(newfield)\n # Get the new data.\n # Create a new empty recarray\n newdtype = np.dtype(_data.dtype.descr + [(newfieldname, newfield.dtype)])\n newdata = np.recarray(_data.shape, newdtype)\n # Add the existing field\n [newdata.setfield(_data.getfield(*f), *f)\n for f in _data.dtype.fields.values()]\n # Add the new field\n newdata.setfield(newfield._data, *newdata.dtype.fields[newfieldname])\n newdata = newdata.view(MaskedRecords)\n # Get the new mask\n # Create a new empty recarray\n newmdtype = np.dtype([(n, np.bool) for n in newdtype.names])\n newmask = np.recarray(_data.shape, newmdtype)\n # Add the old masks\n [newmask.setfield(_mask.getfield(*f), *f)\n for f in _mask.dtype.fields.values()]\n # Add the mask of the new field\n newmask.setfield(ma.getmaskarray(newfield),\n *newmask.dtype.fields[newfieldname])\n newdata._mask = newmask\n return newdata\n | .venv\Lib\site-packages\numpy\ma\mrecords.py | mrecords.py | Python | 27,846 | 0.95 | 0.192755 | 0.104634 | vue-tools | 761 | 2025-03-31T20:03:28.997035 | MIT | false | 3ae018cad2f20298d542ab56af3b8e1c |
from typing import Any, TypeVar\n\nfrom numpy import dtype\n\nfrom . import MaskedArray\n\n__all__ = [\n "MaskedRecords",\n "mrecarray",\n "fromarrays",\n "fromrecords",\n "fromtextfile",\n "addfield",\n]\n\n_ShapeT_co = TypeVar("_ShapeT_co", covariant=True, bound=tuple[int, ...])\n_DTypeT_co = TypeVar("_DTypeT_co", bound=dtype, covariant=True)\n\nclass MaskedRecords(MaskedArray[_ShapeT_co, _DTypeT_co]):\n def __new__(\n cls,\n shape,\n dtype=...,\n buf=...,\n offset=...,\n strides=...,\n formats=...,\n names=...,\n titles=...,\n byteorder=...,\n aligned=...,\n mask=...,\n hard_mask=...,\n fill_value=...,\n keep_mask=...,\n copy=...,\n **options,\n ): ...\n _mask: Any\n _fill_value: Any\n @property\n def _data(self): ...\n @property\n def _fieldmask(self): ...\n def __array_finalize__(self, obj): ...\n def __len__(self): ...\n def __getattribute__(self, attr): ...\n def __setattr__(self, attr, val): ...\n def __getitem__(self, indx): ...\n def __setitem__(self, indx, value): ...\n def view(self, dtype=..., type=...): ...\n def harden_mask(self): ...\n def soften_mask(self): ...\n def copy(self): ...\n def tolist(self, fill_value=...): ...\n def __reduce__(self): ...\n\nmrecarray = MaskedRecords\n\ndef fromarrays(\n arraylist,\n dtype=...,\n shape=...,\n formats=...,\n names=...,\n titles=...,\n aligned=...,\n byteorder=...,\n fill_value=...,\n): ...\n\ndef fromrecords(\n reclist,\n dtype=...,\n shape=...,\n formats=...,\n names=...,\n titles=...,\n aligned=...,\n byteorder=...,\n fill_value=...,\n mask=...,\n): ...\n\ndef fromtextfile(\n fname,\n delimiter=...,\n commentchar=...,\n missingchar=...,\n varnames=...,\n vartypes=...,\n # NOTE: deprecated: NumPy 1.22.0, 2021-09-23\n # delimitor=...,\n): ...\n\ndef addfield(mrecord, newfield, newfieldname=...): ...\n | .venv\Lib\site-packages\numpy\ma\mrecords.pyi | mrecords.pyi | Other | 2,069 | 0.95 | 0.208333 | 0.034884 | react-lib | 727 | 2025-04-17T21:22:56.970089 | Apache-2.0 | false | b3a0f750a5aa1e49ba895f405609e379 |
==================================\nA guide to masked arrays in NumPy\n==================================\n\n.. Contents::\n\nSee http://www.scipy.org/scipy/numpy/wiki/MaskedArray (dead link)\nfor updates of this document.\n\n\nHistory\n-------\n\nAs a regular user of MaskedArray, I (Pierre G.F. Gerard-Marchant) became\nincreasingly frustrated with the subclassing of masked arrays (even if\nI can only blame my inexperience). I needed to develop a class of arrays\nthat could store some additional information along with numerical values,\nwhile keeping the possibility for missing data (picture storing a series\nof dates along with measurements, what would later become the `TimeSeries\nScikit <http://projects.scipy.org/scipy/scikits/wiki/TimeSeries>`__\n(dead link).\n\nI started to implement such a class, but then quickly realized that\nany additional information disappeared when processing these subarrays\n(for example, adding a constant value to a subarray would erase its\ndates). I ended up writing the equivalent of *numpy.core.ma* for my\nparticular class, ufuncs included. Everything went fine until I needed to\nsubclass my new class, when more problems showed up: some attributes of\nthe new subclass were lost during processing. I identified the culprit as\nMaskedArray, which returns masked ndarrays when I expected masked\narrays of my class. I was preparing myself to rewrite *numpy.core.ma*\nwhen I forced myself to learn how to subclass ndarrays. As I became more\nfamiliar with the *__new__* and *__array_finalize__* methods,\nI started to wonder why masked arrays were objects, and not ndarrays,\nand whether it wouldn't be more convenient for subclassing if they did\nbehave like regular ndarrays.\n\nThe new *maskedarray* is what I eventually come up with. The\nmain differences with the initial *numpy.core.ma* package are\nthat MaskedArray is now a subclass of *ndarray* and that the\n*_data* section can now be any subclass of *ndarray*. Apart from a\ncouple of issues listed below, the behavior of the new MaskedArray\nclass reproduces the old one. Initially the *maskedarray*\nimplementation was marginally slower than *numpy.ma* in some areas,\nbut work is underway to speed it up; the expectation is that it can be\nmade substantially faster than the present *numpy.ma*.\n\n\nNote that if the subclass has some special methods and\nattributes, they are not propagated to the masked version:\nthis would require a modification of the *__getattribute__*\nmethod (first trying *ndarray.__getattribute__*, then trying\n*self._data.__getattribute__* if an exception is raised in the first\nplace), which really slows things down.\n\nMain differences\n----------------\n\n * The *_data* part of the masked array can be any subclass of ndarray (but not recarray, cf below).\n * *fill_value* is now a property, not a function.\n * in the majority of cases, the mask is forced to *nomask* when no value is actually masked. A notable exception is when a masked array (with no masked values) has just been unpickled.\n * I got rid of the *share_mask* flag, I never understood its purpose.\n * *put*, *putmask* and *take* now mimic the ndarray methods, to avoid unpleasant surprises. Moreover, *put* and *putmask* both update the mask when needed. * if *a* is a masked array, *bool(a)* raises a *ValueError*, as it does with ndarrays.\n * in the same way, the comparison of two masked arrays is a masked array, not a boolean\n * *filled(a)* returns an array of the same subclass as *a._data*, and no test is performed on whether it is contiguous or not.\n * the mask is always printed, even if it's *nomask*, which makes things easy (for me at least) to remember that a masked array is used.\n * *cumsum* works as if the *_data* array was filled with 0. The mask is preserved, but not updated.\n * *cumprod* works as if the *_data* array was filled with 1. The mask is preserved, but not updated.\n\nNew features\n------------\n\nThis list is non-exhaustive...\n\n * the *mr_* function mimics *r_* for masked arrays.\n * the *anom* method returns the anomalies (deviations from the average)\n\nUsing the new package with numpy.core.ma\n----------------------------------------\n\nI tried to make sure that the new package can understand old masked\narrays. Unfortunately, there's no upward compatibility.\n\nFor example:\n\n>>> import numpy.core.ma as old_ma\n>>> import maskedarray as new_ma\n>>> x = old_ma.array([1,2,3,4,5], mask=[0,0,1,0,0])\n>>> x\narray(data =\n [ 1 2 999999 4 5],\n mask =\n [False False True False False],\n fill_value=999999)\n>>> y = new_ma.array([1,2,3,4,5], mask=[0,0,1,0,0])\n>>> y\narray(data = [1 2 -- 4 5],\n mask = [False False True False False],\n fill_value=999999)\n>>> x==y\narray(data =\n [True True True True True],\n mask =\n [False False True False False],\n fill_value=?)\n>>> old_ma.getmask(x) == new_ma.getmask(x)\narray([True, True, True, True, True])\n>>> old_ma.getmask(y) == new_ma.getmask(y)\narray([True, True, False, True, True])\n>>> old_ma.getmask(y)\nFalse\n\n\nUsing maskedarray with matplotlib\n---------------------------------\n\nStarting with matplotlib 0.91.2, the masked array importing will work with\nthe maskedarray branch) as well as with earlier versions.\n\nBy default matplotlib still uses numpy.ma, but there is an rcParams setting\nthat you can use to select maskedarray instead. In the matplotlibrc file\nyou will find::\n\n #maskedarray : False # True to use external maskedarray module\n # instead of numpy.ma; this is a temporary #\n setting for testing maskedarray.\n\n\nUncomment and set to True to select maskedarray everywhere.\nAlternatively, you can test a script with maskedarray by using a\ncommand-line option, e.g.::\n\n python simple_plot.py --maskedarray\n\n\nMasked records\n--------------\n\nLike *numpy.ma.core*, the *ndarray*-based implementation\nof MaskedArray is limited when working with records: you can\nmask any record of the array, but not a field in a record. If you\nneed this feature, you may want to give the *mrecords* package\na try (available in the *maskedarray* directory in the scipy\nsandbox). This module defines a new class, *MaskedRecord*. An\ninstance of this class accepts a *recarray* as data, and uses two\nmasks: the *fieldmask* has as many entries as records in the array,\neach entry with the same fields as a record, but of boolean types:\nthey indicate whether the field is masked or not; a record entry\nis flagged as masked in the *mask* array if all the fields are\nmasked. A few examples in the file should give you an idea of what\ncan be done. Note that *mrecords* is still experimental...\n\nOptimizing maskedarray\n----------------------\n\nShould masked arrays be filled before processing or not?\n--------------------------------------------------------\n\nIn the current implementation, most operations on masked arrays involve\nthe following steps:\n\n * the input arrays are filled\n * the operation is performed on the filled arrays\n * the mask is set for the results, from the combination of the input masks and the mask corresponding to the domain of the operation.\n\nFor example, consider the division of two masked arrays::\n\n import numpy\n import maskedarray as ma\n x = ma.array([1,2,3,4],mask=[1,0,0,0], dtype=numpy.float64)\n y = ma.array([-1,0,1,2], mask=[0,0,0,1], dtype=numpy.float64)\n\nThe division of x by y is then computed as::\n\n d1 = x.filled(0) # d1 = array([0., 2., 3., 4.])\n d2 = y.filled(1) # array([-1., 0., 1., 1.])\n m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m =\n array([True,False,False,True])\n dm = ma.divide.domain(d1,d2) # array([False, True, False, False])\n result = (d1/d2).view(MaskedArray) # masked_array([-0. inf, 3., 4.])\n result._mask = logical_or(m, dm)\n\nNote that a division by zero takes place. To avoid it, we can consider\nto fill the input arrays, taking the domain mask into account, so that::\n\n d1 = x._data.copy() # d1 = array([1., 2., 3., 4.])\n d2 = y._data.copy() # array([-1., 0., 1., 2.])\n dm = ma.divide.domain(d1,d2) # array([False, True, False, False])\n numpy.putmask(d2, dm, 1) # d2 = array([-1., 1., 1., 2.])\n m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m =\n array([True,False,False,True])\n result = (d1/d2).view(MaskedArray) # masked_array([-1. 0., 3., 2.])\n result._mask = logical_or(m, dm)\n\nNote that the *.copy()* is required to avoid updating the inputs with\n*putmask*. The *.filled()* method also involves a *.copy()*.\n\nA third possibility consists in avoid filling the arrays::\n\n d1 = x._data # d1 = array([1., 2., 3., 4.])\n d2 = y._data # array([-1., 0., 1., 2.])\n dm = ma.divide.domain(d1,d2) # array([False, True, False, False])\n m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m =\n array([True,False,False,True])\n result = (d1/d2).view(MaskedArray) # masked_array([-1. inf, 3., 2.])\n result._mask = logical_or(m, dm)\n\nNote that here again the division by zero takes place.\n\nA quick benchmark gives the following results:\n\n * *numpy.ma.divide* : 2.69 ms per loop\n * classical division : 2.21 ms per loop\n * division w/ prefilling : 2.34 ms per loop\n * division w/o filling : 1.55 ms per loop\n\nSo, is it worth filling the arrays beforehand ? Yes, if we are interested\nin avoiding floating-point exceptions that may fill the result with infs\nand nans. No, if we are only interested into speed...\n\n\nThanks\n------\n\nI'd like to thank Paul Dubois, Travis Oliphant and Sasha for the\noriginal masked array package: without you, I would never have started\nthat (it might be argued that I shouldn't have anyway, but that's\nanother story...). I also wish to extend these thanks to Reggie Dugard\nand Eric Firing for their suggestions and numerous improvements.\n\n\nRevision notes\n--------------\n\n * 08/25/2007 : Creation of this page\n * 01/23/2007 : The package has been moved to the SciPy sandbox, and is regularly updated: please check out your SVN version!\n | .venv\Lib\site-packages\numpy\ma\README.rst | README.rst | Other | 10,110 | 0.95 | 0.144068 | 0.141304 | awesome-app | 788 | 2025-03-05T10:15:39.737847 | BSD-3-Clause | false | 583d4eb4a51d72e84a0c5064af3d0c44 |
"""Miscellaneous functions for testing masked arrays and subclasses\n\n:author: Pierre Gerard-Marchant\n:contact: pierregm_at_uga_dot_edu\n\n"""\nimport operator\n\nimport numpy as np\nimport numpy._core.umath as umath\nimport numpy.testing\nfrom numpy import ndarray\nfrom numpy.testing import ( # noqa: F401\n assert_,\n assert_allclose,\n assert_array_almost_equal_nulp,\n assert_raises,\n build_err_msg,\n)\n\nfrom .core import filled, getmask, mask_or, masked, masked_array, nomask\n\n__all__masked = [\n 'almost', 'approx', 'assert_almost_equal', 'assert_array_almost_equal',\n 'assert_array_approx_equal', 'assert_array_compare',\n 'assert_array_equal', 'assert_array_less', 'assert_close',\n 'assert_equal', 'assert_equal_records', 'assert_mask_equal',\n 'assert_not_equal', 'fail_if_array_equal',\n ]\n\n# Include some normal test functions to avoid breaking other projects who\n# have mistakenly included them from this file. SciPy is one. That is\n# unfortunate, as some of these functions are not intended to work with\n# masked arrays. But there was no way to tell before.\nfrom unittest import TestCase # noqa: F401\n\n__some__from_testing = [\n 'TestCase', 'assert_', 'assert_allclose', 'assert_array_almost_equal_nulp',\n 'assert_raises'\n ]\n\n__all__ = __all__masked + __some__from_testing # noqa: PLE0605\n\n\ndef approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):\n """\n Returns true if all components of a and b are equal to given tolerances.\n\n If fill_value is True, masked values considered equal. Otherwise,\n masked values are considered unequal. The relative error rtol should\n be positive and << 1.0 The absolute error atol comes into play for\n those elements of b that are very small or zero; it says how small a\n must be also.\n\n """\n m = mask_or(getmask(a), getmask(b))\n d1 = filled(a)\n d2 = filled(b)\n if d1.dtype.char == "O" or d2.dtype.char == "O":\n return np.equal(d1, d2).ravel()\n x = filled(\n masked_array(d1, copy=False, mask=m), fill_value\n ).astype(np.float64)\n y = filled(masked_array(d2, copy=False, mask=m), 1).astype(np.float64)\n d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))\n return d.ravel()\n\n\ndef almost(a, b, decimal=6, fill_value=True):\n """\n Returns True if a and b are equal up to decimal places.\n\n If fill_value is True, masked values considered equal. Otherwise,\n masked values are considered unequal.\n\n """\n m = mask_or(getmask(a), getmask(b))\n d1 = filled(a)\n d2 = filled(b)\n if d1.dtype.char == "O" or d2.dtype.char == "O":\n return np.equal(d1, d2).ravel()\n x = filled(\n masked_array(d1, copy=False, mask=m), fill_value\n ).astype(np.float64)\n y = filled(masked_array(d2, copy=False, mask=m), 1).astype(np.float64)\n d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)\n return d.ravel()\n\n\ndef _assert_equal_on_sequences(actual, desired, err_msg=''):\n """\n Asserts the equality of two non-array sequences.\n\n """\n assert_equal(len(actual), len(desired), err_msg)\n for k in range(len(desired)):\n assert_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}')\n\n\ndef assert_equal_records(a, b):\n """\n Asserts that two records are equal.\n\n Pretty crude for now.\n\n """\n assert_equal(a.dtype, b.dtype)\n for f in a.dtype.names:\n (af, bf) = (operator.getitem(a, f), operator.getitem(b, f))\n if not (af is masked) and not (bf is masked):\n assert_equal(operator.getitem(a, f), operator.getitem(b, f))\n\n\ndef assert_equal(actual, desired, err_msg=''):\n """\n Asserts that two items are equal.\n\n """\n # Case #1: dictionary .....\n if isinstance(desired, dict):\n if not isinstance(actual, dict):\n raise AssertionError(repr(type(actual)))\n assert_equal(len(actual), len(desired), err_msg)\n for k, i in desired.items():\n if k not in actual:\n raise AssertionError(f"{k} not in {actual}")\n assert_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}')\n return\n # Case #2: lists .....\n if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):\n return _assert_equal_on_sequences(actual, desired, err_msg='')\n if not (isinstance(actual, ndarray) or isinstance(desired, ndarray)):\n msg = build_err_msg([actual, desired], err_msg,)\n if not desired == actual:\n raise AssertionError(msg)\n return\n # Case #4. arrays or equivalent\n if ((actual is masked) and not (desired is masked)) or \\n ((desired is masked) and not (actual is masked)):\n msg = build_err_msg([actual, desired],\n err_msg, header='', names=('x', 'y'))\n raise ValueError(msg)\n actual = np.asanyarray(actual)\n desired = np.asanyarray(desired)\n (actual_dtype, desired_dtype) = (actual.dtype, desired.dtype)\n if actual_dtype.char == "S" and desired_dtype.char == "S":\n return _assert_equal_on_sequences(actual.tolist(),\n desired.tolist(),\n err_msg='')\n return assert_array_equal(actual, desired, err_msg)\n\n\ndef fail_if_equal(actual, desired, err_msg='',):\n """\n Raises an assertion error if two items are equal.\n\n """\n if isinstance(desired, dict):\n if not isinstance(actual, dict):\n raise AssertionError(repr(type(actual)))\n fail_if_equal(len(actual), len(desired), err_msg)\n for k, i in desired.items():\n if k not in actual:\n raise AssertionError(repr(k))\n fail_if_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}')\n return\n if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):\n fail_if_equal(len(actual), len(desired), err_msg)\n for k in range(len(desired)):\n fail_if_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}')\n return\n if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray):\n return fail_if_array_equal(actual, desired, err_msg)\n msg = build_err_msg([actual, desired], err_msg)\n if not desired != actual:\n raise AssertionError(msg)\n\n\nassert_not_equal = fail_if_equal\n\n\ndef assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True):\n """\n Asserts that two items are almost equal.\n\n The test is equivalent to abs(desired-actual) < 0.5 * 10**(-decimal).\n\n """\n if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray):\n return assert_array_almost_equal(actual, desired, decimal=decimal,\n err_msg=err_msg, verbose=verbose)\n msg = build_err_msg([actual, desired],\n err_msg=err_msg, verbose=verbose)\n if not round(abs(desired - actual), decimal) == 0:\n raise AssertionError(msg)\n\n\nassert_close = assert_almost_equal\n\n\ndef assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='',\n fill_value=True):\n """\n Asserts that comparison between two masked arrays is satisfied.\n\n The comparison is elementwise.\n\n """\n # Allocate a common mask and refill\n m = mask_or(getmask(x), getmask(y))\n x = masked_array(x, copy=False, mask=m, keep_mask=False, subok=False)\n y = masked_array(y, copy=False, mask=m, keep_mask=False, subok=False)\n if ((x is masked) and not (y is masked)) or \\n ((y is masked) and not (x is masked)):\n msg = build_err_msg([x, y], err_msg=err_msg, verbose=verbose,\n header=header, names=('x', 'y'))\n raise ValueError(msg)\n # OK, now run the basic tests on filled versions\n return np.testing.assert_array_compare(comparison,\n x.filled(fill_value),\n y.filled(fill_value),\n err_msg=err_msg,\n verbose=verbose, header=header)\n\n\ndef assert_array_equal(x, y, err_msg='', verbose=True):\n """\n Checks the elementwise equality of two masked arrays.\n\n """\n assert_array_compare(operator.__eq__, x, y,\n err_msg=err_msg, verbose=verbose,\n header='Arrays are not equal')\n\n\ndef fail_if_array_equal(x, y, err_msg='', verbose=True):\n """\n Raises an assertion error if two masked arrays are not equal elementwise.\n\n """\n def compare(x, y):\n return (not np.all(approx(x, y)))\n assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,\n header='Arrays are not equal')\n\n\ndef assert_array_approx_equal(x, y, decimal=6, err_msg='', verbose=True):\n """\n Checks the equality of two masked arrays, up to given number odecimals.\n\n The equality is checked elementwise.\n\n """\n def compare(x, y):\n "Returns the result of the loose comparison between x and y)."\n return approx(x, y, rtol=10. ** -decimal)\n assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,\n header='Arrays are not almost equal')\n\n\ndef assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True):\n """\n Checks the equality of two masked arrays, up to given number odecimals.\n\n The equality is checked elementwise.\n\n """\n def compare(x, y):\n "Returns the result of the loose comparison between x and y)."\n return almost(x, y, decimal)\n assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,\n header='Arrays are not almost equal')\n\n\ndef assert_array_less(x, y, err_msg='', verbose=True):\n """\n Checks that x is smaller than y elementwise.\n\n """\n assert_array_compare(operator.__lt__, x, y,\n err_msg=err_msg, verbose=verbose,\n header='Arrays are not less-ordered')\n\n\ndef assert_mask_equal(m1, m2, err_msg=''):\n """\n Asserts the equality of two masks.\n\n """\n if m1 is nomask:\n assert_(m2 is nomask)\n if m2 is nomask:\n assert_(m1 is nomask)\n assert_array_equal(m1, m2, err_msg=err_msg)\n | .venv\Lib\site-packages\numpy\ma\testutils.py | testutils.py | Python | 10,529 | 0.95 | 0.173469 | 0.038627 | react-lib | 481 | 2024-03-01T19:04:26.745681 | Apache-2.0 | true | 1e1b2913676a102db9b1664b3c5ab552 |
"""\n=============\nMasked Arrays\n=============\n\nArrays sometimes contain invalid or missing data. When doing operations\non such arrays, we wish to suppress invalid values, which is the purpose masked\narrays fulfill (an example of typical use is given below).\n\nFor example, examine the following array:\n\n>>> x = np.array([2, 1, 3, np.nan, 5, 2, 3, np.nan])\n\nWhen we try to calculate the mean of the data, the result is undetermined:\n\n>>> np.mean(x)\nnan\n\nThe mean is calculated using roughly ``np.sum(x)/len(x)``, but since\nany number added to ``NaN`` [1]_ produces ``NaN``, this doesn't work. Enter\nmasked arrays:\n\n>>> m = np.ma.masked_array(x, np.isnan(x))\n>>> m\nmasked_array(data=[2.0, 1.0, 3.0, --, 5.0, 2.0, 3.0, --],\n mask=[False, False, False, True, False, False, False, True],\n fill_value=1e+20)\n\nHere, we construct a masked array that suppress all ``NaN`` values. We\nmay now proceed to calculate the mean of the other values:\n\n>>> np.mean(m)\n2.6666666666666665\n\n.. [1] Not-a-Number, a floating point value that is the result of an\n invalid operation.\n\n.. moduleauthor:: Pierre Gerard-Marchant\n.. moduleauthor:: Jarrod Millman\n\n"""\nfrom . import core, extras\nfrom .core import *\nfrom .extras import *\n\n__all__ = ['core', 'extras']\n__all__ += core.__all__\n__all__ += extras.__all__\n\nfrom numpy._pytesttester import PytestTester\n\ntest = PytestTester(__name__)\ndel PytestTester\n | .venv\Lib\site-packages\numpy\ma\__init__.py | __init__.py | Python | 1,459 | 0.85 | 0.018868 | 0 | awesome-app | 965 | 2023-10-26T15:19:00.355432 | Apache-2.0 | false | 6922504978ebdd8a0a467e7cb05d4862 |
from . import core, extras\nfrom .core import (\n MAError,\n MaskedArray,\n MaskError,\n MaskType,\n abs,\n absolute,\n add,\n all,\n allclose,\n allequal,\n alltrue,\n amax,\n amin,\n angle,\n anom,\n anomalies,\n any,\n append,\n arange,\n arccos,\n arccosh,\n arcsin,\n arcsinh,\n arctan,\n arctan2,\n arctanh,\n argmax,\n argmin,\n argsort,\n around,\n array,\n asanyarray,\n asarray,\n bitwise_and,\n bitwise_or,\n bitwise_xor,\n bool_,\n ceil,\n choose,\n clip,\n common_fill_value,\n compress,\n compressed,\n concatenate,\n conjugate,\n convolve,\n copy,\n correlate,\n cos,\n cosh,\n count,\n cumprod,\n cumsum,\n default_fill_value,\n diag,\n diagonal,\n diff,\n divide,\n empty,\n empty_like,\n equal,\n exp,\n expand_dims,\n fabs,\n filled,\n fix_invalid,\n flatten_mask,\n flatten_structured_array,\n floor,\n floor_divide,\n fmod,\n frombuffer,\n fromflex,\n fromfunction,\n getdata,\n getmask,\n getmaskarray,\n greater,\n greater_equal,\n harden_mask,\n hypot,\n identity,\n ids,\n indices,\n inner,\n innerproduct,\n is_mask,\n is_masked,\n isarray,\n isMA,\n isMaskedArray,\n left_shift,\n less,\n less_equal,\n log,\n log2,\n log10,\n logical_and,\n logical_not,\n logical_or,\n logical_xor,\n make_mask,\n make_mask_descr,\n make_mask_none,\n mask_or,\n masked,\n masked_array,\n masked_equal,\n masked_greater,\n masked_greater_equal,\n masked_inside,\n masked_invalid,\n masked_less,\n masked_less_equal,\n masked_not_equal,\n masked_object,\n masked_outside,\n masked_print_option,\n masked_singleton,\n masked_values,\n masked_where,\n max,\n maximum,\n maximum_fill_value,\n mean,\n min,\n minimum,\n minimum_fill_value,\n mod,\n multiply,\n mvoid,\n ndim,\n negative,\n nomask,\n nonzero,\n not_equal,\n ones,\n ones_like,\n outer,\n outerproduct,\n power,\n prod,\n product,\n ptp,\n put,\n putmask,\n ravel,\n remainder,\n repeat,\n reshape,\n resize,\n right_shift,\n round,\n round_,\n set_fill_value,\n shape,\n sin,\n sinh,\n size,\n soften_mask,\n sometrue,\n sort,\n sqrt,\n squeeze,\n std,\n subtract,\n sum,\n swapaxes,\n take,\n tan,\n tanh,\n trace,\n transpose,\n true_divide,\n var,\n where,\n zeros,\n zeros_like,\n)\nfrom .extras import (\n apply_along_axis,\n apply_over_axes,\n atleast_1d,\n atleast_2d,\n atleast_3d,\n average,\n clump_masked,\n clump_unmasked,\n column_stack,\n compress_cols,\n compress_nd,\n compress_rowcols,\n compress_rows,\n corrcoef,\n count_masked,\n cov,\n diagflat,\n dot,\n dstack,\n ediff1d,\n flatnotmasked_contiguous,\n flatnotmasked_edges,\n hsplit,\n hstack,\n in1d,\n intersect1d,\n isin,\n mask_cols,\n mask_rowcols,\n mask_rows,\n masked_all,\n masked_all_like,\n median,\n mr_,\n ndenumerate,\n notmasked_contiguous,\n notmasked_edges,\n polyfit,\n row_stack,\n setdiff1d,\n setxor1d,\n stack,\n union1d,\n unique,\n vander,\n vstack,\n)\n\n__all__ = [\n "core",\n "extras",\n "MAError",\n "MaskError",\n "MaskType",\n "MaskedArray",\n "abs",\n "absolute",\n "add",\n "all",\n "allclose",\n "allequal",\n "alltrue",\n "amax",\n "amin",\n "angle",\n "anom",\n "anomalies",\n "any",\n "append",\n "arange",\n "arccos",\n "arccosh",\n "arcsin",\n "arcsinh",\n "arctan",\n "arctan2",\n "arctanh",\n "argmax",\n "argmin",\n "argsort",\n "around",\n "array",\n "asanyarray",\n "asarray",\n "bitwise_and",\n "bitwise_or",\n "bitwise_xor",\n "bool_",\n "ceil",\n "choose",\n "clip",\n "common_fill_value",\n "compress",\n "compressed",\n "concatenate",\n "conjugate",\n "convolve",\n "copy",\n "correlate",\n "cos",\n "cosh",\n "count",\n "cumprod",\n "cumsum",\n "default_fill_value",\n "diag",\n "diagonal",\n "diff",\n "divide",\n "empty",\n "empty_like",\n "equal",\n "exp",\n "expand_dims",\n "fabs",\n "filled",\n "fix_invalid",\n "flatten_mask",\n "flatten_structured_array",\n "floor",\n "floor_divide",\n "fmod",\n "frombuffer",\n "fromflex",\n "fromfunction",\n "getdata",\n "getmask",\n "getmaskarray",\n "greater",\n "greater_equal",\n "harden_mask",\n "hypot",\n "identity",\n "ids",\n "indices",\n "inner",\n "innerproduct",\n "isMA",\n "isMaskedArray",\n "is_mask",\n "is_masked",\n "isarray",\n "left_shift",\n "less",\n "less_equal",\n "log",\n "log10",\n "log2",\n "logical_and",\n "logical_not",\n "logical_or",\n "logical_xor",\n "make_mask",\n "make_mask_descr",\n "make_mask_none",\n "mask_or",\n "masked",\n "masked_array",\n "masked_equal",\n "masked_greater",\n "masked_greater_equal",\n "masked_inside",\n "masked_invalid",\n "masked_less",\n "masked_less_equal",\n "masked_not_equal",\n "masked_object",\n "masked_outside",\n "masked_print_option",\n "masked_singleton",\n "masked_values",\n "masked_where",\n "max",\n "maximum",\n "maximum_fill_value",\n "mean",\n "min",\n "minimum",\n "minimum_fill_value",\n "mod",\n "multiply",\n "mvoid",\n "ndim",\n "negative",\n "nomask",\n "nonzero",\n "not_equal",\n "ones",\n "ones_like",\n "outer",\n "outerproduct",\n "power",\n "prod",\n "product",\n "ptp",\n "put",\n "putmask",\n "ravel",\n "remainder",\n "repeat",\n "reshape",\n "resize",\n "right_shift",\n "round",\n "round_",\n "set_fill_value",\n "shape",\n "sin",\n "sinh",\n "size",\n "soften_mask",\n "sometrue",\n "sort",\n "sqrt",\n "squeeze",\n "std",\n "subtract",\n "sum",\n "swapaxes",\n "take",\n "tan",\n "tanh",\n "trace",\n "transpose",\n "true_divide",\n "var",\n "where",\n "zeros",\n "zeros_like",\n "apply_along_axis",\n "apply_over_axes",\n "atleast_1d",\n "atleast_2d",\n "atleast_3d",\n "average",\n "clump_masked",\n "clump_unmasked",\n "column_stack",\n "compress_cols",\n "compress_nd",\n "compress_rowcols",\n "compress_rows",\n "count_masked",\n "corrcoef",\n "cov",\n "diagflat",\n "dot",\n "dstack",\n "ediff1d",\n "flatnotmasked_contiguous",\n "flatnotmasked_edges",\n "hsplit",\n "hstack",\n "isin",\n "in1d",\n "intersect1d",\n "mask_cols",\n "mask_rowcols",\n "mask_rows",\n "masked_all",\n "masked_all_like",\n "median",\n "mr_",\n "ndenumerate",\n "notmasked_contiguous",\n "notmasked_edges",\n "polyfit",\n "row_stack",\n "setdiff1d",\n "setxor1d",\n "stack",\n "unique",\n "union1d",\n "vander",\n "vstack",\n]\n | .venv\Lib\site-packages\numpy\ma\__init__.pyi | __init__.pyi | Other | 7,404 | 0.85 | 0 | 0 | react-lib | 664 | 2025-03-04T07:08:26.168106 | BSD-3-Clause | false | 1c28ee5c05d8e1876c73bca6600d623e |
import pytest\n\nimport numpy as np\nfrom numpy.ma import masked_array\nfrom numpy.testing import assert_array_equal\n\n\ndef test_matrix_transpose_raises_error_for_1d():\n msg = "matrix transpose with ndim < 2 is undefined"\n ma_arr = masked_array(data=[1, 2, 3, 4, 5, 6],\n mask=[1, 0, 1, 1, 1, 0])\n with pytest.raises(ValueError, match=msg):\n ma_arr.mT\n\n\ndef test_matrix_transpose_equals_transpose_2d():\n ma_arr = masked_array(data=[[1, 2, 3], [4, 5, 6]],\n mask=[[1, 0, 1], [1, 1, 0]])\n assert_array_equal(ma_arr.T, ma_arr.mT)\n\n\nARRAY_SHAPES_TO_TEST = (\n (5, 2),\n (5, 2, 3),\n (5, 2, 3, 4),\n)\n\n\n@pytest.mark.parametrize("shape", ARRAY_SHAPES_TO_TEST)\ndef test_matrix_transpose_equals_swapaxes(shape):\n num_of_axes = len(shape)\n vec = np.arange(shape[-1])\n arr = np.broadcast_to(vec, shape)\n\n rng = np.random.default_rng(42)\n mask = rng.choice([0, 1], size=shape)\n ma_arr = masked_array(data=arr, mask=mask)\n\n tgt = np.swapaxes(arr, num_of_axes - 2, num_of_axes - 1)\n assert_array_equal(tgt, ma_arr.mT)\n | .venv\Lib\site-packages\numpy\ma\tests\test_arrayobject.py | test_arrayobject.py | Python | 1,139 | 0.85 | 0.075 | 0 | react-lib | 315 | 2024-06-20T00:44:00.362011 | BSD-3-Clause | true | 45774d88d0f34efd5992b1ed35e65564 |
"""Test deprecation and future warnings.\n\n"""\nimport io\nimport textwrap\n\nimport pytest\n\nimport numpy as np\nfrom numpy.ma.core import MaskedArrayFutureWarning\nfrom numpy.ma.testutils import assert_equal\nfrom numpy.testing import assert_warns\n\n\nclass TestArgsort:\n """ gh-8701 """\n def _test_base(self, argsort, cls):\n arr_0d = np.array(1).view(cls)\n argsort(arr_0d)\n\n arr_1d = np.array([1, 2, 3]).view(cls)\n argsort(arr_1d)\n\n # argsort has a bad default for >1d arrays\n arr_2d = np.array([[1, 2], [3, 4]]).view(cls)\n result = assert_warns(\n np.ma.core.MaskedArrayFutureWarning, argsort, arr_2d)\n assert_equal(result, argsort(arr_2d, axis=None))\n\n # should be no warnings for explicitly specifying it\n argsort(arr_2d, axis=None)\n argsort(arr_2d, axis=-1)\n\n def test_function_ndarray(self):\n return self._test_base(np.ma.argsort, np.ndarray)\n\n def test_function_maskedarray(self):\n return self._test_base(np.ma.argsort, np.ma.MaskedArray)\n\n def test_method(self):\n return self._test_base(np.ma.MaskedArray.argsort, np.ma.MaskedArray)\n\n\nclass TestMinimumMaximum:\n\n def test_axis_default(self):\n # NumPy 1.13, 2017-05-06\n\n data1d = np.ma.arange(6)\n data2d = data1d.reshape(2, 3)\n\n ma_min = np.ma.minimum.reduce\n ma_max = np.ma.maximum.reduce\n\n # check that the default axis is still None, but warns on 2d arrays\n result = assert_warns(MaskedArrayFutureWarning, ma_max, data2d)\n assert_equal(result, ma_max(data2d, axis=None))\n\n result = assert_warns(MaskedArrayFutureWarning, ma_min, data2d)\n assert_equal(result, ma_min(data2d, axis=None))\n\n # no warnings on 1d, as both new and old defaults are equivalent\n result = ma_min(data1d)\n assert_equal(result, ma_min(data1d, axis=None))\n assert_equal(result, ma_min(data1d, axis=0))\n\n result = ma_max(data1d)\n assert_equal(result, ma_max(data1d, axis=None))\n assert_equal(result, ma_max(data1d, axis=0))\n\n\nclass TestFromtextfile:\n def test_fromtextfile_delimitor(self):\n # NumPy 1.22.0, 2021-09-23\n\n textfile = io.StringIO(textwrap.dedent(\n """\n A,B,C,D\n 'string 1';1;1.0;'mixed column'\n 'string 2';2;2.0;\n 'string 3';3;3.0;123\n 'string 4';4;4.0;3.14\n """\n ))\n\n with pytest.warns(DeprecationWarning):\n result = np.ma.mrecords.fromtextfile(textfile, delimitor=';')\n | .venv\Lib\site-packages\numpy\ma\tests\test_deprecations.py | test_deprecations.py | Python | 2,656 | 0.95 | 0.126437 | 0.095238 | react-lib | 645 | 2024-12-30T04:15:49.946273 | Apache-2.0 | true | 8576db1312798f04a74011e11ee04b59 |
"""Tests suite for MaskedArray.\nAdapted from the original test_ma by Pierre Gerard-Marchant\n\n:author: Pierre Gerard-Marchant\n:contact: pierregm_at_uga_dot_edu\n\n"""\nimport itertools\nimport warnings\n\nimport pytest\n\nimport numpy as np\nfrom numpy._core.numeric import normalize_axis_tuple\nfrom numpy.ma.core import (\n MaskedArray,\n arange,\n array,\n count,\n getmaskarray,\n masked,\n masked_array,\n nomask,\n ones,\n shape,\n zeros,\n)\nfrom numpy.ma.extras import (\n _covhelper,\n apply_along_axis,\n apply_over_axes,\n atleast_1d,\n atleast_2d,\n atleast_3d,\n average,\n clump_masked,\n clump_unmasked,\n compress_nd,\n compress_rowcols,\n corrcoef,\n cov,\n diagflat,\n dot,\n ediff1d,\n flatnotmasked_contiguous,\n in1d,\n intersect1d,\n isin,\n mask_rowcols,\n masked_all,\n masked_all_like,\n median,\n mr_,\n ndenumerate,\n notmasked_contiguous,\n notmasked_edges,\n polyfit,\n setdiff1d,\n setxor1d,\n stack,\n union1d,\n unique,\n vstack,\n)\nfrom numpy.ma.testutils import (\n assert_,\n assert_almost_equal,\n assert_array_equal,\n assert_equal,\n)\nfrom numpy.testing import assert_warns, suppress_warnings\n\n\nclass TestGeneric:\n #\n def test_masked_all(self):\n # Tests masked_all\n # Standard dtype\n test = masked_all((2,), dtype=float)\n control = array([1, 1], mask=[1, 1], dtype=float)\n assert_equal(test, control)\n # Flexible dtype\n dt = np.dtype({'names': ['a', 'b'], 'formats': ['f', 'f']})\n test = masked_all((2,), dtype=dt)\n control = array([(0, 0), (0, 0)], mask=[(1, 1), (1, 1)], dtype=dt)\n assert_equal(test, control)\n test = masked_all((2, 2), dtype=dt)\n control = array([[(0, 0), (0, 0)], [(0, 0), (0, 0)]],\n mask=[[(1, 1), (1, 1)], [(1, 1), (1, 1)]],\n dtype=dt)\n assert_equal(test, control)\n # Nested dtype\n dt = np.dtype([('a', 'f'), ('b', [('ba', 'f'), ('bb', 'f')])])\n test = masked_all((2,), dtype=dt)\n control = array([(1, (1, 1)), (1, (1, 1))],\n mask=[(1, (1, 1)), (1, (1, 1))], dtype=dt)\n assert_equal(test, control)\n test = masked_all((2,), dtype=dt)\n control = array([(1, (1, 1)), (1, (1, 1))],\n mask=[(1, (1, 1)), (1, (1, 1))], dtype=dt)\n assert_equal(test, control)\n test = masked_all((1, 1), dtype=dt)\n control = array([[(1, (1, 1))]], mask=[[(1, (1, 1))]], dtype=dt)\n assert_equal(test, control)\n\n def test_masked_all_with_object_nested(self):\n # Test masked_all works with nested array with dtype of an 'object'\n # refers to issue #15895\n my_dtype = np.dtype([('b', ([('c', object)], (1,)))])\n masked_arr = np.ma.masked_all((1,), my_dtype)\n\n assert_equal(type(masked_arr['b']), np.ma.core.MaskedArray)\n assert_equal(type(masked_arr['b']['c']), np.ma.core.MaskedArray)\n assert_equal(len(masked_arr['b']['c']), 1)\n assert_equal(masked_arr['b']['c'].shape, (1, 1))\n assert_equal(masked_arr['b']['c']._fill_value.shape, ())\n\n def test_masked_all_with_object(self):\n # same as above except that the array is not nested\n my_dtype = np.dtype([('b', (object, (1,)))])\n masked_arr = np.ma.masked_all((1,), my_dtype)\n\n assert_equal(type(masked_arr['b']), np.ma.core.MaskedArray)\n assert_equal(len(masked_arr['b']), 1)\n assert_equal(masked_arr['b'].shape, (1, 1))\n assert_equal(masked_arr['b']._fill_value.shape, ())\n\n def test_masked_all_like(self):\n # Tests masked_all\n # Standard dtype\n base = array([1, 2], dtype=float)\n test = masked_all_like(base)\n control = array([1, 1], mask=[1, 1], dtype=float)\n assert_equal(test, control)\n # Flexible dtype\n dt = np.dtype({'names': ['a', 'b'], 'formats': ['f', 'f']})\n base = array([(0, 0), (0, 0)], mask=[(1, 1), (1, 1)], dtype=dt)\n test = masked_all_like(base)\n control = array([(10, 10), (10, 10)], mask=[(1, 1), (1, 1)], dtype=dt)\n assert_equal(test, control)\n # Nested dtype\n dt = np.dtype([('a', 'f'), ('b', [('ba', 'f'), ('bb', 'f')])])\n control = array([(1, (1, 1)), (1, (1, 1))],\n mask=[(1, (1, 1)), (1, (1, 1))], dtype=dt)\n test = masked_all_like(control)\n assert_equal(test, control)\n\n def check_clump(self, f):\n for i in range(1, 7):\n for j in range(2**i):\n k = np.arange(i, dtype=int)\n ja = np.full(i, j, dtype=int)\n a = masked_array(2**k)\n a.mask = (ja & (2**k)) != 0\n s = 0\n for sl in f(a):\n s += a.data[sl].sum()\n if f == clump_unmasked:\n assert_equal(a.compressed().sum(), s)\n else:\n a.mask = ~a.mask\n assert_equal(a.compressed().sum(), s)\n\n def test_clump_masked(self):\n # Test clump_masked\n a = masked_array(np.arange(10))\n a[[0, 1, 2, 6, 8, 9]] = masked\n #\n test = clump_masked(a)\n control = [slice(0, 3), slice(6, 7), slice(8, 10)]\n assert_equal(test, control)\n\n self.check_clump(clump_masked)\n\n def test_clump_unmasked(self):\n # Test clump_unmasked\n a = masked_array(np.arange(10))\n a[[0, 1, 2, 6, 8, 9]] = masked\n test = clump_unmasked(a)\n control = [slice(3, 6), slice(7, 8), ]\n assert_equal(test, control)\n\n self.check_clump(clump_unmasked)\n\n def test_flatnotmasked_contiguous(self):\n # Test flatnotmasked_contiguous\n a = arange(10)\n # No mask\n test = flatnotmasked_contiguous(a)\n assert_equal(test, [slice(0, a.size)])\n # mask of all false\n a.mask = np.zeros(10, dtype=bool)\n assert_equal(test, [slice(0, a.size)])\n # Some mask\n a[(a < 3) | (a > 8) | (a == 5)] = masked\n test = flatnotmasked_contiguous(a)\n assert_equal(test, [slice(3, 5), slice(6, 9)])\n #\n a[:] = masked\n test = flatnotmasked_contiguous(a)\n assert_equal(test, [])\n\n\nclass TestAverage:\n # Several tests of average. Why so many ? Good point...\n def test_testAverage1(self):\n # Test of average.\n ott = array([0., 1., 2., 3.], mask=[True, False, False, False])\n assert_equal(2.0, average(ott, axis=0))\n assert_equal(2.0, average(ott, weights=[1., 1., 2., 1.]))\n result, wts = average(ott, weights=[1., 1., 2., 1.], returned=True)\n assert_equal(2.0, result)\n assert_(wts == 4.0)\n ott[:] = masked\n assert_equal(average(ott, axis=0).mask, [True])\n ott = array([0., 1., 2., 3.], mask=[True, False, False, False])\n ott = ott.reshape(2, 2)\n ott[:, 1] = masked\n assert_equal(average(ott, axis=0), [2.0, 0.0])\n assert_equal(average(ott, axis=1).mask[0], [True])\n assert_equal([2., 0.], average(ott, axis=0))\n result, wts = average(ott, axis=0, returned=True)\n assert_equal(wts, [1., 0.])\n\n def test_testAverage2(self):\n # More tests of average.\n w1 = [0, 1, 1, 1, 1, 0]\n w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]]\n x = arange(6, dtype=np.float64)\n assert_equal(average(x, axis=0), 2.5)\n assert_equal(average(x, axis=0, weights=w1), 2.5)\n y = array([arange(6, dtype=np.float64), 2.0 * arange(6)])\n assert_equal(average(y, None), np.add.reduce(np.arange(6)) * 3. / 12.)\n assert_equal(average(y, axis=0), np.arange(6) * 3. / 2.)\n assert_equal(average(y, axis=1),\n [average(x, axis=0), average(x, axis=0) * 2.0])\n assert_equal(average(y, None, weights=w2), 20. / 6.)\n assert_equal(average(y, axis=0, weights=w2),\n [0., 1., 2., 3., 4., 10.])\n assert_equal(average(y, axis=1),\n [average(x, axis=0), average(x, axis=0) * 2.0])\n m1 = zeros(6)\n m2 = [0, 0, 1, 1, 0, 0]\n m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]]\n m4 = ones(6)\n m5 = [0, 1, 1, 1, 1, 1]\n assert_equal(average(masked_array(x, m1), axis=0), 2.5)\n assert_equal(average(masked_array(x, m2), axis=0), 2.5)\n assert_equal(average(masked_array(x, m4), axis=0).mask, [True])\n assert_equal(average(masked_array(x, m5), axis=0), 0.0)\n assert_equal(count(average(masked_array(x, m4), axis=0)), 0)\n z = masked_array(y, m3)\n assert_equal(average(z, None), 20. / 6.)\n assert_equal(average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5])\n assert_equal(average(z, axis=1), [2.5, 5.0])\n assert_equal(average(z, axis=0, weights=w2),\n [0., 1., 99., 99., 4.0, 10.0])\n\n def test_testAverage3(self):\n # Yet more tests of average!\n a = arange(6)\n b = arange(6) * 3\n r1, w1 = average([[a, b], [b, a]], axis=1, returned=True)\n assert_equal(shape(r1), shape(w1))\n assert_equal(r1.shape, w1.shape)\n r2, w2 = average(ones((2, 2, 3)), axis=0, weights=[3, 1], returned=True)\n assert_equal(shape(w2), shape(r2))\n r2, w2 = average(ones((2, 2, 3)), returned=True)\n assert_equal(shape(w2), shape(r2))\n r2, w2 = average(ones((2, 2, 3)), weights=ones((2, 2, 3)), returned=True)\n assert_equal(shape(w2), shape(r2))\n a2d = array([[1, 2], [0, 4]], float)\n a2dm = masked_array(a2d, [[False, False], [True, False]])\n a2da = average(a2d, axis=0)\n assert_equal(a2da, [0.5, 3.0])\n a2dma = average(a2dm, axis=0)\n assert_equal(a2dma, [1.0, 3.0])\n a2dma = average(a2dm, axis=None)\n assert_equal(a2dma, 7. / 3.)\n a2dma = average(a2dm, axis=1)\n assert_equal(a2dma, [1.5, 4.0])\n\n def test_testAverage4(self):\n # Test that `keepdims` works with average\n x = np.array([2, 3, 4]).reshape(3, 1)\n b = np.ma.array(x, mask=[[False], [False], [True]])\n w = np.array([4, 5, 6]).reshape(3, 1)\n actual = average(b, weights=w, axis=1, keepdims=True)\n desired = masked_array([[2.], [3.], [4.]], [[False], [False], [True]])\n assert_equal(actual, desired)\n\n def test_weight_and_input_dims_different(self):\n # this test mirrors a test for np.average()\n # in lib/test/test_function_base.py\n y = np.arange(12).reshape(2, 2, 3)\n w = np.array([0., 0., 1., .5, .5, 0., 0., .5, .5, 1., 0., 0.])\\n .reshape(2, 2, 3)\n\n m = np.full((2, 2, 3), False)\n yma = np.ma.array(y, mask=m)\n subw0 = w[:, :, 0]\n\n actual = average(yma, axis=(0, 1), weights=subw0)\n desired = masked_array([7., 8., 9.], mask=[False, False, False])\n assert_almost_equal(actual, desired)\n\n m = np.full((2, 2, 3), False)\n m[:, :, 0] = True\n m[0, 0, 1] = True\n yma = np.ma.array(y, mask=m)\n actual = average(yma, axis=(0, 1), weights=subw0)\n desired = masked_array(\n [np.nan, 8., 9.],\n mask=[True, False, False])\n assert_almost_equal(actual, desired)\n\n m = np.full((2, 2, 3), False)\n yma = np.ma.array(y, mask=m)\n\n subw1 = w[1, :, :]\n actual = average(yma, axis=(1, 2), weights=subw1)\n desired = masked_array([2.25, 8.25], mask=[False, False])\n assert_almost_equal(actual, desired)\n\n # here the weights have the wrong shape for the specified axes\n with pytest.raises(\n ValueError,\n match="Shape of weights must be consistent with "\n "shape of a along specified axis"):\n average(yma, axis=(0, 1, 2), weights=subw0)\n\n with pytest.raises(\n ValueError,\n match="Shape of weights must be consistent with "\n "shape of a along specified axis"):\n average(yma, axis=(0, 1), weights=subw1)\n\n # swapping the axes should be same as transposing weights\n actual = average(yma, axis=(1, 0), weights=subw0)\n desired = average(yma, axis=(0, 1), weights=subw0.T)\n assert_almost_equal(actual, desired)\n\n def test_onintegers_with_mask(self):\n # Test average on integers with mask\n a = average(array([1, 2]))\n assert_equal(a, 1.5)\n a = average(array([1, 2, 3, 4], mask=[False, False, True, True]))\n assert_equal(a, 1.5)\n\n def test_complex(self):\n # Test with complex data.\n # (Regression test for https://github.com/numpy/numpy/issues/2684)\n mask = np.array([[0, 0, 0, 1, 0],\n [0, 1, 0, 0, 0]], dtype=bool)\n a = masked_array([[0, 1 + 2j, 3 + 4j, 5 + 6j, 7 + 8j],\n [9j, 0 + 1j, 2 + 3j, 4 + 5j, 7 + 7j]],\n mask=mask)\n\n av = average(a)\n expected = np.average(a.compressed())\n assert_almost_equal(av.real, expected.real)\n assert_almost_equal(av.imag, expected.imag)\n\n av0 = average(a, axis=0)\n expected0 = average(a.real, axis=0) + average(a.imag, axis=0) * 1j\n assert_almost_equal(av0.real, expected0.real)\n assert_almost_equal(av0.imag, expected0.imag)\n\n av1 = average(a, axis=1)\n expected1 = average(a.real, axis=1) + average(a.imag, axis=1) * 1j\n assert_almost_equal(av1.real, expected1.real)\n assert_almost_equal(av1.imag, expected1.imag)\n\n # Test with the 'weights' argument.\n wts = np.array([[0.5, 1.0, 2.0, 1.0, 0.5],\n [1.0, 1.0, 1.0, 1.0, 1.0]])\n wav = average(a, weights=wts)\n expected = np.average(a.compressed(), weights=wts[~mask])\n assert_almost_equal(wav.real, expected.real)\n assert_almost_equal(wav.imag, expected.imag)\n\n wav0 = average(a, weights=wts, axis=0)\n expected0 = (average(a.real, weights=wts, axis=0) +\n average(a.imag, weights=wts, axis=0) * 1j)\n assert_almost_equal(wav0.real, expected0.real)\n assert_almost_equal(wav0.imag, expected0.imag)\n\n wav1 = average(a, weights=wts, axis=1)\n expected1 = (average(a.real, weights=wts, axis=1) +\n average(a.imag, weights=wts, axis=1) * 1j)\n assert_almost_equal(wav1.real, expected1.real)\n assert_almost_equal(wav1.imag, expected1.imag)\n\n @pytest.mark.parametrize(\n 'x, axis, expected_avg, weights, expected_wavg, expected_wsum',\n [([1, 2, 3], None, [2.0], [3, 4, 1], [1.75], [8.0]),\n ([[1, 2, 5], [1, 6, 11]], 0, [[1.0, 4.0, 8.0]],\n [1, 3], [[1.0, 5.0, 9.5]], [[4, 4, 4]])],\n )\n def test_basic_keepdims(self, x, axis, expected_avg,\n weights, expected_wavg, expected_wsum):\n avg = np.ma.average(x, axis=axis, keepdims=True)\n assert avg.shape == np.shape(expected_avg)\n assert_array_equal(avg, expected_avg)\n\n wavg = np.ma.average(x, axis=axis, weights=weights, keepdims=True)\n assert wavg.shape == np.shape(expected_wavg)\n assert_array_equal(wavg, expected_wavg)\n\n wavg, wsum = np.ma.average(x, axis=axis, weights=weights,\n returned=True, keepdims=True)\n assert wavg.shape == np.shape(expected_wavg)\n assert_array_equal(wavg, expected_wavg)\n assert wsum.shape == np.shape(expected_wsum)\n assert_array_equal(wsum, expected_wsum)\n\n def test_masked_weights(self):\n # Test with masked weights.\n # (Regression test for https://github.com/numpy/numpy/issues/10438)\n a = np.ma.array(np.arange(9).reshape(3, 3),\n mask=[[1, 0, 0], [1, 0, 0], [0, 0, 0]])\n weights_unmasked = masked_array([5, 28, 31], mask=False)\n weights_masked = masked_array([5, 28, 31], mask=[1, 0, 0])\n\n avg_unmasked = average(a, axis=0,\n weights=weights_unmasked, returned=False)\n expected_unmasked = np.array([6.0, 5.21875, 6.21875])\n assert_almost_equal(avg_unmasked, expected_unmasked)\n\n avg_masked = average(a, axis=0, weights=weights_masked, returned=False)\n expected_masked = np.array([6.0, 5.576271186440678, 6.576271186440678])\n assert_almost_equal(avg_masked, expected_masked)\n\n # weights should be masked if needed\n # depending on the array mask. This is to avoid summing\n # masked nan or other values that are not cancelled by a zero\n a = np.ma.array([1.0, 2.0, 3.0, 4.0],\n mask=[False, False, True, True])\n avg_unmasked = average(a, weights=[1, 1, 1, np.nan])\n\n assert_almost_equal(avg_unmasked, 1.5)\n\n a = np.ma.array([\n [1.0, 2.0, 3.0, 4.0],\n [5.0, 6.0, 7.0, 8.0],\n [9.0, 1.0, 2.0, 3.0],\n ], mask=[\n [False, True, True, False],\n [True, False, True, True],\n [True, False, True, False],\n ])\n\n avg_masked = np.ma.average(a, weights=[1, np.nan, 1], axis=0)\n avg_expected = np.ma.array([1.0, np.nan, np.nan, 3.5],\n mask=[False, True, True, False])\n\n assert_almost_equal(avg_masked, avg_expected)\n assert_equal(avg_masked.mask, avg_expected.mask)\n\n\nclass TestConcatenator:\n # Tests for mr_, the equivalent of r_ for masked arrays.\n\n def test_1d(self):\n # Tests mr_ on 1D arrays.\n assert_array_equal(mr_[1, 2, 3, 4, 5, 6], array([1, 2, 3, 4, 5, 6]))\n b = ones(5)\n m = [1, 0, 0, 0, 0]\n d = masked_array(b, mask=m)\n c = mr_[d, 0, 0, d]\n assert_(isinstance(c, MaskedArray))\n assert_array_equal(c, [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1])\n assert_array_equal(c.mask, mr_[m, 0, 0, m])\n\n def test_2d(self):\n # Tests mr_ on 2D arrays.\n a_1 = np.random.rand(5, 5)\n a_2 = np.random.rand(5, 5)\n m_1 = np.round(np.random.rand(5, 5), 0)\n m_2 = np.round(np.random.rand(5, 5), 0)\n b_1 = masked_array(a_1, mask=m_1)\n b_2 = masked_array(a_2, mask=m_2)\n # append columns\n d = mr_['1', b_1, b_2]\n assert_(d.shape == (5, 10))\n assert_array_equal(d[:, :5], b_1)\n assert_array_equal(d[:, 5:], b_2)\n assert_array_equal(d.mask, np.r_['1', m_1, m_2])\n d = mr_[b_1, b_2]\n assert_(d.shape == (10, 5))\n assert_array_equal(d[:5, :], b_1)\n assert_array_equal(d[5:, :], b_2)\n assert_array_equal(d.mask, np.r_[m_1, m_2])\n\n def test_masked_constant(self):\n actual = mr_[np.ma.masked, 1]\n assert_equal(actual.mask, [True, False])\n assert_equal(actual.data[1], 1)\n\n actual = mr_[[1, 2], np.ma.masked]\n assert_equal(actual.mask, [False, False, True])\n assert_equal(actual.data[:2], [1, 2])\n\n\nclass TestNotMasked:\n # Tests notmasked_edges and notmasked_contiguous.\n\n def test_edges(self):\n # Tests unmasked_edges\n data = masked_array(np.arange(25).reshape(5, 5),\n mask=[[0, 0, 1, 0, 0],\n [0, 0, 0, 1, 1],\n [1, 1, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [1, 1, 1, 0, 0]],)\n test = notmasked_edges(data, None)\n assert_equal(test, [0, 24])\n test = notmasked_edges(data, 0)\n assert_equal(test[0], [(0, 0, 1, 0, 0), (0, 1, 2, 3, 4)])\n assert_equal(test[1], [(3, 3, 3, 4, 4), (0, 1, 2, 3, 4)])\n test = notmasked_edges(data, 1)\n assert_equal(test[0], [(0, 1, 2, 3, 4), (0, 0, 2, 0, 3)])\n assert_equal(test[1], [(0, 1, 2, 3, 4), (4, 2, 4, 4, 4)])\n #\n test = notmasked_edges(data.data, None)\n assert_equal(test, [0, 24])\n test = notmasked_edges(data.data, 0)\n assert_equal(test[0], [(0, 0, 0, 0, 0), (0, 1, 2, 3, 4)])\n assert_equal(test[1], [(4, 4, 4, 4, 4), (0, 1, 2, 3, 4)])\n test = notmasked_edges(data.data, -1)\n assert_equal(test[0], [(0, 1, 2, 3, 4), (0, 0, 0, 0, 0)])\n assert_equal(test[1], [(0, 1, 2, 3, 4), (4, 4, 4, 4, 4)])\n #\n data[-2] = masked\n test = notmasked_edges(data, 0)\n assert_equal(test[0], [(0, 0, 1, 0, 0), (0, 1, 2, 3, 4)])\n assert_equal(test[1], [(1, 1, 2, 4, 4), (0, 1, 2, 3, 4)])\n test = notmasked_edges(data, -1)\n assert_equal(test[0], [(0, 1, 2, 4), (0, 0, 2, 3)])\n assert_equal(test[1], [(0, 1, 2, 4), (4, 2, 4, 4)])\n\n def test_contiguous(self):\n # Tests notmasked_contiguous\n a = masked_array(np.arange(24).reshape(3, 8),\n mask=[[0, 0, 0, 0, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1, 1],\n [0, 0, 0, 0, 0, 0, 1, 0]])\n tmp = notmasked_contiguous(a, None)\n assert_equal(tmp, [\n slice(0, 4, None),\n slice(16, 22, None),\n slice(23, 24, None)\n ])\n\n tmp = notmasked_contiguous(a, 0)\n assert_equal(tmp, [\n [slice(0, 1, None), slice(2, 3, None)],\n [slice(0, 1, None), slice(2, 3, None)],\n [slice(0, 1, None), slice(2, 3, None)],\n [slice(0, 1, None), slice(2, 3, None)],\n [slice(2, 3, None)],\n [slice(2, 3, None)],\n [],\n [slice(2, 3, None)]\n ])\n #\n tmp = notmasked_contiguous(a, 1)\n assert_equal(tmp, [\n [slice(0, 4, None)],\n [],\n [slice(0, 6, None), slice(7, 8, None)]\n ])\n\n\nclass TestCompressFunctions:\n\n def test_compress_nd(self):\n # Tests compress_nd\n x = np.array(list(range(3 * 4 * 5))).reshape(3, 4, 5)\n m = np.zeros((3, 4, 5)).astype(bool)\n m[1, 1, 1] = True\n x = array(x, mask=m)\n\n # axis=None\n a = compress_nd(x)\n assert_equal(a, [[[ 0, 2, 3, 4],\n [10, 12, 13, 14],\n [15, 17, 18, 19]],\n [[40, 42, 43, 44],\n [50, 52, 53, 54],\n [55, 57, 58, 59]]])\n\n # axis=0\n a = compress_nd(x, 0)\n assert_equal(a, [[[ 0, 1, 2, 3, 4],\n [ 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19]],\n [[40, 41, 42, 43, 44],\n [45, 46, 47, 48, 49],\n [50, 51, 52, 53, 54],\n [55, 56, 57, 58, 59]]])\n\n # axis=1\n a = compress_nd(x, 1)\n assert_equal(a, [[[ 0, 1, 2, 3, 4],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19]],\n [[20, 21, 22, 23, 24],\n [30, 31, 32, 33, 34],\n [35, 36, 37, 38, 39]],\n [[40, 41, 42, 43, 44],\n [50, 51, 52, 53, 54],\n [55, 56, 57, 58, 59]]])\n\n a2 = compress_nd(x, (1,))\n a3 = compress_nd(x, -2)\n a4 = compress_nd(x, (-2,))\n assert_equal(a, a2)\n assert_equal(a, a3)\n assert_equal(a, a4)\n\n # axis=2\n a = compress_nd(x, 2)\n assert_equal(a, [[[ 0, 2, 3, 4],\n [ 5, 7, 8, 9],\n [10, 12, 13, 14],\n [15, 17, 18, 19]],\n [[20, 22, 23, 24],\n [25, 27, 28, 29],\n [30, 32, 33, 34],\n [35, 37, 38, 39]],\n [[40, 42, 43, 44],\n [45, 47, 48, 49],\n [50, 52, 53, 54],\n [55, 57, 58, 59]]])\n\n a2 = compress_nd(x, (2,))\n a3 = compress_nd(x, -1)\n a4 = compress_nd(x, (-1,))\n assert_equal(a, a2)\n assert_equal(a, a3)\n assert_equal(a, a4)\n\n # axis=(0, 1)\n a = compress_nd(x, (0, 1))\n assert_equal(a, [[[ 0, 1, 2, 3, 4],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19]],\n [[40, 41, 42, 43, 44],\n [50, 51, 52, 53, 54],\n [55, 56, 57, 58, 59]]])\n a2 = compress_nd(x, (0, -2))\n assert_equal(a, a2)\n\n # axis=(1, 2)\n a = compress_nd(x, (1, 2))\n assert_equal(a, [[[ 0, 2, 3, 4],\n [10, 12, 13, 14],\n [15, 17, 18, 19]],\n [[20, 22, 23, 24],\n [30, 32, 33, 34],\n [35, 37, 38, 39]],\n [[40, 42, 43, 44],\n [50, 52, 53, 54],\n [55, 57, 58, 59]]])\n\n a2 = compress_nd(x, (-2, 2))\n a3 = compress_nd(x, (1, -1))\n a4 = compress_nd(x, (-2, -1))\n assert_equal(a, a2)\n assert_equal(a, a3)\n assert_equal(a, a4)\n\n # axis=(0, 2)\n a = compress_nd(x, (0, 2))\n assert_equal(a, [[[ 0, 2, 3, 4],\n [ 5, 7, 8, 9],\n [10, 12, 13, 14],\n [15, 17, 18, 19]],\n [[40, 42, 43, 44],\n [45, 47, 48, 49],\n [50, 52, 53, 54],\n [55, 57, 58, 59]]])\n\n a2 = compress_nd(x, (0, -1))\n assert_equal(a, a2)\n\n def test_compress_rowcols(self):\n # Tests compress_rowcols\n x = array(np.arange(9).reshape(3, 3),\n mask=[[1, 0, 0], [0, 0, 0], [0, 0, 0]])\n assert_equal(compress_rowcols(x), [[4, 5], [7, 8]])\n assert_equal(compress_rowcols(x, 0), [[3, 4, 5], [6, 7, 8]])\n assert_equal(compress_rowcols(x, 1), [[1, 2], [4, 5], [7, 8]])\n x = array(x._data, mask=[[0, 0, 0], [0, 1, 0], [0, 0, 0]])\n assert_equal(compress_rowcols(x), [[0, 2], [6, 8]])\n assert_equal(compress_rowcols(x, 0), [[0, 1, 2], [6, 7, 8]])\n assert_equal(compress_rowcols(x, 1), [[0, 2], [3, 5], [6, 8]])\n x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 0]])\n assert_equal(compress_rowcols(x), [[8]])\n assert_equal(compress_rowcols(x, 0), [[6, 7, 8]])\n assert_equal(compress_rowcols(x, 1,), [[2], [5], [8]])\n x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n assert_equal(compress_rowcols(x).size, 0)\n assert_equal(compress_rowcols(x, 0).size, 0)\n assert_equal(compress_rowcols(x, 1).size, 0)\n\n def test_mask_rowcols(self):\n # Tests mask_rowcols.\n x = array(np.arange(9).reshape(3, 3),\n mask=[[1, 0, 0], [0, 0, 0], [0, 0, 0]])\n assert_equal(mask_rowcols(x).mask,\n [[1, 1, 1], [1, 0, 0], [1, 0, 0]])\n assert_equal(mask_rowcols(x, 0).mask,\n [[1, 1, 1], [0, 0, 0], [0, 0, 0]])\n assert_equal(mask_rowcols(x, 1).mask,\n [[1, 0, 0], [1, 0, 0], [1, 0, 0]])\n x = array(x._data, mask=[[0, 0, 0], [0, 1, 0], [0, 0, 0]])\n assert_equal(mask_rowcols(x).mask,\n [[0, 1, 0], [1, 1, 1], [0, 1, 0]])\n assert_equal(mask_rowcols(x, 0).mask,\n [[0, 0, 0], [1, 1, 1], [0, 0, 0]])\n assert_equal(mask_rowcols(x, 1).mask,\n [[0, 1, 0], [0, 1, 0], [0, 1, 0]])\n x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 0]])\n assert_equal(mask_rowcols(x).mask,\n [[1, 1, 1], [1, 1, 1], [1, 1, 0]])\n assert_equal(mask_rowcols(x, 0).mask,\n [[1, 1, 1], [1, 1, 1], [0, 0, 0]])\n assert_equal(mask_rowcols(x, 1,).mask,\n [[1, 1, 0], [1, 1, 0], [1, 1, 0]])\n x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n assert_(mask_rowcols(x).all() is masked)\n assert_(mask_rowcols(x, 0).all() is masked)\n assert_(mask_rowcols(x, 1).all() is masked)\n assert_(mask_rowcols(x).mask.all())\n assert_(mask_rowcols(x, 0).mask.all())\n assert_(mask_rowcols(x, 1).mask.all())\n\n @pytest.mark.parametrize("axis", [None, 0, 1])\n @pytest.mark.parametrize(["func", "rowcols_axis"],\n [(np.ma.mask_rows, 0), (np.ma.mask_cols, 1)])\n def test_mask_row_cols_axis_deprecation(self, axis, func, rowcols_axis):\n # Test deprecation of the axis argument to `mask_rows` and `mask_cols`\n x = array(np.arange(9).reshape(3, 3),\n mask=[[1, 0, 0], [0, 0, 0], [0, 0, 0]])\n\n with assert_warns(DeprecationWarning):\n res = func(x, axis=axis)\n assert_equal(res, mask_rowcols(x, rowcols_axis))\n\n def test_dot(self):\n # Tests dot product\n n = np.arange(1, 7)\n #\n m = [1, 0, 0, 0, 0, 0]\n a = masked_array(n, mask=m).reshape(2, 3)\n b = masked_array(n, mask=m).reshape(3, 2)\n c = dot(a, b, strict=True)\n assert_equal(c.mask, [[1, 1], [1, 0]])\n c = dot(b, a, strict=True)\n assert_equal(c.mask, [[1, 1, 1], [1, 0, 0], [1, 0, 0]])\n c = dot(a, b, strict=False)\n assert_equal(c, np.dot(a.filled(0), b.filled(0)))\n c = dot(b, a, strict=False)\n assert_equal(c, np.dot(b.filled(0), a.filled(0)))\n #\n m = [0, 0, 0, 0, 0, 1]\n a = masked_array(n, mask=m).reshape(2, 3)\n b = masked_array(n, mask=m).reshape(3, 2)\n c = dot(a, b, strict=True)\n assert_equal(c.mask, [[0, 1], [1, 1]])\n c = dot(b, a, strict=True)\n assert_equal(c.mask, [[0, 0, 1], [0, 0, 1], [1, 1, 1]])\n c = dot(a, b, strict=False)\n assert_equal(c, np.dot(a.filled(0), b.filled(0)))\n assert_equal(c, dot(a, b))\n c = dot(b, a, strict=False)\n assert_equal(c, np.dot(b.filled(0), a.filled(0)))\n #\n m = [0, 0, 0, 0, 0, 0]\n a = masked_array(n, mask=m).reshape(2, 3)\n b = masked_array(n, mask=m).reshape(3, 2)\n c = dot(a, b)\n assert_equal(c.mask, nomask)\n c = dot(b, a)\n assert_equal(c.mask, nomask)\n #\n a = masked_array(n, mask=[1, 0, 0, 0, 0, 0]).reshape(2, 3)\n b = masked_array(n, mask=[0, 0, 0, 0, 0, 0]).reshape(3, 2)\n c = dot(a, b, strict=True)\n assert_equal(c.mask, [[1, 1], [0, 0]])\n c = dot(a, b, strict=False)\n assert_equal(c, np.dot(a.filled(0), b.filled(0)))\n c = dot(b, a, strict=True)\n assert_equal(c.mask, [[1, 0, 0], [1, 0, 0], [1, 0, 0]])\n c = dot(b, a, strict=False)\n assert_equal(c, np.dot(b.filled(0), a.filled(0)))\n #\n a = masked_array(n, mask=[0, 0, 0, 0, 0, 1]).reshape(2, 3)\n b = masked_array(n, mask=[0, 0, 0, 0, 0, 0]).reshape(3, 2)\n c = dot(a, b, strict=True)\n assert_equal(c.mask, [[0, 0], [1, 1]])\n c = dot(a, b)\n assert_equal(c, np.dot(a.filled(0), b.filled(0)))\n c = dot(b, a, strict=True)\n assert_equal(c.mask, [[0, 0, 1], [0, 0, 1], [0, 0, 1]])\n c = dot(b, a, strict=False)\n assert_equal(c, np.dot(b.filled(0), a.filled(0)))\n #\n a = masked_array(n, mask=[0, 0, 0, 0, 0, 1]).reshape(2, 3)\n b = masked_array(n, mask=[0, 0, 1, 0, 0, 0]).reshape(3, 2)\n c = dot(a, b, strict=True)\n assert_equal(c.mask, [[1, 0], [1, 1]])\n c = dot(a, b, strict=False)\n assert_equal(c, np.dot(a.filled(0), b.filled(0)))\n c = dot(b, a, strict=True)\n assert_equal(c.mask, [[0, 0, 1], [1, 1, 1], [0, 0, 1]])\n c = dot(b, a, strict=False)\n assert_equal(c, np.dot(b.filled(0), a.filled(0)))\n #\n a = masked_array(np.arange(8).reshape(2, 2, 2),\n mask=[[[1, 0], [0, 0]], [[0, 0], [0, 0]]])\n b = masked_array(np.arange(8).reshape(2, 2, 2),\n mask=[[[0, 0], [0, 0]], [[0, 0], [0, 1]]])\n c = dot(a, b, strict=True)\n assert_equal(c.mask,\n [[[[1, 1], [1, 1]], [[0, 0], [0, 1]]],\n [[[0, 0], [0, 1]], [[0, 0], [0, 1]]]])\n c = dot(a, b, strict=False)\n assert_equal(c.mask,\n [[[[0, 0], [0, 1]], [[0, 0], [0, 0]]],\n [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]])\n c = dot(b, a, strict=True)\n assert_equal(c.mask,\n [[[[1, 0], [0, 0]], [[1, 0], [0, 0]]],\n [[[1, 0], [0, 0]], [[1, 1], [1, 1]]]])\n c = dot(b, a, strict=False)\n assert_equal(c.mask,\n [[[[0, 0], [0, 0]], [[0, 0], [0, 0]]],\n [[[0, 0], [0, 0]], [[1, 0], [0, 0]]]])\n #\n a = masked_array(np.arange(8).reshape(2, 2, 2),\n mask=[[[1, 0], [0, 0]], [[0, 0], [0, 0]]])\n b = 5.\n c = dot(a, b, strict=True)\n assert_equal(c.mask, [[[1, 0], [0, 0]], [[0, 0], [0, 0]]])\n c = dot(a, b, strict=False)\n assert_equal(c.mask, [[[1, 0], [0, 0]], [[0, 0], [0, 0]]])\n c = dot(b, a, strict=True)\n assert_equal(c.mask, [[[1, 0], [0, 0]], [[0, 0], [0, 0]]])\n c = dot(b, a, strict=False)\n assert_equal(c.mask, [[[1, 0], [0, 0]], [[0, 0], [0, 0]]])\n #\n a = masked_array(np.arange(8).reshape(2, 2, 2),\n mask=[[[1, 0], [0, 0]], [[0, 0], [0, 0]]])\n b = masked_array(np.arange(2), mask=[0, 1])\n c = dot(a, b, strict=True)\n assert_equal(c.mask, [[1, 1], [1, 1]])\n c = dot(a, b, strict=False)\n assert_equal(c.mask, [[1, 0], [0, 0]])\n\n def test_dot_returns_maskedarray(self):\n # See gh-6611\n a = np.eye(3)\n b = array(a)\n assert_(type(dot(a, a)) is MaskedArray)\n assert_(type(dot(a, b)) is MaskedArray)\n assert_(type(dot(b, a)) is MaskedArray)\n assert_(type(dot(b, b)) is MaskedArray)\n\n def test_dot_out(self):\n a = array(np.eye(3))\n out = array(np.zeros((3, 3)))\n res = dot(a, a, out=out)\n assert_(res is out)\n assert_equal(a, res)\n\n\nclass TestApplyAlongAxis:\n # Tests 2D functions\n def test_3d(self):\n a = arange(12.).reshape(2, 2, 3)\n\n def myfunc(b):\n return b[1]\n\n xa = apply_along_axis(myfunc, 2, a)\n assert_equal(xa, [[1, 4], [7, 10]])\n\n # Tests kwargs functions\n def test_3d_kwargs(self):\n a = arange(12).reshape(2, 2, 3)\n\n def myfunc(b, offset=0):\n return b[1 + offset]\n\n xa = apply_along_axis(myfunc, 2, a, offset=1)\n assert_equal(xa, [[2, 5], [8, 11]])\n\n\nclass TestApplyOverAxes:\n # Tests apply_over_axes\n def test_basic(self):\n a = arange(24).reshape(2, 3, 4)\n test = apply_over_axes(np.sum, a, [0, 2])\n ctrl = np.array([[[60], [92], [124]]])\n assert_equal(test, ctrl)\n a[(a % 2).astype(bool)] = masked\n test = apply_over_axes(np.sum, a, [0, 2])\n ctrl = np.array([[[28], [44], [60]]])\n assert_equal(test, ctrl)\n\n\nclass TestMedian:\n def test_pytype(self):\n r = np.ma.median([[np.inf, np.inf], [np.inf, np.inf]], axis=-1)\n assert_equal(r, np.inf)\n\n def test_inf(self):\n # test that even which computes handles inf / x = masked\n r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],\n [np.inf, np.inf]]), axis=-1)\n assert_equal(r, np.inf)\n r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],\n [np.inf, np.inf]]), axis=None)\n assert_equal(r, np.inf)\n # all masked\n r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],\n [np.inf, np.inf]], mask=True),\n axis=-1)\n assert_equal(r.mask, True)\n r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],\n [np.inf, np.inf]], mask=True),\n axis=None)\n assert_equal(r.mask, True)\n\n def test_non_masked(self):\n x = np.arange(9)\n assert_equal(np.ma.median(x), 4.)\n assert_(type(np.ma.median(x)) is not MaskedArray)\n x = range(8)\n assert_equal(np.ma.median(x), 3.5)\n assert_(type(np.ma.median(x)) is not MaskedArray)\n x = 5\n assert_equal(np.ma.median(x), 5.)\n assert_(type(np.ma.median(x)) is not MaskedArray)\n # integer\n x = np.arange(9 * 8).reshape(9, 8)\n assert_equal(np.ma.median(x, axis=0), np.median(x, axis=0))\n assert_equal(np.ma.median(x, axis=1), np.median(x, axis=1))\n assert_(np.ma.median(x, axis=1) is not MaskedArray)\n # float\n x = np.arange(9 * 8.).reshape(9, 8)\n assert_equal(np.ma.median(x, axis=0), np.median(x, axis=0))\n assert_equal(np.ma.median(x, axis=1), np.median(x, axis=1))\n assert_(np.ma.median(x, axis=1) is not MaskedArray)\n\n def test_docstring_examples(self):\n "test the examples given in the docstring of ma.median"\n x = array(np.arange(8), mask=[0] * 4 + [1] * 4)\n assert_equal(np.ma.median(x), 1.5)\n assert_equal(np.ma.median(x).shape, (), "shape mismatch")\n assert_(type(np.ma.median(x)) is not MaskedArray)\n x = array(np.arange(10).reshape(2, 5), mask=[0] * 6 + [1] * 4)\n assert_equal(np.ma.median(x), 2.5)\n assert_equal(np.ma.median(x).shape, (), "shape mismatch")\n assert_(type(np.ma.median(x)) is not MaskedArray)\n ma_x = np.ma.median(x, axis=-1, overwrite_input=True)\n assert_equal(ma_x, [2., 5.])\n assert_equal(ma_x.shape, (2,), "shape mismatch")\n assert_(type(ma_x) is MaskedArray)\n\n def test_axis_argument_errors(self):\n msg = "mask = %s, ndim = %s, axis = %s, overwrite_input = %s"\n for ndmin in range(5):\n for mask in [False, True]:\n x = array(1, ndmin=ndmin, mask=mask)\n\n # Valid axis values should not raise exception\n args = itertools.product(range(-ndmin, ndmin), [False, True])\n for axis, over in args:\n try:\n np.ma.median(x, axis=axis, overwrite_input=over)\n except Exception:\n raise AssertionError(msg % (mask, ndmin, axis, over))\n\n # Invalid axis values should raise exception\n args = itertools.product([-(ndmin + 1), ndmin], [False, True])\n for axis, over in args:\n try:\n np.ma.median(x, axis=axis, overwrite_input=over)\n except np.exceptions.AxisError:\n pass\n else:\n raise AssertionError(msg % (mask, ndmin, axis, over))\n\n def test_masked_0d(self):\n # Check values\n x = array(1, mask=False)\n assert_equal(np.ma.median(x), 1)\n x = array(1, mask=True)\n assert_equal(np.ma.median(x), np.ma.masked)\n\n def test_masked_1d(self):\n x = array(np.arange(5), mask=True)\n assert_equal(np.ma.median(x), np.ma.masked)\n assert_equal(np.ma.median(x).shape, (), "shape mismatch")\n assert_(type(np.ma.median(x)) is np.ma.core.MaskedConstant)\n x = array(np.arange(5), mask=False)\n assert_equal(np.ma.median(x), 2.)\n assert_equal(np.ma.median(x).shape, (), "shape mismatch")\n assert_(type(np.ma.median(x)) is not MaskedArray)\n x = array(np.arange(5), mask=[0, 1, 0, 0, 0])\n assert_equal(np.ma.median(x), 2.5)\n assert_equal(np.ma.median(x).shape, (), "shape mismatch")\n assert_(type(np.ma.median(x)) is not MaskedArray)\n x = array(np.arange(5), mask=[0, 1, 1, 1, 1])\n assert_equal(np.ma.median(x), 0.)\n assert_equal(np.ma.median(x).shape, (), "shape mismatch")\n assert_(type(np.ma.median(x)) is not MaskedArray)\n # integer\n x = array(np.arange(5), mask=[0, 1, 1, 0, 0])\n assert_equal(np.ma.median(x), 3.)\n assert_equal(np.ma.median(x).shape, (), "shape mismatch")\n assert_(type(np.ma.median(x)) is not MaskedArray)\n # float\n x = array(np.arange(5.), mask=[0, 1, 1, 0, 0])\n assert_equal(np.ma.median(x), 3.)\n assert_equal(np.ma.median(x).shape, (), "shape mismatch")\n assert_(type(np.ma.median(x)) is not MaskedArray)\n # integer\n x = array(np.arange(6), mask=[0, 1, 1, 1, 1, 0])\n assert_equal(np.ma.median(x), 2.5)\n assert_equal(np.ma.median(x).shape, (), "shape mismatch")\n assert_(type(np.ma.median(x)) is not MaskedArray)\n # float\n x = array(np.arange(6.), mask=[0, 1, 1, 1, 1, 0])\n assert_equal(np.ma.median(x), 2.5)\n assert_equal(np.ma.median(x).shape, (), "shape mismatch")\n assert_(type(np.ma.median(x)) is not MaskedArray)\n\n def test_1d_shape_consistency(self):\n assert_equal(np.ma.median(array([1, 2, 3], mask=[0, 0, 0])).shape,\n np.ma.median(array([1, 2, 3], mask=[0, 1, 0])).shape)\n\n def test_2d(self):\n # Tests median w/ 2D\n (n, p) = (101, 30)\n x = masked_array(np.linspace(-1., 1., n),)\n x[:10] = x[-10:] = masked\n z = masked_array(np.empty((n, p), dtype=float))\n z[:, 0] = x[:]\n idx = np.arange(len(x))\n for i in range(1, p):\n np.random.shuffle(idx)\n z[:, i] = x[idx]\n assert_equal(median(z[:, 0]), 0)\n assert_equal(median(z), 0)\n assert_equal(median(z, axis=0), np.zeros(p))\n assert_equal(median(z.T, axis=1), np.zeros(p))\n\n def test_2d_waxis(self):\n # Tests median w/ 2D arrays and different axis.\n x = masked_array(np.arange(30).reshape(10, 3))\n x[:3] = x[-3:] = masked\n assert_equal(median(x), 14.5)\n assert_(type(np.ma.median(x)) is not MaskedArray)\n assert_equal(median(x, axis=0), [13.5, 14.5, 15.5])\n assert_(type(np.ma.median(x, axis=0)) is MaskedArray)\n assert_equal(median(x, axis=1), [0, 0, 0, 10, 13, 16, 19, 0, 0, 0])\n assert_(type(np.ma.median(x, axis=1)) is MaskedArray)\n assert_equal(median(x, axis=1).mask, [1, 1, 1, 0, 0, 0, 0, 1, 1, 1])\n\n def test_3d(self):\n # Tests median w/ 3D\n x = np.ma.arange(24).reshape(3, 4, 2)\n x[x % 3 == 0] = masked\n assert_equal(median(x, 0), [[12, 9], [6, 15], [12, 9], [18, 15]])\n x.shape = (4, 3, 2)\n assert_equal(median(x, 0), [[99, 10], [11, 99], [13, 14]])\n x = np.ma.arange(24).reshape(4, 3, 2)\n x[x % 5 == 0] = masked\n assert_equal(median(x, 0), [[12, 10], [8, 9], [16, 17]])\n\n def test_neg_axis(self):\n x = masked_array(np.arange(30).reshape(10, 3))\n x[:3] = x[-3:] = masked\n assert_equal(median(x, axis=-1), median(x, axis=1))\n\n def test_out_1d(self):\n # integer float even odd\n for v in (30, 30., 31, 31.):\n x = masked_array(np.arange(v))\n x[:3] = x[-3:] = masked\n out = masked_array(np.ones(()))\n r = median(x, out=out)\n if v == 30:\n assert_equal(out, 14.5)\n else:\n assert_equal(out, 15.)\n assert_(r is out)\n assert_(type(r) is MaskedArray)\n\n def test_out(self):\n # integer float even odd\n for v in (40, 40., 30, 30.):\n x = masked_array(np.arange(v).reshape(10, -1))\n x[:3] = x[-3:] = masked\n out = masked_array(np.ones(10))\n r = median(x, axis=1, out=out)\n if v == 30:\n e = masked_array([0.] * 3 + [10, 13, 16, 19] + [0.] * 3,\n mask=[True] * 3 + [False] * 4 + [True] * 3)\n else:\n e = masked_array([0.] * 3 + [13.5, 17.5, 21.5, 25.5] + [0.] * 3,\n mask=[True] * 3 + [False] * 4 + [True] * 3)\n assert_equal(r, e)\n assert_(r is out)\n assert_(type(r) is MaskedArray)\n\n @pytest.mark.parametrize(\n argnames='axis',\n argvalues=[\n None,\n 1,\n (1, ),\n (0, 1),\n (-3, -1),\n ]\n )\n def test_keepdims_out(self, axis):\n mask = np.zeros((3, 5, 7, 11), dtype=bool)\n # Randomly set some elements to True:\n w = np.random.random((4, 200)) * np.array(mask.shape)[:, None]\n w = w.astype(np.intp)\n mask[tuple(w)] = np.nan\n d = masked_array(np.ones(mask.shape), mask=mask)\n if axis is None:\n shape_out = (1,) * d.ndim\n else:\n axis_norm = normalize_axis_tuple(axis, d.ndim)\n shape_out = tuple(\n 1 if i in axis_norm else d.shape[i] for i in range(d.ndim))\n out = masked_array(np.empty(shape_out))\n result = median(d, axis=axis, keepdims=True, out=out)\n assert result is out\n assert_equal(result.shape, shape_out)\n\n def test_single_non_masked_value_on_axis(self):\n data = [[1., 0.],\n [0., 3.],\n [0., 0.]]\n masked_arr = np.ma.masked_equal(data, 0)\n expected = [1., 3.]\n assert_array_equal(np.ma.median(masked_arr, axis=0),\n expected)\n\n def test_nan(self):\n for mask in (False, np.zeros(6, dtype=bool)):\n dm = np.ma.array([[1, np.nan, 3], [1, 2, 3]])\n dm.mask = mask\n\n # scalar result\n r = np.ma.median(dm, axis=None)\n assert_(np.isscalar(r))\n assert_array_equal(r, np.nan)\n r = np.ma.median(dm.ravel(), axis=0)\n assert_(np.isscalar(r))\n assert_array_equal(r, np.nan)\n\n r = np.ma.median(dm, axis=0)\n assert_equal(type(r), MaskedArray)\n assert_array_equal(r, [1, np.nan, 3])\n r = np.ma.median(dm, axis=1)\n assert_equal(type(r), MaskedArray)\n assert_array_equal(r, [np.nan, 2])\n r = np.ma.median(dm, axis=-1)\n assert_equal(type(r), MaskedArray)\n assert_array_equal(r, [np.nan, 2])\n\n dm = np.ma.array([[1, np.nan, 3], [1, 2, 3]])\n dm[:, 2] = np.ma.masked\n assert_array_equal(np.ma.median(dm, axis=None), np.nan)\n assert_array_equal(np.ma.median(dm, axis=0), [1, np.nan, 3])\n assert_array_equal(np.ma.median(dm, axis=1), [np.nan, 1.5])\n\n def test_out_nan(self):\n o = np.ma.masked_array(np.zeros((4,)))\n d = np.ma.masked_array(np.ones((3, 4)))\n d[2, 1] = np.nan\n d[2, 2] = np.ma.masked\n assert_equal(np.ma.median(d, 0, out=o), o)\n o = np.ma.masked_array(np.zeros((3,)))\n assert_equal(np.ma.median(d, 1, out=o), o)\n o = np.ma.masked_array(np.zeros(()))\n assert_equal(np.ma.median(d, out=o), o)\n\n def test_nan_behavior(self):\n a = np.ma.masked_array(np.arange(24, dtype=float))\n a[::3] = np.ma.masked\n a[2] = np.nan\n assert_array_equal(np.ma.median(a), np.nan)\n assert_array_equal(np.ma.median(a, axis=0), np.nan)\n\n a = np.ma.masked_array(np.arange(24, dtype=float).reshape(2, 3, 4))\n a.mask = np.arange(a.size) % 2 == 1\n aorig = a.copy()\n a[1, 2, 3] = np.nan\n a[1, 1, 2] = np.nan\n\n # no axis\n assert_array_equal(np.ma.median(a), np.nan)\n assert_(np.isscalar(np.ma.median(a)))\n\n # axis0\n b = np.ma.median(aorig, axis=0)\n b[2, 3] = np.nan\n b[1, 2] = np.nan\n assert_equal(np.ma.median(a, 0), b)\n\n # axis1\n b = np.ma.median(aorig, axis=1)\n b[1, 3] = np.nan\n b[1, 2] = np.nan\n assert_equal(np.ma.median(a, 1), b)\n\n # axis02\n b = np.ma.median(aorig, axis=(0, 2))\n b[1] = np.nan\n b[2] = np.nan\n assert_equal(np.ma.median(a, (0, 2)), b)\n\n def test_ambigous_fill(self):\n # 255 is max value, used as filler for sort\n a = np.array([[3, 3, 255], [3, 3, 255]], dtype=np.uint8)\n a = np.ma.masked_array(a, mask=a == 3)\n assert_array_equal(np.ma.median(a, axis=1), 255)\n assert_array_equal(np.ma.median(a, axis=1).mask, False)\n assert_array_equal(np.ma.median(a, axis=0), a[0])\n assert_array_equal(np.ma.median(a), 255)\n\n def test_special(self):\n for inf in [np.inf, -np.inf]:\n a = np.array([[inf, np.nan], [np.nan, np.nan]])\n a = np.ma.masked_array(a, mask=np.isnan(a))\n assert_equal(np.ma.median(a, axis=0), [inf, np.nan])\n assert_equal(np.ma.median(a, axis=1), [inf, np.nan])\n assert_equal(np.ma.median(a), inf)\n\n a = np.array([[np.nan, np.nan, inf], [np.nan, np.nan, inf]])\n a = np.ma.masked_array(a, mask=np.isnan(a))\n assert_array_equal(np.ma.median(a, axis=1), inf)\n assert_array_equal(np.ma.median(a, axis=1).mask, False)\n assert_array_equal(np.ma.median(a, axis=0), a[0])\n assert_array_equal(np.ma.median(a), inf)\n\n # no mask\n a = np.array([[inf, inf], [inf, inf]])\n assert_equal(np.ma.median(a), inf)\n assert_equal(np.ma.median(a, axis=0), inf)\n assert_equal(np.ma.median(a, axis=1), inf)\n\n a = np.array([[inf, 7, -inf, -9],\n [-10, np.nan, np.nan, 5],\n [4, np.nan, np.nan, inf]],\n dtype=np.float32)\n a = np.ma.masked_array(a, mask=np.isnan(a))\n if inf > 0:\n assert_equal(np.ma.median(a, axis=0), [4., 7., -inf, 5.])\n assert_equal(np.ma.median(a), 4.5)\n else:\n assert_equal(np.ma.median(a, axis=0), [-10., 7., -inf, -9.])\n assert_equal(np.ma.median(a), -2.5)\n assert_equal(np.ma.median(a, axis=1), [-1., -2.5, inf])\n\n for i in range(10):\n for j in range(1, 10):\n a = np.array([([np.nan] * i) + ([inf] * j)] * 2)\n a = np.ma.masked_array(a, mask=np.isnan(a))\n assert_equal(np.ma.median(a), inf)\n assert_equal(np.ma.median(a, axis=1), inf)\n assert_equal(np.ma.median(a, axis=0),\n ([np.nan] * i) + [inf] * j)\n\n def test_empty(self):\n # empty arrays\n a = np.ma.masked_array(np.array([], dtype=float))\n with suppress_warnings() as w:\n w.record(RuntimeWarning)\n assert_array_equal(np.ma.median(a), np.nan)\n assert_(w.log[0].category is RuntimeWarning)\n\n # multiple dimensions\n a = np.ma.masked_array(np.array([], dtype=float, ndmin=3))\n # no axis\n with suppress_warnings() as w:\n w.record(RuntimeWarning)\n warnings.filterwarnings('always', '', RuntimeWarning)\n assert_array_equal(np.ma.median(a), np.nan)\n assert_(w.log[0].category is RuntimeWarning)\n\n # axis 0 and 1\n b = np.ma.masked_array(np.array([], dtype=float, ndmin=2))\n assert_equal(np.ma.median(a, axis=0), b)\n assert_equal(np.ma.median(a, axis=1), b)\n\n # axis 2\n b = np.ma.masked_array(np.array(np.nan, dtype=float, ndmin=2))\n with warnings.catch_warnings(record=True) as w:\n warnings.filterwarnings('always', '', RuntimeWarning)\n assert_equal(np.ma.median(a, axis=2), b)\n assert_(w[0].category is RuntimeWarning)\n\n def test_object(self):\n o = np.ma.masked_array(np.arange(7.))\n assert_(type(np.ma.median(o.astype(object))), float)\n o[2] = np.nan\n assert_(type(np.ma.median(o.astype(object))), float)\n\n\nclass TestCov:\n\n def setup_method(self):\n self.data = array(np.random.rand(12))\n\n def test_covhelper(self):\n x = self.data\n # Test not mask output type is a float.\n assert_(_covhelper(x, rowvar=True)[1].dtype, np.float32)\n assert_(_covhelper(x, y=x, rowvar=False)[1].dtype, np.float32)\n # Test not mask output is equal after casting to float.\n mask = x > 0.5\n assert_array_equal(\n _covhelper(\n np.ma.masked_array(x, mask), rowvar=True\n )[1].astype(bool),\n ~mask.reshape(1, -1),\n )\n assert_array_equal(\n _covhelper(\n np.ma.masked_array(x, mask), y=x, rowvar=False\n )[1].astype(bool),\n np.vstack((~mask, ~mask)),\n )\n\n def test_1d_without_missing(self):\n # Test cov on 1D variable w/o missing values\n x = self.data\n assert_almost_equal(np.cov(x), cov(x))\n assert_almost_equal(np.cov(x, rowvar=False), cov(x, rowvar=False))\n assert_almost_equal(np.cov(x, rowvar=False, bias=True),\n cov(x, rowvar=False, bias=True))\n\n def test_2d_without_missing(self):\n # Test cov on 1 2D variable w/o missing values\n x = self.data.reshape(3, 4)\n assert_almost_equal(np.cov(x), cov(x))\n assert_almost_equal(np.cov(x, rowvar=False), cov(x, rowvar=False))\n assert_almost_equal(np.cov(x, rowvar=False, bias=True),\n cov(x, rowvar=False, bias=True))\n\n def test_1d_with_missing(self):\n # Test cov 1 1D variable w/missing values\n x = self.data\n x[-1] = masked\n x -= x.mean()\n nx = x.compressed()\n assert_almost_equal(np.cov(nx), cov(x))\n assert_almost_equal(np.cov(nx, rowvar=False), cov(x, rowvar=False))\n assert_almost_equal(np.cov(nx, rowvar=False, bias=True),\n cov(x, rowvar=False, bias=True))\n #\n try:\n cov(x, allow_masked=False)\n except ValueError:\n pass\n #\n # 2 1D variables w/ missing values\n nx = x[1:-1]\n assert_almost_equal(np.cov(nx, nx[::-1]), cov(x, x[::-1]))\n assert_almost_equal(np.cov(nx, nx[::-1], rowvar=False),\n cov(x, x[::-1], rowvar=False))\n assert_almost_equal(np.cov(nx, nx[::-1], rowvar=False, bias=True),\n cov(x, x[::-1], rowvar=False, bias=True))\n\n def test_2d_with_missing(self):\n # Test cov on 2D variable w/ missing value\n x = self.data\n x[-1] = masked\n x = x.reshape(3, 4)\n valid = np.logical_not(getmaskarray(x)).astype(int)\n frac = np.dot(valid, valid.T)\n xf = (x - x.mean(1)[:, None]).filled(0)\n assert_almost_equal(cov(x),\n np.cov(xf) * (x.shape[1] - 1) / (frac - 1.))\n assert_almost_equal(cov(x, bias=True),\n np.cov(xf, bias=True) * x.shape[1] / frac)\n frac = np.dot(valid.T, valid)\n xf = (x - x.mean(0)).filled(0)\n assert_almost_equal(cov(x, rowvar=False),\n (np.cov(xf, rowvar=False) *\n (x.shape[0] - 1) / (frac - 1.)))\n assert_almost_equal(cov(x, rowvar=False, bias=True),\n (np.cov(xf, rowvar=False, bias=True) *\n x.shape[0] / frac))\n\n\nclass TestCorrcoef:\n\n def setup_method(self):\n self.data = array(np.random.rand(12))\n self.data2 = array(np.random.rand(12))\n\n def test_ddof(self):\n # ddof raises DeprecationWarning\n x, y = self.data, self.data2\n expected = np.corrcoef(x)\n expected2 = np.corrcoef(x, y)\n with suppress_warnings() as sup:\n warnings.simplefilter("always")\n assert_warns(DeprecationWarning, corrcoef, x, ddof=-1)\n sup.filter(DeprecationWarning, "bias and ddof have no effect")\n # ddof has no or negligible effect on the function\n assert_almost_equal(np.corrcoef(x, ddof=0), corrcoef(x, ddof=0))\n assert_almost_equal(corrcoef(x, ddof=-1), expected)\n assert_almost_equal(corrcoef(x, y, ddof=-1), expected2)\n assert_almost_equal(corrcoef(x, ddof=3), expected)\n assert_almost_equal(corrcoef(x, y, ddof=3), expected2)\n\n def test_bias(self):\n x, y = self.data, self.data2\n expected = np.corrcoef(x)\n # bias raises DeprecationWarning\n with suppress_warnings() as sup:\n warnings.simplefilter("always")\n assert_warns(DeprecationWarning, corrcoef, x, y, True, False)\n assert_warns(DeprecationWarning, corrcoef, x, y, True, True)\n assert_warns(DeprecationWarning, corrcoef, x, bias=False)\n sup.filter(DeprecationWarning, "bias and ddof have no effect")\n # bias has no or negligible effect on the function\n assert_almost_equal(corrcoef(x, bias=1), expected)\n\n def test_1d_without_missing(self):\n # Test cov on 1D variable w/o missing values\n x = self.data\n assert_almost_equal(np.corrcoef(x), corrcoef(x))\n assert_almost_equal(np.corrcoef(x, rowvar=False),\n corrcoef(x, rowvar=False))\n with suppress_warnings() as sup:\n sup.filter(DeprecationWarning, "bias and ddof have no effect")\n assert_almost_equal(np.corrcoef(x, rowvar=False, bias=True),\n corrcoef(x, rowvar=False, bias=True))\n\n def test_2d_without_missing(self):\n # Test corrcoef on 1 2D variable w/o missing values\n x = self.data.reshape(3, 4)\n assert_almost_equal(np.corrcoef(x), corrcoef(x))\n assert_almost_equal(np.corrcoef(x, rowvar=False),\n corrcoef(x, rowvar=False))\n with suppress_warnings() as sup:\n sup.filter(DeprecationWarning, "bias and ddof have no effect")\n assert_almost_equal(np.corrcoef(x, rowvar=False, bias=True),\n corrcoef(x, rowvar=False, bias=True))\n\n def test_1d_with_missing(self):\n # Test corrcoef 1 1D variable w/missing values\n x = self.data\n x[-1] = masked\n x -= x.mean()\n nx = x.compressed()\n assert_almost_equal(np.corrcoef(nx), corrcoef(x))\n assert_almost_equal(np.corrcoef(nx, rowvar=False),\n corrcoef(x, rowvar=False))\n with suppress_warnings() as sup:\n sup.filter(DeprecationWarning, "bias and ddof have no effect")\n assert_almost_equal(np.corrcoef(nx, rowvar=False, bias=True),\n corrcoef(x, rowvar=False, bias=True))\n try:\n corrcoef(x, allow_masked=False)\n except ValueError:\n pass\n # 2 1D variables w/ missing values\n nx = x[1:-1]\n assert_almost_equal(np.corrcoef(nx, nx[::-1]), corrcoef(x, x[::-1]))\n assert_almost_equal(np.corrcoef(nx, nx[::-1], rowvar=False),\n corrcoef(x, x[::-1], rowvar=False))\n with suppress_warnings() as sup:\n sup.filter(DeprecationWarning, "bias and ddof have no effect")\n # ddof and bias have no or negligible effect on the function\n assert_almost_equal(np.corrcoef(nx, nx[::-1]),\n corrcoef(x, x[::-1], bias=1))\n assert_almost_equal(np.corrcoef(nx, nx[::-1]),\n corrcoef(x, x[::-1], ddof=2))\n\n def test_2d_with_missing(self):\n # Test corrcoef on 2D variable w/ missing value\n x = self.data\n x[-1] = masked\n x = x.reshape(3, 4)\n\n test = corrcoef(x)\n control = np.corrcoef(x)\n assert_almost_equal(test[:-1, :-1], control[:-1, :-1])\n with suppress_warnings() as sup:\n sup.filter(DeprecationWarning, "bias and ddof have no effect")\n # ddof and bias have no or negligible effect on the function\n assert_almost_equal(corrcoef(x, ddof=-2)[:-1, :-1],\n control[:-1, :-1])\n assert_almost_equal(corrcoef(x, ddof=3)[:-1, :-1],\n control[:-1, :-1])\n assert_almost_equal(corrcoef(x, bias=1)[:-1, :-1],\n control[:-1, :-1])\n\n\nclass TestPolynomial:\n #\n def test_polyfit(self):\n # Tests polyfit\n # On ndarrays\n x = np.random.rand(10)\n y = np.random.rand(20).reshape(-1, 2)\n assert_almost_equal(polyfit(x, y, 3), np.polyfit(x, y, 3))\n # ON 1D maskedarrays\n x = x.view(MaskedArray)\n x[0] = masked\n y = y.view(MaskedArray)\n y[0, 0] = y[-1, -1] = masked\n #\n (C, R, K, S, D) = polyfit(x, y[:, 0], 3, full=True)\n (c, r, k, s, d) = np.polyfit(x[1:], y[1:, 0].compressed(), 3,\n full=True)\n for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):\n assert_almost_equal(a, a_)\n #\n (C, R, K, S, D) = polyfit(x, y[:, -1], 3, full=True)\n (c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1, -1], 3, full=True)\n for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):\n assert_almost_equal(a, a_)\n #\n (C, R, K, S, D) = polyfit(x, y, 3, full=True)\n (c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1, :], 3, full=True)\n for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):\n assert_almost_equal(a, a_)\n #\n w = np.random.rand(10) + 1\n wo = w.copy()\n xs = x[1:-1]\n ys = y[1:-1]\n ws = w[1:-1]\n (C, R, K, S, D) = polyfit(x, y, 3, full=True, w=w)\n (c, r, k, s, d) = np.polyfit(xs, ys, 3, full=True, w=ws)\n assert_equal(w, wo)\n for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):\n assert_almost_equal(a, a_)\n\n def test_polyfit_with_masked_NaNs(self):\n x = np.random.rand(10)\n y = np.random.rand(20).reshape(-1, 2)\n\n x[0] = np.nan\n y[-1, -1] = np.nan\n x = x.view(MaskedArray)\n y = y.view(MaskedArray)\n x[0] = masked\n y[-1, -1] = masked\n\n (C, R, K, S, D) = polyfit(x, y, 3, full=True)\n (c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1, :], 3, full=True)\n for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):\n assert_almost_equal(a, a_)\n\n\nclass TestArraySetOps:\n\n def test_unique_onlist(self):\n # Test unique on list\n data = [1, 1, 1, 2, 2, 3]\n test = unique(data, return_index=True, return_inverse=True)\n assert_(isinstance(test[0], MaskedArray))\n assert_equal(test[0], masked_array([1, 2, 3], mask=[0, 0, 0]))\n assert_equal(test[1], [0, 3, 5])\n assert_equal(test[2], [0, 0, 0, 1, 1, 2])\n\n def test_unique_onmaskedarray(self):\n # Test unique on masked data w/use_mask=True\n data = masked_array([1, 1, 1, 2, 2, 3], mask=[0, 0, 1, 0, 1, 0])\n test = unique(data, return_index=True, return_inverse=True)\n assert_equal(test[0], masked_array([1, 2, 3, -1], mask=[0, 0, 0, 1]))\n assert_equal(test[1], [0, 3, 5, 2])\n assert_equal(test[2], [0, 0, 3, 1, 3, 2])\n #\n data.fill_value = 3\n data = masked_array(data=[1, 1, 1, 2, 2, 3],\n mask=[0, 0, 1, 0, 1, 0], fill_value=3)\n test = unique(data, return_index=True, return_inverse=True)\n assert_equal(test[0], masked_array([1, 2, 3, -1], mask=[0, 0, 0, 1]))\n assert_equal(test[1], [0, 3, 5, 2])\n assert_equal(test[2], [0, 0, 3, 1, 3, 2])\n\n def test_unique_allmasked(self):\n # Test all masked\n data = masked_array([1, 1, 1], mask=True)\n test = unique(data, return_index=True, return_inverse=True)\n assert_equal(test[0], masked_array([1, ], mask=[True]))\n assert_equal(test[1], [0])\n assert_equal(test[2], [0, 0, 0])\n #\n # Test masked\n data = masked\n test = unique(data, return_index=True, return_inverse=True)\n assert_equal(test[0], masked_array(masked))\n assert_equal(test[1], [0])\n assert_equal(test[2], [0])\n\n def test_ediff1d(self):\n # Tests mediff1d\n x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])\n control = array([1, 1, 1, 4], mask=[1, 0, 0, 1])\n test = ediff1d(x)\n assert_equal(test, control)\n assert_equal(test.filled(0), control.filled(0))\n assert_equal(test.mask, control.mask)\n\n def test_ediff1d_tobegin(self):\n # Test ediff1d w/ to_begin\n x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])\n test = ediff1d(x, to_begin=masked)\n control = array([0, 1, 1, 1, 4], mask=[1, 1, 0, 0, 1])\n assert_equal(test, control)\n assert_equal(test.filled(0), control.filled(0))\n assert_equal(test.mask, control.mask)\n #\n test = ediff1d(x, to_begin=[1, 2, 3])\n control = array([1, 2, 3, 1, 1, 1, 4], mask=[0, 0, 0, 1, 0, 0, 1])\n assert_equal(test, control)\n assert_equal(test.filled(0), control.filled(0))\n assert_equal(test.mask, control.mask)\n\n def test_ediff1d_toend(self):\n # Test ediff1d w/ to_end\n x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])\n test = ediff1d(x, to_end=masked)\n control = array([1, 1, 1, 4, 0], mask=[1, 0, 0, 1, 1])\n assert_equal(test, control)\n assert_equal(test.filled(0), control.filled(0))\n assert_equal(test.mask, control.mask)\n #\n test = ediff1d(x, to_end=[1, 2, 3])\n control = array([1, 1, 1, 4, 1, 2, 3], mask=[1, 0, 0, 1, 0, 0, 0])\n assert_equal(test, control)\n assert_equal(test.filled(0), control.filled(0))\n assert_equal(test.mask, control.mask)\n\n def test_ediff1d_tobegin_toend(self):\n # Test ediff1d w/ to_begin and to_end\n x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])\n test = ediff1d(x, to_end=masked, to_begin=masked)\n control = array([0, 1, 1, 1, 4, 0], mask=[1, 1, 0, 0, 1, 1])\n assert_equal(test, control)\n assert_equal(test.filled(0), control.filled(0))\n assert_equal(test.mask, control.mask)\n #\n test = ediff1d(x, to_end=[1, 2, 3], to_begin=masked)\n control = array([0, 1, 1, 1, 4, 1, 2, 3],\n mask=[1, 1, 0, 0, 1, 0, 0, 0])\n assert_equal(test, control)\n assert_equal(test.filled(0), control.filled(0))\n assert_equal(test.mask, control.mask)\n\n def test_ediff1d_ndarray(self):\n # Test ediff1d w/ a ndarray\n x = np.arange(5)\n test = ediff1d(x)\n control = array([1, 1, 1, 1], mask=[0, 0, 0, 0])\n assert_equal(test, control)\n assert_(isinstance(test, MaskedArray))\n assert_equal(test.filled(0), control.filled(0))\n assert_equal(test.mask, control.mask)\n #\n test = ediff1d(x, to_end=masked, to_begin=masked)\n control = array([0, 1, 1, 1, 1, 0], mask=[1, 0, 0, 0, 0, 1])\n assert_(isinstance(test, MaskedArray))\n assert_equal(test.filled(0), control.filled(0))\n assert_equal(test.mask, control.mask)\n\n def test_intersect1d(self):\n # Test intersect1d\n x = array([1, 3, 3, 3], mask=[0, 0, 0, 1])\n y = array([3, 1, 1, 1], mask=[0, 0, 0, 1])\n test = intersect1d(x, y)\n control = array([1, 3, -1], mask=[0, 0, 1])\n assert_equal(test, control)\n\n def test_setxor1d(self):\n # Test setxor1d\n a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])\n b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])\n test = setxor1d(a, b)\n assert_equal(test, array([3, 4, 7]))\n #\n a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])\n b = [1, 2, 3, 4, 5]\n test = setxor1d(a, b)\n assert_equal(test, array([3, 4, 7, -1], mask=[0, 0, 0, 1]))\n #\n a = array([1, 2, 3])\n b = array([6, 5, 4])\n test = setxor1d(a, b)\n assert_(isinstance(test, MaskedArray))\n assert_equal(test, [1, 2, 3, 4, 5, 6])\n #\n a = array([1, 8, 2, 3], mask=[0, 1, 0, 0])\n b = array([6, 5, 4, 8], mask=[0, 0, 0, 1])\n test = setxor1d(a, b)\n assert_(isinstance(test, MaskedArray))\n assert_equal(test, [1, 2, 3, 4, 5, 6])\n #\n assert_array_equal([], setxor1d([], []))\n\n def test_setxor1d_unique(self):\n # Test setxor1d with assume_unique=True\n a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])\n b = [1, 2, 3, 4, 5]\n test = setxor1d(a, b, assume_unique=True)\n assert_equal(test, array([3, 4, 7, -1], mask=[0, 0, 0, 1]))\n #\n a = array([1, 8, 2, 3], mask=[0, 1, 0, 0])\n b = array([6, 5, 4, 8], mask=[0, 0, 0, 1])\n test = setxor1d(a, b, assume_unique=True)\n assert_(isinstance(test, MaskedArray))\n assert_equal(test, [1, 2, 3, 4, 5, 6])\n #\n a = array([[1], [8], [2], [3]])\n b = array([[6, 5], [4, 8]])\n test = setxor1d(a, b, assume_unique=True)\n assert_(isinstance(test, MaskedArray))\n assert_equal(test, [1, 2, 3, 4, 5, 6])\n\n def test_isin(self):\n # the tests for in1d cover most of isin's behavior\n # if in1d is removed, would need to change those tests to test\n # isin instead.\n a = np.arange(24).reshape([2, 3, 4])\n mask = np.zeros([2, 3, 4])\n mask[1, 2, 0] = 1\n a = array(a, mask=mask)\n b = array(data=[0, 10, 20, 30, 1, 3, 11, 22, 33],\n mask=[0, 1, 0, 1, 0, 1, 0, 1, 0])\n ec = zeros((2, 3, 4), dtype=bool)\n ec[0, 0, 0] = True\n ec[0, 0, 1] = True\n ec[0, 2, 3] = True\n c = isin(a, b)\n assert_(isinstance(c, MaskedArray))\n assert_array_equal(c, ec)\n # compare results of np.isin to ma.isin\n d = np.isin(a, b[~b.mask]) & ~a.mask\n assert_array_equal(c, d)\n\n def test_in1d(self):\n # Test in1d\n a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])\n b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])\n test = in1d(a, b)\n assert_equal(test, [True, True, True, False, True])\n #\n a = array([5, 5, 2, 1, -1], mask=[0, 0, 0, 0, 1])\n b = array([1, 5, -1], mask=[0, 0, 1])\n test = in1d(a, b)\n assert_equal(test, [True, True, False, True, True])\n #\n assert_array_equal([], in1d([], []))\n\n def test_in1d_invert(self):\n # Test in1d's invert parameter\n a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])\n b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])\n assert_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True))\n\n a = array([5, 5, 2, 1, -1], mask=[0, 0, 0, 0, 1])\n b = array([1, 5, -1], mask=[0, 0, 1])\n assert_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True))\n\n assert_array_equal([], in1d([], [], invert=True))\n\n def test_union1d(self):\n # Test union1d\n a = array([1, 2, 5, 7, 5, -1], mask=[0, 0, 0, 0, 0, 1])\n b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])\n test = union1d(a, b)\n control = array([1, 2, 3, 4, 5, 7, -1], mask=[0, 0, 0, 0, 0, 0, 1])\n assert_equal(test, control)\n\n # Tests gh-10340, arguments to union1d should be\n # flattened if they are not already 1D\n x = array([[0, 1, 2], [3, 4, 5]], mask=[[0, 0, 0], [0, 0, 1]])\n y = array([0, 1, 2, 3, 4], mask=[0, 0, 0, 0, 1])\n ez = array([0, 1, 2, 3, 4, 5], mask=[0, 0, 0, 0, 0, 1])\n z = union1d(x, y)\n assert_equal(z, ez)\n #\n assert_array_equal([], union1d([], []))\n\n def test_setdiff1d(self):\n # Test setdiff1d\n a = array([6, 5, 4, 7, 7, 1, 2, 1], mask=[0, 0, 0, 0, 0, 0, 0, 1])\n b = array([2, 4, 3, 3, 2, 1, 5])\n test = setdiff1d(a, b)\n assert_equal(test, array([6, 7, -1], mask=[0, 0, 1]))\n #\n a = arange(10)\n b = arange(8)\n assert_equal(setdiff1d(a, b), array([8, 9]))\n a = array([], np.uint32, mask=[])\n assert_equal(setdiff1d(a, []).dtype, np.uint32)\n\n def test_setdiff1d_char_array(self):\n # Test setdiff1d_charray\n a = np.array(['a', 'b', 'c'])\n b = np.array(['a', 'b', 's'])\n assert_array_equal(setdiff1d(a, b), np.array(['c']))\n\n\nclass TestShapeBase:\n\n def test_atleast_2d(self):\n # Test atleast_2d\n a = masked_array([0, 1, 2], mask=[0, 1, 0])\n b = atleast_2d(a)\n assert_equal(b.shape, (1, 3))\n assert_equal(b.mask.shape, b.data.shape)\n assert_equal(a.shape, (3,))\n assert_equal(a.mask.shape, a.data.shape)\n assert_equal(b.mask.shape, b.data.shape)\n\n def test_shape_scalar(self):\n # the atleast and diagflat function should work with scalars\n # GitHub issue #3367\n # Additionally, the atleast functions should accept multiple scalars\n # correctly\n b = atleast_1d(1.0)\n assert_equal(b.shape, (1,))\n assert_equal(b.mask.shape, b.shape)\n assert_equal(b.data.shape, b.shape)\n\n b = atleast_1d(1.0, 2.0)\n for a in b:\n assert_equal(a.shape, (1,))\n assert_equal(a.mask.shape, a.shape)\n assert_equal(a.data.shape, a.shape)\n\n b = atleast_2d(1.0)\n assert_equal(b.shape, (1, 1))\n assert_equal(b.mask.shape, b.shape)\n assert_equal(b.data.shape, b.shape)\n\n b = atleast_2d(1.0, 2.0)\n for a in b:\n assert_equal(a.shape, (1, 1))\n assert_equal(a.mask.shape, a.shape)\n assert_equal(a.data.shape, a.shape)\n\n b = atleast_3d(1.0)\n assert_equal(b.shape, (1, 1, 1))\n assert_equal(b.mask.shape, b.shape)\n assert_equal(b.data.shape, b.shape)\n\n b = atleast_3d(1.0, 2.0)\n for a in b:\n assert_equal(a.shape, (1, 1, 1))\n assert_equal(a.mask.shape, a.shape)\n assert_equal(a.data.shape, a.shape)\n\n b = diagflat(1.0)\n assert_equal(b.shape, (1, 1))\n assert_equal(b.mask.shape, b.data.shape)\n\n\nclass TestNDEnumerate:\n\n def test_ndenumerate_nomasked(self):\n ordinary = np.arange(6.).reshape((1, 3, 2))\n empty_mask = np.zeros_like(ordinary, dtype=bool)\n with_mask = masked_array(ordinary, mask=empty_mask)\n assert_equal(list(np.ndenumerate(ordinary)),\n list(ndenumerate(ordinary)))\n assert_equal(list(ndenumerate(ordinary)),\n list(ndenumerate(with_mask)))\n assert_equal(list(ndenumerate(with_mask)),\n list(ndenumerate(with_mask, compressed=False)))\n\n def test_ndenumerate_allmasked(self):\n a = masked_all(())\n b = masked_all((100,))\n c = masked_all((2, 3, 4))\n assert_equal(list(ndenumerate(a)), [])\n assert_equal(list(ndenumerate(b)), [])\n assert_equal(list(ndenumerate(b, compressed=False)),\n list(zip(np.ndindex((100,)), 100 * [masked])))\n assert_equal(list(ndenumerate(c)), [])\n assert_equal(list(ndenumerate(c, compressed=False)),\n list(zip(np.ndindex((2, 3, 4)), 2 * 3 * 4 * [masked])))\n\n def test_ndenumerate_mixedmasked(self):\n a = masked_array(np.arange(12).reshape((3, 4)),\n mask=[[1, 1, 1, 1],\n [1, 1, 0, 1],\n [0, 0, 0, 0]])\n items = [((1, 2), 6),\n ((2, 0), 8), ((2, 1), 9), ((2, 2), 10), ((2, 3), 11)]\n assert_equal(list(ndenumerate(a)), items)\n assert_equal(len(list(ndenumerate(a, compressed=False))), a.size)\n for coordinate, value in ndenumerate(a, compressed=False):\n assert_equal(a[coordinate], value)\n\n\nclass TestStack:\n\n def test_stack_1d(self):\n a = masked_array([0, 1, 2], mask=[0, 1, 0])\n b = masked_array([9, 8, 7], mask=[1, 0, 0])\n\n c = stack([a, b], axis=0)\n assert_equal(c.shape, (2, 3))\n assert_array_equal(a.mask, c[0].mask)\n assert_array_equal(b.mask, c[1].mask)\n\n d = vstack([a, b])\n assert_array_equal(c.data, d.data)\n assert_array_equal(c.mask, d.mask)\n\n c = stack([a, b], axis=1)\n assert_equal(c.shape, (3, 2))\n assert_array_equal(a.mask, c[:, 0].mask)\n assert_array_equal(b.mask, c[:, 1].mask)\n\n def test_stack_masks(self):\n a = masked_array([0, 1, 2], mask=True)\n b = masked_array([9, 8, 7], mask=False)\n\n c = stack([a, b], axis=0)\n assert_equal(c.shape, (2, 3))\n assert_array_equal(a.mask, c[0].mask)\n assert_array_equal(b.mask, c[1].mask)\n\n d = vstack([a, b])\n assert_array_equal(c.data, d.data)\n assert_array_equal(c.mask, d.mask)\n\n c = stack([a, b], axis=1)\n assert_equal(c.shape, (3, 2))\n assert_array_equal(a.mask, c[:, 0].mask)\n assert_array_equal(b.mask, c[:, 1].mask)\n\n def test_stack_nd(self):\n # 2D\n shp = (3, 2)\n d1 = np.random.randint(0, 10, shp)\n d2 = np.random.randint(0, 10, shp)\n m1 = np.random.randint(0, 2, shp).astype(bool)\n m2 = np.random.randint(0, 2, shp).astype(bool)\n a1 = masked_array(d1, mask=m1)\n a2 = masked_array(d2, mask=m2)\n\n c = stack([a1, a2], axis=0)\n c_shp = (2,) + shp\n assert_equal(c.shape, c_shp)\n assert_array_equal(a1.mask, c[0].mask)\n assert_array_equal(a2.mask, c[1].mask)\n\n c = stack([a1, a2], axis=-1)\n c_shp = shp + (2,)\n assert_equal(c.shape, c_shp)\n assert_array_equal(a1.mask, c[..., 0].mask)\n assert_array_equal(a2.mask, c[..., 1].mask)\n\n # 4D\n shp = (3, 2, 4, 5,)\n d1 = np.random.randint(0, 10, shp)\n d2 = np.random.randint(0, 10, shp)\n m1 = np.random.randint(0, 2, shp).astype(bool)\n m2 = np.random.randint(0, 2, shp).astype(bool)\n a1 = masked_array(d1, mask=m1)\n a2 = masked_array(d2, mask=m2)\n\n c = stack([a1, a2], axis=0)\n c_shp = (2,) + shp\n assert_equal(c.shape, c_shp)\n assert_array_equal(a1.mask, c[0].mask)\n assert_array_equal(a2.mask, c[1].mask)\n\n c = stack([a1, a2], axis=-1)\n c_shp = shp + (2,)\n assert_equal(c.shape, c_shp)\n assert_array_equal(a1.mask, c[..., 0].mask)\n assert_array_equal(a2.mask, c[..., 1].mask)\n | .venv\Lib\site-packages\numpy\ma\tests\test_extras.py | test_extras.py | Python | 80,433 | 0.75 | 0.081582 | 0.098324 | vue-tools | 181 | 2024-03-02T00:10:30.917230 | GPL-3.0 | true | 3bfed528dec04314a237b36514219711 |
"""Tests suite for mrecords.\n\n:author: Pierre Gerard-Marchant\n:contact: pierregm_at_uga_dot_edu\n\n"""\nimport pickle\n\nimport numpy as np\nimport numpy.ma as ma\nfrom numpy._core.records import fromarrays as recfromarrays\nfrom numpy._core.records import fromrecords as recfromrecords\nfrom numpy._core.records import recarray\nfrom numpy.ma import masked, nomask\nfrom numpy.ma.mrecords import (\n MaskedRecords,\n addfield,\n fromarrays,\n fromrecords,\n fromtextfile,\n mrecarray,\n)\nfrom numpy.ma.testutils import (\n assert_,\n assert_equal,\n assert_equal_records,\n)\nfrom numpy.testing import temppath\n\n\nclass TestMRecords:\n\n ilist = [1, 2, 3, 4, 5]\n flist = [1.1, 2.2, 3.3, 4.4, 5.5]\n slist = [b'one', b'two', b'three', b'four', b'five']\n ddtype = [('a', int), ('b', float), ('c', '|S8')]\n mask = [0, 1, 0, 0, 1]\n base = ma.array(list(zip(ilist, flist, slist)), mask=mask, dtype=ddtype)\n\n def test_byview(self):\n # Test creation by view\n base = self.base\n mbase = base.view(mrecarray)\n assert_equal(mbase.recordmask, base.recordmask)\n assert_equal_records(mbase._mask, base._mask)\n assert_(isinstance(mbase._data, recarray))\n assert_equal_records(mbase._data, base._data.view(recarray))\n for field in ('a', 'b', 'c'):\n assert_equal(base[field], mbase[field])\n assert_equal_records(mbase.view(mrecarray), mbase)\n\n def test_get(self):\n # Tests fields retrieval\n base = self.base.copy()\n mbase = base.view(mrecarray)\n # As fields..........\n for field in ('a', 'b', 'c'):\n assert_equal(getattr(mbase, field), mbase[field])\n assert_equal(base[field], mbase[field])\n # as elements .......\n mbase_first = mbase[0]\n assert_(isinstance(mbase_first, mrecarray))\n assert_equal(mbase_first.dtype, mbase.dtype)\n assert_equal(mbase_first.tolist(), (1, 1.1, b'one'))\n # Used to be mask, now it's recordmask\n assert_equal(mbase_first.recordmask, nomask)\n assert_equal(mbase_first._mask.item(), (False, False, False))\n assert_equal(mbase_first['a'], mbase['a'][0])\n mbase_last = mbase[-1]\n assert_(isinstance(mbase_last, mrecarray))\n assert_equal(mbase_last.dtype, mbase.dtype)\n assert_equal(mbase_last.tolist(), (None, None, None))\n # Used to be mask, now it's recordmask\n assert_equal(mbase_last.recordmask, True)\n assert_equal(mbase_last._mask.item(), (True, True, True))\n assert_equal(mbase_last['a'], mbase['a'][-1])\n assert_(mbase_last['a'] is masked)\n # as slice ..........\n mbase_sl = mbase[:2]\n assert_(isinstance(mbase_sl, mrecarray))\n assert_equal(mbase_sl.dtype, mbase.dtype)\n # Used to be mask, now it's recordmask\n assert_equal(mbase_sl.recordmask, [0, 1])\n assert_equal_records(mbase_sl.mask,\n np.array([(False, False, False),\n (True, True, True)],\n dtype=mbase._mask.dtype))\n assert_equal_records(mbase_sl, base[:2].view(mrecarray))\n for field in ('a', 'b', 'c'):\n assert_equal(getattr(mbase_sl, field), base[:2][field])\n\n def test_set_fields(self):\n # Tests setting fields.\n base = self.base.copy()\n mbase = base.view(mrecarray)\n mbase = mbase.copy()\n mbase.fill_value = (999999, 1e20, 'N/A')\n # Change the data, the mask should be conserved\n mbase.a._data[:] = 5\n assert_equal(mbase['a']._data, [5, 5, 5, 5, 5])\n assert_equal(mbase['a']._mask, [0, 1, 0, 0, 1])\n # Change the elements, and the mask will follow\n mbase.a = 1\n assert_equal(mbase['a']._data, [1] * 5)\n assert_equal(ma.getmaskarray(mbase['a']), [0] * 5)\n # Use to be _mask, now it's recordmask\n assert_equal(mbase.recordmask, [False] * 5)\n assert_equal(mbase._mask.tolist(),\n np.array([(0, 0, 0),\n (0, 1, 1),\n (0, 0, 0),\n (0, 0, 0),\n (0, 1, 1)],\n dtype=bool))\n # Set a field to mask ........................\n mbase.c = masked\n # Use to be mask, and now it's still mask !\n assert_equal(mbase.c.mask, [1] * 5)\n assert_equal(mbase.c.recordmask, [1] * 5)\n assert_equal(ma.getmaskarray(mbase['c']), [1] * 5)\n assert_equal(ma.getdata(mbase['c']), [b'N/A'] * 5)\n assert_equal(mbase._mask.tolist(),\n np.array([(0, 0, 1),\n (0, 1, 1),\n (0, 0, 1),\n (0, 0, 1),\n (0, 1, 1)],\n dtype=bool))\n # Set fields by slices .......................\n mbase = base.view(mrecarray).copy()\n mbase.a[3:] = 5\n assert_equal(mbase.a, [1, 2, 3, 5, 5])\n assert_equal(mbase.a._mask, [0, 1, 0, 0, 0])\n mbase.b[3:] = masked\n assert_equal(mbase.b, base['b'])\n assert_equal(mbase.b._mask, [0, 1, 0, 1, 1])\n # Set fields globally..........................\n ndtype = [('alpha', '|S1'), ('num', int)]\n data = ma.array([('a', 1), ('b', 2), ('c', 3)], dtype=ndtype)\n rdata = data.view(MaskedRecords)\n val = ma.array([10, 20, 30], mask=[1, 0, 0])\n\n rdata['num'] = val\n assert_equal(rdata.num, val)\n assert_equal(rdata.num.mask, [1, 0, 0])\n\n def test_set_fields_mask(self):\n # Tests setting the mask of a field.\n base = self.base.copy()\n # This one has already a mask....\n mbase = base.view(mrecarray)\n mbase['a'][-2] = masked\n assert_equal(mbase.a, [1, 2, 3, 4, 5])\n assert_equal(mbase.a._mask, [0, 1, 0, 1, 1])\n # This one has not yet\n mbase = fromarrays([np.arange(5), np.random.rand(5)],\n dtype=[('a', int), ('b', float)])\n mbase['a'][-2] = masked\n assert_equal(mbase.a, [0, 1, 2, 3, 4])\n assert_equal(mbase.a._mask, [0, 0, 0, 1, 0])\n\n def test_set_mask(self):\n base = self.base.copy()\n mbase = base.view(mrecarray)\n # Set the mask to True .......................\n mbase.mask = masked\n assert_equal(ma.getmaskarray(mbase['b']), [1] * 5)\n assert_equal(mbase['a']._mask, mbase['b']._mask)\n assert_equal(mbase['a']._mask, mbase['c']._mask)\n assert_equal(mbase._mask.tolist(),\n np.array([(1, 1, 1)] * 5, dtype=bool))\n # Delete the mask ............................\n mbase.mask = nomask\n assert_equal(ma.getmaskarray(mbase['c']), [0] * 5)\n assert_equal(mbase._mask.tolist(),\n np.array([(0, 0, 0)] * 5, dtype=bool))\n\n def test_set_mask_fromarray(self):\n base = self.base.copy()\n mbase = base.view(mrecarray)\n # Sets the mask w/ an array\n mbase.mask = [1, 0, 0, 0, 1]\n assert_equal(mbase.a.mask, [1, 0, 0, 0, 1])\n assert_equal(mbase.b.mask, [1, 0, 0, 0, 1])\n assert_equal(mbase.c.mask, [1, 0, 0, 0, 1])\n # Yay, once more !\n mbase.mask = [0, 0, 0, 0, 1]\n assert_equal(mbase.a.mask, [0, 0, 0, 0, 1])\n assert_equal(mbase.b.mask, [0, 0, 0, 0, 1])\n assert_equal(mbase.c.mask, [0, 0, 0, 0, 1])\n\n def test_set_mask_fromfields(self):\n mbase = self.base.copy().view(mrecarray)\n\n nmask = np.array(\n [(0, 1, 0), (0, 1, 0), (1, 0, 1), (1, 0, 1), (0, 0, 0)],\n dtype=[('a', bool), ('b', bool), ('c', bool)])\n mbase.mask = nmask\n assert_equal(mbase.a.mask, [0, 0, 1, 1, 0])\n assert_equal(mbase.b.mask, [1, 1, 0, 0, 0])\n assert_equal(mbase.c.mask, [0, 0, 1, 1, 0])\n # Reinitialize and redo\n mbase.mask = False\n mbase.fieldmask = nmask\n assert_equal(mbase.a.mask, [0, 0, 1, 1, 0])\n assert_equal(mbase.b.mask, [1, 1, 0, 0, 0])\n assert_equal(mbase.c.mask, [0, 0, 1, 1, 0])\n\n def test_set_elements(self):\n base = self.base.copy()\n # Set an element to mask .....................\n mbase = base.view(mrecarray).copy()\n mbase[-2] = masked\n assert_equal(\n mbase._mask.tolist(),\n np.array([(0, 0, 0), (1, 1, 1), (0, 0, 0), (1, 1, 1), (1, 1, 1)],\n dtype=bool))\n # Used to be mask, now it's recordmask!\n assert_equal(mbase.recordmask, [0, 1, 0, 1, 1])\n # Set slices .................................\n mbase = base.view(mrecarray).copy()\n mbase[:2] = (5, 5, 5)\n assert_equal(mbase.a._data, [5, 5, 3, 4, 5])\n assert_equal(mbase.a._mask, [0, 0, 0, 0, 1])\n assert_equal(mbase.b._data, [5., 5., 3.3, 4.4, 5.5])\n assert_equal(mbase.b._mask, [0, 0, 0, 0, 1])\n assert_equal(mbase.c._data,\n [b'5', b'5', b'three', b'four', b'five'])\n assert_equal(mbase.b._mask, [0, 0, 0, 0, 1])\n\n mbase = base.view(mrecarray).copy()\n mbase[:2] = masked\n assert_equal(mbase.a._data, [1, 2, 3, 4, 5])\n assert_equal(mbase.a._mask, [1, 1, 0, 0, 1])\n assert_equal(mbase.b._data, [1.1, 2.2, 3.3, 4.4, 5.5])\n assert_equal(mbase.b._mask, [1, 1, 0, 0, 1])\n assert_equal(mbase.c._data,\n [b'one', b'two', b'three', b'four', b'five'])\n assert_equal(mbase.b._mask, [1, 1, 0, 0, 1])\n\n def test_setslices_hardmask(self):\n # Tests setting slices w/ hardmask.\n base = self.base.copy()\n mbase = base.view(mrecarray)\n mbase.harden_mask()\n try:\n mbase[-2:] = (5, 5, 5)\n assert_equal(mbase.a._data, [1, 2, 3, 5, 5])\n assert_equal(mbase.b._data, [1.1, 2.2, 3.3, 5, 5.5])\n assert_equal(mbase.c._data,\n [b'one', b'two', b'three', b'5', b'five'])\n assert_equal(mbase.a._mask, [0, 1, 0, 0, 1])\n assert_equal(mbase.b._mask, mbase.a._mask)\n assert_equal(mbase.b._mask, mbase.c._mask)\n except NotImplementedError:\n # OK, not implemented yet...\n pass\n except AssertionError:\n raise\n else:\n raise Exception("Flexible hard masks should be supported !")\n # Not using a tuple should crash\n try:\n mbase[-2:] = 3\n except (NotImplementedError, TypeError):\n pass\n else:\n raise TypeError("Should have expected a readable buffer object!")\n\n def test_hardmask(self):\n # Test hardmask\n base = self.base.copy()\n mbase = base.view(mrecarray)\n mbase.harden_mask()\n assert_(mbase._hardmask)\n mbase.mask = nomask\n assert_equal_records(mbase._mask, base._mask)\n mbase.soften_mask()\n assert_(not mbase._hardmask)\n mbase.mask = nomask\n # So, the mask of a field is no longer set to nomask...\n assert_equal_records(mbase._mask,\n ma.make_mask_none(base.shape, base.dtype))\n assert_(ma.make_mask(mbase['b']._mask) is nomask)\n assert_equal(mbase['a']._mask, mbase['b']._mask)\n\n def test_pickling(self):\n # Test pickling\n base = self.base.copy()\n mrec = base.view(mrecarray)\n for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):\n _ = pickle.dumps(mrec, protocol=proto)\n mrec_ = pickle.loads(_)\n assert_equal(mrec_.dtype, mrec.dtype)\n assert_equal_records(mrec_._data, mrec._data)\n assert_equal(mrec_._mask, mrec._mask)\n assert_equal_records(mrec_._mask, mrec._mask)\n\n def test_filled(self):\n # Test filling the array\n _a = ma.array([1, 2, 3], mask=[0, 0, 1], dtype=int)\n _b = ma.array([1.1, 2.2, 3.3], mask=[0, 0, 1], dtype=float)\n _c = ma.array(['one', 'two', 'three'], mask=[0, 0, 1], dtype='|S8')\n ddtype = [('a', int), ('b', float), ('c', '|S8')]\n mrec = fromarrays([_a, _b, _c], dtype=ddtype,\n fill_value=(99999, 99999., 'N/A'))\n mrecfilled = mrec.filled()\n assert_equal(mrecfilled['a'], np.array((1, 2, 99999), dtype=int))\n assert_equal(mrecfilled['b'], np.array((1.1, 2.2, 99999.),\n dtype=float))\n assert_equal(mrecfilled['c'], np.array(('one', 'two', 'N/A'),\n dtype='|S8'))\n\n def test_tolist(self):\n # Test tolist.\n _a = ma.array([1, 2, 3], mask=[0, 0, 1], dtype=int)\n _b = ma.array([1.1, 2.2, 3.3], mask=[0, 0, 1], dtype=float)\n _c = ma.array(['one', 'two', 'three'], mask=[1, 0, 0], dtype='|S8')\n ddtype = [('a', int), ('b', float), ('c', '|S8')]\n mrec = fromarrays([_a, _b, _c], dtype=ddtype,\n fill_value=(99999, 99999., 'N/A'))\n\n assert_equal(mrec.tolist(),\n [(1, 1.1, None), (2, 2.2, b'two'),\n (None, None, b'three')])\n\n def test_withnames(self):\n # Test the creation w/ format and names\n x = mrecarray(1, formats=float, names='base')\n x[0]['base'] = 10\n assert_equal(x['base'][0], 10)\n\n def test_exotic_formats(self):\n # Test that 'exotic' formats are processed properly\n easy = mrecarray(1, dtype=[('i', int), ('s', '|S8'), ('f', float)])\n easy[0] = masked\n assert_equal(easy.filled(1).item(), (1, b'1', 1.))\n\n solo = mrecarray(1, dtype=[('f0', '<f8', (2, 2))])\n solo[0] = masked\n assert_equal(solo.filled(1).item(),\n np.array((1,), dtype=solo.dtype).item())\n\n mult = mrecarray(2, dtype="i4, (2,3)float, float")\n mult[0] = masked\n mult[1] = (1, 1, 1)\n mult.filled(0)\n assert_equal_records(mult.filled(0),\n np.array([(0, 0, 0), (1, 1, 1)],\n dtype=mult.dtype))\n\n\nclass TestView:\n\n def setup_method(self):\n (a, b) = (np.arange(10), np.random.rand(10))\n ndtype = [('a', float), ('b', float)]\n arr = np.array(list(zip(a, b)), dtype=ndtype)\n\n mrec = fromarrays([a, b], dtype=ndtype, fill_value=(-9., -99.))\n mrec.mask[3] = (False, True)\n self.data = (mrec, a, b, arr)\n\n def test_view_by_itself(self):\n (mrec, a, b, arr) = self.data\n test = mrec.view()\n assert_(isinstance(test, MaskedRecords))\n assert_equal_records(test, mrec)\n assert_equal_records(test._mask, mrec._mask)\n\n def test_view_simple_dtype(self):\n (mrec, a, b, arr) = self.data\n ntype = (float, 2)\n test = mrec.view(ntype)\n assert_(isinstance(test, ma.MaskedArray))\n assert_equal(test, np.array(list(zip(a, b)), dtype=float))\n assert_(test[3, 1] is ma.masked)\n\n def test_view_flexible_type(self):\n (mrec, a, b, arr) = self.data\n alttype = [('A', float), ('B', float)]\n test = mrec.view(alttype)\n assert_(isinstance(test, MaskedRecords))\n assert_equal_records(test, arr.view(alttype))\n assert_(test['B'][3] is masked)\n assert_equal(test.dtype, np.dtype(alttype))\n assert_(test._fill_value is None)\n\n\n##############################################################################\nclass TestMRecordsImport:\n\n _a = ma.array([1, 2, 3], mask=[0, 0, 1], dtype=int)\n _b = ma.array([1.1, 2.2, 3.3], mask=[0, 0, 1], dtype=float)\n _c = ma.array([b'one', b'two', b'three'],\n mask=[0, 0, 1], dtype='|S8')\n ddtype = [('a', int), ('b', float), ('c', '|S8')]\n mrec = fromarrays([_a, _b, _c], dtype=ddtype,\n fill_value=(b'99999', b'99999.',\n b'N/A'))\n nrec = recfromarrays((_a._data, _b._data, _c._data), dtype=ddtype)\n data = (mrec, nrec, ddtype)\n\n def test_fromarrays(self):\n _a = ma.array([1, 2, 3], mask=[0, 0, 1], dtype=int)\n _b = ma.array([1.1, 2.2, 3.3], mask=[0, 0, 1], dtype=float)\n _c = ma.array(['one', 'two', 'three'], mask=[0, 0, 1], dtype='|S8')\n (mrec, nrec, _) = self.data\n for (f, l) in zip(('a', 'b', 'c'), (_a, _b, _c)):\n assert_equal(getattr(mrec, f)._mask, l._mask)\n # One record only\n _x = ma.array([1, 1.1, 'one'], mask=[1, 0, 0], dtype=object)\n assert_equal_records(fromarrays(_x, dtype=mrec.dtype), mrec[0])\n\n def test_fromrecords(self):\n # Test construction from records.\n (mrec, nrec, ddtype) = self.data\n # ......\n palist = [(1, 'abc', 3.7000002861022949, 0),\n (2, 'xy', 6.6999998092651367, 1),\n (0, ' ', 0.40000000596046448, 0)]\n pa = recfromrecords(palist, names='c1, c2, c3, c4')\n mpa = fromrecords(palist, names='c1, c2, c3, c4')\n assert_equal_records(pa, mpa)\n # .....\n _mrec = fromrecords(nrec)\n assert_equal(_mrec.dtype, mrec.dtype)\n for field in _mrec.dtype.names:\n assert_equal(getattr(_mrec, field), getattr(mrec._data, field))\n\n _mrec = fromrecords(nrec.tolist(), names='c1,c2,c3')\n assert_equal(_mrec.dtype, [('c1', int), ('c2', float), ('c3', '|S5')])\n for (f, n) in zip(('c1', 'c2', 'c3'), ('a', 'b', 'c')):\n assert_equal(getattr(_mrec, f), getattr(mrec._data, n))\n\n _mrec = fromrecords(mrec)\n assert_equal(_mrec.dtype, mrec.dtype)\n assert_equal_records(_mrec._data, mrec.filled())\n assert_equal_records(_mrec._mask, mrec._mask)\n\n def test_fromrecords_wmask(self):\n # Tests construction from records w/ mask.\n (mrec, nrec, ddtype) = self.data\n\n _mrec = fromrecords(nrec.tolist(), dtype=ddtype, mask=[0, 1, 0,])\n assert_equal_records(_mrec._data, mrec._data)\n assert_equal(_mrec._mask.tolist(), [(0, 0, 0), (1, 1, 1), (0, 0, 0)])\n\n _mrec = fromrecords(nrec.tolist(), dtype=ddtype, mask=True)\n assert_equal_records(_mrec._data, mrec._data)\n assert_equal(_mrec._mask.tolist(), [(1, 1, 1), (1, 1, 1), (1, 1, 1)])\n\n _mrec = fromrecords(nrec.tolist(), dtype=ddtype, mask=mrec._mask)\n assert_equal_records(_mrec._data, mrec._data)\n assert_equal(_mrec._mask.tolist(), mrec._mask.tolist())\n\n _mrec = fromrecords(nrec.tolist(), dtype=ddtype,\n mask=mrec._mask.tolist())\n assert_equal_records(_mrec._data, mrec._data)\n assert_equal(_mrec._mask.tolist(), mrec._mask.tolist())\n\n def test_fromtextfile(self):\n # Tests reading from a text file.\n fcontent = (\n"""#\n'One (S)','Two (I)','Three (F)','Four (M)','Five (-)','Six (C)'\n'strings',1,1.0,'mixed column',,1\n'with embedded "double quotes"',2,2.0,1.0,,1\n'strings',3,3.0E5,3,,1\n'strings',4,-1e-10,,,1\n""")\n with temppath() as path:\n with open(path, 'w') as f:\n f.write(fcontent)\n mrectxt = fromtextfile(path, delimiter=',', varnames='ABCDEFG')\n assert_(isinstance(mrectxt, MaskedRecords))\n assert_equal(mrectxt.F, [1, 1, 1, 1])\n assert_equal(mrectxt.E._mask, [1, 1, 1, 1])\n assert_equal(mrectxt.C, [1, 2, 3.e+5, -1e-10])\n\n def test_addfield(self):\n # Tests addfield\n (mrec, nrec, ddtype) = self.data\n (d, m) = ([100, 200, 300], [1, 0, 0])\n mrec = addfield(mrec, ma.array(d, mask=m))\n assert_equal(mrec.f3, d)\n assert_equal(mrec.f3._mask, m)\n\n\ndef test_record_array_with_object_field():\n # Trac #1839\n y = ma.masked_array(\n [(1, '2'), (3, '4')],\n mask=[(0, 0), (0, 1)],\n dtype=[('a', int), ('b', object)])\n # getting an item used to fail\n y[1]\n | .venv\Lib\site-packages\numpy\ma\tests\test_mrecords.py | test_mrecords.py | Python | 20,391 | 0.95 | 0.076459 | 0.105145 | vue-tools | 405 | 2024-05-15T18:57:20.089469 | BSD-3-Clause | true | 6986e7d6be178aaf6e6392f3c9b370ef |
import pickle\nfrom functools import reduce\n\nimport pytest\n\nimport numpy as np\nimport numpy._core.fromnumeric as fromnumeric\nimport numpy._core.umath as umath\nfrom numpy.ma import (\n MaskedArray,\n MaskType,\n absolute,\n add,\n all,\n allclose,\n allequal,\n alltrue,\n arange,\n arccos,\n arcsin,\n arctan,\n arctan2,\n array,\n average,\n choose,\n concatenate,\n conjugate,\n cos,\n cosh,\n count,\n divide,\n equal,\n exp,\n filled,\n getmask,\n greater,\n greater_equal,\n inner,\n isMaskedArray,\n less,\n less_equal,\n log,\n log10,\n make_mask,\n masked,\n masked_array,\n masked_equal,\n masked_greater,\n masked_greater_equal,\n masked_inside,\n masked_less,\n masked_less_equal,\n masked_not_equal,\n masked_outside,\n masked_print_option,\n masked_values,\n masked_where,\n maximum,\n minimum,\n multiply,\n nomask,\n nonzero,\n not_equal,\n ones,\n outer,\n product,\n put,\n ravel,\n repeat,\n resize,\n shape,\n sin,\n sinh,\n sometrue,\n sort,\n sqrt,\n subtract,\n sum,\n take,\n tan,\n tanh,\n transpose,\n where,\n zeros,\n)\nfrom numpy.testing import (\n assert_,\n assert_equal,\n assert_raises,\n)\n\npi = np.pi\n\n\ndef eq(v, w, msg=''):\n result = allclose(v, w)\n if not result:\n print(f'Not eq:{msg}\n{v}\n----{w}')\n return result\n\n\nclass TestMa:\n\n def setup_method(self):\n x = np.array([1., 1., 1., -2., pi / 2.0, 4., 5., -10., 10., 1., 2., 3.])\n y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])\n a10 = 10.\n m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]\n m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]\n xm = array(x, mask=m1)\n ym = array(y, mask=m2)\n z = np.array([-.5, 0., .5, .8])\n zm = array(z, mask=[0, 1, 0, 0])\n xf = np.where(m1, 1e+20, x)\n s = x.shape\n xm.set_fill_value(1e+20)\n self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf, s)\n\n def test_testBasic1d(self):\n # Test of basic array creation and properties in 1 dimension.\n (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d\n assert_(not isMaskedArray(x))\n assert_(isMaskedArray(xm))\n assert_equal(shape(xm), s)\n assert_equal(xm.shape, s)\n assert_equal(xm.dtype, x.dtype)\n assert_equal(xm.size, reduce(lambda x, y: x * y, s))\n assert_equal(count(xm), len(m1) - reduce(lambda x, y: x + y, m1))\n assert_(eq(xm, xf))\n assert_(eq(filled(xm, 1.e20), xf))\n assert_(eq(x, xm))\n\n @pytest.mark.parametrize("s", [(4, 3), (6, 2)])\n def test_testBasic2d(self, s):\n # Test of basic array creation and properties in 2 dimensions.\n (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d\n x.shape = s\n y.shape = s\n xm.shape = s\n ym.shape = s\n xf.shape = s\n\n assert_(not isMaskedArray(x))\n assert_(isMaskedArray(xm))\n assert_equal(shape(xm), s)\n assert_equal(xm.shape, s)\n assert_equal(xm.size, reduce(lambda x, y: x * y, s))\n assert_equal(count(xm), len(m1) - reduce(lambda x, y: x + y, m1))\n assert_(eq(xm, xf))\n assert_(eq(filled(xm, 1.e20), xf))\n assert_(eq(x, xm))\n\n def test_testArithmetic(self):\n # Test of basic arithmetic.\n (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d\n a2d = array([[1, 2], [0, 4]])\n a2dm = masked_array(a2d, [[0, 0], [1, 0]])\n assert_(eq(a2d * a2d, a2d * a2dm))\n assert_(eq(a2d + a2d, a2d + a2dm))\n assert_(eq(a2d - a2d, a2d - a2dm))\n for s in [(12,), (4, 3), (2, 6)]:\n x = x.reshape(s)\n y = y.reshape(s)\n xm = xm.reshape(s)\n ym = ym.reshape(s)\n xf = xf.reshape(s)\n assert_(eq(-x, -xm))\n assert_(eq(x + y, xm + ym))\n assert_(eq(x - y, xm - ym))\n assert_(eq(x * y, xm * ym))\n with np.errstate(divide='ignore', invalid='ignore'):\n assert_(eq(x / y, xm / ym))\n assert_(eq(a10 + y, a10 + ym))\n assert_(eq(a10 - y, a10 - ym))\n assert_(eq(a10 * y, a10 * ym))\n with np.errstate(divide='ignore', invalid='ignore'):\n assert_(eq(a10 / y, a10 / ym))\n assert_(eq(x + a10, xm + a10))\n assert_(eq(x - a10, xm - a10))\n assert_(eq(x * a10, xm * a10))\n assert_(eq(x / a10, xm / a10))\n assert_(eq(x ** 2, xm ** 2))\n assert_(eq(abs(x) ** 2.5, abs(xm) ** 2.5))\n assert_(eq(x ** y, xm ** ym))\n assert_(eq(np.add(x, y), add(xm, ym)))\n assert_(eq(np.subtract(x, y), subtract(xm, ym)))\n assert_(eq(np.multiply(x, y), multiply(xm, ym)))\n with np.errstate(divide='ignore', invalid='ignore'):\n assert_(eq(np.divide(x, y), divide(xm, ym)))\n\n def test_testMixedArithmetic(self):\n na = np.array([1])\n ma = array([1])\n assert_(isinstance(na + ma, MaskedArray))\n assert_(isinstance(ma + na, MaskedArray))\n\n def test_testUfuncs1(self):\n # Test various functions such as sin, cos.\n (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d\n assert_(eq(np.cos(x), cos(xm)))\n assert_(eq(np.cosh(x), cosh(xm)))\n assert_(eq(np.sin(x), sin(xm)))\n assert_(eq(np.sinh(x), sinh(xm)))\n assert_(eq(np.tan(x), tan(xm)))\n assert_(eq(np.tanh(x), tanh(xm)))\n with np.errstate(divide='ignore', invalid='ignore'):\n assert_(eq(np.sqrt(abs(x)), sqrt(xm)))\n assert_(eq(np.log(abs(x)), log(xm)))\n assert_(eq(np.log10(abs(x)), log10(xm)))\n assert_(eq(np.exp(x), exp(xm)))\n assert_(eq(np.arcsin(z), arcsin(zm)))\n assert_(eq(np.arccos(z), arccos(zm)))\n assert_(eq(np.arctan(z), arctan(zm)))\n assert_(eq(np.arctan2(x, y), arctan2(xm, ym)))\n assert_(eq(np.absolute(x), absolute(xm)))\n assert_(eq(np.equal(x, y), equal(xm, ym)))\n assert_(eq(np.not_equal(x, y), not_equal(xm, ym)))\n assert_(eq(np.less(x, y), less(xm, ym)))\n assert_(eq(np.greater(x, y), greater(xm, ym)))\n assert_(eq(np.less_equal(x, y), less_equal(xm, ym)))\n assert_(eq(np.greater_equal(x, y), greater_equal(xm, ym)))\n assert_(eq(np.conjugate(x), conjugate(xm)))\n assert_(eq(np.concatenate((x, y)), concatenate((xm, ym))))\n assert_(eq(np.concatenate((x, y)), concatenate((x, y))))\n assert_(eq(np.concatenate((x, y)), concatenate((xm, y))))\n assert_(eq(np.concatenate((x, y, x)), concatenate((x, ym, x))))\n\n def test_xtestCount(self):\n # Test count\n ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])\n assert_(count(ott).dtype.type is np.intp)\n assert_equal(3, count(ott))\n assert_equal(1, count(1))\n assert_(eq(0, array(1, mask=[1])))\n ott = ott.reshape((2, 2))\n assert_(count(ott).dtype.type is np.intp)\n assert_(isinstance(count(ott, 0), np.ndarray))\n assert_(count(ott).dtype.type is np.intp)\n assert_(eq(3, count(ott)))\n assert_(getmask(count(ott, 0)) is nomask)\n assert_(eq([1, 2], count(ott, 0)))\n\n def test_testMinMax(self):\n # Test minimum and maximum.\n (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d\n xr = np.ravel(x) # max doesn't work if shaped\n xmr = ravel(xm)\n\n # true because of careful selection of data\n assert_(eq(max(xr), maximum.reduce(xmr)))\n assert_(eq(min(xr), minimum.reduce(xmr)))\n\n def test_testAddSumProd(self):\n # Test add, sum, product.\n (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d\n assert_(eq(np.add.reduce(x), add.reduce(x)))\n assert_(eq(np.add.accumulate(x), add.accumulate(x)))\n assert_(eq(4, sum(array(4), axis=0)))\n assert_(eq(4, sum(array(4), axis=0)))\n assert_(eq(np.sum(x, axis=0), sum(x, axis=0)))\n assert_(eq(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0)))\n assert_(eq(np.sum(x, 0), sum(x, 0)))\n assert_(eq(np.prod(x, axis=0), product(x, axis=0)))\n assert_(eq(np.prod(x, 0), product(x, 0)))\n assert_(eq(np.prod(filled(xm, 1), axis=0),\n product(xm, axis=0)))\n if len(s) > 1:\n assert_(eq(np.concatenate((x, y), 1),\n concatenate((xm, ym), 1)))\n assert_(eq(np.add.reduce(x, 1), add.reduce(x, 1)))\n assert_(eq(np.sum(x, 1), sum(x, 1)))\n assert_(eq(np.prod(x, 1), product(x, 1)))\n\n def test_testCI(self):\n # Test of conversions and indexing\n x1 = np.array([1, 2, 4, 3])\n x2 = array(x1, mask=[1, 0, 0, 0])\n x3 = array(x1, mask=[0, 1, 0, 1])\n x4 = array(x1)\n # test conversion to strings\n str(x2) # raises?\n repr(x2) # raises?\n assert_(eq(np.sort(x1), sort(x2, fill_value=0)))\n # tests of indexing\n assert_(type(x2[1]) is type(x1[1]))\n assert_(x1[1] == x2[1])\n assert_(x2[0] is masked)\n assert_(eq(x1[2], x2[2]))\n assert_(eq(x1[2:5], x2[2:5]))\n assert_(eq(x1[:], x2[:]))\n assert_(eq(x1[1:], x3[1:]))\n x1[2] = 9\n x2[2] = 9\n assert_(eq(x1, x2))\n x1[1:3] = 99\n x2[1:3] = 99\n assert_(eq(x1, x2))\n x2[1] = masked\n assert_(eq(x1, x2))\n x2[1:3] = masked\n assert_(eq(x1, x2))\n x2[:] = x1\n x2[1] = masked\n assert_(allequal(getmask(x2), array([0, 1, 0, 0])))\n x3[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])\n assert_(allequal(getmask(x3), array([0, 1, 1, 0])))\n x4[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])\n assert_(allequal(getmask(x4), array([0, 1, 1, 0])))\n assert_(allequal(x4, array([1, 2, 3, 4])))\n x1 = np.arange(5) * 1.0\n x2 = masked_values(x1, 3.0)\n assert_(eq(x1, x2))\n assert_(allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask))\n assert_(eq(3.0, x2.fill_value))\n x1 = array([1, 'hello', 2, 3], object)\n x2 = np.array([1, 'hello', 2, 3], object)\n s1 = x1[1]\n s2 = x2[1]\n assert_equal(type(s2), str)\n assert_equal(type(s1), str)\n assert_equal(s1, s2)\n assert_(x1[1:1].shape == (0,))\n\n def test_testCopySize(self):\n # Tests of some subtle points of copying and sizing.\n n = [0, 0, 1, 0, 0]\n m = make_mask(n)\n m2 = make_mask(m)\n assert_(m is m2)\n m3 = make_mask(m, copy=True)\n assert_(m is not m3)\n\n x1 = np.arange(5)\n y1 = array(x1, mask=m)\n assert_(y1._data is not x1)\n assert_(allequal(x1, y1._data))\n assert_(y1._mask is m)\n\n y1a = array(y1, copy=0)\n # For copy=False, one might expect that the array would just\n # passed on, i.e., that it would be "is" instead of "==".\n # See gh-4043 for discussion.\n assert_(y1a._mask.__array_interface__ ==\n y1._mask.__array_interface__)\n\n y2 = array(x1, mask=m3, copy=0)\n assert_(y2._mask is m3)\n assert_(y2[2] is masked)\n y2[2] = 9\n assert_(y2[2] is not masked)\n assert_(y2._mask is m3)\n assert_(allequal(y2.mask, 0))\n\n y2a = array(x1, mask=m, copy=1)\n assert_(y2a._mask is not m)\n assert_(y2a[2] is masked)\n y2a[2] = 9\n assert_(y2a[2] is not masked)\n assert_(y2a._mask is not m)\n assert_(allequal(y2a.mask, 0))\n\n y3 = array(x1 * 1.0, mask=m)\n assert_(filled(y3).dtype is (x1 * 1.0).dtype)\n\n x4 = arange(4)\n x4[2] = masked\n y4 = resize(x4, (8,))\n assert_(eq(concatenate([x4, x4]), y4))\n assert_(eq(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0]))\n y5 = repeat(x4, (2, 2, 2, 2), axis=0)\n assert_(eq(y5, [0, 0, 1, 1, 2, 2, 3, 3]))\n y6 = repeat(x4, 2, axis=0)\n assert_(eq(y5, y6))\n\n def test_testPut(self):\n # Test of put\n d = arange(5)\n n = [0, 0, 0, 1, 1]\n m = make_mask(n)\n m2 = m.copy()\n x = array(d, mask=m)\n assert_(x[3] is masked)\n assert_(x[4] is masked)\n x[[1, 4]] = [10, 40]\n assert_(x._mask is m)\n assert_(x[3] is masked)\n assert_(x[4] is not masked)\n assert_(eq(x, [0, 10, 2, -1, 40]))\n\n x = array(d, mask=m2, copy=True)\n x.put([0, 1, 2], [-1, 100, 200])\n assert_(x._mask is not m2)\n assert_(x[3] is masked)\n assert_(x[4] is masked)\n assert_(eq(x, [-1, 100, 200, 0, 0]))\n\n def test_testPut2(self):\n # Test of put\n d = arange(5)\n x = array(d, mask=[0, 0, 0, 0, 0])\n z = array([10, 40], mask=[1, 0])\n assert_(x[2] is not masked)\n assert_(x[3] is not masked)\n x[2:4] = z\n assert_(x[2] is masked)\n assert_(x[3] is not masked)\n assert_(eq(x, [0, 1, 10, 40, 4]))\n\n d = arange(5)\n x = array(d, mask=[0, 0, 0, 0, 0])\n y = x[2:4]\n z = array([10, 40], mask=[1, 0])\n assert_(x[2] is not masked)\n assert_(x[3] is not masked)\n y[:] = z\n assert_(y[0] is masked)\n assert_(y[1] is not masked)\n assert_(eq(y, [10, 40]))\n assert_(x[2] is masked)\n assert_(x[3] is not masked)\n assert_(eq(x, [0, 1, 10, 40, 4]))\n\n def test_testMaPut(self):\n (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d\n m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1]\n i = np.nonzero(m)[0]\n put(ym, i, zm)\n assert_(all(take(ym, i, axis=0) == zm))\n\n def test_testOddFeatures(self):\n # Test of other odd features\n x = arange(20)\n x = x.reshape(4, 5)\n x.flat[5] = 12\n assert_(x[1, 0] == 12)\n z = x + 10j * x\n assert_(eq(z.real, x))\n assert_(eq(z.imag, 10 * x))\n assert_(eq((z * conjugate(z)).real, 101 * x * x))\n z.imag[...] = 0.0\n\n x = arange(10)\n x[3] = masked\n assert_(str(x[3]) == str(masked))\n c = x >= 8\n assert_(count(where(c, masked, masked)) == 0)\n assert_(shape(where(c, masked, masked)) == c.shape)\n z = where(c, x, masked)\n assert_(z.dtype is x.dtype)\n assert_(z[3] is masked)\n assert_(z[4] is masked)\n assert_(z[7] is masked)\n assert_(z[8] is not masked)\n assert_(z[9] is not masked)\n assert_(eq(x, z))\n z = where(c, masked, x)\n assert_(z.dtype is x.dtype)\n assert_(z[3] is masked)\n assert_(z[4] is not masked)\n assert_(z[7] is not masked)\n assert_(z[8] is masked)\n assert_(z[9] is masked)\n z = masked_where(c, x)\n assert_(z.dtype is x.dtype)\n assert_(z[3] is masked)\n assert_(z[4] is not masked)\n assert_(z[7] is not masked)\n assert_(z[8] is masked)\n assert_(z[9] is masked)\n assert_(eq(x, z))\n x = array([1., 2., 3., 4., 5.])\n c = array([1, 1, 1, 0, 0])\n x[2] = masked\n z = where(c, x, -x)\n assert_(eq(z, [1., 2., 0., -4., -5]))\n c[0] = masked\n z = where(c, x, -x)\n assert_(eq(z, [1., 2., 0., -4., -5]))\n assert_(z[0] is masked)\n assert_(z[1] is not masked)\n assert_(z[2] is masked)\n assert_(eq(masked_where(greater(x, 2), x), masked_greater(x, 2)))\n assert_(eq(masked_where(greater_equal(x, 2), x),\n masked_greater_equal(x, 2)))\n assert_(eq(masked_where(less(x, 2), x), masked_less(x, 2)))\n assert_(eq(masked_where(less_equal(x, 2), x), masked_less_equal(x, 2)))\n assert_(eq(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2)))\n assert_(eq(masked_where(equal(x, 2), x), masked_equal(x, 2)))\n assert_(eq(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2)))\n assert_(eq(masked_inside(list(range(5)), 1, 3), [0, 199, 199, 199, 4]))\n assert_(eq(masked_outside(list(range(5)), 1, 3), [199, 1, 2, 3, 199]))\n assert_(eq(masked_inside(array(list(range(5)),\n mask=[1, 0, 0, 0, 0]), 1, 3).mask,\n [1, 1, 1, 1, 0]))\n assert_(eq(masked_outside(array(list(range(5)),\n mask=[0, 1, 0, 0, 0]), 1, 3).mask,\n [1, 1, 0, 0, 1]))\n assert_(eq(masked_equal(array(list(range(5)),\n mask=[1, 0, 0, 0, 0]), 2).mask,\n [1, 0, 1, 0, 0]))\n assert_(eq(masked_not_equal(array([2, 2, 1, 2, 1],\n mask=[1, 0, 0, 0, 0]), 2).mask,\n [1, 0, 1, 0, 1]))\n assert_(eq(masked_where([1, 1, 0, 0, 0], [1, 2, 3, 4, 5]),\n [99, 99, 3, 4, 5]))\n atest = ones((10, 10, 10), dtype=np.float32)\n btest = zeros(atest.shape, MaskType)\n ctest = masked_where(btest, atest)\n assert_(eq(atest, ctest))\n z = choose(c, (-x, x))\n assert_(eq(z, [1., 2., 0., -4., -5]))\n assert_(z[0] is masked)\n assert_(z[1] is not masked)\n assert_(z[2] is masked)\n x = arange(6)\n x[5] = masked\n y = arange(6) * 10\n y[2] = masked\n c = array([1, 1, 1, 0, 0, 0], mask=[1, 0, 0, 0, 0, 0])\n cm = c.filled(1)\n z = where(c, x, y)\n zm = where(cm, x, y)\n assert_(eq(z, zm))\n assert_(getmask(zm) is nomask)\n assert_(eq(zm, [0, 1, 2, 30, 40, 50]))\n z = where(c, masked, 1)\n assert_(eq(z, [99, 99, 99, 1, 1, 1]))\n z = where(c, 1, masked)\n assert_(eq(z, [99, 1, 1, 99, 99, 99]))\n\n def test_testMinMax2(self):\n # Test of minimum, maximum.\n assert_(eq(minimum([1, 2, 3], [4, 0, 9]), [1, 0, 3]))\n assert_(eq(maximum([1, 2, 3], [4, 0, 9]), [4, 2, 9]))\n x = arange(5)\n y = arange(5) - 2\n x[3] = masked\n y[0] = masked\n assert_(eq(minimum(x, y), where(less(x, y), x, y)))\n assert_(eq(maximum(x, y), where(greater(x, y), x, y)))\n assert_(minimum.reduce(x) == 0)\n assert_(maximum.reduce(x) == 4)\n\n def test_testTakeTransposeInnerOuter(self):\n # Test of take, transpose, inner, outer products\n x = arange(24)\n y = np.arange(24)\n x[5:6] = masked\n x = x.reshape(2, 3, 4)\n y = y.reshape(2, 3, 4)\n assert_(eq(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1))))\n assert_(eq(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1)))\n assert_(eq(np.inner(filled(x, 0), filled(y, 0)),\n inner(x, y)))\n assert_(eq(np.outer(filled(x, 0), filled(y, 0)),\n outer(x, y)))\n y = array(['abc', 1, 'def', 2, 3], object)\n y[2] = masked\n t = take(y, [0, 3, 4])\n assert_(t[0] == 'abc')\n assert_(t[1] == 2)\n assert_(t[2] == 3)\n\n def test_testInplace(self):\n # Test of inplace operations and rich comparisons\n y = arange(10)\n\n x = arange(10)\n xm = arange(10)\n xm[2] = masked\n x += 1\n assert_(eq(x, y + 1))\n xm += 1\n assert_(eq(x, y + 1))\n\n x = arange(10)\n xm = arange(10)\n xm[2] = masked\n x -= 1\n assert_(eq(x, y - 1))\n xm -= 1\n assert_(eq(xm, y - 1))\n\n x = arange(10) * 1.0\n xm = arange(10) * 1.0\n xm[2] = masked\n x *= 2.0\n assert_(eq(x, y * 2))\n xm *= 2.0\n assert_(eq(xm, y * 2))\n\n x = arange(10) * 2\n xm = arange(10)\n xm[2] = masked\n x //= 2\n assert_(eq(x, y))\n xm //= 2\n assert_(eq(x, y))\n\n x = arange(10) * 1.0\n xm = arange(10) * 1.0\n xm[2] = masked\n x /= 2.0\n assert_(eq(x, y / 2.0))\n xm /= arange(10)\n assert_(eq(xm, ones((10,))))\n\n x = arange(10).astype(np.float32)\n xm = arange(10)\n xm[2] = masked\n x += 1.\n assert_(eq(x, y + 1.))\n\n def test_testPickle(self):\n # Test of pickling\n x = arange(12)\n x[4:10:2] = masked\n x = x.reshape(4, 3)\n for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):\n s = pickle.dumps(x, protocol=proto)\n y = pickle.loads(s)\n assert_(eq(x, y))\n\n def test_testMasked(self):\n # Test of masked element\n xx = arange(6)\n xx[1] = masked\n assert_(str(masked) == '--')\n assert_(xx[1] is masked)\n assert_equal(filled(xx[1], 0), 0)\n\n def test_testAverage1(self):\n # Test of average.\n ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])\n assert_(eq(2.0, average(ott, axis=0)))\n assert_(eq(2.0, average(ott, weights=[1., 1., 2., 1.])))\n result, wts = average(ott, weights=[1., 1., 2., 1.], returned=True)\n assert_(eq(2.0, result))\n assert_(wts == 4.0)\n ott[:] = masked\n assert_(average(ott, axis=0) is masked)\n ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])\n ott = ott.reshape(2, 2)\n ott[:, 1] = masked\n assert_(eq(average(ott, axis=0), [2.0, 0.0]))\n assert_(average(ott, axis=1)[0] is masked)\n assert_(eq([2., 0.], average(ott, axis=0)))\n result, wts = average(ott, axis=0, returned=True)\n assert_(eq(wts, [1., 0.]))\n\n def test_testAverage2(self):\n # More tests of average.\n w1 = [0, 1, 1, 1, 1, 0]\n w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]]\n x = arange(6)\n assert_(allclose(average(x, axis=0), 2.5))\n assert_(allclose(average(x, axis=0, weights=w1), 2.5))\n y = array([arange(6), 2.0 * arange(6)])\n assert_(allclose(average(y, None),\n np.add.reduce(np.arange(6)) * 3. / 12.))\n assert_(allclose(average(y, axis=0), np.arange(6) * 3. / 2.))\n assert_(allclose(average(y, axis=1),\n [average(x, axis=0), average(x, axis=0) * 2.0]))\n assert_(allclose(average(y, None, weights=w2), 20. / 6.))\n assert_(allclose(average(y, axis=0, weights=w2),\n [0., 1., 2., 3., 4., 10.]))\n assert_(allclose(average(y, axis=1),\n [average(x, axis=0), average(x, axis=0) * 2.0]))\n m1 = zeros(6)\n m2 = [0, 0, 1, 1, 0, 0]\n m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]]\n m4 = ones(6)\n m5 = [0, 1, 1, 1, 1, 1]\n assert_(allclose(average(masked_array(x, m1), axis=0), 2.5))\n assert_(allclose(average(masked_array(x, m2), axis=0), 2.5))\n assert_(average(masked_array(x, m4), axis=0) is masked)\n assert_equal(average(masked_array(x, m5), axis=0), 0.0)\n assert_equal(count(average(masked_array(x, m4), axis=0)), 0)\n z = masked_array(y, m3)\n assert_(allclose(average(z, None), 20. / 6.))\n assert_(allclose(average(z, axis=0),\n [0., 1., 99., 99., 4.0, 7.5]))\n assert_(allclose(average(z, axis=1), [2.5, 5.0]))\n assert_(allclose(average(z, axis=0, weights=w2),\n [0., 1., 99., 99., 4.0, 10.0]))\n\n a = arange(6)\n b = arange(6) * 3\n r1, w1 = average([[a, b], [b, a]], axis=1, returned=True)\n assert_equal(shape(r1), shape(w1))\n assert_equal(r1.shape, w1.shape)\n r2, w2 = average(ones((2, 2, 3)), axis=0, weights=[3, 1], returned=True)\n assert_equal(shape(w2), shape(r2))\n r2, w2 = average(ones((2, 2, 3)), returned=True)\n assert_equal(shape(w2), shape(r2))\n r2, w2 = average(ones((2, 2, 3)), weights=ones((2, 2, 3)), returned=True)\n assert_(shape(w2) == shape(r2))\n a2d = array([[1, 2], [0, 4]], float)\n a2dm = masked_array(a2d, [[0, 0], [1, 0]])\n a2da = average(a2d, axis=0)\n assert_(eq(a2da, [0.5, 3.0]))\n a2dma = average(a2dm, axis=0)\n assert_(eq(a2dma, [1.0, 3.0]))\n a2dma = average(a2dm, axis=None)\n assert_(eq(a2dma, 7. / 3.))\n a2dma = average(a2dm, axis=1)\n assert_(eq(a2dma, [1.5, 4.0]))\n\n def test_testToPython(self):\n assert_equal(1, int(array(1)))\n assert_equal(1.0, float(array(1)))\n assert_equal(1, int(array([[[1]]])))\n assert_equal(1.0, float(array([[1]])))\n assert_raises(TypeError, float, array([1, 1]))\n assert_raises(ValueError, bool, array([0, 1]))\n assert_raises(ValueError, bool, array([0, 0], mask=[0, 1]))\n\n def test_testScalarArithmetic(self):\n xm = array(0, mask=1)\n # TODO FIXME: Find out what the following raises a warning in r8247\n with np.errstate(divide='ignore'):\n assert_((1 / array(0)).mask)\n assert_((1 + xm).mask)\n assert_((-xm).mask)\n assert_((-xm).mask)\n assert_(maximum(xm, xm).mask)\n assert_(minimum(xm, xm).mask)\n assert_(xm.filled().dtype is xm._data.dtype)\n x = array(0, mask=0)\n assert_(x.filled() == x._data)\n assert_equal(str(xm), str(masked_print_option))\n\n def test_testArrayMethods(self):\n a = array([1, 3, 2])\n assert_(eq(a.any(), a._data.any()))\n assert_(eq(a.all(), a._data.all()))\n assert_(eq(a.argmax(), a._data.argmax()))\n assert_(eq(a.argmin(), a._data.argmin()))\n assert_(eq(a.choose(0, 1, 2, 3, 4),\n a._data.choose(0, 1, 2, 3, 4)))\n assert_(eq(a.compress([1, 0, 1]), a._data.compress([1, 0, 1])))\n assert_(eq(a.conj(), a._data.conj()))\n assert_(eq(a.conjugate(), a._data.conjugate()))\n m = array([[1, 2], [3, 4]])\n assert_(eq(m.diagonal(), m._data.diagonal()))\n assert_(eq(a.sum(), a._data.sum()))\n assert_(eq(a.take([1, 2]), a._data.take([1, 2])))\n assert_(eq(m.transpose(), m._data.transpose()))\n\n def test_testArrayAttributes(self):\n a = array([1, 3, 2])\n assert_equal(a.ndim, 1)\n\n def test_testAPI(self):\n assert_(not [m for m in dir(np.ndarray)\n if m not in dir(MaskedArray) and\n not m.startswith('_')])\n\n def test_testSingleElementSubscript(self):\n a = array([1, 3, 2])\n b = array([1, 3, 2], mask=[1, 0, 1])\n assert_equal(a[0].shape, ())\n assert_equal(b[0].shape, ())\n assert_equal(b[1].shape, ())\n\n def test_assignment_by_condition(self):\n # Test for gh-18951\n a = array([1, 2, 3, 4], mask=[1, 0, 1, 0])\n c = a >= 3\n a[c] = 5\n assert_(a[2] is masked)\n\n def test_assignment_by_condition_2(self):\n # gh-19721\n a = masked_array([0, 1], mask=[False, False])\n b = masked_array([0, 1], mask=[True, True])\n mask = a < 1\n b[mask] = a[mask]\n expected_mask = [False, True]\n assert_equal(b.mask, expected_mask)\n\n\nclass TestUfuncs:\n def setup_method(self):\n self.d = (array([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6),\n array([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6),)\n\n def test_testUfuncRegression(self):\n f_invalid_ignore = [\n 'sqrt', 'arctanh', 'arcsin', 'arccos',\n 'arccosh', 'arctanh', 'log', 'log10', 'divide',\n 'true_divide', 'floor_divide', 'remainder', 'fmod']\n for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate',\n 'sin', 'cos', 'tan',\n 'arcsin', 'arccos', 'arctan',\n 'sinh', 'cosh', 'tanh',\n 'arcsinh',\n 'arccosh',\n 'arctanh',\n 'absolute', 'fabs', 'negative',\n 'floor', 'ceil',\n 'logical_not',\n 'add', 'subtract', 'multiply',\n 'divide', 'true_divide', 'floor_divide',\n 'remainder', 'fmod', 'hypot', 'arctan2',\n 'equal', 'not_equal', 'less_equal', 'greater_equal',\n 'less', 'greater',\n 'logical_and', 'logical_or', 'logical_xor']:\n try:\n uf = getattr(umath, f)\n except AttributeError:\n uf = getattr(fromnumeric, f)\n mf = getattr(np.ma, f)\n args = self.d[:uf.nin]\n with np.errstate():\n if f in f_invalid_ignore:\n np.seterr(invalid='ignore')\n if f in ['arctanh', 'log', 'log10']:\n np.seterr(divide='ignore')\n ur = uf(*args)\n mr = mf(*args)\n assert_(eq(ur.filled(0), mr.filled(0), f))\n assert_(eqmask(ur.mask, mr.mask))\n\n def test_reduce(self):\n a = self.d[0]\n assert_(not alltrue(a, axis=0))\n assert_(sometrue(a, axis=0))\n assert_equal(sum(a[:3], axis=0), 0)\n assert_equal(product(a, axis=0), 0)\n\n def test_minmax(self):\n a = arange(1, 13).reshape(3, 4)\n amask = masked_where(a < 5, a)\n assert_equal(amask.max(), a.max())\n assert_equal(amask.min(), 5)\n assert_((amask.max(0) == a.max(0)).all())\n assert_((amask.min(0) == [5, 6, 7, 8]).all())\n assert_(amask.max(1)[0].mask)\n assert_(amask.min(1)[0].mask)\n\n def test_nonzero(self):\n for t in "?bhilqpBHILQPfdgFDGO":\n x = array([1, 0, 2, 0], mask=[0, 0, 1, 1])\n assert_(eq(nonzero(x), [0]))\n\n\nclass TestArrayMethods:\n\n def setup_method(self):\n x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,\n 8.43, 7.78, 9.865, 5.878, 8.979, 4.732,\n 3.012, 6.022, 5.095, 3.116, 5.238, 3.957,\n 6.04, 9.63, 7.712, 3.382, 4.489, 6.479,\n 7.189, 9.645, 5.395, 4.961, 9.894, 2.893,\n 7.357, 9.828, 6.272, 3.758, 6.693, 0.993])\n X = x.reshape(6, 6)\n XX = x.reshape(3, 2, 2, 3)\n\n m = np.array([0, 1, 0, 1, 0, 0,\n 1, 0, 1, 1, 0, 1,\n 0, 0, 0, 1, 0, 1,\n 0, 0, 0, 1, 1, 1,\n 1, 0, 0, 1, 0, 0,\n 0, 0, 1, 0, 1, 0])\n mx = array(data=x, mask=m)\n mX = array(data=X, mask=m.reshape(X.shape))\n mXX = array(data=XX, mask=m.reshape(XX.shape))\n\n self.d = (x, X, XX, m, mx, mX, mXX)\n\n def test_trace(self):\n (x, X, XX, m, mx, mX, mXX,) = self.d\n mXdiag = mX.diagonal()\n assert_equal(mX.trace(), mX.diagonal().compressed().sum())\n assert_(eq(mX.trace(),\n X.trace() - sum(mXdiag.mask * X.diagonal(),\n axis=0)))\n\n def test_clip(self):\n (x, X, XX, m, mx, mX, mXX,) = self.d\n clipped = mx.clip(2, 8)\n assert_(eq(clipped.mask, mx.mask))\n assert_(eq(clipped._data, x.clip(2, 8)))\n assert_(eq(clipped._data, mx._data.clip(2, 8)))\n\n def test_ptp(self):\n (x, X, XX, m, mx, mX, mXX,) = self.d\n (n, m) = X.shape\n # print(type(mx), mx.compressed())\n # raise Exception()\n assert_equal(mx.ptp(), np.ptp(mx.compressed()))\n rows = np.zeros(n, np.float64)\n cols = np.zeros(m, np.float64)\n for k in range(m):\n cols[k] = np.ptp(mX[:, k].compressed())\n for k in range(n):\n rows[k] = np.ptp(mX[k].compressed())\n assert_(eq(mX.ptp(0), cols))\n assert_(eq(mX.ptp(1), rows))\n\n def test_swapaxes(self):\n (x, X, XX, m, mx, mX, mXX,) = self.d\n mXswapped = mX.swapaxes(0, 1)\n assert_(eq(mXswapped[-1], mX[:, -1]))\n mXXswapped = mXX.swapaxes(0, 2)\n assert_equal(mXXswapped.shape, (2, 2, 3, 3))\n\n def test_cumprod(self):\n (x, X, XX, m, mx, mX, mXX,) = self.d\n mXcp = mX.cumprod(0)\n assert_(eq(mXcp._data, mX.filled(1).cumprod(0)))\n mXcp = mX.cumprod(1)\n assert_(eq(mXcp._data, mX.filled(1).cumprod(1)))\n\n def test_cumsum(self):\n (x, X, XX, m, mx, mX, mXX,) = self.d\n mXcp = mX.cumsum(0)\n assert_(eq(mXcp._data, mX.filled(0).cumsum(0)))\n mXcp = mX.cumsum(1)\n assert_(eq(mXcp._data, mX.filled(0).cumsum(1)))\n\n def test_varstd(self):\n (x, X, XX, m, mx, mX, mXX,) = self.d\n assert_(eq(mX.var(axis=None), mX.compressed().var()))\n assert_(eq(mX.std(axis=None), mX.compressed().std()))\n assert_(eq(mXX.var(axis=3).shape, XX.var(axis=3).shape))\n assert_(eq(mX.var().shape, X.var().shape))\n (mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1))\n for k in range(6):\n assert_(eq(mXvar1[k], mX[k].compressed().var()))\n assert_(eq(mXvar0[k], mX[:, k].compressed().var()))\n assert_(eq(np.sqrt(mXvar0[k]),\n mX[:, k].compressed().std()))\n\n\ndef eqmask(m1, m2):\n if m1 is nomask:\n return m2 is nomask\n if m2 is nomask:\n return m1 is nomask\n return (m1 == m2).all()\n | .venv\Lib\site-packages\numpy\ma\tests\test_old_ma.py | test_old_ma.py | Python | 33,960 | 0.95 | 0.072187 | 0.034602 | python-kit | 653 | 2024-10-26T22:52:54.924185 | GPL-3.0 | true | c5ad3013be4adc4b853a23fd0348ebdc |
import numpy as np\nfrom numpy.testing import (\n assert_,\n assert_allclose,\n assert_array_equal,\n suppress_warnings,\n)\n\n\nclass TestRegression:\n def test_masked_array_create(self):\n # Ticket #17\n x = np.ma.masked_array([0, 1, 2, 3, 0, 4, 5, 6],\n mask=[0, 0, 0, 1, 1, 1, 0, 0])\n assert_array_equal(np.ma.nonzero(x), [[1, 2, 6, 7]])\n\n def test_masked_array(self):\n # Ticket #61\n np.ma.array(1, mask=[1])\n\n def test_mem_masked_where(self):\n # Ticket #62\n from numpy.ma import MaskType, masked_where\n a = np.zeros((1, 1))\n b = np.zeros(a.shape, MaskType)\n c = masked_where(b, a)\n a - c\n\n def test_masked_array_multiply(self):\n # Ticket #254\n a = np.ma.zeros((4, 1))\n a[2, 0] = np.ma.masked\n b = np.zeros((4, 2))\n a * b\n b * a\n\n def test_masked_array_repeat(self):\n # Ticket #271\n np.ma.array([1], mask=False).repeat(10)\n\n def test_masked_array_repr_unicode(self):\n # Ticket #1256\n repr(np.ma.array("Unicode"))\n\n def test_atleast_2d(self):\n # Ticket #1559\n a = np.ma.masked_array([0.0, 1.2, 3.5], mask=[False, True, False])\n b = np.atleast_2d(a)\n assert_(a.mask.ndim == 1)\n assert_(b.mask.ndim == 2)\n\n def test_set_fill_value_unicode_py3(self):\n # Ticket #2733\n a = np.ma.masked_array(['a', 'b', 'c'], mask=[1, 0, 0])\n a.fill_value = 'X'\n assert_(a.fill_value == 'X')\n\n def test_var_sets_maskedarray_scalar(self):\n # Issue gh-2757\n a = np.ma.array(np.arange(5), mask=True)\n mout = np.ma.array(-1, dtype=float)\n a.var(out=mout)\n assert_(mout._data == 0)\n\n def test_ddof_corrcoef(self):\n # See gh-3336\n x = np.ma.masked_equal([1, 2, 3, 4, 5], 4)\n y = np.array([2, 2.5, 3.1, 3, 5])\n # this test can be removed after deprecation.\n with suppress_warnings() as sup:\n sup.filter(DeprecationWarning, "bias and ddof have no effect")\n r0 = np.ma.corrcoef(x, y, ddof=0)\n r1 = np.ma.corrcoef(x, y, ddof=1)\n # ddof should not have an effect (it gets cancelled out)\n assert_allclose(r0.data, r1.data)\n\n def test_mask_not_backmangled(self):\n # See gh-10314. Test case taken from gh-3140.\n a = np.ma.MaskedArray([1., 2.], mask=[False, False])\n assert_(a.mask.shape == (2,))\n b = np.tile(a, (2, 1))\n # Check that the above no longer changes a.shape to (1, 2)\n assert_(a.mask.shape == (2,))\n assert_(b.shape == (2, 2))\n assert_(b.mask.shape == (2, 2))\n\n def test_empty_list_on_structured(self):\n # See gh-12464. Indexing with empty list should give empty result.\n ma = np.ma.MaskedArray([(1, 1.), (2, 2.), (3, 3.)], dtype='i4,f4')\n assert_array_equal(ma[[]], ma[:0])\n\n def test_masked_array_tobytes_fortran(self):\n ma = np.ma.arange(4).reshape((2, 2))\n assert_array_equal(ma.tobytes(order='F'), ma.T.tobytes())\n\n def test_structured_array(self):\n # see gh-22041\n np.ma.array((1, (b"", b"")),\n dtype=[("x", np.int_),\n ("y", [("i", np.void), ("j", np.void)])])\n | .venv\Lib\site-packages\numpy\ma\tests\test_regression.py | test_regression.py | Python | 3,403 | 0.95 | 0.15 | 0.188235 | awesome-app | 678 | 2024-12-09T22:33:23.788541 | MIT | true | 2d5bb9984db58ab8eb9a5314e1cd7f5f |
"""Tests suite for MaskedArray & subclassing.\n\n:author: Pierre Gerard-Marchant\n:contact: pierregm_at_uga_dot_edu\n\n"""\nimport numpy as np\nfrom numpy.lib.mixins import NDArrayOperatorsMixin\nfrom numpy.ma.core import (\n MaskedArray,\n add,\n arange,\n array,\n asanyarray,\n asarray,\n divide,\n hypot,\n log,\n masked,\n masked_array,\n nomask,\n)\nfrom numpy.ma.testutils import assert_equal\nfrom numpy.testing import assert_, assert_raises\n\n# from numpy.ma.core import (\n\ndef assert_startswith(a, b):\n # produces a better error message than assert_(a.startswith(b))\n assert_equal(a[:len(b)], b)\n\nclass SubArray(np.ndarray):\n # Defines a generic np.ndarray subclass, that stores some metadata\n # in the dictionary `info`.\n def __new__(cls, arr, info={}):\n x = np.asanyarray(arr).view(cls)\n x.info = info.copy()\n return x\n\n def __array_finalize__(self, obj):\n super().__array_finalize__(obj)\n self.info = getattr(obj, 'info', {}).copy()\n\n def __add__(self, other):\n result = super().__add__(other)\n result.info['added'] = result.info.get('added', 0) + 1\n return result\n\n def __iadd__(self, other):\n result = super().__iadd__(other)\n result.info['iadded'] = result.info.get('iadded', 0) + 1\n return result\n\n\nsubarray = SubArray\n\n\nclass SubMaskedArray(MaskedArray):\n """Pure subclass of MaskedArray, keeping some info on subclass."""\n def __new__(cls, info=None, **kwargs):\n obj = super().__new__(cls, **kwargs)\n obj._optinfo['info'] = info\n return obj\n\n\nclass MSubArray(SubArray, MaskedArray):\n\n def __new__(cls, data, info={}, mask=nomask):\n subarr = SubArray(data, info)\n _data = MaskedArray.__new__(cls, data=subarr, mask=mask)\n _data.info = subarr.info\n return _data\n\n @property\n def _series(self):\n _view = self.view(MaskedArray)\n _view._sharedmask = False\n return _view\n\n\nmsubarray = MSubArray\n\n\n# Also a subclass that overrides __str__, __repr__ and __setitem__, disallowing\n# setting to non-class values (and thus np.ma.core.masked_print_option)\n# and overrides __array_wrap__, updating the info dict, to check that this\n# doesn't get destroyed by MaskedArray._update_from. But this one also needs\n# its own iterator...\nclass CSAIterator:\n """\n Flat iterator object that uses its own setter/getter\n (works around ndarray.flat not propagating subclass setters/getters\n see https://github.com/numpy/numpy/issues/4564)\n roughly following MaskedIterator\n """\n def __init__(self, a):\n self._original = a\n self._dataiter = a.view(np.ndarray).flat\n\n def __iter__(self):\n return self\n\n def __getitem__(self, indx):\n out = self._dataiter.__getitem__(indx)\n if not isinstance(out, np.ndarray):\n out = out.__array__()\n out = out.view(type(self._original))\n return out\n\n def __setitem__(self, index, value):\n self._dataiter[index] = self._original._validate_input(value)\n\n def __next__(self):\n return next(self._dataiter).__array__().view(type(self._original))\n\n\nclass ComplicatedSubArray(SubArray):\n\n def __str__(self):\n return f'myprefix {self.view(SubArray)} mypostfix'\n\n def __repr__(self):\n # Return a repr that does not start with 'name('\n return f'<{self.__class__.__name__} {self}>'\n\n def _validate_input(self, value):\n if not isinstance(value, ComplicatedSubArray):\n raise ValueError("Can only set to MySubArray values")\n return value\n\n def __setitem__(self, item, value):\n # validation ensures direct assignment with ndarray or\n # masked_print_option will fail\n super().__setitem__(item, self._validate_input(value))\n\n def __getitem__(self, item):\n # ensure getter returns our own class also for scalars\n value = super().__getitem__(item)\n if not isinstance(value, np.ndarray): # scalar\n value = value.__array__().view(ComplicatedSubArray)\n return value\n\n @property\n def flat(self):\n return CSAIterator(self)\n\n @flat.setter\n def flat(self, value):\n y = self.ravel()\n y[:] = value\n\n def __array_wrap__(self, obj, context=None, return_scalar=False):\n obj = super().__array_wrap__(obj, context, return_scalar)\n if context is not None and context[0] is np.multiply:\n obj.info['multiplied'] = obj.info.get('multiplied', 0) + 1\n\n return obj\n\n\nclass WrappedArray(NDArrayOperatorsMixin):\n """\n Wrapping a MaskedArray rather than subclassing to test that\n ufunc deferrals are commutative.\n See: https://github.com/numpy/numpy/issues/15200)\n """\n __slots__ = ('_array', 'attrs')\n __array_priority__ = 20\n\n def __init__(self, array, **attrs):\n self._array = array\n self.attrs = attrs\n\n def __repr__(self):\n return f"{self.__class__.__name__}(\n{self._array}\n{self.attrs}\n)"\n\n def __array__(self, dtype=None, copy=None):\n return np.asarray(self._array)\n\n def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):\n if method == '__call__':\n inputs = [arg._array if isinstance(arg, self.__class__) else arg\n for arg in inputs]\n return self.__class__(ufunc(*inputs, **kwargs), **self.attrs)\n else:\n return NotImplemented\n\n\nclass TestSubclassing:\n # Test suite for masked subclasses of ndarray.\n\n def setup_method(self):\n x = np.arange(5, dtype='float')\n mx = msubarray(x, mask=[0, 1, 0, 0, 0])\n self.data = (x, mx)\n\n def test_data_subclassing(self):\n # Tests whether the subclass is kept.\n x = np.arange(5)\n m = [0, 0, 1, 0, 0]\n xsub = SubArray(x)\n xmsub = masked_array(xsub, mask=m)\n assert_(isinstance(xmsub, MaskedArray))\n assert_equal(xmsub._data, xsub)\n assert_(isinstance(xmsub._data, SubArray))\n\n def test_maskedarray_subclassing(self):\n # Tests subclassing MaskedArray\n (x, mx) = self.data\n assert_(isinstance(mx._data, subarray))\n\n def test_masked_unary_operations(self):\n # Tests masked_unary_operation\n (x, mx) = self.data\n with np.errstate(divide='ignore'):\n assert_(isinstance(log(mx), msubarray))\n assert_equal(log(x), np.log(x))\n\n def test_masked_binary_operations(self):\n # Tests masked_binary_operation\n (x, mx) = self.data\n # Result should be a msubarray\n assert_(isinstance(add(mx, mx), msubarray))\n assert_(isinstance(add(mx, x), msubarray))\n # Result should work\n assert_equal(add(mx, x), mx + x)\n assert_(isinstance(add(mx, mx)._data, subarray))\n assert_(isinstance(add.outer(mx, mx), msubarray))\n assert_(isinstance(hypot(mx, mx), msubarray))\n assert_(isinstance(hypot(mx, x), msubarray))\n\n def test_masked_binary_operations2(self):\n # Tests domained_masked_binary_operation\n (x, mx) = self.data\n xmx = masked_array(mx.data.__array__(), mask=mx.mask)\n assert_(isinstance(divide(mx, mx), msubarray))\n assert_(isinstance(divide(mx, x), msubarray))\n assert_equal(divide(mx, mx), divide(xmx, xmx))\n\n def test_attributepropagation(self):\n x = array(arange(5), mask=[0] + [1] * 4)\n my = masked_array(subarray(x))\n ym = msubarray(x)\n #\n z = (my + 1)\n assert_(isinstance(z, MaskedArray))\n assert_(not isinstance(z, MSubArray))\n assert_(isinstance(z._data, SubArray))\n assert_equal(z._data.info, {})\n #\n z = (ym + 1)\n assert_(isinstance(z, MaskedArray))\n assert_(isinstance(z, MSubArray))\n assert_(isinstance(z._data, SubArray))\n assert_(z._data.info['added'] > 0)\n # Test that inplace methods from data get used (gh-4617)\n ym += 1\n assert_(isinstance(ym, MaskedArray))\n assert_(isinstance(ym, MSubArray))\n assert_(isinstance(ym._data, SubArray))\n assert_(ym._data.info['iadded'] > 0)\n #\n ym._set_mask([1, 0, 0, 0, 1])\n assert_equal(ym._mask, [1, 0, 0, 0, 1])\n ym._series._set_mask([0, 0, 0, 0, 1])\n assert_equal(ym._mask, [0, 0, 0, 0, 1])\n #\n xsub = subarray(x, info={'name': 'x'})\n mxsub = masked_array(xsub)\n assert_(hasattr(mxsub, 'info'))\n assert_equal(mxsub.info, xsub.info)\n\n def test_subclasspreservation(self):\n # Checks that masked_array(...,subok=True) preserves the class.\n x = np.arange(5)\n m = [0, 0, 1, 0, 0]\n xinfo = list(zip(x, m))\n xsub = MSubArray(x, mask=m, info={'xsub': xinfo})\n #\n mxsub = masked_array(xsub, subok=False)\n assert_(not isinstance(mxsub, MSubArray))\n assert_(isinstance(mxsub, MaskedArray))\n assert_equal(mxsub._mask, m)\n #\n mxsub = asarray(xsub)\n assert_(not isinstance(mxsub, MSubArray))\n assert_(isinstance(mxsub, MaskedArray))\n assert_equal(mxsub._mask, m)\n #\n mxsub = masked_array(xsub, subok=True)\n assert_(isinstance(mxsub, MSubArray))\n assert_equal(mxsub.info, xsub.info)\n assert_equal(mxsub._mask, xsub._mask)\n #\n mxsub = asanyarray(xsub)\n assert_(isinstance(mxsub, MSubArray))\n assert_equal(mxsub.info, xsub.info)\n assert_equal(mxsub._mask, m)\n\n def test_subclass_items(self):\n """test that getter and setter go via baseclass"""\n x = np.arange(5)\n xcsub = ComplicatedSubArray(x)\n mxcsub = masked_array(xcsub, mask=[True, False, True, False, False])\n # getter should return a ComplicatedSubArray, even for single item\n # first check we wrote ComplicatedSubArray correctly\n assert_(isinstance(xcsub[1], ComplicatedSubArray))\n assert_(isinstance(xcsub[1, ...], ComplicatedSubArray))\n assert_(isinstance(xcsub[1:4], ComplicatedSubArray))\n\n # now that it propagates inside the MaskedArray\n assert_(isinstance(mxcsub[1], ComplicatedSubArray))\n assert_(isinstance(mxcsub[1, ...].data, ComplicatedSubArray))\n assert_(mxcsub[0] is masked)\n assert_(isinstance(mxcsub[0, ...].data, ComplicatedSubArray))\n assert_(isinstance(mxcsub[1:4].data, ComplicatedSubArray))\n\n # also for flattened version (which goes via MaskedIterator)\n assert_(isinstance(mxcsub.flat[1].data, ComplicatedSubArray))\n assert_(mxcsub.flat[0] is masked)\n assert_(isinstance(mxcsub.flat[1:4].base, ComplicatedSubArray))\n\n # setter should only work with ComplicatedSubArray input\n # first check we wrote ComplicatedSubArray correctly\n assert_raises(ValueError, xcsub.__setitem__, 1, x[4])\n # now that it propagates inside the MaskedArray\n assert_raises(ValueError, mxcsub.__setitem__, 1, x[4])\n assert_raises(ValueError, mxcsub.__setitem__, slice(1, 4), x[1:4])\n mxcsub[1] = xcsub[4]\n mxcsub[1:4] = xcsub[1:4]\n # also for flattened version (which goes via MaskedIterator)\n assert_raises(ValueError, mxcsub.flat.__setitem__, 1, x[4])\n assert_raises(ValueError, mxcsub.flat.__setitem__, slice(1, 4), x[1:4])\n mxcsub.flat[1] = xcsub[4]\n mxcsub.flat[1:4] = xcsub[1:4]\n\n def test_subclass_nomask_items(self):\n x = np.arange(5)\n xcsub = ComplicatedSubArray(x)\n mxcsub_nomask = masked_array(xcsub)\n\n assert_(isinstance(mxcsub_nomask[1, ...].data, ComplicatedSubArray))\n assert_(isinstance(mxcsub_nomask[0, ...].data, ComplicatedSubArray))\n\n assert_(isinstance(mxcsub_nomask[1], ComplicatedSubArray))\n assert_(isinstance(mxcsub_nomask[0], ComplicatedSubArray))\n\n def test_subclass_repr(self):\n """test that repr uses the name of the subclass\n and 'array' for np.ndarray"""\n x = np.arange(5)\n mx = masked_array(x, mask=[True, False, True, False, False])\n assert_startswith(repr(mx), 'masked_array')\n xsub = SubArray(x)\n mxsub = masked_array(xsub, mask=[True, False, True, False, False])\n assert_startswith(repr(mxsub),\n f'masked_{SubArray.__name__}(data=[--, 1, --, 3, 4]')\n\n def test_subclass_str(self):\n """test str with subclass that has overridden str, setitem"""\n # first without override\n x = np.arange(5)\n xsub = SubArray(x)\n mxsub = masked_array(xsub, mask=[True, False, True, False, False])\n assert_equal(str(mxsub), '[-- 1 -- 3 4]')\n\n xcsub = ComplicatedSubArray(x)\n assert_raises(ValueError, xcsub.__setitem__, 0,\n np.ma.core.masked_print_option)\n mxcsub = masked_array(xcsub, mask=[True, False, True, False, False])\n assert_equal(str(mxcsub), 'myprefix [-- 1 -- 3 4] mypostfix')\n\n def test_pure_subclass_info_preservation(self):\n # Test that ufuncs and methods conserve extra information consistently;\n # see gh-7122.\n arr1 = SubMaskedArray('test', data=[1, 2, 3, 4, 5, 6])\n arr2 = SubMaskedArray(data=[0, 1, 2, 3, 4, 5])\n diff1 = np.subtract(arr1, arr2)\n assert_('info' in diff1._optinfo)\n assert_(diff1._optinfo['info'] == 'test')\n diff2 = arr1 - arr2\n assert_('info' in diff2._optinfo)\n assert_(diff2._optinfo['info'] == 'test')\n\n\nclass ArrayNoInheritance:\n """Quantity-like class that does not inherit from ndarray"""\n def __init__(self, data, units):\n self.magnitude = data\n self.units = units\n\n def __getattr__(self, attr):\n return getattr(self.magnitude, attr)\n\n\ndef test_array_no_inheritance():\n data_masked = np.ma.array([1, 2, 3], mask=[True, False, True])\n data_masked_units = ArrayNoInheritance(data_masked, 'meters')\n\n # Get the masked representation of the Quantity-like class\n new_array = np.ma.array(data_masked_units)\n assert_equal(data_masked.data, new_array.data)\n assert_equal(data_masked.mask, new_array.mask)\n # Test sharing the mask\n data_masked.mask = [True, False, False]\n assert_equal(data_masked.mask, new_array.mask)\n assert_(new_array.sharedmask)\n\n # Get the masked representation of the Quantity-like class\n new_array = np.ma.array(data_masked_units, copy=True)\n assert_equal(data_masked.data, new_array.data)\n assert_equal(data_masked.mask, new_array.mask)\n # Test that the mask is not shared when copy=True\n data_masked.mask = [True, False, True]\n assert_equal([True, False, False], new_array.mask)\n assert_(not new_array.sharedmask)\n\n # Get the masked representation of the Quantity-like class\n new_array = np.ma.array(data_masked_units, keep_mask=False)\n assert_equal(data_masked.data, new_array.data)\n # The change did not affect the original mask\n assert_equal(data_masked.mask, [True, False, True])\n # Test that the mask is False and not shared when keep_mask=False\n assert_(not new_array.mask)\n assert_(not new_array.sharedmask)\n\n\nclass TestClassWrapping:\n # Test suite for classes that wrap MaskedArrays\n\n def setup_method(self):\n m = np.ma.masked_array([1, 3, 5], mask=[False, True, False])\n wm = WrappedArray(m)\n self.data = (m, wm)\n\n def test_masked_unary_operations(self):\n # Tests masked_unary_operation\n (m, wm) = self.data\n with np.errstate(divide='ignore'):\n assert_(isinstance(np.log(wm), WrappedArray))\n\n def test_masked_binary_operations(self):\n # Tests masked_binary_operation\n (m, wm) = self.data\n # Result should be a WrappedArray\n assert_(isinstance(np.add(wm, wm), WrappedArray))\n assert_(isinstance(np.add(m, wm), WrappedArray))\n assert_(isinstance(np.add(wm, m), WrappedArray))\n # add and '+' should call the same ufunc\n assert_equal(np.add(m, wm), m + wm)\n assert_(isinstance(np.hypot(m, wm), WrappedArray))\n assert_(isinstance(np.hypot(wm, m), WrappedArray))\n # Test domained binary operations\n assert_(isinstance(np.divide(wm, m), WrappedArray))\n assert_(isinstance(np.divide(m, wm), WrappedArray))\n assert_equal(np.divide(wm, m) * m, np.divide(m, m) * wm)\n # Test broadcasting\n m2 = np.stack([m, m])\n assert_(isinstance(np.divide(wm, m2), WrappedArray))\n assert_(isinstance(np.divide(m2, wm), WrappedArray))\n assert_equal(np.divide(m2, wm), np.divide(wm, m2))\n\n def test_mixins_have_slots(self):\n mixin = NDArrayOperatorsMixin()\n # Should raise an error\n assert_raises(AttributeError, mixin.__setattr__, "not_a_real_attr", 1)\n\n m = np.ma.masked_array([1, 3, 5], mask=[False, True, False])\n wm = WrappedArray(m)\n assert_raises(AttributeError, wm.__setattr__, "not_an_attr", 2)\n | .venv\Lib\site-packages\numpy\ma\tests\test_subclassing.py | test_subclassing.py | Python | 17,405 | 0.95 | 0.162047 | 0.145408 | awesome-app | 140 | 2023-08-22T23:58:53.244064 | BSD-3-Clause | true | 1e7a38b6cb7e3e5e4e4d7c173eee786b |
\n\n | .venv\Lib\site-packages\numpy\ma\tests\__pycache__\test_arrayobject.cpython-313.pyc | test_arrayobject.cpython-313.pyc | Other | 2,221 | 0.8 | 0 | 0.064516 | vue-tools | 407 | 2024-04-14T11:06:38.012140 | MIT | true | 16ca1bb643f5baa7b0096ef1006827a3 |
\n\n | .venv\Lib\site-packages\numpy\ma\tests\__pycache__\test_deprecations.cpython-313.pyc | test_deprecations.cpython-313.pyc | Other | 4,863 | 0.95 | 0 | 0 | awesome-app | 149 | 2025-06-13T01:51:49.806603 | BSD-3-Clause | true | c60db4ec686f95b310ca12e7df730e59 |
\n\n | .venv\Lib\site-packages\numpy\ma\tests\__pycache__\test_mrecords.cpython-313.pyc | test_mrecords.cpython-313.pyc | Other | 30,424 | 0.8 | 0.004348 | 0 | awesome-app | 413 | 2024-03-13T06:46:29.090205 | Apache-2.0 | true | 8bcd5b3d35701e723790f3247c2afa9e |
\n\n | .venv\Lib\site-packages\numpy\ma\tests\__pycache__\test_old_ma.cpython-313.pyc | test_old_ma.cpython-313.pyc | Other | 63,098 | 0.6 | 0 | 0.008219 | react-lib | 268 | 2023-08-01T09:46:19.941972 | BSD-3-Clause | true | 0633116fc239a05e4a970dd2fffb0152 |
\n\n | .venv\Lib\site-packages\numpy\ma\tests\__pycache__\test_regression.cpython-313.pyc | test_regression.cpython-313.pyc | Other | 7,464 | 0.8 | 0 | 0.022222 | python-kit | 385 | 2024-04-30T06:10:45.813577 | GPL-3.0 | true | 4c27ef4363743cc5f817357dce6a6e42 |
\n\n | .venv\Lib\site-packages\numpy\ma\tests\__pycache__\test_subclassing.cpython-313.pyc | test_subclassing.cpython-313.pyc | Other | 27,816 | 0.95 | 0.013393 | 0 | node-utils | 423 | 2024-05-19T06:29:40.072351 | GPL-3.0 | true | 906d3e82d0cc6eda7778de90897f5e72 |
\n\n | .venv\Lib\site-packages\numpy\ma\tests\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 189 | 0.7 | 0 | 0 | node-utils | 692 | 2024-06-21T03:43:36.550880 | GPL-3.0 | true | 33eefbbada4ad432b0a431bef5a7e423 |
\n\n | .venv\Lib\site-packages\numpy\ma\__pycache__\extras.cpython-313.pyc | extras.cpython-313.pyc | Other | 79,097 | 0.75 | 0.056647 | 0.003349 | python-kit | 312 | 2024-10-24T13:56:25.848761 | Apache-2.0 | false | 319139b3eb8ac0d8092f899b26fa9862 |
\n\n | .venv\Lib\site-packages\numpy\ma\__pycache__\mrecords.cpython-313.pyc | mrecords.cpython-313.pyc | Other | 33,862 | 0.95 | 0.043573 | 0.017722 | react-lib | 269 | 2024-03-07T23:38:31.280435 | GPL-3.0 | false | cc4d1c186e0ba814cc12575285c88f53 |
\n\n | .venv\Lib\site-packages\numpy\ma\__pycache__\testutils.cpython-313.pyc | testutils.cpython-313.pyc | Other | 12,544 | 0.95 | 0.04698 | 0 | vue-tools | 706 | 2025-03-22T00:07:43.410111 | MIT | true | f5ece112234e4fa07a314bf80e2534b2 |
\n\n | .venv\Lib\site-packages\numpy\ma\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 1,679 | 0.7 | 0.022222 | 0 | node-utils | 911 | 2024-07-10T21:22:11.145824 | BSD-3-Clause | false | f118b42f1fa0853bc429e9c56b283f62 |
__all__ = ['matrix', 'bmat', 'asmatrix']\n\nimport ast\nimport sys\nimport warnings\n\nimport numpy._core.numeric as N\nfrom numpy._core.numeric import concatenate, isscalar\nfrom numpy._utils import set_module\n\n# While not in __all__, matrix_power used to be defined here, so we import\n# it for backward compatibility.\nfrom numpy.linalg import matrix_power\n\n\ndef _convert_from_string(data):\n for char in '[]':\n data = data.replace(char, '')\n\n rows = data.split(';')\n newdata = []\n for count, row in enumerate(rows):\n trow = row.split(',')\n newrow = []\n for col in trow:\n temp = col.split()\n newrow.extend(map(ast.literal_eval, temp))\n if count == 0:\n Ncols = len(newrow)\n elif len(newrow) != Ncols:\n raise ValueError("Rows not the same size.")\n newdata.append(newrow)\n return newdata\n\n\n@set_module('numpy')\ndef asmatrix(data, dtype=None):\n """\n Interpret the input as a matrix.\n\n Unlike `matrix`, `asmatrix` does not make a copy if the input is already\n a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``.\n\n Parameters\n ----------\n data : array_like\n Input data.\n dtype : data-type\n Data-type of the output matrix.\n\n Returns\n -------\n mat : matrix\n `data` interpreted as a matrix.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([[1, 2], [3, 4]])\n\n >>> m = np.asmatrix(x)\n\n >>> x[0,0] = 5\n\n >>> m\n matrix([[5, 2],\n [3, 4]])\n\n """\n return matrix(data, dtype=dtype, copy=False)\n\n\n@set_module('numpy')\nclass matrix(N.ndarray):\n """\n matrix(data, dtype=None, copy=True)\n\n Returns a matrix from an array-like object, or from a string of data.\n\n A matrix is a specialized 2-D array that retains its 2-D nature\n through operations. It has certain special operators, such as ``*``\n (matrix multiplication) and ``**`` (matrix power).\n\n .. note:: It is no longer recommended to use this class, even for linear\n algebra. Instead use regular arrays. The class may be removed\n in the future.\n\n Parameters\n ----------\n data : array_like or string\n If `data` is a string, it is interpreted as a matrix with commas\n or spaces separating columns, and semicolons separating rows.\n dtype : data-type\n Data-type of the output matrix.\n copy : bool\n If `data` is already an `ndarray`, then this flag determines\n whether the data is copied (the default), or whether a view is\n constructed.\n\n See Also\n --------\n array\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.matrix('1 2; 3 4')\n >>> a\n matrix([[1, 2],\n [3, 4]])\n\n >>> np.matrix([[1, 2], [3, 4]])\n matrix([[1, 2],\n [3, 4]])\n\n """\n __array_priority__ = 10.0\n\n def __new__(subtype, data, dtype=None, copy=True):\n warnings.warn('the matrix subclass is not the recommended way to '\n 'represent matrices or deal with linear algebra (see '\n 'https://docs.scipy.org/doc/numpy/user/'\n 'numpy-for-matlab-users.html). '\n 'Please adjust your code to use regular ndarray.',\n PendingDeprecationWarning, stacklevel=2)\n if isinstance(data, matrix):\n dtype2 = data.dtype\n if (dtype is None):\n dtype = dtype2\n if (dtype2 == dtype) and (not copy):\n return data\n return data.astype(dtype)\n\n if isinstance(data, N.ndarray):\n if dtype is None:\n intype = data.dtype\n else:\n intype = N.dtype(dtype)\n new = data.view(subtype)\n if intype != data.dtype:\n return new.astype(intype)\n if copy:\n return new.copy()\n else:\n return new\n\n if isinstance(data, str):\n data = _convert_from_string(data)\n\n # now convert data to an array\n copy = None if not copy else True\n arr = N.array(data, dtype=dtype, copy=copy)\n ndim = arr.ndim\n shape = arr.shape\n if (ndim > 2):\n raise ValueError("matrix must be 2-dimensional")\n elif ndim == 0:\n shape = (1, 1)\n elif ndim == 1:\n shape = (1, shape[0])\n\n order = 'C'\n if (ndim == 2) and arr.flags.fortran:\n order = 'F'\n\n if not (order or arr.flags.contiguous):\n arr = arr.copy()\n\n ret = N.ndarray.__new__(subtype, shape, arr.dtype,\n buffer=arr,\n order=order)\n return ret\n\n def __array_finalize__(self, obj):\n self._getitem = False\n if (isinstance(obj, matrix) and obj._getitem):\n return\n ndim = self.ndim\n if (ndim == 2):\n return\n if (ndim > 2):\n newshape = tuple(x for x in self.shape if x > 1)\n ndim = len(newshape)\n if ndim == 2:\n self.shape = newshape\n return\n elif (ndim > 2):\n raise ValueError("shape too large to be a matrix.")\n else:\n newshape = self.shape\n if ndim == 0:\n self.shape = (1, 1)\n elif ndim == 1:\n self.shape = (1, newshape[0])\n return\n\n def __getitem__(self, index):\n self._getitem = True\n\n try:\n out = N.ndarray.__getitem__(self, index)\n finally:\n self._getitem = False\n\n if not isinstance(out, N.ndarray):\n return out\n\n if out.ndim == 0:\n return out[()]\n if out.ndim == 1:\n sh = out.shape[0]\n # Determine when we should have a column array\n try:\n n = len(index)\n except Exception:\n n = 0\n if n > 1 and isscalar(index[1]):\n out.shape = (sh, 1)\n else:\n out.shape = (1, sh)\n return out\n\n def __mul__(self, other):\n if isinstance(other, (N.ndarray, list, tuple)):\n # This promotes 1-D vectors to row vectors\n return N.dot(self, asmatrix(other))\n if isscalar(other) or not hasattr(other, '__rmul__'):\n return N.dot(self, other)\n return NotImplemented\n\n def __rmul__(self, other):\n return N.dot(other, self)\n\n def __imul__(self, other):\n self[:] = self * other\n return self\n\n def __pow__(self, other):\n return matrix_power(self, other)\n\n def __ipow__(self, other):\n self[:] = self ** other\n return self\n\n def __rpow__(self, other):\n return NotImplemented\n\n def _align(self, axis):\n """A convenience function for operations that need to preserve axis\n orientation.\n """\n if axis is None:\n return self[0, 0]\n elif axis == 0:\n return self\n elif axis == 1:\n return self.transpose()\n else:\n raise ValueError("unsupported axis")\n\n def _collapse(self, axis):\n """A convenience function for operations that want to collapse\n to a scalar like _align, but are using keepdims=True\n """\n if axis is None:\n return self[0, 0]\n else:\n return self\n\n # Necessary because base-class tolist expects dimension\n # reduction by x[0]\n def tolist(self):\n """\n Return the matrix as a (possibly nested) list.\n\n See `ndarray.tolist` for full documentation.\n\n See Also\n --------\n ndarray.tolist\n\n Examples\n --------\n >>> x = np.matrix(np.arange(12).reshape((3,4))); x\n matrix([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n >>> x.tolist()\n [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]\n\n """\n return self.__array__().tolist()\n\n # To preserve orientation of result...\n def sum(self, axis=None, dtype=None, out=None):\n """\n Returns the sum of the matrix elements, along the given axis.\n\n Refer to `numpy.sum` for full documentation.\n\n See Also\n --------\n numpy.sum\n\n Notes\n -----\n This is the same as `ndarray.sum`, except that where an `ndarray` would\n be returned, a `matrix` object is returned instead.\n\n Examples\n --------\n >>> x = np.matrix([[1, 2], [4, 3]])\n >>> x.sum()\n 10\n >>> x.sum(axis=1)\n matrix([[3],\n [7]])\n >>> x.sum(axis=1, dtype='float')\n matrix([[3.],\n [7.]])\n >>> out = np.zeros((2, 1), dtype='float')\n >>> x.sum(axis=1, dtype='float', out=np.asmatrix(out))\n matrix([[3.],\n [7.]])\n\n """\n return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)\n\n # To update docstring from array to matrix...\n def squeeze(self, axis=None):\n """\n Return a possibly reshaped matrix.\n\n Refer to `numpy.squeeze` for more documentation.\n\n Parameters\n ----------\n axis : None or int or tuple of ints, optional\n Selects a subset of the axes of length one in the shape.\n If an axis is selected with shape entry greater than one,\n an error is raised.\n\n Returns\n -------\n squeezed : matrix\n The matrix, but as a (1, N) matrix if it had shape (N, 1).\n\n See Also\n --------\n numpy.squeeze : related function\n\n Notes\n -----\n If `m` has a single column then that column is returned\n as the single row of a matrix. Otherwise `m` is returned.\n The returned matrix is always either `m` itself or a view into `m`.\n Supplying an axis keyword argument will not affect the returned matrix\n but it may cause an error to be raised.\n\n Examples\n --------\n >>> c = np.matrix([[1], [2]])\n >>> c\n matrix([[1],\n [2]])\n >>> c.squeeze()\n matrix([[1, 2]])\n >>> r = c.T\n >>> r\n matrix([[1, 2]])\n >>> r.squeeze()\n matrix([[1, 2]])\n >>> m = np.matrix([[1, 2], [3, 4]])\n >>> m.squeeze()\n matrix([[1, 2],\n [3, 4]])\n\n """\n return N.ndarray.squeeze(self, axis=axis)\n\n # To update docstring from array to matrix...\n def flatten(self, order='C'):\n """\n Return a flattened copy of the matrix.\n\n All `N` elements of the matrix are placed into a single row.\n\n Parameters\n ----------\n order : {'C', 'F', 'A', 'K'}, optional\n 'C' means to flatten in row-major (C-style) order. 'F' means to\n flatten in column-major (Fortran-style) order. 'A' means to\n flatten in column-major order if `m` is Fortran *contiguous* in\n memory, row-major order otherwise. 'K' means to flatten `m` in\n the order the elements occur in memory. The default is 'C'.\n\n Returns\n -------\n y : matrix\n A copy of the matrix, flattened to a `(1, N)` matrix where `N`\n is the number of elements in the original matrix.\n\n See Also\n --------\n ravel : Return a flattened array.\n flat : A 1-D flat iterator over the matrix.\n\n Examples\n --------\n >>> m = np.matrix([[1,2], [3,4]])\n >>> m.flatten()\n matrix([[1, 2, 3, 4]])\n >>> m.flatten('F')\n matrix([[1, 3, 2, 4]])\n\n """\n return N.ndarray.flatten(self, order=order)\n\n def mean(self, axis=None, dtype=None, out=None):\n """\n Returns the average of the matrix elements along the given axis.\n\n Refer to `numpy.mean` for full documentation.\n\n See Also\n --------\n numpy.mean\n\n Notes\n -----\n Same as `ndarray.mean` except that, where that returns an `ndarray`,\n this returns a `matrix` object.\n\n Examples\n --------\n >>> x = np.matrix(np.arange(12).reshape((3, 4)))\n >>> x\n matrix([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n >>> x.mean()\n 5.5\n >>> x.mean(0)\n matrix([[4., 5., 6., 7.]])\n >>> x.mean(1)\n matrix([[ 1.5],\n [ 5.5],\n [ 9.5]])\n\n """\n return N.ndarray.mean(self, axis, dtype, out, keepdims=True)._collapse(axis)\n\n def std(self, axis=None, dtype=None, out=None, ddof=0):\n """\n Return the standard deviation of the array elements along the given axis.\n\n Refer to `numpy.std` for full documentation.\n\n See Also\n --------\n numpy.std\n\n Notes\n -----\n This is the same as `ndarray.std`, except that where an `ndarray` would\n be returned, a `matrix` object is returned instead.\n\n Examples\n --------\n >>> x = np.matrix(np.arange(12).reshape((3, 4)))\n >>> x\n matrix([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n >>> x.std()\n 3.4520525295346629 # may vary\n >>> x.std(0)\n matrix([[ 3.26598632, 3.26598632, 3.26598632, 3.26598632]]) # may vary\n >>> x.std(1)\n matrix([[ 1.11803399],\n [ 1.11803399],\n [ 1.11803399]])\n\n """\n return N.ndarray.std(self, axis, dtype, out, ddof,\n keepdims=True)._collapse(axis)\n\n def var(self, axis=None, dtype=None, out=None, ddof=0):\n """\n Returns the variance of the matrix elements, along the given axis.\n\n Refer to `numpy.var` for full documentation.\n\n See Also\n --------\n numpy.var\n\n Notes\n -----\n This is the same as `ndarray.var`, except that where an `ndarray` would\n be returned, a `matrix` object is returned instead.\n\n Examples\n --------\n >>> x = np.matrix(np.arange(12).reshape((3, 4)))\n >>> x\n matrix([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n >>> x.var()\n 11.916666666666666\n >>> x.var(0)\n matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) # may vary\n >>> x.var(1)\n matrix([[1.25],\n [1.25],\n [1.25]])\n\n """\n return N.ndarray.var(self, axis, dtype, out, ddof,\n keepdims=True)._collapse(axis)\n\n def prod(self, axis=None, dtype=None, out=None):\n """\n Return the product of the array elements over the given axis.\n\n Refer to `prod` for full documentation.\n\n See Also\n --------\n prod, ndarray.prod\n\n Notes\n -----\n Same as `ndarray.prod`, except, where that returns an `ndarray`, this\n returns a `matrix` object instead.\n\n Examples\n --------\n >>> x = np.matrix(np.arange(12).reshape((3,4))); x\n matrix([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n >>> x.prod()\n 0\n >>> x.prod(0)\n matrix([[ 0, 45, 120, 231]])\n >>> x.prod(1)\n matrix([[ 0],\n [ 840],\n [7920]])\n\n """\n return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis)\n\n def any(self, axis=None, out=None):\n """\n Test whether any array element along a given axis evaluates to True.\n\n Refer to `numpy.any` for full documentation.\n\n Parameters\n ----------\n axis : int, optional\n Axis along which logical OR is performed\n out : ndarray, optional\n Output to existing array instead of creating new one, must have\n same shape as expected output\n\n Returns\n -------\n any : bool, ndarray\n Returns a single bool if `axis` is ``None``; otherwise,\n returns `ndarray`\n\n """\n return N.ndarray.any(self, axis, out, keepdims=True)._collapse(axis)\n\n def all(self, axis=None, out=None):\n """\n Test whether all matrix elements along a given axis evaluate to True.\n\n Parameters\n ----------\n See `numpy.all` for complete descriptions\n\n See Also\n --------\n numpy.all\n\n Notes\n -----\n This is the same as `ndarray.all`, but it returns a `matrix` object.\n\n Examples\n --------\n >>> x = np.matrix(np.arange(12).reshape((3,4))); x\n matrix([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n >>> y = x[0]; y\n matrix([[0, 1, 2, 3]])\n >>> (x == y)\n matrix([[ True, True, True, True],\n [False, False, False, False],\n [False, False, False, False]])\n >>> (x == y).all()\n False\n >>> (x == y).all(0)\n matrix([[False, False, False, False]])\n >>> (x == y).all(1)\n matrix([[ True],\n [False],\n [False]])\n\n """\n return N.ndarray.all(self, axis, out, keepdims=True)._collapse(axis)\n\n def max(self, axis=None, out=None):\n """\n Return the maximum value along an axis.\n\n Parameters\n ----------\n See `amax` for complete descriptions\n\n See Also\n --------\n amax, ndarray.max\n\n Notes\n -----\n This is the same as `ndarray.max`, but returns a `matrix` object\n where `ndarray.max` would return an ndarray.\n\n Examples\n --------\n >>> x = np.matrix(np.arange(12).reshape((3,4))); x\n matrix([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n >>> x.max()\n 11\n >>> x.max(0)\n matrix([[ 8, 9, 10, 11]])\n >>> x.max(1)\n matrix([[ 3],\n [ 7],\n [11]])\n\n """\n return N.ndarray.max(self, axis, out, keepdims=True)._collapse(axis)\n\n def argmax(self, axis=None, out=None):\n """\n Indexes of the maximum values along an axis.\n\n Return the indexes of the first occurrences of the maximum values\n along the specified axis. If axis is None, the index is for the\n flattened matrix.\n\n Parameters\n ----------\n See `numpy.argmax` for complete descriptions\n\n See Also\n --------\n numpy.argmax\n\n Notes\n -----\n This is the same as `ndarray.argmax`, but returns a `matrix` object\n where `ndarray.argmax` would return an `ndarray`.\n\n Examples\n --------\n >>> x = np.matrix(np.arange(12).reshape((3,4))); x\n matrix([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n >>> x.argmax()\n 11\n >>> x.argmax(0)\n matrix([[2, 2, 2, 2]])\n >>> x.argmax(1)\n matrix([[3],\n [3],\n [3]])\n\n """\n return N.ndarray.argmax(self, axis, out)._align(axis)\n\n def min(self, axis=None, out=None):\n """\n Return the minimum value along an axis.\n\n Parameters\n ----------\n See `amin` for complete descriptions.\n\n See Also\n --------\n amin, ndarray.min\n\n Notes\n -----\n This is the same as `ndarray.min`, but returns a `matrix` object\n where `ndarray.min` would return an ndarray.\n\n Examples\n --------\n >>> x = -np.matrix(np.arange(12).reshape((3,4))); x\n matrix([[ 0, -1, -2, -3],\n [ -4, -5, -6, -7],\n [ -8, -9, -10, -11]])\n >>> x.min()\n -11\n >>> x.min(0)\n matrix([[ -8, -9, -10, -11]])\n >>> x.min(1)\n matrix([[ -3],\n [ -7],\n [-11]])\n\n """\n return N.ndarray.min(self, axis, out, keepdims=True)._collapse(axis)\n\n def argmin(self, axis=None, out=None):\n """\n Indexes of the minimum values along an axis.\n\n Return the indexes of the first occurrences of the minimum values\n along the specified axis. If axis is None, the index is for the\n flattened matrix.\n\n Parameters\n ----------\n See `numpy.argmin` for complete descriptions.\n\n See Also\n --------\n numpy.argmin\n\n Notes\n -----\n This is the same as `ndarray.argmin`, but returns a `matrix` object\n where `ndarray.argmin` would return an `ndarray`.\n\n Examples\n --------\n >>> x = -np.matrix(np.arange(12).reshape((3,4))); x\n matrix([[ 0, -1, -2, -3],\n [ -4, -5, -6, -7],\n [ -8, -9, -10, -11]])\n >>> x.argmin()\n 11\n >>> x.argmin(0)\n matrix([[2, 2, 2, 2]])\n >>> x.argmin(1)\n matrix([[3],\n [3],\n [3]])\n\n """\n return N.ndarray.argmin(self, axis, out)._align(axis)\n\n def ptp(self, axis=None, out=None):\n """\n Peak-to-peak (maximum - minimum) value along the given axis.\n\n Refer to `numpy.ptp` for full documentation.\n\n See Also\n --------\n numpy.ptp\n\n Notes\n -----\n Same as `ndarray.ptp`, except, where that would return an `ndarray` object,\n this returns a `matrix` object.\n\n Examples\n --------\n >>> x = np.matrix(np.arange(12).reshape((3,4))); x\n matrix([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n >>> x.ptp()\n 11\n >>> x.ptp(0)\n matrix([[8, 8, 8, 8]])\n >>> x.ptp(1)\n matrix([[3],\n [3],\n [3]])\n\n """\n return N.ptp(self, axis, out)._align(axis)\n\n @property\n def I(self): # noqa: E743\n """\n Returns the (multiplicative) inverse of invertible `self`.\n\n Parameters\n ----------\n None\n\n Returns\n -------\n ret : matrix object\n If `self` is non-singular, `ret` is such that ``ret * self`` ==\n ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return\n ``True``.\n\n Raises\n ------\n numpy.linalg.LinAlgError: Singular matrix\n If `self` is singular.\n\n See Also\n --------\n linalg.inv\n\n Examples\n --------\n >>> m = np.matrix('[1, 2; 3, 4]'); m\n matrix([[1, 2],\n [3, 4]])\n >>> m.getI()\n matrix([[-2. , 1. ],\n [ 1.5, -0.5]])\n >>> m.getI() * m\n matrix([[ 1., 0.], # may vary\n [ 0., 1.]])\n\n """\n M, N = self.shape\n if M == N:\n from numpy.linalg import inv as func\n else:\n from numpy.linalg import pinv as func\n return asmatrix(func(self))\n\n @property\n def A(self):\n """\n Return `self` as an `ndarray` object.\n\n Equivalent to ``np.asarray(self)``.\n\n Parameters\n ----------\n None\n\n Returns\n -------\n ret : ndarray\n `self` as an `ndarray`\n\n Examples\n --------\n >>> x = np.matrix(np.arange(12).reshape((3,4))); x\n matrix([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n >>> x.getA()\n array([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n\n """\n return self.__array__()\n\n @property\n def A1(self):\n """\n Return `self` as a flattened `ndarray`.\n\n Equivalent to ``np.asarray(x).ravel()``\n\n Parameters\n ----------\n None\n\n Returns\n -------\n ret : ndarray\n `self`, 1-D, as an `ndarray`\n\n Examples\n --------\n >>> x = np.matrix(np.arange(12).reshape((3,4))); x\n matrix([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n >>> x.getA1()\n array([ 0, 1, 2, ..., 9, 10, 11])\n\n\n """\n return self.__array__().ravel()\n\n def ravel(self, order='C'):\n """\n Return a flattened matrix.\n\n Refer to `numpy.ravel` for more documentation.\n\n Parameters\n ----------\n order : {'C', 'F', 'A', 'K'}, optional\n The elements of `m` are read using this index order. 'C' means to\n index the elements in C-like order, with the last axis index\n changing fastest, back to the first axis index changing slowest.\n 'F' means to index the elements in Fortran-like index order, with\n the first index changing fastest, and the last index changing\n slowest. Note that the 'C' and 'F' options take no account of the\n memory layout of the underlying array, and only refer to the order\n of axis indexing. 'A' means to read the elements in Fortran-like\n index order if `m` is Fortran *contiguous* in memory, C-like order\n otherwise. 'K' means to read the elements in the order they occur\n in memory, except for reversing the data when strides are negative.\n By default, 'C' index order is used.\n\n Returns\n -------\n ret : matrix\n Return the matrix flattened to shape `(1, N)` where `N`\n is the number of elements in the original matrix.\n A copy is made only if necessary.\n\n See Also\n --------\n matrix.flatten : returns a similar output matrix but always a copy\n matrix.flat : a flat iterator on the array.\n numpy.ravel : related function which returns an ndarray\n\n """\n return N.ndarray.ravel(self, order=order)\n\n @property\n def T(self):\n """\n Returns the transpose of the matrix.\n\n Does *not* conjugate! For the complex conjugate transpose, use ``.H``.\n\n Parameters\n ----------\n None\n\n Returns\n -------\n ret : matrix object\n The (non-conjugated) transpose of the matrix.\n\n See Also\n --------\n transpose, getH\n\n Examples\n --------\n >>> m = np.matrix('[1, 2; 3, 4]')\n >>> m\n matrix([[1, 2],\n [3, 4]])\n >>> m.getT()\n matrix([[1, 3],\n [2, 4]])\n\n """\n return self.transpose()\n\n @property\n def H(self):\n """\n Returns the (complex) conjugate transpose of `self`.\n\n Equivalent to ``np.transpose(self)`` if `self` is real-valued.\n\n Parameters\n ----------\n None\n\n Returns\n -------\n ret : matrix object\n complex conjugate transpose of `self`\n\n Examples\n --------\n >>> x = np.matrix(np.arange(12).reshape((3,4)))\n >>> z = x - 1j*x; z\n matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j],\n [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j],\n [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]])\n >>> z.getH()\n matrix([[ 0. -0.j, 4. +4.j, 8. +8.j],\n [ 1. +1.j, 5. +5.j, 9. +9.j],\n [ 2. +2.j, 6. +6.j, 10.+10.j],\n [ 3. +3.j, 7. +7.j, 11.+11.j]])\n\n """\n if issubclass(self.dtype.type, N.complexfloating):\n return self.transpose().conjugate()\n else:\n return self.transpose()\n\n # kept for compatibility\n getT = T.fget\n getA = A.fget\n getA1 = A1.fget\n getH = H.fget\n getI = I.fget\n\ndef _from_string(str, gdict, ldict):\n rows = str.split(';')\n rowtup = []\n for row in rows:\n trow = row.split(',')\n newrow = []\n for x in trow:\n newrow.extend(x.split())\n trow = newrow\n coltup = []\n for col in trow:\n col = col.strip()\n try:\n thismat = ldict[col]\n except KeyError:\n try:\n thismat = gdict[col]\n except KeyError as e:\n raise NameError(f"name {col!r} is not defined") from None\n\n coltup.append(thismat)\n rowtup.append(concatenate(coltup, axis=-1))\n return concatenate(rowtup, axis=0)\n\n\n@set_module('numpy')\ndef bmat(obj, ldict=None, gdict=None):\n """\n Build a matrix object from a string, nested sequence, or array.\n\n Parameters\n ----------\n obj : str or array_like\n Input data. If a string, variables in the current scope may be\n referenced by name.\n ldict : dict, optional\n A dictionary that replaces local operands in current frame.\n Ignored if `obj` is not a string or `gdict` is None.\n gdict : dict, optional\n A dictionary that replaces global operands in current frame.\n Ignored if `obj` is not a string.\n\n Returns\n -------\n out : matrix\n Returns a matrix object, which is a specialized 2-D array.\n\n See Also\n --------\n block :\n A generalization of this function for N-d arrays, that returns normal\n ndarrays.\n\n Examples\n --------\n >>> import numpy as np\n >>> A = np.asmatrix('1 1; 1 1')\n >>> B = np.asmatrix('2 2; 2 2')\n >>> C = np.asmatrix('3 4; 5 6')\n >>> D = np.asmatrix('7 8; 9 0')\n\n All the following expressions construct the same block matrix:\n\n >>> np.bmat([[A, B], [C, D]])\n matrix([[1, 1, 2, 2],\n [1, 1, 2, 2],\n [3, 4, 7, 8],\n [5, 6, 9, 0]])\n >>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])\n matrix([[1, 1, 2, 2],\n [1, 1, 2, 2],\n [3, 4, 7, 8],\n [5, 6, 9, 0]])\n >>> np.bmat('A,B; C,D')\n matrix([[1, 1, 2, 2],\n [1, 1, 2, 2],\n [3, 4, 7, 8],\n [5, 6, 9, 0]])\n\n """\n if isinstance(obj, str):\n if gdict is None:\n # get previous frame\n frame = sys._getframe().f_back\n glob_dict = frame.f_globals\n loc_dict = frame.f_locals\n else:\n glob_dict = gdict\n loc_dict = ldict\n\n return matrix(_from_string(obj, glob_dict, loc_dict))\n\n if isinstance(obj, (tuple, list)):\n # [[A,B],[C,D]]\n arr_rows = []\n for row in obj:\n if isinstance(row, N.ndarray): # not 2-d\n return matrix(concatenate(obj, axis=-1))\n else:\n arr_rows.append(concatenate(row, axis=-1))\n return matrix(concatenate(arr_rows, axis=0))\n if isinstance(obj, N.ndarray):\n return matrix(obj)\n | .venv\Lib\site-packages\numpy\matrixlib\defmatrix.py | defmatrix.py | Python | 31,994 | 0.95 | 0.111707 | 0.014024 | awesome-app | 689 | 2025-02-02T00:43:23.205086 | Apache-2.0 | false | c7854566aa25ea2dbac2b9004b6e8b44 |
from collections.abc import Mapping, Sequence\nfrom typing import Any\n\nfrom numpy import matrix\nfrom numpy._typing import ArrayLike, DTypeLike, NDArray\n\n__all__ = ["asmatrix", "bmat", "matrix"]\n\ndef bmat(\n obj: str | Sequence[ArrayLike] | NDArray[Any],\n ldict: Mapping[str, Any] | None = ...,\n gdict: Mapping[str, Any] | None = ...,\n) -> matrix[tuple[int, int], Any]: ...\n\ndef asmatrix(\n data: ArrayLike, dtype: DTypeLike = ...\n) -> matrix[tuple[int, int], Any]: ...\n | .venv\Lib\site-packages\numpy\matrixlib\defmatrix.pyi | defmatrix.pyi | Other | 495 | 0.85 | 0.117647 | 0 | react-lib | 368 | 2024-10-20T13:46:26.433772 | GPL-3.0 | false | 92bd4260b37ec6d87fd2e5abc58dd017 |
"""Sub-package containing the matrix class and related functions.\n\n"""\nfrom . import defmatrix\nfrom .defmatrix import *\n\n__all__ = defmatrix.__all__\n\nfrom numpy._pytesttester import PytestTester\n\ntest = PytestTester(__name__)\ndel PytestTester\n | .venv\Lib\site-packages\numpy\matrixlib\__init__.py | __init__.py | Python | 255 | 0.85 | 0.083333 | 0 | node-utils | 755 | 2024-01-01T14:52:02.958794 | MIT | false | 7d994df4df45924c064760bd0e6201bf |
from numpy import matrix\n\nfrom .defmatrix import asmatrix, bmat\n\n__all__ = ["matrix", "bmat", "asmatrix"]\n | .venv\Lib\site-packages\numpy\matrixlib\__init__.pyi | __init__.pyi | Other | 111 | 0.85 | 0 | 0 | react-lib | 391 | 2023-11-06T15:23:41.953782 | BSD-3-Clause | false | ab72d00833d0dddaaf8f839d7e931c66 |
import collections.abc\n\nimport numpy as np\nfrom numpy import asmatrix, bmat, matrix\nfrom numpy.linalg import matrix_power\nfrom numpy.testing import (\n assert_,\n assert_almost_equal,\n assert_array_almost_equal,\n assert_array_equal,\n assert_equal,\n assert_raises,\n)\n\n\nclass TestCtor:\n def test_basic(self):\n A = np.array([[1, 2], [3, 4]])\n mA = matrix(A)\n assert_(np.all(mA.A == A))\n\n B = bmat("A,A;A,A")\n C = bmat([[A, A], [A, A]])\n D = np.array([[1, 2, 1, 2],\n [3, 4, 3, 4],\n [1, 2, 1, 2],\n [3, 4, 3, 4]])\n assert_(np.all(B.A == D))\n assert_(np.all(C.A == D))\n\n E = np.array([[5, 6], [7, 8]])\n AEresult = matrix([[1, 2, 5, 6], [3, 4, 7, 8]])\n assert_(np.all(bmat([A, E]) == AEresult))\n\n vec = np.arange(5)\n mvec = matrix(vec)\n assert_(mvec.shape == (1, 5))\n\n def test_exceptions(self):\n # Check for ValueError when called with invalid string data.\n assert_raises(ValueError, matrix, "invalid")\n\n def test_bmat_nondefault_str(self):\n A = np.array([[1, 2], [3, 4]])\n B = np.array([[5, 6], [7, 8]])\n Aresult = np.array([[1, 2, 1, 2],\n [3, 4, 3, 4],\n [1, 2, 1, 2],\n [3, 4, 3, 4]])\n mixresult = np.array([[1, 2, 5, 6],\n [3, 4, 7, 8],\n [5, 6, 1, 2],\n [7, 8, 3, 4]])\n assert_(np.all(bmat("A,A;A,A") == Aresult))\n assert_(np.all(bmat("A,A;A,A", ldict={'A': B}) == Aresult))\n assert_raises(TypeError, bmat, "A,A;A,A", gdict={'A': B})\n assert_(\n np.all(bmat("A,A;A,A", ldict={'A': A}, gdict={'A': B}) == Aresult))\n b2 = bmat("A,B;C,D", ldict={'A': A, 'B': B}, gdict={'C': B, 'D': A})\n assert_(np.all(b2 == mixresult))\n\n\nclass TestProperties:\n def test_sum(self):\n """Test whether matrix.sum(axis=1) preserves orientation.\n Fails in NumPy <= 0.9.6.2127.\n """\n M = matrix([[1, 2, 0, 0],\n [3, 4, 0, 0],\n [1, 2, 1, 2],\n [3, 4, 3, 4]])\n sum0 = matrix([8, 12, 4, 6])\n sum1 = matrix([3, 7, 6, 14]).T\n sumall = 30\n assert_array_equal(sum0, M.sum(axis=0))\n assert_array_equal(sum1, M.sum(axis=1))\n assert_equal(sumall, M.sum())\n\n assert_array_equal(sum0, np.sum(M, axis=0))\n assert_array_equal(sum1, np.sum(M, axis=1))\n assert_equal(sumall, np.sum(M))\n\n def test_prod(self):\n x = matrix([[1, 2, 3], [4, 5, 6]])\n assert_equal(x.prod(), 720)\n assert_equal(x.prod(0), matrix([[4, 10, 18]]))\n assert_equal(x.prod(1), matrix([[6], [120]]))\n\n assert_equal(np.prod(x), 720)\n assert_equal(np.prod(x, axis=0), matrix([[4, 10, 18]]))\n assert_equal(np.prod(x, axis=1), matrix([[6], [120]]))\n\n y = matrix([0, 1, 3])\n assert_(y.prod() == 0)\n\n def test_max(self):\n x = matrix([[1, 2, 3], [4, 5, 6]])\n assert_equal(x.max(), 6)\n assert_equal(x.max(0), matrix([[4, 5, 6]]))\n assert_equal(x.max(1), matrix([[3], [6]]))\n\n assert_equal(np.max(x), 6)\n assert_equal(np.max(x, axis=0), matrix([[4, 5, 6]]))\n assert_equal(np.max(x, axis=1), matrix([[3], [6]]))\n\n def test_min(self):\n x = matrix([[1, 2, 3], [4, 5, 6]])\n assert_equal(x.min(), 1)\n assert_equal(x.min(0), matrix([[1, 2, 3]]))\n assert_equal(x.min(1), matrix([[1], [4]]))\n\n assert_equal(np.min(x), 1)\n assert_equal(np.min(x, axis=0), matrix([[1, 2, 3]]))\n assert_equal(np.min(x, axis=1), matrix([[1], [4]]))\n\n def test_ptp(self):\n x = np.arange(4).reshape((2, 2))\n mx = x.view(np.matrix)\n assert_(mx.ptp() == 3)\n assert_(np.all(mx.ptp(0) == np.array([2, 2])))\n assert_(np.all(mx.ptp(1) == np.array([1, 1])))\n\n def test_var(self):\n x = np.arange(9).reshape((3, 3))\n mx = x.view(np.matrix)\n assert_equal(x.var(ddof=0), mx.var(ddof=0))\n assert_equal(x.var(ddof=1), mx.var(ddof=1))\n\n def test_basic(self):\n import numpy.linalg as linalg\n\n A = np.array([[1., 2.],\n [3., 4.]])\n mA = matrix(A)\n assert_(np.allclose(linalg.inv(A), mA.I))\n assert_(np.all(np.array(np.transpose(A) == mA.T)))\n assert_(np.all(np.array(np.transpose(A) == mA.H)))\n assert_(np.all(A == mA.A))\n\n B = A + 2j * A\n mB = matrix(B)\n assert_(np.allclose(linalg.inv(B), mB.I))\n assert_(np.all(np.array(np.transpose(B) == mB.T)))\n assert_(np.all(np.array(np.transpose(B).conj() == mB.H)))\n\n def test_pinv(self):\n x = matrix(np.arange(6).reshape(2, 3))\n xpinv = matrix([[-0.77777778, 0.27777778],\n [-0.11111111, 0.11111111],\n [ 0.55555556, -0.05555556]])\n assert_almost_equal(x.I, xpinv)\n\n def test_comparisons(self):\n A = np.arange(100).reshape(10, 10)\n mA = matrix(A)\n mB = matrix(A) + 0.1\n assert_(np.all(mB == A + 0.1))\n assert_(np.all(mB == matrix(A + 0.1)))\n assert_(not np.any(mB == matrix(A - 0.1)))\n assert_(np.all(mA < mB))\n assert_(np.all(mA <= mB))\n assert_(np.all(mA <= mA))\n assert_(not np.any(mA < mA))\n\n assert_(not np.any(mB < mA))\n assert_(np.all(mB >= mA))\n assert_(np.all(mB >= mB))\n assert_(not np.any(mB > mB))\n\n assert_(np.all(mA == mA))\n assert_(not np.any(mA == mB))\n assert_(np.all(mB != mA))\n\n assert_(not np.all(abs(mA) > 0))\n assert_(np.all(abs(mB > 0)))\n\n def test_asmatrix(self):\n A = np.arange(100).reshape(10, 10)\n mA = asmatrix(A)\n A[0, 0] = -10\n assert_(A[0, 0] == mA[0, 0])\n\n def test_noaxis(self):\n A = matrix([[1, 0], [0, 1]])\n assert_(A.sum() == matrix(2))\n assert_(A.mean() == matrix(0.5))\n\n def test_repr(self):\n A = matrix([[1, 0], [0, 1]])\n assert_(repr(A) == "matrix([[1, 0],\n [0, 1]])")\n\n def test_make_bool_matrix_from_str(self):\n A = matrix('True; True; False')\n B = matrix([[True], [True], [False]])\n assert_array_equal(A, B)\n\nclass TestCasting:\n def test_basic(self):\n A = np.arange(100).reshape(10, 10)\n mA = matrix(A)\n\n mB = mA.copy()\n O = np.ones((10, 10), np.float64) * 0.1\n mB = mB + O\n assert_(mB.dtype.type == np.float64)\n assert_(np.all(mA != mB))\n assert_(np.all(mB == mA + 0.1))\n\n mC = mA.copy()\n O = np.ones((10, 10), np.complex128)\n mC = mC * O\n assert_(mC.dtype.type == np.complex128)\n assert_(np.all(mA != mB))\n\n\nclass TestAlgebra:\n def test_basic(self):\n import numpy.linalg as linalg\n\n A = np.array([[1., 2.], [3., 4.]])\n mA = matrix(A)\n\n B = np.identity(2)\n for i in range(6):\n assert_(np.allclose((mA ** i).A, B))\n B = np.dot(B, A)\n\n Ainv = linalg.inv(A)\n B = np.identity(2)\n for i in range(6):\n assert_(np.allclose((mA ** -i).A, B))\n B = np.dot(B, Ainv)\n\n assert_(np.allclose((mA * mA).A, np.dot(A, A)))\n assert_(np.allclose((mA + mA).A, (A + A)))\n assert_(np.allclose((3 * mA).A, (3 * A)))\n\n mA2 = matrix(A)\n mA2 *= 3\n assert_(np.allclose(mA2.A, 3 * A))\n\n def test_pow(self):\n """Test raising a matrix to an integer power works as expected."""\n m = matrix("1. 2.; 3. 4.")\n m2 = m.copy()\n m2 **= 2\n mi = m.copy()\n mi **= -1\n m4 = m2.copy()\n m4 **= 2\n assert_array_almost_equal(m2, m**2)\n assert_array_almost_equal(m4, np.dot(m2, m2))\n assert_array_almost_equal(np.dot(mi, m), np.eye(2))\n\n def test_scalar_type_pow(self):\n m = matrix([[1, 2], [3, 4]])\n for scalar_t in [np.int8, np.uint8]:\n two = scalar_t(2)\n assert_array_almost_equal(m ** 2, m ** two)\n\n def test_notimplemented(self):\n '''Check that 'not implemented' operations produce a failure.'''\n A = matrix([[1., 2.],\n [3., 4.]])\n\n # __rpow__\n with assert_raises(TypeError):\n 1.0**A\n\n # __mul__ with something not a list, ndarray, tuple, or scalar\n with assert_raises(TypeError):\n A * object()\n\n\nclass TestMatrixReturn:\n def test_instance_methods(self):\n a = matrix([1.0], dtype='f8')\n methodargs = {\n 'astype': ('intc',),\n 'clip': (0.0, 1.0),\n 'compress': ([1],),\n 'repeat': (1,),\n 'reshape': (1,),\n 'swapaxes': (0, 0),\n 'dot': np.array([1.0]),\n }\n excluded_methods = [\n 'argmin', 'choose', 'dump', 'dumps', 'fill', 'getfield',\n 'getA', 'getA1', 'item', 'nonzero', 'put', 'putmask', 'resize',\n 'searchsorted', 'setflags', 'setfield', 'sort',\n 'partition', 'argpartition', 'newbyteorder', 'to_device',\n 'take', 'tofile', 'tolist', 'tobytes', 'all', 'any',\n 'sum', 'argmax', 'argmin', 'min', 'max', 'mean', 'var', 'ptp',\n 'prod', 'std', 'ctypes', 'itemset', 'bitwise_count',\n ]\n for attrib in dir(a):\n if attrib.startswith('_') or attrib in excluded_methods:\n continue\n f = getattr(a, attrib)\n if isinstance(f, collections.abc.Callable):\n # reset contents of a\n a.astype('f8')\n a.fill(1.0)\n args = methodargs.get(attrib, ())\n b = f(*args)\n assert_(type(b) is matrix, f"{attrib}")\n assert_(type(a.real) is matrix)\n assert_(type(a.imag) is matrix)\n c, d = matrix([0.0]).nonzero()\n assert_(type(c) is np.ndarray)\n assert_(type(d) is np.ndarray)\n\n\nclass TestIndexing:\n def test_basic(self):\n x = asmatrix(np.zeros((3, 2), float))\n y = np.zeros((3, 1), float)\n y[:, 0] = [0.8, 0.2, 0.3]\n x[:, 1] = y > 0.5\n assert_equal(x, [[0, 1], [0, 0], [0, 0]])\n\n\nclass TestNewScalarIndexing:\n a = matrix([[1, 2], [3, 4]])\n\n def test_dimesions(self):\n a = self.a\n x = a[0]\n assert_equal(x.ndim, 2)\n\n def test_array_from_matrix_list(self):\n a = self.a\n x = np.array([a, a])\n assert_equal(x.shape, [2, 2, 2])\n\n def test_array_to_list(self):\n a = self.a\n assert_equal(a.tolist(), [[1, 2], [3, 4]])\n\n def test_fancy_indexing(self):\n a = self.a\n x = a[1, [0, 1, 0]]\n assert_(isinstance(x, matrix))\n assert_equal(x, matrix([[3, 4, 3]]))\n x = a[[1, 0]]\n assert_(isinstance(x, matrix))\n assert_equal(x, matrix([[3, 4], [1, 2]]))\n x = a[[[1], [0]], [[1, 0], [0, 1]]]\n assert_(isinstance(x, matrix))\n assert_equal(x, matrix([[4, 3], [1, 2]]))\n\n def test_matrix_element(self):\n x = matrix([[1, 2, 3], [4, 5, 6]])\n assert_equal(x[0][0], matrix([[1, 2, 3]]))\n assert_equal(x[0][0].shape, (1, 3))\n assert_equal(x[0].shape, (1, 3))\n assert_equal(x[:, 0].shape, (2, 1))\n\n x = matrix(0)\n assert_equal(x[0, 0], 0)\n assert_equal(x[0], 0)\n assert_equal(x[:, 0].shape, x.shape)\n\n def test_scalar_indexing(self):\n x = asmatrix(np.zeros((3, 2), float))\n assert_equal(x[0, 0], x[0][0])\n\n def test_row_column_indexing(self):\n x = asmatrix(np.eye(2))\n assert_array_equal(x[0, :], [[1, 0]])\n assert_array_equal(x[1, :], [[0, 1]])\n assert_array_equal(x[:, 0], [[1], [0]])\n assert_array_equal(x[:, 1], [[0], [1]])\n\n def test_boolean_indexing(self):\n A = np.arange(6)\n A.shape = (3, 2)\n x = asmatrix(A)\n assert_array_equal(x[:, np.array([True, False])], x[:, 0])\n assert_array_equal(x[np.array([True, False, False]), :], x[0, :])\n\n def test_list_indexing(self):\n A = np.arange(6)\n A.shape = (3, 2)\n x = asmatrix(A)\n assert_array_equal(x[:, [1, 0]], x[:, ::-1])\n assert_array_equal(x[[2, 1, 0], :], x[::-1, :])\n\n\nclass TestPower:\n def test_returntype(self):\n a = np.array([[0, 1], [0, 0]])\n assert_(type(matrix_power(a, 2)) is np.ndarray)\n a = asmatrix(a)\n assert_(type(matrix_power(a, 2)) is matrix)\n\n def test_list(self):\n assert_array_equal(matrix_power([[0, 1], [0, 0]], 2), [[0, 0], [0, 0]])\n\n\nclass TestShape:\n\n a = np.array([[1], [2]])\n m = matrix([[1], [2]])\n\n def test_shape(self):\n assert_equal(self.a.shape, (2, 1))\n assert_equal(self.m.shape, (2, 1))\n\n def test_numpy_ravel(self):\n assert_equal(np.ravel(self.a).shape, (2,))\n assert_equal(np.ravel(self.m).shape, (2,))\n\n def test_member_ravel(self):\n assert_equal(self.a.ravel().shape, (2,))\n assert_equal(self.m.ravel().shape, (1, 2))\n\n def test_member_flatten(self):\n assert_equal(self.a.flatten().shape, (2,))\n assert_equal(self.m.flatten().shape, (1, 2))\n\n def test_numpy_ravel_order(self):\n x = np.array([[1, 2, 3], [4, 5, 6]])\n assert_equal(np.ravel(x), [1, 2, 3, 4, 5, 6])\n assert_equal(np.ravel(x, order='F'), [1, 4, 2, 5, 3, 6])\n assert_equal(np.ravel(x.T), [1, 4, 2, 5, 3, 6])\n assert_equal(np.ravel(x.T, order='A'), [1, 2, 3, 4, 5, 6])\n x = matrix([[1, 2, 3], [4, 5, 6]])\n assert_equal(np.ravel(x), [1, 2, 3, 4, 5, 6])\n assert_equal(np.ravel(x, order='F'), [1, 4, 2, 5, 3, 6])\n assert_equal(np.ravel(x.T), [1, 4, 2, 5, 3, 6])\n assert_equal(np.ravel(x.T, order='A'), [1, 2, 3, 4, 5, 6])\n\n def test_matrix_ravel_order(self):\n x = matrix([[1, 2, 3], [4, 5, 6]])\n assert_equal(x.ravel(), [[1, 2, 3, 4, 5, 6]])\n assert_equal(x.ravel(order='F'), [[1, 4, 2, 5, 3, 6]])\n assert_equal(x.T.ravel(), [[1, 4, 2, 5, 3, 6]])\n assert_equal(x.T.ravel(order='A'), [[1, 2, 3, 4, 5, 6]])\n\n def test_array_memory_sharing(self):\n assert_(np.may_share_memory(self.a, self.a.ravel()))\n assert_(not np.may_share_memory(self.a, self.a.flatten()))\n\n def test_matrix_memory_sharing(self):\n assert_(np.may_share_memory(self.m, self.m.ravel()))\n assert_(not np.may_share_memory(self.m, self.m.flatten()))\n\n def test_expand_dims_matrix(self):\n # matrices are always 2d - so expand_dims only makes sense when the\n # type is changed away from matrix.\n a = np.arange(10).reshape((2, 5)).view(np.matrix)\n expanded = np.expand_dims(a, axis=1)\n assert_equal(expanded.ndim, 3)\n assert_(not isinstance(expanded, np.matrix))\n | .venv\Lib\site-packages\numpy\matrixlib\tests\test_defmatrix.py | test_defmatrix.py | Python | 15,432 | 0.95 | 0.12967 | 0.015915 | vue-tools | 712 | 2024-03-29T02:05:14.021606 | Apache-2.0 | true | c9c411c8ac37b1bbd5b80b56ef470f46 |
"""Tests of interaction of matrix with other parts of numpy.\n\nNote that tests with MaskedArray and linalg are done in separate files.\n"""\nimport textwrap\nimport warnings\n\nimport pytest\n\nimport numpy as np\nfrom numpy.testing import (\n assert_,\n assert_almost_equal,\n assert_array_almost_equal,\n assert_array_equal,\n assert_equal,\n assert_raises,\n assert_raises_regex,\n)\n\n\ndef test_fancy_indexing():\n # The matrix class messes with the shape. While this is always\n # weird (getitem is not used, it does not have setitem nor knows\n # about fancy indexing), this tests gh-3110\n # 2018-04-29: moved here from core.tests.test_index.\n m = np.matrix([[1, 2], [3, 4]])\n\n assert_(isinstance(m[[0, 1, 0], :], np.matrix))\n\n # gh-3110. Note the transpose currently because matrices do *not*\n # support dimension fixing for fancy indexing correctly.\n x = np.asmatrix(np.arange(50).reshape(5, 10))\n assert_equal(x[:2, np.array(-1)], x[:2, -1].T)\n\n\ndef test_polynomial_mapdomain():\n # test that polynomial preserved matrix subtype.\n # 2018-04-29: moved here from polynomial.tests.polyutils.\n dom1 = [0, 4]\n dom2 = [1, 3]\n x = np.matrix([dom1, dom1])\n res = np.polynomial.polyutils.mapdomain(x, dom1, dom2)\n assert_(isinstance(res, np.matrix))\n\n\ndef test_sort_matrix_none():\n # 2018-04-29: moved here from core.tests.test_multiarray\n a = np.matrix([[2, 1, 0]])\n actual = np.sort(a, axis=None)\n expected = np.matrix([[0, 1, 2]])\n assert_equal(actual, expected)\n assert_(type(expected) is np.matrix)\n\n\ndef test_partition_matrix_none():\n # gh-4301\n # 2018-04-29: moved here from core.tests.test_multiarray\n a = np.matrix([[2, 1, 0]])\n actual = np.partition(a, 1, axis=None)\n expected = np.matrix([[0, 1, 2]])\n assert_equal(actual, expected)\n assert_(type(expected) is np.matrix)\n\n\ndef test_dot_scalar_and_matrix_of_objects():\n # Ticket #2469\n # 2018-04-29: moved here from core.tests.test_multiarray\n arr = np.matrix([1, 2], dtype=object)\n desired = np.matrix([[3, 6]], dtype=object)\n assert_equal(np.dot(arr, 3), desired)\n assert_equal(np.dot(3, arr), desired)\n\n\ndef test_inner_scalar_and_matrix():\n # 2018-04-29: moved here from core.tests.test_multiarray\n for dt in np.typecodes['AllInteger'] + np.typecodes['AllFloat'] + '?':\n sca = np.array(3, dtype=dt)[()]\n arr = np.matrix([[1, 2], [3, 4]], dtype=dt)\n desired = np.matrix([[3, 6], [9, 12]], dtype=dt)\n assert_equal(np.inner(arr, sca), desired)\n assert_equal(np.inner(sca, arr), desired)\n\n\ndef test_inner_scalar_and_matrix_of_objects():\n # Ticket #4482\n # 2018-04-29: moved here from core.tests.test_multiarray\n arr = np.matrix([1, 2], dtype=object)\n desired = np.matrix([[3, 6]], dtype=object)\n assert_equal(np.inner(arr, 3), desired)\n assert_equal(np.inner(3, arr), desired)\n\n\ndef test_iter_allocate_output_subtype():\n # Make sure that the subtype with priority wins\n # 2018-04-29: moved here from core.tests.test_nditer, given the\n # matrix specific shape test.\n\n # matrix vs ndarray\n a = np.matrix([[1, 2], [3, 4]])\n b = np.arange(4).reshape(2, 2).T\n i = np.nditer([a, b, None], [],\n [['readonly'], ['readonly'], ['writeonly', 'allocate']])\n assert_(type(i.operands[2]) is np.matrix)\n assert_(type(i.operands[2]) is not np.ndarray)\n assert_equal(i.operands[2].shape, (2, 2))\n\n # matrix always wants things to be 2D\n b = np.arange(4).reshape(1, 2, 2)\n assert_raises(RuntimeError, np.nditer, [a, b, None], [],\n [['readonly'], ['readonly'], ['writeonly', 'allocate']])\n # but if subtypes are disabled, the result can still work\n i = np.nditer([a, b, None], [],\n [['readonly'], ['readonly'],\n ['writeonly', 'allocate', 'no_subtype']])\n assert_(type(i.operands[2]) is np.ndarray)\n assert_(type(i.operands[2]) is not np.matrix)\n assert_equal(i.operands[2].shape, (1, 2, 2))\n\n\ndef like_function():\n # 2018-04-29: moved here from core.tests.test_numeric\n a = np.matrix([[1, 2], [3, 4]])\n for like_function in np.zeros_like, np.ones_like, np.empty_like:\n b = like_function(a)\n assert_(type(b) is np.matrix)\n\n c = like_function(a, subok=False)\n assert_(type(c) is not np.matrix)\n\n\ndef test_array_astype():\n # 2018-04-29: copied here from core.tests.test_api\n # subok=True passes through a matrix\n a = np.matrix([[0, 1, 2], [3, 4, 5]], dtype='f4')\n b = a.astype('f4', subok=True, copy=False)\n assert_(a is b)\n\n # subok=True is default, and creates a subtype on a cast\n b = a.astype('i4', copy=False)\n assert_equal(a, b)\n assert_equal(type(b), np.matrix)\n\n # subok=False never returns a matrix\n b = a.astype('f4', subok=False, copy=False)\n assert_equal(a, b)\n assert_(not (a is b))\n assert_(type(b) is not np.matrix)\n\n\ndef test_stack():\n # 2018-04-29: copied here from core.tests.test_shape_base\n # check np.matrix cannot be stacked\n m = np.matrix([[1, 2], [3, 4]])\n assert_raises_regex(ValueError, 'shape too large to be a matrix',\n np.stack, [m, m])\n\n\ndef test_object_scalar_multiply():\n # Tickets #2469 and #4482\n # 2018-04-29: moved here from core.tests.test_ufunc\n arr = np.matrix([1, 2], dtype=object)\n desired = np.matrix([[3, 6]], dtype=object)\n assert_equal(np.multiply(arr, 3), desired)\n assert_equal(np.multiply(3, arr), desired)\n\n\ndef test_nanfunctions_matrices():\n # Check that it works and that type and\n # shape are preserved\n # 2018-04-29: moved here from core.tests.test_nanfunctions\n mat = np.matrix(np.eye(3))\n for f in [np.nanmin, np.nanmax]:\n res = f(mat, axis=0)\n assert_(isinstance(res, np.matrix))\n assert_(res.shape == (1, 3))\n res = f(mat, axis=1)\n assert_(isinstance(res, np.matrix))\n assert_(res.shape == (3, 1))\n res = f(mat)\n assert_(np.isscalar(res))\n # check that rows of nan are dealt with for subclasses (#4628)\n mat[1] = np.nan\n for f in [np.nanmin, np.nanmax]:\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n res = f(mat, axis=0)\n assert_(isinstance(res, np.matrix))\n assert_(not np.any(np.isnan(res)))\n assert_(len(w) == 0)\n\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n res = f(mat, axis=1)\n assert_(isinstance(res, np.matrix))\n assert_(np.isnan(res[1, 0]) and not np.isnan(res[0, 0])\n and not np.isnan(res[2, 0]))\n assert_(len(w) == 1, 'no warning raised')\n assert_(issubclass(w[0].category, RuntimeWarning))\n\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n res = f(mat)\n assert_(np.isscalar(res))\n assert_(res != np.nan)\n assert_(len(w) == 0)\n\n\ndef test_nanfunctions_matrices_general():\n # Check that it works and that type and\n # shape are preserved\n # 2018-04-29: moved here from core.tests.test_nanfunctions\n mat = np.matrix(np.eye(3))\n for f in (np.nanargmin, np.nanargmax, np.nansum, np.nanprod,\n np.nanmean, np.nanvar, np.nanstd):\n res = f(mat, axis=0)\n assert_(isinstance(res, np.matrix))\n assert_(res.shape == (1, 3))\n res = f(mat, axis=1)\n assert_(isinstance(res, np.matrix))\n assert_(res.shape == (3, 1))\n res = f(mat)\n assert_(np.isscalar(res))\n\n for f in np.nancumsum, np.nancumprod:\n res = f(mat, axis=0)\n assert_(isinstance(res, np.matrix))\n assert_(res.shape == (3, 3))\n res = f(mat, axis=1)\n assert_(isinstance(res, np.matrix))\n assert_(res.shape == (3, 3))\n res = f(mat)\n assert_(isinstance(res, np.matrix))\n assert_(res.shape == (1, 3 * 3))\n\n\ndef test_average_matrix():\n # 2018-04-29: moved here from core.tests.test_function_base.\n y = np.matrix(np.random.rand(5, 5))\n assert_array_equal(y.mean(0), np.average(y, 0))\n\n a = np.matrix([[1, 2], [3, 4]])\n w = np.matrix([[1, 2], [3, 4]])\n\n r = np.average(a, axis=0, weights=w)\n assert_equal(type(r), np.matrix)\n assert_equal(r, [[2.5, 10.0 / 3]])\n\n\ndef test_dot_matrix():\n # Test to make sure matrices give the same answer as ndarrays\n # 2018-04-29: moved here from core.tests.test_function_base.\n x = np.linspace(0, 5)\n y = np.linspace(-5, 0)\n mx = np.matrix(x)\n my = np.matrix(y)\n r = np.dot(x, y)\n mr = np.dot(mx, my.T)\n assert_almost_equal(mr, r)\n\n\ndef test_ediff1d_matrix():\n # 2018-04-29: moved here from core.tests.test_arraysetops.\n assert isinstance(np.ediff1d(np.matrix(1)), np.matrix)\n assert isinstance(np.ediff1d(np.matrix(1), to_begin=1), np.matrix)\n\n\ndef test_apply_along_axis_matrix():\n # this test is particularly malicious because matrix\n # refuses to become 1d\n # 2018-04-29: moved here from core.tests.test_shape_base.\n def double(row):\n return row * 2\n\n m = np.matrix([[0, 1], [2, 3]])\n expected = np.matrix([[0, 2], [4, 6]])\n\n result = np.apply_along_axis(double, 0, m)\n assert_(isinstance(result, np.matrix))\n assert_array_equal(result, expected)\n\n result = np.apply_along_axis(double, 1, m)\n assert_(isinstance(result, np.matrix))\n assert_array_equal(result, expected)\n\n\ndef test_kron_matrix():\n # 2018-04-29: moved here from core.tests.test_shape_base.\n a = np.ones([2, 2])\n m = np.asmatrix(a)\n assert_equal(type(np.kron(a, a)), np.ndarray)\n assert_equal(type(np.kron(m, m)), np.matrix)\n assert_equal(type(np.kron(a, m)), np.matrix)\n assert_equal(type(np.kron(m, a)), np.matrix)\n\n\nclass TestConcatenatorMatrix:\n # 2018-04-29: moved here from core.tests.test_index_tricks.\n def test_matrix(self):\n a = [1, 2]\n b = [3, 4]\n\n ab_r = np.r_['r', a, b]\n ab_c = np.r_['c', a, b]\n\n assert_equal(type(ab_r), np.matrix)\n assert_equal(type(ab_c), np.matrix)\n\n assert_equal(np.array(ab_r), [[1, 2, 3, 4]])\n assert_equal(np.array(ab_c), [[1], [2], [3], [4]])\n\n assert_raises(ValueError, lambda: np.r_['rc', a, b])\n\n def test_matrix_scalar(self):\n r = np.r_['r', [1, 2], 3]\n assert_equal(type(r), np.matrix)\n assert_equal(np.array(r), [[1, 2, 3]])\n\n def test_matrix_builder(self):\n a = np.array([1])\n b = np.array([2])\n c = np.array([3])\n d = np.array([4])\n actual = np.r_['a, b; c, d']\n expected = np.bmat([[a, b], [c, d]])\n\n assert_equal(actual, expected)\n assert_equal(type(actual), type(expected))\n\n\ndef test_array_equal_error_message_matrix():\n # 2018-04-29: moved here from testing.tests.test_utils.\n with pytest.raises(AssertionError) as exc_info:\n assert_equal(np.array([1, 2]), np.matrix([1, 2]))\n msg = str(exc_info.value)\n msg_reference = textwrap.dedent("""\\n\n Arrays are not equal\n\n (shapes (2,), (1, 2) mismatch)\n ACTUAL: array([1, 2])\n DESIRED: matrix([[1, 2]])""")\n assert_equal(msg, msg_reference)\n\n\ndef test_array_almost_equal_matrix():\n # Matrix slicing keeps things 2-D, while array does not necessarily.\n # See gh-8452.\n # 2018-04-29: moved here from testing.tests.test_utils.\n m1 = np.matrix([[1., 2.]])\n m2 = np.matrix([[1., np.nan]])\n m3 = np.matrix([[1., -np.inf]])\n m4 = np.matrix([[np.nan, np.inf]])\n m5 = np.matrix([[1., 2.], [np.nan, np.inf]])\n for assert_func in assert_array_almost_equal, assert_almost_equal:\n for m in m1, m2, m3, m4, m5:\n assert_func(m, m)\n a = np.array(m)\n assert_func(a, m)\n assert_func(m, a)\n | .venv\Lib\site-packages\numpy\matrixlib\tests\test_interaction.py | test_interaction.py | Python | 12,234 | 0.95 | 0.108333 | 0.176471 | node-utils | 167 | 2024-08-12T19:12:48.533614 | Apache-2.0 | true | 025a7c881eb4bbd55f4e46af0dd94604 |
import pickle\n\nimport numpy as np\nfrom numpy.ma.core import (\n MaskedArray,\n MaskType,\n add,\n allequal,\n divide,\n getmask,\n hypot,\n log,\n masked,\n masked_array,\n masked_values,\n nomask,\n)\nfrom numpy.ma.extras import mr_\nfrom numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_raises\n\n\nclass MMatrix(MaskedArray, np.matrix,):\n\n def __new__(cls, data, mask=nomask):\n mat = np.matrix(data)\n _data = MaskedArray.__new__(cls, data=mat, mask=mask)\n return _data\n\n def __array_finalize__(self, obj):\n np.matrix.__array_finalize__(self, obj)\n MaskedArray.__array_finalize__(self, obj)\n\n @property\n def _series(self):\n _view = self.view(MaskedArray)\n _view._sharedmask = False\n return _view\n\n\nclass TestMaskedMatrix:\n def test_matrix_indexing(self):\n # Tests conversions and indexing\n x1 = np.matrix([[1, 2, 3], [4, 3, 2]])\n x2 = masked_array(x1, mask=[[1, 0, 0], [0, 1, 0]])\n x3 = masked_array(x1, mask=[[0, 1, 0], [1, 0, 0]])\n x4 = masked_array(x1)\n # test conversion to strings\n str(x2) # raises?\n repr(x2) # raises?\n # tests of indexing\n assert_(type(x2[1, 0]) is type(x1[1, 0]))\n assert_(x1[1, 0] == x2[1, 0])\n assert_(x2[1, 1] is masked)\n assert_equal(x1[0, 2], x2[0, 2])\n assert_equal(x1[0, 1:], x2[0, 1:])\n assert_equal(x1[:, 2], x2[:, 2])\n assert_equal(x1[:], x2[:])\n assert_equal(x1[1:], x3[1:])\n x1[0, 2] = 9\n x2[0, 2] = 9\n assert_equal(x1, x2)\n x1[0, 1:] = 99\n x2[0, 1:] = 99\n assert_equal(x1, x2)\n x2[0, 1] = masked\n assert_equal(x1, x2)\n x2[0, 1:] = masked\n assert_equal(x1, x2)\n x2[0, :] = x1[0, :]\n x2[0, 1] = masked\n assert_(allequal(getmask(x2), np.array([[0, 1, 0], [0, 1, 0]])))\n x3[1, :] = masked_array([1, 2, 3], [1, 1, 0])\n assert_(allequal(getmask(x3)[1], masked_array([1, 1, 0])))\n assert_(allequal(getmask(x3[1]), masked_array([1, 1, 0])))\n x4[1, :] = masked_array([1, 2, 3], [1, 1, 0])\n assert_(allequal(getmask(x4[1]), masked_array([1, 1, 0])))\n assert_(allequal(x4[1], masked_array([1, 2, 3])))\n x1 = np.matrix(np.arange(5) * 1.0)\n x2 = masked_values(x1, 3.0)\n assert_equal(x1, x2)\n assert_(allequal(masked_array([0, 0, 0, 1, 0], dtype=MaskType),\n x2.mask))\n assert_equal(3.0, x2.fill_value)\n\n def test_pickling_subbaseclass(self):\n # Test pickling w/ a subclass of ndarray\n a = masked_array(np.matrix(list(range(10))), mask=[1, 0, 1, 0, 0] * 2)\n for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):\n a_pickled = pickle.loads(pickle.dumps(a, protocol=proto))\n assert_equal(a_pickled._mask, a._mask)\n assert_equal(a_pickled, a)\n assert_(isinstance(a_pickled._data, np.matrix))\n\n def test_count_mean_with_matrix(self):\n m = masked_array(np.matrix([[1, 2], [3, 4]]), mask=np.zeros((2, 2)))\n\n assert_equal(m.count(axis=0).shape, (1, 2))\n assert_equal(m.count(axis=1).shape, (2, 1))\n\n # Make sure broadcasting inside mean and var work\n assert_equal(m.mean(axis=0), [[2., 3.]])\n assert_equal(m.mean(axis=1), [[1.5], [3.5]])\n\n def test_flat(self):\n # Test that flat can return items even for matrices [#4585, #4615]\n # test simple access\n test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1])\n assert_equal(test.flat[1], 2)\n assert_equal(test.flat[2], masked)\n assert_(np.all(test.flat[0:2] == test[0, 0:2]))\n # Test flat on masked_matrices\n test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1])\n test.flat = masked_array([3, 2, 1], mask=[1, 0, 0])\n control = masked_array(np.matrix([[3, 2, 1]]), mask=[1, 0, 0])\n assert_equal(test, control)\n # Test setting\n test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1])\n testflat = test.flat\n testflat[:] = testflat[[2, 1, 0]]\n assert_equal(test, control)\n testflat[0] = 9\n # test that matrices keep the correct shape (#4615)\n a = masked_array(np.matrix(np.eye(2)), mask=0)\n b = a.flat\n b01 = b[:2]\n assert_equal(b01.data, np.array([[1., 0.]]))\n assert_equal(b01.mask, np.array([[False, False]]))\n\n def test_allany_onmatrices(self):\n x = np.array([[0.13, 0.26, 0.90],\n [0.28, 0.33, 0.63],\n [0.31, 0.87, 0.70]])\n X = np.matrix(x)\n m = np.array([[True, False, False],\n [False, False, False],\n [True, True, False]], dtype=np.bool)\n mX = masked_array(X, mask=m)\n mXbig = (mX > 0.5)\n mXsmall = (mX < 0.5)\n\n assert_(not mXbig.all())\n assert_(mXbig.any())\n assert_equal(mXbig.all(0), np.matrix([False, False, True]))\n assert_equal(mXbig.all(1), np.matrix([False, False, True]).T)\n assert_equal(mXbig.any(0), np.matrix([False, False, True]))\n assert_equal(mXbig.any(1), np.matrix([True, True, True]).T)\n\n assert_(not mXsmall.all())\n assert_(mXsmall.any())\n assert_equal(mXsmall.all(0), np.matrix([True, True, False]))\n assert_equal(mXsmall.all(1), np.matrix([False, False, False]).T)\n assert_equal(mXsmall.any(0), np.matrix([True, True, False]))\n assert_equal(mXsmall.any(1), np.matrix([True, True, False]).T)\n\n def test_compressed(self):\n a = masked_array(np.matrix([1, 2, 3, 4]), mask=[0, 0, 0, 0])\n b = a.compressed()\n assert_equal(b, a)\n assert_(isinstance(b, np.matrix))\n a[0, 0] = masked\n b = a.compressed()\n assert_equal(b, [[2, 3, 4]])\n\n def test_ravel(self):\n a = masked_array(np.matrix([1, 2, 3, 4, 5]), mask=[[0, 1, 0, 0, 0]])\n aravel = a.ravel()\n assert_equal(aravel.shape, (1, 5))\n assert_equal(aravel._mask.shape, a.shape)\n\n def test_view(self):\n # Test view w/ flexible dtype\n iterator = list(zip(np.arange(10), np.random.rand(10)))\n data = np.array(iterator)\n a = masked_array(iterator, dtype=[('a', float), ('b', float)])\n a.mask[0] = (1, 0)\n test = a.view((float, 2), np.matrix)\n assert_equal(test, data)\n assert_(isinstance(test, np.matrix))\n assert_(not isinstance(test, MaskedArray))\n\n\nclass TestSubclassing:\n # Test suite for masked subclasses of ndarray.\n\n def setup_method(self):\n x = np.arange(5, dtype='float')\n mx = MMatrix(x, mask=[0, 1, 0, 0, 0])\n self.data = (x, mx)\n\n def test_maskedarray_subclassing(self):\n # Tests subclassing MaskedArray\n (x, mx) = self.data\n assert_(isinstance(mx._data, np.matrix))\n\n def test_masked_unary_operations(self):\n # Tests masked_unary_operation\n (x, mx) = self.data\n with np.errstate(divide='ignore'):\n assert_(isinstance(log(mx), MMatrix))\n assert_equal(log(x), np.log(x))\n\n def test_masked_binary_operations(self):\n # Tests masked_binary_operation\n (x, mx) = self.data\n # Result should be a MMatrix\n assert_(isinstance(add(mx, mx), MMatrix))\n assert_(isinstance(add(mx, x), MMatrix))\n # Result should work\n assert_equal(add(mx, x), mx + x)\n assert_(isinstance(add(mx, mx)._data, np.matrix))\n with assert_raises(TypeError):\n add.outer(mx, mx)\n assert_(isinstance(hypot(mx, mx), MMatrix))\n assert_(isinstance(hypot(mx, x), MMatrix))\n\n def test_masked_binary_operations2(self):\n # Tests domained_masked_binary_operation\n (x, mx) = self.data\n xmx = masked_array(mx.data.__array__(), mask=mx.mask)\n assert_(isinstance(divide(mx, mx), MMatrix))\n assert_(isinstance(divide(mx, x), MMatrix))\n assert_equal(divide(mx, mx), divide(xmx, xmx))\n\nclass TestConcatenator:\n # Tests for mr_, the equivalent of r_ for masked arrays.\n\n def test_matrix_builder(self):\n assert_raises(np.ma.MAError, lambda: mr_['1, 2; 3, 4'])\n\n def test_matrix(self):\n # Test consistency with unmasked version. If we ever deprecate\n # matrix, this test should either still pass, or both actual and\n # expected should fail to be build.\n actual = mr_['r', 1, 2, 3]\n expected = np.ma.array(np.r_['r', 1, 2, 3])\n assert_array_equal(actual, expected)\n\n # outer type is masked array, inner type is matrix\n assert_equal(type(actual), type(expected))\n assert_equal(type(actual.data), type(expected.data))\n | .venv\Lib\site-packages\numpy\matrixlib\tests\test_masked_matrix.py | test_masked_matrix.py | Python | 9,027 | 0.95 | 0.1125 | 0.109524 | vue-tools | 898 | 2024-10-13T16:21:52.616291 | BSD-3-Clause | true | 24e6b6e466f8debcc3ae31bfecb44c88 |
""" Test functions for linalg module using the matrix class."""\nimport numpy as np\nfrom numpy.linalg.tests.test_linalg import (\n CondCases,\n DetCases,\n EigCases,\n EigvalsCases,\n InvCases,\n LinalgCase,\n LinalgTestCase,\n LstsqCases,\n PinvCases,\n SolveCases,\n SVDCases,\n _TestNorm2D,\n _TestNormDoubleBase,\n _TestNormInt64Base,\n _TestNormSingleBase,\n apply_tag,\n)\nfrom numpy.linalg.tests.test_linalg import TestQR as _TestQR\n\nCASES = []\n\n# square test cases\nCASES += apply_tag('square', [\n LinalgCase("0x0_matrix",\n np.empty((0, 0), dtype=np.double).view(np.matrix),\n np.empty((0, 1), dtype=np.double).view(np.matrix),\n tags={'size-0'}),\n LinalgCase("matrix_b_only",\n np.array([[1., 2.], [3., 4.]]),\n np.matrix([2., 1.]).T),\n LinalgCase("matrix_a_and_b",\n np.matrix([[1., 2.], [3., 4.]]),\n np.matrix([2., 1.]).T),\n])\n\n# hermitian test-cases\nCASES += apply_tag('hermitian', [\n LinalgCase("hmatrix_a_and_b",\n np.matrix([[1., 2.], [2., 1.]]),\n None),\n])\n# No need to make generalized or strided cases for matrices.\n\n\nclass MatrixTestCase(LinalgTestCase):\n TEST_CASES = CASES\n\n\nclass TestSolveMatrix(SolveCases, MatrixTestCase):\n pass\n\n\nclass TestInvMatrix(InvCases, MatrixTestCase):\n pass\n\n\nclass TestEigvalsMatrix(EigvalsCases, MatrixTestCase):\n pass\n\n\nclass TestEigMatrix(EigCases, MatrixTestCase):\n pass\n\n\nclass TestSVDMatrix(SVDCases, MatrixTestCase):\n pass\n\n\nclass TestCondMatrix(CondCases, MatrixTestCase):\n pass\n\n\nclass TestPinvMatrix(PinvCases, MatrixTestCase):\n pass\n\n\nclass TestDetMatrix(DetCases, MatrixTestCase):\n pass\n\n\nclass TestLstsqMatrix(LstsqCases, MatrixTestCase):\n pass\n\n\nclass _TestNorm2DMatrix(_TestNorm2D):\n array = np.matrix\n\n\nclass TestNormDoubleMatrix(_TestNorm2DMatrix, _TestNormDoubleBase):\n pass\n\n\nclass TestNormSingleMatrix(_TestNorm2DMatrix, _TestNormSingleBase):\n pass\n\n\nclass TestNormInt64Matrix(_TestNorm2DMatrix, _TestNormInt64Base):\n pass\n\n\nclass TestQRMatrix(_TestQR):\n array = np.matrix\n | .venv\Lib\site-packages\numpy\matrixlib\tests\test_matrix_linalg.py | test_matrix_linalg.py | Python | 2,254 | 0.95 | 0.171429 | 0.041667 | python-kit | 747 | 2023-07-18T01:45:01.274625 | Apache-2.0 | true | 3bebae6b4bf742c5f8ae613982863255 |
import numpy as np\nfrom numpy.testing import assert_, assert_array_equal, assert_equal\n\n\nclass TestView:\n def test_type(self):\n x = np.array([1, 2, 3])\n assert_(isinstance(x.view(np.matrix), np.matrix))\n\n def test_keywords(self):\n x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])\n # We must be specific about the endianness here:\n y = x.view(dtype='<i2', type=np.matrix)\n assert_array_equal(y, [[513]])\n\n assert_(isinstance(y, np.matrix))\n assert_equal(y.dtype, np.dtype('<i2'))\n | .venv\Lib\site-packages\numpy\matrixlib\tests\test_multiarray.py | test_multiarray.py | Python | 572 | 0.95 | 0.176471 | 0.076923 | node-utils | 734 | 2024-07-16T13:13:26.665435 | MIT | true | 95190713fe73f389a32174dca27eae37 |
import numpy as np\nfrom numpy.testing import assert_equal\n\n\nclass TestDot:\n def test_matscalar(self):\n b1 = np.matrix(np.ones((3, 3), dtype=complex))\n assert_equal(b1 * 1.0, b1)\n\n\ndef test_diagonal():\n b1 = np.matrix([[1, 2], [3, 4]])\n diag_b1 = np.matrix([[1, 4]])\n array_b1 = np.array([1, 4])\n\n assert_equal(b1.diagonal(), diag_b1)\n assert_equal(np.diagonal(b1), array_b1)\n assert_equal(np.diag(b1), array_b1)\n | .venv\Lib\site-packages\numpy\matrixlib\tests\test_numeric.py | test_numeric.py | Python | 465 | 0.85 | 0.166667 | 0 | python-kit | 137 | 2023-09-08T21:52:24.939710 | GPL-3.0 | true | b91a5777e2f4e1e9e65714ac1be0411d |
import numpy as np\nfrom numpy.testing import assert_, assert_equal, assert_raises\n\n\nclass TestRegression:\n def test_kron_matrix(self):\n # Ticket #71\n x = np.matrix('[1 0; 1 0]')\n assert_equal(type(np.kron(x, x)), type(x))\n\n def test_matrix_properties(self):\n # Ticket #125\n a = np.matrix([1.0], dtype=float)\n assert_(type(a.real) is np.matrix)\n assert_(type(a.imag) is np.matrix)\n c, d = np.matrix([0.0]).nonzero()\n assert_(type(c) is np.ndarray)\n assert_(type(d) is np.ndarray)\n\n def test_matrix_multiply_by_1d_vector(self):\n # Ticket #473\n def mul():\n np.asmatrix(np.eye(2)) * np.ones(2)\n\n assert_raises(ValueError, mul)\n\n def test_matrix_std_argmax(self):\n # Ticket #83\n x = np.asmatrix(np.random.uniform(0, 1, (3, 3)))\n assert_equal(x.std().shape, ())\n assert_equal(x.argmax().shape, ())\n | .venv\Lib\site-packages\numpy\matrixlib\tests\test_regression.py | test_regression.py | Python | 965 | 0.95 | 0.193548 | 0.16 | python-kit | 750 | 2023-08-23T17:27:21.994511 | GPL-3.0 | true | 12ae70eea7f2740c625ff7cd9a478083 |
\n\n | .venv\Lib\site-packages\numpy\matrixlib\tests\__pycache__\test_defmatrix.cpython-313.pyc | test_defmatrix.cpython-313.pyc | Other | 33,242 | 0.8 | 0 | 0 | react-lib | 138 | 2024-11-10T12:00:13.640705 | BSD-3-Clause | true | fb5c0a6eefe2ce99a790b80f58055edc |
\n\n | .venv\Lib\site-packages\numpy\matrixlib\tests\__pycache__\test_interaction.cpython-313.pyc | test_interaction.cpython-313.pyc | Other | 21,476 | 0.95 | 0 | 0.022346 | awesome-app | 274 | 2024-11-18T02:36:21.351106 | BSD-3-Clause | true | 1d5606e08fdd552f62ec6d25b85609f0 |
\n\n | .venv\Lib\site-packages\numpy\matrixlib\tests\__pycache__\test_masked_matrix.cpython-313.pyc | test_masked_matrix.cpython-313.pyc | Other | 16,631 | 0.8 | 0 | 0.014706 | awesome-app | 893 | 2024-10-27T16:01:59.688700 | Apache-2.0 | true | c65afc3ab284885dba36b75eedabbfd7 |
\n\n | .venv\Lib\site-packages\numpy\matrixlib\tests\__pycache__\test_matrix_linalg.cpython-313.pyc | test_matrix_linalg.cpython-313.pyc | Other | 4,586 | 0.95 | 0.057143 | 0 | awesome-app | 403 | 2025-01-30T11:18:27.139702 | BSD-3-Clause | true | 6d268b9e05ab7fdf226cc320aac87d78 |
\n\n | .venv\Lib\site-packages\numpy\matrixlib\tests\__pycache__\test_multiarray.cpython-313.pyc | test_multiarray.cpython-313.pyc | Other | 1,664 | 0.7 | 0 | 0 | node-utils | 794 | 2024-01-19T15:29:38.462231 | Apache-2.0 | true | a5a4cbee306fc9b2f2c392ea2a0c0dbf |
\n\n | .venv\Lib\site-packages\numpy\matrixlib\tests\__pycache__\test_numeric.cpython-313.pyc | test_numeric.cpython-313.pyc | Other | 1,490 | 0.8 | 0 | 0 | react-lib | 473 | 2025-02-27T14:46:08.680609 | Apache-2.0 | true | b407e76c4041781876d05c076acae4b8 |
\n\n | .venv\Lib\site-packages\numpy\matrixlib\tests\__pycache__\test_regression.cpython-313.pyc | test_regression.cpython-313.pyc | Other | 2,891 | 0.8 | 0 | 0 | vue-tools | 120 | 2025-04-11T05:49:37.882335 | Apache-2.0 | true | afbcf54f41579a88d58ef3f9539ee966 |
\n\n | .venv\Lib\site-packages\numpy\matrixlib\tests\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 196 | 0.7 | 0 | 0 | react-lib | 839 | 2024-08-08T14:37:53.217559 | Apache-2.0 | true | 84a63856abaaf0765ade9ff7992b73b1 |
\n\n | .venv\Lib\site-packages\numpy\matrixlib\__pycache__\defmatrix.cpython-313.pyc | defmatrix.cpython-313.pyc | Other | 31,626 | 0.95 | 0.044419 | 0 | react-lib | 729 | 2024-01-12T05:07:52.974915 | MIT | false | 2d9af5c69288b99d8630c6dbfce8907c |
\n\n | .venv\Lib\site-packages\numpy\matrixlib\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 484 | 0.85 | 0.142857 | 0 | python-kit | 426 | 2024-01-26T05:13:48.196904 | BSD-3-Clause | false | ecee9bbc07dd076e601596b231125bad |
"""\n====================================================\nChebyshev Series (:mod:`numpy.polynomial.chebyshev`)\n====================================================\n\nThis module provides a number of objects (mostly functions) useful for\ndealing with Chebyshev series, including a `Chebyshev` class that\nencapsulates the usual arithmetic operations. (General information\non how this module represents and works with such polynomials is in the\ndocstring for its "parent" sub-package, `numpy.polynomial`).\n\nClasses\n-------\n\n.. autosummary::\n :toctree: generated/\n\n Chebyshev\n\n\nConstants\n---------\n\n.. autosummary::\n :toctree: generated/\n\n chebdomain\n chebzero\n chebone\n chebx\n\nArithmetic\n----------\n\n.. autosummary::\n :toctree: generated/\n\n chebadd\n chebsub\n chebmulx\n chebmul\n chebdiv\n chebpow\n chebval\n chebval2d\n chebval3d\n chebgrid2d\n chebgrid3d\n\nCalculus\n--------\n\n.. autosummary::\n :toctree: generated/\n\n chebder\n chebint\n\nMisc Functions\n--------------\n\n.. autosummary::\n :toctree: generated/\n\n chebfromroots\n chebroots\n chebvander\n chebvander2d\n chebvander3d\n chebgauss\n chebweight\n chebcompanion\n chebfit\n chebpts1\n chebpts2\n chebtrim\n chebline\n cheb2poly\n poly2cheb\n chebinterpolate\n\nSee also\n--------\n`numpy.polynomial`\n\nNotes\n-----\nThe implementations of multiplication, division, integration, and\ndifferentiation use the algebraic identities [1]_:\n\n.. math::\n T_n(x) = \\frac{z^n + z^{-n}}{2} \\\\\n z\\frac{dx}{dz} = \\frac{z - z^{-1}}{2}.\n\nwhere\n\n.. math:: x = \\frac{z + z^{-1}}{2}.\n\nThese identities allow a Chebyshev series to be expressed as a finite,\nsymmetric Laurent series. In this module, this sort of Laurent series\nis referred to as a "z-series."\n\nReferences\n----------\n.. [1] A. T. Benjamin, et al., "Combinatorial Trigonometry with Chebyshev\n Polynomials," *Journal of Statistical Planning and Inference 14*, 2008\n (https://web.archive.org/web/20080221202153/https://www.math.hmc.edu/~benjamin/papers/CombTrig.pdf, pg. 4)\n\n""" # noqa: E501\nimport numpy as np\nimport numpy.linalg as la\nfrom numpy.lib.array_utils import normalize_axis_index\n\nfrom . import polyutils as pu\nfrom ._polybase import ABCPolyBase\n\n__all__ = [\n 'chebzero', 'chebone', 'chebx', 'chebdomain', 'chebline', 'chebadd',\n 'chebsub', 'chebmulx', 'chebmul', 'chebdiv', 'chebpow', 'chebval',\n 'chebder', 'chebint', 'cheb2poly', 'poly2cheb', 'chebfromroots',\n 'chebvander', 'chebfit', 'chebtrim', 'chebroots', 'chebpts1',\n 'chebpts2', 'Chebyshev', 'chebval2d', 'chebval3d', 'chebgrid2d',\n 'chebgrid3d', 'chebvander2d', 'chebvander3d', 'chebcompanion',\n 'chebgauss', 'chebweight', 'chebinterpolate']\n\nchebtrim = pu.trimcoef\n\n#\n# A collection of functions for manipulating z-series. These are private\n# functions and do minimal error checking.\n#\n\ndef _cseries_to_zseries(c):\n """Convert Chebyshev series to z-series.\n\n Convert a Chebyshev series to the equivalent z-series. The result is\n never an empty array. The dtype of the return is the same as that of\n the input. No checks are run on the arguments as this routine is for\n internal use.\n\n Parameters\n ----------\n c : 1-D ndarray\n Chebyshev coefficients, ordered from low to high\n\n Returns\n -------\n zs : 1-D ndarray\n Odd length symmetric z-series, ordered from low to high.\n\n """\n n = c.size\n zs = np.zeros(2 * n - 1, dtype=c.dtype)\n zs[n - 1:] = c / 2\n return zs + zs[::-1]\n\n\ndef _zseries_to_cseries(zs):\n """Convert z-series to a Chebyshev series.\n\n Convert a z series to the equivalent Chebyshev series. The result is\n never an empty array. The dtype of the return is the same as that of\n the input. No checks are run on the arguments as this routine is for\n internal use.\n\n Parameters\n ----------\n zs : 1-D ndarray\n Odd length symmetric z-series, ordered from low to high.\n\n Returns\n -------\n c : 1-D ndarray\n Chebyshev coefficients, ordered from low to high.\n\n """\n n = (zs.size + 1) // 2\n c = zs[n - 1:].copy()\n c[1:n] *= 2\n return c\n\n\ndef _zseries_mul(z1, z2):\n """Multiply two z-series.\n\n Multiply two z-series to produce a z-series.\n\n Parameters\n ----------\n z1, z2 : 1-D ndarray\n The arrays must be 1-D but this is not checked.\n\n Returns\n -------\n product : 1-D ndarray\n The product z-series.\n\n Notes\n -----\n This is simply convolution. If symmetric/anti-symmetric z-series are\n denoted by S/A then the following rules apply:\n\n S*S, A*A -> S\n S*A, A*S -> A\n\n """\n return np.convolve(z1, z2)\n\n\ndef _zseries_div(z1, z2):\n """Divide the first z-series by the second.\n\n Divide `z1` by `z2` and return the quotient and remainder as z-series.\n Warning: this implementation only applies when both z1 and z2 have the\n same symmetry, which is sufficient for present purposes.\n\n Parameters\n ----------\n z1, z2 : 1-D ndarray\n The arrays must be 1-D and have the same symmetry, but this is not\n checked.\n\n Returns\n -------\n\n (quotient, remainder) : 1-D ndarrays\n Quotient and remainder as z-series.\n\n Notes\n -----\n This is not the same as polynomial division on account of the desired form\n of the remainder. If symmetric/anti-symmetric z-series are denoted by S/A\n then the following rules apply:\n\n S/S -> S,S\n A/A -> S,A\n\n The restriction to types of the same symmetry could be fixed but seems like\n unneeded generality. There is no natural form for the remainder in the case\n where there is no symmetry.\n\n """\n z1 = z1.copy()\n z2 = z2.copy()\n lc1 = len(z1)\n lc2 = len(z2)\n if lc2 == 1:\n z1 /= z2\n return z1, z1[:1] * 0\n elif lc1 < lc2:\n return z1[:1] * 0, z1\n else:\n dlen = lc1 - lc2\n scl = z2[0]\n z2 /= scl\n quo = np.empty(dlen + 1, dtype=z1.dtype)\n i = 0\n j = dlen\n while i < j:\n r = z1[i]\n quo[i] = z1[i]\n quo[dlen - i] = r\n tmp = r * z2\n z1[i:i + lc2] -= tmp\n z1[j:j + lc2] -= tmp\n i += 1\n j -= 1\n r = z1[i]\n quo[i] = r\n tmp = r * z2\n z1[i:i + lc2] -= tmp\n quo /= scl\n rem = z1[i + 1:i - 1 + lc2].copy()\n return quo, rem\n\n\ndef _zseries_der(zs):\n """Differentiate a z-series.\n\n The derivative is with respect to x, not z. This is achieved using the\n chain rule and the value of dx/dz given in the module notes.\n\n Parameters\n ----------\n zs : z-series\n The z-series to differentiate.\n\n Returns\n -------\n derivative : z-series\n The derivative\n\n Notes\n -----\n The zseries for x (ns) has been multiplied by two in order to avoid\n using floats that are incompatible with Decimal and likely other\n specialized scalar types. This scaling has been compensated by\n multiplying the value of zs by two also so that the two cancels in the\n division.\n\n """\n n = len(zs) // 2\n ns = np.array([-1, 0, 1], dtype=zs.dtype)\n zs *= np.arange(-n, n + 1) * 2\n d, r = _zseries_div(zs, ns)\n return d\n\n\ndef _zseries_int(zs):\n """Integrate a z-series.\n\n The integral is with respect to x, not z. This is achieved by a change\n of variable using dx/dz given in the module notes.\n\n Parameters\n ----------\n zs : z-series\n The z-series to integrate\n\n Returns\n -------\n integral : z-series\n The indefinite integral\n\n Notes\n -----\n The zseries for x (ns) has been multiplied by two in order to avoid\n using floats that are incompatible with Decimal and likely other\n specialized scalar types. This scaling has been compensated by\n dividing the resulting zs by two.\n\n """\n n = 1 + len(zs) // 2\n ns = np.array([-1, 0, 1], dtype=zs.dtype)\n zs = _zseries_mul(zs, ns)\n div = np.arange(-n, n + 1) * 2\n zs[:n] /= div[:n]\n zs[n + 1:] /= div[n + 1:]\n zs[n] = 0\n return zs\n\n#\n# Chebyshev series functions\n#\n\n\ndef poly2cheb(pol):\n """\n Convert a polynomial to a Chebyshev series.\n\n Convert an array representing the coefficients of a polynomial (relative\n to the "standard" basis) ordered from lowest degree to highest, to an\n array of the coefficients of the equivalent Chebyshev series, ordered\n from lowest to highest degree.\n\n Parameters\n ----------\n pol : array_like\n 1-D array containing the polynomial coefficients\n\n Returns\n -------\n c : ndarray\n 1-D array containing the coefficients of the equivalent Chebyshev\n series.\n\n See Also\n --------\n cheb2poly\n\n Notes\n -----\n The easy way to do conversions between polynomial basis sets\n is to use the convert method of a class instance.\n\n Examples\n --------\n >>> from numpy import polynomial as P\n >>> p = P.Polynomial(range(4))\n >>> p\n Polynomial([0., 1., 2., 3.], domain=[-1., 1.], window=[-1., 1.], symbol='x')\n >>> c = p.convert(kind=P.Chebyshev)\n >>> c\n Chebyshev([1. , 3.25, 1. , 0.75], domain=[-1., 1.], window=[-1., ...\n >>> P.chebyshev.poly2cheb(range(4))\n array([1. , 3.25, 1. , 0.75])\n\n """\n [pol] = pu.as_series([pol])\n deg = len(pol) - 1\n res = 0\n for i in range(deg, -1, -1):\n res = chebadd(chebmulx(res), pol[i])\n return res\n\n\ndef cheb2poly(c):\n """\n Convert a Chebyshev series to a polynomial.\n\n Convert an array representing the coefficients of a Chebyshev series,\n ordered from lowest degree to highest, to an array of the coefficients\n of the equivalent polynomial (relative to the "standard" basis) ordered\n from lowest to highest degree.\n\n Parameters\n ----------\n c : array_like\n 1-D array containing the Chebyshev series coefficients, ordered\n from lowest order term to highest.\n\n Returns\n -------\n pol : ndarray\n 1-D array containing the coefficients of the equivalent polynomial\n (relative to the "standard" basis) ordered from lowest order term\n to highest.\n\n See Also\n --------\n poly2cheb\n\n Notes\n -----\n The easy way to do conversions between polynomial basis sets\n is to use the convert method of a class instance.\n\n Examples\n --------\n >>> from numpy import polynomial as P\n >>> c = P.Chebyshev(range(4))\n >>> c\n Chebyshev([0., 1., 2., 3.], domain=[-1., 1.], window=[-1., 1.], symbol='x')\n >>> p = c.convert(kind=P.Polynomial)\n >>> p\n Polynomial([-2., -8., 4., 12.], domain=[-1., 1.], window=[-1., 1.], ...\n >>> P.chebyshev.cheb2poly(range(4))\n array([-2., -8., 4., 12.])\n\n """\n from .polynomial import polyadd, polymulx, polysub\n\n [c] = pu.as_series([c])\n n = len(c)\n if n < 3:\n return c\n else:\n c0 = c[-2]\n c1 = c[-1]\n # i is the current degree of c1\n for i in range(n - 1, 1, -1):\n tmp = c0\n c0 = polysub(c[i - 2], c1)\n c1 = polyadd(tmp, polymulx(c1) * 2)\n return polyadd(c0, polymulx(c1))\n\n\n#\n# These are constant arrays are of integer type so as to be compatible\n# with the widest range of other types, such as Decimal.\n#\n\n# Chebyshev default domain.\nchebdomain = np.array([-1., 1.])\n\n# Chebyshev coefficients representing zero.\nchebzero = np.array([0])\n\n# Chebyshev coefficients representing one.\nchebone = np.array([1])\n\n# Chebyshev coefficients representing the identity x.\nchebx = np.array([0, 1])\n\n\ndef chebline(off, scl):\n """\n Chebyshev series whose graph is a straight line.\n\n Parameters\n ----------\n off, scl : scalars\n The specified line is given by ``off + scl*x``.\n\n Returns\n -------\n y : ndarray\n This module's representation of the Chebyshev series for\n ``off + scl*x``.\n\n See Also\n --------\n numpy.polynomial.polynomial.polyline\n numpy.polynomial.legendre.legline\n numpy.polynomial.laguerre.lagline\n numpy.polynomial.hermite.hermline\n numpy.polynomial.hermite_e.hermeline\n\n Examples\n --------\n >>> import numpy.polynomial.chebyshev as C\n >>> C.chebline(3,2)\n array([3, 2])\n >>> C.chebval(-3, C.chebline(3,2)) # should be -3\n -3.0\n\n """\n if scl != 0:\n return np.array([off, scl])\n else:\n return np.array([off])\n\n\ndef chebfromroots(roots):\n """\n Generate a Chebyshev series with given roots.\n\n The function returns the coefficients of the polynomial\n\n .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),\n\n in Chebyshev form, where the :math:`r_n` are the roots specified in\n `roots`. If a zero has multiplicity n, then it must appear in `roots`\n n times. For instance, if 2 is a root of multiplicity three and 3 is a\n root of multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3].\n The roots can appear in any order.\n\n If the returned coefficients are `c`, then\n\n .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x)\n\n The coefficient of the last term is not generally 1 for monic\n polynomials in Chebyshev form.\n\n Parameters\n ----------\n roots : array_like\n Sequence containing the roots.\n\n Returns\n -------\n out : ndarray\n 1-D array of coefficients. If all roots are real then `out` is a\n real array, if some of the roots are complex, then `out` is complex\n even if all the coefficients in the result are real (see Examples\n below).\n\n See Also\n --------\n numpy.polynomial.polynomial.polyfromroots\n numpy.polynomial.legendre.legfromroots\n numpy.polynomial.laguerre.lagfromroots\n numpy.polynomial.hermite.hermfromroots\n numpy.polynomial.hermite_e.hermefromroots\n\n Examples\n --------\n >>> import numpy.polynomial.chebyshev as C\n >>> C.chebfromroots((-1,0,1)) # x^3 - x relative to the standard basis\n array([ 0. , -0.25, 0. , 0.25])\n >>> j = complex(0,1)\n >>> C.chebfromroots((-j,j)) # x^2 + 1 relative to the standard basis\n array([1.5+0.j, 0. +0.j, 0.5+0.j])\n\n """\n return pu._fromroots(chebline, chebmul, roots)\n\n\ndef chebadd(c1, c2):\n """\n Add one Chebyshev series to another.\n\n Returns the sum of two Chebyshev series `c1` + `c2`. The arguments\n are sequences of coefficients ordered from lowest order term to\n highest, i.e., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Chebyshev series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Array representing the Chebyshev series of their sum.\n\n See Also\n --------\n chebsub, chebmulx, chebmul, chebdiv, chebpow\n\n Notes\n -----\n Unlike multiplication, division, etc., the sum of two Chebyshev series\n is a Chebyshev series (without having to "reproject" the result onto\n the basis set) so addition, just like that of "standard" polynomials,\n is simply "component-wise."\n\n Examples\n --------\n >>> from numpy.polynomial import chebyshev as C\n >>> c1 = (1,2,3)\n >>> c2 = (3,2,1)\n >>> C.chebadd(c1,c2)\n array([4., 4., 4.])\n\n """\n return pu._add(c1, c2)\n\n\ndef chebsub(c1, c2):\n """\n Subtract one Chebyshev series from another.\n\n Returns the difference of two Chebyshev series `c1` - `c2`. The\n sequences of coefficients are from lowest order term to highest, i.e.,\n [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Chebyshev series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Of Chebyshev series coefficients representing their difference.\n\n See Also\n --------\n chebadd, chebmulx, chebmul, chebdiv, chebpow\n\n Notes\n -----\n Unlike multiplication, division, etc., the difference of two Chebyshev\n series is a Chebyshev series (without having to "reproject" the result\n onto the basis set) so subtraction, just like that of "standard"\n polynomials, is simply "component-wise."\n\n Examples\n --------\n >>> from numpy.polynomial import chebyshev as C\n >>> c1 = (1,2,3)\n >>> c2 = (3,2,1)\n >>> C.chebsub(c1,c2)\n array([-2., 0., 2.])\n >>> C.chebsub(c2,c1) # -C.chebsub(c1,c2)\n array([ 2., 0., -2.])\n\n """\n return pu._sub(c1, c2)\n\n\ndef chebmulx(c):\n """Multiply a Chebyshev series by x.\n\n Multiply the polynomial `c` by x, where x is the independent\n variable.\n\n\n Parameters\n ----------\n c : array_like\n 1-D array of Chebyshev series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Array representing the result of the multiplication.\n\n See Also\n --------\n chebadd, chebsub, chebmul, chebdiv, chebpow\n\n Examples\n --------\n >>> from numpy.polynomial import chebyshev as C\n >>> C.chebmulx([1,2,3])\n array([1. , 2.5, 1. , 1.5])\n\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n # The zero series needs special treatment\n if len(c) == 1 and c[0] == 0:\n return c\n\n prd = np.empty(len(c) + 1, dtype=c.dtype)\n prd[0] = c[0] * 0\n prd[1] = c[0]\n if len(c) > 1:\n tmp = c[1:] / 2\n prd[2:] = tmp\n prd[0:-2] += tmp\n return prd\n\n\ndef chebmul(c1, c2):\n """\n Multiply one Chebyshev series by another.\n\n Returns the product of two Chebyshev series `c1` * `c2`. The arguments\n are sequences of coefficients, from lowest order "term" to highest,\n e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Chebyshev series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Of Chebyshev series coefficients representing their product.\n\n See Also\n --------\n chebadd, chebsub, chebmulx, chebdiv, chebpow\n\n Notes\n -----\n In general, the (polynomial) product of two C-series results in terms\n that are not in the Chebyshev polynomial basis set. Thus, to express\n the product as a C-series, it is typically necessary to "reproject"\n the product onto said basis set, which typically produces\n "unintuitive live" (but correct) results; see Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial import chebyshev as C\n >>> c1 = (1,2,3)\n >>> c2 = (3,2,1)\n >>> C.chebmul(c1,c2) # multiplication requires "reprojection"\n array([ 6.5, 12. , 12. , 4. , 1.5])\n\n """\n # c1, c2 are trimmed copies\n [c1, c2] = pu.as_series([c1, c2])\n z1 = _cseries_to_zseries(c1)\n z2 = _cseries_to_zseries(c2)\n prd = _zseries_mul(z1, z2)\n ret = _zseries_to_cseries(prd)\n return pu.trimseq(ret)\n\n\ndef chebdiv(c1, c2):\n """\n Divide one Chebyshev series by another.\n\n Returns the quotient-with-remainder of two Chebyshev series\n `c1` / `c2`. The arguments are sequences of coefficients from lowest\n order "term" to highest, e.g., [1,2,3] represents the series\n ``T_0 + 2*T_1 + 3*T_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Chebyshev series coefficients ordered from low to\n high.\n\n Returns\n -------\n [quo, rem] : ndarrays\n Of Chebyshev series coefficients representing the quotient and\n remainder.\n\n See Also\n --------\n chebadd, chebsub, chebmulx, chebmul, chebpow\n\n Notes\n -----\n In general, the (polynomial) division of one C-series by another\n results in quotient and remainder terms that are not in the Chebyshev\n polynomial basis set. Thus, to express these results as C-series, it\n is typically necessary to "reproject" the results onto said basis\n set, which typically produces "unintuitive" (but correct) results;\n see Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial import chebyshev as C\n >>> c1 = (1,2,3)\n >>> c2 = (3,2,1)\n >>> C.chebdiv(c1,c2) # quotient "intuitive," remainder not\n (array([3.]), array([-8., -4.]))\n >>> c2 = (0,1,2,3)\n >>> C.chebdiv(c2,c1) # neither "intuitive"\n (array([0., 2.]), array([-2., -4.]))\n\n """\n # c1, c2 are trimmed copies\n [c1, c2] = pu.as_series([c1, c2])\n if c2[-1] == 0:\n raise ZeroDivisionError # FIXME: add message with details to exception\n\n # note: this is more efficient than `pu._div(chebmul, c1, c2)`\n lc1 = len(c1)\n lc2 = len(c2)\n if lc1 < lc2:\n return c1[:1] * 0, c1\n elif lc2 == 1:\n return c1 / c2[-1], c1[:1] * 0\n else:\n z1 = _cseries_to_zseries(c1)\n z2 = _cseries_to_zseries(c2)\n quo, rem = _zseries_div(z1, z2)\n quo = pu.trimseq(_zseries_to_cseries(quo))\n rem = pu.trimseq(_zseries_to_cseries(rem))\n return quo, rem\n\n\ndef chebpow(c, pow, maxpower=16):\n """Raise a Chebyshev series to a power.\n\n Returns the Chebyshev series `c` raised to the power `pow`. The\n argument `c` is a sequence of coefficients ordered from low to high.\n i.e., [1,2,3] is the series ``T_0 + 2*T_1 + 3*T_2.``\n\n Parameters\n ----------\n c : array_like\n 1-D array of Chebyshev series coefficients ordered from low to\n high.\n pow : integer\n Power to which the series will be raised\n maxpower : integer, optional\n Maximum power allowed. This is mainly to limit growth of the series\n to unmanageable size. Default is 16\n\n Returns\n -------\n coef : ndarray\n Chebyshev series of power.\n\n See Also\n --------\n chebadd, chebsub, chebmulx, chebmul, chebdiv\n\n Examples\n --------\n >>> from numpy.polynomial import chebyshev as C\n >>> C.chebpow([1, 2, 3, 4], 2)\n array([15.5, 22. , 16. , ..., 12.5, 12. , 8. ])\n\n """\n # note: this is more efficient than `pu._pow(chebmul, c1, c2)`, as it\n # avoids converting between z and c series repeatedly\n\n # c is a trimmed copy\n [c] = pu.as_series([c])\n power = int(pow)\n if power != pow or power < 0:\n raise ValueError("Power must be a non-negative integer.")\n elif maxpower is not None and power > maxpower:\n raise ValueError("Power is too large")\n elif power == 0:\n return np.array([1], dtype=c.dtype)\n elif power == 1:\n return c\n else:\n # This can be made more efficient by using powers of two\n # in the usual way.\n zs = _cseries_to_zseries(c)\n prd = zs\n for i in range(2, power + 1):\n prd = np.convolve(prd, zs)\n return _zseries_to_cseries(prd)\n\n\ndef chebder(c, m=1, scl=1, axis=0):\n """\n Differentiate a Chebyshev series.\n\n Returns the Chebyshev series coefficients `c` differentiated `m` times\n along `axis`. At each iteration the result is multiplied by `scl` (the\n scaling factor is for use in a linear change of variable). The argument\n `c` is an array of coefficients from low to high degree along each\n axis, e.g., [1,2,3] represents the series ``1*T_0 + 2*T_1 + 3*T_2``\n while [[1,2],[1,2]] represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) +\n 2*T_0(x)*T_1(y) + 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is\n ``y``.\n\n Parameters\n ----------\n c : array_like\n Array of Chebyshev series coefficients. If c is multidimensional\n the different axis correspond to different variables with the\n degree in each axis given by the corresponding index.\n m : int, optional\n Number of derivatives taken, must be non-negative. (Default: 1)\n scl : scalar, optional\n Each differentiation is multiplied by `scl`. The end result is\n multiplication by ``scl**m``. This is for use in a linear change of\n variable. (Default: 1)\n axis : int, optional\n Axis over which the derivative is taken. (Default: 0).\n\n Returns\n -------\n der : ndarray\n Chebyshev series of the derivative.\n\n See Also\n --------\n chebint\n\n Notes\n -----\n In general, the result of differentiating a C-series needs to be\n "reprojected" onto the C-series basis set. Thus, typically, the\n result of this function is "unintuitive," albeit correct; see Examples\n section below.\n\n Examples\n --------\n >>> from numpy.polynomial import chebyshev as C\n >>> c = (1,2,3,4)\n >>> C.chebder(c)\n array([14., 12., 24.])\n >>> C.chebder(c,3)\n array([96.])\n >>> C.chebder(c,scl=-1)\n array([-14., -12., -24.])\n >>> C.chebder(c,2,-1)\n array([12., 96.])\n\n """\n c = np.array(c, ndmin=1, copy=True)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n cnt = pu._as_int(m, "the order of derivation")\n iaxis = pu._as_int(axis, "the axis")\n if cnt < 0:\n raise ValueError("The order of derivation must be non-negative")\n iaxis = normalize_axis_index(iaxis, c.ndim)\n\n if cnt == 0:\n return c\n\n c = np.moveaxis(c, iaxis, 0)\n n = len(c)\n if cnt >= n:\n c = c[:1] * 0\n else:\n for i in range(cnt):\n n = n - 1\n c *= scl\n der = np.empty((n,) + c.shape[1:], dtype=c.dtype)\n for j in range(n, 2, -1):\n der[j - 1] = (2 * j) * c[j]\n c[j - 2] += (j * c[j]) / (j - 2)\n if n > 1:\n der[1] = 4 * c[2]\n der[0] = c[1]\n c = der\n c = np.moveaxis(c, 0, iaxis)\n return c\n\n\ndef chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0):\n """\n Integrate a Chebyshev series.\n\n Returns the Chebyshev series coefficients `c` integrated `m` times from\n `lbnd` along `axis`. At each iteration the resulting series is\n **multiplied** by `scl` and an integration constant, `k`, is added.\n The scaling factor is for use in a linear change of variable. ("Buyer\n beware": note that, depending on what one is doing, one may want `scl`\n to be the reciprocal of what one might expect; for more information,\n see the Notes section below.) The argument `c` is an array of\n coefficients from low to high degree along each axis, e.g., [1,2,3]\n represents the series ``T_0 + 2*T_1 + 3*T_2`` while [[1,2],[1,2]]\n represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) +\n 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.\n\n Parameters\n ----------\n c : array_like\n Array of Chebyshev series coefficients. If c is multidimensional\n the different axis correspond to different variables with the\n degree in each axis given by the corresponding index.\n m : int, optional\n Order of integration, must be positive. (Default: 1)\n k : {[], list, scalar}, optional\n Integration constant(s). The value of the first integral at zero\n is the first value in the list, the value of the second integral\n at zero is the second value, etc. If ``k == []`` (the default),\n all constants are set to zero. If ``m == 1``, a single scalar can\n be given instead of a list.\n lbnd : scalar, optional\n The lower bound of the integral. (Default: 0)\n scl : scalar, optional\n Following each integration the result is *multiplied* by `scl`\n before the integration constant is added. (Default: 1)\n axis : int, optional\n Axis over which the integral is taken. (Default: 0).\n\n Returns\n -------\n S : ndarray\n C-series coefficients of the integral.\n\n Raises\n ------\n ValueError\n If ``m < 1``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or\n ``np.ndim(scl) != 0``.\n\n See Also\n --------\n chebder\n\n Notes\n -----\n Note that the result of each integration is *multiplied* by `scl`.\n Why is this important to note? Say one is making a linear change of\n variable :math:`u = ax + b` in an integral relative to `x`. Then\n :math:`dx = du/a`, so one will need to set `scl` equal to\n :math:`1/a`- perhaps not what one would have first thought.\n\n Also note that, in general, the result of integrating a C-series needs\n to be "reprojected" onto the C-series basis set. Thus, typically,\n the result of this function is "unintuitive," albeit correct; see\n Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial import chebyshev as C\n >>> c = (1,2,3)\n >>> C.chebint(c)\n array([ 0.5, -0.5, 0.5, 0.5])\n >>> C.chebint(c,3)\n array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667, # may vary\n 0.00625 ])\n >>> C.chebint(c, k=3)\n array([ 3.5, -0.5, 0.5, 0.5])\n >>> C.chebint(c,lbnd=-2)\n array([ 8.5, -0.5, 0.5, 0.5])\n >>> C.chebint(c,scl=-2)\n array([-1., 1., -1., -1.])\n\n """\n c = np.array(c, ndmin=1, copy=True)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n if not np.iterable(k):\n k = [k]\n cnt = pu._as_int(m, "the order of integration")\n iaxis = pu._as_int(axis, "the axis")\n if cnt < 0:\n raise ValueError("The order of integration must be non-negative")\n if len(k) > cnt:\n raise ValueError("Too many integration constants")\n if np.ndim(lbnd) != 0:\n raise ValueError("lbnd must be a scalar.")\n if np.ndim(scl) != 0:\n raise ValueError("scl must be a scalar.")\n iaxis = normalize_axis_index(iaxis, c.ndim)\n\n if cnt == 0:\n return c\n\n c = np.moveaxis(c, iaxis, 0)\n k = list(k) + [0] * (cnt - len(k))\n for i in range(cnt):\n n = len(c)\n c *= scl\n if n == 1 and np.all(c[0] == 0):\n c[0] += k[i]\n else:\n tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)\n tmp[0] = c[0] * 0\n tmp[1] = c[0]\n if n > 1:\n tmp[2] = c[1] / 4\n for j in range(2, n):\n tmp[j + 1] = c[j] / (2 * (j + 1))\n tmp[j - 1] -= c[j] / (2 * (j - 1))\n tmp[0] += k[i] - chebval(lbnd, tmp)\n c = tmp\n c = np.moveaxis(c, 0, iaxis)\n return c\n\n\ndef chebval(x, c, tensor=True):\n """\n Evaluate a Chebyshev series at points x.\n\n If `c` is of length `n + 1`, this function returns the value:\n\n .. math:: p(x) = c_0 * T_0(x) + c_1 * T_1(x) + ... + c_n * T_n(x)\n\n The parameter `x` is converted to an array only if it is a tuple or a\n list, otherwise it is treated as a scalar. In either case, either `x`\n or its elements must support multiplication and addition both with\n themselves and with the elements of `c`.\n\n If `c` is a 1-D array, then ``p(x)`` will have the same shape as `x`. If\n `c` is multidimensional, then the shape of the result depends on the\n value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +\n x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that\n scalars have shape (,).\n\n Trailing zeros in the coefficients will be used in the evaluation, so\n they should be avoided if efficiency is a concern.\n\n Parameters\n ----------\n x : array_like, compatible object\n If `x` is a list or tuple, it is converted to an ndarray, otherwise\n it is left unchanged and treated as a scalar. In either case, `x`\n or its elements must support addition and multiplication with\n themselves and with the elements of `c`.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree n are contained in c[n]. If `c` is multidimensional the\n remaining indices enumerate multiple polynomials. In the two\n dimensional case the coefficients may be thought of as stored in\n the columns of `c`.\n tensor : boolean, optional\n If True, the shape of the coefficient array is extended with ones\n on the right, one for each dimension of `x`. Scalars have dimension 0\n for this action. The result is that every column of coefficients in\n `c` is evaluated for every element of `x`. If False, `x` is broadcast\n over the columns of `c` for the evaluation. This keyword is useful\n when `c` is multidimensional. The default value is True.\n\n Returns\n -------\n values : ndarray, algebra_like\n The shape of the return value is described above.\n\n See Also\n --------\n chebval2d, chebgrid2d, chebval3d, chebgrid3d\n\n Notes\n -----\n The evaluation uses Clenshaw recursion, aka synthetic division.\n\n """\n c = np.array(c, ndmin=1, copy=True)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n if isinstance(x, (tuple, list)):\n x = np.asarray(x)\n if isinstance(x, np.ndarray) and tensor:\n c = c.reshape(c.shape + (1,) * x.ndim)\n\n if len(c) == 1:\n c0 = c[0]\n c1 = 0\n elif len(c) == 2:\n c0 = c[0]\n c1 = c[1]\n else:\n x2 = 2 * x\n c0 = c[-2]\n c1 = c[-1]\n for i in range(3, len(c) + 1):\n tmp = c0\n c0 = c[-i] - c1\n c1 = tmp + c1 * x2\n return c0 + c1 * x\n\n\ndef chebval2d(x, y, c):\n """\n Evaluate a 2-D Chebyshev series at points (x, y).\n\n This function returns the values:\n\n .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * T_i(x) * T_j(y)\n\n The parameters `x` and `y` are converted to arrays only if they are\n tuples or a lists, otherwise they are treated as a scalars and they\n must have the same shape after conversion. In either case, either `x`\n and `y` or their elements must support multiplication and addition both\n with themselves and with the elements of `c`.\n\n If `c` is a 1-D array a one is implicitly appended to its shape to make\n it 2-D. The shape of the result will be c.shape[2:] + x.shape.\n\n Parameters\n ----------\n x, y : array_like, compatible objects\n The two dimensional series is evaluated at the points ``(x, y)``,\n where `x` and `y` must have the same shape. If `x` or `y` is a list\n or tuple, it is first converted to an ndarray, otherwise it is left\n unchanged and if it isn't an ndarray it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term\n of multi-degree i,j is contained in ``c[i,j]``. If `c` has\n dimension greater than 2 the remaining indices enumerate multiple\n sets of coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional Chebyshev series at points formed\n from pairs of corresponding values from `x` and `y`.\n\n See Also\n --------\n chebval, chebgrid2d, chebval3d, chebgrid3d\n """\n return pu._valnd(chebval, c, x, y)\n\n\ndef chebgrid2d(x, y, c):\n """\n Evaluate a 2-D Chebyshev series on the Cartesian product of x and y.\n\n This function returns the values:\n\n .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * T_i(a) * T_j(b),\n\n where the points `(a, b)` consist of all pairs formed by taking\n `a` from `x` and `b` from `y`. The resulting points form a grid with\n `x` in the first dimension and `y` in the second.\n\n The parameters `x` and `y` are converted to arrays only if they are\n tuples or a lists, otherwise they are treated as a scalars. In either\n case, either `x` and `y` or their elements must support multiplication\n and addition both with themselves and with the elements of `c`.\n\n If `c` has fewer than two dimensions, ones are implicitly appended to\n its shape to make it 2-D. The shape of the result will be c.shape[2:] +\n x.shape + y.shape.\n\n Parameters\n ----------\n x, y : array_like, compatible objects\n The two dimensional series is evaluated at the points in the\n Cartesian product of `x` and `y`. If `x` or `y` is a list or\n tuple, it is first converted to an ndarray, otherwise it is left\n unchanged and, if it isn't an ndarray, it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term of\n multi-degree i,j is contained in ``c[i,j]``. If `c` has dimension\n greater than two the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional Chebyshev series at points in the\n Cartesian product of `x` and `y`.\n\n See Also\n --------\n chebval, chebval2d, chebval3d, chebgrid3d\n """\n return pu._gridnd(chebval, c, x, y)\n\n\ndef chebval3d(x, y, z, c):\n """\n Evaluate a 3-D Chebyshev series at points (x, y, z).\n\n This function returns the values:\n\n .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * T_i(x) * T_j(y) * T_k(z)\n\n The parameters `x`, `y`, and `z` are converted to arrays only if\n they are tuples or a lists, otherwise they are treated as a scalars and\n they must have the same shape after conversion. In either case, either\n `x`, `y`, and `z` or their elements must support multiplication and\n addition both with themselves and with the elements of `c`.\n\n If `c` has fewer than 3 dimensions, ones are implicitly appended to its\n shape to make it 3-D. The shape of the result will be c.shape[3:] +\n x.shape.\n\n Parameters\n ----------\n x, y, z : array_like, compatible object\n The three dimensional series is evaluated at the points\n ``(x, y, z)``, where `x`, `y`, and `z` must have the same shape. If\n any of `x`, `y`, or `z` is a list or tuple, it is first converted\n to an ndarray, otherwise it is left unchanged and if it isn't an\n ndarray it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term of\n multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension\n greater than 3 the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the multidimensional polynomial on points formed with\n triples of corresponding values from `x`, `y`, and `z`.\n\n See Also\n --------\n chebval, chebval2d, chebgrid2d, chebgrid3d\n """\n return pu._valnd(chebval, c, x, y, z)\n\n\ndef chebgrid3d(x, y, z, c):\n """\n Evaluate a 3-D Chebyshev series on the Cartesian product of x, y, and z.\n\n This function returns the values:\n\n .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * T_i(a) * T_j(b) * T_k(c)\n\n where the points ``(a, b, c)`` consist of all triples formed by taking\n `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form\n a grid with `x` in the first dimension, `y` in the second, and `z` in\n the third.\n\n The parameters `x`, `y`, and `z` are converted to arrays only if they\n are tuples or a lists, otherwise they are treated as a scalars. In\n either case, either `x`, `y`, and `z` or their elements must support\n multiplication and addition both with themselves and with the elements\n of `c`.\n\n If `c` has fewer than three dimensions, ones are implicitly appended to\n its shape to make it 3-D. The shape of the result will be c.shape[3:] +\n x.shape + y.shape + z.shape.\n\n Parameters\n ----------\n x, y, z : array_like, compatible objects\n The three dimensional series is evaluated at the points in the\n Cartesian product of `x`, `y`, and `z`. If `x`, `y`, or `z` is a\n list or tuple, it is first converted to an ndarray, otherwise it is\n left unchanged and, if it isn't an ndarray, it is treated as a\n scalar.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree i,j are contained in ``c[i,j]``. If `c` has dimension\n greater than two the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points in the Cartesian\n product of `x` and `y`.\n\n See Also\n --------\n chebval, chebval2d, chebgrid2d, chebval3d\n """\n return pu._gridnd(chebval, c, x, y, z)\n\n\ndef chebvander(x, deg):\n """Pseudo-Vandermonde matrix of given degree.\n\n Returns the pseudo-Vandermonde matrix of degree `deg` and sample points\n `x`. The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., i] = T_i(x),\n\n where ``0 <= i <= deg``. The leading indices of `V` index the elements of\n `x` and the last index is the degree of the Chebyshev polynomial.\n\n If `c` is a 1-D array of coefficients of length ``n + 1`` and `V` is the\n matrix ``V = chebvander(x, n)``, then ``np.dot(V, c)`` and\n ``chebval(x, c)`` are the same up to roundoff. This equivalence is\n useful both for least squares fitting and for the evaluation of a large\n number of Chebyshev series of the same degree and sample points.\n\n Parameters\n ----------\n x : array_like\n Array of points. The dtype is converted to float64 or complex128\n depending on whether any of the elements are complex. If `x` is\n scalar it is converted to a 1-D array.\n deg : int\n Degree of the resulting matrix.\n\n Returns\n -------\n vander : ndarray\n The pseudo Vandermonde matrix. The shape of the returned matrix is\n ``x.shape + (deg + 1,)``, where The last index is the degree of the\n corresponding Chebyshev polynomial. The dtype will be the same as\n the converted `x`.\n\n """\n ideg = pu._as_int(deg, "deg")\n if ideg < 0:\n raise ValueError("deg must be non-negative")\n\n x = np.array(x, copy=None, ndmin=1) + 0.0\n dims = (ideg + 1,) + x.shape\n dtyp = x.dtype\n v = np.empty(dims, dtype=dtyp)\n # Use forward recursion to generate the entries.\n v[0] = x * 0 + 1\n if ideg > 0:\n x2 = 2 * x\n v[1] = x\n for i in range(2, ideg + 1):\n v[i] = v[i - 1] * x2 - v[i - 2]\n return np.moveaxis(v, 0, -1)\n\n\ndef chebvander2d(x, y, deg):\n """Pseudo-Vandermonde matrix of given degrees.\n\n Returns the pseudo-Vandermonde matrix of degrees `deg` and sample\n points ``(x, y)``. The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., (deg[1] + 1)*i + j] = T_i(x) * T_j(y),\n\n where ``0 <= i <= deg[0]`` and ``0 <= j <= deg[1]``. The leading indices of\n `V` index the points ``(x, y)`` and the last index encodes the degrees of\n the Chebyshev polynomials.\n\n If ``V = chebvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`\n correspond to the elements of a 2-D coefficient array `c` of shape\n (xdeg + 1, ydeg + 1) in the order\n\n .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...\n\n and ``np.dot(V, c.flat)`` and ``chebval2d(x, y, c)`` will be the same\n up to roundoff. This equivalence is useful both for least squares\n fitting and for the evaluation of a large number of 2-D Chebyshev\n series of the same degrees and sample points.\n\n Parameters\n ----------\n x, y : array_like\n Arrays of point coordinates, all of the same shape. The dtypes\n will be converted to either float64 or complex128 depending on\n whether any of the elements are complex. Scalars are converted to\n 1-D arrays.\n deg : list of ints\n List of maximum degrees of the form [x_deg, y_deg].\n\n Returns\n -------\n vander2d : ndarray\n The shape of the returned matrix is ``x.shape + (order,)``, where\n :math:`order = (deg[0]+1)*(deg[1]+1)`. The dtype will be the same\n as the converted `x` and `y`.\n\n See Also\n --------\n chebvander, chebvander3d, chebval2d, chebval3d\n """\n return pu._vander_nd_flat((chebvander, chebvander), (x, y), deg)\n\n\ndef chebvander3d(x, y, z, deg):\n """Pseudo-Vandermonde matrix of given degrees.\n\n Returns the pseudo-Vandermonde matrix of degrees `deg` and sample\n points ``(x, y, z)``. If `l`, `m`, `n` are the given degrees in `x`, `y`, `z`,\n then The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = T_i(x)*T_j(y)*T_k(z),\n\n where ``0 <= i <= l``, ``0 <= j <= m``, and ``0 <= j <= n``. The leading\n indices of `V` index the points ``(x, y, z)`` and the last index encodes\n the degrees of the Chebyshev polynomials.\n\n If ``V = chebvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns\n of `V` correspond to the elements of a 3-D coefficient array `c` of\n shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order\n\n .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...\n\n and ``np.dot(V, c.flat)`` and ``chebval3d(x, y, z, c)`` will be the\n same up to roundoff. This equivalence is useful both for least squares\n fitting and for the evaluation of a large number of 3-D Chebyshev\n series of the same degrees and sample points.\n\n Parameters\n ----------\n x, y, z : array_like\n Arrays of point coordinates, all of the same shape. The dtypes will\n be converted to either float64 or complex128 depending on whether\n any of the elements are complex. Scalars are converted to 1-D\n arrays.\n deg : list of ints\n List of maximum degrees of the form [x_deg, y_deg, z_deg].\n\n Returns\n -------\n vander3d : ndarray\n The shape of the returned matrix is ``x.shape + (order,)``, where\n :math:`order = (deg[0]+1)*(deg[1]+1)*(deg[2]+1)`. The dtype will\n be the same as the converted `x`, `y`, and `z`.\n\n See Also\n --------\n chebvander, chebvander3d, chebval2d, chebval3d\n """\n return pu._vander_nd_flat((chebvander, chebvander, chebvander), (x, y, z), deg)\n\n\ndef chebfit(x, y, deg, rcond=None, full=False, w=None):\n """\n Least squares fit of Chebyshev series to data.\n\n Return the coefficients of a Chebyshev series of degree `deg` that is the\n least squares fit to the data values `y` given at points `x`. If `y` is\n 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple\n fits are done, one for each column of `y`, and the resulting\n coefficients are stored in the corresponding columns of a 2-D return.\n The fitted polynomial(s) are in the form\n\n .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x),\n\n where `n` is `deg`.\n\n Parameters\n ----------\n x : array_like, shape (M,)\n x-coordinates of the M sample points ``(x[i], y[i])``.\n y : array_like, shape (M,) or (M, K)\n y-coordinates of the sample points. Several data sets of sample\n points sharing the same x-coordinates can be fitted at once by\n passing in a 2D-array that contains one dataset per column.\n deg : int or 1-D array_like\n Degree(s) of the fitting polynomials. If `deg` is a single integer,\n all terms up to and including the `deg`'th term are included in the\n fit. For NumPy versions >= 1.11.0 a list of integers specifying the\n degrees of the terms to include may be used instead.\n rcond : float, optional\n Relative condition number of the fit. Singular values smaller than\n this relative to the largest singular value will be ignored. The\n default value is ``len(x)*eps``, where eps is the relative precision of\n the float type, about 2e-16 in most cases.\n full : bool, optional\n Switch determining nature of return value. When it is False (the\n default) just the coefficients are returned, when True diagnostic\n information from the singular value decomposition is also returned.\n w : array_like, shape (`M`,), optional\n Weights. If not None, the weight ``w[i]`` applies to the unsquared\n residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are\n chosen so that the errors of the products ``w[i]*y[i]`` all have the\n same variance. When using inverse-variance weighting, use\n ``w[i] = 1/sigma(y[i])``. The default value is None.\n\n Returns\n -------\n coef : ndarray, shape (M,) or (M, K)\n Chebyshev coefficients ordered from low to high. If `y` was 2-D,\n the coefficients for the data in column k of `y` are in column\n `k`.\n\n [residuals, rank, singular_values, rcond] : list\n These values are only returned if ``full == True``\n\n - residuals -- sum of squared residuals of the least squares fit\n - rank -- the numerical rank of the scaled Vandermonde matrix\n - singular_values -- singular values of the scaled Vandermonde matrix\n - rcond -- value of `rcond`.\n\n For more details, see `numpy.linalg.lstsq`.\n\n Warns\n -----\n RankWarning\n The rank of the coefficient matrix in the least-squares fit is\n deficient. The warning is only raised if ``full == False``. The\n warnings can be turned off by\n\n >>> import warnings\n >>> warnings.simplefilter('ignore', np.exceptions.RankWarning)\n\n See Also\n --------\n numpy.polynomial.polynomial.polyfit\n numpy.polynomial.legendre.legfit\n numpy.polynomial.laguerre.lagfit\n numpy.polynomial.hermite.hermfit\n numpy.polynomial.hermite_e.hermefit\n chebval : Evaluates a Chebyshev series.\n chebvander : Vandermonde matrix of Chebyshev series.\n chebweight : Chebyshev weight function.\n numpy.linalg.lstsq : Computes a least-squares fit from the matrix.\n scipy.interpolate.UnivariateSpline : Computes spline fits.\n\n Notes\n -----\n The solution is the coefficients of the Chebyshev series `p` that\n minimizes the sum of the weighted squared errors\n\n .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,\n\n where :math:`w_j` are the weights. This problem is solved by setting up\n as the (typically) overdetermined matrix equation\n\n .. math:: V(x) * c = w * y,\n\n where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the\n coefficients to be solved for, `w` are the weights, and `y` are the\n observed values. This equation is then solved using the singular value\n decomposition of `V`.\n\n If some of the singular values of `V` are so small that they are\n neglected, then a `~exceptions.RankWarning` will be issued. This means that\n the coefficient values may be poorly determined. Using a lower order fit\n will usually get rid of the warning. The `rcond` parameter can also be\n set to a value smaller than its default, but the resulting fit may be\n spurious and have large contributions from roundoff error.\n\n Fits using Chebyshev series are usually better conditioned than fits\n using power series, but much can depend on the distribution of the\n sample points and the smoothness of the data. If the quality of the fit\n is inadequate splines may be a good alternative.\n\n References\n ----------\n .. [1] Wikipedia, "Curve fitting",\n https://en.wikipedia.org/wiki/Curve_fitting\n\n Examples\n --------\n\n """\n return pu._fit(chebvander, x, y, deg, rcond, full, w)\n\n\ndef chebcompanion(c):\n """Return the scaled companion matrix of c.\n\n The basis polynomials are scaled so that the companion matrix is\n symmetric when `c` is a Chebyshev basis polynomial. This provides\n better eigenvalue estimates than the unscaled case and for basis\n polynomials the eigenvalues are guaranteed to be real if\n `numpy.linalg.eigvalsh` is used to obtain them.\n\n Parameters\n ----------\n c : array_like\n 1-D array of Chebyshev series coefficients ordered from low to high\n degree.\n\n Returns\n -------\n mat : ndarray\n Scaled companion matrix of dimensions (deg, deg).\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n if len(c) < 2:\n raise ValueError('Series must have maximum degree of at least 1.')\n if len(c) == 2:\n return np.array([[-c[0] / c[1]]])\n\n n = len(c) - 1\n mat = np.zeros((n, n), dtype=c.dtype)\n scl = np.array([1.] + [np.sqrt(.5)] * (n - 1))\n top = mat.reshape(-1)[1::n + 1]\n bot = mat.reshape(-1)[n::n + 1]\n top[0] = np.sqrt(.5)\n top[1:] = 1 / 2\n bot[...] = top\n mat[:, -1] -= (c[:-1] / c[-1]) * (scl / scl[-1]) * .5\n return mat\n\n\ndef chebroots(c):\n """\n Compute the roots of a Chebyshev series.\n\n Return the roots (a.k.a. "zeros") of the polynomial\n\n .. math:: p(x) = \\sum_i c[i] * T_i(x).\n\n Parameters\n ----------\n c : 1-D array_like\n 1-D array of coefficients.\n\n Returns\n -------\n out : ndarray\n Array of the roots of the series. If all the roots are real,\n then `out` is also real, otherwise it is complex.\n\n See Also\n --------\n numpy.polynomial.polynomial.polyroots\n numpy.polynomial.legendre.legroots\n numpy.polynomial.laguerre.lagroots\n numpy.polynomial.hermite.hermroots\n numpy.polynomial.hermite_e.hermeroots\n\n Notes\n -----\n The root estimates are obtained as the eigenvalues of the companion\n matrix, Roots far from the origin of the complex plane may have large\n errors due to the numerical instability of the series for such\n values. Roots with multiplicity greater than 1 will also show larger\n errors as the value of the series near such points is relatively\n insensitive to errors in the roots. Isolated roots near the origin can\n be improved by a few iterations of Newton's method.\n\n The Chebyshev series basis polynomials aren't powers of `x` so the\n results of this function may seem unintuitive.\n\n Examples\n --------\n >>> import numpy.polynomial.chebyshev as cheb\n >>> cheb.chebroots((-1, 1,-1, 1)) # T3 - T2 + T1 - T0 has real roots\n array([ -5.00000000e-01, 2.60860684e-17, 1.00000000e+00]) # may vary\n\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n if len(c) < 2:\n return np.array([], dtype=c.dtype)\n if len(c) == 2:\n return np.array([-c[0] / c[1]])\n\n # rotated companion matrix reduces error\n m = chebcompanion(c)[::-1, ::-1]\n r = la.eigvals(m)\n r.sort()\n return r\n\n\ndef chebinterpolate(func, deg, args=()):\n """Interpolate a function at the Chebyshev points of the first kind.\n\n Returns the Chebyshev series that interpolates `func` at the Chebyshev\n points of the first kind in the interval [-1, 1]. The interpolating\n series tends to a minmax approximation to `func` with increasing `deg`\n if the function is continuous in the interval.\n\n Parameters\n ----------\n func : function\n The function to be approximated. It must be a function of a single\n variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are\n extra arguments passed in the `args` parameter.\n deg : int\n Degree of the interpolating polynomial\n args : tuple, optional\n Extra arguments to be used in the function call. Default is no extra\n arguments.\n\n Returns\n -------\n coef : ndarray, shape (deg + 1,)\n Chebyshev coefficients of the interpolating series ordered from low to\n high.\n\n Examples\n --------\n >>> import numpy.polynomial.chebyshev as C\n >>> C.chebinterpolate(lambda x: np.tanh(x) + 0.5, 8)\n array([ 5.00000000e-01, 8.11675684e-01, -9.86864911e-17,\n -5.42457905e-02, -2.71387850e-16, 4.51658839e-03,\n 2.46716228e-17, -3.79694221e-04, -3.26899002e-16])\n\n Notes\n -----\n The Chebyshev polynomials used in the interpolation are orthogonal when\n sampled at the Chebyshev points of the first kind. If it is desired to\n constrain some of the coefficients they can simply be set to the desired\n value after the interpolation, no new interpolation or fit is needed. This\n is especially useful if it is known apriori that some of coefficients are\n zero. For instance, if the function is even then the coefficients of the\n terms of odd degree in the result can be set to zero.\n\n """\n deg = np.asarray(deg)\n\n # check arguments.\n if deg.ndim > 0 or deg.dtype.kind not in 'iu' or deg.size == 0:\n raise TypeError("deg must be an int")\n if deg < 0:\n raise ValueError("expected deg >= 0")\n\n order = deg + 1\n xcheb = chebpts1(order)\n yfunc = func(xcheb, *args)\n m = chebvander(xcheb, deg)\n c = np.dot(m.T, yfunc)\n c[0] /= order\n c[1:] /= 0.5 * order\n\n return c\n\n\ndef chebgauss(deg):\n """\n Gauss-Chebyshev quadrature.\n\n Computes the sample points and weights for Gauss-Chebyshev quadrature.\n These sample points and weights will correctly integrate polynomials of\n degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with\n the weight function :math:`f(x) = 1/\\sqrt{1 - x^2}`.\n\n Parameters\n ----------\n deg : int\n Number of sample points and weights. It must be >= 1.\n\n Returns\n -------\n x : ndarray\n 1-D ndarray containing the sample points.\n y : ndarray\n 1-D ndarray containing the weights.\n\n Notes\n -----\n The results have only been tested up to degree 100, higher degrees may\n be problematic. For Gauss-Chebyshev there are closed form solutions for\n the sample points and weights. If n = `deg`, then\n\n .. math:: x_i = \\cos(\\pi (2 i - 1) / (2 n))\n\n .. math:: w_i = \\pi / n\n\n """\n ideg = pu._as_int(deg, "deg")\n if ideg <= 0:\n raise ValueError("deg must be a positive integer")\n\n x = np.cos(np.pi * np.arange(1, 2 * ideg, 2) / (2.0 * ideg))\n w = np.ones(ideg) * (np.pi / ideg)\n\n return x, w\n\n\ndef chebweight(x):\n """\n The weight function of the Chebyshev polynomials.\n\n The weight function is :math:`1/\\sqrt{1 - x^2}` and the interval of\n integration is :math:`[-1, 1]`. The Chebyshev polynomials are\n orthogonal, but not normalized, with respect to this weight function.\n\n Parameters\n ----------\n x : array_like\n Values at which the weight function will be computed.\n\n Returns\n -------\n w : ndarray\n The weight function at `x`.\n """\n w = 1. / (np.sqrt(1. + x) * np.sqrt(1. - x))\n return w\n\n\ndef chebpts1(npts):\n """\n Chebyshev points of the first kind.\n\n The Chebyshev points of the first kind are the points ``cos(x)``,\n where ``x = [pi*(k + .5)/npts for k in range(npts)]``.\n\n Parameters\n ----------\n npts : int\n Number of sample points desired.\n\n Returns\n -------\n pts : ndarray\n The Chebyshev points of the first kind.\n\n See Also\n --------\n chebpts2\n """\n _npts = int(npts)\n if _npts != npts:\n raise ValueError("npts must be integer")\n if _npts < 1:\n raise ValueError("npts must be >= 1")\n\n x = 0.5 * np.pi / _npts * np.arange(-_npts + 1, _npts + 1, 2)\n return np.sin(x)\n\n\ndef chebpts2(npts):\n """\n Chebyshev points of the second kind.\n\n The Chebyshev points of the second kind are the points ``cos(x)``,\n where ``x = [pi*k/(npts - 1) for k in range(npts)]`` sorted in ascending\n order.\n\n Parameters\n ----------\n npts : int\n Number of sample points desired.\n\n Returns\n -------\n pts : ndarray\n The Chebyshev points of the second kind.\n """\n _npts = int(npts)\n if _npts != npts:\n raise ValueError("npts must be integer")\n if _npts < 2:\n raise ValueError("npts must be >= 2")\n\n x = np.linspace(-np.pi, 0, _npts)\n return np.cos(x)\n\n\n#\n# Chebyshev series class\n#\n\nclass Chebyshev(ABCPolyBase):\n """A Chebyshev series class.\n\n The Chebyshev class provides the standard Python numerical methods\n '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the\n attributes and methods listed below.\n\n Parameters\n ----------\n coef : array_like\n Chebyshev coefficients in order of increasing degree, i.e.,\n ``(1, 2, 3)`` gives ``1*T_0(x) + 2*T_1(x) + 3*T_2(x)``.\n domain : (2,) array_like, optional\n Domain to use. The interval ``[domain[0], domain[1]]`` is mapped\n to the interval ``[window[0], window[1]]`` by shifting and scaling.\n The default value is [-1., 1.].\n window : (2,) array_like, optional\n Window, see `domain` for its use. The default value is [-1., 1.].\n symbol : str, optional\n Symbol used to represent the independent variable in string\n representations of the polynomial expression, e.g. for printing.\n The symbol must be a valid Python identifier. Default value is 'x'.\n\n .. versionadded:: 1.24\n\n """\n # Virtual Functions\n _add = staticmethod(chebadd)\n _sub = staticmethod(chebsub)\n _mul = staticmethod(chebmul)\n _div = staticmethod(chebdiv)\n _pow = staticmethod(chebpow)\n _val = staticmethod(chebval)\n _int = staticmethod(chebint)\n _der = staticmethod(chebder)\n _fit = staticmethod(chebfit)\n _line = staticmethod(chebline)\n _roots = staticmethod(chebroots)\n _fromroots = staticmethod(chebfromroots)\n\n @classmethod\n def interpolate(cls, func, deg, domain=None, args=()):\n """Interpolate a function at the Chebyshev points of the first kind.\n\n Returns the series that interpolates `func` at the Chebyshev points of\n the first kind scaled and shifted to the `domain`. The resulting series\n tends to a minmax approximation of `func` when the function is\n continuous in the domain.\n\n Parameters\n ----------\n func : function\n The function to be interpolated. It must be a function of a single\n variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are\n extra arguments passed in the `args` parameter.\n deg : int\n Degree of the interpolating polynomial.\n domain : {None, [beg, end]}, optional\n Domain over which `func` is interpolated. The default is None, in\n which case the domain is [-1, 1].\n args : tuple, optional\n Extra arguments to be used in the function call. Default is no\n extra arguments.\n\n Returns\n -------\n polynomial : Chebyshev instance\n Interpolating Chebyshev instance.\n\n Notes\n -----\n See `numpy.polynomial.chebinterpolate` for more details.\n\n """\n if domain is None:\n domain = cls.domain\n xfunc = lambda x: func(pu.mapdomain(x, cls.window, domain), *args)\n coef = chebinterpolate(xfunc, deg)\n return cls(coef, domain=domain)\n\n # Virtual properties\n domain = np.array(chebdomain)\n window = np.array(chebdomain)\n basis_name = 'T'\n | .venv\Lib\site-packages\numpy\polynomial\chebyshev.py | chebyshev.py | Python | 64,325 | 0.75 | 0.091363 | 0.022741 | node-utils | 957 | 2024-12-19T18:47:06.189735 | MIT | false | 5e6fa3d7ef2fc0ef005df2ad2259eac7 |
from collections.abc import Callable, Iterable\nfrom typing import Any, Concatenate, Final, Self, TypeVar, overload\nfrom typing import Literal as L\n\nimport numpy as np\nimport numpy.typing as npt\nfrom numpy._typing import _IntLike_co\n\nfrom ._polybase import ABCPolyBase\nfrom ._polytypes import (\n _Array1,\n _Array2,\n _CoefSeries,\n _FuncBinOp,\n _FuncCompanion,\n _FuncDer,\n _FuncFit,\n _FuncFromRoots,\n _FuncGauss,\n _FuncInteg,\n _FuncLine,\n _FuncPoly2Ortho,\n _FuncPow,\n _FuncPts,\n _FuncRoots,\n _FuncUnOp,\n _FuncVal,\n _FuncVal2D,\n _FuncVal3D,\n _FuncValFromRoots,\n _FuncVander,\n _FuncVander2D,\n _FuncVander3D,\n _FuncWeight,\n _Series,\n _SeriesLikeCoef_co,\n)\nfrom .polyutils import trimcoef as chebtrim\n\n__all__ = [\n "chebzero",\n "chebone",\n "chebx",\n "chebdomain",\n "chebline",\n "chebadd",\n "chebsub",\n "chebmulx",\n "chebmul",\n "chebdiv",\n "chebpow",\n "chebval",\n "chebder",\n "chebint",\n "cheb2poly",\n "poly2cheb",\n "chebfromroots",\n "chebvander",\n "chebfit",\n "chebtrim",\n "chebroots",\n "chebpts1",\n "chebpts2",\n "Chebyshev",\n "chebval2d",\n "chebval3d",\n "chebgrid2d",\n "chebgrid3d",\n "chebvander2d",\n "chebvander3d",\n "chebcompanion",\n "chebgauss",\n "chebweight",\n "chebinterpolate",\n]\n\n_NumberOrObjectT = TypeVar("_NumberOrObjectT", bound=np.number | np.object_)\ndef _cseries_to_zseries(c: npt.NDArray[_NumberOrObjectT]) -> _Series[_NumberOrObjectT]: ...\ndef _zseries_to_cseries(zs: npt.NDArray[_NumberOrObjectT]) -> _Series[_NumberOrObjectT]: ...\ndef _zseries_mul(\n z1: npt.NDArray[_NumberOrObjectT],\n z2: npt.NDArray[_NumberOrObjectT],\n) -> _Series[_NumberOrObjectT]: ...\ndef _zseries_div(\n z1: npt.NDArray[_NumberOrObjectT],\n z2: npt.NDArray[_NumberOrObjectT],\n) -> _Series[_NumberOrObjectT]: ...\ndef _zseries_der(zs: npt.NDArray[_NumberOrObjectT]) -> _Series[_NumberOrObjectT]: ...\ndef _zseries_int(zs: npt.NDArray[_NumberOrObjectT]) -> _Series[_NumberOrObjectT]: ...\n\npoly2cheb: _FuncPoly2Ortho[L["poly2cheb"]]\ncheb2poly: _FuncUnOp[L["cheb2poly"]]\n\nchebdomain: Final[_Array2[np.float64]]\nchebzero: Final[_Array1[np.int_]]\nchebone: Final[_Array1[np.int_]]\nchebx: Final[_Array2[np.int_]]\n\nchebline: _FuncLine[L["chebline"]]\nchebfromroots: _FuncFromRoots[L["chebfromroots"]]\nchebadd: _FuncBinOp[L["chebadd"]]\nchebsub: _FuncBinOp[L["chebsub"]]\nchebmulx: _FuncUnOp[L["chebmulx"]]\nchebmul: _FuncBinOp[L["chebmul"]]\nchebdiv: _FuncBinOp[L["chebdiv"]]\nchebpow: _FuncPow[L["chebpow"]]\nchebder: _FuncDer[L["chebder"]]\nchebint: _FuncInteg[L["chebint"]]\nchebval: _FuncVal[L["chebval"]]\nchebval2d: _FuncVal2D[L["chebval2d"]]\nchebval3d: _FuncVal3D[L["chebval3d"]]\nchebvalfromroots: _FuncValFromRoots[L["chebvalfromroots"]]\nchebgrid2d: _FuncVal2D[L["chebgrid2d"]]\nchebgrid3d: _FuncVal3D[L["chebgrid3d"]]\nchebvander: _FuncVander[L["chebvander"]]\nchebvander2d: _FuncVander2D[L["chebvander2d"]]\nchebvander3d: _FuncVander3D[L["chebvander3d"]]\nchebfit: _FuncFit[L["chebfit"]]\nchebcompanion: _FuncCompanion[L["chebcompanion"]]\nchebroots: _FuncRoots[L["chebroots"]]\nchebgauss: _FuncGauss[L["chebgauss"]]\nchebweight: _FuncWeight[L["chebweight"]]\nchebpts1: _FuncPts[L["chebpts1"]]\nchebpts2: _FuncPts[L["chebpts2"]]\n\n# keep in sync with `Chebyshev.interpolate`\n_RT = TypeVar("_RT", bound=np.number | np.bool | np.object_)\n@overload\ndef chebinterpolate(\n func: np.ufunc,\n deg: _IntLike_co,\n args: tuple[()] = ...,\n) -> npt.NDArray[np.float64 | np.complex128 | np.object_]: ...\n@overload\ndef chebinterpolate(\n func: Callable[[npt.NDArray[np.float64]], _RT],\n deg: _IntLike_co,\n args: tuple[()] = ...,\n) -> npt.NDArray[_RT]: ...\n@overload\ndef chebinterpolate(\n func: Callable[Concatenate[npt.NDArray[np.float64], ...], _RT],\n deg: _IntLike_co,\n args: Iterable[Any],\n) -> npt.NDArray[_RT]: ...\n\nclass Chebyshev(ABCPolyBase[L["T"]]):\n @overload\n @classmethod\n def interpolate(\n cls,\n func: Callable[[npt.NDArray[np.float64]], _CoefSeries],\n deg: _IntLike_co,\n domain: _SeriesLikeCoef_co | None = ...,\n args: tuple[()] = ...,\n ) -> Self: ...\n @overload\n @classmethod\n def interpolate(\n cls,\n func: Callable[\n Concatenate[npt.NDArray[np.float64], ...],\n _CoefSeries,\n ],\n deg: _IntLike_co,\n domain: _SeriesLikeCoef_co | None = ...,\n *,\n args: Iterable[Any],\n ) -> Self: ...\n @overload\n @classmethod\n def interpolate(\n cls,\n func: Callable[\n Concatenate[npt.NDArray[np.float64], ...],\n _CoefSeries,\n ],\n deg: _IntLike_co,\n domain: _SeriesLikeCoef_co | None,\n args: Iterable[Any],\n ) -> Self: ...\n | .venv\Lib\site-packages\numpy\polynomial\chebyshev.pyi | chebyshev.pyi | Other | 4,968 | 0.95 | 0.071823 | 0.011628 | node-utils | 496 | 2023-10-14T18:31:56.476025 | MIT | false | da85e6bb2dd48461d0ba968704a307d7 |
"""\n==============================================================\nHermite Series, "Physicists" (:mod:`numpy.polynomial.hermite`)\n==============================================================\n\nThis module provides a number of objects (mostly functions) useful for\ndealing with Hermite series, including a `Hermite` class that\nencapsulates the usual arithmetic operations. (General information\non how this module represents and works with such polynomials is in the\ndocstring for its "parent" sub-package, `numpy.polynomial`).\n\nClasses\n-------\n.. autosummary::\n :toctree: generated/\n\n Hermite\n\nConstants\n---------\n.. autosummary::\n :toctree: generated/\n\n hermdomain\n hermzero\n hermone\n hermx\n\nArithmetic\n----------\n.. autosummary::\n :toctree: generated/\n\n hermadd\n hermsub\n hermmulx\n hermmul\n hermdiv\n hermpow\n hermval\n hermval2d\n hermval3d\n hermgrid2d\n hermgrid3d\n\nCalculus\n--------\n.. autosummary::\n :toctree: generated/\n\n hermder\n hermint\n\nMisc Functions\n--------------\n.. autosummary::\n :toctree: generated/\n\n hermfromroots\n hermroots\n hermvander\n hermvander2d\n hermvander3d\n hermgauss\n hermweight\n hermcompanion\n hermfit\n hermtrim\n hermline\n herm2poly\n poly2herm\n\nSee also\n--------\n`numpy.polynomial`\n\n"""\nimport numpy as np\nimport numpy.linalg as la\nfrom numpy.lib.array_utils import normalize_axis_index\n\nfrom . import polyutils as pu\nfrom ._polybase import ABCPolyBase\n\n__all__ = [\n 'hermzero', 'hermone', 'hermx', 'hermdomain', 'hermline', 'hermadd',\n 'hermsub', 'hermmulx', 'hermmul', 'hermdiv', 'hermpow', 'hermval',\n 'hermder', 'hermint', 'herm2poly', 'poly2herm', 'hermfromroots',\n 'hermvander', 'hermfit', 'hermtrim', 'hermroots', 'Hermite',\n 'hermval2d', 'hermval3d', 'hermgrid2d', 'hermgrid3d', 'hermvander2d',\n 'hermvander3d', 'hermcompanion', 'hermgauss', 'hermweight']\n\nhermtrim = pu.trimcoef\n\n\ndef poly2herm(pol):\n """\n poly2herm(pol)\n\n Convert a polynomial to a Hermite series.\n\n Convert an array representing the coefficients of a polynomial (relative\n to the "standard" basis) ordered from lowest degree to highest, to an\n array of the coefficients of the equivalent Hermite series, ordered\n from lowest to highest degree.\n\n Parameters\n ----------\n pol : array_like\n 1-D array containing the polynomial coefficients\n\n Returns\n -------\n c : ndarray\n 1-D array containing the coefficients of the equivalent Hermite\n series.\n\n See Also\n --------\n herm2poly\n\n Notes\n -----\n The easy way to do conversions between polynomial basis sets\n is to use the convert method of a class instance.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import poly2herm\n >>> poly2herm(np.arange(4))\n array([1. , 2.75 , 0.5 , 0.375])\n\n """\n [pol] = pu.as_series([pol])\n deg = len(pol) - 1\n res = 0\n for i in range(deg, -1, -1):\n res = hermadd(hermmulx(res), pol[i])\n return res\n\n\ndef herm2poly(c):\n """\n Convert a Hermite series to a polynomial.\n\n Convert an array representing the coefficients of a Hermite series,\n ordered from lowest degree to highest, to an array of the coefficients\n of the equivalent polynomial (relative to the "standard" basis) ordered\n from lowest to highest degree.\n\n Parameters\n ----------\n c : array_like\n 1-D array containing the Hermite series coefficients, ordered\n from lowest order term to highest.\n\n Returns\n -------\n pol : ndarray\n 1-D array containing the coefficients of the equivalent polynomial\n (relative to the "standard" basis) ordered from lowest order term\n to highest.\n\n See Also\n --------\n poly2herm\n\n Notes\n -----\n The easy way to do conversions between polynomial basis sets\n is to use the convert method of a class instance.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import herm2poly\n >>> herm2poly([ 1. , 2.75 , 0.5 , 0.375])\n array([0., 1., 2., 3.])\n\n """\n from .polynomial import polyadd, polymulx, polysub\n\n [c] = pu.as_series([c])\n n = len(c)\n if n == 1:\n return c\n if n == 2:\n c[1] *= 2\n return c\n else:\n c0 = c[-2]\n c1 = c[-1]\n # i is the current degree of c1\n for i in range(n - 1, 1, -1):\n tmp = c0\n c0 = polysub(c[i - 2], c1 * (2 * (i - 1)))\n c1 = polyadd(tmp, polymulx(c1) * 2)\n return polyadd(c0, polymulx(c1) * 2)\n\n\n#\n# These are constant arrays are of integer type so as to be compatible\n# with the widest range of other types, such as Decimal.\n#\n\n# Hermite\nhermdomain = np.array([-1., 1.])\n\n# Hermite coefficients representing zero.\nhermzero = np.array([0])\n\n# Hermite coefficients representing one.\nhermone = np.array([1])\n\n# Hermite coefficients representing the identity x.\nhermx = np.array([0, 1 / 2])\n\n\ndef hermline(off, scl):\n """\n Hermite series whose graph is a straight line.\n\n\n\n Parameters\n ----------\n off, scl : scalars\n The specified line is given by ``off + scl*x``.\n\n Returns\n -------\n y : ndarray\n This module's representation of the Hermite series for\n ``off + scl*x``.\n\n See Also\n --------\n numpy.polynomial.polynomial.polyline\n numpy.polynomial.chebyshev.chebline\n numpy.polynomial.legendre.legline\n numpy.polynomial.laguerre.lagline\n numpy.polynomial.hermite_e.hermeline\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermline, hermval\n >>> hermval(0,hermline(3, 2))\n 3.0\n >>> hermval(1,hermline(3, 2))\n 5.0\n\n """\n if scl != 0:\n return np.array([off, scl / 2])\n else:\n return np.array([off])\n\n\ndef hermfromroots(roots):\n """\n Generate a Hermite series with given roots.\n\n The function returns the coefficients of the polynomial\n\n .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),\n\n in Hermite form, where the :math:`r_n` are the roots specified in `roots`.\n If a zero has multiplicity n, then it must appear in `roots` n times.\n For instance, if 2 is a root of multiplicity three and 3 is a root of\n multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The\n roots can appear in any order.\n\n If the returned coefficients are `c`, then\n\n .. math:: p(x) = c_0 + c_1 * H_1(x) + ... + c_n * H_n(x)\n\n The coefficient of the last term is not generally 1 for monic\n polynomials in Hermite form.\n\n Parameters\n ----------\n roots : array_like\n Sequence containing the roots.\n\n Returns\n -------\n out : ndarray\n 1-D array of coefficients. If all roots are real then `out` is a\n real array, if some of the roots are complex, then `out` is complex\n even if all the coefficients in the result are real (see Examples\n below).\n\n See Also\n --------\n numpy.polynomial.polynomial.polyfromroots\n numpy.polynomial.legendre.legfromroots\n numpy.polynomial.laguerre.lagfromroots\n numpy.polynomial.chebyshev.chebfromroots\n numpy.polynomial.hermite_e.hermefromroots\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermfromroots, hermval\n >>> coef = hermfromroots((-1, 0, 1))\n >>> hermval((-1, 0, 1), coef)\n array([0., 0., 0.])\n >>> coef = hermfromroots((-1j, 1j))\n >>> hermval((-1j, 1j), coef)\n array([0.+0.j, 0.+0.j])\n\n """\n return pu._fromroots(hermline, hermmul, roots)\n\n\ndef hermadd(c1, c2):\n """\n Add one Hermite series to another.\n\n Returns the sum of two Hermite series `c1` + `c2`. The arguments\n are sequences of coefficients ordered from lowest order term to\n highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Hermite series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Array representing the Hermite series of their sum.\n\n See Also\n --------\n hermsub, hermmulx, hermmul, hermdiv, hermpow\n\n Notes\n -----\n Unlike multiplication, division, etc., the sum of two Hermite series\n is a Hermite series (without having to "reproject" the result onto\n the basis set) so addition, just like that of "standard" polynomials,\n is simply "component-wise."\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermadd\n >>> hermadd([1, 2, 3], [1, 2, 3, 4])\n array([2., 4., 6., 4.])\n\n """\n return pu._add(c1, c2)\n\n\ndef hermsub(c1, c2):\n """\n Subtract one Hermite series from another.\n\n Returns the difference of two Hermite series `c1` - `c2`. The\n sequences of coefficients are from lowest order term to highest, i.e.,\n [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Hermite series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Of Hermite series coefficients representing their difference.\n\n See Also\n --------\n hermadd, hermmulx, hermmul, hermdiv, hermpow\n\n Notes\n -----\n Unlike multiplication, division, etc., the difference of two Hermite\n series is a Hermite series (without having to "reproject" the result\n onto the basis set) so subtraction, just like that of "standard"\n polynomials, is simply "component-wise."\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermsub\n >>> hermsub([1, 2, 3, 4], [1, 2, 3])\n array([0., 0., 0., 4.])\n\n """\n return pu._sub(c1, c2)\n\n\ndef hermmulx(c):\n """Multiply a Hermite series by x.\n\n Multiply the Hermite series `c` by x, where x is the independent\n variable.\n\n\n Parameters\n ----------\n c : array_like\n 1-D array of Hermite series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Array representing the result of the multiplication.\n\n See Also\n --------\n hermadd, hermsub, hermmul, hermdiv, hermpow\n\n Notes\n -----\n The multiplication uses the recursion relationship for Hermite\n polynomials in the form\n\n .. math::\n\n xP_i(x) = (P_{i + 1}(x)/2 + i*P_{i - 1}(x))\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermmulx\n >>> hermmulx([1, 2, 3])\n array([2. , 6.5, 1. , 1.5])\n\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n # The zero series needs special treatment\n if len(c) == 1 and c[0] == 0:\n return c\n\n prd = np.empty(len(c) + 1, dtype=c.dtype)\n prd[0] = c[0] * 0\n prd[1] = c[0] / 2\n for i in range(1, len(c)):\n prd[i + 1] = c[i] / 2\n prd[i - 1] += c[i] * i\n return prd\n\n\ndef hermmul(c1, c2):\n """\n Multiply one Hermite series by another.\n\n Returns the product of two Hermite series `c1` * `c2`. The arguments\n are sequences of coefficients, from lowest order "term" to highest,\n e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Hermite series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Of Hermite series coefficients representing their product.\n\n See Also\n --------\n hermadd, hermsub, hermmulx, hermdiv, hermpow\n\n Notes\n -----\n In general, the (polynomial) product of two C-series results in terms\n that are not in the Hermite polynomial basis set. Thus, to express\n the product as a Hermite series, it is necessary to "reproject" the\n product onto said basis set, which may produce "unintuitive" (but\n correct) results; see Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermmul\n >>> hermmul([1, 2, 3], [0, 1, 2])\n array([52., 29., 52., 7., 6.])\n\n """\n # s1, s2 are trimmed copies\n [c1, c2] = pu.as_series([c1, c2])\n\n if len(c1) > len(c2):\n c = c2\n xs = c1\n else:\n c = c1\n xs = c2\n\n if len(c) == 1:\n c0 = c[0] * xs\n c1 = 0\n elif len(c) == 2:\n c0 = c[0] * xs\n c1 = c[1] * xs\n else:\n nd = len(c)\n c0 = c[-2] * xs\n c1 = c[-1] * xs\n for i in range(3, len(c) + 1):\n tmp = c0\n nd = nd - 1\n c0 = hermsub(c[-i] * xs, c1 * (2 * (nd - 1)))\n c1 = hermadd(tmp, hermmulx(c1) * 2)\n return hermadd(c0, hermmulx(c1) * 2)\n\n\ndef hermdiv(c1, c2):\n """\n Divide one Hermite series by another.\n\n Returns the quotient-with-remainder of two Hermite series\n `c1` / `c2`. The arguments are sequences of coefficients from lowest\n order "term" to highest, e.g., [1,2,3] represents the series\n ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Hermite series coefficients ordered from low to\n high.\n\n Returns\n -------\n [quo, rem] : ndarrays\n Of Hermite series coefficients representing the quotient and\n remainder.\n\n See Also\n --------\n hermadd, hermsub, hermmulx, hermmul, hermpow\n\n Notes\n -----\n In general, the (polynomial) division of one Hermite series by another\n results in quotient and remainder terms that are not in the Hermite\n polynomial basis set. Thus, to express these results as a Hermite\n series, it is necessary to "reproject" the results onto the Hermite\n basis set, which may produce "unintuitive" (but correct) results; see\n Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermdiv\n >>> hermdiv([ 52., 29., 52., 7., 6.], [0, 1, 2])\n (array([1., 2., 3.]), array([0.]))\n >>> hermdiv([ 54., 31., 52., 7., 6.], [0, 1, 2])\n (array([1., 2., 3.]), array([2., 2.]))\n >>> hermdiv([ 53., 30., 52., 7., 6.], [0, 1, 2])\n (array([1., 2., 3.]), array([1., 1.]))\n\n """\n return pu._div(hermmul, c1, c2)\n\n\ndef hermpow(c, pow, maxpower=16):\n """Raise a Hermite series to a power.\n\n Returns the Hermite series `c` raised to the power `pow`. The\n argument `c` is a sequence of coefficients ordered from low to high.\n i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.``\n\n Parameters\n ----------\n c : array_like\n 1-D array of Hermite series coefficients ordered from low to\n high.\n pow : integer\n Power to which the series will be raised\n maxpower : integer, optional\n Maximum power allowed. This is mainly to limit growth of the series\n to unmanageable size. Default is 16\n\n Returns\n -------\n coef : ndarray\n Hermite series of power.\n\n See Also\n --------\n hermadd, hermsub, hermmulx, hermmul, hermdiv\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermpow\n >>> hermpow([1, 2, 3], 2)\n array([81., 52., 82., 12., 9.])\n\n """\n return pu._pow(hermmul, c, pow, maxpower)\n\n\ndef hermder(c, m=1, scl=1, axis=0):\n """\n Differentiate a Hermite series.\n\n Returns the Hermite series coefficients `c` differentiated `m` times\n along `axis`. At each iteration the result is multiplied by `scl` (the\n scaling factor is for use in a linear change of variable). The argument\n `c` is an array of coefficients from low to high degree along each\n axis, e.g., [1,2,3] represents the series ``1*H_0 + 2*H_1 + 3*H_2``\n while [[1,2],[1,2]] represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) +\n 2*H_0(x)*H_1(y) + 2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is\n ``y``.\n\n Parameters\n ----------\n c : array_like\n Array of Hermite series coefficients. If `c` is multidimensional the\n different axis correspond to different variables with the degree in\n each axis given by the corresponding index.\n m : int, optional\n Number of derivatives taken, must be non-negative. (Default: 1)\n scl : scalar, optional\n Each differentiation is multiplied by `scl`. The end result is\n multiplication by ``scl**m``. This is for use in a linear change of\n variable. (Default: 1)\n axis : int, optional\n Axis over which the derivative is taken. (Default: 0).\n\n Returns\n -------\n der : ndarray\n Hermite series of the derivative.\n\n See Also\n --------\n hermint\n\n Notes\n -----\n In general, the result of differentiating a Hermite series does not\n resemble the same operation on a power series. Thus the result of this\n function may be "unintuitive," albeit correct; see Examples section\n below.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermder\n >>> hermder([ 1. , 0.5, 0.5, 0.5])\n array([1., 2., 3.])\n >>> hermder([-0.5, 1./2., 1./8., 1./12., 1./16.], m=2)\n array([1., 2., 3.])\n\n """\n c = np.array(c, ndmin=1, copy=True)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n cnt = pu._as_int(m, "the order of derivation")\n iaxis = pu._as_int(axis, "the axis")\n if cnt < 0:\n raise ValueError("The order of derivation must be non-negative")\n iaxis = normalize_axis_index(iaxis, c.ndim)\n\n if cnt == 0:\n return c\n\n c = np.moveaxis(c, iaxis, 0)\n n = len(c)\n if cnt >= n:\n c = c[:1] * 0\n else:\n for i in range(cnt):\n n = n - 1\n c *= scl\n der = np.empty((n,) + c.shape[1:], dtype=c.dtype)\n for j in range(n, 0, -1):\n der[j - 1] = (2 * j) * c[j]\n c = der\n c = np.moveaxis(c, 0, iaxis)\n return c\n\n\ndef hermint(c, m=1, k=[], lbnd=0, scl=1, axis=0):\n """\n Integrate a Hermite series.\n\n Returns the Hermite series coefficients `c` integrated `m` times from\n `lbnd` along `axis`. At each iteration the resulting series is\n **multiplied** by `scl` and an integration constant, `k`, is added.\n The scaling factor is for use in a linear change of variable. ("Buyer\n beware": note that, depending on what one is doing, one may want `scl`\n to be the reciprocal of what one might expect; for more information,\n see the Notes section below.) The argument `c` is an array of\n coefficients from low to high degree along each axis, e.g., [1,2,3]\n represents the series ``H_0 + 2*H_1 + 3*H_2`` while [[1,2],[1,2]]\n represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) + 2*H_0(x)*H_1(y) +\n 2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.\n\n Parameters\n ----------\n c : array_like\n Array of Hermite series coefficients. If c is multidimensional the\n different axis correspond to different variables with the degree in\n each axis given by the corresponding index.\n m : int, optional\n Order of integration, must be positive. (Default: 1)\n k : {[], list, scalar}, optional\n Integration constant(s). The value of the first integral at\n ``lbnd`` is the first value in the list, the value of the second\n integral at ``lbnd`` is the second value, etc. If ``k == []`` (the\n default), all constants are set to zero. If ``m == 1``, a single\n scalar can be given instead of a list.\n lbnd : scalar, optional\n The lower bound of the integral. (Default: 0)\n scl : scalar, optional\n Following each integration the result is *multiplied* by `scl`\n before the integration constant is added. (Default: 1)\n axis : int, optional\n Axis over which the integral is taken. (Default: 0).\n\n Returns\n -------\n S : ndarray\n Hermite series coefficients of the integral.\n\n Raises\n ------\n ValueError\n If ``m < 0``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or\n ``np.ndim(scl) != 0``.\n\n See Also\n --------\n hermder\n\n Notes\n -----\n Note that the result of each integration is *multiplied* by `scl`.\n Why is this important to note? Say one is making a linear change of\n variable :math:`u = ax + b` in an integral relative to `x`. Then\n :math:`dx = du/a`, so one will need to set `scl` equal to\n :math:`1/a` - perhaps not what one would have first thought.\n\n Also note that, in general, the result of integrating a C-series needs\n to be "reprojected" onto the C-series basis set. Thus, typically,\n the result of this function is "unintuitive," albeit correct; see\n Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermint\n >>> hermint([1,2,3]) # integrate once, value 0 at 0.\n array([1. , 0.5, 0.5, 0.5])\n >>> hermint([1,2,3], m=2) # integrate twice, value & deriv 0 at 0\n array([-0.5 , 0.5 , 0.125 , 0.08333333, 0.0625 ]) # may vary\n >>> hermint([1,2,3], k=1) # integrate once, value 1 at 0.\n array([2. , 0.5, 0.5, 0.5])\n >>> hermint([1,2,3], lbnd=-1) # integrate once, value 0 at -1\n array([-2. , 0.5, 0.5, 0.5])\n >>> hermint([1,2,3], m=2, k=[1,2], lbnd=-1)\n array([ 1.66666667, -0.5 , 0.125 , 0.08333333, 0.0625 ]) # may vary\n\n """\n c = np.array(c, ndmin=1, copy=True)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n if not np.iterable(k):\n k = [k]\n cnt = pu._as_int(m, "the order of integration")\n iaxis = pu._as_int(axis, "the axis")\n if cnt < 0:\n raise ValueError("The order of integration must be non-negative")\n if len(k) > cnt:\n raise ValueError("Too many integration constants")\n if np.ndim(lbnd) != 0:\n raise ValueError("lbnd must be a scalar.")\n if np.ndim(scl) != 0:\n raise ValueError("scl must be a scalar.")\n iaxis = normalize_axis_index(iaxis, c.ndim)\n\n if cnt == 0:\n return c\n\n c = np.moveaxis(c, iaxis, 0)\n k = list(k) + [0] * (cnt - len(k))\n for i in range(cnt):\n n = len(c)\n c *= scl\n if n == 1 and np.all(c[0] == 0):\n c[0] += k[i]\n else:\n tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)\n tmp[0] = c[0] * 0\n tmp[1] = c[0] / 2\n for j in range(1, n):\n tmp[j + 1] = c[j] / (2 * (j + 1))\n tmp[0] += k[i] - hermval(lbnd, tmp)\n c = tmp\n c = np.moveaxis(c, 0, iaxis)\n return c\n\n\ndef hermval(x, c, tensor=True):\n """\n Evaluate an Hermite series at points x.\n\n If `c` is of length ``n + 1``, this function returns the value:\n\n .. math:: p(x) = c_0 * H_0(x) + c_1 * H_1(x) + ... + c_n * H_n(x)\n\n The parameter `x` is converted to an array only if it is a tuple or a\n list, otherwise it is treated as a scalar. In either case, either `x`\n or its elements must support multiplication and addition both with\n themselves and with the elements of `c`.\n\n If `c` is a 1-D array, then ``p(x)`` will have the same shape as `x`. If\n `c` is multidimensional, then the shape of the result depends on the\n value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +\n x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that\n scalars have shape (,).\n\n Trailing zeros in the coefficients will be used in the evaluation, so\n they should be avoided if efficiency is a concern.\n\n Parameters\n ----------\n x : array_like, compatible object\n If `x` is a list or tuple, it is converted to an ndarray, otherwise\n it is left unchanged and treated as a scalar. In either case, `x`\n or its elements must support addition and multiplication with\n themselves and with the elements of `c`.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree n are contained in c[n]. If `c` is multidimensional the\n remaining indices enumerate multiple polynomials. In the two\n dimensional case the coefficients may be thought of as stored in\n the columns of `c`.\n tensor : boolean, optional\n If True, the shape of the coefficient array is extended with ones\n on the right, one for each dimension of `x`. Scalars have dimension 0\n for this action. The result is that every column of coefficients in\n `c` is evaluated for every element of `x`. If False, `x` is broadcast\n over the columns of `c` for the evaluation. This keyword is useful\n when `c` is multidimensional. The default value is True.\n\n Returns\n -------\n values : ndarray, algebra_like\n The shape of the return value is described above.\n\n See Also\n --------\n hermval2d, hermgrid2d, hermval3d, hermgrid3d\n\n Notes\n -----\n The evaluation uses Clenshaw recursion, aka synthetic division.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermval\n >>> coef = [1,2,3]\n >>> hermval(1, coef)\n 11.0\n >>> hermval([[1,2],[3,4]], coef)\n array([[ 11., 51.],\n [115., 203.]])\n\n """\n c = np.array(c, ndmin=1, copy=None)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n if isinstance(x, (tuple, list)):\n x = np.asarray(x)\n if isinstance(x, np.ndarray) and tensor:\n c = c.reshape(c.shape + (1,) * x.ndim)\n\n x2 = x * 2\n if len(c) == 1:\n c0 = c[0]\n c1 = 0\n elif len(c) == 2:\n c0 = c[0]\n c1 = c[1]\n else:\n nd = len(c)\n c0 = c[-2]\n c1 = c[-1]\n for i in range(3, len(c) + 1):\n tmp = c0\n nd = nd - 1\n c0 = c[-i] - c1 * (2 * (nd - 1))\n c1 = tmp + c1 * x2\n return c0 + c1 * x2\n\n\ndef hermval2d(x, y, c):\n """\n Evaluate a 2-D Hermite series at points (x, y).\n\n This function returns the values:\n\n .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * H_i(x) * H_j(y)\n\n The parameters `x` and `y` are converted to arrays only if they are\n tuples or a lists, otherwise they are treated as a scalars and they\n must have the same shape after conversion. In either case, either `x`\n and `y` or their elements must support multiplication and addition both\n with themselves and with the elements of `c`.\n\n If `c` is a 1-D array a one is implicitly appended to its shape to make\n it 2-D. The shape of the result will be c.shape[2:] + x.shape.\n\n Parameters\n ----------\n x, y : array_like, compatible objects\n The two dimensional series is evaluated at the points ``(x, y)``,\n where `x` and `y` must have the same shape. If `x` or `y` is a list\n or tuple, it is first converted to an ndarray, otherwise it is left\n unchanged and if it isn't an ndarray it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term\n of multi-degree i,j is contained in ``c[i,j]``. If `c` has\n dimension greater than two the remaining indices enumerate multiple\n sets of coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points formed with\n pairs of corresponding values from `x` and `y`.\n\n See Also\n --------\n hermval, hermgrid2d, hermval3d, hermgrid3d\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermval2d\n >>> x = [1, 2]\n >>> y = [4, 5]\n >>> c = [[1, 2, 3], [4, 5, 6]]\n >>> hermval2d(x, y, c)\n array([1035., 2883.])\n\n """\n return pu._valnd(hermval, c, x, y)\n\n\ndef hermgrid2d(x, y, c):\n """\n Evaluate a 2-D Hermite series on the Cartesian product of x and y.\n\n This function returns the values:\n\n .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * H_i(a) * H_j(b)\n\n where the points ``(a, b)`` consist of all pairs formed by taking\n `a` from `x` and `b` from `y`. The resulting points form a grid with\n `x` in the first dimension and `y` in the second.\n\n The parameters `x` and `y` are converted to arrays only if they are\n tuples or a lists, otherwise they are treated as a scalars. In either\n case, either `x` and `y` or their elements must support multiplication\n and addition both with themselves and with the elements of `c`.\n\n If `c` has fewer than two dimensions, ones are implicitly appended to\n its shape to make it 2-D. The shape of the result will be c.shape[2:] +\n x.shape.\n\n Parameters\n ----------\n x, y : array_like, compatible objects\n The two dimensional series is evaluated at the points in the\n Cartesian product of `x` and `y`. If `x` or `y` is a list or\n tuple, it is first converted to an ndarray, otherwise it is left\n unchanged and, if it isn't an ndarray, it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree i,j are contained in ``c[i,j]``. If `c` has dimension\n greater than two the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points in the Cartesian\n product of `x` and `y`.\n\n See Also\n --------\n hermval, hermval2d, hermval3d, hermgrid3d\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermgrid2d\n >>> x = [1, 2, 3]\n >>> y = [4, 5]\n >>> c = [[1, 2, 3], [4, 5, 6]]\n >>> hermgrid2d(x, y, c)\n array([[1035., 1599.],\n [1867., 2883.],\n [2699., 4167.]])\n\n """\n return pu._gridnd(hermval, c, x, y)\n\n\ndef hermval3d(x, y, z, c):\n """\n Evaluate a 3-D Hermite series at points (x, y, z).\n\n This function returns the values:\n\n .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * H_i(x) * H_j(y) * H_k(z)\n\n The parameters `x`, `y`, and `z` are converted to arrays only if\n they are tuples or a lists, otherwise they are treated as a scalars and\n they must have the same shape after conversion. In either case, either\n `x`, `y`, and `z` or their elements must support multiplication and\n addition both with themselves and with the elements of `c`.\n\n If `c` has fewer than 3 dimensions, ones are implicitly appended to its\n shape to make it 3-D. The shape of the result will be c.shape[3:] +\n x.shape.\n\n Parameters\n ----------\n x, y, z : array_like, compatible object\n The three dimensional series is evaluated at the points\n ``(x, y, z)``, where `x`, `y`, and `z` must have the same shape. If\n any of `x`, `y`, or `z` is a list or tuple, it is first converted\n to an ndarray, otherwise it is left unchanged and if it isn't an\n ndarray it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term of\n multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension\n greater than 3 the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the multidimensional polynomial on points formed with\n triples of corresponding values from `x`, `y`, and `z`.\n\n See Also\n --------\n hermval, hermval2d, hermgrid2d, hermgrid3d\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermval3d\n >>> x = [1, 2]\n >>> y = [4, 5]\n >>> z = [6, 7]\n >>> c = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]\n >>> hermval3d(x, y, z, c)\n array([ 40077., 120131.])\n\n """\n return pu._valnd(hermval, c, x, y, z)\n\n\ndef hermgrid3d(x, y, z, c):\n """\n Evaluate a 3-D Hermite series on the Cartesian product of x, y, and z.\n\n This function returns the values:\n\n .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * H_i(a) * H_j(b) * H_k(c)\n\n where the points ``(a, b, c)`` consist of all triples formed by taking\n `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form\n a grid with `x` in the first dimension, `y` in the second, and `z` in\n the third.\n\n The parameters `x`, `y`, and `z` are converted to arrays only if they\n are tuples or a lists, otherwise they are treated as a scalars. In\n either case, either `x`, `y`, and `z` or their elements must support\n multiplication and addition both with themselves and with the elements\n of `c`.\n\n If `c` has fewer than three dimensions, ones are implicitly appended to\n its shape to make it 3-D. The shape of the result will be c.shape[3:] +\n x.shape + y.shape + z.shape.\n\n Parameters\n ----------\n x, y, z : array_like, compatible objects\n The three dimensional series is evaluated at the points in the\n Cartesian product of `x`, `y`, and `z`. If `x`, `y`, or `z` is a\n list or tuple, it is first converted to an ndarray, otherwise it is\n left unchanged and, if it isn't an ndarray, it is treated as a\n scalar.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree i,j are contained in ``c[i,j]``. If `c` has dimension\n greater than two the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points in the Cartesian\n product of `x` and `y`.\n\n See Also\n --------\n hermval, hermval2d, hermgrid2d, hermval3d\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermgrid3d\n >>> x = [1, 2]\n >>> y = [4, 5]\n >>> z = [6, 7]\n >>> c = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]\n >>> hermgrid3d(x, y, z, c)\n array([[[ 40077., 54117.],\n [ 49293., 66561.]],\n [[ 72375., 97719.],\n [ 88975., 120131.]]])\n\n """\n return pu._gridnd(hermval, c, x, y, z)\n\n\ndef hermvander(x, deg):\n """Pseudo-Vandermonde matrix of given degree.\n\n Returns the pseudo-Vandermonde matrix of degree `deg` and sample points\n `x`. The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., i] = H_i(x),\n\n where ``0 <= i <= deg``. The leading indices of `V` index the elements of\n `x` and the last index is the degree of the Hermite polynomial.\n\n If `c` is a 1-D array of coefficients of length ``n + 1`` and `V` is the\n array ``V = hermvander(x, n)``, then ``np.dot(V, c)`` and\n ``hermval(x, c)`` are the same up to roundoff. This equivalence is\n useful both for least squares fitting and for the evaluation of a large\n number of Hermite series of the same degree and sample points.\n\n Parameters\n ----------\n x : array_like\n Array of points. The dtype is converted to float64 or complex128\n depending on whether any of the elements are complex. If `x` is\n scalar it is converted to a 1-D array.\n deg : int\n Degree of the resulting matrix.\n\n Returns\n -------\n vander : ndarray\n The pseudo-Vandermonde matrix. The shape of the returned matrix is\n ``x.shape + (deg + 1,)``, where The last index is the degree of the\n corresponding Hermite polynomial. The dtype will be the same as\n the converted `x`.\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial.hermite import hermvander\n >>> x = np.array([-1, 0, 1])\n >>> hermvander(x, 3)\n array([[ 1., -2., 2., 4.],\n [ 1., 0., -2., -0.],\n [ 1., 2., 2., -4.]])\n\n """\n ideg = pu._as_int(deg, "deg")\n if ideg < 0:\n raise ValueError("deg must be non-negative")\n\n x = np.array(x, copy=None, ndmin=1) + 0.0\n dims = (ideg + 1,) + x.shape\n dtyp = x.dtype\n v = np.empty(dims, dtype=dtyp)\n v[0] = x * 0 + 1\n if ideg > 0:\n x2 = x * 2\n v[1] = x2\n for i in range(2, ideg + 1):\n v[i] = (v[i - 1] * x2 - v[i - 2] * (2 * (i - 1)))\n return np.moveaxis(v, 0, -1)\n\n\ndef hermvander2d(x, y, deg):\n """Pseudo-Vandermonde matrix of given degrees.\n\n Returns the pseudo-Vandermonde matrix of degrees `deg` and sample\n points ``(x, y)``. The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., (deg[1] + 1)*i + j] = H_i(x) * H_j(y),\n\n where ``0 <= i <= deg[0]`` and ``0 <= j <= deg[1]``. The leading indices of\n `V` index the points ``(x, y)`` and the last index encodes the degrees of\n the Hermite polynomials.\n\n If ``V = hermvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`\n correspond to the elements of a 2-D coefficient array `c` of shape\n (xdeg + 1, ydeg + 1) in the order\n\n .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...\n\n and ``np.dot(V, c.flat)`` and ``hermval2d(x, y, c)`` will be the same\n up to roundoff. This equivalence is useful both for least squares\n fitting and for the evaluation of a large number of 2-D Hermite\n series of the same degrees and sample points.\n\n Parameters\n ----------\n x, y : array_like\n Arrays of point coordinates, all of the same shape. The dtypes\n will be converted to either float64 or complex128 depending on\n whether any of the elements are complex. Scalars are converted to 1-D\n arrays.\n deg : list of ints\n List of maximum degrees of the form [x_deg, y_deg].\n\n Returns\n -------\n vander2d : ndarray\n The shape of the returned matrix is ``x.shape + (order,)``, where\n :math:`order = (deg[0]+1)*(deg[1]+1)`. The dtype will be the same\n as the converted `x` and `y`.\n\n See Also\n --------\n hermvander, hermvander3d, hermval2d, hermval3d\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial.hermite import hermvander2d\n >>> x = np.array([-1, 0, 1])\n >>> y = np.array([-1, 0, 1])\n >>> hermvander2d(x, y, [2, 2])\n array([[ 1., -2., 2., -2., 4., -4., 2., -4., 4.],\n [ 1., 0., -2., 0., 0., -0., -2., -0., 4.],\n [ 1., 2., 2., 2., 4., 4., 2., 4., 4.]])\n\n """\n return pu._vander_nd_flat((hermvander, hermvander), (x, y), deg)\n\n\ndef hermvander3d(x, y, z, deg):\n """Pseudo-Vandermonde matrix of given degrees.\n\n Returns the pseudo-Vandermonde matrix of degrees `deg` and sample\n points ``(x, y, z)``. If `l`, `m`, `n` are the given degrees in `x`, `y`, `z`,\n then The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = H_i(x)*H_j(y)*H_k(z),\n\n where ``0 <= i <= l``, ``0 <= j <= m``, and ``0 <= j <= n``. The leading\n indices of `V` index the points ``(x, y, z)`` and the last index encodes\n the degrees of the Hermite polynomials.\n\n If ``V = hermvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns\n of `V` correspond to the elements of a 3-D coefficient array `c` of\n shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order\n\n .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...\n\n and ``np.dot(V, c.flat)`` and ``hermval3d(x, y, z, c)`` will be the\n same up to roundoff. This equivalence is useful both for least squares\n fitting and for the evaluation of a large number of 3-D Hermite\n series of the same degrees and sample points.\n\n Parameters\n ----------\n x, y, z : array_like\n Arrays of point coordinates, all of the same shape. The dtypes will\n be converted to either float64 or complex128 depending on whether\n any of the elements are complex. Scalars are converted to 1-D\n arrays.\n deg : list of ints\n List of maximum degrees of the form [x_deg, y_deg, z_deg].\n\n Returns\n -------\n vander3d : ndarray\n The shape of the returned matrix is ``x.shape + (order,)``, where\n :math:`order = (deg[0]+1)*(deg[1]+1)*(deg[2]+1)`. The dtype will\n be the same as the converted `x`, `y`, and `z`.\n\n See Also\n --------\n hermvander, hermvander3d, hermval2d, hermval3d\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermvander3d\n >>> x = np.array([-1, 0, 1])\n >>> y = np.array([-1, 0, 1])\n >>> z = np.array([-1, 0, 1])\n >>> hermvander3d(x, y, z, [0, 1, 2])\n array([[ 1., -2., 2., -2., 4., -4.],\n [ 1., 0., -2., 0., 0., -0.],\n [ 1., 2., 2., 2., 4., 4.]])\n\n """\n return pu._vander_nd_flat((hermvander, hermvander, hermvander), (x, y, z), deg)\n\n\ndef hermfit(x, y, deg, rcond=None, full=False, w=None):\n """\n Least squares fit of Hermite series to data.\n\n Return the coefficients of a Hermite series of degree `deg` that is the\n least squares fit to the data values `y` given at points `x`. If `y` is\n 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple\n fits are done, one for each column of `y`, and the resulting\n coefficients are stored in the corresponding columns of a 2-D return.\n The fitted polynomial(s) are in the form\n\n .. math:: p(x) = c_0 + c_1 * H_1(x) + ... + c_n * H_n(x),\n\n where `n` is `deg`.\n\n Parameters\n ----------\n x : array_like, shape (M,)\n x-coordinates of the M sample points ``(x[i], y[i])``.\n y : array_like, shape (M,) or (M, K)\n y-coordinates of the sample points. Several data sets of sample\n points sharing the same x-coordinates can be fitted at once by\n passing in a 2D-array that contains one dataset per column.\n deg : int or 1-D array_like\n Degree(s) of the fitting polynomials. If `deg` is a single integer\n all terms up to and including the `deg`'th term are included in the\n fit. For NumPy versions >= 1.11.0 a list of integers specifying the\n degrees of the terms to include may be used instead.\n rcond : float, optional\n Relative condition number of the fit. Singular values smaller than\n this relative to the largest singular value will be ignored. The\n default value is len(x)*eps, where eps is the relative precision of\n the float type, about 2e-16 in most cases.\n full : bool, optional\n Switch determining nature of return value. When it is False (the\n default) just the coefficients are returned, when True diagnostic\n information from the singular value decomposition is also returned.\n w : array_like, shape (`M`,), optional\n Weights. If not None, the weight ``w[i]`` applies to the unsquared\n residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are\n chosen so that the errors of the products ``w[i]*y[i]`` all have the\n same variance. When using inverse-variance weighting, use\n ``w[i] = 1/sigma(y[i])``. The default value is None.\n\n Returns\n -------\n coef : ndarray, shape (M,) or (M, K)\n Hermite coefficients ordered from low to high. If `y` was 2-D,\n the coefficients for the data in column k of `y` are in column\n `k`.\n\n [residuals, rank, singular_values, rcond] : list\n These values are only returned if ``full == True``\n\n - residuals -- sum of squared residuals of the least squares fit\n - rank -- the numerical rank of the scaled Vandermonde matrix\n - singular_values -- singular values of the scaled Vandermonde matrix\n - rcond -- value of `rcond`.\n\n For more details, see `numpy.linalg.lstsq`.\n\n Warns\n -----\n RankWarning\n The rank of the coefficient matrix in the least-squares fit is\n deficient. The warning is only raised if ``full == False``. The\n warnings can be turned off by\n\n >>> import warnings\n >>> warnings.simplefilter('ignore', np.exceptions.RankWarning)\n\n See Also\n --------\n numpy.polynomial.chebyshev.chebfit\n numpy.polynomial.legendre.legfit\n numpy.polynomial.laguerre.lagfit\n numpy.polynomial.polynomial.polyfit\n numpy.polynomial.hermite_e.hermefit\n hermval : Evaluates a Hermite series.\n hermvander : Vandermonde matrix of Hermite series.\n hermweight : Hermite weight function\n numpy.linalg.lstsq : Computes a least-squares fit from the matrix.\n scipy.interpolate.UnivariateSpline : Computes spline fits.\n\n Notes\n -----\n The solution is the coefficients of the Hermite series `p` that\n minimizes the sum of the weighted squared errors\n\n .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,\n\n where the :math:`w_j` are the weights. This problem is solved by\n setting up the (typically) overdetermined matrix equation\n\n .. math:: V(x) * c = w * y,\n\n where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the\n coefficients to be solved for, `w` are the weights, `y` are the\n observed values. This equation is then solved using the singular value\n decomposition of `V`.\n\n If some of the singular values of `V` are so small that they are\n neglected, then a `~exceptions.RankWarning` will be issued. This means that\n the coefficient values may be poorly determined. Using a lower order fit\n will usually get rid of the warning. The `rcond` parameter can also be\n set to a value smaller than its default, but the resulting fit may be\n spurious and have large contributions from roundoff error.\n\n Fits using Hermite series are probably most useful when the data can be\n approximated by ``sqrt(w(x)) * p(x)``, where ``w(x)`` is the Hermite\n weight. In that case the weight ``sqrt(w(x[i]))`` should be used\n together with data values ``y[i]/sqrt(w(x[i]))``. The weight function is\n available as `hermweight`.\n\n References\n ----------\n .. [1] Wikipedia, "Curve fitting",\n https://en.wikipedia.org/wiki/Curve_fitting\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial.hermite import hermfit, hermval\n >>> x = np.linspace(-10, 10)\n >>> rng = np.random.default_rng()\n >>> err = rng.normal(scale=1./10, size=len(x))\n >>> y = hermval(x, [1, 2, 3]) + err\n >>> hermfit(x, y, 2)\n array([1.02294967, 2.00016403, 2.99994614]) # may vary\n\n """\n return pu._fit(hermvander, x, y, deg, rcond, full, w)\n\n\ndef hermcompanion(c):\n """Return the scaled companion matrix of c.\n\n The basis polynomials are scaled so that the companion matrix is\n symmetric when `c` is an Hermite basis polynomial. This provides\n better eigenvalue estimates than the unscaled case and for basis\n polynomials the eigenvalues are guaranteed to be real if\n `numpy.linalg.eigvalsh` is used to obtain them.\n\n Parameters\n ----------\n c : array_like\n 1-D array of Hermite series coefficients ordered from low to high\n degree.\n\n Returns\n -------\n mat : ndarray\n Scaled companion matrix of dimensions (deg, deg).\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermcompanion\n >>> hermcompanion([1, 0, 1])\n array([[0. , 0.35355339],\n [0.70710678, 0. ]])\n\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n if len(c) < 2:\n raise ValueError('Series must have maximum degree of at least 1.')\n if len(c) == 2:\n return np.array([[-.5 * c[0] / c[1]]])\n\n n = len(c) - 1\n mat = np.zeros((n, n), dtype=c.dtype)\n scl = np.hstack((1., 1. / np.sqrt(2. * np.arange(n - 1, 0, -1))))\n scl = np.multiply.accumulate(scl)[::-1]\n top = mat.reshape(-1)[1::n + 1]\n bot = mat.reshape(-1)[n::n + 1]\n top[...] = np.sqrt(.5 * np.arange(1, n))\n bot[...] = top\n mat[:, -1] -= scl * c[:-1] / (2.0 * c[-1])\n return mat\n\n\ndef hermroots(c):\n """\n Compute the roots of a Hermite series.\n\n Return the roots (a.k.a. "zeros") of the polynomial\n\n .. math:: p(x) = \\sum_i c[i] * H_i(x).\n\n Parameters\n ----------\n c : 1-D array_like\n 1-D array of coefficients.\n\n Returns\n -------\n out : ndarray\n Array of the roots of the series. If all the roots are real,\n then `out` is also real, otherwise it is complex.\n\n See Also\n --------\n numpy.polynomial.polynomial.polyroots\n numpy.polynomial.legendre.legroots\n numpy.polynomial.laguerre.lagroots\n numpy.polynomial.chebyshev.chebroots\n numpy.polynomial.hermite_e.hermeroots\n\n Notes\n -----\n The root estimates are obtained as the eigenvalues of the companion\n matrix, Roots far from the origin of the complex plane may have large\n errors due to the numerical instability of the series for such\n values. Roots with multiplicity greater than 1 will also show larger\n errors as the value of the series near such points is relatively\n insensitive to errors in the roots. Isolated roots near the origin can\n be improved by a few iterations of Newton's method.\n\n The Hermite series basis polynomials aren't powers of `x` so the\n results of this function may seem unintuitive.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermroots, hermfromroots\n >>> coef = hermfromroots([-1, 0, 1])\n >>> coef\n array([0. , 0.25 , 0. , 0.125])\n >>> hermroots(coef)\n array([-1.00000000e+00, -1.38777878e-17, 1.00000000e+00])\n\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n if len(c) <= 1:\n return np.array([], dtype=c.dtype)\n if len(c) == 2:\n return np.array([-.5 * c[0] / c[1]])\n\n # rotated companion matrix reduces error\n m = hermcompanion(c)[::-1, ::-1]\n r = la.eigvals(m)\n r.sort()\n return r\n\n\ndef _normed_hermite_n(x, n):\n """\n Evaluate a normalized Hermite polynomial.\n\n Compute the value of the normalized Hermite polynomial of degree ``n``\n at the points ``x``.\n\n\n Parameters\n ----------\n x : ndarray of double.\n Points at which to evaluate the function\n n : int\n Degree of the normalized Hermite function to be evaluated.\n\n Returns\n -------\n values : ndarray\n The shape of the return value is described above.\n\n Notes\n -----\n This function is needed for finding the Gauss points and integration\n weights for high degrees. The values of the standard Hermite functions\n overflow when n >= 207.\n\n """\n if n == 0:\n return np.full(x.shape, 1 / np.sqrt(np.sqrt(np.pi)))\n\n c0 = 0.\n c1 = 1. / np.sqrt(np.sqrt(np.pi))\n nd = float(n)\n for i in range(n - 1):\n tmp = c0\n c0 = -c1 * np.sqrt((nd - 1.) / nd)\n c1 = tmp + c1 * x * np.sqrt(2. / nd)\n nd = nd - 1.0\n return c0 + c1 * x * np.sqrt(2)\n\n\ndef hermgauss(deg):\n """\n Gauss-Hermite quadrature.\n\n Computes the sample points and weights for Gauss-Hermite quadrature.\n These sample points and weights will correctly integrate polynomials of\n degree :math:`2*deg - 1` or less over the interval :math:`[-\\inf, \\inf]`\n with the weight function :math:`f(x) = \\exp(-x^2)`.\n\n Parameters\n ----------\n deg : int\n Number of sample points and weights. It must be >= 1.\n\n Returns\n -------\n x : ndarray\n 1-D ndarray containing the sample points.\n y : ndarray\n 1-D ndarray containing the weights.\n\n Notes\n -----\n The results have only been tested up to degree 100, higher degrees may\n be problematic. The weights are determined by using the fact that\n\n .. math:: w_k = c / (H'_n(x_k) * H_{n-1}(x_k))\n\n where :math:`c` is a constant independent of :math:`k` and :math:`x_k`\n is the k'th root of :math:`H_n`, and then scaling the results to get\n the right value when integrating 1.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermgauss\n >>> hermgauss(2)\n (array([-0.70710678, 0.70710678]), array([0.88622693, 0.88622693]))\n\n """\n ideg = pu._as_int(deg, "deg")\n if ideg <= 0:\n raise ValueError("deg must be a positive integer")\n\n # first approximation of roots. We use the fact that the companion\n # matrix is symmetric in this case in order to obtain better zeros.\n c = np.array([0] * deg + [1], dtype=np.float64)\n m = hermcompanion(c)\n x = la.eigvalsh(m)\n\n # improve roots by one application of Newton\n dy = _normed_hermite_n(x, ideg)\n df = _normed_hermite_n(x, ideg - 1) * np.sqrt(2 * ideg)\n x -= dy / df\n\n # compute the weights. We scale the factor to avoid possible numerical\n # overflow.\n fm = _normed_hermite_n(x, ideg - 1)\n fm /= np.abs(fm).max()\n w = 1 / (fm * fm)\n\n # for Hermite we can also symmetrize\n w = (w + w[::-1]) / 2\n x = (x - x[::-1]) / 2\n\n # scale w to get the right value\n w *= np.sqrt(np.pi) / w.sum()\n\n return x, w\n\n\ndef hermweight(x):\n """\n Weight function of the Hermite polynomials.\n\n The weight function is :math:`\\exp(-x^2)` and the interval of\n integration is :math:`[-\\inf, \\inf]`. the Hermite polynomials are\n orthogonal, but not normalized, with respect to this weight function.\n\n Parameters\n ----------\n x : array_like\n Values at which the weight function will be computed.\n\n Returns\n -------\n w : ndarray\n The weight function at `x`.\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial.hermite import hermweight\n >>> x = np.arange(-2, 2)\n >>> hermweight(x)\n array([0.01831564, 0.36787944, 1. , 0.36787944])\n\n """\n w = np.exp(-x**2)\n return w\n\n\n#\n# Hermite series class\n#\n\nclass Hermite(ABCPolyBase):\n """An Hermite series class.\n\n The Hermite class provides the standard Python numerical methods\n '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the\n attributes and methods listed below.\n\n Parameters\n ----------\n coef : array_like\n Hermite coefficients in order of increasing degree, i.e,\n ``(1, 2, 3)`` gives ``1*H_0(x) + 2*H_1(x) + 3*H_2(x)``.\n domain : (2,) array_like, optional\n Domain to use. The interval ``[domain[0], domain[1]]`` is mapped\n to the interval ``[window[0], window[1]]`` by shifting and scaling.\n The default value is [-1., 1.].\n window : (2,) array_like, optional\n Window, see `domain` for its use. The default value is [-1., 1.].\n symbol : str, optional\n Symbol used to represent the independent variable in string\n representations of the polynomial expression, e.g. for printing.\n The symbol must be a valid Python identifier. Default value is 'x'.\n\n .. versionadded:: 1.24\n\n """\n # Virtual Functions\n _add = staticmethod(hermadd)\n _sub = staticmethod(hermsub)\n _mul = staticmethod(hermmul)\n _div = staticmethod(hermdiv)\n _pow = staticmethod(hermpow)\n _val = staticmethod(hermval)\n _int = staticmethod(hermint)\n _der = staticmethod(hermder)\n _fit = staticmethod(hermfit)\n _line = staticmethod(hermline)\n _roots = staticmethod(hermroots)\n _fromroots = staticmethod(hermfromroots)\n\n # Virtual properties\n domain = np.array(hermdomain)\n window = np.array(hermdomain)\n basis_name = 'H'\n | .venv\Lib\site-packages\numpy\polynomial\hermite.py | hermite.py | Python | 56,343 | 0.75 | 0.084483 | 0.019816 | react-lib | 763 | 2025-05-16T18:38:16.289584 | GPL-3.0 | false | 01074bfc4d08093a4ce2b566cc813a87 |
from typing import Any, Final, TypeVar\nfrom typing import Literal as L\n\nimport numpy as np\n\nfrom ._polybase import ABCPolyBase\nfrom ._polytypes import (\n _Array1,\n _Array2,\n _FuncBinOp,\n _FuncCompanion,\n _FuncDer,\n _FuncFit,\n _FuncFromRoots,\n _FuncGauss,\n _FuncInteg,\n _FuncLine,\n _FuncPoly2Ortho,\n _FuncPow,\n _FuncRoots,\n _FuncUnOp,\n _FuncVal,\n _FuncVal2D,\n _FuncVal3D,\n _FuncValFromRoots,\n _FuncVander,\n _FuncVander2D,\n _FuncVander3D,\n _FuncWeight,\n)\nfrom .polyutils import trimcoef as hermtrim\n\n__all__ = [\n "hermzero",\n "hermone",\n "hermx",\n "hermdomain",\n "hermline",\n "hermadd",\n "hermsub",\n "hermmulx",\n "hermmul",\n "hermdiv",\n "hermpow",\n "hermval",\n "hermder",\n "hermint",\n "herm2poly",\n "poly2herm",\n "hermfromroots",\n "hermvander",\n "hermfit",\n "hermtrim",\n "hermroots",\n "Hermite",\n "hermval2d",\n "hermval3d",\n "hermgrid2d",\n "hermgrid3d",\n "hermvander2d",\n "hermvander3d",\n "hermcompanion",\n "hermgauss",\n "hermweight",\n]\n\npoly2herm: _FuncPoly2Ortho[L["poly2herm"]]\nherm2poly: _FuncUnOp[L["herm2poly"]]\n\nhermdomain: Final[_Array2[np.float64]]\nhermzero: Final[_Array1[np.int_]]\nhermone: Final[_Array1[np.int_]]\nhermx: Final[_Array2[np.int_]]\n\nhermline: _FuncLine[L["hermline"]]\nhermfromroots: _FuncFromRoots[L["hermfromroots"]]\nhermadd: _FuncBinOp[L["hermadd"]]\nhermsub: _FuncBinOp[L["hermsub"]]\nhermmulx: _FuncUnOp[L["hermmulx"]]\nhermmul: _FuncBinOp[L["hermmul"]]\nhermdiv: _FuncBinOp[L["hermdiv"]]\nhermpow: _FuncPow[L["hermpow"]]\nhermder: _FuncDer[L["hermder"]]\nhermint: _FuncInteg[L["hermint"]]\nhermval: _FuncVal[L["hermval"]]\nhermval2d: _FuncVal2D[L["hermval2d"]]\nhermval3d: _FuncVal3D[L["hermval3d"]]\nhermvalfromroots: _FuncValFromRoots[L["hermvalfromroots"]]\nhermgrid2d: _FuncVal2D[L["hermgrid2d"]]\nhermgrid3d: _FuncVal3D[L["hermgrid3d"]]\nhermvander: _FuncVander[L["hermvander"]]\nhermvander2d: _FuncVander2D[L["hermvander2d"]]\nhermvander3d: _FuncVander3D[L["hermvander3d"]]\nhermfit: _FuncFit[L["hermfit"]]\nhermcompanion: _FuncCompanion[L["hermcompanion"]]\nhermroots: _FuncRoots[L["hermroots"]]\n\n_ND = TypeVar("_ND", bound=Any)\ndef _normed_hermite_n(\n x: np.ndarray[_ND, np.dtype[np.float64]],\n n: int | np.intp,\n) -> np.ndarray[_ND, np.dtype[np.float64]]: ...\n\nhermgauss: _FuncGauss[L["hermgauss"]]\nhermweight: _FuncWeight[L["hermweight"]]\n\nclass Hermite(ABCPolyBase[L["H"]]): ...\n | .venv\Lib\site-packages\numpy\polynomial\hermite.pyi | hermite.pyi | Other | 2,570 | 0.85 | 0.018692 | 0 | vue-tools | 421 | 2024-12-29T22:45:04.897465 | Apache-2.0 | false | 403e9a6519209f448b5652b2c72c1f33 |
"""\n===================================================================\nHermiteE Series, "Probabilists" (:mod:`numpy.polynomial.hermite_e`)\n===================================================================\n\nThis module provides a number of objects (mostly functions) useful for\ndealing with Hermite_e series, including a `HermiteE` class that\nencapsulates the usual arithmetic operations. (General information\non how this module represents and works with such polynomials is in the\ndocstring for its "parent" sub-package, `numpy.polynomial`).\n\nClasses\n-------\n.. autosummary::\n :toctree: generated/\n\n HermiteE\n\nConstants\n---------\n.. autosummary::\n :toctree: generated/\n\n hermedomain\n hermezero\n hermeone\n hermex\n\nArithmetic\n----------\n.. autosummary::\n :toctree: generated/\n\n hermeadd\n hermesub\n hermemulx\n hermemul\n hermediv\n hermepow\n hermeval\n hermeval2d\n hermeval3d\n hermegrid2d\n hermegrid3d\n\nCalculus\n--------\n.. autosummary::\n :toctree: generated/\n\n hermeder\n hermeint\n\nMisc Functions\n--------------\n.. autosummary::\n :toctree: generated/\n\n hermefromroots\n hermeroots\n hermevander\n hermevander2d\n hermevander3d\n hermegauss\n hermeweight\n hermecompanion\n hermefit\n hermetrim\n hermeline\n herme2poly\n poly2herme\n\nSee also\n--------\n`numpy.polynomial`\n\n"""\nimport numpy as np\nimport numpy.linalg as la\nfrom numpy.lib.array_utils import normalize_axis_index\n\nfrom . import polyutils as pu\nfrom ._polybase import ABCPolyBase\n\n__all__ = [\n 'hermezero', 'hermeone', 'hermex', 'hermedomain', 'hermeline',\n 'hermeadd', 'hermesub', 'hermemulx', 'hermemul', 'hermediv',\n 'hermepow', 'hermeval', 'hermeder', 'hermeint', 'herme2poly',\n 'poly2herme', 'hermefromroots', 'hermevander', 'hermefit', 'hermetrim',\n 'hermeroots', 'HermiteE', 'hermeval2d', 'hermeval3d', 'hermegrid2d',\n 'hermegrid3d', 'hermevander2d', 'hermevander3d', 'hermecompanion',\n 'hermegauss', 'hermeweight']\n\nhermetrim = pu.trimcoef\n\n\ndef poly2herme(pol):\n """\n poly2herme(pol)\n\n Convert a polynomial to a Hermite series.\n\n Convert an array representing the coefficients of a polynomial (relative\n to the "standard" basis) ordered from lowest degree to highest, to an\n array of the coefficients of the equivalent Hermite series, ordered\n from lowest to highest degree.\n\n Parameters\n ----------\n pol : array_like\n 1-D array containing the polynomial coefficients\n\n Returns\n -------\n c : ndarray\n 1-D array containing the coefficients of the equivalent Hermite\n series.\n\n See Also\n --------\n herme2poly\n\n Notes\n -----\n The easy way to do conversions between polynomial basis sets\n is to use the convert method of a class instance.\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial.hermite_e import poly2herme\n >>> poly2herme(np.arange(4))\n array([ 2., 10., 2., 3.])\n\n """\n [pol] = pu.as_series([pol])\n deg = len(pol) - 1\n res = 0\n for i in range(deg, -1, -1):\n res = hermeadd(hermemulx(res), pol[i])\n return res\n\n\ndef herme2poly(c):\n """\n Convert a Hermite series to a polynomial.\n\n Convert an array representing the coefficients of a Hermite series,\n ordered from lowest degree to highest, to an array of the coefficients\n of the equivalent polynomial (relative to the "standard" basis) ordered\n from lowest to highest degree.\n\n Parameters\n ----------\n c : array_like\n 1-D array containing the Hermite series coefficients, ordered\n from lowest order term to highest.\n\n Returns\n -------\n pol : ndarray\n 1-D array containing the coefficients of the equivalent polynomial\n (relative to the "standard" basis) ordered from lowest order term\n to highest.\n\n See Also\n --------\n poly2herme\n\n Notes\n -----\n The easy way to do conversions between polynomial basis sets\n is to use the convert method of a class instance.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite_e import herme2poly\n >>> herme2poly([ 2., 10., 2., 3.])\n array([0., 1., 2., 3.])\n\n """\n from .polynomial import polyadd, polymulx, polysub\n\n [c] = pu.as_series([c])\n n = len(c)\n if n == 1:\n return c\n if n == 2:\n return c\n else:\n c0 = c[-2]\n c1 = c[-1]\n # i is the current degree of c1\n for i in range(n - 1, 1, -1):\n tmp = c0\n c0 = polysub(c[i - 2], c1 * (i - 1))\n c1 = polyadd(tmp, polymulx(c1))\n return polyadd(c0, polymulx(c1))\n\n\n#\n# These are constant arrays are of integer type so as to be compatible\n# with the widest range of other types, such as Decimal.\n#\n\n# Hermite\nhermedomain = np.array([-1., 1.])\n\n# Hermite coefficients representing zero.\nhermezero = np.array([0])\n\n# Hermite coefficients representing one.\nhermeone = np.array([1])\n\n# Hermite coefficients representing the identity x.\nhermex = np.array([0, 1])\n\n\ndef hermeline(off, scl):\n """\n Hermite series whose graph is a straight line.\n\n Parameters\n ----------\n off, scl : scalars\n The specified line is given by ``off + scl*x``.\n\n Returns\n -------\n y : ndarray\n This module's representation of the Hermite series for\n ``off + scl*x``.\n\n See Also\n --------\n numpy.polynomial.polynomial.polyline\n numpy.polynomial.chebyshev.chebline\n numpy.polynomial.legendre.legline\n numpy.polynomial.laguerre.lagline\n numpy.polynomial.hermite.hermline\n\n Examples\n --------\n >>> from numpy.polynomial.hermite_e import hermeline\n >>> from numpy.polynomial.hermite_e import hermeline, hermeval\n >>> hermeval(0,hermeline(3, 2))\n 3.0\n >>> hermeval(1,hermeline(3, 2))\n 5.0\n\n """\n if scl != 0:\n return np.array([off, scl])\n else:\n return np.array([off])\n\n\ndef hermefromroots(roots):\n """\n Generate a HermiteE series with given roots.\n\n The function returns the coefficients of the polynomial\n\n .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),\n\n in HermiteE form, where the :math:`r_n` are the roots specified in `roots`.\n If a zero has multiplicity n, then it must appear in `roots` n times.\n For instance, if 2 is a root of multiplicity three and 3 is a root of\n multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The\n roots can appear in any order.\n\n If the returned coefficients are `c`, then\n\n .. math:: p(x) = c_0 + c_1 * He_1(x) + ... + c_n * He_n(x)\n\n The coefficient of the last term is not generally 1 for monic\n polynomials in HermiteE form.\n\n Parameters\n ----------\n roots : array_like\n Sequence containing the roots.\n\n Returns\n -------\n out : ndarray\n 1-D array of coefficients. If all roots are real then `out` is a\n real array, if some of the roots are complex, then `out` is complex\n even if all the coefficients in the result are real (see Examples\n below).\n\n See Also\n --------\n numpy.polynomial.polynomial.polyfromroots\n numpy.polynomial.legendre.legfromroots\n numpy.polynomial.laguerre.lagfromroots\n numpy.polynomial.hermite.hermfromroots\n numpy.polynomial.chebyshev.chebfromroots\n\n Examples\n --------\n >>> from numpy.polynomial.hermite_e import hermefromroots, hermeval\n >>> coef = hermefromroots((-1, 0, 1))\n >>> hermeval((-1, 0, 1), coef)\n array([0., 0., 0.])\n >>> coef = hermefromroots((-1j, 1j))\n >>> hermeval((-1j, 1j), coef)\n array([0.+0.j, 0.+0.j])\n\n """\n return pu._fromroots(hermeline, hermemul, roots)\n\n\ndef hermeadd(c1, c2):\n """\n Add one Hermite series to another.\n\n Returns the sum of two Hermite series `c1` + `c2`. The arguments\n are sequences of coefficients ordered from lowest order term to\n highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Hermite series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Array representing the Hermite series of their sum.\n\n See Also\n --------\n hermesub, hermemulx, hermemul, hermediv, hermepow\n\n Notes\n -----\n Unlike multiplication, division, etc., the sum of two Hermite series\n is a Hermite series (without having to "reproject" the result onto\n the basis set) so addition, just like that of "standard" polynomials,\n is simply "component-wise."\n\n Examples\n --------\n >>> from numpy.polynomial.hermite_e import hermeadd\n >>> hermeadd([1, 2, 3], [1, 2, 3, 4])\n array([2., 4., 6., 4.])\n\n """\n return pu._add(c1, c2)\n\n\ndef hermesub(c1, c2):\n """\n Subtract one Hermite series from another.\n\n Returns the difference of two Hermite series `c1` - `c2`. The\n sequences of coefficients are from lowest order term to highest, i.e.,\n [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Hermite series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Of Hermite series coefficients representing their difference.\n\n See Also\n --------\n hermeadd, hermemulx, hermemul, hermediv, hermepow\n\n Notes\n -----\n Unlike multiplication, division, etc., the difference of two Hermite\n series is a Hermite series (without having to "reproject" the result\n onto the basis set) so subtraction, just like that of "standard"\n polynomials, is simply "component-wise."\n\n Examples\n --------\n >>> from numpy.polynomial.hermite_e import hermesub\n >>> hermesub([1, 2, 3, 4], [1, 2, 3])\n array([0., 0., 0., 4.])\n\n """\n return pu._sub(c1, c2)\n\n\ndef hermemulx(c):\n """Multiply a Hermite series by x.\n\n Multiply the Hermite series `c` by x, where x is the independent\n variable.\n\n\n Parameters\n ----------\n c : array_like\n 1-D array of Hermite series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Array representing the result of the multiplication.\n\n See Also\n --------\n hermeadd, hermesub, hermemul, hermediv, hermepow\n\n Notes\n -----\n The multiplication uses the recursion relationship for Hermite\n polynomials in the form\n\n .. math::\n\n xP_i(x) = (P_{i + 1}(x) + iP_{i - 1}(x)))\n\n Examples\n --------\n >>> from numpy.polynomial.hermite_e import hermemulx\n >>> hermemulx([1, 2, 3])\n array([2., 7., 2., 3.])\n\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n # The zero series needs special treatment\n if len(c) == 1 and c[0] == 0:\n return c\n\n prd = np.empty(len(c) + 1, dtype=c.dtype)\n prd[0] = c[0] * 0\n prd[1] = c[0]\n for i in range(1, len(c)):\n prd[i + 1] = c[i]\n prd[i - 1] += c[i] * i\n return prd\n\n\ndef hermemul(c1, c2):\n """\n Multiply one Hermite series by another.\n\n Returns the product of two Hermite series `c1` * `c2`. The arguments\n are sequences of coefficients, from lowest order "term" to highest,\n e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Hermite series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Of Hermite series coefficients representing their product.\n\n See Also\n --------\n hermeadd, hermesub, hermemulx, hermediv, hermepow\n\n Notes\n -----\n In general, the (polynomial) product of two C-series results in terms\n that are not in the Hermite polynomial basis set. Thus, to express\n the product as a Hermite series, it is necessary to "reproject" the\n product onto said basis set, which may produce "unintuitive" (but\n correct) results; see Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite_e import hermemul\n >>> hermemul([1, 2, 3], [0, 1, 2])\n array([14., 15., 28., 7., 6.])\n\n """\n # s1, s2 are trimmed copies\n [c1, c2] = pu.as_series([c1, c2])\n\n if len(c1) > len(c2):\n c = c2\n xs = c1\n else:\n c = c1\n xs = c2\n\n if len(c) == 1:\n c0 = c[0] * xs\n c1 = 0\n elif len(c) == 2:\n c0 = c[0] * xs\n c1 = c[1] * xs\n else:\n nd = len(c)\n c0 = c[-2] * xs\n c1 = c[-1] * xs\n for i in range(3, len(c) + 1):\n tmp = c0\n nd = nd - 1\n c0 = hermesub(c[-i] * xs, c1 * (nd - 1))\n c1 = hermeadd(tmp, hermemulx(c1))\n return hermeadd(c0, hermemulx(c1))\n\n\ndef hermediv(c1, c2):\n """\n Divide one Hermite series by another.\n\n Returns the quotient-with-remainder of two Hermite series\n `c1` / `c2`. The arguments are sequences of coefficients from lowest\n order "term" to highest, e.g., [1,2,3] represents the series\n ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Hermite series coefficients ordered from low to\n high.\n\n Returns\n -------\n [quo, rem] : ndarrays\n Of Hermite series coefficients representing the quotient and\n remainder.\n\n See Also\n --------\n hermeadd, hermesub, hermemulx, hermemul, hermepow\n\n Notes\n -----\n In general, the (polynomial) division of one Hermite series by another\n results in quotient and remainder terms that are not in the Hermite\n polynomial basis set. Thus, to express these results as a Hermite\n series, it is necessary to "reproject" the results onto the Hermite\n basis set, which may produce "unintuitive" (but correct) results; see\n Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite_e import hermediv\n >>> hermediv([ 14., 15., 28., 7., 6.], [0, 1, 2])\n (array([1., 2., 3.]), array([0.]))\n >>> hermediv([ 15., 17., 28., 7., 6.], [0, 1, 2])\n (array([1., 2., 3.]), array([1., 2.]))\n\n """\n return pu._div(hermemul, c1, c2)\n\n\ndef hermepow(c, pow, maxpower=16):\n """Raise a Hermite series to a power.\n\n Returns the Hermite series `c` raised to the power `pow`. The\n argument `c` is a sequence of coefficients ordered from low to high.\n i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.``\n\n Parameters\n ----------\n c : array_like\n 1-D array of Hermite series coefficients ordered from low to\n high.\n pow : integer\n Power to which the series will be raised\n maxpower : integer, optional\n Maximum power allowed. This is mainly to limit growth of the series\n to unmanageable size. Default is 16\n\n Returns\n -------\n coef : ndarray\n Hermite series of power.\n\n See Also\n --------\n hermeadd, hermesub, hermemulx, hermemul, hermediv\n\n Examples\n --------\n >>> from numpy.polynomial.hermite_e import hermepow\n >>> hermepow([1, 2, 3], 2)\n array([23., 28., 46., 12., 9.])\n\n """\n return pu._pow(hermemul, c, pow, maxpower)\n\n\ndef hermeder(c, m=1, scl=1, axis=0):\n """\n Differentiate a Hermite_e series.\n\n Returns the series coefficients `c` differentiated `m` times along\n `axis`. At each iteration the result is multiplied by `scl` (the\n scaling factor is for use in a linear change of variable). The argument\n `c` is an array of coefficients from low to high degree along each\n axis, e.g., [1,2,3] represents the series ``1*He_0 + 2*He_1 + 3*He_2``\n while [[1,2],[1,2]] represents ``1*He_0(x)*He_0(y) + 1*He_1(x)*He_0(y)\n + 2*He_0(x)*He_1(y) + 2*He_1(x)*He_1(y)`` if axis=0 is ``x`` and axis=1\n is ``y``.\n\n Parameters\n ----------\n c : array_like\n Array of Hermite_e series coefficients. If `c` is multidimensional\n the different axis correspond to different variables with the\n degree in each axis given by the corresponding index.\n m : int, optional\n Number of derivatives taken, must be non-negative. (Default: 1)\n scl : scalar, optional\n Each differentiation is multiplied by `scl`. The end result is\n multiplication by ``scl**m``. This is for use in a linear change of\n variable. (Default: 1)\n axis : int, optional\n Axis over which the derivative is taken. (Default: 0).\n\n Returns\n -------\n der : ndarray\n Hermite series of the derivative.\n\n See Also\n --------\n hermeint\n\n Notes\n -----\n In general, the result of differentiating a Hermite series does not\n resemble the same operation on a power series. Thus the result of this\n function may be "unintuitive," albeit correct; see Examples section\n below.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite_e import hermeder\n >>> hermeder([ 1., 1., 1., 1.])\n array([1., 2., 3.])\n >>> hermeder([-0.25, 1., 1./2., 1./3., 1./4 ], m=2)\n array([1., 2., 3.])\n\n """\n c = np.array(c, ndmin=1, copy=True)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n cnt = pu._as_int(m, "the order of derivation")\n iaxis = pu._as_int(axis, "the axis")\n if cnt < 0:\n raise ValueError("The order of derivation must be non-negative")\n iaxis = normalize_axis_index(iaxis, c.ndim)\n\n if cnt == 0:\n return c\n\n c = np.moveaxis(c, iaxis, 0)\n n = len(c)\n if cnt >= n:\n return c[:1] * 0\n else:\n for i in range(cnt):\n n = n - 1\n c *= scl\n der = np.empty((n,) + c.shape[1:], dtype=c.dtype)\n for j in range(n, 0, -1):\n der[j - 1] = j * c[j]\n c = der\n c = np.moveaxis(c, 0, iaxis)\n return c\n\n\ndef hermeint(c, m=1, k=[], lbnd=0, scl=1, axis=0):\n """\n Integrate a Hermite_e series.\n\n Returns the Hermite_e series coefficients `c` integrated `m` times from\n `lbnd` along `axis`. At each iteration the resulting series is\n **multiplied** by `scl` and an integration constant, `k`, is added.\n The scaling factor is for use in a linear change of variable. ("Buyer\n beware": note that, depending on what one is doing, one may want `scl`\n to be the reciprocal of what one might expect; for more information,\n see the Notes section below.) The argument `c` is an array of\n coefficients from low to high degree along each axis, e.g., [1,2,3]\n represents the series ``H_0 + 2*H_1 + 3*H_2`` while [[1,2],[1,2]]\n represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) + 2*H_0(x)*H_1(y) +\n 2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.\n\n Parameters\n ----------\n c : array_like\n Array of Hermite_e series coefficients. If c is multidimensional\n the different axis correspond to different variables with the\n degree in each axis given by the corresponding index.\n m : int, optional\n Order of integration, must be positive. (Default: 1)\n k : {[], list, scalar}, optional\n Integration constant(s). The value of the first integral at\n ``lbnd`` is the first value in the list, the value of the second\n integral at ``lbnd`` is the second value, etc. If ``k == []`` (the\n default), all constants are set to zero. If ``m == 1``, a single\n scalar can be given instead of a list.\n lbnd : scalar, optional\n The lower bound of the integral. (Default: 0)\n scl : scalar, optional\n Following each integration the result is *multiplied* by `scl`\n before the integration constant is added. (Default: 1)\n axis : int, optional\n Axis over which the integral is taken. (Default: 0).\n\n Returns\n -------\n S : ndarray\n Hermite_e series coefficients of the integral.\n\n Raises\n ------\n ValueError\n If ``m < 0``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or\n ``np.ndim(scl) != 0``.\n\n See Also\n --------\n hermeder\n\n Notes\n -----\n Note that the result of each integration is *multiplied* by `scl`.\n Why is this important to note? Say one is making a linear change of\n variable :math:`u = ax + b` in an integral relative to `x`. Then\n :math:`dx = du/a`, so one will need to set `scl` equal to\n :math:`1/a` - perhaps not what one would have first thought.\n\n Also note that, in general, the result of integrating a C-series needs\n to be "reprojected" onto the C-series basis set. Thus, typically,\n the result of this function is "unintuitive," albeit correct; see\n Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite_e import hermeint\n >>> hermeint([1, 2, 3]) # integrate once, value 0 at 0.\n array([1., 1., 1., 1.])\n >>> hermeint([1, 2, 3], m=2) # integrate twice, value & deriv 0 at 0\n array([-0.25 , 1. , 0.5 , 0.33333333, 0.25 ]) # may vary\n >>> hermeint([1, 2, 3], k=1) # integrate once, value 1 at 0.\n array([2., 1., 1., 1.])\n >>> hermeint([1, 2, 3], lbnd=-1) # integrate once, value 0 at -1\n array([-1., 1., 1., 1.])\n >>> hermeint([1, 2, 3], m=2, k=[1, 2], lbnd=-1)\n array([ 1.83333333, 0. , 0.5 , 0.33333333, 0.25 ]) # may vary\n\n """\n c = np.array(c, ndmin=1, copy=True)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n if not np.iterable(k):\n k = [k]\n cnt = pu._as_int(m, "the order of integration")\n iaxis = pu._as_int(axis, "the axis")\n if cnt < 0:\n raise ValueError("The order of integration must be non-negative")\n if len(k) > cnt:\n raise ValueError("Too many integration constants")\n if np.ndim(lbnd) != 0:\n raise ValueError("lbnd must be a scalar.")\n if np.ndim(scl) != 0:\n raise ValueError("scl must be a scalar.")\n iaxis = normalize_axis_index(iaxis, c.ndim)\n\n if cnt == 0:\n return c\n\n c = np.moveaxis(c, iaxis, 0)\n k = list(k) + [0] * (cnt - len(k))\n for i in range(cnt):\n n = len(c)\n c *= scl\n if n == 1 and np.all(c[0] == 0):\n c[0] += k[i]\n else:\n tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)\n tmp[0] = c[0] * 0\n tmp[1] = c[0]\n for j in range(1, n):\n tmp[j + 1] = c[j] / (j + 1)\n tmp[0] += k[i] - hermeval(lbnd, tmp)\n c = tmp\n c = np.moveaxis(c, 0, iaxis)\n return c\n\n\ndef hermeval(x, c, tensor=True):\n """\n Evaluate an HermiteE series at points x.\n\n If `c` is of length ``n + 1``, this function returns the value:\n\n .. math:: p(x) = c_0 * He_0(x) + c_1 * He_1(x) + ... + c_n * He_n(x)\n\n The parameter `x` is converted to an array only if it is a tuple or a\n list, otherwise it is treated as a scalar. In either case, either `x`\n or its elements must support multiplication and addition both with\n themselves and with the elements of `c`.\n\n If `c` is a 1-D array, then ``p(x)`` will have the same shape as `x`. If\n `c` is multidimensional, then the shape of the result depends on the\n value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +\n x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that\n scalars have shape (,).\n\n Trailing zeros in the coefficients will be used in the evaluation, so\n they should be avoided if efficiency is a concern.\n\n Parameters\n ----------\n x : array_like, compatible object\n If `x` is a list or tuple, it is converted to an ndarray, otherwise\n it is left unchanged and treated as a scalar. In either case, `x`\n or its elements must support addition and multiplication with\n with themselves and with the elements of `c`.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree n are contained in c[n]. If `c` is multidimensional the\n remaining indices enumerate multiple polynomials. In the two\n dimensional case the coefficients may be thought of as stored in\n the columns of `c`.\n tensor : boolean, optional\n If True, the shape of the coefficient array is extended with ones\n on the right, one for each dimension of `x`. Scalars have dimension 0\n for this action. The result is that every column of coefficients in\n `c` is evaluated for every element of `x`. If False, `x` is broadcast\n over the columns of `c` for the evaluation. This keyword is useful\n when `c` is multidimensional. The default value is True.\n\n Returns\n -------\n values : ndarray, algebra_like\n The shape of the return value is described above.\n\n See Also\n --------\n hermeval2d, hermegrid2d, hermeval3d, hermegrid3d\n\n Notes\n -----\n The evaluation uses Clenshaw recursion, aka synthetic division.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite_e import hermeval\n >>> coef = [1,2,3]\n >>> hermeval(1, coef)\n 3.0\n >>> hermeval([[1,2],[3,4]], coef)\n array([[ 3., 14.],\n [31., 54.]])\n\n """\n c = np.array(c, ndmin=1, copy=None)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n if isinstance(x, (tuple, list)):\n x = np.asarray(x)\n if isinstance(x, np.ndarray) and tensor:\n c = c.reshape(c.shape + (1,) * x.ndim)\n\n if len(c) == 1:\n c0 = c[0]\n c1 = 0\n elif len(c) == 2:\n c0 = c[0]\n c1 = c[1]\n else:\n nd = len(c)\n c0 = c[-2]\n c1 = c[-1]\n for i in range(3, len(c) + 1):\n tmp = c0\n nd = nd - 1\n c0 = c[-i] - c1 * (nd - 1)\n c1 = tmp + c1 * x\n return c0 + c1 * x\n\n\ndef hermeval2d(x, y, c):\n """\n Evaluate a 2-D HermiteE series at points (x, y).\n\n This function returns the values:\n\n .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * He_i(x) * He_j(y)\n\n The parameters `x` and `y` are converted to arrays only if they are\n tuples or a lists, otherwise they are treated as a scalars and they\n must have the same shape after conversion. In either case, either `x`\n and `y` or their elements must support multiplication and addition both\n with themselves and with the elements of `c`.\n\n If `c` is a 1-D array a one is implicitly appended to its shape to make\n it 2-D. The shape of the result will be c.shape[2:] + x.shape.\n\n Parameters\n ----------\n x, y : array_like, compatible objects\n The two dimensional series is evaluated at the points ``(x, y)``,\n where `x` and `y` must have the same shape. If `x` or `y` is a list\n or tuple, it is first converted to an ndarray, otherwise it is left\n unchanged and if it isn't an ndarray it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term\n of multi-degree i,j is contained in ``c[i,j]``. If `c` has\n dimension greater than two the remaining indices enumerate multiple\n sets of coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points formed with\n pairs of corresponding values from `x` and `y`.\n\n See Also\n --------\n hermeval, hermegrid2d, hermeval3d, hermegrid3d\n """\n return pu._valnd(hermeval, c, x, y)\n\n\ndef hermegrid2d(x, y, c):\n """\n Evaluate a 2-D HermiteE series on the Cartesian product of x and y.\n\n This function returns the values:\n\n .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * H_i(a) * H_j(b)\n\n where the points ``(a, b)`` consist of all pairs formed by taking\n `a` from `x` and `b` from `y`. The resulting points form a grid with\n `x` in the first dimension and `y` in the second.\n\n The parameters `x` and `y` are converted to arrays only if they are\n tuples or a lists, otherwise they are treated as a scalars. In either\n case, either `x` and `y` or their elements must support multiplication\n and addition both with themselves and with the elements of `c`.\n\n If `c` has fewer than two dimensions, ones are implicitly appended to\n its shape to make it 2-D. The shape of the result will be c.shape[2:] +\n x.shape.\n\n Parameters\n ----------\n x, y : array_like, compatible objects\n The two dimensional series is evaluated at the points in the\n Cartesian product of `x` and `y`. If `x` or `y` is a list or\n tuple, it is first converted to an ndarray, otherwise it is left\n unchanged and, if it isn't an ndarray, it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree i,j are contained in ``c[i,j]``. If `c` has dimension\n greater than two the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points in the Cartesian\n product of `x` and `y`.\n\n See Also\n --------\n hermeval, hermeval2d, hermeval3d, hermegrid3d\n """\n return pu._gridnd(hermeval, c, x, y)\n\n\ndef hermeval3d(x, y, z, c):\n """\n Evaluate a 3-D Hermite_e series at points (x, y, z).\n\n This function returns the values:\n\n .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * He_i(x) * He_j(y) * He_k(z)\n\n The parameters `x`, `y`, and `z` are converted to arrays only if\n they are tuples or a lists, otherwise they are treated as a scalars and\n they must have the same shape after conversion. In either case, either\n `x`, `y`, and `z` or their elements must support multiplication and\n addition both with themselves and with the elements of `c`.\n\n If `c` has fewer than 3 dimensions, ones are implicitly appended to its\n shape to make it 3-D. The shape of the result will be c.shape[3:] +\n x.shape.\n\n Parameters\n ----------\n x, y, z : array_like, compatible object\n The three dimensional series is evaluated at the points\n `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If\n any of `x`, `y`, or `z` is a list or tuple, it is first converted\n to an ndarray, otherwise it is left unchanged and if it isn't an\n ndarray it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term of\n multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension\n greater than 3 the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the multidimensional polynomial on points formed with\n triples of corresponding values from `x`, `y`, and `z`.\n\n See Also\n --------\n hermeval, hermeval2d, hermegrid2d, hermegrid3d\n """\n return pu._valnd(hermeval, c, x, y, z)\n\n\ndef hermegrid3d(x, y, z, c):\n """\n Evaluate a 3-D HermiteE series on the Cartesian product of x, y, and z.\n\n This function returns the values:\n\n .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * He_i(a) * He_j(b) * He_k(c)\n\n where the points ``(a, b, c)`` consist of all triples formed by taking\n `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form\n a grid with `x` in the first dimension, `y` in the second, and `z` in\n the third.\n\n The parameters `x`, `y`, and `z` are converted to arrays only if they\n are tuples or a lists, otherwise they are treated as a scalars. In\n either case, either `x`, `y`, and `z` or their elements must support\n multiplication and addition both with themselves and with the elements\n of `c`.\n\n If `c` has fewer than three dimensions, ones are implicitly appended to\n its shape to make it 3-D. The shape of the result will be c.shape[3:] +\n x.shape + y.shape + z.shape.\n\n Parameters\n ----------\n x, y, z : array_like, compatible objects\n The three dimensional series is evaluated at the points in the\n Cartesian product of `x`, `y`, and `z`. If `x`, `y`, or `z` is a\n list or tuple, it is first converted to an ndarray, otherwise it is\n left unchanged and, if it isn't an ndarray, it is treated as a\n scalar.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree i,j are contained in ``c[i,j]``. If `c` has dimension\n greater than two the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points in the Cartesian\n product of `x` and `y`.\n\n See Also\n --------\n hermeval, hermeval2d, hermegrid2d, hermeval3d\n """\n return pu._gridnd(hermeval, c, x, y, z)\n\n\ndef hermevander(x, deg):\n """Pseudo-Vandermonde matrix of given degree.\n\n Returns the pseudo-Vandermonde matrix of degree `deg` and sample points\n `x`. The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., i] = He_i(x),\n\n where ``0 <= i <= deg``. The leading indices of `V` index the elements of\n `x` and the last index is the degree of the HermiteE polynomial.\n\n If `c` is a 1-D array of coefficients of length ``n + 1`` and `V` is the\n array ``V = hermevander(x, n)``, then ``np.dot(V, c)`` and\n ``hermeval(x, c)`` are the same up to roundoff. This equivalence is\n useful both for least squares fitting and for the evaluation of a large\n number of HermiteE series of the same degree and sample points.\n\n Parameters\n ----------\n x : array_like\n Array of points. The dtype is converted to float64 or complex128\n depending on whether any of the elements are complex. If `x` is\n scalar it is converted to a 1-D array.\n deg : int\n Degree of the resulting matrix.\n\n Returns\n -------\n vander : ndarray\n The pseudo-Vandermonde matrix. The shape of the returned matrix is\n ``x.shape + (deg + 1,)``, where The last index is the degree of the\n corresponding HermiteE polynomial. The dtype will be the same as\n the converted `x`.\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial.hermite_e import hermevander\n >>> x = np.array([-1, 0, 1])\n >>> hermevander(x, 3)\n array([[ 1., -1., 0., 2.],\n [ 1., 0., -1., -0.],\n [ 1., 1., 0., -2.]])\n\n """\n ideg = pu._as_int(deg, "deg")\n if ideg < 0:\n raise ValueError("deg must be non-negative")\n\n x = np.array(x, copy=None, ndmin=1) + 0.0\n dims = (ideg + 1,) + x.shape\n dtyp = x.dtype\n v = np.empty(dims, dtype=dtyp)\n v[0] = x * 0 + 1\n if ideg > 0:\n v[1] = x\n for i in range(2, ideg + 1):\n v[i] = (v[i - 1] * x - v[i - 2] * (i - 1))\n return np.moveaxis(v, 0, -1)\n\n\ndef hermevander2d(x, y, deg):\n """Pseudo-Vandermonde matrix of given degrees.\n\n Returns the pseudo-Vandermonde matrix of degrees `deg` and sample\n points ``(x, y)``. The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., (deg[1] + 1)*i + j] = He_i(x) * He_j(y),\n\n where ``0 <= i <= deg[0]`` and ``0 <= j <= deg[1]``. The leading indices of\n `V` index the points ``(x, y)`` and the last index encodes the degrees of\n the HermiteE polynomials.\n\n If ``V = hermevander2d(x, y, [xdeg, ydeg])``, then the columns of `V`\n correspond to the elements of a 2-D coefficient array `c` of shape\n (xdeg + 1, ydeg + 1) in the order\n\n .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...\n\n and ``np.dot(V, c.flat)`` and ``hermeval2d(x, y, c)`` will be the same\n up to roundoff. This equivalence is useful both for least squares\n fitting and for the evaluation of a large number of 2-D HermiteE\n series of the same degrees and sample points.\n\n Parameters\n ----------\n x, y : array_like\n Arrays of point coordinates, all of the same shape. The dtypes\n will be converted to either float64 or complex128 depending on\n whether any of the elements are complex. Scalars are converted to\n 1-D arrays.\n deg : list of ints\n List of maximum degrees of the form [x_deg, y_deg].\n\n Returns\n -------\n vander2d : ndarray\n The shape of the returned matrix is ``x.shape + (order,)``, where\n :math:`order = (deg[0]+1)*(deg[1]+1)`. The dtype will be the same\n as the converted `x` and `y`.\n\n See Also\n --------\n hermevander, hermevander3d, hermeval2d, hermeval3d\n """\n return pu._vander_nd_flat((hermevander, hermevander), (x, y), deg)\n\n\ndef hermevander3d(x, y, z, deg):\n """Pseudo-Vandermonde matrix of given degrees.\n\n Returns the pseudo-Vandermonde matrix of degrees `deg` and sample\n points ``(x, y, z)``. If `l`, `m`, `n` are the given degrees in `x`, `y`, `z`,\n then Hehe pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = He_i(x)*He_j(y)*He_k(z),\n\n where ``0 <= i <= l``, ``0 <= j <= m``, and ``0 <= j <= n``. The leading\n indices of `V` index the points ``(x, y, z)`` and the last index encodes\n the degrees of the HermiteE polynomials.\n\n If ``V = hermevander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns\n of `V` correspond to the elements of a 3-D coefficient array `c` of\n shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order\n\n .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...\n\n and ``np.dot(V, c.flat)`` and ``hermeval3d(x, y, z, c)`` will be the\n same up to roundoff. This equivalence is useful both for least squares\n fitting and for the evaluation of a large number of 3-D HermiteE\n series of the same degrees and sample points.\n\n Parameters\n ----------\n x, y, z : array_like\n Arrays of point coordinates, all of the same shape. The dtypes will\n be converted to either float64 or complex128 depending on whether\n any of the elements are complex. Scalars are converted to 1-D\n arrays.\n deg : list of ints\n List of maximum degrees of the form [x_deg, y_deg, z_deg].\n\n Returns\n -------\n vander3d : ndarray\n The shape of the returned matrix is ``x.shape + (order,)``, where\n :math:`order = (deg[0]+1)*(deg[1]+1)*(deg[2]+1)`. The dtype will\n be the same as the converted `x`, `y`, and `z`.\n\n See Also\n --------\n hermevander, hermevander3d, hermeval2d, hermeval3d\n """\n return pu._vander_nd_flat((hermevander, hermevander, hermevander), (x, y, z), deg)\n\n\ndef hermefit(x, y, deg, rcond=None, full=False, w=None):\n """\n Least squares fit of Hermite series to data.\n\n Return the coefficients of a HermiteE series of degree `deg` that is\n the least squares fit to the data values `y` given at points `x`. If\n `y` is 1-D the returned coefficients will also be 1-D. If `y` is 2-D\n multiple fits are done, one for each column of `y`, and the resulting\n coefficients are stored in the corresponding columns of a 2-D return.\n The fitted polynomial(s) are in the form\n\n .. math:: p(x) = c_0 + c_1 * He_1(x) + ... + c_n * He_n(x),\n\n where `n` is `deg`.\n\n Parameters\n ----------\n x : array_like, shape (M,)\n x-coordinates of the M sample points ``(x[i], y[i])``.\n y : array_like, shape (M,) or (M, K)\n y-coordinates of the sample points. Several data sets of sample\n points sharing the same x-coordinates can be fitted at once by\n passing in a 2D-array that contains one dataset per column.\n deg : int or 1-D array_like\n Degree(s) of the fitting polynomials. If `deg` is a single integer\n all terms up to and including the `deg`'th term are included in the\n fit. For NumPy versions >= 1.11.0 a list of integers specifying the\n degrees of the terms to include may be used instead.\n rcond : float, optional\n Relative condition number of the fit. Singular values smaller than\n this relative to the largest singular value will be ignored. The\n default value is len(x)*eps, where eps is the relative precision of\n the float type, about 2e-16 in most cases.\n full : bool, optional\n Switch determining nature of return value. When it is False (the\n default) just the coefficients are returned, when True diagnostic\n information from the singular value decomposition is also returned.\n w : array_like, shape (`M`,), optional\n Weights. If not None, the weight ``w[i]`` applies to the unsquared\n residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are\n chosen so that the errors of the products ``w[i]*y[i]`` all have the\n same variance. When using inverse-variance weighting, use\n ``w[i] = 1/sigma(y[i])``. The default value is None.\n\n Returns\n -------\n coef : ndarray, shape (M,) or (M, K)\n Hermite coefficients ordered from low to high. If `y` was 2-D,\n the coefficients for the data in column k of `y` are in column\n `k`.\n\n [residuals, rank, singular_values, rcond] : list\n These values are only returned if ``full == True``\n\n - residuals -- sum of squared residuals of the least squares fit\n - rank -- the numerical rank of the scaled Vandermonde matrix\n - singular_values -- singular values of the scaled Vandermonde matrix\n - rcond -- value of `rcond`.\n\n For more details, see `numpy.linalg.lstsq`.\n\n Warns\n -----\n RankWarning\n The rank of the coefficient matrix in the least-squares fit is\n deficient. The warning is only raised if ``full = False``. The\n warnings can be turned off by\n\n >>> import warnings\n >>> warnings.simplefilter('ignore', np.exceptions.RankWarning)\n\n See Also\n --------\n numpy.polynomial.chebyshev.chebfit\n numpy.polynomial.legendre.legfit\n numpy.polynomial.polynomial.polyfit\n numpy.polynomial.hermite.hermfit\n numpy.polynomial.laguerre.lagfit\n hermeval : Evaluates a Hermite series.\n hermevander : pseudo Vandermonde matrix of Hermite series.\n hermeweight : HermiteE weight function.\n numpy.linalg.lstsq : Computes a least-squares fit from the matrix.\n scipy.interpolate.UnivariateSpline : Computes spline fits.\n\n Notes\n -----\n The solution is the coefficients of the HermiteE series `p` that\n minimizes the sum of the weighted squared errors\n\n .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,\n\n where the :math:`w_j` are the weights. This problem is solved by\n setting up the (typically) overdetermined matrix equation\n\n .. math:: V(x) * c = w * y,\n\n where `V` is the pseudo Vandermonde matrix of `x`, the elements of `c`\n are the coefficients to be solved for, and the elements of `y` are the\n observed values. This equation is then solved using the singular value\n decomposition of `V`.\n\n If some of the singular values of `V` are so small that they are\n neglected, then a `~exceptions.RankWarning` will be issued. This means that\n the coefficient values may be poorly determined. Using a lower order fit\n will usually get rid of the warning. The `rcond` parameter can also be\n set to a value smaller than its default, but the resulting fit may be\n spurious and have large contributions from roundoff error.\n\n Fits using HermiteE series are probably most useful when the data can\n be approximated by ``sqrt(w(x)) * p(x)``, where ``w(x)`` is the HermiteE\n weight. In that case the weight ``sqrt(w(x[i]))`` should be used\n together with data values ``y[i]/sqrt(w(x[i]))``. The weight function is\n available as `hermeweight`.\n\n References\n ----------\n .. [1] Wikipedia, "Curve fitting",\n https://en.wikipedia.org/wiki/Curve_fitting\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial.hermite_e import hermefit, hermeval\n >>> x = np.linspace(-10, 10)\n >>> rng = np.random.default_rng()\n >>> err = rng.normal(scale=1./10, size=len(x))\n >>> y = hermeval(x, [1, 2, 3]) + err\n >>> hermefit(x, y, 2)\n array([1.02284196, 2.00032805, 2.99978457]) # may vary\n\n """\n return pu._fit(hermevander, x, y, deg, rcond, full, w)\n\n\ndef hermecompanion(c):\n """\n Return the scaled companion matrix of c.\n\n The basis polynomials are scaled so that the companion matrix is\n symmetric when `c` is an HermiteE basis polynomial. This provides\n better eigenvalue estimates than the unscaled case and for basis\n polynomials the eigenvalues are guaranteed to be real if\n `numpy.linalg.eigvalsh` is used to obtain them.\n\n Parameters\n ----------\n c : array_like\n 1-D array of HermiteE series coefficients ordered from low to high\n degree.\n\n Returns\n -------\n mat : ndarray\n Scaled companion matrix of dimensions (deg, deg).\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n if len(c) < 2:\n raise ValueError('Series must have maximum degree of at least 1.')\n if len(c) == 2:\n return np.array([[-c[0] / c[1]]])\n\n n = len(c) - 1\n mat = np.zeros((n, n), dtype=c.dtype)\n scl = np.hstack((1., 1. / np.sqrt(np.arange(n - 1, 0, -1))))\n scl = np.multiply.accumulate(scl)[::-1]\n top = mat.reshape(-1)[1::n + 1]\n bot = mat.reshape(-1)[n::n + 1]\n top[...] = np.sqrt(np.arange(1, n))\n bot[...] = top\n mat[:, -1] -= scl * c[:-1] / c[-1]\n return mat\n\n\ndef hermeroots(c):\n """\n Compute the roots of a HermiteE series.\n\n Return the roots (a.k.a. "zeros") of the polynomial\n\n .. math:: p(x) = \\sum_i c[i] * He_i(x).\n\n Parameters\n ----------\n c : 1-D array_like\n 1-D array of coefficients.\n\n Returns\n -------\n out : ndarray\n Array of the roots of the series. If all the roots are real,\n then `out` is also real, otherwise it is complex.\n\n See Also\n --------\n numpy.polynomial.polynomial.polyroots\n numpy.polynomial.legendre.legroots\n numpy.polynomial.laguerre.lagroots\n numpy.polynomial.hermite.hermroots\n numpy.polynomial.chebyshev.chebroots\n\n Notes\n -----\n The root estimates are obtained as the eigenvalues of the companion\n matrix, Roots far from the origin of the complex plane may have large\n errors due to the numerical instability of the series for such\n values. Roots with multiplicity greater than 1 will also show larger\n errors as the value of the series near such points is relatively\n insensitive to errors in the roots. Isolated roots near the origin can\n be improved by a few iterations of Newton's method.\n\n The HermiteE series basis polynomials aren't powers of `x` so the\n results of this function may seem unintuitive.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite_e import hermeroots, hermefromroots\n >>> coef = hermefromroots([-1, 0, 1])\n >>> coef\n array([0., 2., 0., 1.])\n >>> hermeroots(coef)\n array([-1., 0., 1.]) # may vary\n\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n if len(c) <= 1:\n return np.array([], dtype=c.dtype)\n if len(c) == 2:\n return np.array([-c[0] / c[1]])\n\n # rotated companion matrix reduces error\n m = hermecompanion(c)[::-1, ::-1]\n r = la.eigvals(m)\n r.sort()\n return r\n\n\ndef _normed_hermite_e_n(x, n):\n """\n Evaluate a normalized HermiteE polynomial.\n\n Compute the value of the normalized HermiteE polynomial of degree ``n``\n at the points ``x``.\n\n\n Parameters\n ----------\n x : ndarray of double.\n Points at which to evaluate the function\n n : int\n Degree of the normalized HermiteE function to be evaluated.\n\n Returns\n -------\n values : ndarray\n The shape of the return value is described above.\n\n Notes\n -----\n This function is needed for finding the Gauss points and integration\n weights for high degrees. The values of the standard HermiteE functions\n overflow when n >= 207.\n\n """\n if n == 0:\n return np.full(x.shape, 1 / np.sqrt(np.sqrt(2 * np.pi)))\n\n c0 = 0.\n c1 = 1. / np.sqrt(np.sqrt(2 * np.pi))\n nd = float(n)\n for i in range(n - 1):\n tmp = c0\n c0 = -c1 * np.sqrt((nd - 1.) / nd)\n c1 = tmp + c1 * x * np.sqrt(1. / nd)\n nd = nd - 1.0\n return c0 + c1 * x\n\n\ndef hermegauss(deg):\n """\n Gauss-HermiteE quadrature.\n\n Computes the sample points and weights for Gauss-HermiteE quadrature.\n These sample points and weights will correctly integrate polynomials of\n degree :math:`2*deg - 1` or less over the interval :math:`[-\\inf, \\inf]`\n with the weight function :math:`f(x) = \\exp(-x^2/2)`.\n\n Parameters\n ----------\n deg : int\n Number of sample points and weights. It must be >= 1.\n\n Returns\n -------\n x : ndarray\n 1-D ndarray containing the sample points.\n y : ndarray\n 1-D ndarray containing the weights.\n\n Notes\n -----\n The results have only been tested up to degree 100, higher degrees may\n be problematic. The weights are determined by using the fact that\n\n .. math:: w_k = c / (He'_n(x_k) * He_{n-1}(x_k))\n\n where :math:`c` is a constant independent of :math:`k` and :math:`x_k`\n is the k'th root of :math:`He_n`, and then scaling the results to get\n the right value when integrating 1.\n\n """\n ideg = pu._as_int(deg, "deg")\n if ideg <= 0:\n raise ValueError("deg must be a positive integer")\n\n # first approximation of roots. We use the fact that the companion\n # matrix is symmetric in this case in order to obtain better zeros.\n c = np.array([0] * deg + [1])\n m = hermecompanion(c)\n x = la.eigvalsh(m)\n\n # improve roots by one application of Newton\n dy = _normed_hermite_e_n(x, ideg)\n df = _normed_hermite_e_n(x, ideg - 1) * np.sqrt(ideg)\n x -= dy / df\n\n # compute the weights. We scale the factor to avoid possible numerical\n # overflow.\n fm = _normed_hermite_e_n(x, ideg - 1)\n fm /= np.abs(fm).max()\n w = 1 / (fm * fm)\n\n # for Hermite_e we can also symmetrize\n w = (w + w[::-1]) / 2\n x = (x - x[::-1]) / 2\n\n # scale w to get the right value\n w *= np.sqrt(2 * np.pi) / w.sum()\n\n return x, w\n\n\ndef hermeweight(x):\n """Weight function of the Hermite_e polynomials.\n\n The weight function is :math:`\\exp(-x^2/2)` and the interval of\n integration is :math:`[-\\inf, \\inf]`. the HermiteE polynomials are\n orthogonal, but not normalized, with respect to this weight function.\n\n Parameters\n ----------\n x : array_like\n Values at which the weight function will be computed.\n\n Returns\n -------\n w : ndarray\n The weight function at `x`.\n """\n w = np.exp(-.5 * x**2)\n return w\n\n\n#\n# HermiteE series class\n#\n\nclass HermiteE(ABCPolyBase):\n """An HermiteE series class.\n\n The HermiteE class provides the standard Python numerical methods\n '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the\n attributes and methods listed below.\n\n Parameters\n ----------\n coef : array_like\n HermiteE coefficients in order of increasing degree, i.e,\n ``(1, 2, 3)`` gives ``1*He_0(x) + 2*He_1(X) + 3*He_2(x)``.\n domain : (2,) array_like, optional\n Domain to use. The interval ``[domain[0], domain[1]]`` is mapped\n to the interval ``[window[0], window[1]]`` by shifting and scaling.\n The default value is [-1., 1.].\n window : (2,) array_like, optional\n Window, see `domain` for its use. The default value is [-1., 1.].\n symbol : str, optional\n Symbol used to represent the independent variable in string\n representations of the polynomial expression, e.g. for printing.\n The symbol must be a valid Python identifier. Default value is 'x'.\n\n .. versionadded:: 1.24\n\n """\n # Virtual Functions\n _add = staticmethod(hermeadd)\n _sub = staticmethod(hermesub)\n _mul = staticmethod(hermemul)\n _div = staticmethod(hermediv)\n _pow = staticmethod(hermepow)\n _val = staticmethod(hermeval)\n _int = staticmethod(hermeint)\n _der = staticmethod(hermeder)\n _fit = staticmethod(hermefit)\n _line = staticmethod(hermeline)\n _roots = staticmethod(hermeroots)\n _fromroots = staticmethod(hermefromroots)\n\n # Virtual properties\n domain = np.array(hermedomain)\n window = np.array(hermedomain)\n basis_name = 'He'\n | .venv\Lib\site-packages\numpy\polynomial\hermite_e.py | hermite_e.py | Python | 53,947 | 0.75 | 0.089525 | 0.02099 | python-kit | 417 | 2024-03-31T16:40:41.396472 | MIT | false | f58c17989254578f244dabc6dd1f1dc5 |
from typing import Any, Final, TypeVar\nfrom typing import Literal as L\n\nimport numpy as np\n\nfrom ._polybase import ABCPolyBase\nfrom ._polytypes import (\n _Array1,\n _Array2,\n _FuncBinOp,\n _FuncCompanion,\n _FuncDer,\n _FuncFit,\n _FuncFromRoots,\n _FuncGauss,\n _FuncInteg,\n _FuncLine,\n _FuncPoly2Ortho,\n _FuncPow,\n _FuncRoots,\n _FuncUnOp,\n _FuncVal,\n _FuncVal2D,\n _FuncVal3D,\n _FuncValFromRoots,\n _FuncVander,\n _FuncVander2D,\n _FuncVander3D,\n _FuncWeight,\n)\nfrom .polyutils import trimcoef as hermetrim\n\n__all__ = [\n "hermezero",\n "hermeone",\n "hermex",\n "hermedomain",\n "hermeline",\n "hermeadd",\n "hermesub",\n "hermemulx",\n "hermemul",\n "hermediv",\n "hermepow",\n "hermeval",\n "hermeder",\n "hermeint",\n "herme2poly",\n "poly2herme",\n "hermefromroots",\n "hermevander",\n "hermefit",\n "hermetrim",\n "hermeroots",\n "HermiteE",\n "hermeval2d",\n "hermeval3d",\n "hermegrid2d",\n "hermegrid3d",\n "hermevander2d",\n "hermevander3d",\n "hermecompanion",\n "hermegauss",\n "hermeweight",\n]\n\npoly2herme: _FuncPoly2Ortho[L["poly2herme"]]\nherme2poly: _FuncUnOp[L["herme2poly"]]\n\nhermedomain: Final[_Array2[np.float64]]\nhermezero: Final[_Array1[np.int_]]\nhermeone: Final[_Array1[np.int_]]\nhermex: Final[_Array2[np.int_]]\n\nhermeline: _FuncLine[L["hermeline"]]\nhermefromroots: _FuncFromRoots[L["hermefromroots"]]\nhermeadd: _FuncBinOp[L["hermeadd"]]\nhermesub: _FuncBinOp[L["hermesub"]]\nhermemulx: _FuncUnOp[L["hermemulx"]]\nhermemul: _FuncBinOp[L["hermemul"]]\nhermediv: _FuncBinOp[L["hermediv"]]\nhermepow: _FuncPow[L["hermepow"]]\nhermeder: _FuncDer[L["hermeder"]]\nhermeint: _FuncInteg[L["hermeint"]]\nhermeval: _FuncVal[L["hermeval"]]\nhermeval2d: _FuncVal2D[L["hermeval2d"]]\nhermeval3d: _FuncVal3D[L["hermeval3d"]]\nhermevalfromroots: _FuncValFromRoots[L["hermevalfromroots"]]\nhermegrid2d: _FuncVal2D[L["hermegrid2d"]]\nhermegrid3d: _FuncVal3D[L["hermegrid3d"]]\nhermevander: _FuncVander[L["hermevander"]]\nhermevander2d: _FuncVander2D[L["hermevander2d"]]\nhermevander3d: _FuncVander3D[L["hermevander3d"]]\nhermefit: _FuncFit[L["hermefit"]]\nhermecompanion: _FuncCompanion[L["hermecompanion"]]\nhermeroots: _FuncRoots[L["hermeroots"]]\n\n_ND = TypeVar("_ND", bound=Any)\ndef _normed_hermite_e_n(\n x: np.ndarray[_ND, np.dtype[np.float64]],\n n: int | np.intp,\n) -> np.ndarray[_ND, np.dtype[np.float64]]: ...\n\nhermegauss: _FuncGauss[L["hermegauss"]]\nhermeweight: _FuncWeight[L["hermeweight"]]\n\nclass HermiteE(ABCPolyBase[L["He"]]): ...\n | .venv\Lib\site-packages\numpy\polynomial\hermite_e.pyi | hermite_e.pyi | Other | 2,662 | 0.85 | 0.018692 | 0 | react-lib | 885 | 2024-04-14T14:48:56.314884 | MIT | false | 92320443330c4090e677a819fcea809a |
"""\n==================================================\nLaguerre Series (:mod:`numpy.polynomial.laguerre`)\n==================================================\n\nThis module provides a number of objects (mostly functions) useful for\ndealing with Laguerre series, including a `Laguerre` class that\nencapsulates the usual arithmetic operations. (General information\non how this module represents and works with such polynomials is in the\ndocstring for its "parent" sub-package, `numpy.polynomial`).\n\nClasses\n-------\n.. autosummary::\n :toctree: generated/\n\n Laguerre\n\nConstants\n---------\n.. autosummary::\n :toctree: generated/\n\n lagdomain\n lagzero\n lagone\n lagx\n\nArithmetic\n----------\n.. autosummary::\n :toctree: generated/\n\n lagadd\n lagsub\n lagmulx\n lagmul\n lagdiv\n lagpow\n lagval\n lagval2d\n lagval3d\n laggrid2d\n laggrid3d\n\nCalculus\n--------\n.. autosummary::\n :toctree: generated/\n\n lagder\n lagint\n\nMisc Functions\n--------------\n.. autosummary::\n :toctree: generated/\n\n lagfromroots\n lagroots\n lagvander\n lagvander2d\n lagvander3d\n laggauss\n lagweight\n lagcompanion\n lagfit\n lagtrim\n lagline\n lag2poly\n poly2lag\n\nSee also\n--------\n`numpy.polynomial`\n\n"""\nimport numpy as np\nimport numpy.linalg as la\nfrom numpy.lib.array_utils import normalize_axis_index\n\nfrom . import polyutils as pu\nfrom ._polybase import ABCPolyBase\n\n__all__ = [\n 'lagzero', 'lagone', 'lagx', 'lagdomain', 'lagline', 'lagadd',\n 'lagsub', 'lagmulx', 'lagmul', 'lagdiv', 'lagpow', 'lagval', 'lagder',\n 'lagint', 'lag2poly', 'poly2lag', 'lagfromroots', 'lagvander',\n 'lagfit', 'lagtrim', 'lagroots', 'Laguerre', 'lagval2d', 'lagval3d',\n 'laggrid2d', 'laggrid3d', 'lagvander2d', 'lagvander3d', 'lagcompanion',\n 'laggauss', 'lagweight']\n\nlagtrim = pu.trimcoef\n\n\ndef poly2lag(pol):\n """\n poly2lag(pol)\n\n Convert a polynomial to a Laguerre series.\n\n Convert an array representing the coefficients of a polynomial (relative\n to the "standard" basis) ordered from lowest degree to highest, to an\n array of the coefficients of the equivalent Laguerre series, ordered\n from lowest to highest degree.\n\n Parameters\n ----------\n pol : array_like\n 1-D array containing the polynomial coefficients\n\n Returns\n -------\n c : ndarray\n 1-D array containing the coefficients of the equivalent Laguerre\n series.\n\n See Also\n --------\n lag2poly\n\n Notes\n -----\n The easy way to do conversions between polynomial basis sets\n is to use the convert method of a class instance.\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial.laguerre import poly2lag\n >>> poly2lag(np.arange(4))\n array([ 23., -63., 58., -18.])\n\n """\n [pol] = pu.as_series([pol])\n res = 0\n for p in pol[::-1]:\n res = lagadd(lagmulx(res), p)\n return res\n\n\ndef lag2poly(c):\n """\n Convert a Laguerre series to a polynomial.\n\n Convert an array representing the coefficients of a Laguerre series,\n ordered from lowest degree to highest, to an array of the coefficients\n of the equivalent polynomial (relative to the "standard" basis) ordered\n from lowest to highest degree.\n\n Parameters\n ----------\n c : array_like\n 1-D array containing the Laguerre series coefficients, ordered\n from lowest order term to highest.\n\n Returns\n -------\n pol : ndarray\n 1-D array containing the coefficients of the equivalent polynomial\n (relative to the "standard" basis) ordered from lowest order term\n to highest.\n\n See Also\n --------\n poly2lag\n\n Notes\n -----\n The easy way to do conversions between polynomial basis sets\n is to use the convert method of a class instance.\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lag2poly\n >>> lag2poly([ 23., -63., 58., -18.])\n array([0., 1., 2., 3.])\n\n """\n from .polynomial import polyadd, polymulx, polysub\n\n [c] = pu.as_series([c])\n n = len(c)\n if n == 1:\n return c\n else:\n c0 = c[-2]\n c1 = c[-1]\n # i is the current degree of c1\n for i in range(n - 1, 1, -1):\n tmp = c0\n c0 = polysub(c[i - 2], (c1 * (i - 1)) / i)\n c1 = polyadd(tmp, polysub((2 * i - 1) * c1, polymulx(c1)) / i)\n return polyadd(c0, polysub(c1, polymulx(c1)))\n\n\n#\n# These are constant arrays are of integer type so as to be compatible\n# with the widest range of other types, such as Decimal.\n#\n\n# Laguerre\nlagdomain = np.array([0., 1.])\n\n# Laguerre coefficients representing zero.\nlagzero = np.array([0])\n\n# Laguerre coefficients representing one.\nlagone = np.array([1])\n\n# Laguerre coefficients representing the identity x.\nlagx = np.array([1, -1])\n\n\ndef lagline(off, scl):\n """\n Laguerre series whose graph is a straight line.\n\n Parameters\n ----------\n off, scl : scalars\n The specified line is given by ``off + scl*x``.\n\n Returns\n -------\n y : ndarray\n This module's representation of the Laguerre series for\n ``off + scl*x``.\n\n See Also\n --------\n numpy.polynomial.polynomial.polyline\n numpy.polynomial.chebyshev.chebline\n numpy.polynomial.legendre.legline\n numpy.polynomial.hermite.hermline\n numpy.polynomial.hermite_e.hermeline\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagline, lagval\n >>> lagval(0,lagline(3, 2))\n 3.0\n >>> lagval(1,lagline(3, 2))\n 5.0\n\n """\n if scl != 0:\n return np.array([off + scl, -scl])\n else:\n return np.array([off])\n\n\ndef lagfromroots(roots):\n """\n Generate a Laguerre series with given roots.\n\n The function returns the coefficients of the polynomial\n\n .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),\n\n in Laguerre form, where the :math:`r_n` are the roots specified in `roots`.\n If a zero has multiplicity n, then it must appear in `roots` n times.\n For instance, if 2 is a root of multiplicity three and 3 is a root of\n multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The\n roots can appear in any order.\n\n If the returned coefficients are `c`, then\n\n .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x)\n\n The coefficient of the last term is not generally 1 for monic\n polynomials in Laguerre form.\n\n Parameters\n ----------\n roots : array_like\n Sequence containing the roots.\n\n Returns\n -------\n out : ndarray\n 1-D array of coefficients. If all roots are real then `out` is a\n real array, if some of the roots are complex, then `out` is complex\n even if all the coefficients in the result are real (see Examples\n below).\n\n See Also\n --------\n numpy.polynomial.polynomial.polyfromroots\n numpy.polynomial.legendre.legfromroots\n numpy.polynomial.chebyshev.chebfromroots\n numpy.polynomial.hermite.hermfromroots\n numpy.polynomial.hermite_e.hermefromroots\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagfromroots, lagval\n >>> coef = lagfromroots((-1, 0, 1))\n >>> lagval((-1, 0, 1), coef)\n array([0., 0., 0.])\n >>> coef = lagfromroots((-1j, 1j))\n >>> lagval((-1j, 1j), coef)\n array([0.+0.j, 0.+0.j])\n\n """\n return pu._fromroots(lagline, lagmul, roots)\n\n\ndef lagadd(c1, c2):\n """\n Add one Laguerre series to another.\n\n Returns the sum of two Laguerre series `c1` + `c2`. The arguments\n are sequences of coefficients ordered from lowest order term to\n highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Laguerre series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Array representing the Laguerre series of their sum.\n\n See Also\n --------\n lagsub, lagmulx, lagmul, lagdiv, lagpow\n\n Notes\n -----\n Unlike multiplication, division, etc., the sum of two Laguerre series\n is a Laguerre series (without having to "reproject" the result onto\n the basis set) so addition, just like that of "standard" polynomials,\n is simply "component-wise."\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagadd\n >>> lagadd([1, 2, 3], [1, 2, 3, 4])\n array([2., 4., 6., 4.])\n\n """\n return pu._add(c1, c2)\n\n\ndef lagsub(c1, c2):\n """\n Subtract one Laguerre series from another.\n\n Returns the difference of two Laguerre series `c1` - `c2`. The\n sequences of coefficients are from lowest order term to highest, i.e.,\n [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Laguerre series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Of Laguerre series coefficients representing their difference.\n\n See Also\n --------\n lagadd, lagmulx, lagmul, lagdiv, lagpow\n\n Notes\n -----\n Unlike multiplication, division, etc., the difference of two Laguerre\n series is a Laguerre series (without having to "reproject" the result\n onto the basis set) so subtraction, just like that of "standard"\n polynomials, is simply "component-wise."\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagsub\n >>> lagsub([1, 2, 3, 4], [1, 2, 3])\n array([0., 0., 0., 4.])\n\n """\n return pu._sub(c1, c2)\n\n\ndef lagmulx(c):\n """Multiply a Laguerre series by x.\n\n Multiply the Laguerre series `c` by x, where x is the independent\n variable.\n\n\n Parameters\n ----------\n c : array_like\n 1-D array of Laguerre series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Array representing the result of the multiplication.\n\n See Also\n --------\n lagadd, lagsub, lagmul, lagdiv, lagpow\n\n Notes\n -----\n The multiplication uses the recursion relationship for Laguerre\n polynomials in the form\n\n .. math::\n\n xP_i(x) = (-(i + 1)*P_{i + 1}(x) + (2i + 1)P_{i}(x) - iP_{i - 1}(x))\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagmulx\n >>> lagmulx([1, 2, 3])\n array([-1., -1., 11., -9.])\n\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n # The zero series needs special treatment\n if len(c) == 1 and c[0] == 0:\n return c\n\n prd = np.empty(len(c) + 1, dtype=c.dtype)\n prd[0] = c[0]\n prd[1] = -c[0]\n for i in range(1, len(c)):\n prd[i + 1] = -c[i] * (i + 1)\n prd[i] += c[i] * (2 * i + 1)\n prd[i - 1] -= c[i] * i\n return prd\n\n\ndef lagmul(c1, c2):\n """\n Multiply one Laguerre series by another.\n\n Returns the product of two Laguerre series `c1` * `c2`. The arguments\n are sequences of coefficients, from lowest order "term" to highest,\n e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Laguerre series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Of Laguerre series coefficients representing their product.\n\n See Also\n --------\n lagadd, lagsub, lagmulx, lagdiv, lagpow\n\n Notes\n -----\n In general, the (polynomial) product of two C-series results in terms\n that are not in the Laguerre polynomial basis set. Thus, to express\n the product as a Laguerre series, it is necessary to "reproject" the\n product onto said basis set, which may produce "unintuitive" (but\n correct) results; see Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagmul\n >>> lagmul([1, 2, 3], [0, 1, 2])\n array([ 8., -13., 38., -51., 36.])\n\n """\n # s1, s2 are trimmed copies\n [c1, c2] = pu.as_series([c1, c2])\n\n if len(c1) > len(c2):\n c = c2\n xs = c1\n else:\n c = c1\n xs = c2\n\n if len(c) == 1:\n c0 = c[0] * xs\n c1 = 0\n elif len(c) == 2:\n c0 = c[0] * xs\n c1 = c[1] * xs\n else:\n nd = len(c)\n c0 = c[-2] * xs\n c1 = c[-1] * xs\n for i in range(3, len(c) + 1):\n tmp = c0\n nd = nd - 1\n c0 = lagsub(c[-i] * xs, (c1 * (nd - 1)) / nd)\n c1 = lagadd(tmp, lagsub((2 * nd - 1) * c1, lagmulx(c1)) / nd)\n return lagadd(c0, lagsub(c1, lagmulx(c1)))\n\n\ndef lagdiv(c1, c2):\n """\n Divide one Laguerre series by another.\n\n Returns the quotient-with-remainder of two Laguerre series\n `c1` / `c2`. The arguments are sequences of coefficients from lowest\n order "term" to highest, e.g., [1,2,3] represents the series\n ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Laguerre series coefficients ordered from low to\n high.\n\n Returns\n -------\n [quo, rem] : ndarrays\n Of Laguerre series coefficients representing the quotient and\n remainder.\n\n See Also\n --------\n lagadd, lagsub, lagmulx, lagmul, lagpow\n\n Notes\n -----\n In general, the (polynomial) division of one Laguerre series by another\n results in quotient and remainder terms that are not in the Laguerre\n polynomial basis set. Thus, to express these results as a Laguerre\n series, it is necessary to "reproject" the results onto the Laguerre\n basis set, which may produce "unintuitive" (but correct) results; see\n Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagdiv\n >>> lagdiv([ 8., -13., 38., -51., 36.], [0, 1, 2])\n (array([1., 2., 3.]), array([0.]))\n >>> lagdiv([ 9., -12., 38., -51., 36.], [0, 1, 2])\n (array([1., 2., 3.]), array([1., 1.]))\n\n """\n return pu._div(lagmul, c1, c2)\n\n\ndef lagpow(c, pow, maxpower=16):\n """Raise a Laguerre series to a power.\n\n Returns the Laguerre series `c` raised to the power `pow`. The\n argument `c` is a sequence of coefficients ordered from low to high.\n i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.``\n\n Parameters\n ----------\n c : array_like\n 1-D array of Laguerre series coefficients ordered from low to\n high.\n pow : integer\n Power to which the series will be raised\n maxpower : integer, optional\n Maximum power allowed. This is mainly to limit growth of the series\n to unmanageable size. Default is 16\n\n Returns\n -------\n coef : ndarray\n Laguerre series of power.\n\n See Also\n --------\n lagadd, lagsub, lagmulx, lagmul, lagdiv\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagpow\n >>> lagpow([1, 2, 3], 2)\n array([ 14., -16., 56., -72., 54.])\n\n """\n return pu._pow(lagmul, c, pow, maxpower)\n\n\ndef lagder(c, m=1, scl=1, axis=0):\n """\n Differentiate a Laguerre series.\n\n Returns the Laguerre series coefficients `c` differentiated `m` times\n along `axis`. At each iteration the result is multiplied by `scl` (the\n scaling factor is for use in a linear change of variable). The argument\n `c` is an array of coefficients from low to high degree along each\n axis, e.g., [1,2,3] represents the series ``1*L_0 + 2*L_1 + 3*L_2``\n while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) +\n 2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is\n ``y``.\n\n Parameters\n ----------\n c : array_like\n Array of Laguerre series coefficients. If `c` is multidimensional\n the different axis correspond to different variables with the\n degree in each axis given by the corresponding index.\n m : int, optional\n Number of derivatives taken, must be non-negative. (Default: 1)\n scl : scalar, optional\n Each differentiation is multiplied by `scl`. The end result is\n multiplication by ``scl**m``. This is for use in a linear change of\n variable. (Default: 1)\n axis : int, optional\n Axis over which the derivative is taken. (Default: 0).\n\n Returns\n -------\n der : ndarray\n Laguerre series of the derivative.\n\n See Also\n --------\n lagint\n\n Notes\n -----\n In general, the result of differentiating a Laguerre series does not\n resemble the same operation on a power series. Thus the result of this\n function may be "unintuitive," albeit correct; see Examples section\n below.\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagder\n >>> lagder([ 1., 1., 1., -3.])\n array([1., 2., 3.])\n >>> lagder([ 1., 0., 0., -4., 3.], m=2)\n array([1., 2., 3.])\n\n """\n c = np.array(c, ndmin=1, copy=True)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n\n cnt = pu._as_int(m, "the order of derivation")\n iaxis = pu._as_int(axis, "the axis")\n if cnt < 0:\n raise ValueError("The order of derivation must be non-negative")\n iaxis = normalize_axis_index(iaxis, c.ndim)\n\n if cnt == 0:\n return c\n\n c = np.moveaxis(c, iaxis, 0)\n n = len(c)\n if cnt >= n:\n c = c[:1] * 0\n else:\n for i in range(cnt):\n n = n - 1\n c *= scl\n der = np.empty((n,) + c.shape[1:], dtype=c.dtype)\n for j in range(n, 1, -1):\n der[j - 1] = -c[j]\n c[j - 1] += c[j]\n der[0] = -c[1]\n c = der\n c = np.moveaxis(c, 0, iaxis)\n return c\n\n\ndef lagint(c, m=1, k=[], lbnd=0, scl=1, axis=0):\n """\n Integrate a Laguerre series.\n\n Returns the Laguerre series coefficients `c` integrated `m` times from\n `lbnd` along `axis`. At each iteration the resulting series is\n **multiplied** by `scl` and an integration constant, `k`, is added.\n The scaling factor is for use in a linear change of variable. ("Buyer\n beware": note that, depending on what one is doing, one may want `scl`\n to be the reciprocal of what one might expect; for more information,\n see the Notes section below.) The argument `c` is an array of\n coefficients from low to high degree along each axis, e.g., [1,2,3]\n represents the series ``L_0 + 2*L_1 + 3*L_2`` while [[1,2],[1,2]]\n represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) +\n 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.\n\n\n Parameters\n ----------\n c : array_like\n Array of Laguerre series coefficients. If `c` is multidimensional\n the different axis correspond to different variables with the\n degree in each axis given by the corresponding index.\n m : int, optional\n Order of integration, must be positive. (Default: 1)\n k : {[], list, scalar}, optional\n Integration constant(s). The value of the first integral at\n ``lbnd`` is the first value in the list, the value of the second\n integral at ``lbnd`` is the second value, etc. If ``k == []`` (the\n default), all constants are set to zero. If ``m == 1``, a single\n scalar can be given instead of a list.\n lbnd : scalar, optional\n The lower bound of the integral. (Default: 0)\n scl : scalar, optional\n Following each integration the result is *multiplied* by `scl`\n before the integration constant is added. (Default: 1)\n axis : int, optional\n Axis over which the integral is taken. (Default: 0).\n\n Returns\n -------\n S : ndarray\n Laguerre series coefficients of the integral.\n\n Raises\n ------\n ValueError\n If ``m < 0``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or\n ``np.ndim(scl) != 0``.\n\n See Also\n --------\n lagder\n\n Notes\n -----\n Note that the result of each integration is *multiplied* by `scl`.\n Why is this important to note? Say one is making a linear change of\n variable :math:`u = ax + b` in an integral relative to `x`. Then\n :math:`dx = du/a`, so one will need to set `scl` equal to\n :math:`1/a` - perhaps not what one would have first thought.\n\n Also note that, in general, the result of integrating a C-series needs\n to be "reprojected" onto the C-series basis set. Thus, typically,\n the result of this function is "unintuitive," albeit correct; see\n Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagint\n >>> lagint([1,2,3])\n array([ 1., 1., 1., -3.])\n >>> lagint([1,2,3], m=2)\n array([ 1., 0., 0., -4., 3.])\n >>> lagint([1,2,3], k=1)\n array([ 2., 1., 1., -3.])\n >>> lagint([1,2,3], lbnd=-1)\n array([11.5, 1. , 1. , -3. ])\n >>> lagint([1,2], m=2, k=[1,2], lbnd=-1)\n array([ 11.16666667, -5. , -3. , 2. ]) # may vary\n\n """\n c = np.array(c, ndmin=1, copy=True)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n if not np.iterable(k):\n k = [k]\n cnt = pu._as_int(m, "the order of integration")\n iaxis = pu._as_int(axis, "the axis")\n if cnt < 0:\n raise ValueError("The order of integration must be non-negative")\n if len(k) > cnt:\n raise ValueError("Too many integration constants")\n if np.ndim(lbnd) != 0:\n raise ValueError("lbnd must be a scalar.")\n if np.ndim(scl) != 0:\n raise ValueError("scl must be a scalar.")\n iaxis = normalize_axis_index(iaxis, c.ndim)\n\n if cnt == 0:\n return c\n\n c = np.moveaxis(c, iaxis, 0)\n k = list(k) + [0] * (cnt - len(k))\n for i in range(cnt):\n n = len(c)\n c *= scl\n if n == 1 and np.all(c[0] == 0):\n c[0] += k[i]\n else:\n tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)\n tmp[0] = c[0]\n tmp[1] = -c[0]\n for j in range(1, n):\n tmp[j] += c[j]\n tmp[j + 1] = -c[j]\n tmp[0] += k[i] - lagval(lbnd, tmp)\n c = tmp\n c = np.moveaxis(c, 0, iaxis)\n return c\n\n\ndef lagval(x, c, tensor=True):\n """\n Evaluate a Laguerre series at points x.\n\n If `c` is of length ``n + 1``, this function returns the value:\n\n .. math:: p(x) = c_0 * L_0(x) + c_1 * L_1(x) + ... + c_n * L_n(x)\n\n The parameter `x` is converted to an array only if it is a tuple or a\n list, otherwise it is treated as a scalar. In either case, either `x`\n or its elements must support multiplication and addition both with\n themselves and with the elements of `c`.\n\n If `c` is a 1-D array, then ``p(x)`` will have the same shape as `x`. If\n `c` is multidimensional, then the shape of the result depends on the\n value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +\n x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that\n scalars have shape (,).\n\n Trailing zeros in the coefficients will be used in the evaluation, so\n they should be avoided if efficiency is a concern.\n\n Parameters\n ----------\n x : array_like, compatible object\n If `x` is a list or tuple, it is converted to an ndarray, otherwise\n it is left unchanged and treated as a scalar. In either case, `x`\n or its elements must support addition and multiplication with\n themselves and with the elements of `c`.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree n are contained in c[n]. If `c` is multidimensional the\n remaining indices enumerate multiple polynomials. In the two\n dimensional case the coefficients may be thought of as stored in\n the columns of `c`.\n tensor : boolean, optional\n If True, the shape of the coefficient array is extended with ones\n on the right, one for each dimension of `x`. Scalars have dimension 0\n for this action. The result is that every column of coefficients in\n `c` is evaluated for every element of `x`. If False, `x` is broadcast\n over the columns of `c` for the evaluation. This keyword is useful\n when `c` is multidimensional. The default value is True.\n\n Returns\n -------\n values : ndarray, algebra_like\n The shape of the return value is described above.\n\n See Also\n --------\n lagval2d, laggrid2d, lagval3d, laggrid3d\n\n Notes\n -----\n The evaluation uses Clenshaw recursion, aka synthetic division.\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagval\n >>> coef = [1, 2, 3]\n >>> lagval(1, coef)\n -0.5\n >>> lagval([[1, 2],[3, 4]], coef)\n array([[-0.5, -4. ],\n [-4.5, -2. ]])\n\n """\n c = np.array(c, ndmin=1, copy=None)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n if isinstance(x, (tuple, list)):\n x = np.asarray(x)\n if isinstance(x, np.ndarray) and tensor:\n c = c.reshape(c.shape + (1,) * x.ndim)\n\n if len(c) == 1:\n c0 = c[0]\n c1 = 0\n elif len(c) == 2:\n c0 = c[0]\n c1 = c[1]\n else:\n nd = len(c)\n c0 = c[-2]\n c1 = c[-1]\n for i in range(3, len(c) + 1):\n tmp = c0\n nd = nd - 1\n c0 = c[-i] - (c1 * (nd - 1)) / nd\n c1 = tmp + (c1 * ((2 * nd - 1) - x)) / nd\n return c0 + c1 * (1 - x)\n\n\ndef lagval2d(x, y, c):\n """\n Evaluate a 2-D Laguerre series at points (x, y).\n\n This function returns the values:\n\n .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * L_i(x) * L_j(y)\n\n The parameters `x` and `y` are converted to arrays only if they are\n tuples or a lists, otherwise they are treated as a scalars and they\n must have the same shape after conversion. In either case, either `x`\n and `y` or their elements must support multiplication and addition both\n with themselves and with the elements of `c`.\n\n If `c` is a 1-D array a one is implicitly appended to its shape to make\n it 2-D. The shape of the result will be c.shape[2:] + x.shape.\n\n Parameters\n ----------\n x, y : array_like, compatible objects\n The two dimensional series is evaluated at the points ``(x, y)``,\n where `x` and `y` must have the same shape. If `x` or `y` is a list\n or tuple, it is first converted to an ndarray, otherwise it is left\n unchanged and if it isn't an ndarray it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term\n of multi-degree i,j is contained in ``c[i,j]``. If `c` has\n dimension greater than two the remaining indices enumerate multiple\n sets of coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points formed with\n pairs of corresponding values from `x` and `y`.\n\n See Also\n --------\n lagval, laggrid2d, lagval3d, laggrid3d\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagval2d\n >>> c = [[1, 2],[3, 4]]\n >>> lagval2d(1, 1, c)\n 1.0\n """\n return pu._valnd(lagval, c, x, y)\n\n\ndef laggrid2d(x, y, c):\n """\n Evaluate a 2-D Laguerre series on the Cartesian product of x and y.\n\n This function returns the values:\n\n .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * L_i(a) * L_j(b)\n\n where the points ``(a, b)`` consist of all pairs formed by taking\n `a` from `x` and `b` from `y`. The resulting points form a grid with\n `x` in the first dimension and `y` in the second.\n\n The parameters `x` and `y` are converted to arrays only if they are\n tuples or a lists, otherwise they are treated as a scalars. In either\n case, either `x` and `y` or their elements must support multiplication\n and addition both with themselves and with the elements of `c`.\n\n If `c` has fewer than two dimensions, ones are implicitly appended to\n its shape to make it 2-D. The shape of the result will be c.shape[2:] +\n x.shape + y.shape.\n\n Parameters\n ----------\n x, y : array_like, compatible objects\n The two dimensional series is evaluated at the points in the\n Cartesian product of `x` and `y`. If `x` or `y` is a list or\n tuple, it is first converted to an ndarray, otherwise it is left\n unchanged and, if it isn't an ndarray, it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term of\n multi-degree i,j is contained in ``c[i,j]``. If `c` has dimension\n greater than two the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional Chebyshev series at points in the\n Cartesian product of `x` and `y`.\n\n See Also\n --------\n lagval, lagval2d, lagval3d, laggrid3d\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import laggrid2d\n >>> c = [[1, 2], [3, 4]]\n >>> laggrid2d([0, 1], [0, 1], c)\n array([[10., 4.],\n [ 3., 1.]])\n\n """\n return pu._gridnd(lagval, c, x, y)\n\n\ndef lagval3d(x, y, z, c):\n """\n Evaluate a 3-D Laguerre series at points (x, y, z).\n\n This function returns the values:\n\n .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * L_i(x) * L_j(y) * L_k(z)\n\n The parameters `x`, `y`, and `z` are converted to arrays only if\n they are tuples or a lists, otherwise they are treated as a scalars and\n they must have the same shape after conversion. In either case, either\n `x`, `y`, and `z` or their elements must support multiplication and\n addition both with themselves and with the elements of `c`.\n\n If `c` has fewer than 3 dimensions, ones are implicitly appended to its\n shape to make it 3-D. The shape of the result will be c.shape[3:] +\n x.shape.\n\n Parameters\n ----------\n x, y, z : array_like, compatible object\n The three dimensional series is evaluated at the points\n ``(x, y, z)``, where `x`, `y`, and `z` must have the same shape. If\n any of `x`, `y`, or `z` is a list or tuple, it is first converted\n to an ndarray, otherwise it is left unchanged and if it isn't an\n ndarray it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term of\n multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension\n greater than 3 the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the multidimensional polynomial on points formed with\n triples of corresponding values from `x`, `y`, and `z`.\n\n See Also\n --------\n lagval, lagval2d, laggrid2d, laggrid3d\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagval3d\n >>> c = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]\n >>> lagval3d(1, 1, 2, c)\n -1.0\n\n """\n return pu._valnd(lagval, c, x, y, z)\n\n\ndef laggrid3d(x, y, z, c):\n """\n Evaluate a 3-D Laguerre series on the Cartesian product of x, y, and z.\n\n This function returns the values:\n\n .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * L_i(a) * L_j(b) * L_k(c)\n\n where the points ``(a, b, c)`` consist of all triples formed by taking\n `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form\n a grid with `x` in the first dimension, `y` in the second, and `z` in\n the third.\n\n The parameters `x`, `y`, and `z` are converted to arrays only if they\n are tuples or a lists, otherwise they are treated as a scalars. In\n either case, either `x`, `y`, and `z` or their elements must support\n multiplication and addition both with themselves and with the elements\n of `c`.\n\n If `c` has fewer than three dimensions, ones are implicitly appended to\n its shape to make it 3-D. The shape of the result will be c.shape[3:] +\n x.shape + y.shape + z.shape.\n\n Parameters\n ----------\n x, y, z : array_like, compatible objects\n The three dimensional series is evaluated at the points in the\n Cartesian product of `x`, `y`, and `z`. If `x`, `y`, or `z` is a\n list or tuple, it is first converted to an ndarray, otherwise it is\n left unchanged and, if it isn't an ndarray, it is treated as a\n scalar.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree i,j are contained in ``c[i,j]``. If `c` has dimension\n greater than two the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points in the Cartesian\n product of `x` and `y`.\n\n See Also\n --------\n lagval, lagval2d, laggrid2d, lagval3d\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import laggrid3d\n >>> c = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]\n >>> laggrid3d([0, 1], [0, 1], [2, 4], c)\n array([[[ -4., -44.],\n [ -2., -18.]],\n [[ -2., -14.],\n [ -1., -5.]]])\n\n """\n return pu._gridnd(lagval, c, x, y, z)\n\n\ndef lagvander(x, deg):\n """Pseudo-Vandermonde matrix of given degree.\n\n Returns the pseudo-Vandermonde matrix of degree `deg` and sample points\n `x`. The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., i] = L_i(x)\n\n where ``0 <= i <= deg``. The leading indices of `V` index the elements of\n `x` and the last index is the degree of the Laguerre polynomial.\n\n If `c` is a 1-D array of coefficients of length ``n + 1`` and `V` is the\n array ``V = lagvander(x, n)``, then ``np.dot(V, c)`` and\n ``lagval(x, c)`` are the same up to roundoff. This equivalence is\n useful both for least squares fitting and for the evaluation of a large\n number of Laguerre series of the same degree and sample points.\n\n Parameters\n ----------\n x : array_like\n Array of points. The dtype is converted to float64 or complex128\n depending on whether any of the elements are complex. If `x` is\n scalar it is converted to a 1-D array.\n deg : int\n Degree of the resulting matrix.\n\n Returns\n -------\n vander : ndarray\n The pseudo-Vandermonde matrix. The shape of the returned matrix is\n ``x.shape + (deg + 1,)``, where The last index is the degree of the\n corresponding Laguerre polynomial. The dtype will be the same as\n the converted `x`.\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial.laguerre import lagvander\n >>> x = np.array([0, 1, 2])\n >>> lagvander(x, 3)\n array([[ 1. , 1. , 1. , 1. ],\n [ 1. , 0. , -0.5 , -0.66666667],\n [ 1. , -1. , -1. , -0.33333333]])\n\n """\n ideg = pu._as_int(deg, "deg")\n if ideg < 0:\n raise ValueError("deg must be non-negative")\n\n x = np.array(x, copy=None, ndmin=1) + 0.0\n dims = (ideg + 1,) + x.shape\n dtyp = x.dtype\n v = np.empty(dims, dtype=dtyp)\n v[0] = x * 0 + 1\n if ideg > 0:\n v[1] = 1 - x\n for i in range(2, ideg + 1):\n v[i] = (v[i - 1] * (2 * i - 1 - x) - v[i - 2] * (i - 1)) / i\n return np.moveaxis(v, 0, -1)\n\n\ndef lagvander2d(x, y, deg):\n """Pseudo-Vandermonde matrix of given degrees.\n\n Returns the pseudo-Vandermonde matrix of degrees `deg` and sample\n points ``(x, y)``. The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., (deg[1] + 1)*i + j] = L_i(x) * L_j(y),\n\n where ``0 <= i <= deg[0]`` and ``0 <= j <= deg[1]``. The leading indices of\n `V` index the points ``(x, y)`` and the last index encodes the degrees of\n the Laguerre polynomials.\n\n If ``V = lagvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`\n correspond to the elements of a 2-D coefficient array `c` of shape\n (xdeg + 1, ydeg + 1) in the order\n\n .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...\n\n and ``np.dot(V, c.flat)`` and ``lagval2d(x, y, c)`` will be the same\n up to roundoff. This equivalence is useful both for least squares\n fitting and for the evaluation of a large number of 2-D Laguerre\n series of the same degrees and sample points.\n\n Parameters\n ----------\n x, y : array_like\n Arrays of point coordinates, all of the same shape. The dtypes\n will be converted to either float64 or complex128 depending on\n whether any of the elements are complex. Scalars are converted to\n 1-D arrays.\n deg : list of ints\n List of maximum degrees of the form [x_deg, y_deg].\n\n Returns\n -------\n vander2d : ndarray\n The shape of the returned matrix is ``x.shape + (order,)``, where\n :math:`order = (deg[0]+1)*(deg[1]+1)`. The dtype will be the same\n as the converted `x` and `y`.\n\n See Also\n --------\n lagvander, lagvander3d, lagval2d, lagval3d\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial.laguerre import lagvander2d\n >>> x = np.array([0])\n >>> y = np.array([2])\n >>> lagvander2d(x, y, [2, 1])\n array([[ 1., -1., 1., -1., 1., -1.]])\n\n """\n return pu._vander_nd_flat((lagvander, lagvander), (x, y), deg)\n\n\ndef lagvander3d(x, y, z, deg):\n """Pseudo-Vandermonde matrix of given degrees.\n\n Returns the pseudo-Vandermonde matrix of degrees `deg` and sample\n points ``(x, y, z)``. If `l`, `m`, `n` are the given degrees in `x`, `y`, `z`,\n then The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = L_i(x)*L_j(y)*L_k(z),\n\n where ``0 <= i <= l``, ``0 <= j <= m``, and ``0 <= j <= n``. The leading\n indices of `V` index the points ``(x, y, z)`` and the last index encodes\n the degrees of the Laguerre polynomials.\n\n If ``V = lagvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns\n of `V` correspond to the elements of a 3-D coefficient array `c` of\n shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order\n\n .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...\n\n and ``np.dot(V, c.flat)`` and ``lagval3d(x, y, z, c)`` will be the\n same up to roundoff. This equivalence is useful both for least squares\n fitting and for the evaluation of a large number of 3-D Laguerre\n series of the same degrees and sample points.\n\n Parameters\n ----------\n x, y, z : array_like\n Arrays of point coordinates, all of the same shape. The dtypes will\n be converted to either float64 or complex128 depending on whether\n any of the elements are complex. Scalars are converted to 1-D\n arrays.\n deg : list of ints\n List of maximum degrees of the form [x_deg, y_deg, z_deg].\n\n Returns\n -------\n vander3d : ndarray\n The shape of the returned matrix is ``x.shape + (order,)``, where\n :math:`order = (deg[0]+1)*(deg[1]+1)*(deg[2]+1)`. The dtype will\n be the same as the converted `x`, `y`, and `z`.\n\n See Also\n --------\n lagvander, lagvander3d, lagval2d, lagval3d\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial.laguerre import lagvander3d\n >>> x = np.array([0])\n >>> y = np.array([2])\n >>> z = np.array([0])\n >>> lagvander3d(x, y, z, [2, 1, 3])\n array([[ 1., 1., 1., 1., -1., -1., -1., -1., 1., 1., 1., 1., -1.,\n -1., -1., -1., 1., 1., 1., 1., -1., -1., -1., -1.]])\n\n """\n return pu._vander_nd_flat((lagvander, lagvander, lagvander), (x, y, z), deg)\n\n\ndef lagfit(x, y, deg, rcond=None, full=False, w=None):\n """\n Least squares fit of Laguerre series to data.\n\n Return the coefficients of a Laguerre series of degree `deg` that is the\n least squares fit to the data values `y` given at points `x`. If `y` is\n 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple\n fits are done, one for each column of `y`, and the resulting\n coefficients are stored in the corresponding columns of a 2-D return.\n The fitted polynomial(s) are in the form\n\n .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x),\n\n where ``n`` is `deg`.\n\n Parameters\n ----------\n x : array_like, shape (M,)\n x-coordinates of the M sample points ``(x[i], y[i])``.\n y : array_like, shape (M,) or (M, K)\n y-coordinates of the sample points. Several data sets of sample\n points sharing the same x-coordinates can be fitted at once by\n passing in a 2D-array that contains one dataset per column.\n deg : int or 1-D array_like\n Degree(s) of the fitting polynomials. If `deg` is a single integer\n all terms up to and including the `deg`'th term are included in the\n fit. For NumPy versions >= 1.11.0 a list of integers specifying the\n degrees of the terms to include may be used instead.\n rcond : float, optional\n Relative condition number of the fit. Singular values smaller than\n this relative to the largest singular value will be ignored. The\n default value is len(x)*eps, where eps is the relative precision of\n the float type, about 2e-16 in most cases.\n full : bool, optional\n Switch determining nature of return value. When it is False (the\n default) just the coefficients are returned, when True diagnostic\n information from the singular value decomposition is also returned.\n w : array_like, shape (`M`,), optional\n Weights. If not None, the weight ``w[i]`` applies to the unsquared\n residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are\n chosen so that the errors of the products ``w[i]*y[i]`` all have the\n same variance. When using inverse-variance weighting, use\n ``w[i] = 1/sigma(y[i])``. The default value is None.\n\n Returns\n -------\n coef : ndarray, shape (M,) or (M, K)\n Laguerre coefficients ordered from low to high. If `y` was 2-D,\n the coefficients for the data in column *k* of `y` are in column\n *k*.\n\n [residuals, rank, singular_values, rcond] : list\n These values are only returned if ``full == True``\n\n - residuals -- sum of squared residuals of the least squares fit\n - rank -- the numerical rank of the scaled Vandermonde matrix\n - singular_values -- singular values of the scaled Vandermonde matrix\n - rcond -- value of `rcond`.\n\n For more details, see `numpy.linalg.lstsq`.\n\n Warns\n -----\n RankWarning\n The rank of the coefficient matrix in the least-squares fit is\n deficient. The warning is only raised if ``full == False``. The\n warnings can be turned off by\n\n >>> import warnings\n >>> warnings.simplefilter('ignore', np.exceptions.RankWarning)\n\n See Also\n --------\n numpy.polynomial.polynomial.polyfit\n numpy.polynomial.legendre.legfit\n numpy.polynomial.chebyshev.chebfit\n numpy.polynomial.hermite.hermfit\n numpy.polynomial.hermite_e.hermefit\n lagval : Evaluates a Laguerre series.\n lagvander : pseudo Vandermonde matrix of Laguerre series.\n lagweight : Laguerre weight function.\n numpy.linalg.lstsq : Computes a least-squares fit from the matrix.\n scipy.interpolate.UnivariateSpline : Computes spline fits.\n\n Notes\n -----\n The solution is the coefficients of the Laguerre series ``p`` that\n minimizes the sum of the weighted squared errors\n\n .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,\n\n where the :math:`w_j` are the weights. This problem is solved by\n setting up as the (typically) overdetermined matrix equation\n\n .. math:: V(x) * c = w * y,\n\n where ``V`` is the weighted pseudo Vandermonde matrix of `x`, ``c`` are the\n coefficients to be solved for, `w` are the weights, and `y` are the\n observed values. This equation is then solved using the singular value\n decomposition of ``V``.\n\n If some of the singular values of `V` are so small that they are\n neglected, then a `~exceptions.RankWarning` will be issued. This means that\n the coefficient values may be poorly determined. Using a lower order fit\n will usually get rid of the warning. The `rcond` parameter can also be\n set to a value smaller than its default, but the resulting fit may be\n spurious and have large contributions from roundoff error.\n\n Fits using Laguerre series are probably most useful when the data can\n be approximated by ``sqrt(w(x)) * p(x)``, where ``w(x)`` is the Laguerre\n weight. In that case the weight ``sqrt(w(x[i]))`` should be used\n together with data values ``y[i]/sqrt(w(x[i]))``. The weight function is\n available as `lagweight`.\n\n References\n ----------\n .. [1] Wikipedia, "Curve fitting",\n https://en.wikipedia.org/wiki/Curve_fitting\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial.laguerre import lagfit, lagval\n >>> x = np.linspace(0, 10)\n >>> rng = np.random.default_rng()\n >>> err = rng.normal(scale=1./10, size=len(x))\n >>> y = lagval(x, [1, 2, 3]) + err\n >>> lagfit(x, y, 2)\n array([1.00578369, 1.99417356, 2.99827656]) # may vary\n\n """\n return pu._fit(lagvander, x, y, deg, rcond, full, w)\n\n\ndef lagcompanion(c):\n """\n Return the companion matrix of c.\n\n The usual companion matrix of the Laguerre polynomials is already\n symmetric when `c` is a basis Laguerre polynomial, so no scaling is\n applied.\n\n Parameters\n ----------\n c : array_like\n 1-D array of Laguerre series coefficients ordered from low to high\n degree.\n\n Returns\n -------\n mat : ndarray\n Companion matrix of dimensions (deg, deg).\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagcompanion\n >>> lagcompanion([1, 2, 3])\n array([[ 1. , -0.33333333],\n [-1. , 4.33333333]])\n\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n if len(c) < 2:\n raise ValueError('Series must have maximum degree of at least 1.')\n if len(c) == 2:\n return np.array([[1 + c[0] / c[1]]])\n\n n = len(c) - 1\n mat = np.zeros((n, n), dtype=c.dtype)\n top = mat.reshape(-1)[1::n + 1]\n mid = mat.reshape(-1)[0::n + 1]\n bot = mat.reshape(-1)[n::n + 1]\n top[...] = -np.arange(1, n)\n mid[...] = 2. * np.arange(n) + 1.\n bot[...] = top\n mat[:, -1] += (c[:-1] / c[-1]) * n\n return mat\n\n\ndef lagroots(c):\n """\n Compute the roots of a Laguerre series.\n\n Return the roots (a.k.a. "zeros") of the polynomial\n\n .. math:: p(x) = \\sum_i c[i] * L_i(x).\n\n Parameters\n ----------\n c : 1-D array_like\n 1-D array of coefficients.\n\n Returns\n -------\n out : ndarray\n Array of the roots of the series. If all the roots are real,\n then `out` is also real, otherwise it is complex.\n\n See Also\n --------\n numpy.polynomial.polynomial.polyroots\n numpy.polynomial.legendre.legroots\n numpy.polynomial.chebyshev.chebroots\n numpy.polynomial.hermite.hermroots\n numpy.polynomial.hermite_e.hermeroots\n\n Notes\n -----\n The root estimates are obtained as the eigenvalues of the companion\n matrix, Roots far from the origin of the complex plane may have large\n errors due to the numerical instability of the series for such\n values. Roots with multiplicity greater than 1 will also show larger\n errors as the value of the series near such points is relatively\n insensitive to errors in the roots. Isolated roots near the origin can\n be improved by a few iterations of Newton's method.\n\n The Laguerre series basis polynomials aren't powers of `x` so the\n results of this function may seem unintuitive.\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagroots, lagfromroots\n >>> coef = lagfromroots([0, 1, 2])\n >>> coef\n array([ 2., -8., 12., -6.])\n >>> lagroots(coef)\n array([-4.4408921e-16, 1.0000000e+00, 2.0000000e+00])\n\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n if len(c) <= 1:\n return np.array([], dtype=c.dtype)\n if len(c) == 2:\n return np.array([1 + c[0] / c[1]])\n\n # rotated companion matrix reduces error\n m = lagcompanion(c)[::-1, ::-1]\n r = la.eigvals(m)\n r.sort()\n return r\n\n\ndef laggauss(deg):\n """\n Gauss-Laguerre quadrature.\n\n Computes the sample points and weights for Gauss-Laguerre quadrature.\n These sample points and weights will correctly integrate polynomials of\n degree :math:`2*deg - 1` or less over the interval :math:`[0, \\inf]`\n with the weight function :math:`f(x) = \\exp(-x)`.\n\n Parameters\n ----------\n deg : int\n Number of sample points and weights. It must be >= 1.\n\n Returns\n -------\n x : ndarray\n 1-D ndarray containing the sample points.\n y : ndarray\n 1-D ndarray containing the weights.\n\n Notes\n -----\n The results have only been tested up to degree 100 higher degrees may\n be problematic. The weights are determined by using the fact that\n\n .. math:: w_k = c / (L'_n(x_k) * L_{n-1}(x_k))\n\n where :math:`c` is a constant independent of :math:`k` and :math:`x_k`\n is the k'th root of :math:`L_n`, and then scaling the results to get\n the right value when integrating 1.\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import laggauss\n >>> laggauss(2)\n (array([0.58578644, 3.41421356]), array([0.85355339, 0.14644661]))\n\n """\n ideg = pu._as_int(deg, "deg")\n if ideg <= 0:\n raise ValueError("deg must be a positive integer")\n\n # first approximation of roots. We use the fact that the companion\n # matrix is symmetric in this case in order to obtain better zeros.\n c = np.array([0] * deg + [1])\n m = lagcompanion(c)\n x = la.eigvalsh(m)\n\n # improve roots by one application of Newton\n dy = lagval(x, c)\n df = lagval(x, lagder(c))\n x -= dy / df\n\n # compute the weights. We scale the factor to avoid possible numerical\n # overflow.\n fm = lagval(x, c[1:])\n fm /= np.abs(fm).max()\n df /= np.abs(df).max()\n w = 1 / (fm * df)\n\n # scale w to get the right value, 1 in this case\n w /= w.sum()\n\n return x, w\n\n\ndef lagweight(x):\n """Weight function of the Laguerre polynomials.\n\n The weight function is :math:`exp(-x)` and the interval of integration\n is :math:`[0, \\inf]`. The Laguerre polynomials are orthogonal, but not\n normalized, with respect to this weight function.\n\n Parameters\n ----------\n x : array_like\n Values at which the weight function will be computed.\n\n Returns\n -------\n w : ndarray\n The weight function at `x`.\n\n Examples\n --------\n >>> from numpy.polynomial.laguerre import lagweight\n >>> x = np.array([0, 1, 2])\n >>> lagweight(x)\n array([1. , 0.36787944, 0.13533528])\n\n """\n w = np.exp(-x)\n return w\n\n#\n# Laguerre series class\n#\n\nclass Laguerre(ABCPolyBase):\n """A Laguerre series class.\n\n The Laguerre class provides the standard Python numerical methods\n '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the\n attributes and methods listed below.\n\n Parameters\n ----------\n coef : array_like\n Laguerre coefficients in order of increasing degree, i.e,\n ``(1, 2, 3)`` gives ``1*L_0(x) + 2*L_1(X) + 3*L_2(x)``.\n domain : (2,) array_like, optional\n Domain to use. The interval ``[domain[0], domain[1]]`` is mapped\n to the interval ``[window[0], window[1]]`` by shifting and scaling.\n The default value is [0., 1.].\n window : (2,) array_like, optional\n Window, see `domain` for its use. The default value is [0., 1.].\n symbol : str, optional\n Symbol used to represent the independent variable in string\n representations of the polynomial expression, e.g. for printing.\n The symbol must be a valid Python identifier. Default value is 'x'.\n\n .. versionadded:: 1.24\n\n """\n # Virtual Functions\n _add = staticmethod(lagadd)\n _sub = staticmethod(lagsub)\n _mul = staticmethod(lagmul)\n _div = staticmethod(lagdiv)\n _pow = staticmethod(lagpow)\n _val = staticmethod(lagval)\n _int = staticmethod(lagint)\n _der = staticmethod(lagder)\n _fit = staticmethod(lagfit)\n _line = staticmethod(lagline)\n _roots = staticmethod(lagroots)\n _fromroots = staticmethod(lagfromroots)\n\n # Virtual properties\n domain = np.array(lagdomain)\n window = np.array(lagdomain)\n basis_name = 'L'\n | .venv\Lib\site-packages\numpy\polynomial\laguerre.py | laguerre.py | Python | 54,149 | 0.75 | 0.08 | 0.020588 | python-kit | 240 | 2025-03-05T20:57:25.561182 | Apache-2.0 | false | 4175de8331b4ec4a4ece2401542dc092 |
from typing import Final\nfrom typing import Literal as L\n\nimport numpy as np\n\nfrom ._polybase import ABCPolyBase\nfrom ._polytypes import (\n _Array1,\n _Array2,\n _FuncBinOp,\n _FuncCompanion,\n _FuncDer,\n _FuncFit,\n _FuncFromRoots,\n _FuncGauss,\n _FuncInteg,\n _FuncLine,\n _FuncPoly2Ortho,\n _FuncPow,\n _FuncRoots,\n _FuncUnOp,\n _FuncVal,\n _FuncVal2D,\n _FuncVal3D,\n _FuncValFromRoots,\n _FuncVander,\n _FuncVander2D,\n _FuncVander3D,\n _FuncWeight,\n)\nfrom .polyutils import trimcoef as lagtrim\n\n__all__ = [\n "lagzero",\n "lagone",\n "lagx",\n "lagdomain",\n "lagline",\n "lagadd",\n "lagsub",\n "lagmulx",\n "lagmul",\n "lagdiv",\n "lagpow",\n "lagval",\n "lagder",\n "lagint",\n "lag2poly",\n "poly2lag",\n "lagfromroots",\n "lagvander",\n "lagfit",\n "lagtrim",\n "lagroots",\n "Laguerre",\n "lagval2d",\n "lagval3d",\n "laggrid2d",\n "laggrid3d",\n "lagvander2d",\n "lagvander3d",\n "lagcompanion",\n "laggauss",\n "lagweight",\n]\n\npoly2lag: _FuncPoly2Ortho[L["poly2lag"]]\nlag2poly: _FuncUnOp[L["lag2poly"]]\n\nlagdomain: Final[_Array2[np.float64]]\nlagzero: Final[_Array1[np.int_]]\nlagone: Final[_Array1[np.int_]]\nlagx: Final[_Array2[np.int_]]\n\nlagline: _FuncLine[L["lagline"]]\nlagfromroots: _FuncFromRoots[L["lagfromroots"]]\nlagadd: _FuncBinOp[L["lagadd"]]\nlagsub: _FuncBinOp[L["lagsub"]]\nlagmulx: _FuncUnOp[L["lagmulx"]]\nlagmul: _FuncBinOp[L["lagmul"]]\nlagdiv: _FuncBinOp[L["lagdiv"]]\nlagpow: _FuncPow[L["lagpow"]]\nlagder: _FuncDer[L["lagder"]]\nlagint: _FuncInteg[L["lagint"]]\nlagval: _FuncVal[L["lagval"]]\nlagval2d: _FuncVal2D[L["lagval2d"]]\nlagval3d: _FuncVal3D[L["lagval3d"]]\nlagvalfromroots: _FuncValFromRoots[L["lagvalfromroots"]]\nlaggrid2d: _FuncVal2D[L["laggrid2d"]]\nlaggrid3d: _FuncVal3D[L["laggrid3d"]]\nlagvander: _FuncVander[L["lagvander"]]\nlagvander2d: _FuncVander2D[L["lagvander2d"]]\nlagvander3d: _FuncVander3D[L["lagvander3d"]]\nlagfit: _FuncFit[L["lagfit"]]\nlagcompanion: _FuncCompanion[L["lagcompanion"]]\nlagroots: _FuncRoots[L["lagroots"]]\nlaggauss: _FuncGauss[L["laggauss"]]\nlagweight: _FuncWeight[L["lagweight"]]\n\nclass Laguerre(ABCPolyBase[L["L"]]): ...\n | .venv\Lib\site-packages\numpy\polynomial\laguerre.pyi | laguerre.pyi | Other | 2,291 | 0.85 | 0.01 | 0 | python-kit | 268 | 2025-01-20T08:15:22.713079 | BSD-3-Clause | false | 998b4cb6d1498a3278cc8c59ac3bc655 |
"""\n==================================================\nLegendre Series (:mod:`numpy.polynomial.legendre`)\n==================================================\n\nThis module provides a number of objects (mostly functions) useful for\ndealing with Legendre series, including a `Legendre` class that\nencapsulates the usual arithmetic operations. (General information\non how this module represents and works with such polynomials is in the\ndocstring for its "parent" sub-package, `numpy.polynomial`).\n\nClasses\n-------\n.. autosummary::\n :toctree: generated/\n\n Legendre\n\nConstants\n---------\n\n.. autosummary::\n :toctree: generated/\n\n legdomain\n legzero\n legone\n legx\n\nArithmetic\n----------\n\n.. autosummary::\n :toctree: generated/\n\n legadd\n legsub\n legmulx\n legmul\n legdiv\n legpow\n legval\n legval2d\n legval3d\n leggrid2d\n leggrid3d\n\nCalculus\n--------\n\n.. autosummary::\n :toctree: generated/\n\n legder\n legint\n\nMisc Functions\n--------------\n\n.. autosummary::\n :toctree: generated/\n\n legfromroots\n legroots\n legvander\n legvander2d\n legvander3d\n leggauss\n legweight\n legcompanion\n legfit\n legtrim\n legline\n leg2poly\n poly2leg\n\nSee also\n--------\nnumpy.polynomial\n\n"""\nimport numpy as np\nimport numpy.linalg as la\nfrom numpy.lib.array_utils import normalize_axis_index\n\nfrom . import polyutils as pu\nfrom ._polybase import ABCPolyBase\n\n__all__ = [\n 'legzero', 'legone', 'legx', 'legdomain', 'legline', 'legadd',\n 'legsub', 'legmulx', 'legmul', 'legdiv', 'legpow', 'legval', 'legder',\n 'legint', 'leg2poly', 'poly2leg', 'legfromroots', 'legvander',\n 'legfit', 'legtrim', 'legroots', 'Legendre', 'legval2d', 'legval3d',\n 'leggrid2d', 'leggrid3d', 'legvander2d', 'legvander3d', 'legcompanion',\n 'leggauss', 'legweight']\n\nlegtrim = pu.trimcoef\n\n\ndef poly2leg(pol):\n """\n Convert a polynomial to a Legendre series.\n\n Convert an array representing the coefficients of a polynomial (relative\n to the "standard" basis) ordered from lowest degree to highest, to an\n array of the coefficients of the equivalent Legendre series, ordered\n from lowest to highest degree.\n\n Parameters\n ----------\n pol : array_like\n 1-D array containing the polynomial coefficients\n\n Returns\n -------\n c : ndarray\n 1-D array containing the coefficients of the equivalent Legendre\n series.\n\n See Also\n --------\n leg2poly\n\n Notes\n -----\n The easy way to do conversions between polynomial basis sets\n is to use the convert method of a class instance.\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy import polynomial as P\n >>> p = P.Polynomial(np.arange(4))\n >>> p\n Polynomial([0., 1., 2., 3.], domain=[-1., 1.], window=[-1., 1.], ...\n >>> c = P.Legendre(P.legendre.poly2leg(p.coef))\n >>> c\n Legendre([ 1. , 3.25, 1. , 0.75], domain=[-1, 1], window=[-1, 1]) # may vary\n\n """\n [pol] = pu.as_series([pol])\n deg = len(pol) - 1\n res = 0\n for i in range(deg, -1, -1):\n res = legadd(legmulx(res), pol[i])\n return res\n\n\ndef leg2poly(c):\n """\n Convert a Legendre series to a polynomial.\n\n Convert an array representing the coefficients of a Legendre series,\n ordered from lowest degree to highest, to an array of the coefficients\n of the equivalent polynomial (relative to the "standard" basis) ordered\n from lowest to highest degree.\n\n Parameters\n ----------\n c : array_like\n 1-D array containing the Legendre series coefficients, ordered\n from lowest order term to highest.\n\n Returns\n -------\n pol : ndarray\n 1-D array containing the coefficients of the equivalent polynomial\n (relative to the "standard" basis) ordered from lowest order term\n to highest.\n\n See Also\n --------\n poly2leg\n\n Notes\n -----\n The easy way to do conversions between polynomial basis sets\n is to use the convert method of a class instance.\n\n Examples\n --------\n >>> from numpy import polynomial as P\n >>> c = P.Legendre(range(4))\n >>> c\n Legendre([0., 1., 2., 3.], domain=[-1., 1.], window=[-1., 1.], symbol='x')\n >>> p = c.convert(kind=P.Polynomial)\n >>> p\n Polynomial([-1. , -3.5, 3. , 7.5], domain=[-1., 1.], window=[-1., ...\n >>> P.legendre.leg2poly(range(4))\n array([-1. , -3.5, 3. , 7.5])\n\n\n """\n from .polynomial import polyadd, polymulx, polysub\n\n [c] = pu.as_series([c])\n n = len(c)\n if n < 3:\n return c\n else:\n c0 = c[-2]\n c1 = c[-1]\n # i is the current degree of c1\n for i in range(n - 1, 1, -1):\n tmp = c0\n c0 = polysub(c[i - 2], (c1 * (i - 1)) / i)\n c1 = polyadd(tmp, (polymulx(c1) * (2 * i - 1)) / i)\n return polyadd(c0, polymulx(c1))\n\n\n#\n# These are constant arrays are of integer type so as to be compatible\n# with the widest range of other types, such as Decimal.\n#\n\n# Legendre\nlegdomain = np.array([-1., 1.])\n\n# Legendre coefficients representing zero.\nlegzero = np.array([0])\n\n# Legendre coefficients representing one.\nlegone = np.array([1])\n\n# Legendre coefficients representing the identity x.\nlegx = np.array([0, 1])\n\n\ndef legline(off, scl):\n """\n Legendre series whose graph is a straight line.\n\n\n\n Parameters\n ----------\n off, scl : scalars\n The specified line is given by ``off + scl*x``.\n\n Returns\n -------\n y : ndarray\n This module's representation of the Legendre series for\n ``off + scl*x``.\n\n See Also\n --------\n numpy.polynomial.polynomial.polyline\n numpy.polynomial.chebyshev.chebline\n numpy.polynomial.laguerre.lagline\n numpy.polynomial.hermite.hermline\n numpy.polynomial.hermite_e.hermeline\n\n Examples\n --------\n >>> import numpy.polynomial.legendre as L\n >>> L.legline(3,2)\n array([3, 2])\n >>> L.legval(-3, L.legline(3,2)) # should be -3\n -3.0\n\n """\n if scl != 0:\n return np.array([off, scl])\n else:\n return np.array([off])\n\n\ndef legfromroots(roots):\n """\n Generate a Legendre series with given roots.\n\n The function returns the coefficients of the polynomial\n\n .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),\n\n in Legendre form, where the :math:`r_n` are the roots specified in `roots`.\n If a zero has multiplicity n, then it must appear in `roots` n times.\n For instance, if 2 is a root of multiplicity three and 3 is a root of\n multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The\n roots can appear in any order.\n\n If the returned coefficients are `c`, then\n\n .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x)\n\n The coefficient of the last term is not generally 1 for monic\n polynomials in Legendre form.\n\n Parameters\n ----------\n roots : array_like\n Sequence containing the roots.\n\n Returns\n -------\n out : ndarray\n 1-D array of coefficients. If all roots are real then `out` is a\n real array, if some of the roots are complex, then `out` is complex\n even if all the coefficients in the result are real (see Examples\n below).\n\n See Also\n --------\n numpy.polynomial.polynomial.polyfromroots\n numpy.polynomial.chebyshev.chebfromroots\n numpy.polynomial.laguerre.lagfromroots\n numpy.polynomial.hermite.hermfromroots\n numpy.polynomial.hermite_e.hermefromroots\n\n Examples\n --------\n >>> import numpy.polynomial.legendre as L\n >>> L.legfromroots((-1,0,1)) # x^3 - x relative to the standard basis\n array([ 0. , -0.4, 0. , 0.4])\n >>> j = complex(0,1)\n >>> L.legfromroots((-j,j)) # x^2 + 1 relative to the standard basis\n array([ 1.33333333+0.j, 0.00000000+0.j, 0.66666667+0.j]) # may vary\n\n """\n return pu._fromroots(legline, legmul, roots)\n\n\ndef legadd(c1, c2):\n """\n Add one Legendre series to another.\n\n Returns the sum of two Legendre series `c1` + `c2`. The arguments\n are sequences of coefficients ordered from lowest order term to\n highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Legendre series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Array representing the Legendre series of their sum.\n\n See Also\n --------\n legsub, legmulx, legmul, legdiv, legpow\n\n Notes\n -----\n Unlike multiplication, division, etc., the sum of two Legendre series\n is a Legendre series (without having to "reproject" the result onto\n the basis set) so addition, just like that of "standard" polynomials,\n is simply "component-wise."\n\n Examples\n --------\n >>> from numpy.polynomial import legendre as L\n >>> c1 = (1,2,3)\n >>> c2 = (3,2,1)\n >>> L.legadd(c1,c2)\n array([4., 4., 4.])\n\n """\n return pu._add(c1, c2)\n\n\ndef legsub(c1, c2):\n """\n Subtract one Legendre series from another.\n\n Returns the difference of two Legendre series `c1` - `c2`. The\n sequences of coefficients are from lowest order term to highest, i.e.,\n [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Legendre series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Of Legendre series coefficients representing their difference.\n\n See Also\n --------\n legadd, legmulx, legmul, legdiv, legpow\n\n Notes\n -----\n Unlike multiplication, division, etc., the difference of two Legendre\n series is a Legendre series (without having to "reproject" the result\n onto the basis set) so subtraction, just like that of "standard"\n polynomials, is simply "component-wise."\n\n Examples\n --------\n >>> from numpy.polynomial import legendre as L\n >>> c1 = (1,2,3)\n >>> c2 = (3,2,1)\n >>> L.legsub(c1,c2)\n array([-2., 0., 2.])\n >>> L.legsub(c2,c1) # -C.legsub(c1,c2)\n array([ 2., 0., -2.])\n\n """\n return pu._sub(c1, c2)\n\n\ndef legmulx(c):\n """Multiply a Legendre series by x.\n\n Multiply the Legendre series `c` by x, where x is the independent\n variable.\n\n\n Parameters\n ----------\n c : array_like\n 1-D array of Legendre series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Array representing the result of the multiplication.\n\n See Also\n --------\n legadd, legsub, legmul, legdiv, legpow\n\n Notes\n -----\n The multiplication uses the recursion relationship for Legendre\n polynomials in the form\n\n .. math::\n\n xP_i(x) = ((i + 1)*P_{i + 1}(x) + i*P_{i - 1}(x))/(2i + 1)\n\n Examples\n --------\n >>> from numpy.polynomial import legendre as L\n >>> L.legmulx([1,2,3])\n array([ 0.66666667, 2.2, 1.33333333, 1.8]) # may vary\n\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n # The zero series needs special treatment\n if len(c) == 1 and c[0] == 0:\n return c\n\n prd = np.empty(len(c) + 1, dtype=c.dtype)\n prd[0] = c[0] * 0\n prd[1] = c[0]\n for i in range(1, len(c)):\n j = i + 1\n k = i - 1\n s = i + j\n prd[j] = (c[i] * j) / s\n prd[k] += (c[i] * i) / s\n return prd\n\n\ndef legmul(c1, c2):\n """\n Multiply one Legendre series by another.\n\n Returns the product of two Legendre series `c1` * `c2`. The arguments\n are sequences of coefficients, from lowest order "term" to highest,\n e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Legendre series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Of Legendre series coefficients representing their product.\n\n See Also\n --------\n legadd, legsub, legmulx, legdiv, legpow\n\n Notes\n -----\n In general, the (polynomial) product of two C-series results in terms\n that are not in the Legendre polynomial basis set. Thus, to express\n the product as a Legendre series, it is necessary to "reproject" the\n product onto said basis set, which may produce "unintuitive" (but\n correct) results; see Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial import legendre as L\n >>> c1 = (1,2,3)\n >>> c2 = (3,2)\n >>> L.legmul(c1,c2) # multiplication requires "reprojection"\n array([ 4.33333333, 10.4 , 11.66666667, 3.6 ]) # may vary\n\n """\n # s1, s2 are trimmed copies\n [c1, c2] = pu.as_series([c1, c2])\n\n if len(c1) > len(c2):\n c = c2\n xs = c1\n else:\n c = c1\n xs = c2\n\n if len(c) == 1:\n c0 = c[0] * xs\n c1 = 0\n elif len(c) == 2:\n c0 = c[0] * xs\n c1 = c[1] * xs\n else:\n nd = len(c)\n c0 = c[-2] * xs\n c1 = c[-1] * xs\n for i in range(3, len(c) + 1):\n tmp = c0\n nd = nd - 1\n c0 = legsub(c[-i] * xs, (c1 * (nd - 1)) / nd)\n c1 = legadd(tmp, (legmulx(c1) * (2 * nd - 1)) / nd)\n return legadd(c0, legmulx(c1))\n\n\ndef legdiv(c1, c2):\n """\n Divide one Legendre series by another.\n\n Returns the quotient-with-remainder of two Legendre series\n `c1` / `c2`. The arguments are sequences of coefficients from lowest\n order "term" to highest, e.g., [1,2,3] represents the series\n ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Legendre series coefficients ordered from low to\n high.\n\n Returns\n -------\n quo, rem : ndarrays\n Of Legendre series coefficients representing the quotient and\n remainder.\n\n See Also\n --------\n legadd, legsub, legmulx, legmul, legpow\n\n Notes\n -----\n In general, the (polynomial) division of one Legendre series by another\n results in quotient and remainder terms that are not in the Legendre\n polynomial basis set. Thus, to express these results as a Legendre\n series, it is necessary to "reproject" the results onto the Legendre\n basis set, which may produce "unintuitive" (but correct) results; see\n Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial import legendre as L\n >>> c1 = (1,2,3)\n >>> c2 = (3,2,1)\n >>> L.legdiv(c1,c2) # quotient "intuitive," remainder not\n (array([3.]), array([-8., -4.]))\n >>> c2 = (0,1,2,3)\n >>> L.legdiv(c2,c1) # neither "intuitive"\n (array([-0.07407407, 1.66666667]), array([-1.03703704, -2.51851852])) # may vary\n\n """\n return pu._div(legmul, c1, c2)\n\n\ndef legpow(c, pow, maxpower=16):\n """Raise a Legendre series to a power.\n\n Returns the Legendre series `c` raised to the power `pow`. The\n argument `c` is a sequence of coefficients ordered from low to high.\n i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.``\n\n Parameters\n ----------\n c : array_like\n 1-D array of Legendre series coefficients ordered from low to\n high.\n pow : integer\n Power to which the series will be raised\n maxpower : integer, optional\n Maximum power allowed. This is mainly to limit growth of the series\n to unmanageable size. Default is 16\n\n Returns\n -------\n coef : ndarray\n Legendre series of power.\n\n See Also\n --------\n legadd, legsub, legmulx, legmul, legdiv\n\n """\n return pu._pow(legmul, c, pow, maxpower)\n\n\ndef legder(c, m=1, scl=1, axis=0):\n """\n Differentiate a Legendre series.\n\n Returns the Legendre series coefficients `c` differentiated `m` times\n along `axis`. At each iteration the result is multiplied by `scl` (the\n scaling factor is for use in a linear change of variable). The argument\n `c` is an array of coefficients from low to high degree along each\n axis, e.g., [1,2,3] represents the series ``1*L_0 + 2*L_1 + 3*L_2``\n while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) +\n 2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is\n ``y``.\n\n Parameters\n ----------\n c : array_like\n Array of Legendre series coefficients. If c is multidimensional the\n different axis correspond to different variables with the degree in\n each axis given by the corresponding index.\n m : int, optional\n Number of derivatives taken, must be non-negative. (Default: 1)\n scl : scalar, optional\n Each differentiation is multiplied by `scl`. The end result is\n multiplication by ``scl**m``. This is for use in a linear change of\n variable. (Default: 1)\n axis : int, optional\n Axis over which the derivative is taken. (Default: 0).\n\n Returns\n -------\n der : ndarray\n Legendre series of the derivative.\n\n See Also\n --------\n legint\n\n Notes\n -----\n In general, the result of differentiating a Legendre series does not\n resemble the same operation on a power series. Thus the result of this\n function may be "unintuitive," albeit correct; see Examples section\n below.\n\n Examples\n --------\n >>> from numpy.polynomial import legendre as L\n >>> c = (1,2,3,4)\n >>> L.legder(c)\n array([ 6., 9., 20.])\n >>> L.legder(c, 3)\n array([60.])\n >>> L.legder(c, scl=-1)\n array([ -6., -9., -20.])\n >>> L.legder(c, 2,-1)\n array([ 9., 60.])\n\n """\n c = np.array(c, ndmin=1, copy=True)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n cnt = pu._as_int(m, "the order of derivation")\n iaxis = pu._as_int(axis, "the axis")\n if cnt < 0:\n raise ValueError("The order of derivation must be non-negative")\n iaxis = normalize_axis_index(iaxis, c.ndim)\n\n if cnt == 0:\n return c\n\n c = np.moveaxis(c, iaxis, 0)\n n = len(c)\n if cnt >= n:\n c = c[:1] * 0\n else:\n for i in range(cnt):\n n = n - 1\n c *= scl\n der = np.empty((n,) + c.shape[1:], dtype=c.dtype)\n for j in range(n, 2, -1):\n der[j - 1] = (2 * j - 1) * c[j]\n c[j - 2] += c[j]\n if n > 1:\n der[1] = 3 * c[2]\n der[0] = c[1]\n c = der\n c = np.moveaxis(c, 0, iaxis)\n return c\n\n\ndef legint(c, m=1, k=[], lbnd=0, scl=1, axis=0):\n """\n Integrate a Legendre series.\n\n Returns the Legendre series coefficients `c` integrated `m` times from\n `lbnd` along `axis`. At each iteration the resulting series is\n **multiplied** by `scl` and an integration constant, `k`, is added.\n The scaling factor is for use in a linear change of variable. ("Buyer\n beware": note that, depending on what one is doing, one may want `scl`\n to be the reciprocal of what one might expect; for more information,\n see the Notes section below.) The argument `c` is an array of\n coefficients from low to high degree along each axis, e.g., [1,2,3]\n represents the series ``L_0 + 2*L_1 + 3*L_2`` while [[1,2],[1,2]]\n represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) +\n 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.\n\n Parameters\n ----------\n c : array_like\n Array of Legendre series coefficients. If c is multidimensional the\n different axis correspond to different variables with the degree in\n each axis given by the corresponding index.\n m : int, optional\n Order of integration, must be positive. (Default: 1)\n k : {[], list, scalar}, optional\n Integration constant(s). The value of the first integral at\n ``lbnd`` is the first value in the list, the value of the second\n integral at ``lbnd`` is the second value, etc. If ``k == []`` (the\n default), all constants are set to zero. If ``m == 1``, a single\n scalar can be given instead of a list.\n lbnd : scalar, optional\n The lower bound of the integral. (Default: 0)\n scl : scalar, optional\n Following each integration the result is *multiplied* by `scl`\n before the integration constant is added. (Default: 1)\n axis : int, optional\n Axis over which the integral is taken. (Default: 0).\n\n Returns\n -------\n S : ndarray\n Legendre series coefficient array of the integral.\n\n Raises\n ------\n ValueError\n If ``m < 0``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or\n ``np.ndim(scl) != 0``.\n\n See Also\n --------\n legder\n\n Notes\n -----\n Note that the result of each integration is *multiplied* by `scl`.\n Why is this important to note? Say one is making a linear change of\n variable :math:`u = ax + b` in an integral relative to `x`. Then\n :math:`dx = du/a`, so one will need to set `scl` equal to\n :math:`1/a` - perhaps not what one would have first thought.\n\n Also note that, in general, the result of integrating a C-series needs\n to be "reprojected" onto the C-series basis set. Thus, typically,\n the result of this function is "unintuitive," albeit correct; see\n Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial import legendre as L\n >>> c = (1,2,3)\n >>> L.legint(c)\n array([ 0.33333333, 0.4 , 0.66666667, 0.6 ]) # may vary\n >>> L.legint(c, 3)\n array([ 1.66666667e-02, -1.78571429e-02, 4.76190476e-02, # may vary\n -1.73472348e-18, 1.90476190e-02, 9.52380952e-03])\n >>> L.legint(c, k=3)\n array([ 3.33333333, 0.4 , 0.66666667, 0.6 ]) # may vary\n >>> L.legint(c, lbnd=-2)\n array([ 7.33333333, 0.4 , 0.66666667, 0.6 ]) # may vary\n >>> L.legint(c, scl=2)\n array([ 0.66666667, 0.8 , 1.33333333, 1.2 ]) # may vary\n\n """\n c = np.array(c, ndmin=1, copy=True)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n if not np.iterable(k):\n k = [k]\n cnt = pu._as_int(m, "the order of integration")\n iaxis = pu._as_int(axis, "the axis")\n if cnt < 0:\n raise ValueError("The order of integration must be non-negative")\n if len(k) > cnt:\n raise ValueError("Too many integration constants")\n if np.ndim(lbnd) != 0:\n raise ValueError("lbnd must be a scalar.")\n if np.ndim(scl) != 0:\n raise ValueError("scl must be a scalar.")\n iaxis = normalize_axis_index(iaxis, c.ndim)\n\n if cnt == 0:\n return c\n\n c = np.moveaxis(c, iaxis, 0)\n k = list(k) + [0] * (cnt - len(k))\n for i in range(cnt):\n n = len(c)\n c *= scl\n if n == 1 and np.all(c[0] == 0):\n c[0] += k[i]\n else:\n tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)\n tmp[0] = c[0] * 0\n tmp[1] = c[0]\n if n > 1:\n tmp[2] = c[1] / 3\n for j in range(2, n):\n t = c[j] / (2 * j + 1)\n tmp[j + 1] = t\n tmp[j - 1] -= t\n tmp[0] += k[i] - legval(lbnd, tmp)\n c = tmp\n c = np.moveaxis(c, 0, iaxis)\n return c\n\n\ndef legval(x, c, tensor=True):\n """\n Evaluate a Legendre series at points x.\n\n If `c` is of length ``n + 1``, this function returns the value:\n\n .. math:: p(x) = c_0 * L_0(x) + c_1 * L_1(x) + ... + c_n * L_n(x)\n\n The parameter `x` is converted to an array only if it is a tuple or a\n list, otherwise it is treated as a scalar. In either case, either `x`\n or its elements must support multiplication and addition both with\n themselves and with the elements of `c`.\n\n If `c` is a 1-D array, then ``p(x)`` will have the same shape as `x`. If\n `c` is multidimensional, then the shape of the result depends on the\n value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +\n x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that\n scalars have shape (,).\n\n Trailing zeros in the coefficients will be used in the evaluation, so\n they should be avoided if efficiency is a concern.\n\n Parameters\n ----------\n x : array_like, compatible object\n If `x` is a list or tuple, it is converted to an ndarray, otherwise\n it is left unchanged and treated as a scalar. In either case, `x`\n or its elements must support addition and multiplication with\n themselves and with the elements of `c`.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree n are contained in c[n]. If `c` is multidimensional the\n remaining indices enumerate multiple polynomials. In the two\n dimensional case the coefficients may be thought of as stored in\n the columns of `c`.\n tensor : boolean, optional\n If True, the shape of the coefficient array is extended with ones\n on the right, one for each dimension of `x`. Scalars have dimension 0\n for this action. The result is that every column of coefficients in\n `c` is evaluated for every element of `x`. If False, `x` is broadcast\n over the columns of `c` for the evaluation. This keyword is useful\n when `c` is multidimensional. The default value is True.\n\n Returns\n -------\n values : ndarray, algebra_like\n The shape of the return value is described above.\n\n See Also\n --------\n legval2d, leggrid2d, legval3d, leggrid3d\n\n Notes\n -----\n The evaluation uses Clenshaw recursion, aka synthetic division.\n\n """\n c = np.array(c, ndmin=1, copy=None)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n if isinstance(x, (tuple, list)):\n x = np.asarray(x)\n if isinstance(x, np.ndarray) and tensor:\n c = c.reshape(c.shape + (1,) * x.ndim)\n\n if len(c) == 1:\n c0 = c[0]\n c1 = 0\n elif len(c) == 2:\n c0 = c[0]\n c1 = c[1]\n else:\n nd = len(c)\n c0 = c[-2]\n c1 = c[-1]\n for i in range(3, len(c) + 1):\n tmp = c0\n nd = nd - 1\n c0 = c[-i] - c1 * ((nd - 1) / nd)\n c1 = tmp + c1 * x * ((2 * nd - 1) / nd)\n return c0 + c1 * x\n\n\ndef legval2d(x, y, c):\n """\n Evaluate a 2-D Legendre series at points (x, y).\n\n This function returns the values:\n\n .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * L_i(x) * L_j(y)\n\n The parameters `x` and `y` are converted to arrays only if they are\n tuples or a lists, otherwise they are treated as a scalars and they\n must have the same shape after conversion. In either case, either `x`\n and `y` or their elements must support multiplication and addition both\n with themselves and with the elements of `c`.\n\n If `c` is a 1-D array a one is implicitly appended to its shape to make\n it 2-D. The shape of the result will be c.shape[2:] + x.shape.\n\n Parameters\n ----------\n x, y : array_like, compatible objects\n The two dimensional series is evaluated at the points ``(x, y)``,\n where `x` and `y` must have the same shape. If `x` or `y` is a list\n or tuple, it is first converted to an ndarray, otherwise it is left\n unchanged and if it isn't an ndarray it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term\n of multi-degree i,j is contained in ``c[i,j]``. If `c` has\n dimension greater than two the remaining indices enumerate multiple\n sets of coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional Legendre series at points formed\n from pairs of corresponding values from `x` and `y`.\n\n See Also\n --------\n legval, leggrid2d, legval3d, leggrid3d\n """\n return pu._valnd(legval, c, x, y)\n\n\ndef leggrid2d(x, y, c):\n """\n Evaluate a 2-D Legendre series on the Cartesian product of x and y.\n\n This function returns the values:\n\n .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * L_i(a) * L_j(b)\n\n where the points ``(a, b)`` consist of all pairs formed by taking\n `a` from `x` and `b` from `y`. The resulting points form a grid with\n `x` in the first dimension and `y` in the second.\n\n The parameters `x` and `y` are converted to arrays only if they are\n tuples or a lists, otherwise they are treated as a scalars. In either\n case, either `x` and `y` or their elements must support multiplication\n and addition both with themselves and with the elements of `c`.\n\n If `c` has fewer than two dimensions, ones are implicitly appended to\n its shape to make it 2-D. The shape of the result will be c.shape[2:] +\n x.shape + y.shape.\n\n Parameters\n ----------\n x, y : array_like, compatible objects\n The two dimensional series is evaluated at the points in the\n Cartesian product of `x` and `y`. If `x` or `y` is a list or\n tuple, it is first converted to an ndarray, otherwise it is left\n unchanged and, if it isn't an ndarray, it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term of\n multi-degree i,j is contained in ``c[i,j]``. If `c` has dimension\n greater than two the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional Chebyshev series at points in the\n Cartesian product of `x` and `y`.\n\n See Also\n --------\n legval, legval2d, legval3d, leggrid3d\n """\n return pu._gridnd(legval, c, x, y)\n\n\ndef legval3d(x, y, z, c):\n """\n Evaluate a 3-D Legendre series at points (x, y, z).\n\n This function returns the values:\n\n .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * L_i(x) * L_j(y) * L_k(z)\n\n The parameters `x`, `y`, and `z` are converted to arrays only if\n they are tuples or a lists, otherwise they are treated as a scalars and\n they must have the same shape after conversion. In either case, either\n `x`, `y`, and `z` or their elements must support multiplication and\n addition both with themselves and with the elements of `c`.\n\n If `c` has fewer than 3 dimensions, ones are implicitly appended to its\n shape to make it 3-D. The shape of the result will be c.shape[3:] +\n x.shape.\n\n Parameters\n ----------\n x, y, z : array_like, compatible object\n The three dimensional series is evaluated at the points\n ``(x, y, z)``, where `x`, `y`, and `z` must have the same shape. If\n any of `x`, `y`, or `z` is a list or tuple, it is first converted\n to an ndarray, otherwise it is left unchanged and if it isn't an\n ndarray it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term of\n multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension\n greater than 3 the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the multidimensional polynomial on points formed with\n triples of corresponding values from `x`, `y`, and `z`.\n\n See Also\n --------\n legval, legval2d, leggrid2d, leggrid3d\n """\n return pu._valnd(legval, c, x, y, z)\n\n\ndef leggrid3d(x, y, z, c):\n """\n Evaluate a 3-D Legendre series on the Cartesian product of x, y, and z.\n\n This function returns the values:\n\n .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * L_i(a) * L_j(b) * L_k(c)\n\n where the points ``(a, b, c)`` consist of all triples formed by taking\n `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form\n a grid with `x` in the first dimension, `y` in the second, and `z` in\n the third.\n\n The parameters `x`, `y`, and `z` are converted to arrays only if they\n are tuples or a lists, otherwise they are treated as a scalars. In\n either case, either `x`, `y`, and `z` or their elements must support\n multiplication and addition both with themselves and with the elements\n of `c`.\n\n If `c` has fewer than three dimensions, ones are implicitly appended to\n its shape to make it 3-D. The shape of the result will be c.shape[3:] +\n x.shape + y.shape + z.shape.\n\n Parameters\n ----------\n x, y, z : array_like, compatible objects\n The three dimensional series is evaluated at the points in the\n Cartesian product of `x`, `y`, and `z`. If `x`, `y`, or `z` is a\n list or tuple, it is first converted to an ndarray, otherwise it is\n left unchanged and, if it isn't an ndarray, it is treated as a\n scalar.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree i,j are contained in ``c[i,j]``. If `c` has dimension\n greater than two the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points in the Cartesian\n product of `x` and `y`.\n\n See Also\n --------\n legval, legval2d, leggrid2d, legval3d\n """\n return pu._gridnd(legval, c, x, y, z)\n\n\ndef legvander(x, deg):\n """Pseudo-Vandermonde matrix of given degree.\n\n Returns the pseudo-Vandermonde matrix of degree `deg` and sample points\n `x`. The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., i] = L_i(x)\n\n where ``0 <= i <= deg``. The leading indices of `V` index the elements of\n `x` and the last index is the degree of the Legendre polynomial.\n\n If `c` is a 1-D array of coefficients of length ``n + 1`` and `V` is the\n array ``V = legvander(x, n)``, then ``np.dot(V, c)`` and\n ``legval(x, c)`` are the same up to roundoff. This equivalence is\n useful both for least squares fitting and for the evaluation of a large\n number of Legendre series of the same degree and sample points.\n\n Parameters\n ----------\n x : array_like\n Array of points. The dtype is converted to float64 or complex128\n depending on whether any of the elements are complex. If `x` is\n scalar it is converted to a 1-D array.\n deg : int\n Degree of the resulting matrix.\n\n Returns\n -------\n vander : ndarray\n The pseudo-Vandermonde matrix. The shape of the returned matrix is\n ``x.shape + (deg + 1,)``, where The last index is the degree of the\n corresponding Legendre polynomial. The dtype will be the same as\n the converted `x`.\n\n """\n ideg = pu._as_int(deg, "deg")\n if ideg < 0:\n raise ValueError("deg must be non-negative")\n\n x = np.array(x, copy=None, ndmin=1) + 0.0\n dims = (ideg + 1,) + x.shape\n dtyp = x.dtype\n v = np.empty(dims, dtype=dtyp)\n # Use forward recursion to generate the entries. This is not as accurate\n # as reverse recursion in this application but it is more efficient.\n v[0] = x * 0 + 1\n if ideg > 0:\n v[1] = x\n for i in range(2, ideg + 1):\n v[i] = (v[i - 1] * x * (2 * i - 1) - v[i - 2] * (i - 1)) / i\n return np.moveaxis(v, 0, -1)\n\n\ndef legvander2d(x, y, deg):\n """Pseudo-Vandermonde matrix of given degrees.\n\n Returns the pseudo-Vandermonde matrix of degrees `deg` and sample\n points ``(x, y)``. The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., (deg[1] + 1)*i + j] = L_i(x) * L_j(y),\n\n where ``0 <= i <= deg[0]`` and ``0 <= j <= deg[1]``. The leading indices of\n `V` index the points ``(x, y)`` and the last index encodes the degrees of\n the Legendre polynomials.\n\n If ``V = legvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`\n correspond to the elements of a 2-D coefficient array `c` of shape\n (xdeg + 1, ydeg + 1) in the order\n\n .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...\n\n and ``np.dot(V, c.flat)`` and ``legval2d(x, y, c)`` will be the same\n up to roundoff. This equivalence is useful both for least squares\n fitting and for the evaluation of a large number of 2-D Legendre\n series of the same degrees and sample points.\n\n Parameters\n ----------\n x, y : array_like\n Arrays of point coordinates, all of the same shape. The dtypes\n will be converted to either float64 or complex128 depending on\n whether any of the elements are complex. Scalars are converted to\n 1-D arrays.\n deg : list of ints\n List of maximum degrees of the form [x_deg, y_deg].\n\n Returns\n -------\n vander2d : ndarray\n The shape of the returned matrix is ``x.shape + (order,)``, where\n :math:`order = (deg[0]+1)*(deg[1]+1)`. The dtype will be the same\n as the converted `x` and `y`.\n\n See Also\n --------\n legvander, legvander3d, legval2d, legval3d\n """\n return pu._vander_nd_flat((legvander, legvander), (x, y), deg)\n\n\ndef legvander3d(x, y, z, deg):\n """Pseudo-Vandermonde matrix of given degrees.\n\n Returns the pseudo-Vandermonde matrix of degrees `deg` and sample\n points ``(x, y, z)``. If `l`, `m`, `n` are the given degrees in `x`, `y`, `z`,\n then The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = L_i(x)*L_j(y)*L_k(z),\n\n where ``0 <= i <= l``, ``0 <= j <= m``, and ``0 <= j <= n``. The leading\n indices of `V` index the points ``(x, y, z)`` and the last index encodes\n the degrees of the Legendre polynomials.\n\n If ``V = legvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns\n of `V` correspond to the elements of a 3-D coefficient array `c` of\n shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order\n\n .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...\n\n and ``np.dot(V, c.flat)`` and ``legval3d(x, y, z, c)`` will be the\n same up to roundoff. This equivalence is useful both for least squares\n fitting and for the evaluation of a large number of 3-D Legendre\n series of the same degrees and sample points.\n\n Parameters\n ----------\n x, y, z : array_like\n Arrays of point coordinates, all of the same shape. The dtypes will\n be converted to either float64 or complex128 depending on whether\n any of the elements are complex. Scalars are converted to 1-D\n arrays.\n deg : list of ints\n List of maximum degrees of the form [x_deg, y_deg, z_deg].\n\n Returns\n -------\n vander3d : ndarray\n The shape of the returned matrix is ``x.shape + (order,)``, where\n :math:`order = (deg[0]+1)*(deg[1]+1)*(deg[2]+1)`. The dtype will\n be the same as the converted `x`, `y`, and `z`.\n\n See Also\n --------\n legvander, legvander3d, legval2d, legval3d\n """\n return pu._vander_nd_flat((legvander, legvander, legvander), (x, y, z), deg)\n\n\ndef legfit(x, y, deg, rcond=None, full=False, w=None):\n """\n Least squares fit of Legendre series to data.\n\n Return the coefficients of a Legendre series of degree `deg` that is the\n least squares fit to the data values `y` given at points `x`. If `y` is\n 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple\n fits are done, one for each column of `y`, and the resulting\n coefficients are stored in the corresponding columns of a 2-D return.\n The fitted polynomial(s) are in the form\n\n .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x),\n\n where `n` is `deg`.\n\n Parameters\n ----------\n x : array_like, shape (M,)\n x-coordinates of the M sample points ``(x[i], y[i])``.\n y : array_like, shape (M,) or (M, K)\n y-coordinates of the sample points. Several data sets of sample\n points sharing the same x-coordinates can be fitted at once by\n passing in a 2D-array that contains one dataset per column.\n deg : int or 1-D array_like\n Degree(s) of the fitting polynomials. If `deg` is a single integer\n all terms up to and including the `deg`'th term are included in the\n fit. For NumPy versions >= 1.11.0 a list of integers specifying the\n degrees of the terms to include may be used instead.\n rcond : float, optional\n Relative condition number of the fit. Singular values smaller than\n this relative to the largest singular value will be ignored. The\n default value is len(x)*eps, where eps is the relative precision of\n the float type, about 2e-16 in most cases.\n full : bool, optional\n Switch determining nature of return value. When it is False (the\n default) just the coefficients are returned, when True diagnostic\n information from the singular value decomposition is also returned.\n w : array_like, shape (`M`,), optional\n Weights. If not None, the weight ``w[i]`` applies to the unsquared\n residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are\n chosen so that the errors of the products ``w[i]*y[i]`` all have the\n same variance. When using inverse-variance weighting, use\n ``w[i] = 1/sigma(y[i])``. The default value is None.\n\n Returns\n -------\n coef : ndarray, shape (M,) or (M, K)\n Legendre coefficients ordered from low to high. If `y` was\n 2-D, the coefficients for the data in column k of `y` are in\n column `k`. If `deg` is specified as a list, coefficients for\n terms not included in the fit are set equal to zero in the\n returned `coef`.\n\n [residuals, rank, singular_values, rcond] : list\n These values are only returned if ``full == True``\n\n - residuals -- sum of squared residuals of the least squares fit\n - rank -- the numerical rank of the scaled Vandermonde matrix\n - singular_values -- singular values of the scaled Vandermonde matrix\n - rcond -- value of `rcond`.\n\n For more details, see `numpy.linalg.lstsq`.\n\n Warns\n -----\n RankWarning\n The rank of the coefficient matrix in the least-squares fit is\n deficient. The warning is only raised if ``full == False``. The\n warnings can be turned off by\n\n >>> import warnings\n >>> warnings.simplefilter('ignore', np.exceptions.RankWarning)\n\n See Also\n --------\n numpy.polynomial.polynomial.polyfit\n numpy.polynomial.chebyshev.chebfit\n numpy.polynomial.laguerre.lagfit\n numpy.polynomial.hermite.hermfit\n numpy.polynomial.hermite_e.hermefit\n legval : Evaluates a Legendre series.\n legvander : Vandermonde matrix of Legendre series.\n legweight : Legendre weight function (= 1).\n numpy.linalg.lstsq : Computes a least-squares fit from the matrix.\n scipy.interpolate.UnivariateSpline : Computes spline fits.\n\n Notes\n -----\n The solution is the coefficients of the Legendre series `p` that\n minimizes the sum of the weighted squared errors\n\n .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,\n\n where :math:`w_j` are the weights. This problem is solved by setting up\n as the (typically) overdetermined matrix equation\n\n .. math:: V(x) * c = w * y,\n\n where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the\n coefficients to be solved for, `w` are the weights, and `y` are the\n observed values. This equation is then solved using the singular value\n decomposition of `V`.\n\n If some of the singular values of `V` are so small that they are\n neglected, then a `~exceptions.RankWarning` will be issued. This means that\n the coefficient values may be poorly determined. Using a lower order fit\n will usually get rid of the warning. The `rcond` parameter can also be\n set to a value smaller than its default, but the resulting fit may be\n spurious and have large contributions from roundoff error.\n\n Fits using Legendre series are usually better conditioned than fits\n using power series, but much can depend on the distribution of the\n sample points and the smoothness of the data. If the quality of the fit\n is inadequate splines may be a good alternative.\n\n References\n ----------\n .. [1] Wikipedia, "Curve fitting",\n https://en.wikipedia.org/wiki/Curve_fitting\n\n Examples\n --------\n\n """\n return pu._fit(legvander, x, y, deg, rcond, full, w)\n\n\ndef legcompanion(c):\n """Return the scaled companion matrix of c.\n\n The basis polynomials are scaled so that the companion matrix is\n symmetric when `c` is an Legendre basis polynomial. This provides\n better eigenvalue estimates than the unscaled case and for basis\n polynomials the eigenvalues are guaranteed to be real if\n `numpy.linalg.eigvalsh` is used to obtain them.\n\n Parameters\n ----------\n c : array_like\n 1-D array of Legendre series coefficients ordered from low to high\n degree.\n\n Returns\n -------\n mat : ndarray\n Scaled companion matrix of dimensions (deg, deg).\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n if len(c) < 2:\n raise ValueError('Series must have maximum degree of at least 1.')\n if len(c) == 2:\n return np.array([[-c[0] / c[1]]])\n\n n = len(c) - 1\n mat = np.zeros((n, n), dtype=c.dtype)\n scl = 1. / np.sqrt(2 * np.arange(n) + 1)\n top = mat.reshape(-1)[1::n + 1]\n bot = mat.reshape(-1)[n::n + 1]\n top[...] = np.arange(1, n) * scl[:n - 1] * scl[1:n]\n bot[...] = top\n mat[:, -1] -= (c[:-1] / c[-1]) * (scl / scl[-1]) * (n / (2 * n - 1))\n return mat\n\n\ndef legroots(c):\n """\n Compute the roots of a Legendre series.\n\n Return the roots (a.k.a. "zeros") of the polynomial\n\n .. math:: p(x) = \\sum_i c[i] * L_i(x).\n\n Parameters\n ----------\n c : 1-D array_like\n 1-D array of coefficients.\n\n Returns\n -------\n out : ndarray\n Array of the roots of the series. If all the roots are real,\n then `out` is also real, otherwise it is complex.\n\n See Also\n --------\n numpy.polynomial.polynomial.polyroots\n numpy.polynomial.chebyshev.chebroots\n numpy.polynomial.laguerre.lagroots\n numpy.polynomial.hermite.hermroots\n numpy.polynomial.hermite_e.hermeroots\n\n Notes\n -----\n The root estimates are obtained as the eigenvalues of the companion\n matrix, Roots far from the origin of the complex plane may have large\n errors due to the numerical instability of the series for such values.\n Roots with multiplicity greater than 1 will also show larger errors as\n the value of the series near such points is relatively insensitive to\n errors in the roots. Isolated roots near the origin can be improved by\n a few iterations of Newton's method.\n\n The Legendre series basis polynomials aren't powers of ``x`` so the\n results of this function may seem unintuitive.\n\n Examples\n --------\n >>> import numpy.polynomial.legendre as leg\n >>> leg.legroots((1, 2, 3, 4)) # 4L_3 + 3L_2 + 2L_1 + 1L_0, all real roots\n array([-0.85099543, -0.11407192, 0.51506735]) # may vary\n\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n if len(c) < 2:\n return np.array([], dtype=c.dtype)\n if len(c) == 2:\n return np.array([-c[0] / c[1]])\n\n # rotated companion matrix reduces error\n m = legcompanion(c)[::-1, ::-1]\n r = la.eigvals(m)\n r.sort()\n return r\n\n\ndef leggauss(deg):\n """\n Gauss-Legendre quadrature.\n\n Computes the sample points and weights for Gauss-Legendre quadrature.\n These sample points and weights will correctly integrate polynomials of\n degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with\n the weight function :math:`f(x) = 1`.\n\n Parameters\n ----------\n deg : int\n Number of sample points and weights. It must be >= 1.\n\n Returns\n -------\n x : ndarray\n 1-D ndarray containing the sample points.\n y : ndarray\n 1-D ndarray containing the weights.\n\n Notes\n -----\n The results have only been tested up to degree 100, higher degrees may\n be problematic. The weights are determined by using the fact that\n\n .. math:: w_k = c / (L'_n(x_k) * L_{n-1}(x_k))\n\n where :math:`c` is a constant independent of :math:`k` and :math:`x_k`\n is the k'th root of :math:`L_n`, and then scaling the results to get\n the right value when integrating 1.\n\n """\n ideg = pu._as_int(deg, "deg")\n if ideg <= 0:\n raise ValueError("deg must be a positive integer")\n\n # first approximation of roots. We use the fact that the companion\n # matrix is symmetric in this case in order to obtain better zeros.\n c = np.array([0] * deg + [1])\n m = legcompanion(c)\n x = la.eigvalsh(m)\n\n # improve roots by one application of Newton\n dy = legval(x, c)\n df = legval(x, legder(c))\n x -= dy / df\n\n # compute the weights. We scale the factor to avoid possible numerical\n # overflow.\n fm = legval(x, c[1:])\n fm /= np.abs(fm).max()\n df /= np.abs(df).max()\n w = 1 / (fm * df)\n\n # for Legendre we can also symmetrize\n w = (w + w[::-1]) / 2\n x = (x - x[::-1]) / 2\n\n # scale w to get the right value\n w *= 2. / w.sum()\n\n return x, w\n\n\ndef legweight(x):\n """\n Weight function of the Legendre polynomials.\n\n The weight function is :math:`1` and the interval of integration is\n :math:`[-1, 1]`. The Legendre polynomials are orthogonal, but not\n normalized, with respect to this weight function.\n\n Parameters\n ----------\n x : array_like\n Values at which the weight function will be computed.\n\n Returns\n -------\n w : ndarray\n The weight function at `x`.\n """\n w = x * 0.0 + 1.0\n return w\n\n#\n# Legendre series class\n#\n\nclass Legendre(ABCPolyBase):\n """A Legendre series class.\n\n The Legendre class provides the standard Python numerical methods\n '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the\n attributes and methods listed below.\n\n Parameters\n ----------\n coef : array_like\n Legendre coefficients in order of increasing degree, i.e.,\n ``(1, 2, 3)`` gives ``1*P_0(x) + 2*P_1(x) + 3*P_2(x)``.\n domain : (2,) array_like, optional\n Domain to use. The interval ``[domain[0], domain[1]]`` is mapped\n to the interval ``[window[0], window[1]]`` by shifting and scaling.\n The default value is [-1., 1.].\n window : (2,) array_like, optional\n Window, see `domain` for its use. The default value is [-1., 1.].\n symbol : str, optional\n Symbol used to represent the independent variable in string\n representations of the polynomial expression, e.g. for printing.\n The symbol must be a valid Python identifier. Default value is 'x'.\n\n .. versionadded:: 1.24\n\n """\n # Virtual Functions\n _add = staticmethod(legadd)\n _sub = staticmethod(legsub)\n _mul = staticmethod(legmul)\n _div = staticmethod(legdiv)\n _pow = staticmethod(legpow)\n _val = staticmethod(legval)\n _int = staticmethod(legint)\n _der = staticmethod(legder)\n _fit = staticmethod(legfit)\n _line = staticmethod(legline)\n _roots = staticmethod(legroots)\n _fromroots = staticmethod(legfromroots)\n\n # Virtual properties\n domain = np.array(legdomain)\n window = np.array(legdomain)\n basis_name = 'P'\n | .venv\Lib\site-packages\numpy\polynomial\legendre.py | legendre.py | Python | 52,734 | 0.75 | 0.086604 | 0.023006 | node-utils | 235 | 2024-05-03T02:43:37.546516 | GPL-3.0 | false | 6b11a990b86530e221b2895a1f4ff0b4 |
from typing import Final\nfrom typing import Literal as L\n\nimport numpy as np\n\nfrom ._polybase import ABCPolyBase\nfrom ._polytypes import (\n _Array1,\n _Array2,\n _FuncBinOp,\n _FuncCompanion,\n _FuncDer,\n _FuncFit,\n _FuncFromRoots,\n _FuncGauss,\n _FuncInteg,\n _FuncLine,\n _FuncPoly2Ortho,\n _FuncPow,\n _FuncRoots,\n _FuncUnOp,\n _FuncVal,\n _FuncVal2D,\n _FuncVal3D,\n _FuncValFromRoots,\n _FuncVander,\n _FuncVander2D,\n _FuncVander3D,\n _FuncWeight,\n)\nfrom .polyutils import trimcoef as legtrim\n\n__all__ = [\n "legzero",\n "legone",\n "legx",\n "legdomain",\n "legline",\n "legadd",\n "legsub",\n "legmulx",\n "legmul",\n "legdiv",\n "legpow",\n "legval",\n "legder",\n "legint",\n "leg2poly",\n "poly2leg",\n "legfromroots",\n "legvander",\n "legfit",\n "legtrim",\n "legroots",\n "Legendre",\n "legval2d",\n "legval3d",\n "leggrid2d",\n "leggrid3d",\n "legvander2d",\n "legvander3d",\n "legcompanion",\n "leggauss",\n "legweight",\n]\n\npoly2leg: _FuncPoly2Ortho[L["poly2leg"]]\nleg2poly: _FuncUnOp[L["leg2poly"]]\n\nlegdomain: Final[_Array2[np.float64]]\nlegzero: Final[_Array1[np.int_]]\nlegone: Final[_Array1[np.int_]]\nlegx: Final[_Array2[np.int_]]\n\nlegline: _FuncLine[L["legline"]]\nlegfromroots: _FuncFromRoots[L["legfromroots"]]\nlegadd: _FuncBinOp[L["legadd"]]\nlegsub: _FuncBinOp[L["legsub"]]\nlegmulx: _FuncUnOp[L["legmulx"]]\nlegmul: _FuncBinOp[L["legmul"]]\nlegdiv: _FuncBinOp[L["legdiv"]]\nlegpow: _FuncPow[L["legpow"]]\nlegder: _FuncDer[L["legder"]]\nlegint: _FuncInteg[L["legint"]]\nlegval: _FuncVal[L["legval"]]\nlegval2d: _FuncVal2D[L["legval2d"]]\nlegval3d: _FuncVal3D[L["legval3d"]]\nlegvalfromroots: _FuncValFromRoots[L["legvalfromroots"]]\nleggrid2d: _FuncVal2D[L["leggrid2d"]]\nleggrid3d: _FuncVal3D[L["leggrid3d"]]\nlegvander: _FuncVander[L["legvander"]]\nlegvander2d: _FuncVander2D[L["legvander2d"]]\nlegvander3d: _FuncVander3D[L["legvander3d"]]\nlegfit: _FuncFit[L["legfit"]]\nlegcompanion: _FuncCompanion[L["legcompanion"]]\nlegroots: _FuncRoots[L["legroots"]]\nleggauss: _FuncGauss[L["leggauss"]]\nlegweight: _FuncWeight[L["legweight"]]\n\nclass Legendre(ABCPolyBase[L["P"]]): ...\n | .venv\Lib\site-packages\numpy\polynomial\legendre.pyi | legendre.pyi | Other | 2,291 | 0.85 | 0.01 | 0 | python-kit | 895 | 2023-08-07T13:23:49.975564 | BSD-3-Clause | false | 9cb7f65714f22fa0d1dd962da36e98e4 |
"""\n=================================================\nPower Series (:mod:`numpy.polynomial.polynomial`)\n=================================================\n\nThis module provides a number of objects (mostly functions) useful for\ndealing with polynomials, including a `Polynomial` class that\nencapsulates the usual arithmetic operations. (General information\non how this module represents and works with polynomial objects is in\nthe docstring for its "parent" sub-package, `numpy.polynomial`).\n\nClasses\n-------\n.. autosummary::\n :toctree: generated/\n\n Polynomial\n\nConstants\n---------\n.. autosummary::\n :toctree: generated/\n\n polydomain\n polyzero\n polyone\n polyx\n\nArithmetic\n----------\n.. autosummary::\n :toctree: generated/\n\n polyadd\n polysub\n polymulx\n polymul\n polydiv\n polypow\n polyval\n polyval2d\n polyval3d\n polygrid2d\n polygrid3d\n\nCalculus\n--------\n.. autosummary::\n :toctree: generated/\n\n polyder\n polyint\n\nMisc Functions\n--------------\n.. autosummary::\n :toctree: generated/\n\n polyfromroots\n polyroots\n polyvalfromroots\n polyvander\n polyvander2d\n polyvander3d\n polycompanion\n polyfit\n polytrim\n polyline\n\nSee Also\n--------\n`numpy.polynomial`\n\n"""\n__all__ = [\n 'polyzero', 'polyone', 'polyx', 'polydomain', 'polyline', 'polyadd',\n 'polysub', 'polymulx', 'polymul', 'polydiv', 'polypow', 'polyval',\n 'polyvalfromroots', 'polyder', 'polyint', 'polyfromroots', 'polyvander',\n 'polyfit', 'polytrim', 'polyroots', 'Polynomial', 'polyval2d', 'polyval3d',\n 'polygrid2d', 'polygrid3d', 'polyvander2d', 'polyvander3d',\n 'polycompanion']\n\nimport numpy as np\nimport numpy.linalg as la\nfrom numpy.lib.array_utils import normalize_axis_index\n\nfrom . import polyutils as pu\nfrom ._polybase import ABCPolyBase\n\npolytrim = pu.trimcoef\n\n#\n# These are constant arrays are of integer type so as to be compatible\n# with the widest range of other types, such as Decimal.\n#\n\n# Polynomial default domain.\npolydomain = np.array([-1., 1.])\n\n# Polynomial coefficients representing zero.\npolyzero = np.array([0])\n\n# Polynomial coefficients representing one.\npolyone = np.array([1])\n\n# Polynomial coefficients representing the identity x.\npolyx = np.array([0, 1])\n\n#\n# Polynomial series functions\n#\n\n\ndef polyline(off, scl):\n """\n Returns an array representing a linear polynomial.\n\n Parameters\n ----------\n off, scl : scalars\n The "y-intercept" and "slope" of the line, respectively.\n\n Returns\n -------\n y : ndarray\n This module's representation of the linear polynomial ``off +\n scl*x``.\n\n See Also\n --------\n numpy.polynomial.chebyshev.chebline\n numpy.polynomial.legendre.legline\n numpy.polynomial.laguerre.lagline\n numpy.polynomial.hermite.hermline\n numpy.polynomial.hermite_e.hermeline\n\n Examples\n --------\n >>> from numpy.polynomial import polynomial as P\n >>> P.polyline(1, -1)\n array([ 1, -1])\n >>> P.polyval(1, P.polyline(1, -1)) # should be 0\n 0.0\n\n """\n if scl != 0:\n return np.array([off, scl])\n else:\n return np.array([off])\n\n\ndef polyfromroots(roots):\n """\n Generate a monic polynomial with given roots.\n\n Return the coefficients of the polynomial\n\n .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),\n\n where the :math:`r_n` are the roots specified in `roots`. If a zero has\n multiplicity n, then it must appear in `roots` n times. For instance,\n if 2 is a root of multiplicity three and 3 is a root of multiplicity 2,\n then `roots` looks something like [2, 2, 2, 3, 3]. The roots can appear\n in any order.\n\n If the returned coefficients are `c`, then\n\n .. math:: p(x) = c_0 + c_1 * x + ... + x^n\n\n The coefficient of the last term is 1 for monic polynomials in this\n form.\n\n Parameters\n ----------\n roots : array_like\n Sequence containing the roots.\n\n Returns\n -------\n out : ndarray\n 1-D array of the polynomial's coefficients If all the roots are\n real, then `out` is also real, otherwise it is complex. (see\n Examples below).\n\n See Also\n --------\n numpy.polynomial.chebyshev.chebfromroots\n numpy.polynomial.legendre.legfromroots\n numpy.polynomial.laguerre.lagfromroots\n numpy.polynomial.hermite.hermfromroots\n numpy.polynomial.hermite_e.hermefromroots\n\n Notes\n -----\n The coefficients are determined by multiplying together linear factors\n of the form ``(x - r_i)``, i.e.\n\n .. math:: p(x) = (x - r_0) (x - r_1) ... (x - r_n)\n\n where ``n == len(roots) - 1``; note that this implies that ``1`` is always\n returned for :math:`a_n`.\n\n Examples\n --------\n >>> from numpy.polynomial import polynomial as P\n >>> P.polyfromroots((-1,0,1)) # x(x - 1)(x + 1) = x^3 - x\n array([ 0., -1., 0., 1.])\n >>> j = complex(0,1)\n >>> P.polyfromroots((-j,j)) # complex returned, though values are real\n array([1.+0.j, 0.+0.j, 1.+0.j])\n\n """\n return pu._fromroots(polyline, polymul, roots)\n\n\ndef polyadd(c1, c2):\n """\n Add one polynomial to another.\n\n Returns the sum of two polynomials `c1` + `c2`. The arguments are\n sequences of coefficients from lowest order term to highest, i.e.,\n [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of polynomial coefficients ordered from low to high.\n\n Returns\n -------\n out : ndarray\n The coefficient array representing their sum.\n\n See Also\n --------\n polysub, polymulx, polymul, polydiv, polypow\n\n Examples\n --------\n >>> from numpy.polynomial import polynomial as P\n >>> c1 = (1, 2, 3)\n >>> c2 = (3, 2, 1)\n >>> sum = P.polyadd(c1,c2); sum\n array([4., 4., 4.])\n >>> P.polyval(2, sum) # 4 + 4(2) + 4(2**2)\n 28.0\n\n """\n return pu._add(c1, c2)\n\n\ndef polysub(c1, c2):\n """\n Subtract one polynomial from another.\n\n Returns the difference of two polynomials `c1` - `c2`. The arguments\n are sequences of coefficients from lowest order term to highest, i.e.,\n [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of polynomial coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Of coefficients representing their difference.\n\n See Also\n --------\n polyadd, polymulx, polymul, polydiv, polypow\n\n Examples\n --------\n >>> from numpy.polynomial import polynomial as P\n >>> c1 = (1, 2, 3)\n >>> c2 = (3, 2, 1)\n >>> P.polysub(c1,c2)\n array([-2., 0., 2.])\n >>> P.polysub(c2, c1) # -P.polysub(c1,c2)\n array([ 2., 0., -2.])\n\n """\n return pu._sub(c1, c2)\n\n\ndef polymulx(c):\n """Multiply a polynomial by x.\n\n Multiply the polynomial `c` by x, where x is the independent\n variable.\n\n\n Parameters\n ----------\n c : array_like\n 1-D array of polynomial coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Array representing the result of the multiplication.\n\n See Also\n --------\n polyadd, polysub, polymul, polydiv, polypow\n\n Examples\n --------\n >>> from numpy.polynomial import polynomial as P\n >>> c = (1, 2, 3)\n >>> P.polymulx(c)\n array([0., 1., 2., 3.])\n\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n # The zero series needs special treatment\n if len(c) == 1 and c[0] == 0:\n return c\n\n prd = np.empty(len(c) + 1, dtype=c.dtype)\n prd[0] = c[0] * 0\n prd[1:] = c\n return prd\n\n\ndef polymul(c1, c2):\n """\n Multiply one polynomial by another.\n\n Returns the product of two polynomials `c1` * `c2`. The arguments are\n sequences of coefficients, from lowest order term to highest, e.g.,\n [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2.``\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of coefficients representing a polynomial, relative to the\n "standard" basis, and ordered from lowest order term to highest.\n\n Returns\n -------\n out : ndarray\n Of the coefficients of their product.\n\n See Also\n --------\n polyadd, polysub, polymulx, polydiv, polypow\n\n Examples\n --------\n >>> from numpy.polynomial import polynomial as P\n >>> c1 = (1, 2, 3)\n >>> c2 = (3, 2, 1)\n >>> P.polymul(c1, c2)\n array([ 3., 8., 14., 8., 3.])\n\n """\n # c1, c2 are trimmed copies\n [c1, c2] = pu.as_series([c1, c2])\n ret = np.convolve(c1, c2)\n return pu.trimseq(ret)\n\n\ndef polydiv(c1, c2):\n """\n Divide one polynomial by another.\n\n Returns the quotient-with-remainder of two polynomials `c1` / `c2`.\n The arguments are sequences of coefficients, from lowest order term\n to highest, e.g., [1,2,3] represents ``1 + 2*x + 3*x**2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of polynomial coefficients ordered from low to high.\n\n Returns\n -------\n [quo, rem] : ndarrays\n Of coefficient series representing the quotient and remainder.\n\n See Also\n --------\n polyadd, polysub, polymulx, polymul, polypow\n\n Examples\n --------\n >>> from numpy.polynomial import polynomial as P\n >>> c1 = (1, 2, 3)\n >>> c2 = (3, 2, 1)\n >>> P.polydiv(c1, c2)\n (array([3.]), array([-8., -4.]))\n >>> P.polydiv(c2, c1)\n (array([ 0.33333333]), array([ 2.66666667, 1.33333333])) # may vary\n\n """\n # c1, c2 are trimmed copies\n [c1, c2] = pu.as_series([c1, c2])\n if c2[-1] == 0:\n raise ZeroDivisionError # FIXME: add message with details to exception\n\n # note: this is more efficient than `pu._div(polymul, c1, c2)`\n lc1 = len(c1)\n lc2 = len(c2)\n if lc1 < lc2:\n return c1[:1] * 0, c1\n elif lc2 == 1:\n return c1 / c2[-1], c1[:1] * 0\n else:\n dlen = lc1 - lc2\n scl = c2[-1]\n c2 = c2[:-1] / scl\n i = dlen\n j = lc1 - 1\n while i >= 0:\n c1[i:j] -= c2 * c1[j]\n i -= 1\n j -= 1\n return c1[j + 1:] / scl, pu.trimseq(c1[:j + 1])\n\n\ndef polypow(c, pow, maxpower=None):\n """Raise a polynomial to a power.\n\n Returns the polynomial `c` raised to the power `pow`. The argument\n `c` is a sequence of coefficients ordered from low to high. i.e.,\n [1,2,3] is the series ``1 + 2*x + 3*x**2.``\n\n Parameters\n ----------\n c : array_like\n 1-D array of array of series coefficients ordered from low to\n high degree.\n pow : integer\n Power to which the series will be raised\n maxpower : integer, optional\n Maximum power allowed. This is mainly to limit growth of the series\n to unmanageable size. Default is 16\n\n Returns\n -------\n coef : ndarray\n Power series of power.\n\n See Also\n --------\n polyadd, polysub, polymulx, polymul, polydiv\n\n Examples\n --------\n >>> from numpy.polynomial import polynomial as P\n >>> P.polypow([1, 2, 3], 2)\n array([ 1., 4., 10., 12., 9.])\n\n """\n # note: this is more efficient than `pu._pow(polymul, c1, c2)`, as it\n # avoids calling `as_series` repeatedly\n return pu._pow(np.convolve, c, pow, maxpower)\n\n\ndef polyder(c, m=1, scl=1, axis=0):\n """\n Differentiate a polynomial.\n\n Returns the polynomial coefficients `c` differentiated `m` times along\n `axis`. At each iteration the result is multiplied by `scl` (the\n scaling factor is for use in a linear change of variable). The\n argument `c` is an array of coefficients from low to high degree along\n each axis, e.g., [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``\n while [[1,2],[1,2]] represents ``1 + 1*x + 2*y + 2*x*y`` if axis=0 is\n ``x`` and axis=1 is ``y``.\n\n Parameters\n ----------\n c : array_like\n Array of polynomial coefficients. If c is multidimensional the\n different axis correspond to different variables with the degree\n in each axis given by the corresponding index.\n m : int, optional\n Number of derivatives taken, must be non-negative. (Default: 1)\n scl : scalar, optional\n Each differentiation is multiplied by `scl`. The end result is\n multiplication by ``scl**m``. This is for use in a linear change\n of variable. (Default: 1)\n axis : int, optional\n Axis over which the derivative is taken. (Default: 0).\n\n Returns\n -------\n der : ndarray\n Polynomial coefficients of the derivative.\n\n See Also\n --------\n polyint\n\n Examples\n --------\n >>> from numpy.polynomial import polynomial as P\n >>> c = (1, 2, 3, 4)\n >>> P.polyder(c) # (d/dx)(c)\n array([ 2., 6., 12.])\n >>> P.polyder(c, 3) # (d**3/dx**3)(c)\n array([24.])\n >>> P.polyder(c, scl=-1) # (d/d(-x))(c)\n array([ -2., -6., -12.])\n >>> P.polyder(c, 2, -1) # (d**2/d(-x)**2)(c)\n array([ 6., 24.])\n\n """\n c = np.array(c, ndmin=1, copy=True)\n if c.dtype.char in '?bBhHiIlLqQpP':\n # astype fails with NA\n c = c + 0.0\n cdt = c.dtype\n cnt = pu._as_int(m, "the order of derivation")\n iaxis = pu._as_int(axis, "the axis")\n if cnt < 0:\n raise ValueError("The order of derivation must be non-negative")\n iaxis = normalize_axis_index(iaxis, c.ndim)\n\n if cnt == 0:\n return c\n\n c = np.moveaxis(c, iaxis, 0)\n n = len(c)\n if cnt >= n:\n c = c[:1] * 0\n else:\n for i in range(cnt):\n n = n - 1\n c *= scl\n der = np.empty((n,) + c.shape[1:], dtype=cdt)\n for j in range(n, 0, -1):\n der[j - 1] = j * c[j]\n c = der\n c = np.moveaxis(c, 0, iaxis)\n return c\n\n\ndef polyint(c, m=1, k=[], lbnd=0, scl=1, axis=0):\n """\n Integrate a polynomial.\n\n Returns the polynomial coefficients `c` integrated `m` times from\n `lbnd` along `axis`. At each iteration the resulting series is\n **multiplied** by `scl` and an integration constant, `k`, is added.\n The scaling factor is for use in a linear change of variable. ("Buyer\n beware": note that, depending on what one is doing, one may want `scl`\n to be the reciprocal of what one might expect; for more information,\n see the Notes section below.) The argument `c` is an array of\n coefficients, from low to high degree along each axis, e.g., [1,2,3]\n represents the polynomial ``1 + 2*x + 3*x**2`` while [[1,2],[1,2]]\n represents ``1 + 1*x + 2*y + 2*x*y`` if axis=0 is ``x`` and axis=1 is\n ``y``.\n\n Parameters\n ----------\n c : array_like\n 1-D array of polynomial coefficients, ordered from low to high.\n m : int, optional\n Order of integration, must be positive. (Default: 1)\n k : {[], list, scalar}, optional\n Integration constant(s). The value of the first integral at zero\n is the first value in the list, the value of the second integral\n at zero is the second value, etc. If ``k == []`` (the default),\n all constants are set to zero. If ``m == 1``, a single scalar can\n be given instead of a list.\n lbnd : scalar, optional\n The lower bound of the integral. (Default: 0)\n scl : scalar, optional\n Following each integration the result is *multiplied* by `scl`\n before the integration constant is added. (Default: 1)\n axis : int, optional\n Axis over which the integral is taken. (Default: 0).\n\n Returns\n -------\n S : ndarray\n Coefficient array of the integral.\n\n Raises\n ------\n ValueError\n If ``m < 1``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or\n ``np.ndim(scl) != 0``.\n\n See Also\n --------\n polyder\n\n Notes\n -----\n Note that the result of each integration is *multiplied* by `scl`. Why\n is this important to note? Say one is making a linear change of\n variable :math:`u = ax + b` in an integral relative to `x`. Then\n :math:`dx = du/a`, so one will need to set `scl` equal to\n :math:`1/a` - perhaps not what one would have first thought.\n\n Examples\n --------\n >>> from numpy.polynomial import polynomial as P\n >>> c = (1, 2, 3)\n >>> P.polyint(c) # should return array([0, 1, 1, 1])\n array([0., 1., 1., 1.])\n >>> P.polyint(c, 3) # should return array([0, 0, 0, 1/6, 1/12, 1/20])\n array([ 0. , 0. , 0. , 0.16666667, 0.08333333, # may vary\n 0.05 ])\n >>> P.polyint(c, k=3) # should return array([3, 1, 1, 1])\n array([3., 1., 1., 1.])\n >>> P.polyint(c,lbnd=-2) # should return array([6, 1, 1, 1])\n array([6., 1., 1., 1.])\n >>> P.polyint(c,scl=-2) # should return array([0, -2, -2, -2])\n array([ 0., -2., -2., -2.])\n\n """\n c = np.array(c, ndmin=1, copy=True)\n if c.dtype.char in '?bBhHiIlLqQpP':\n # astype doesn't preserve mask attribute.\n c = c + 0.0\n cdt = c.dtype\n if not np.iterable(k):\n k = [k]\n cnt = pu._as_int(m, "the order of integration")\n iaxis = pu._as_int(axis, "the axis")\n if cnt < 0:\n raise ValueError("The order of integration must be non-negative")\n if len(k) > cnt:\n raise ValueError("Too many integration constants")\n if np.ndim(lbnd) != 0:\n raise ValueError("lbnd must be a scalar.")\n if np.ndim(scl) != 0:\n raise ValueError("scl must be a scalar.")\n iaxis = normalize_axis_index(iaxis, c.ndim)\n\n if cnt == 0:\n return c\n\n k = list(k) + [0] * (cnt - len(k))\n c = np.moveaxis(c, iaxis, 0)\n for i in range(cnt):\n n = len(c)\n c *= scl\n if n == 1 and np.all(c[0] == 0):\n c[0] += k[i]\n else:\n tmp = np.empty((n + 1,) + c.shape[1:], dtype=cdt)\n tmp[0] = c[0] * 0\n tmp[1] = c[0]\n for j in range(1, n):\n tmp[j + 1] = c[j] / (j + 1)\n tmp[0] += k[i] - polyval(lbnd, tmp)\n c = tmp\n c = np.moveaxis(c, 0, iaxis)\n return c\n\n\ndef polyval(x, c, tensor=True):\n """\n Evaluate a polynomial at points x.\n\n If `c` is of length ``n + 1``, this function returns the value\n\n .. math:: p(x) = c_0 + c_1 * x + ... + c_n * x^n\n\n The parameter `x` is converted to an array only if it is a tuple or a\n list, otherwise it is treated as a scalar. In either case, either `x`\n or its elements must support multiplication and addition both with\n themselves and with the elements of `c`.\n\n If `c` is a 1-D array, then ``p(x)`` will have the same shape as `x`. If\n `c` is multidimensional, then the shape of the result depends on the\n value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +\n x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that\n scalars have shape (,).\n\n Trailing zeros in the coefficients will be used in the evaluation, so\n they should be avoided if efficiency is a concern.\n\n Parameters\n ----------\n x : array_like, compatible object\n If `x` is a list or tuple, it is converted to an ndarray, otherwise\n it is left unchanged and treated as a scalar. In either case, `x`\n or its elements must support addition and multiplication with\n with themselves and with the elements of `c`.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree n are contained in c[n]. If `c` is multidimensional the\n remaining indices enumerate multiple polynomials. In the two\n dimensional case the coefficients may be thought of as stored in\n the columns of `c`.\n tensor : boolean, optional\n If True, the shape of the coefficient array is extended with ones\n on the right, one for each dimension of `x`. Scalars have dimension 0\n for this action. The result is that every column of coefficients in\n `c` is evaluated for every element of `x`. If False, `x` is broadcast\n over the columns of `c` for the evaluation. This keyword is useful\n when `c` is multidimensional. The default value is True.\n\n Returns\n -------\n values : ndarray, compatible object\n The shape of the returned array is described above.\n\n See Also\n --------\n polyval2d, polygrid2d, polyval3d, polygrid3d\n\n Notes\n -----\n The evaluation uses Horner's method.\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial.polynomial import polyval\n >>> polyval(1, [1,2,3])\n 6.0\n >>> a = np.arange(4).reshape(2,2)\n >>> a\n array([[0, 1],\n [2, 3]])\n >>> polyval(a, [1, 2, 3])\n array([[ 1., 6.],\n [17., 34.]])\n >>> coef = np.arange(4).reshape(2, 2) # multidimensional coefficients\n >>> coef\n array([[0, 1],\n [2, 3]])\n >>> polyval([1, 2], coef, tensor=True)\n array([[2., 4.],\n [4., 7.]])\n >>> polyval([1, 2], coef, tensor=False)\n array([2., 7.])\n\n """\n c = np.array(c, ndmin=1, copy=None)\n if c.dtype.char in '?bBhHiIlLqQpP':\n # astype fails with NA\n c = c + 0.0\n if isinstance(x, (tuple, list)):\n x = np.asarray(x)\n if isinstance(x, np.ndarray) and tensor:\n c = c.reshape(c.shape + (1,) * x.ndim)\n\n c0 = c[-1] + x * 0\n for i in range(2, len(c) + 1):\n c0 = c[-i] + c0 * x\n return c0\n\n\ndef polyvalfromroots(x, r, tensor=True):\n """\n Evaluate a polynomial specified by its roots at points x.\n\n If `r` is of length ``N``, this function returns the value\n\n .. math:: p(x) = \\prod_{n=1}^{N} (x - r_n)\n\n The parameter `x` is converted to an array only if it is a tuple or a\n list, otherwise it is treated as a scalar. In either case, either `x`\n or its elements must support multiplication and addition both with\n themselves and with the elements of `r`.\n\n If `r` is a 1-D array, then ``p(x)`` will have the same shape as `x`. If `r`\n is multidimensional, then the shape of the result depends on the value of\n `tensor`. If `tensor` is ``True`` the shape will be r.shape[1:] + x.shape;\n that is, each polynomial is evaluated at every value of `x`. If `tensor` is\n ``False``, the shape will be r.shape[1:]; that is, each polynomial is\n evaluated only for the corresponding broadcast value of `x`. Note that\n scalars have shape (,).\n\n Parameters\n ----------\n x : array_like, compatible object\n If `x` is a list or tuple, it is converted to an ndarray, otherwise\n it is left unchanged and treated as a scalar. In either case, `x`\n or its elements must support addition and multiplication with\n with themselves and with the elements of `r`.\n r : array_like\n Array of roots. If `r` is multidimensional the first index is the\n root index, while the remaining indices enumerate multiple\n polynomials. For instance, in the two dimensional case the roots\n of each polynomial may be thought of as stored in the columns of `r`.\n tensor : boolean, optional\n If True, the shape of the roots array is extended with ones on the\n right, one for each dimension of `x`. Scalars have dimension 0 for this\n action. The result is that every column of coefficients in `r` is\n evaluated for every element of `x`. If False, `x` is broadcast over the\n columns of `r` for the evaluation. This keyword is useful when `r` is\n multidimensional. The default value is True.\n\n Returns\n -------\n values : ndarray, compatible object\n The shape of the returned array is described above.\n\n See Also\n --------\n polyroots, polyfromroots, polyval\n\n Examples\n --------\n >>> from numpy.polynomial.polynomial import polyvalfromroots\n >>> polyvalfromroots(1, [1, 2, 3])\n 0.0\n >>> a = np.arange(4).reshape(2, 2)\n >>> a\n array([[0, 1],\n [2, 3]])\n >>> polyvalfromroots(a, [-1, 0, 1])\n array([[-0., 0.],\n [ 6., 24.]])\n >>> r = np.arange(-2, 2).reshape(2,2) # multidimensional coefficients\n >>> r # each column of r defines one polynomial\n array([[-2, -1],\n [ 0, 1]])\n >>> b = [-2, 1]\n >>> polyvalfromroots(b, r, tensor=True)\n array([[-0., 3.],\n [ 3., 0.]])\n >>> polyvalfromroots(b, r, tensor=False)\n array([-0., 0.])\n\n """\n r = np.array(r, ndmin=1, copy=None)\n if r.dtype.char in '?bBhHiIlLqQpP':\n r = r.astype(np.double)\n if isinstance(x, (tuple, list)):\n x = np.asarray(x)\n if isinstance(x, np.ndarray):\n if tensor:\n r = r.reshape(r.shape + (1,) * x.ndim)\n elif x.ndim >= r.ndim:\n raise ValueError("x.ndim must be < r.ndim when tensor == False")\n return np.prod(x - r, axis=0)\n\n\ndef polyval2d(x, y, c):\n """\n Evaluate a 2-D polynomial at points (x, y).\n\n This function returns the value\n\n .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * x^i * y^j\n\n The parameters `x` and `y` are converted to arrays only if they are\n tuples or a lists, otherwise they are treated as a scalars and they\n must have the same shape after conversion. In either case, either `x`\n and `y` or their elements must support multiplication and addition both\n with themselves and with the elements of `c`.\n\n If `c` has fewer than two dimensions, ones are implicitly appended to\n its shape to make it 2-D. The shape of the result will be c.shape[2:] +\n x.shape.\n\n Parameters\n ----------\n x, y : array_like, compatible objects\n The two dimensional series is evaluated at the points ``(x, y)``,\n where `x` and `y` must have the same shape. If `x` or `y` is a list\n or tuple, it is first converted to an ndarray, otherwise it is left\n unchanged and, if it isn't an ndarray, it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term\n of multi-degree i,j is contained in ``c[i,j]``. If `c` has\n dimension greater than two the remaining indices enumerate multiple\n sets of coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points formed with\n pairs of corresponding values from `x` and `y`.\n\n See Also\n --------\n polyval, polygrid2d, polyval3d, polygrid3d\n\n Examples\n --------\n >>> from numpy.polynomial import polynomial as P\n >>> c = ((1, 2, 3), (4, 5, 6))\n >>> P.polyval2d(1, 1, c)\n 21.0\n\n """\n return pu._valnd(polyval, c, x, y)\n\n\ndef polygrid2d(x, y, c):\n """\n Evaluate a 2-D polynomial on the Cartesian product of x and y.\n\n This function returns the values:\n\n .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * a^i * b^j\n\n where the points ``(a, b)`` consist of all pairs formed by taking\n `a` from `x` and `b` from `y`. The resulting points form a grid with\n `x` in the first dimension and `y` in the second.\n\n The parameters `x` and `y` are converted to arrays only if they are\n tuples or a lists, otherwise they are treated as a scalars. In either\n case, either `x` and `y` or their elements must support multiplication\n and addition both with themselves and with the elements of `c`.\n\n If `c` has fewer than two dimensions, ones are implicitly appended to\n its shape to make it 2-D. The shape of the result will be c.shape[2:] +\n x.shape + y.shape.\n\n Parameters\n ----------\n x, y : array_like, compatible objects\n The two dimensional series is evaluated at the points in the\n Cartesian product of `x` and `y`. If `x` or `y` is a list or\n tuple, it is first converted to an ndarray, otherwise it is left\n unchanged and, if it isn't an ndarray, it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree i,j are contained in ``c[i,j]``. If `c` has dimension\n greater than two the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points in the Cartesian\n product of `x` and `y`.\n\n See Also\n --------\n polyval, polyval2d, polyval3d, polygrid3d\n\n Examples\n --------\n >>> from numpy.polynomial import polynomial as P\n >>> c = ((1, 2, 3), (4, 5, 6))\n >>> P.polygrid2d([0, 1], [0, 1], c)\n array([[ 1., 6.],\n [ 5., 21.]])\n\n """\n return pu._gridnd(polyval, c, x, y)\n\n\ndef polyval3d(x, y, z, c):\n """\n Evaluate a 3-D polynomial at points (x, y, z).\n\n This function returns the values:\n\n .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * x^i * y^j * z^k\n\n The parameters `x`, `y`, and `z` are converted to arrays only if\n they are tuples or a lists, otherwise they are treated as a scalars and\n they must have the same shape after conversion. In either case, either\n `x`, `y`, and `z` or their elements must support multiplication and\n addition both with themselves and with the elements of `c`.\n\n If `c` has fewer than 3 dimensions, ones are implicitly appended to its\n shape to make it 3-D. The shape of the result will be c.shape[3:] +\n x.shape.\n\n Parameters\n ----------\n x, y, z : array_like, compatible object\n The three dimensional series is evaluated at the points\n ``(x, y, z)``, where `x`, `y`, and `z` must have the same shape. If\n any of `x`, `y`, or `z` is a list or tuple, it is first converted\n to an ndarray, otherwise it is left unchanged and if it isn't an\n ndarray it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term of\n multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension\n greater than 3 the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the multidimensional polynomial on points formed with\n triples of corresponding values from `x`, `y`, and `z`.\n\n See Also\n --------\n polyval, polyval2d, polygrid2d, polygrid3d\n\n Examples\n --------\n >>> from numpy.polynomial import polynomial as P\n >>> c = ((1, 2, 3), (4, 5, 6), (7, 8, 9))\n >>> P.polyval3d(1, 1, 1, c)\n 45.0\n\n """\n return pu._valnd(polyval, c, x, y, z)\n\n\ndef polygrid3d(x, y, z, c):\n """\n Evaluate a 3-D polynomial on the Cartesian product of x, y and z.\n\n This function returns the values:\n\n .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * a^i * b^j * c^k\n\n where the points ``(a, b, c)`` consist of all triples formed by taking\n `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form\n a grid with `x` in the first dimension, `y` in the second, and `z` in\n the third.\n\n The parameters `x`, `y`, and `z` are converted to arrays only if they\n are tuples or a lists, otherwise they are treated as a scalars. In\n either case, either `x`, `y`, and `z` or their elements must support\n multiplication and addition both with themselves and with the elements\n of `c`.\n\n If `c` has fewer than three dimensions, ones are implicitly appended to\n its shape to make it 3-D. The shape of the result will be c.shape[3:] +\n x.shape + y.shape + z.shape.\n\n Parameters\n ----------\n x, y, z : array_like, compatible objects\n The three dimensional series is evaluated at the points in the\n Cartesian product of `x`, `y`, and `z`. If `x`, `y`, or `z` is a\n list or tuple, it is first converted to an ndarray, otherwise it is\n left unchanged and, if it isn't an ndarray, it is treated as a\n scalar.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree i,j are contained in ``c[i,j]``. If `c` has dimension\n greater than two the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points in the Cartesian\n product of `x` and `y`.\n\n See Also\n --------\n polyval, polyval2d, polygrid2d, polyval3d\n\n Examples\n --------\n >>> from numpy.polynomial import polynomial as P\n >>> c = ((1, 2, 3), (4, 5, 6), (7, 8, 9))\n >>> P.polygrid3d([0, 1], [0, 1], [0, 1], c)\n array([[ 1., 13.],\n [ 6., 51.]])\n\n """\n return pu._gridnd(polyval, c, x, y, z)\n\n\ndef polyvander(x, deg):\n """Vandermonde matrix of given degree.\n\n Returns the Vandermonde matrix of degree `deg` and sample points\n `x`. The Vandermonde matrix is defined by\n\n .. math:: V[..., i] = x^i,\n\n where ``0 <= i <= deg``. The leading indices of `V` index the elements of\n `x` and the last index is the power of `x`.\n\n If `c` is a 1-D array of coefficients of length ``n + 1`` and `V` is the\n matrix ``V = polyvander(x, n)``, then ``np.dot(V, c)`` and\n ``polyval(x, c)`` are the same up to roundoff. This equivalence is\n useful both for least squares fitting and for the evaluation of a large\n number of polynomials of the same degree and sample points.\n\n Parameters\n ----------\n x : array_like\n Array of points. The dtype is converted to float64 or complex128\n depending on whether any of the elements are complex. If `x` is\n scalar it is converted to a 1-D array.\n deg : int\n Degree of the resulting matrix.\n\n Returns\n -------\n vander : ndarray.\n The Vandermonde matrix. The shape of the returned matrix is\n ``x.shape + (deg + 1,)``, where the last index is the power of `x`.\n The dtype will be the same as the converted `x`.\n\n See Also\n --------\n polyvander2d, polyvander3d\n\n Examples\n --------\n The Vandermonde matrix of degree ``deg = 5`` and sample points\n ``x = [-1, 2, 3]`` contains the element-wise powers of `x`\n from 0 to 5 as its columns.\n\n >>> from numpy.polynomial import polynomial as P\n >>> x, deg = [-1, 2, 3], 5\n >>> P.polyvander(x=x, deg=deg)\n array([[ 1., -1., 1., -1., 1., -1.],\n [ 1., 2., 4., 8., 16., 32.],\n [ 1., 3., 9., 27., 81., 243.]])\n\n """\n ideg = pu._as_int(deg, "deg")\n if ideg < 0:\n raise ValueError("deg must be non-negative")\n\n x = np.array(x, copy=None, ndmin=1) + 0.0\n dims = (ideg + 1,) + x.shape\n dtyp = x.dtype\n v = np.empty(dims, dtype=dtyp)\n v[0] = x * 0 + 1\n if ideg > 0:\n v[1] = x\n for i in range(2, ideg + 1):\n v[i] = v[i - 1] * x\n return np.moveaxis(v, 0, -1)\n\n\ndef polyvander2d(x, y, deg):\n """Pseudo-Vandermonde matrix of given degrees.\n\n Returns the pseudo-Vandermonde matrix of degrees `deg` and sample\n points ``(x, y)``. The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., (deg[1] + 1)*i + j] = x^i * y^j,\n\n where ``0 <= i <= deg[0]`` and ``0 <= j <= deg[1]``. The leading indices of\n `V` index the points ``(x, y)`` and the last index encodes the powers of\n `x` and `y`.\n\n If ``V = polyvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`\n correspond to the elements of a 2-D coefficient array `c` of shape\n (xdeg + 1, ydeg + 1) in the order\n\n .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...\n\n and ``np.dot(V, c.flat)`` and ``polyval2d(x, y, c)`` will be the same\n up to roundoff. This equivalence is useful both for least squares\n fitting and for the evaluation of a large number of 2-D polynomials\n of the same degrees and sample points.\n\n Parameters\n ----------\n x, y : array_like\n Arrays of point coordinates, all of the same shape. The dtypes\n will be converted to either float64 or complex128 depending on\n whether any of the elements are complex. Scalars are converted to\n 1-D arrays.\n deg : list of ints\n List of maximum degrees of the form [x_deg, y_deg].\n\n Returns\n -------\n vander2d : ndarray\n The shape of the returned matrix is ``x.shape + (order,)``, where\n :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same\n as the converted `x` and `y`.\n\n See Also\n --------\n polyvander, polyvander3d, polyval2d, polyval3d\n\n Examples\n --------\n >>> import numpy as np\n\n The 2-D pseudo-Vandermonde matrix of degree ``[1, 2]`` and sample\n points ``x = [-1, 2]`` and ``y = [1, 3]`` is as follows:\n\n >>> from numpy.polynomial import polynomial as P\n >>> x = np.array([-1, 2])\n >>> y = np.array([1, 3])\n >>> m, n = 1, 2\n >>> deg = np.array([m, n])\n >>> V = P.polyvander2d(x=x, y=y, deg=deg)\n >>> V\n array([[ 1., 1., 1., -1., -1., -1.],\n [ 1., 3., 9., 2., 6., 18.]])\n\n We can verify the columns for any ``0 <= i <= m`` and ``0 <= j <= n``:\n\n >>> i, j = 0, 1\n >>> V[:, (deg[1]+1)*i + j] == x**i * y**j\n array([ True, True])\n\n The (1D) Vandermonde matrix of sample points ``x`` and degree ``m`` is a\n special case of the (2D) pseudo-Vandermonde matrix with ``y`` points all\n zero and degree ``[m, 0]``.\n\n >>> P.polyvander2d(x=x, y=0*x, deg=(m, 0)) == P.polyvander(x=x, deg=m)\n array([[ True, True],\n [ True, True]])\n\n """\n return pu._vander_nd_flat((polyvander, polyvander), (x, y), deg)\n\n\ndef polyvander3d(x, y, z, deg):\n """Pseudo-Vandermonde matrix of given degrees.\n\n Returns the pseudo-Vandermonde matrix of degrees `deg` and sample\n points ``(x, y, z)``. If `l`, `m`, `n` are the given degrees in `x`, `y`, `z`,\n then The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = x^i * y^j * z^k,\n\n where ``0 <= i <= l``, ``0 <= j <= m``, and ``0 <= j <= n``. The leading\n indices of `V` index the points ``(x, y, z)`` and the last index encodes\n the powers of `x`, `y`, and `z`.\n\n If ``V = polyvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns\n of `V` correspond to the elements of a 3-D coefficient array `c` of\n shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order\n\n .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...\n\n and ``np.dot(V, c.flat)`` and ``polyval3d(x, y, z, c)`` will be the\n same up to roundoff. This equivalence is useful both for least squares\n fitting and for the evaluation of a large number of 3-D polynomials\n of the same degrees and sample points.\n\n Parameters\n ----------\n x, y, z : array_like\n Arrays of point coordinates, all of the same shape. The dtypes will\n be converted to either float64 or complex128 depending on whether\n any of the elements are complex. Scalars are converted to 1-D\n arrays.\n deg : list of ints\n List of maximum degrees of the form [x_deg, y_deg, z_deg].\n\n Returns\n -------\n vander3d : ndarray\n The shape of the returned matrix is ``x.shape + (order,)``, where\n :math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will\n be the same as the converted `x`, `y`, and `z`.\n\n See Also\n --------\n polyvander, polyvander3d, polyval2d, polyval3d\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial import polynomial as P\n >>> x = np.asarray([-1, 2, 1])\n >>> y = np.asarray([1, -2, -3])\n >>> z = np.asarray([2, 2, 5])\n >>> l, m, n = [2, 2, 1]\n >>> deg = [l, m, n]\n >>> V = P.polyvander3d(x=x, y=y, z=z, deg=deg)\n >>> V\n array([[ 1., 2., 1., 2., 1., 2., -1., -2., -1.,\n -2., -1., -2., 1., 2., 1., 2., 1., 2.],\n [ 1., 2., -2., -4., 4., 8., 2., 4., -4.,\n -8., 8., 16., 4., 8., -8., -16., 16., 32.],\n [ 1., 5., -3., -15., 9., 45., 1., 5., -3.,\n -15., 9., 45., 1., 5., -3., -15., 9., 45.]])\n\n We can verify the columns for any ``0 <= i <= l``, ``0 <= j <= m``,\n and ``0 <= k <= n``\n\n >>> i, j, k = 2, 1, 0\n >>> V[:, (m+1)*(n+1)*i + (n+1)*j + k] == x**i * y**j * z**k\n array([ True, True, True])\n\n """\n return pu._vander_nd_flat((polyvander, polyvander, polyvander), (x, y, z), deg)\n\n\ndef polyfit(x, y, deg, rcond=None, full=False, w=None):\n """\n Least-squares fit of a polynomial to data.\n\n Return the coefficients of a polynomial of degree `deg` that is the\n least squares fit to the data values `y` given at points `x`. If `y` is\n 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple\n fits are done, one for each column of `y`, and the resulting\n coefficients are stored in the corresponding columns of a 2-D return.\n The fitted polynomial(s) are in the form\n\n .. math:: p(x) = c_0 + c_1 * x + ... + c_n * x^n,\n\n where `n` is `deg`.\n\n Parameters\n ----------\n x : array_like, shape (`M`,)\n x-coordinates of the `M` sample (data) points ``(x[i], y[i])``.\n y : array_like, shape (`M`,) or (`M`, `K`)\n y-coordinates of the sample points. Several sets of sample points\n sharing the same x-coordinates can be (independently) fit with one\n call to `polyfit` by passing in for `y` a 2-D array that contains\n one data set per column.\n deg : int or 1-D array_like\n Degree(s) of the fitting polynomials. If `deg` is a single integer\n all terms up to and including the `deg`'th term are included in the\n fit. For NumPy versions >= 1.11.0 a list of integers specifying the\n degrees of the terms to include may be used instead.\n rcond : float, optional\n Relative condition number of the fit. Singular values smaller\n than `rcond`, relative to the largest singular value, will be\n ignored. The default value is ``len(x)*eps``, where `eps` is the\n relative precision of the platform's float type, about 2e-16 in\n most cases.\n full : bool, optional\n Switch determining the nature of the return value. When ``False``\n (the default) just the coefficients are returned; when ``True``,\n diagnostic information from the singular value decomposition (used\n to solve the fit's matrix equation) is also returned.\n w : array_like, shape (`M`,), optional\n Weights. If not None, the weight ``w[i]`` applies to the unsquared\n residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are\n chosen so that the errors of the products ``w[i]*y[i]`` all have the\n same variance. When using inverse-variance weighting, use\n ``w[i] = 1/sigma(y[i])``. The default value is None.\n\n Returns\n -------\n coef : ndarray, shape (`deg` + 1,) or (`deg` + 1, `K`)\n Polynomial coefficients ordered from low to high. If `y` was 2-D,\n the coefficients in column `k` of `coef` represent the polynomial\n fit to the data in `y`'s `k`-th column.\n\n [residuals, rank, singular_values, rcond] : list\n These values are only returned if ``full == True``\n\n - residuals -- sum of squared residuals of the least squares fit\n - rank -- the numerical rank of the scaled Vandermonde matrix\n - singular_values -- singular values of the scaled Vandermonde matrix\n - rcond -- value of `rcond`.\n\n For more details, see `numpy.linalg.lstsq`.\n\n Raises\n ------\n RankWarning\n Raised if the matrix in the least-squares fit is rank deficient.\n The warning is only raised if ``full == False``. The warnings can\n be turned off by:\n\n >>> import warnings\n >>> warnings.simplefilter('ignore', np.exceptions.RankWarning)\n\n See Also\n --------\n numpy.polynomial.chebyshev.chebfit\n numpy.polynomial.legendre.legfit\n numpy.polynomial.laguerre.lagfit\n numpy.polynomial.hermite.hermfit\n numpy.polynomial.hermite_e.hermefit\n polyval : Evaluates a polynomial.\n polyvander : Vandermonde matrix for powers.\n numpy.linalg.lstsq : Computes a least-squares fit from the matrix.\n scipy.interpolate.UnivariateSpline : Computes spline fits.\n\n Notes\n -----\n The solution is the coefficients of the polynomial `p` that minimizes\n the sum of the weighted squared errors\n\n .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,\n\n where the :math:`w_j` are the weights. This problem is solved by\n setting up the (typically) over-determined matrix equation:\n\n .. math:: V(x) * c = w * y,\n\n where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the\n coefficients to be solved for, `w` are the weights, and `y` are the\n observed values. This equation is then solved using the singular value\n decomposition of `V`.\n\n If some of the singular values of `V` are so small that they are\n neglected (and `full` == ``False``), a `~exceptions.RankWarning` will be\n raised. This means that the coefficient values may be poorly determined.\n Fitting to a lower order polynomial will usually get rid of the warning\n (but may not be what you want, of course; if you have independent\n reason(s) for choosing the degree which isn't working, you may have to:\n a) reconsider those reasons, and/or b) reconsider the quality of your\n data). The `rcond` parameter can also be set to a value smaller than\n its default, but the resulting fit may be spurious and have large\n contributions from roundoff error.\n\n Polynomial fits using double precision tend to "fail" at about\n (polynomial) degree 20. Fits using Chebyshev or Legendre series are\n generally better conditioned, but much can still depend on the\n distribution of the sample points and the smoothness of the data. If\n the quality of the fit is inadequate, splines may be a good\n alternative.\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial import polynomial as P\n >>> x = np.linspace(-1,1,51) # x "data": [-1, -0.96, ..., 0.96, 1]\n >>> rng = np.random.default_rng()\n >>> err = rng.normal(size=len(x))\n >>> y = x**3 - x + err # x^3 - x + Gaussian noise\n >>> c, stats = P.polyfit(x,y,3,full=True)\n >>> c # c[0], c[1] approx. -1, c[2] should be approx. 0, c[3] approx. 1\n array([ 0.23111996, -1.02785049, -0.2241444 , 1.08405657]) # may vary\n >>> stats # note the large SSR, explaining the rather poor results\n [array([48.312088]), # may vary\n 4,\n array([1.38446749, 1.32119158, 0.50443316, 0.28853036]),\n 1.1324274851176597e-14]\n\n Same thing without the added noise\n\n >>> y = x**3 - x\n >>> c, stats = P.polyfit(x,y,3,full=True)\n >>> c # c[0], c[1] ~= -1, c[2] should be "very close to 0", c[3] ~= 1\n array([-6.73496154e-17, -1.00000000e+00, 0.00000000e+00, 1.00000000e+00])\n >>> stats # note the minuscule SSR\n [array([8.79579319e-31]),\n np.int32(4),\n array([1.38446749, 1.32119158, 0.50443316, 0.28853036]),\n 1.1324274851176597e-14]\n\n """\n return pu._fit(polyvander, x, y, deg, rcond, full, w)\n\n\ndef polycompanion(c):\n """\n Return the companion matrix of c.\n\n The companion matrix for power series cannot be made symmetric by\n scaling the basis, so this function differs from those for the\n orthogonal polynomials.\n\n Parameters\n ----------\n c : array_like\n 1-D array of polynomial coefficients ordered from low to high\n degree.\n\n Returns\n -------\n mat : ndarray\n Companion matrix of dimensions (deg, deg).\n\n Examples\n --------\n >>> from numpy.polynomial import polynomial as P\n >>> c = (1, 2, 3)\n >>> P.polycompanion(c)\n array([[ 0. , -0.33333333],\n [ 1. , -0.66666667]])\n\n """\n # c is a trimmed copy\n [c] = pu.as_series([c])\n if len(c) < 2:\n raise ValueError('Series must have maximum degree of at least 1.')\n if len(c) == 2:\n return np.array([[-c[0] / c[1]]])\n\n n = len(c) - 1\n mat = np.zeros((n, n), dtype=c.dtype)\n bot = mat.reshape(-1)[n::n + 1]\n bot[...] = 1\n mat[:, -1] -= c[:-1] / c[-1]\n return mat\n\n\ndef polyroots(c):\n """\n Compute the roots of a polynomial.\n\n Return the roots (a.k.a. "zeros") of the polynomial\n\n .. math:: p(x) = \\sum_i c[i] * x^i.\n\n Parameters\n ----------\n c : 1-D array_like\n 1-D array of polynomial coefficients.\n\n Returns\n -------\n out : ndarray\n Array of the roots of the polynomial. If all the roots are real,\n then `out` is also real, otherwise it is complex.\n\n See Also\n --------\n numpy.polynomial.chebyshev.chebroots\n numpy.polynomial.legendre.legroots\n numpy.polynomial.laguerre.lagroots\n numpy.polynomial.hermite.hermroots\n numpy.polynomial.hermite_e.hermeroots\n\n Notes\n -----\n The root estimates are obtained as the eigenvalues of the companion\n matrix, Roots far from the origin of the complex plane may have large\n errors due to the numerical instability of the power series for such\n values. Roots with multiplicity greater than 1 will also show larger\n errors as the value of the series near such points is relatively\n insensitive to errors in the roots. Isolated roots near the origin can\n be improved by a few iterations of Newton's method.\n\n Examples\n --------\n >>> import numpy.polynomial.polynomial as poly\n >>> poly.polyroots(poly.polyfromroots((-1,0,1)))\n array([-1., 0., 1.])\n >>> poly.polyroots(poly.polyfromroots((-1,0,1))).dtype\n dtype('float64')\n >>> j = complex(0,1)\n >>> poly.polyroots(poly.polyfromroots((-j,0,j)))\n array([ 0.00000000e+00+0.j, 0.00000000e+00+1.j, 2.77555756e-17-1.j]) # may vary\n\n """ # noqa: E501\n # c is a trimmed copy\n [c] = pu.as_series([c])\n if len(c) < 2:\n return np.array([], dtype=c.dtype)\n if len(c) == 2:\n return np.array([-c[0] / c[1]])\n\n m = polycompanion(c)\n r = la.eigvals(m)\n r.sort()\n return r\n\n\n#\n# polynomial class\n#\n\nclass Polynomial(ABCPolyBase):\n """A power series class.\n\n The Polynomial class provides the standard Python numerical methods\n '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the\n attributes and methods listed below.\n\n Parameters\n ----------\n coef : array_like\n Polynomial coefficients in order of increasing degree, i.e.,\n ``(1, 2, 3)`` give ``1 + 2*x + 3*x**2``.\n domain : (2,) array_like, optional\n Domain to use. The interval ``[domain[0], domain[1]]`` is mapped\n to the interval ``[window[0], window[1]]`` by shifting and scaling.\n The default value is [-1., 1.].\n window : (2,) array_like, optional\n Window, see `domain` for its use. The default value is [-1., 1.].\n symbol : str, optional\n Symbol used to represent the independent variable in string\n representations of the polynomial expression, e.g. for printing.\n The symbol must be a valid Python identifier. Default value is 'x'.\n\n .. versionadded:: 1.24\n\n """\n # Virtual Functions\n _add = staticmethod(polyadd)\n _sub = staticmethod(polysub)\n _mul = staticmethod(polymul)\n _div = staticmethod(polydiv)\n _pow = staticmethod(polypow)\n _val = staticmethod(polyval)\n _int = staticmethod(polyint)\n _der = staticmethod(polyder)\n _fit = staticmethod(polyfit)\n _line = staticmethod(polyline)\n _roots = staticmethod(polyroots)\n _fromroots = staticmethod(polyfromroots)\n\n # Virtual properties\n domain = np.array(polydomain)\n window = np.array(polydomain)\n basis_name = None\n\n @classmethod\n def _str_term_unicode(cls, i, arg_str):\n if i == '1':\n return f"·{arg_str}"\n else:\n return f"·{arg_str}{i.translate(cls._superscript_mapping)}"\n\n @staticmethod\n def _str_term_ascii(i, arg_str):\n if i == '1':\n return f" {arg_str}"\n else:\n return f" {arg_str}**{i}"\n\n @staticmethod\n def _repr_latex_term(i, arg_str, needs_parens):\n if needs_parens:\n arg_str = rf"\left({arg_str}\right)"\n if i == 0:\n return '1'\n elif i == 1:\n return arg_str\n else:\n return f"{arg_str}^{{{i}}}"\n | .venv\Lib\site-packages\numpy\polynomial\polynomial.py | polynomial.py | Python | 53,812 | 0.75 | 0.084158 | 0.02187 | react-lib | 279 | 2025-06-02T12:07:23.330085 | BSD-3-Clause | false | dd5ce63c673cd82ec678f82736f6a854 |
from typing import Final\nfrom typing import Literal as L\n\nimport numpy as np\n\nfrom ._polybase import ABCPolyBase\nfrom ._polytypes import (\n _Array1,\n _Array2,\n _FuncBinOp,\n _FuncCompanion,\n _FuncDer,\n _FuncFit,\n _FuncFromRoots,\n _FuncInteg,\n _FuncLine,\n _FuncPow,\n _FuncRoots,\n _FuncUnOp,\n _FuncVal,\n _FuncVal2D,\n _FuncVal3D,\n _FuncValFromRoots,\n _FuncVander,\n _FuncVander2D,\n _FuncVander3D,\n)\nfrom .polyutils import trimcoef as polytrim\n\n__all__ = [\n "polyzero",\n "polyone",\n "polyx",\n "polydomain",\n "polyline",\n "polyadd",\n "polysub",\n "polymulx",\n "polymul",\n "polydiv",\n "polypow",\n "polyval",\n "polyvalfromroots",\n "polyder",\n "polyint",\n "polyfromroots",\n "polyvander",\n "polyfit",\n "polytrim",\n "polyroots",\n "Polynomial",\n "polyval2d",\n "polyval3d",\n "polygrid2d",\n "polygrid3d",\n "polyvander2d",\n "polyvander3d",\n "polycompanion",\n]\n\npolydomain: Final[_Array2[np.float64]]\npolyzero: Final[_Array1[np.int_]]\npolyone: Final[_Array1[np.int_]]\npolyx: Final[_Array2[np.int_]]\n\npolyline: _FuncLine[L["Polyline"]]\npolyfromroots: _FuncFromRoots[L["polyfromroots"]]\npolyadd: _FuncBinOp[L["polyadd"]]\npolysub: _FuncBinOp[L["polysub"]]\npolymulx: _FuncUnOp[L["polymulx"]]\npolymul: _FuncBinOp[L["polymul"]]\npolydiv: _FuncBinOp[L["polydiv"]]\npolypow: _FuncPow[L["polypow"]]\npolyder: _FuncDer[L["polyder"]]\npolyint: _FuncInteg[L["polyint"]]\npolyval: _FuncVal[L["polyval"]]\npolyval2d: _FuncVal2D[L["polyval2d"]]\npolyval3d: _FuncVal3D[L["polyval3d"]]\npolyvalfromroots: _FuncValFromRoots[L["polyvalfromroots"]]\npolygrid2d: _FuncVal2D[L["polygrid2d"]]\npolygrid3d: _FuncVal3D[L["polygrid3d"]]\npolyvander: _FuncVander[L["polyvander"]]\npolyvander2d: _FuncVander2D[L["polyvander2d"]]\npolyvander3d: _FuncVander3D[L["polyvander3d"]]\npolyfit: _FuncFit[L["polyfit"]]\npolycompanion: _FuncCompanion[L["polycompanion"]]\npolyroots: _FuncRoots[L["polyroots"]]\n\nclass Polynomial(ABCPolyBase[None]): ...\n | .venv\Lib\site-packages\numpy\polynomial\polynomial.pyi | polynomial.pyi | Other | 2,110 | 0.85 | 0.011236 | 0 | node-utils | 467 | 2025-01-04T20:49:08.232589 | MIT | false | 59eb8b18529fd22a1b076942d4667f7e |
"""\nUtility classes and functions for the polynomial modules.\n\nThis module provides: error and warning objects; a polynomial base class;\nand some routines used in both the `polynomial` and `chebyshev` modules.\n\nFunctions\n---------\n\n.. autosummary::\n :toctree: generated/\n\n as_series convert list of array_likes into 1-D arrays of common type.\n trimseq remove trailing zeros.\n trimcoef remove small trailing coefficients.\n getdomain return the domain appropriate for a given set of abscissae.\n mapdomain maps points between domains.\n mapparms parameters of the linear map between domains.\n\n"""\nimport functools\nimport operator\nimport warnings\n\nimport numpy as np\nfrom numpy._core.multiarray import dragon4_positional, dragon4_scientific\nfrom numpy.exceptions import RankWarning\n\n__all__ = [\n 'as_series', 'trimseq', 'trimcoef', 'getdomain', 'mapdomain', 'mapparms',\n 'format_float']\n\n#\n# Helper functions to convert inputs to 1-D arrays\n#\ndef trimseq(seq):\n """Remove small Poly series coefficients.\n\n Parameters\n ----------\n seq : sequence\n Sequence of Poly series coefficients.\n\n Returns\n -------\n series : sequence\n Subsequence with trailing zeros removed. If the resulting sequence\n would be empty, return the first element. The returned sequence may\n or may not be a view.\n\n Notes\n -----\n Do not lose the type info if the sequence contains unknown objects.\n\n """\n if len(seq) == 0 or seq[-1] != 0:\n return seq\n else:\n for i in range(len(seq) - 1, -1, -1):\n if seq[i] != 0:\n break\n return seq[:i + 1]\n\n\ndef as_series(alist, trim=True):\n """\n Return argument as a list of 1-d arrays.\n\n The returned list contains array(s) of dtype double, complex double, or\n object. A 1-d argument of shape ``(N,)`` is parsed into ``N`` arrays of\n size one; a 2-d argument of shape ``(M,N)`` is parsed into ``M`` arrays\n of size ``N`` (i.e., is "parsed by row"); and a higher dimensional array\n raises a Value Error if it is not first reshaped into either a 1-d or 2-d\n array.\n\n Parameters\n ----------\n alist : array_like\n A 1- or 2-d array_like\n trim : boolean, optional\n When True, trailing zeros are removed from the inputs.\n When False, the inputs are passed through intact.\n\n Returns\n -------\n [a1, a2,...] : list of 1-D arrays\n A copy of the input data as a list of 1-d arrays.\n\n Raises\n ------\n ValueError\n Raised when `as_series` cannot convert its input to 1-d arrays, or at\n least one of the resulting arrays is empty.\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial import polyutils as pu\n >>> a = np.arange(4)\n >>> pu.as_series(a)\n [array([0.]), array([1.]), array([2.]), array([3.])]\n >>> b = np.arange(6).reshape((2,3))\n >>> pu.as_series(b)\n [array([0., 1., 2.]), array([3., 4., 5.])]\n\n >>> pu.as_series((1, np.arange(3), np.arange(2, dtype=np.float16)))\n [array([1.]), array([0., 1., 2.]), array([0., 1.])]\n\n >>> pu.as_series([2, [1.1, 0.]])\n [array([2.]), array([1.1])]\n\n >>> pu.as_series([2, [1.1, 0.]], trim=False)\n [array([2.]), array([1.1, 0. ])]\n\n """\n arrays = [np.array(a, ndmin=1, copy=None) for a in alist]\n for a in arrays:\n if a.size == 0:\n raise ValueError("Coefficient array is empty")\n if a.ndim != 1:\n raise ValueError("Coefficient array is not 1-d")\n if trim:\n arrays = [trimseq(a) for a in arrays]\n\n try:\n dtype = np.common_type(*arrays)\n except Exception as e:\n object_dtype = np.dtypes.ObjectDType()\n has_one_object_type = False\n ret = []\n for a in arrays:\n if a.dtype != object_dtype:\n tmp = np.empty(len(a), dtype=object_dtype)\n tmp[:] = a[:]\n ret.append(tmp)\n else:\n has_one_object_type = True\n ret.append(a.copy())\n if not has_one_object_type:\n raise ValueError("Coefficient arrays have no common type") from e\n else:\n ret = [np.array(a, copy=True, dtype=dtype) for a in arrays]\n return ret\n\n\ndef trimcoef(c, tol=0):\n """\n Remove "small" "trailing" coefficients from a polynomial.\n\n "Small" means "small in absolute value" and is controlled by the\n parameter `tol`; "trailing" means highest order coefficient(s), e.g., in\n ``[0, 1, 1, 0, 0]`` (which represents ``0 + x + x**2 + 0*x**3 + 0*x**4``)\n both the 3-rd and 4-th order coefficients would be "trimmed."\n\n Parameters\n ----------\n c : array_like\n 1-d array of coefficients, ordered from lowest order to highest.\n tol : number, optional\n Trailing (i.e., highest order) elements with absolute value less\n than or equal to `tol` (default value is zero) are removed.\n\n Returns\n -------\n trimmed : ndarray\n 1-d array with trailing zeros removed. If the resulting series\n would be empty, a series containing a single zero is returned.\n\n Raises\n ------\n ValueError\n If `tol` < 0\n\n Examples\n --------\n >>> from numpy.polynomial import polyutils as pu\n >>> pu.trimcoef((0,0,3,0,5,0,0))\n array([0., 0., 3., 0., 5.])\n >>> pu.trimcoef((0,0,1e-3,0,1e-5,0,0),1e-3) # item == tol is trimmed\n array([0.])\n >>> i = complex(0,1) # works for complex\n >>> pu.trimcoef((3e-4,1e-3*(1-i),5e-4,2e-5*(1+i)), 1e-3)\n array([0.0003+0.j , 0.001 -0.001j])\n\n """\n if tol < 0:\n raise ValueError("tol must be non-negative")\n\n [c] = as_series([c])\n [ind] = np.nonzero(np.abs(c) > tol)\n if len(ind) == 0:\n return c[:1] * 0\n else:\n return c[:ind[-1] + 1].copy()\n\ndef getdomain(x):\n """\n Return a domain suitable for given abscissae.\n\n Find a domain suitable for a polynomial or Chebyshev series\n defined at the values supplied.\n\n Parameters\n ----------\n x : array_like\n 1-d array of abscissae whose domain will be determined.\n\n Returns\n -------\n domain : ndarray\n 1-d array containing two values. If the inputs are complex, then\n the two returned points are the lower left and upper right corners\n of the smallest rectangle (aligned with the axes) in the complex\n plane containing the points `x`. If the inputs are real, then the\n two points are the ends of the smallest interval containing the\n points `x`.\n\n See Also\n --------\n mapparms, mapdomain\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial import polyutils as pu\n >>> points = np.arange(4)**2 - 5; points\n array([-5, -4, -1, 4])\n >>> pu.getdomain(points)\n array([-5., 4.])\n >>> c = np.exp(complex(0,1)*np.pi*np.arange(12)/6) # unit circle\n >>> pu.getdomain(c)\n array([-1.-1.j, 1.+1.j])\n\n """\n [x] = as_series([x], trim=False)\n if x.dtype.char in np.typecodes['Complex']:\n rmin, rmax = x.real.min(), x.real.max()\n imin, imax = x.imag.min(), x.imag.max()\n return np.array((complex(rmin, imin), complex(rmax, imax)))\n else:\n return np.array((x.min(), x.max()))\n\ndef mapparms(old, new):\n """\n Linear map parameters between domains.\n\n Return the parameters of the linear map ``offset + scale*x`` that maps\n `old` to `new` such that ``old[i] -> new[i]``, ``i = 0, 1``.\n\n Parameters\n ----------\n old, new : array_like\n Domains. Each domain must (successfully) convert to a 1-d array\n containing precisely two values.\n\n Returns\n -------\n offset, scale : scalars\n The map ``L(x) = offset + scale*x`` maps the first domain to the\n second.\n\n See Also\n --------\n getdomain, mapdomain\n\n Notes\n -----\n Also works for complex numbers, and thus can be used to calculate the\n parameters required to map any line in the complex plane to any other\n line therein.\n\n Examples\n --------\n >>> from numpy.polynomial import polyutils as pu\n >>> pu.mapparms((-1,1),(-1,1))\n (0.0, 1.0)\n >>> pu.mapparms((1,-1),(-1,1))\n (-0.0, -1.0)\n >>> i = complex(0,1)\n >>> pu.mapparms((-i,-1),(1,i))\n ((1+1j), (1-0j))\n\n """\n oldlen = old[1] - old[0]\n newlen = new[1] - new[0]\n off = (old[1] * new[0] - old[0] * new[1]) / oldlen\n scl = newlen / oldlen\n return off, scl\n\ndef mapdomain(x, old, new):\n """\n Apply linear map to input points.\n\n The linear map ``offset + scale*x`` that maps the domain `old` to\n the domain `new` is applied to the points `x`.\n\n Parameters\n ----------\n x : array_like\n Points to be mapped. If `x` is a subtype of ndarray the subtype\n will be preserved.\n old, new : array_like\n The two domains that determine the map. Each must (successfully)\n convert to 1-d arrays containing precisely two values.\n\n Returns\n -------\n x_out : ndarray\n Array of points of the same shape as `x`, after application of the\n linear map between the two domains.\n\n See Also\n --------\n getdomain, mapparms\n\n Notes\n -----\n Effectively, this implements:\n\n .. math::\n x\\_out = new[0] + m(x - old[0])\n\n where\n\n .. math::\n m = \\frac{new[1]-new[0]}{old[1]-old[0]}\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.polynomial import polyutils as pu\n >>> old_domain = (-1,1)\n >>> new_domain = (0,2*np.pi)\n >>> x = np.linspace(-1,1,6); x\n array([-1. , -0.6, -0.2, 0.2, 0.6, 1. ])\n >>> x_out = pu.mapdomain(x, old_domain, new_domain); x_out\n array([ 0. , 1.25663706, 2.51327412, 3.76991118, 5.02654825, # may vary\n 6.28318531])\n >>> x - pu.mapdomain(x_out, new_domain, old_domain)\n array([0., 0., 0., 0., 0., 0.])\n\n Also works for complex numbers (and thus can be used to map any line in\n the complex plane to any other line therein).\n\n >>> i = complex(0,1)\n >>> old = (-1 - i, 1 + i)\n >>> new = (-1 + i, 1 - i)\n >>> z = np.linspace(old[0], old[1], 6); z\n array([-1. -1.j , -0.6-0.6j, -0.2-0.2j, 0.2+0.2j, 0.6+0.6j, 1. +1.j ])\n >>> new_z = pu.mapdomain(z, old, new); new_z\n array([-1.0+1.j , -0.6+0.6j, -0.2+0.2j, 0.2-0.2j, 0.6-0.6j, 1.0-1.j ]) # may vary\n\n """\n if type(x) not in (int, float, complex) and not isinstance(x, np.generic):\n x = np.asanyarray(x)\n off, scl = mapparms(old, new)\n return off + scl * x\n\n\ndef _nth_slice(i, ndim):\n sl = [np.newaxis] * ndim\n sl[i] = slice(None)\n return tuple(sl)\n\n\ndef _vander_nd(vander_fs, points, degrees):\n r"""\n A generalization of the Vandermonde matrix for N dimensions\n\n The result is built by combining the results of 1d Vandermonde matrices,\n\n .. math::\n W[i_0, \ldots, i_M, j_0, \ldots, j_N] = \prod_{k=0}^N{V_k(x_k)[i_0, \ldots, i_M, j_k]}\n\n where\n\n .. math::\n N &= \texttt{len(points)} = \texttt{len(degrees)} = \texttt{len(vander\_fs)} \\\n M &= \texttt{points[k].ndim} \\\n V_k &= \texttt{vander\_fs[k]} \\\n x_k &= \texttt{points[k]} \\\n 0 \le j_k &\le \texttt{degrees[k]}\n\n Expanding the one-dimensional :math:`V_k` functions gives:\n\n .. math::\n W[i_0, \ldots, i_M, j_0, \ldots, j_N] = \prod_{k=0}^N{B_{k, j_k}(x_k[i_0, \ldots, i_M])}\n\n where :math:`B_{k,m}` is the m'th basis of the polynomial construction used along\n dimension :math:`k`. For a regular polynomial, :math:`B_{k, m}(x) = P_m(x) = x^m`.\n\n Parameters\n ----------\n vander_fs : Sequence[function(array_like, int) -> ndarray]\n The 1d vander function to use for each axis, such as ``polyvander``\n points : Sequence[array_like]\n Arrays of point coordinates, all of the same shape. The dtypes\n will be converted to either float64 or complex128 depending on\n whether any of the elements are complex. Scalars are converted to\n 1-D arrays.\n This must be the same length as `vander_fs`.\n degrees : Sequence[int]\n The maximum degree (inclusive) to use for each axis.\n This must be the same length as `vander_fs`.\n\n Returns\n -------\n vander_nd : ndarray\n An array of shape ``points[0].shape + tuple(d + 1 for d in degrees)``.\n """ # noqa: E501\n n_dims = len(vander_fs)\n if n_dims != len(points):\n raise ValueError(\n f"Expected {n_dims} dimensions of sample points, got {len(points)}")\n if n_dims != len(degrees):\n raise ValueError(\n f"Expected {n_dims} dimensions of degrees, got {len(degrees)}")\n if n_dims == 0:\n raise ValueError("Unable to guess a dtype or shape when no points are given")\n\n # convert to the same shape and type\n points = tuple(np.asarray(tuple(points)) + 0.0)\n\n # produce the vandermonde matrix for each dimension, placing the last\n # axis of each in an independent trailing axis of the output\n vander_arrays = (\n vander_fs[i](points[i], degrees[i])[(...,) + _nth_slice(i, n_dims)]\n for i in range(n_dims)\n )\n\n # we checked this wasn't empty already, so no `initial` needed\n return functools.reduce(operator.mul, vander_arrays)\n\n\ndef _vander_nd_flat(vander_fs, points, degrees):\n """\n Like `_vander_nd`, but flattens the last ``len(degrees)`` axes into a single axis\n\n Used to implement the public ``<type>vander<n>d`` functions.\n """\n v = _vander_nd(vander_fs, points, degrees)\n return v.reshape(v.shape[:-len(degrees)] + (-1,))\n\n\ndef _fromroots(line_f, mul_f, roots):\n """\n Helper function used to implement the ``<type>fromroots`` functions.\n\n Parameters\n ----------\n line_f : function(float, float) -> ndarray\n The ``<type>line`` function, such as ``polyline``\n mul_f : function(array_like, array_like) -> ndarray\n The ``<type>mul`` function, such as ``polymul``\n roots\n See the ``<type>fromroots`` functions for more detail\n """\n if len(roots) == 0:\n return np.ones(1)\n else:\n [roots] = as_series([roots], trim=False)\n roots.sort()\n p = [line_f(-r, 1) for r in roots]\n n = len(p)\n while n > 1:\n m, r = divmod(n, 2)\n tmp = [mul_f(p[i], p[i + m]) for i in range(m)]\n if r:\n tmp[0] = mul_f(tmp[0], p[-1])\n p = tmp\n n = m\n return p[0]\n\n\ndef _valnd(val_f, c, *args):\n """\n Helper function used to implement the ``<type>val<n>d`` functions.\n\n Parameters\n ----------\n val_f : function(array_like, array_like, tensor: bool) -> array_like\n The ``<type>val`` function, such as ``polyval``\n c, args\n See the ``<type>val<n>d`` functions for more detail\n """\n args = [np.asanyarray(a) for a in args]\n shape0 = args[0].shape\n if not all(a.shape == shape0 for a in args[1:]):\n if len(args) == 3:\n raise ValueError('x, y, z are incompatible')\n elif len(args) == 2:\n raise ValueError('x, y are incompatible')\n else:\n raise ValueError('ordinates are incompatible')\n it = iter(args)\n x0 = next(it)\n\n # use tensor on only the first\n c = val_f(x0, c)\n for xi in it:\n c = val_f(xi, c, tensor=False)\n return c\n\n\ndef _gridnd(val_f, c, *args):\n """\n Helper function used to implement the ``<type>grid<n>d`` functions.\n\n Parameters\n ----------\n val_f : function(array_like, array_like, tensor: bool) -> array_like\n The ``<type>val`` function, such as ``polyval``\n c, args\n See the ``<type>grid<n>d`` functions for more detail\n """\n for xi in args:\n c = val_f(xi, c)\n return c\n\n\ndef _div(mul_f, c1, c2):\n """\n Helper function used to implement the ``<type>div`` functions.\n\n Implementation uses repeated subtraction of c2 multiplied by the nth basis.\n For some polynomial types, a more efficient approach may be possible.\n\n Parameters\n ----------\n mul_f : function(array_like, array_like) -> array_like\n The ``<type>mul`` function, such as ``polymul``\n c1, c2\n See the ``<type>div`` functions for more detail\n """\n # c1, c2 are trimmed copies\n [c1, c2] = as_series([c1, c2])\n if c2[-1] == 0:\n raise ZeroDivisionError # FIXME: add message with details to exception\n\n lc1 = len(c1)\n lc2 = len(c2)\n if lc1 < lc2:\n return c1[:1] * 0, c1\n elif lc2 == 1:\n return c1 / c2[-1], c1[:1] * 0\n else:\n quo = np.empty(lc1 - lc2 + 1, dtype=c1.dtype)\n rem = c1\n for i in range(lc1 - lc2, - 1, -1):\n p = mul_f([0] * i + [1], c2)\n q = rem[-1] / p[-1]\n rem = rem[:-1] - q * p[:-1]\n quo[i] = q\n return quo, trimseq(rem)\n\n\ndef _add(c1, c2):\n """ Helper function used to implement the ``<type>add`` functions. """\n # c1, c2 are trimmed copies\n [c1, c2] = as_series([c1, c2])\n if len(c1) > len(c2):\n c1[:c2.size] += c2\n ret = c1\n else:\n c2[:c1.size] += c1\n ret = c2\n return trimseq(ret)\n\n\ndef _sub(c1, c2):\n """ Helper function used to implement the ``<type>sub`` functions. """\n # c1, c2 are trimmed copies\n [c1, c2] = as_series([c1, c2])\n if len(c1) > len(c2):\n c1[:c2.size] -= c2\n ret = c1\n else:\n c2 = -c2\n c2[:c1.size] += c1\n ret = c2\n return trimseq(ret)\n\n\ndef _fit(vander_f, x, y, deg, rcond=None, full=False, w=None):\n """\n Helper function used to implement the ``<type>fit`` functions.\n\n Parameters\n ----------\n vander_f : function(array_like, int) -> ndarray\n The 1d vander function, such as ``polyvander``\n c1, c2\n See the ``<type>fit`` functions for more detail\n """\n x = np.asarray(x) + 0.0\n y = np.asarray(y) + 0.0\n deg = np.asarray(deg)\n\n # check arguments.\n if deg.ndim > 1 or deg.dtype.kind not in 'iu' or deg.size == 0:\n raise TypeError("deg must be an int or non-empty 1-D array of int")\n if deg.min() < 0:\n raise ValueError("expected deg >= 0")\n if x.ndim != 1:\n raise TypeError("expected 1D vector for x")\n if x.size == 0:\n raise TypeError("expected non-empty vector for x")\n if y.ndim < 1 or y.ndim > 2:\n raise TypeError("expected 1D or 2D array for y")\n if len(x) != len(y):\n raise TypeError("expected x and y to have same length")\n\n if deg.ndim == 0:\n lmax = deg\n order = lmax + 1\n van = vander_f(x, lmax)\n else:\n deg = np.sort(deg)\n lmax = deg[-1]\n order = len(deg)\n van = vander_f(x, lmax)[:, deg]\n\n # set up the least squares matrices in transposed form\n lhs = van.T\n rhs = y.T\n if w is not None:\n w = np.asarray(w) + 0.0\n if w.ndim != 1:\n raise TypeError("expected 1D vector for w")\n if len(x) != len(w):\n raise TypeError("expected x and w to have same length")\n # apply weights. Don't use inplace operations as they\n # can cause problems with NA.\n lhs = lhs * w\n rhs = rhs * w\n\n # set rcond\n if rcond is None:\n rcond = len(x) * np.finfo(x.dtype).eps\n\n # Determine the norms of the design matrix columns.\n if issubclass(lhs.dtype.type, np.complexfloating):\n scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1))\n else:\n scl = np.sqrt(np.square(lhs).sum(1))\n scl[scl == 0] = 1\n\n # Solve the least squares problem.\n c, resids, rank, s = np.linalg.lstsq(lhs.T / scl, rhs.T, rcond)\n c = (c.T / scl).T\n\n # Expand c to include non-fitted coefficients which are set to zero\n if deg.ndim > 0:\n if c.ndim == 2:\n cc = np.zeros((lmax + 1, c.shape[1]), dtype=c.dtype)\n else:\n cc = np.zeros(lmax + 1, dtype=c.dtype)\n cc[deg] = c\n c = cc\n\n # warn on rank reduction\n if rank != order and not full:\n msg = "The fit may be poorly conditioned"\n warnings.warn(msg, RankWarning, stacklevel=2)\n\n if full:\n return c, [resids, rank, s, rcond]\n else:\n return c\n\n\ndef _pow(mul_f, c, pow, maxpower):\n """\n Helper function used to implement the ``<type>pow`` functions.\n\n Parameters\n ----------\n mul_f : function(array_like, array_like) -> ndarray\n The ``<type>mul`` function, such as ``polymul``\n c : array_like\n 1-D array of array of series coefficients\n pow, maxpower\n See the ``<type>pow`` functions for more detail\n """\n # c is a trimmed copy\n [c] = as_series([c])\n power = int(pow)\n if power != pow or power < 0:\n raise ValueError("Power must be a non-negative integer.")\n elif maxpower is not None and power > maxpower:\n raise ValueError("Power is too large")\n elif power == 0:\n return np.array([1], dtype=c.dtype)\n elif power == 1:\n return c\n else:\n # This can be made more efficient by using powers of two\n # in the usual way.\n prd = c\n for i in range(2, power + 1):\n prd = mul_f(prd, c)\n return prd\n\n\ndef _as_int(x, desc):\n """\n Like `operator.index`, but emits a custom exception when passed an\n incorrect type\n\n Parameters\n ----------\n x : int-like\n Value to interpret as an integer\n desc : str\n description to include in any error message\n\n Raises\n ------\n TypeError : if x is a float or non-numeric\n """\n try:\n return operator.index(x)\n except TypeError as e:\n raise TypeError(f"{desc} must be an integer, received {x}") from e\n\n\ndef format_float(x, parens=False):\n if not np.issubdtype(type(x), np.floating):\n return str(x)\n\n opts = np.get_printoptions()\n\n if np.isnan(x):\n return opts['nanstr']\n elif np.isinf(x):\n return opts['infstr']\n\n exp_format = False\n if x != 0:\n a = np.abs(x)\n if a >= 1.e8 or a < 10**min(0, -(opts['precision'] - 1) // 2):\n exp_format = True\n\n trim, unique = '0', True\n if opts['floatmode'] == 'fixed':\n trim, unique = 'k', False\n\n if exp_format:\n s = dragon4_scientific(x, precision=opts['precision'],\n unique=unique, trim=trim,\n sign=opts['sign'] == '+')\n if parens:\n s = '(' + s + ')'\n else:\n s = dragon4_positional(x, precision=opts['precision'],\n fractional=True,\n unique=unique, trim=trim,\n sign=opts['sign'] == '+')\n return s\n | .venv\Lib\site-packages\numpy\polynomial\polyutils.py | polyutils.py | Python | 23,416 | 0.95 | 0.175231 | 0.036278 | python-kit | 721 | 2024-02-20T04:31:09.841171 | GPL-3.0 | false | bcd8df9b71846bb21117212f4d2e4b1d |
from collections.abc import Callable, Iterable, Sequence\nfrom typing import (\n Final,\n Literal,\n SupportsIndex,\n TypeAlias,\n TypeVar,\n overload,\n)\n\nimport numpy as np\nimport numpy.typing as npt\nfrom numpy._typing import (\n _ArrayLikeComplex_co,\n _ArrayLikeFloat_co,\n _FloatLike_co,\n _NumberLike_co,\n)\n\nfrom ._polytypes import (\n _AnyInt,\n _Array2,\n _ArrayLikeCoef_co,\n _CoefArray,\n _CoefLike_co,\n _CoefSeries,\n _ComplexArray,\n _ComplexSeries,\n _FloatArray,\n _FloatSeries,\n _FuncBinOp,\n _FuncValND,\n _FuncVanderND,\n _ObjectArray,\n _ObjectSeries,\n _SeriesLikeCoef_co,\n _SeriesLikeComplex_co,\n _SeriesLikeFloat_co,\n _SeriesLikeInt_co,\n _Tuple2,\n)\n\n__all__: Final[Sequence[str]] = [\n "as_series",\n "format_float",\n "getdomain",\n "mapdomain",\n "mapparms",\n "trimcoef",\n "trimseq",\n]\n\n_AnyLineF: TypeAlias = Callable[\n [_CoefLike_co, _CoefLike_co],\n _CoefArray,\n]\n_AnyMulF: TypeAlias = Callable[\n [npt.ArrayLike, npt.ArrayLike],\n _CoefArray,\n]\n_AnyVanderF: TypeAlias = Callable[\n [npt.ArrayLike, SupportsIndex],\n _CoefArray,\n]\n\n@overload\ndef as_series(\n alist: npt.NDArray[np.integer] | _FloatArray,\n trim: bool = ...,\n) -> list[_FloatSeries]: ...\n@overload\ndef as_series(\n alist: _ComplexArray,\n trim: bool = ...,\n) -> list[_ComplexSeries]: ...\n@overload\ndef as_series(\n alist: _ObjectArray,\n trim: bool = ...,\n) -> list[_ObjectSeries]: ...\n@overload\ndef as_series( # type: ignore[overload-overlap]\n alist: Iterable[_FloatArray | npt.NDArray[np.integer]],\n trim: bool = ...,\n) -> list[_FloatSeries]: ...\n@overload\ndef as_series(\n alist: Iterable[_ComplexArray],\n trim: bool = ...,\n) -> list[_ComplexSeries]: ...\n@overload\ndef as_series(\n alist: Iterable[_ObjectArray],\n trim: bool = ...,\n) -> list[_ObjectSeries]: ...\n@overload\ndef as_series( # type: ignore[overload-overlap]\n alist: Iterable[_SeriesLikeFloat_co | float],\n trim: bool = ...,\n) -> list[_FloatSeries]: ...\n@overload\ndef as_series(\n alist: Iterable[_SeriesLikeComplex_co | complex],\n trim: bool = ...,\n) -> list[_ComplexSeries]: ...\n@overload\ndef as_series(\n alist: Iterable[_SeriesLikeCoef_co | object],\n trim: bool = ...,\n) -> list[_ObjectSeries]: ...\n\n_T_seq = TypeVar("_T_seq", bound=_CoefArray | Sequence[_CoefLike_co])\ndef trimseq(seq: _T_seq) -> _T_seq: ...\n\n@overload\ndef trimcoef( # type: ignore[overload-overlap]\n c: npt.NDArray[np.integer] | _FloatArray,\n tol: _FloatLike_co = ...,\n) -> _FloatSeries: ...\n@overload\ndef trimcoef(\n c: _ComplexArray,\n tol: _FloatLike_co = ...,\n) -> _ComplexSeries: ...\n@overload\ndef trimcoef(\n c: _ObjectArray,\n tol: _FloatLike_co = ...,\n) -> _ObjectSeries: ...\n@overload\ndef trimcoef( # type: ignore[overload-overlap]\n c: _SeriesLikeFloat_co | float,\n tol: _FloatLike_co = ...,\n) -> _FloatSeries: ...\n@overload\ndef trimcoef(\n c: _SeriesLikeComplex_co | complex,\n tol: _FloatLike_co = ...,\n) -> _ComplexSeries: ...\n@overload\ndef trimcoef(\n c: _SeriesLikeCoef_co | object,\n tol: _FloatLike_co = ...,\n) -> _ObjectSeries: ...\n\n@overload\ndef getdomain( # type: ignore[overload-overlap]\n x: _FloatArray | npt.NDArray[np.integer],\n) -> _Array2[np.float64]: ...\n@overload\ndef getdomain(\n x: _ComplexArray,\n) -> _Array2[np.complex128]: ...\n@overload\ndef getdomain(\n x: _ObjectArray,\n) -> _Array2[np.object_]: ...\n@overload\ndef getdomain( # type: ignore[overload-overlap]\n x: _SeriesLikeFloat_co | float,\n) -> _Array2[np.float64]: ...\n@overload\ndef getdomain(\n x: _SeriesLikeComplex_co | complex,\n) -> _Array2[np.complex128]: ...\n@overload\ndef getdomain(\n x: _SeriesLikeCoef_co | object,\n) -> _Array2[np.object_]: ...\n\n@overload\ndef mapparms( # type: ignore[overload-overlap]\n old: npt.NDArray[np.floating | np.integer],\n new: npt.NDArray[np.floating | np.integer],\n) -> _Tuple2[np.floating]: ...\n@overload\ndef mapparms(\n old: npt.NDArray[np.number],\n new: npt.NDArray[np.number],\n) -> _Tuple2[np.complexfloating]: ...\n@overload\ndef mapparms(\n old: npt.NDArray[np.object_ | np.number],\n new: npt.NDArray[np.object_ | np.number],\n) -> _Tuple2[object]: ...\n@overload\ndef mapparms( # type: ignore[overload-overlap]\n old: Sequence[float],\n new: Sequence[float],\n) -> _Tuple2[float]: ...\n@overload\ndef mapparms(\n old: Sequence[complex],\n new: Sequence[complex],\n) -> _Tuple2[complex]: ...\n@overload\ndef mapparms(\n old: _SeriesLikeFloat_co,\n new: _SeriesLikeFloat_co,\n) -> _Tuple2[np.floating]: ...\n@overload\ndef mapparms(\n old: _SeriesLikeComplex_co,\n new: _SeriesLikeComplex_co,\n) -> _Tuple2[np.complexfloating]: ...\n@overload\ndef mapparms(\n old: _SeriesLikeCoef_co,\n new: _SeriesLikeCoef_co,\n) -> _Tuple2[object]: ...\n\n@overload\ndef mapdomain( # type: ignore[overload-overlap]\n x: _FloatLike_co,\n old: _SeriesLikeFloat_co,\n new: _SeriesLikeFloat_co,\n) -> np.floating: ...\n@overload\ndef mapdomain(\n x: _NumberLike_co,\n old: _SeriesLikeComplex_co,\n new: _SeriesLikeComplex_co,\n) -> np.complexfloating: ...\n@overload\ndef mapdomain( # type: ignore[overload-overlap]\n x: npt.NDArray[np.floating | np.integer],\n old: npt.NDArray[np.floating | np.integer],\n new: npt.NDArray[np.floating | np.integer],\n) -> _FloatSeries: ...\n@overload\ndef mapdomain(\n x: npt.NDArray[np.number],\n old: npt.NDArray[np.number],\n new: npt.NDArray[np.number],\n) -> _ComplexSeries: ...\n@overload\ndef mapdomain(\n x: npt.NDArray[np.object_ | np.number],\n old: npt.NDArray[np.object_ | np.number],\n new: npt.NDArray[np.object_ | np.number],\n) -> _ObjectSeries: ...\n@overload\ndef mapdomain( # type: ignore[overload-overlap]\n x: _SeriesLikeFloat_co,\n old: _SeriesLikeFloat_co,\n new: _SeriesLikeFloat_co,\n) -> _FloatSeries: ...\n@overload\ndef mapdomain(\n x: _SeriesLikeComplex_co,\n old: _SeriesLikeComplex_co,\n new: _SeriesLikeComplex_co,\n) -> _ComplexSeries: ...\n@overload\ndef mapdomain(\n x: _SeriesLikeCoef_co,\n old: _SeriesLikeCoef_co,\n new: _SeriesLikeCoef_co,\n) -> _ObjectSeries: ...\n@overload\ndef mapdomain(\n x: _CoefLike_co,\n old: _SeriesLikeCoef_co,\n new: _SeriesLikeCoef_co,\n) -> object: ...\n\ndef _nth_slice(\n i: SupportsIndex,\n ndim: SupportsIndex,\n) -> tuple[slice | None, ...]: ...\n\n_vander_nd: _FuncVanderND[Literal["_vander_nd"]]\n_vander_nd_flat: _FuncVanderND[Literal["_vander_nd_flat"]]\n\n# keep in sync with `._polytypes._FuncFromRoots`\n@overload\ndef _fromroots( # type: ignore[overload-overlap]\n line_f: _AnyLineF,\n mul_f: _AnyMulF,\n roots: _SeriesLikeFloat_co,\n) -> _FloatSeries: ...\n@overload\ndef _fromroots(\n line_f: _AnyLineF,\n mul_f: _AnyMulF,\n roots: _SeriesLikeComplex_co,\n) -> _ComplexSeries: ...\n@overload\ndef _fromroots(\n line_f: _AnyLineF,\n mul_f: _AnyMulF,\n roots: _SeriesLikeCoef_co,\n) -> _ObjectSeries: ...\n@overload\ndef _fromroots(\n line_f: _AnyLineF,\n mul_f: _AnyMulF,\n roots: _SeriesLikeCoef_co,\n) -> _CoefSeries: ...\n\n_valnd: _FuncValND[Literal["_valnd"]]\n_gridnd: _FuncValND[Literal["_gridnd"]]\n\n# keep in sync with `_polytypes._FuncBinOp`\n@overload\ndef _div( # type: ignore[overload-overlap]\n mul_f: _AnyMulF,\n c1: _SeriesLikeFloat_co,\n c2: _SeriesLikeFloat_co,\n) -> _Tuple2[_FloatSeries]: ...\n@overload\ndef _div(\n mul_f: _AnyMulF,\n c1: _SeriesLikeComplex_co,\n c2: _SeriesLikeComplex_co,\n) -> _Tuple2[_ComplexSeries]: ...\n@overload\ndef _div(\n mul_f: _AnyMulF,\n c1: _SeriesLikeCoef_co,\n c2: _SeriesLikeCoef_co,\n) -> _Tuple2[_ObjectSeries]: ...\n@overload\ndef _div(\n mul_f: _AnyMulF,\n c1: _SeriesLikeCoef_co,\n c2: _SeriesLikeCoef_co,\n) -> _Tuple2[_CoefSeries]: ...\n\n_add: Final[_FuncBinOp]\n_sub: Final[_FuncBinOp]\n\n# keep in sync with `_polytypes._FuncPow`\n@overload\ndef _pow( # type: ignore[overload-overlap]\n mul_f: _AnyMulF,\n c: _SeriesLikeFloat_co,\n pow: _AnyInt,\n maxpower: _AnyInt | None = ...,\n) -> _FloatSeries: ...\n@overload\ndef _pow(\n mul_f: _AnyMulF,\n c: _SeriesLikeComplex_co,\n pow: _AnyInt,\n maxpower: _AnyInt | None = ...,\n) -> _ComplexSeries: ...\n@overload\ndef _pow(\n mul_f: _AnyMulF,\n c: _SeriesLikeCoef_co,\n pow: _AnyInt,\n maxpower: _AnyInt | None = ...,\n) -> _ObjectSeries: ...\n@overload\ndef _pow(\n mul_f: _AnyMulF,\n c: _SeriesLikeCoef_co,\n pow: _AnyInt,\n maxpower: _AnyInt | None = ...,\n) -> _CoefSeries: ...\n\n# keep in sync with `_polytypes._FuncFit`\n@overload\ndef _fit( # type: ignore[overload-overlap]\n vander_f: _AnyVanderF,\n x: _SeriesLikeFloat_co,\n y: _ArrayLikeFloat_co,\n deg: _SeriesLikeInt_co,\n domain: _SeriesLikeFloat_co | None = ...,\n rcond: _FloatLike_co | None = ...,\n full: Literal[False] = ...,\n w: _SeriesLikeFloat_co | None = ...,\n) -> _FloatArray: ...\n@overload\ndef _fit(\n vander_f: _AnyVanderF,\n x: _SeriesLikeComplex_co,\n y: _ArrayLikeComplex_co,\n deg: _SeriesLikeInt_co,\n domain: _SeriesLikeComplex_co | None = ...,\n rcond: _FloatLike_co | None = ...,\n full: Literal[False] = ...,\n w: _SeriesLikeComplex_co | None = ...,\n) -> _ComplexArray: ...\n@overload\ndef _fit(\n vander_f: _AnyVanderF,\n x: _SeriesLikeCoef_co,\n y: _ArrayLikeCoef_co,\n deg: _SeriesLikeInt_co,\n domain: _SeriesLikeCoef_co | None = ...,\n rcond: _FloatLike_co | None = ...,\n full: Literal[False] = ...,\n w: _SeriesLikeCoef_co | None = ...,\n) -> _CoefArray: ...\n@overload\ndef _fit(\n vander_f: _AnyVanderF,\n x: _SeriesLikeCoef_co,\n y: _SeriesLikeCoef_co,\n deg: _SeriesLikeInt_co,\n domain: _SeriesLikeCoef_co | None,\n rcond: _FloatLike_co | None,\n full: Literal[True],\n /,\n w: _SeriesLikeCoef_co | None = ...,\n) -> tuple[_CoefSeries, Sequence[np.inexact | np.int32]]: ...\n@overload\ndef _fit(\n vander_f: _AnyVanderF,\n x: _SeriesLikeCoef_co,\n y: _SeriesLikeCoef_co,\n deg: _SeriesLikeInt_co,\n domain: _SeriesLikeCoef_co | None = ...,\n rcond: _FloatLike_co | None = ...,\n *,\n full: Literal[True],\n w: _SeriesLikeCoef_co | None = ...,\n) -> tuple[_CoefSeries, Sequence[np.inexact | np.int32]]: ...\n\ndef _as_int(x: SupportsIndex, desc: str) -> int: ...\ndef format_float(x: _FloatLike_co, parens: bool = ...) -> str: ...\n | .venv\Lib\site-packages\numpy\polynomial\polyutils.pyi | polyutils.pyi | Other | 10,658 | 0.95 | 0.13948 | 0.012376 | node-utils | 700 | 2025-04-16T04:24:25.921200 | GPL-3.0 | false | fe6bdf224621db2498ec8daa751608c9 |
"""\nAbstract base class for the various polynomial Classes.\n\nThe ABCPolyBase class provides the methods needed to implement the common API\nfor the various polynomial classes. It operates as a mixin, but uses the\nabc module from the stdlib, hence it is only available for Python >= 2.6.\n\n"""\nimport abc\nimport numbers\nimport os\nfrom collections.abc import Callable\n\nimport numpy as np\n\nfrom . import polyutils as pu\n\n__all__ = ['ABCPolyBase']\n\nclass ABCPolyBase(abc.ABC):\n """An abstract base class for immutable series classes.\n\n ABCPolyBase provides the standard Python numerical methods\n '+', '-', '*', '//', '%', 'divmod', '**', and '()' along with the\n methods listed below.\n\n Parameters\n ----------\n coef : array_like\n Series coefficients in order of increasing degree, i.e.,\n ``(1, 2, 3)`` gives ``1*P_0(x) + 2*P_1(x) + 3*P_2(x)``, where\n ``P_i`` is the basis polynomials of degree ``i``.\n domain : (2,) array_like, optional\n Domain to use. The interval ``[domain[0], domain[1]]`` is mapped\n to the interval ``[window[0], window[1]]`` by shifting and scaling.\n The default value is the derived class domain.\n window : (2,) array_like, optional\n Window, see domain for its use. The default value is the\n derived class window.\n symbol : str, optional\n Symbol used to represent the independent variable in string\n representations of the polynomial expression, e.g. for printing.\n The symbol must be a valid Python identifier. Default value is 'x'.\n\n .. versionadded:: 1.24\n\n Attributes\n ----------\n coef : (N,) ndarray\n Series coefficients in order of increasing degree.\n domain : (2,) ndarray\n Domain that is mapped to window.\n window : (2,) ndarray\n Window that domain is mapped to.\n symbol : str\n Symbol representing the independent variable.\n\n Class Attributes\n ----------------\n maxpower : int\n Maximum power allowed, i.e., the largest number ``n`` such that\n ``p(x)**n`` is allowed. This is to limit runaway polynomial size.\n domain : (2,) ndarray\n Default domain of the class.\n window : (2,) ndarray\n Default window of the class.\n\n """\n\n # Not hashable\n __hash__ = None\n\n # Opt out of numpy ufuncs and Python ops with ndarray subclasses.\n __array_ufunc__ = None\n\n # Limit runaway size. T_n^m has degree n*m\n maxpower = 100\n\n # Unicode character mappings for improved __str__\n _superscript_mapping = str.maketrans({\n "0": "⁰",\n "1": "¹",\n "2": "²",\n "3": "³",\n "4": "⁴",\n "5": "⁵",\n "6": "⁶",\n "7": "⁷",\n "8": "⁸",\n "9": "⁹"\n })\n _subscript_mapping = str.maketrans({\n "0": "₀",\n "1": "₁",\n "2": "₂",\n "3": "₃",\n "4": "₄",\n "5": "₅",\n "6": "₆",\n "7": "₇",\n "8": "₈",\n "9": "₉"\n })\n # Some fonts don't support full unicode character ranges necessary for\n # the full set of superscripts and subscripts, including common/default\n # fonts in Windows shells/terminals. Therefore, default to ascii-only\n # printing on windows.\n _use_unicode = not os.name == 'nt'\n\n @property\n def symbol(self):\n return self._symbol\n\n @property\n @abc.abstractmethod\n def domain(self):\n pass\n\n @property\n @abc.abstractmethod\n def window(self):\n pass\n\n @property\n @abc.abstractmethod\n def basis_name(self):\n pass\n\n @staticmethod\n @abc.abstractmethod\n def _add(c1, c2):\n pass\n\n @staticmethod\n @abc.abstractmethod\n def _sub(c1, c2):\n pass\n\n @staticmethod\n @abc.abstractmethod\n def _mul(c1, c2):\n pass\n\n @staticmethod\n @abc.abstractmethod\n def _div(c1, c2):\n pass\n\n @staticmethod\n @abc.abstractmethod\n def _pow(c, pow, maxpower=None):\n pass\n\n @staticmethod\n @abc.abstractmethod\n def _val(x, c):\n pass\n\n @staticmethod\n @abc.abstractmethod\n def _int(c, m, k, lbnd, scl):\n pass\n\n @staticmethod\n @abc.abstractmethod\n def _der(c, m, scl):\n pass\n\n @staticmethod\n @abc.abstractmethod\n def _fit(x, y, deg, rcond, full):\n pass\n\n @staticmethod\n @abc.abstractmethod\n def _line(off, scl):\n pass\n\n @staticmethod\n @abc.abstractmethod\n def _roots(c):\n pass\n\n @staticmethod\n @abc.abstractmethod\n def _fromroots(r):\n pass\n\n def has_samecoef(self, other):\n """Check if coefficients match.\n\n Parameters\n ----------\n other : class instance\n The other class must have the ``coef`` attribute.\n\n Returns\n -------\n bool : boolean\n True if the coefficients are the same, False otherwise.\n\n """\n return (\n len(self.coef) == len(other.coef)\n and np.all(self.coef == other.coef)\n )\n\n def has_samedomain(self, other):\n """Check if domains match.\n\n Parameters\n ----------\n other : class instance\n The other class must have the ``domain`` attribute.\n\n Returns\n -------\n bool : boolean\n True if the domains are the same, False otherwise.\n\n """\n return np.all(self.domain == other.domain)\n\n def has_samewindow(self, other):\n """Check if windows match.\n\n Parameters\n ----------\n other : class instance\n The other class must have the ``window`` attribute.\n\n Returns\n -------\n bool : boolean\n True if the windows are the same, False otherwise.\n\n """\n return np.all(self.window == other.window)\n\n def has_sametype(self, other):\n """Check if types match.\n\n Parameters\n ----------\n other : object\n Class instance.\n\n Returns\n -------\n bool : boolean\n True if other is same class as self\n\n """\n return isinstance(other, self.__class__)\n\n def _get_coefficients(self, other):\n """Interpret other as polynomial coefficients.\n\n The `other` argument is checked to see if it is of the same\n class as self with identical domain and window. If so,\n return its coefficients, otherwise return `other`.\n\n Parameters\n ----------\n other : anything\n Object to be checked.\n\n Returns\n -------\n coef\n The coefficients of`other` if it is a compatible instance,\n of ABCPolyBase, otherwise `other`.\n\n Raises\n ------\n TypeError\n When `other` is an incompatible instance of ABCPolyBase.\n\n """\n if isinstance(other, ABCPolyBase):\n if not isinstance(other, self.__class__):\n raise TypeError("Polynomial types differ")\n elif not np.all(self.domain == other.domain):\n raise TypeError("Domains differ")\n elif not np.all(self.window == other.window):\n raise TypeError("Windows differ")\n elif self.symbol != other.symbol:\n raise ValueError("Polynomial symbols differ")\n return other.coef\n return other\n\n def __init__(self, coef, domain=None, window=None, symbol='x'):\n [coef] = pu.as_series([coef], trim=False)\n self.coef = coef\n\n if domain is not None:\n [domain] = pu.as_series([domain], trim=False)\n if len(domain) != 2:\n raise ValueError("Domain has wrong number of elements.")\n self.domain = domain\n\n if window is not None:\n [window] = pu.as_series([window], trim=False)\n if len(window) != 2:\n raise ValueError("Window has wrong number of elements.")\n self.window = window\n\n # Validation for symbol\n try:\n if not symbol.isidentifier():\n raise ValueError(\n "Symbol string must be a valid Python identifier"\n )\n # If a user passes in something other than a string, the above\n # results in an AttributeError. Catch this and raise a more\n # informative exception\n except AttributeError:\n raise TypeError("Symbol must be a non-empty string")\n\n self._symbol = symbol\n\n def __repr__(self):\n coef = repr(self.coef)[6:-1]\n domain = repr(self.domain)[6:-1]\n window = repr(self.window)[6:-1]\n name = self.__class__.__name__\n return (f"{name}({coef}, domain={domain}, window={window}, "\n f"symbol='{self.symbol}')")\n\n def __format__(self, fmt_str):\n if fmt_str == '':\n return self.__str__()\n if fmt_str not in ('ascii', 'unicode'):\n raise ValueError(\n f"Unsupported format string '{fmt_str}' passed to "\n f"{self.__class__}.__format__. Valid options are "\n f"'ascii' and 'unicode'"\n )\n if fmt_str == 'ascii':\n return self._generate_string(self._str_term_ascii)\n return self._generate_string(self._str_term_unicode)\n\n def __str__(self):\n if self._use_unicode:\n return self._generate_string(self._str_term_unicode)\n return self._generate_string(self._str_term_ascii)\n\n def _generate_string(self, term_method):\n """\n Generate the full string representation of the polynomial, using\n ``term_method`` to generate each polynomial term.\n """\n # Get configuration for line breaks\n linewidth = np.get_printoptions().get('linewidth', 75)\n if linewidth < 1:\n linewidth = 1\n out = pu.format_float(self.coef[0])\n\n off, scale = self.mapparms()\n\n scaled_symbol, needs_parens = self._format_term(pu.format_float,\n off, scale)\n if needs_parens:\n scaled_symbol = '(' + scaled_symbol + ')'\n\n for i, coef in enumerate(self.coef[1:]):\n out += " "\n power = str(i + 1)\n # Polynomial coefficient\n # The coefficient array can be an object array with elements that\n # will raise a TypeError with >= 0 (e.g. strings or Python\n # complex). In this case, represent the coefficient as-is.\n try:\n if coef >= 0:\n next_term = "+ " + pu.format_float(coef, parens=True)\n else:\n next_term = "- " + pu.format_float(-coef, parens=True)\n except TypeError:\n next_term = f"+ {coef}"\n # Polynomial term\n next_term += term_method(power, scaled_symbol)\n # Length of the current line with next term added\n line_len = len(out.split('\n')[-1]) + len(next_term)\n # If not the last term in the polynomial, it will be two\n # characters longer due to the +/- with the next term\n if i < len(self.coef[1:]) - 1:\n line_len += 2\n # Handle linebreaking\n if line_len >= linewidth:\n next_term = next_term.replace(" ", "\n", 1)\n out += next_term\n return out\n\n @classmethod\n def _str_term_unicode(cls, i, arg_str):\n """\n String representation of single polynomial term using unicode\n characters for superscripts and subscripts.\n """\n if cls.basis_name is None:\n raise NotImplementedError(\n "Subclasses must define either a basis_name, or override "\n "_str_term_unicode(cls, i, arg_str)"\n )\n return (f"·{cls.basis_name}{i.translate(cls._subscript_mapping)}"\n f"({arg_str})")\n\n @classmethod\n def _str_term_ascii(cls, i, arg_str):\n """\n String representation of a single polynomial term using ** and _ to\n represent superscripts and subscripts, respectively.\n """\n if cls.basis_name is None:\n raise NotImplementedError(\n "Subclasses must define either a basis_name, or override "\n "_str_term_ascii(cls, i, arg_str)"\n )\n return f" {cls.basis_name}_{i}({arg_str})"\n\n @classmethod\n def _repr_latex_term(cls, i, arg_str, needs_parens):\n if cls.basis_name is None:\n raise NotImplementedError(\n "Subclasses must define either a basis name, or override "\n "_repr_latex_term(i, arg_str, needs_parens)")\n # since we always add parens, we don't care if the expression needs them\n return f"{{{cls.basis_name}}}_{{{i}}}({arg_str})"\n\n @staticmethod\n def _repr_latex_scalar(x, parens=False):\n # TODO: we're stuck with disabling math formatting until we handle\n # exponents in this function\n return fr'\text{{{pu.format_float(x, parens=parens)}}}'\n\n def _format_term(self, scalar_format: Callable, off: float, scale: float):\n """ Format a single term in the expansion """\n if off == 0 and scale == 1:\n term = self.symbol\n needs_parens = False\n elif scale == 1:\n term = f"{scalar_format(off)} + {self.symbol}"\n needs_parens = True\n elif off == 0:\n term = f"{scalar_format(scale)}{self.symbol}"\n needs_parens = True\n else:\n term = (\n f"{scalar_format(off)} + "\n f"{scalar_format(scale)}{self.symbol}"\n )\n needs_parens = True\n return term, needs_parens\n\n def _repr_latex_(self):\n # get the scaled argument string to the basis functions\n off, scale = self.mapparms()\n term, needs_parens = self._format_term(self._repr_latex_scalar,\n off, scale)\n\n mute = r"\color{{LightGray}}{{{}}}".format\n\n parts = []\n for i, c in enumerate(self.coef):\n # prevent duplication of + and - signs\n if i == 0:\n coef_str = f"{self._repr_latex_scalar(c)}"\n elif not isinstance(c, numbers.Real):\n coef_str = f" + ({self._repr_latex_scalar(c)})"\n elif c >= 0:\n coef_str = f" + {self._repr_latex_scalar(c, parens=True)}"\n else:\n coef_str = f" - {self._repr_latex_scalar(-c, parens=True)}"\n\n # produce the string for the term\n term_str = self._repr_latex_term(i, term, needs_parens)\n if term_str == '1':\n part = coef_str\n else:\n part = rf"{coef_str}\,{term_str}"\n\n if c == 0:\n part = mute(part)\n\n parts.append(part)\n\n if parts:\n body = ''.join(parts)\n else:\n # in case somehow there are no coefficients at all\n body = '0'\n\n return rf"${self.symbol} \mapsto {body}$"\n\n # Pickle and copy\n\n def __getstate__(self):\n ret = self.__dict__.copy()\n ret['coef'] = self.coef.copy()\n ret['domain'] = self.domain.copy()\n ret['window'] = self.window.copy()\n ret['symbol'] = self.symbol\n return ret\n\n def __setstate__(self, dict):\n self.__dict__ = dict\n\n # Call\n\n def __call__(self, arg):\n arg = pu.mapdomain(arg, self.domain, self.window)\n return self._val(arg, self.coef)\n\n def __iter__(self):\n return iter(self.coef)\n\n def __len__(self):\n return len(self.coef)\n\n # Numeric properties.\n\n def __neg__(self):\n return self.__class__(\n -self.coef, self.domain, self.window, self.symbol\n )\n\n def __pos__(self):\n return self\n\n def __add__(self, other):\n othercoef = self._get_coefficients(other)\n try:\n coef = self._add(self.coef, othercoef)\n except Exception:\n return NotImplemented\n return self.__class__(coef, self.domain, self.window, self.symbol)\n\n def __sub__(self, other):\n othercoef = self._get_coefficients(other)\n try:\n coef = self._sub(self.coef, othercoef)\n except Exception:\n return NotImplemented\n return self.__class__(coef, self.domain, self.window, self.symbol)\n\n def __mul__(self, other):\n othercoef = self._get_coefficients(other)\n try:\n coef = self._mul(self.coef, othercoef)\n except Exception:\n return NotImplemented\n return self.__class__(coef, self.domain, self.window, self.symbol)\n\n def __truediv__(self, other):\n # there is no true divide if the rhs is not a Number, although it\n # could return the first n elements of an infinite series.\n # It is hard to see where n would come from, though.\n if not isinstance(other, numbers.Number) or isinstance(other, bool):\n raise TypeError(\n f"unsupported types for true division: "\n f"'{type(self)}', '{type(other)}'"\n )\n return self.__floordiv__(other)\n\n def __floordiv__(self, other):\n res = self.__divmod__(other)\n if res is NotImplemented:\n return res\n return res[0]\n\n def __mod__(self, other):\n res = self.__divmod__(other)\n if res is NotImplemented:\n return res\n return res[1]\n\n def __divmod__(self, other):\n othercoef = self._get_coefficients(other)\n try:\n quo, rem = self._div(self.coef, othercoef)\n except ZeroDivisionError:\n raise\n except Exception:\n return NotImplemented\n quo = self.__class__(quo, self.domain, self.window, self.symbol)\n rem = self.__class__(rem, self.domain, self.window, self.symbol)\n return quo, rem\n\n def __pow__(self, other):\n coef = self._pow(self.coef, other, maxpower=self.maxpower)\n res = self.__class__(coef, self.domain, self.window, self.symbol)\n return res\n\n def __radd__(self, other):\n try:\n coef = self._add(other, self.coef)\n except Exception:\n return NotImplemented\n return self.__class__(coef, self.domain, self.window, self.symbol)\n\n def __rsub__(self, other):\n try:\n coef = self._sub(other, self.coef)\n except Exception:\n return NotImplemented\n return self.__class__(coef, self.domain, self.window, self.symbol)\n\n def __rmul__(self, other):\n try:\n coef = self._mul(other, self.coef)\n except Exception:\n return NotImplemented\n return self.__class__(coef, self.domain, self.window, self.symbol)\n\n def __rtruediv__(self, other):\n # An instance of ABCPolyBase is not considered a\n # Number.\n return NotImplemented\n\n def __rfloordiv__(self, other):\n res = self.__rdivmod__(other)\n if res is NotImplemented:\n return res\n return res[0]\n\n def __rmod__(self, other):\n res = self.__rdivmod__(other)\n if res is NotImplemented:\n return res\n return res[1]\n\n def __rdivmod__(self, other):\n try:\n quo, rem = self._div(other, self.coef)\n except ZeroDivisionError:\n raise\n except Exception:\n return NotImplemented\n quo = self.__class__(quo, self.domain, self.window, self.symbol)\n rem = self.__class__(rem, self.domain, self.window, self.symbol)\n return quo, rem\n\n def __eq__(self, other):\n res = (isinstance(other, self.__class__) and\n np.all(self.domain == other.domain) and\n np.all(self.window == other.window) and\n (self.coef.shape == other.coef.shape) and\n np.all(self.coef == other.coef) and\n (self.symbol == other.symbol))\n return res\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n #\n # Extra methods.\n #\n\n def copy(self):\n """Return a copy.\n\n Returns\n -------\n new_series : series\n Copy of self.\n\n """\n return self.__class__(self.coef, self.domain, self.window, self.symbol)\n\n def degree(self):\n """The degree of the series.\n\n Returns\n -------\n degree : int\n Degree of the series, one less than the number of coefficients.\n\n Examples\n --------\n\n Create a polynomial object for ``1 + 7*x + 4*x**2``:\n\n >>> np.polynomial.set_default_printstyle("unicode")\n >>> poly = np.polynomial.Polynomial([1, 7, 4])\n >>> print(poly)\n 1.0 + 7.0·x + 4.0·x²\n >>> poly.degree()\n 2\n\n Note that this method does not check for non-zero coefficients.\n You must trim the polynomial to remove any trailing zeroes:\n\n >>> poly = np.polynomial.Polynomial([1, 7, 0])\n >>> print(poly)\n 1.0 + 7.0·x + 0.0·x²\n >>> poly.degree()\n 2\n >>> poly.trim().degree()\n 1\n\n """\n return len(self) - 1\n\n def cutdeg(self, deg):\n """Truncate series to the given degree.\n\n Reduce the degree of the series to `deg` by discarding the\n high order terms. If `deg` is greater than the current degree a\n copy of the current series is returned. This can be useful in least\n squares where the coefficients of the high degree terms may be very\n small.\n\n Parameters\n ----------\n deg : non-negative int\n The series is reduced to degree `deg` by discarding the high\n order terms. The value of `deg` must be a non-negative integer.\n\n Returns\n -------\n new_series : series\n New instance of series with reduced degree.\n\n """\n return self.truncate(deg + 1)\n\n def trim(self, tol=0):\n """Remove trailing coefficients\n\n Remove trailing coefficients until a coefficient is reached whose\n absolute value greater than `tol` or the beginning of the series is\n reached. If all the coefficients would be removed the series is set\n to ``[0]``. A new series instance is returned with the new\n coefficients. The current instance remains unchanged.\n\n Parameters\n ----------\n tol : non-negative number.\n All trailing coefficients less than `tol` will be removed.\n\n Returns\n -------\n new_series : series\n New instance of series with trimmed coefficients.\n\n """\n coef = pu.trimcoef(self.coef, tol)\n return self.__class__(coef, self.domain, self.window, self.symbol)\n\n def truncate(self, size):\n """Truncate series to length `size`.\n\n Reduce the series to length `size` by discarding the high\n degree terms. The value of `size` must be a positive integer. This\n can be useful in least squares where the coefficients of the\n high degree terms may be very small.\n\n Parameters\n ----------\n size : positive int\n The series is reduced to length `size` by discarding the high\n degree terms. The value of `size` must be a positive integer.\n\n Returns\n -------\n new_series : series\n New instance of series with truncated coefficients.\n\n """\n isize = int(size)\n if isize != size or isize < 1:\n raise ValueError("size must be a positive integer")\n if isize >= len(self.coef):\n coef = self.coef\n else:\n coef = self.coef[:isize]\n return self.__class__(coef, self.domain, self.window, self.symbol)\n\n def convert(self, domain=None, kind=None, window=None):\n """Convert series to a different kind and/or domain and/or window.\n\n Parameters\n ----------\n domain : array_like, optional\n The domain of the converted series. If the value is None,\n the default domain of `kind` is used.\n kind : class, optional\n The polynomial series type class to which the current instance\n should be converted. If kind is None, then the class of the\n current instance is used.\n window : array_like, optional\n The window of the converted series. If the value is None,\n the default window of `kind` is used.\n\n Returns\n -------\n new_series : series\n The returned class can be of different type than the current\n instance and/or have a different domain and/or different\n window.\n\n Notes\n -----\n Conversion between domains and class types can result in\n numerically ill defined series.\n\n """\n if kind is None:\n kind = self.__class__\n if domain is None:\n domain = kind.domain\n if window is None:\n window = kind.window\n return self(kind.identity(domain, window=window, symbol=self.symbol))\n\n def mapparms(self):\n """Return the mapping parameters.\n\n The returned values define a linear map ``off + scl*x`` that is\n applied to the input arguments before the series is evaluated. The\n map depends on the ``domain`` and ``window``; if the current\n ``domain`` is equal to the ``window`` the resulting map is the\n identity. If the coefficients of the series instance are to be\n used by themselves outside this class, then the linear function\n must be substituted for the ``x`` in the standard representation of\n the base polynomials.\n\n Returns\n -------\n off, scl : float or complex\n The mapping function is defined by ``off + scl*x``.\n\n Notes\n -----\n If the current domain is the interval ``[l1, r1]`` and the window\n is ``[l2, r2]``, then the linear mapping function ``L`` is\n defined by the equations::\n\n L(l1) = l2\n L(r1) = r2\n\n """\n return pu.mapparms(self.domain, self.window)\n\n def integ(self, m=1, k=[], lbnd=None):\n """Integrate.\n\n Return a series instance that is the definite integral of the\n current series.\n\n Parameters\n ----------\n m : non-negative int\n The number of integrations to perform.\n k : array_like\n Integration constants. The first constant is applied to the\n first integration, the second to the second, and so on. The\n list of values must less than or equal to `m` in length and any\n missing values are set to zero.\n lbnd : Scalar\n The lower bound of the definite integral.\n\n Returns\n -------\n new_series : series\n A new series representing the integral. The domain is the same\n as the domain of the integrated series.\n\n """\n off, scl = self.mapparms()\n if lbnd is None:\n lbnd = 0\n else:\n lbnd = off + scl * lbnd\n coef = self._int(self.coef, m, k, lbnd, 1. / scl)\n return self.__class__(coef, self.domain, self.window, self.symbol)\n\n def deriv(self, m=1):\n """Differentiate.\n\n Return a series instance of that is the derivative of the current\n series.\n\n Parameters\n ----------\n m : non-negative int\n Find the derivative of order `m`.\n\n Returns\n -------\n new_series : series\n A new series representing the derivative. The domain is the same\n as the domain of the differentiated series.\n\n """\n off, scl = self.mapparms()\n coef = self._der(self.coef, m, scl)\n return self.__class__(coef, self.domain, self.window, self.symbol)\n\n def roots(self):\n """Return the roots of the series polynomial.\n\n Compute the roots for the series. Note that the accuracy of the\n roots decreases the further outside the `domain` they lie.\n\n Returns\n -------\n roots : ndarray\n Array containing the roots of the series.\n\n """\n roots = self._roots(self.coef)\n return pu.mapdomain(roots, self.window, self.domain)\n\n def linspace(self, n=100, domain=None):\n """Return x, y values at equally spaced points in domain.\n\n Returns the x, y values at `n` linearly spaced points across the\n domain. Here y is the value of the polynomial at the points x. By\n default the domain is the same as that of the series instance.\n This method is intended mostly as a plotting aid.\n\n Parameters\n ----------\n n : int, optional\n Number of point pairs to return. The default value is 100.\n domain : {None, array_like}, optional\n If not None, the specified domain is used instead of that of\n the calling instance. It should be of the form ``[beg,end]``.\n The default is None which case the class domain is used.\n\n Returns\n -------\n x, y : ndarray\n x is equal to linspace(self.domain[0], self.domain[1], n) and\n y is the series evaluated at element of x.\n\n """\n if domain is None:\n domain = self.domain\n x = np.linspace(domain[0], domain[1], n)\n y = self(x)\n return x, y\n\n @classmethod\n def fit(cls, x, y, deg, domain=None, rcond=None, full=False, w=None,\n window=None, symbol='x'):\n """Least squares fit to data.\n\n Return a series instance that is the least squares fit to the data\n `y` sampled at `x`. The domain of the returned instance can be\n specified and this will often result in a superior fit with less\n chance of ill conditioning.\n\n Parameters\n ----------\n x : array_like, shape (M,)\n x-coordinates of the M sample points ``(x[i], y[i])``.\n y : array_like, shape (M,)\n y-coordinates of the M sample points ``(x[i], y[i])``.\n deg : int or 1-D array_like\n Degree(s) of the fitting polynomials. If `deg` is a single integer\n all terms up to and including the `deg`'th term are included in the\n fit. For NumPy versions >= 1.11.0 a list of integers specifying the\n degrees of the terms to include may be used instead.\n domain : {None, [beg, end], []}, optional\n Domain to use for the returned series. If ``None``,\n then a minimal domain that covers the points `x` is chosen. If\n ``[]`` the class domain is used. The default value was the\n class domain in NumPy 1.4 and ``None`` in later versions.\n The ``[]`` option was added in numpy 1.5.0.\n rcond : float, optional\n Relative condition number of the fit. Singular values smaller\n than this relative to the largest singular value will be\n ignored. The default value is ``len(x)*eps``, where eps is the\n relative precision of the float type, about 2e-16 in most\n cases.\n full : bool, optional\n Switch determining nature of return value. When it is False\n (the default) just the coefficients are returned, when True\n diagnostic information from the singular value decomposition is\n also returned.\n w : array_like, shape (M,), optional\n Weights. If not None, the weight ``w[i]`` applies to the unsquared\n residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are\n chosen so that the errors of the products ``w[i]*y[i]`` all have\n the same variance. When using inverse-variance weighting, use\n ``w[i] = 1/sigma(y[i])``. The default value is None.\n window : {[beg, end]}, optional\n Window to use for the returned series. The default\n value is the default class domain\n symbol : str, optional\n Symbol representing the independent variable. Default is 'x'.\n\n Returns\n -------\n new_series : series\n A series that represents the least squares fit to the data and\n has the domain and window specified in the call. If the\n coefficients for the unscaled and unshifted basis polynomials are\n of interest, do ``new_series.convert().coef``.\n\n [resid, rank, sv, rcond] : list\n These values are only returned if ``full == True``\n\n - resid -- sum of squared residuals of the least squares fit\n - rank -- the numerical rank of the scaled Vandermonde matrix\n - sv -- singular values of the scaled Vandermonde matrix\n - rcond -- value of `rcond`.\n\n For more details, see `linalg.lstsq`.\n\n """\n if domain is None:\n domain = pu.getdomain(x)\n if domain[0] == domain[1]:\n domain[0] -= 1\n domain[1] += 1\n elif isinstance(domain, list) and len(domain) == 0:\n domain = cls.domain\n\n if window is None:\n window = cls.window\n\n xnew = pu.mapdomain(x, domain, window)\n res = cls._fit(xnew, y, deg, w=w, rcond=rcond, full=full)\n if full:\n [coef, status] = res\n return (\n cls(coef, domain=domain, window=window, symbol=symbol), status\n )\n else:\n coef = res\n return cls(coef, domain=domain, window=window, symbol=symbol)\n\n @classmethod\n def fromroots(cls, roots, domain=[], window=None, symbol='x'):\n """Return series instance that has the specified roots.\n\n Returns a series representing the product\n ``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is a\n list of roots.\n\n Parameters\n ----------\n roots : array_like\n List of roots.\n domain : {[], None, array_like}, optional\n Domain for the resulting series. If None the domain is the\n interval from the smallest root to the largest. If [] the\n domain is the class domain. The default is [].\n window : {None, array_like}, optional\n Window for the returned series. If None the class window is\n used. The default is None.\n symbol : str, optional\n Symbol representing the independent variable. Default is 'x'.\n\n Returns\n -------\n new_series : series\n Series with the specified roots.\n\n """\n [roots] = pu.as_series([roots], trim=False)\n if domain is None:\n domain = pu.getdomain(roots)\n elif isinstance(domain, list) and len(domain) == 0:\n domain = cls.domain\n\n if window is None:\n window = cls.window\n\n deg = len(roots)\n off, scl = pu.mapparms(domain, window)\n rnew = off + scl * roots\n coef = cls._fromroots(rnew) / scl**deg\n return cls(coef, domain=domain, window=window, symbol=symbol)\n\n @classmethod\n def identity(cls, domain=None, window=None, symbol='x'):\n """Identity function.\n\n If ``p`` is the returned series, then ``p(x) == x`` for all\n values of x.\n\n Parameters\n ----------\n domain : {None, array_like}, optional\n If given, the array must be of the form ``[beg, end]``, where\n ``beg`` and ``end`` are the endpoints of the domain. If None is\n given then the class domain is used. The default is None.\n window : {None, array_like}, optional\n If given, the resulting array must be if the form\n ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of\n the window. If None is given then the class window is used. The\n default is None.\n symbol : str, optional\n Symbol representing the independent variable. Default is 'x'.\n\n Returns\n -------\n new_series : series\n Series of representing the identity.\n\n """\n if domain is None:\n domain = cls.domain\n if window is None:\n window = cls.window\n off, scl = pu.mapparms(window, domain)\n coef = cls._line(off, scl)\n return cls(coef, domain, window, symbol)\n\n @classmethod\n def basis(cls, deg, domain=None, window=None, symbol='x'):\n """Series basis polynomial of degree `deg`.\n\n Returns the series representing the basis polynomial of degree `deg`.\n\n Parameters\n ----------\n deg : int\n Degree of the basis polynomial for the series. Must be >= 0.\n domain : {None, array_like}, optional\n If given, the array must be of the form ``[beg, end]``, where\n ``beg`` and ``end`` are the endpoints of the domain. If None is\n given then the class domain is used. The default is None.\n window : {None, array_like}, optional\n If given, the resulting array must be if the form\n ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of\n the window. If None is given then the class window is used. The\n default is None.\n symbol : str, optional\n Symbol representing the independent variable. Default is 'x'.\n\n Returns\n -------\n new_series : series\n A series with the coefficient of the `deg` term set to one and\n all others zero.\n\n """\n if domain is None:\n domain = cls.domain\n if window is None:\n window = cls.window\n ideg = int(deg)\n\n if ideg != deg or ideg < 0:\n raise ValueError("deg must be non-negative integer")\n return cls([0] * ideg + [1], domain, window, symbol)\n\n @classmethod\n def cast(cls, series, domain=None, window=None):\n """Convert series to series of this class.\n\n The `series` is expected to be an instance of some polynomial\n series of one of the types supported by by the numpy.polynomial\n module, but could be some other class that supports the convert\n method.\n\n Parameters\n ----------\n series : series\n The series instance to be converted.\n domain : {None, array_like}, optional\n If given, the array must be of the form ``[beg, end]``, where\n ``beg`` and ``end`` are the endpoints of the domain. If None is\n given then the class domain is used. The default is None.\n window : {None, array_like}, optional\n If given, the resulting array must be if the form\n ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of\n the window. If None is given then the class window is used. The\n default is None.\n\n Returns\n -------\n new_series : series\n A series of the same kind as the calling class and equal to\n `series` when evaluated.\n\n See Also\n --------\n convert : similar instance method\n\n """\n if domain is None:\n domain = cls.domain\n if window is None:\n window = cls.window\n return series.convert(domain, cls, window)\n | .venv\Lib\site-packages\numpy\polynomial\_polybase.py | _polybase.py | Python | 40,549 | 0.95 | 0.18136 | 0.040241 | vue-tools | 530 | 2024-12-12T16:42:06.481126 | BSD-3-Clause | false | 3549f3b4bb55a37647984a2e6776a944 |
import abc\nimport decimal\nimport numbers\nfrom collections.abc import Iterator, Mapping, Sequence\nfrom typing import (\n Any,\n ClassVar,\n Generic,\n Literal,\n LiteralString,\n Self,\n SupportsIndex,\n TypeAlias,\n overload,\n)\n\nfrom typing_extensions import TypeIs, TypeVar\n\nimport numpy as np\nimport numpy.typing as npt\nfrom numpy._typing import (\n _ArrayLikeComplex_co,\n _ArrayLikeFloat_co,\n _FloatLike_co,\n _NumberLike_co,\n)\n\nfrom ._polytypes import (\n _AnyInt,\n _Array2,\n _ArrayLikeCoef_co,\n _ArrayLikeCoefObject_co,\n _CoefLike_co,\n _CoefSeries,\n _Series,\n _SeriesLikeCoef_co,\n _SeriesLikeInt_co,\n _Tuple2,\n)\n\n__all__ = ["ABCPolyBase"]\n\n_NameCo = TypeVar(\n "_NameCo",\n bound=LiteralString | None,\n covariant=True,\n default=LiteralString | None\n)\n_Other = TypeVar("_Other", bound=ABCPolyBase)\n\n_AnyOther: TypeAlias = ABCPolyBase | _CoefLike_co | _SeriesLikeCoef_co\n_Hundred: TypeAlias = Literal[100]\n\nclass ABCPolyBase(Generic[_NameCo], abc.ABC):\n __hash__: ClassVar[None] # type: ignore[assignment] # pyright: ignore[reportIncompatibleMethodOverride]\n __array_ufunc__: ClassVar[None]\n\n maxpower: ClassVar[_Hundred]\n _superscript_mapping: ClassVar[Mapping[int, str]]\n _subscript_mapping: ClassVar[Mapping[int, str]]\n _use_unicode: ClassVar[bool]\n\n basis_name: _NameCo\n coef: _CoefSeries\n domain: _Array2[np.inexact | np.object_]\n window: _Array2[np.inexact | np.object_]\n\n _symbol: LiteralString\n @property\n def symbol(self, /) -> LiteralString: ...\n\n def __init__(\n self,\n /,\n coef: _SeriesLikeCoef_co,\n domain: _SeriesLikeCoef_co | None = ...,\n window: _SeriesLikeCoef_co | None = ...,\n symbol: str = ...,\n ) -> None: ...\n\n @overload\n def __call__(self, /, arg: _Other) -> _Other: ...\n # TODO: Once `_ShapeT@ndarray` is covariant and bounded (see #26081),\n # additionally include 0-d arrays as input types with scalar return type.\n @overload\n def __call__(\n self,\n /,\n arg: _FloatLike_co | decimal.Decimal | numbers.Real | np.object_,\n ) -> np.float64 | np.complex128: ...\n @overload\n def __call__(\n self,\n /,\n arg: _NumberLike_co | numbers.Complex,\n ) -> np.complex128: ...\n @overload\n def __call__(self, /, arg: _ArrayLikeFloat_co) -> (\n npt.NDArray[np.float64]\n | npt.NDArray[np.complex128]\n | npt.NDArray[np.object_]\n ): ...\n @overload\n def __call__(\n self,\n /,\n arg: _ArrayLikeComplex_co,\n ) -> npt.NDArray[np.complex128] | npt.NDArray[np.object_]: ...\n @overload\n def __call__(\n self,\n /,\n arg: _ArrayLikeCoefObject_co,\n ) -> npt.NDArray[np.object_]: ...\n\n def __format__(self, fmt_str: str, /) -> str: ...\n def __eq__(self, x: object, /) -> bool: ...\n def __ne__(self, x: object, /) -> bool: ...\n def __neg__(self, /) -> Self: ...\n def __pos__(self, /) -> Self: ...\n def __add__(self, x: _AnyOther, /) -> Self: ...\n def __sub__(self, x: _AnyOther, /) -> Self: ...\n def __mul__(self, x: _AnyOther, /) -> Self: ...\n def __truediv__(self, x: _AnyOther, /) -> Self: ...\n def __floordiv__(self, x: _AnyOther, /) -> Self: ...\n def __mod__(self, x: _AnyOther, /) -> Self: ...\n def __divmod__(self, x: _AnyOther, /) -> _Tuple2[Self]: ...\n def __pow__(self, x: _AnyOther, /) -> Self: ...\n def __radd__(self, x: _AnyOther, /) -> Self: ...\n def __rsub__(self, x: _AnyOther, /) -> Self: ...\n def __rmul__(self, x: _AnyOther, /) -> Self: ...\n def __rtruediv__(self, x: _AnyOther, /) -> Self: ...\n def __rfloordiv__(self, x: _AnyOther, /) -> Self: ...\n def __rmod__(self, x: _AnyOther, /) -> Self: ...\n def __rdivmod__(self, x: _AnyOther, /) -> _Tuple2[Self]: ...\n def __len__(self, /) -> int: ...\n def __iter__(self, /) -> Iterator[np.inexact | object]: ...\n def __getstate__(self, /) -> dict[str, Any]: ...\n def __setstate__(self, dict: dict[str, Any], /) -> None: ...\n\n def has_samecoef(self, /, other: ABCPolyBase) -> bool: ...\n def has_samedomain(self, /, other: ABCPolyBase) -> bool: ...\n def has_samewindow(self, /, other: ABCPolyBase) -> bool: ...\n @overload\n def has_sametype(self, /, other: ABCPolyBase) -> TypeIs[Self]: ...\n @overload\n def has_sametype(self, /, other: object) -> Literal[False]: ...\n\n def copy(self, /) -> Self: ...\n def degree(self, /) -> int: ...\n def cutdeg(self, /) -> Self: ...\n def trim(self, /, tol: _FloatLike_co = ...) -> Self: ...\n def truncate(self, /, size: _AnyInt) -> Self: ...\n\n @overload\n def convert(\n self,\n /,\n domain: _SeriesLikeCoef_co | None,\n kind: type[_Other],\n window: _SeriesLikeCoef_co | None = ...,\n ) -> _Other: ...\n @overload\n def convert(\n self,\n /,\n domain: _SeriesLikeCoef_co | None = ...,\n *,\n kind: type[_Other],\n window: _SeriesLikeCoef_co | None = ...,\n ) -> _Other: ...\n @overload\n def convert(\n self,\n /,\n domain: _SeriesLikeCoef_co | None = ...,\n kind: None = None,\n window: _SeriesLikeCoef_co | None = ...,\n ) -> Self: ...\n\n def mapparms(self, /) -> _Tuple2[Any]: ...\n\n def integ(\n self,\n /,\n m: SupportsIndex = ...,\n k: _CoefLike_co | _SeriesLikeCoef_co = ...,\n lbnd: _CoefLike_co | None = ...,\n ) -> Self: ...\n\n def deriv(self, /, m: SupportsIndex = ...) -> Self: ...\n\n def roots(self, /) -> _CoefSeries: ...\n\n def linspace(\n self,\n /,\n n: SupportsIndex = ...,\n domain: _SeriesLikeCoef_co | None = ...,\n ) -> _Tuple2[_Series[np.float64 | np.complex128]]: ...\n\n @overload\n @classmethod\n def fit(\n cls,\n x: _SeriesLikeCoef_co,\n y: _SeriesLikeCoef_co,\n deg: int | _SeriesLikeInt_co,\n domain: _SeriesLikeCoef_co | None = ...,\n rcond: _FloatLike_co = ...,\n full: Literal[False] = ...,\n w: _SeriesLikeCoef_co | None = ...,\n window: _SeriesLikeCoef_co | None = ...,\n symbol: str = ...,\n ) -> Self: ...\n @overload\n @classmethod\n def fit(\n cls,\n x: _SeriesLikeCoef_co,\n y: _SeriesLikeCoef_co,\n deg: int | _SeriesLikeInt_co,\n domain: _SeriesLikeCoef_co | None = ...,\n rcond: _FloatLike_co = ...,\n *,\n full: Literal[True],\n w: _SeriesLikeCoef_co | None = ...,\n window: _SeriesLikeCoef_co | None = ...,\n symbol: str = ...,\n ) -> tuple[Self, Sequence[np.inexact | np.int32]]: ...\n @overload\n @classmethod\n def fit(\n cls,\n x: _SeriesLikeCoef_co,\n y: _SeriesLikeCoef_co,\n deg: int | _SeriesLikeInt_co,\n domain: _SeriesLikeCoef_co | None,\n rcond: _FloatLike_co,\n full: Literal[True], /,\n w: _SeriesLikeCoef_co | None = ...,\n window: _SeriesLikeCoef_co | None = ...,\n symbol: str = ...,\n ) -> tuple[Self, Sequence[np.inexact | np.int32]]: ...\n\n @classmethod\n def fromroots(\n cls,\n roots: _ArrayLikeCoef_co,\n domain: _SeriesLikeCoef_co | None = ...,\n window: _SeriesLikeCoef_co | None = ...,\n symbol: str = ...,\n ) -> Self: ...\n\n @classmethod\n def identity(\n cls,\n domain: _SeriesLikeCoef_co | None = ...,\n window: _SeriesLikeCoef_co | None = ...,\n symbol: str = ...,\n ) -> Self: ...\n\n @classmethod\n def basis(\n cls,\n deg: _AnyInt,\n domain: _SeriesLikeCoef_co | None = ...,\n window: _SeriesLikeCoef_co | None = ...,\n symbol: str = ...,\n ) -> Self: ...\n\n @classmethod\n def cast(\n cls,\n series: ABCPolyBase,\n domain: _SeriesLikeCoef_co | None = ...,\n window: _SeriesLikeCoef_co | None = ...,\n ) -> Self: ...\n\n @classmethod\n def _str_term_unicode(cls, /, i: str, arg_str: str) -> str: ...\n @staticmethod\n def _str_term_ascii(i: str, arg_str: str) -> str: ...\n @staticmethod\n def _repr_latex_term(i: str, arg_str: str, needs_parens: bool) -> str: ...\n | .venv\Lib\site-packages\numpy\polynomial\_polybase.pyi | _polybase.pyi | Other | 8,472 | 0.95 | 0.214035 | 0.015504 | react-lib | 590 | 2024-02-09T07:24:37.390896 | BSD-3-Clause | false | cebde57278ac21f44af6e5f682bea385 |
# ruff: noqa: PYI046, PYI047\n\nfrom collections.abc import Callable, Sequence\nfrom typing import (\n Any,\n Literal,\n LiteralString,\n NoReturn,\n Protocol,\n Self,\n SupportsIndex,\n SupportsInt,\n TypeAlias,\n TypeVar,\n overload,\n type_check_only,\n)\n\nimport numpy as np\nimport numpy.typing as npt\nfrom numpy._typing import (\n _ArrayLikeComplex_co,\n # array-likes\n _ArrayLikeFloat_co,\n _ArrayLikeNumber_co,\n _ArrayLikeObject_co,\n _ComplexLike_co,\n _FloatLike_co,\n # scalar-likes\n _IntLike_co,\n _NestedSequence,\n _NumberLike_co,\n _SupportsArray,\n)\n\n_T = TypeVar("_T")\n_T_contra = TypeVar("_T_contra", contravariant=True)\n_ScalarT = TypeVar("_ScalarT", bound=np.number | np.bool | np.object_)\n\n# compatible with e.g. int, float, complex, Decimal, Fraction, and ABCPolyBase\n@type_check_only\nclass _SupportsCoefOps(Protocol[_T_contra]):\n def __eq__(self, x: object, /) -> bool: ...\n def __ne__(self, x: object, /) -> bool: ...\n\n def __neg__(self, /) -> Self: ...\n def __pos__(self, /) -> Self: ...\n\n def __add__(self, x: _T_contra, /) -> Self: ...\n def __sub__(self, x: _T_contra, /) -> Self: ...\n def __mul__(self, x: _T_contra, /) -> Self: ...\n def __pow__(self, x: _T_contra, /) -> Self | float: ...\n\n def __radd__(self, x: _T_contra, /) -> Self: ...\n def __rsub__(self, x: _T_contra, /) -> Self: ...\n def __rmul__(self, x: _T_contra, /) -> Self: ...\n\n_Series: TypeAlias = np.ndarray[tuple[int], np.dtype[_ScalarT]]\n\n_FloatSeries: TypeAlias = _Series[np.floating]\n_ComplexSeries: TypeAlias = _Series[np.complexfloating]\n_ObjectSeries: TypeAlias = _Series[np.object_]\n_CoefSeries: TypeAlias = _Series[np.inexact | np.object_]\n\n_FloatArray: TypeAlias = npt.NDArray[np.floating]\n_ComplexArray: TypeAlias = npt.NDArray[np.complexfloating]\n_ObjectArray: TypeAlias = npt.NDArray[np.object_]\n_CoefArray: TypeAlias = npt.NDArray[np.inexact | np.object_]\n\n_Tuple2: TypeAlias = tuple[_T, _T]\n_Array1: TypeAlias = np.ndarray[tuple[Literal[1]], np.dtype[_ScalarT]]\n_Array2: TypeAlias = np.ndarray[tuple[Literal[2]], np.dtype[_ScalarT]]\n\n_AnyInt: TypeAlias = SupportsInt | SupportsIndex\n\n_CoefObjectLike_co: TypeAlias = np.object_ | _SupportsCoefOps[Any]\n_CoefLike_co: TypeAlias = _NumberLike_co | _CoefObjectLike_co\n\n# The term "series" is used here to refer to 1-d arrays of numeric scalars.\n_SeriesLikeBool_co: TypeAlias = (\n _SupportsArray[np.dtype[np.bool]]\n | Sequence[bool | np.bool]\n)\n_SeriesLikeInt_co: TypeAlias = (\n _SupportsArray[np.dtype[np.integer | np.bool]]\n | Sequence[_IntLike_co]\n)\n_SeriesLikeFloat_co: TypeAlias = (\n _SupportsArray[np.dtype[np.floating | np.integer | np.bool]]\n | Sequence[_FloatLike_co]\n)\n_SeriesLikeComplex_co: TypeAlias = (\n _SupportsArray[np.dtype[np.inexact | np.integer | np.bool]]\n | Sequence[_ComplexLike_co]\n)\n_SeriesLikeObject_co: TypeAlias = (\n _SupportsArray[np.dtype[np.object_]]\n | Sequence[_CoefObjectLike_co]\n)\n_SeriesLikeCoef_co: TypeAlias = (\n _SupportsArray[np.dtype[np.number | np.bool | np.object_]]\n | Sequence[_CoefLike_co]\n)\n\n_ArrayLikeCoefObject_co: TypeAlias = (\n _CoefObjectLike_co\n | _SeriesLikeObject_co\n | _NestedSequence[_SeriesLikeObject_co]\n)\n_ArrayLikeCoef_co: TypeAlias = (\n npt.NDArray[np.number | np.bool | np.object_]\n | _ArrayLikeNumber_co\n | _ArrayLikeCoefObject_co\n)\n\n_Name_co = TypeVar(\n "_Name_co",\n bound=LiteralString,\n covariant=True,\n default=LiteralString\n)\n\n@type_check_only\nclass _Named(Protocol[_Name_co]):\n @property\n def __name__(self, /) -> _Name_co: ...\n\n_Line: TypeAlias = np.ndarray[tuple[Literal[1, 2]], np.dtype[_ScalarT]]\n\n@type_check_only\nclass _FuncLine(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(self, /, off: _ScalarT, scl: _ScalarT) -> _Line[_ScalarT]: ...\n @overload\n def __call__(self, /, off: int, scl: int) -> _Line[np.int_]: ...\n @overload\n def __call__(self, /, off: float, scl: float) -> _Line[np.float64]: ...\n @overload\n def __call__(\n self,\n /,\n off: complex,\n scl: complex,\n ) -> _Line[np.complex128]: ...\n @overload\n def __call__(\n self,\n /,\n off: _SupportsCoefOps[Any],\n scl: _SupportsCoefOps[Any],\n ) -> _Line[np.object_]: ...\n\n@type_check_only\nclass _FuncFromRoots(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(self, /, roots: _SeriesLikeFloat_co) -> _FloatSeries: ...\n @overload\n def __call__(self, /, roots: _SeriesLikeComplex_co) -> _ComplexSeries: ...\n @overload\n def __call__(self, /, roots: _SeriesLikeCoef_co) -> _ObjectSeries: ...\n\n@type_check_only\nclass _FuncBinOp(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n c1: _SeriesLikeBool_co,\n c2: _SeriesLikeBool_co,\n ) -> NoReturn: ...\n @overload\n def __call__(\n self,\n /,\n c1: _SeriesLikeFloat_co,\n c2: _SeriesLikeFloat_co,\n ) -> _FloatSeries: ...\n @overload\n def __call__(\n self,\n /,\n c1: _SeriesLikeComplex_co,\n c2: _SeriesLikeComplex_co,\n ) -> _ComplexSeries: ...\n @overload\n def __call__(\n self,\n /,\n c1: _SeriesLikeCoef_co,\n c2: _SeriesLikeCoef_co,\n ) -> _ObjectSeries: ...\n\n@type_check_only\nclass _FuncUnOp(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(self, /, c: _SeriesLikeFloat_co) -> _FloatSeries: ...\n @overload\n def __call__(self, /, c: _SeriesLikeComplex_co) -> _ComplexSeries: ...\n @overload\n def __call__(self, /, c: _SeriesLikeCoef_co) -> _ObjectSeries: ...\n\n@type_check_only\nclass _FuncPoly2Ortho(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(self, /, pol: _SeriesLikeFloat_co) -> _FloatSeries: ...\n @overload\n def __call__(self, /, pol: _SeriesLikeComplex_co) -> _ComplexSeries: ...\n @overload\n def __call__(self, /, pol: _SeriesLikeCoef_co) -> _ObjectSeries: ...\n\n@type_check_only\nclass _FuncPow(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n c: _SeriesLikeFloat_co,\n pow: _IntLike_co,\n maxpower: _IntLike_co | None = ...,\n ) -> _FloatSeries: ...\n @overload\n def __call__(\n self,\n /,\n c: _SeriesLikeComplex_co,\n pow: _IntLike_co,\n maxpower: _IntLike_co | None = ...,\n ) -> _ComplexSeries: ...\n @overload\n def __call__(\n self,\n /,\n c: _SeriesLikeCoef_co,\n pow: _IntLike_co,\n maxpower: _IntLike_co | None = ...,\n ) -> _ObjectSeries: ...\n\n@type_check_only\nclass _FuncDer(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n c: _ArrayLikeFloat_co,\n m: SupportsIndex = ...,\n scl: _FloatLike_co = ...,\n axis: SupportsIndex = ...,\n ) -> _FloatArray: ...\n @overload\n def __call__(\n self,\n /,\n c: _ArrayLikeComplex_co,\n m: SupportsIndex = ...,\n scl: _ComplexLike_co = ...,\n axis: SupportsIndex = ...,\n ) -> _ComplexArray: ...\n @overload\n def __call__(\n self,\n /,\n c: _ArrayLikeCoef_co,\n m: SupportsIndex = ...,\n scl: _CoefLike_co = ...,\n axis: SupportsIndex = ...,\n ) -> _ObjectArray: ...\n\n@type_check_only\nclass _FuncInteg(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n c: _ArrayLikeFloat_co,\n m: SupportsIndex = ...,\n k: _FloatLike_co | _SeriesLikeFloat_co = ...,\n lbnd: _FloatLike_co = ...,\n scl: _FloatLike_co = ...,\n axis: SupportsIndex = ...,\n ) -> _FloatArray: ...\n @overload\n def __call__(\n self,\n /,\n c: _ArrayLikeComplex_co,\n m: SupportsIndex = ...,\n k: _ComplexLike_co | _SeriesLikeComplex_co = ...,\n lbnd: _ComplexLike_co = ...,\n scl: _ComplexLike_co = ...,\n axis: SupportsIndex = ...,\n ) -> _ComplexArray: ...\n @overload\n def __call__(\n self,\n /,\n c: _ArrayLikeCoef_co,\n m: SupportsIndex = ...,\n k: _CoefLike_co | _SeriesLikeCoef_co = ...,\n lbnd: _CoefLike_co = ...,\n scl: _CoefLike_co = ...,\n axis: SupportsIndex = ...,\n ) -> _ObjectArray: ...\n\n@type_check_only\nclass _FuncValFromRoots(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n x: _FloatLike_co,\n r: _FloatLike_co,\n tensor: bool = ...,\n ) -> np.floating: ...\n @overload\n def __call__(\n self,\n /,\n x: _NumberLike_co,\n r: _NumberLike_co,\n tensor: bool = ...,\n ) -> np.complexfloating: ...\n @overload\n def __call__(\n self,\n /,\n x: _FloatLike_co | _ArrayLikeFloat_co,\n r: _ArrayLikeFloat_co,\n tensor: bool = ...,\n ) -> _FloatArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _NumberLike_co | _ArrayLikeComplex_co,\n r: _ArrayLikeComplex_co,\n tensor: bool = ...,\n ) -> _ComplexArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _CoefLike_co | _ArrayLikeCoef_co,\n r: _ArrayLikeCoef_co,\n tensor: bool = ...,\n ) -> _ObjectArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _CoefLike_co,\n r: _CoefLike_co,\n tensor: bool = ...,\n ) -> _SupportsCoefOps[Any]: ...\n\n@type_check_only\nclass _FuncVal(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n x: _FloatLike_co,\n c: _SeriesLikeFloat_co,\n tensor: bool = ...,\n ) -> np.floating: ...\n @overload\n def __call__(\n self,\n /,\n x: _NumberLike_co,\n c: _SeriesLikeComplex_co,\n tensor: bool = ...,\n ) -> np.complexfloating: ...\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeFloat_co,\n c: _ArrayLikeFloat_co,\n tensor: bool = ...,\n ) -> _FloatArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeComplex_co,\n c: _ArrayLikeComplex_co,\n tensor: bool = ...,\n ) -> _ComplexArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeCoef_co,\n c: _ArrayLikeCoef_co,\n tensor: bool = ...,\n ) -> _ObjectArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _CoefLike_co,\n c: _SeriesLikeObject_co,\n tensor: bool = ...,\n ) -> _SupportsCoefOps[Any]: ...\n\n@type_check_only\nclass _FuncVal2D(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n x: _FloatLike_co,\n y: _FloatLike_co,\n c: _SeriesLikeFloat_co,\n ) -> np.floating: ...\n @overload\n def __call__(\n self,\n /,\n x: _NumberLike_co,\n y: _NumberLike_co,\n c: _SeriesLikeComplex_co,\n ) -> np.complexfloating: ...\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeFloat_co,\n y: _ArrayLikeFloat_co,\n c: _ArrayLikeFloat_co,\n ) -> _FloatArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeComplex_co,\n y: _ArrayLikeComplex_co,\n c: _ArrayLikeComplex_co,\n ) -> _ComplexArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeCoef_co,\n y: _ArrayLikeCoef_co,\n c: _ArrayLikeCoef_co,\n ) -> _ObjectArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _CoefLike_co,\n y: _CoefLike_co,\n c: _SeriesLikeCoef_co,\n ) -> _SupportsCoefOps[Any]: ...\n\n@type_check_only\nclass _FuncVal3D(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n x: _FloatLike_co,\n y: _FloatLike_co,\n z: _FloatLike_co,\n c: _SeriesLikeFloat_co\n ) -> np.floating: ...\n @overload\n def __call__(\n self,\n /,\n x: _NumberLike_co,\n y: _NumberLike_co,\n z: _NumberLike_co,\n c: _SeriesLikeComplex_co,\n ) -> np.complexfloating: ...\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeFloat_co,\n y: _ArrayLikeFloat_co,\n z: _ArrayLikeFloat_co,\n c: _ArrayLikeFloat_co,\n ) -> _FloatArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeComplex_co,\n y: _ArrayLikeComplex_co,\n z: _ArrayLikeComplex_co,\n c: _ArrayLikeComplex_co,\n ) -> _ComplexArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeCoef_co,\n y: _ArrayLikeCoef_co,\n z: _ArrayLikeCoef_co,\n c: _ArrayLikeCoef_co,\n ) -> _ObjectArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _CoefLike_co,\n y: _CoefLike_co,\n z: _CoefLike_co,\n c: _SeriesLikeCoef_co,\n ) -> _SupportsCoefOps[Any]: ...\n\n_AnyValF: TypeAlias = Callable[\n [npt.ArrayLike, npt.ArrayLike, bool],\n _CoefArray,\n]\n\n@type_check_only\nclass _FuncValND(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n val_f: _AnyValF,\n c: _SeriesLikeFloat_co,\n /,\n *args: _FloatLike_co,\n ) -> np.floating: ...\n @overload\n def __call__(\n self,\n val_f: _AnyValF,\n c: _SeriesLikeComplex_co,\n /,\n *args: _NumberLike_co,\n ) -> np.complexfloating: ...\n @overload\n def __call__(\n self,\n val_f: _AnyValF,\n c: _ArrayLikeFloat_co,\n /,\n *args: _ArrayLikeFloat_co,\n ) -> _FloatArray: ...\n @overload\n def __call__(\n self,\n val_f: _AnyValF,\n c: _ArrayLikeComplex_co,\n /,\n *args: _ArrayLikeComplex_co,\n ) -> _ComplexArray: ...\n @overload\n def __call__(\n self,\n val_f: _AnyValF,\n c: _SeriesLikeObject_co,\n /,\n *args: _CoefObjectLike_co,\n ) -> _SupportsCoefOps[Any]: ...\n @overload\n def __call__(\n self,\n val_f: _AnyValF,\n c: _ArrayLikeCoef_co,\n /,\n *args: _ArrayLikeCoef_co,\n ) -> _ObjectArray: ...\n\n@type_check_only\nclass _FuncVander(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeFloat_co,\n deg: SupportsIndex,\n ) -> _FloatArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeComplex_co,\n deg: SupportsIndex,\n ) -> _ComplexArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeCoef_co,\n deg: SupportsIndex,\n ) -> _ObjectArray: ...\n @overload\n def __call__(\n self,\n /,\n x: npt.ArrayLike,\n deg: SupportsIndex,\n ) -> _CoefArray: ...\n\n_AnyDegrees: TypeAlias = Sequence[SupportsIndex]\n\n@type_check_only\nclass _FuncVander2D(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeFloat_co,\n y: _ArrayLikeFloat_co,\n deg: _AnyDegrees,\n ) -> _FloatArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeComplex_co,\n y: _ArrayLikeComplex_co,\n deg: _AnyDegrees,\n ) -> _ComplexArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeCoef_co,\n y: _ArrayLikeCoef_co,\n deg: _AnyDegrees,\n ) -> _ObjectArray: ...\n @overload\n def __call__(\n self,\n /,\n x: npt.ArrayLike,\n y: npt.ArrayLike,\n deg: _AnyDegrees,\n ) -> _CoefArray: ...\n\n@type_check_only\nclass _FuncVander3D(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeFloat_co,\n y: _ArrayLikeFloat_co,\n z: _ArrayLikeFloat_co,\n deg: _AnyDegrees,\n ) -> _FloatArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeComplex_co,\n y: _ArrayLikeComplex_co,\n z: _ArrayLikeComplex_co,\n deg: _AnyDegrees,\n ) -> _ComplexArray: ...\n @overload\n def __call__(\n self,\n /,\n x: _ArrayLikeCoef_co,\n y: _ArrayLikeCoef_co,\n z: _ArrayLikeCoef_co,\n deg: _AnyDegrees,\n ) -> _ObjectArray: ...\n @overload\n def __call__(\n self,\n /,\n x: npt.ArrayLike,\n y: npt.ArrayLike,\n z: npt.ArrayLike,\n deg: _AnyDegrees,\n ) -> _CoefArray: ...\n\n# keep in sync with the broadest overload of `._FuncVander`\n_AnyFuncVander: TypeAlias = Callable[\n [npt.ArrayLike, SupportsIndex],\n _CoefArray,\n]\n\n@type_check_only\nclass _FuncVanderND(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n vander_fs: Sequence[_AnyFuncVander],\n points: Sequence[_ArrayLikeFloat_co],\n degrees: Sequence[SupportsIndex],\n ) -> _FloatArray: ...\n @overload\n def __call__(\n self,\n /,\n vander_fs: Sequence[_AnyFuncVander],\n points: Sequence[_ArrayLikeComplex_co],\n degrees: Sequence[SupportsIndex],\n ) -> _ComplexArray: ...\n @overload\n def __call__(\n self,\n /,\n vander_fs: Sequence[_AnyFuncVander],\n points: Sequence[\n _ArrayLikeObject_co | _ArrayLikeComplex_co,\n ],\n degrees: Sequence[SupportsIndex],\n ) -> _ObjectArray: ...\n @overload\n def __call__(\n self,\n /,\n vander_fs: Sequence[_AnyFuncVander],\n points: Sequence[npt.ArrayLike],\n degrees: Sequence[SupportsIndex],\n ) -> _CoefArray: ...\n\n_FullFitResult: TypeAlias = Sequence[np.inexact | np.int32]\n\n@type_check_only\nclass _FuncFit(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n x: _SeriesLikeFloat_co,\n y: _ArrayLikeFloat_co,\n deg: int | _SeriesLikeInt_co,\n rcond: float | None = ...,\n full: Literal[False] = ...,\n w: _SeriesLikeFloat_co | None = ...,\n ) -> _FloatArray: ...\n @overload\n def __call__(\n self,\n x: _SeriesLikeFloat_co,\n y: _ArrayLikeFloat_co,\n deg: int | _SeriesLikeInt_co,\n rcond: float | None,\n full: Literal[True],\n /,\n w: _SeriesLikeFloat_co | None = ...,\n ) -> tuple[_FloatArray, _FullFitResult]: ...\n @overload\n def __call__(\n self,\n /,\n x: _SeriesLikeFloat_co,\n y: _ArrayLikeFloat_co,\n deg: int | _SeriesLikeInt_co,\n rcond: float | None = ...,\n *,\n full: Literal[True],\n w: _SeriesLikeFloat_co | None = ...,\n ) -> tuple[_FloatArray, _FullFitResult]: ...\n\n @overload\n def __call__(\n self,\n /,\n x: _SeriesLikeComplex_co,\n y: _ArrayLikeComplex_co,\n deg: int | _SeriesLikeInt_co,\n rcond: float | None = ...,\n full: Literal[False] = ...,\n w: _SeriesLikeFloat_co | None = ...,\n ) -> _ComplexArray: ...\n @overload\n def __call__(\n self,\n x: _SeriesLikeComplex_co,\n y: _ArrayLikeComplex_co,\n deg: int | _SeriesLikeInt_co,\n rcond: float | None,\n full: Literal[True],\n /,\n w: _SeriesLikeFloat_co | None = ...,\n ) -> tuple[_ComplexArray, _FullFitResult]: ...\n @overload\n def __call__(\n self,\n /,\n x: _SeriesLikeComplex_co,\n y: _ArrayLikeComplex_co,\n deg: int | _SeriesLikeInt_co,\n rcond: float | None = ...,\n *,\n full: Literal[True],\n w: _SeriesLikeFloat_co | None = ...,\n ) -> tuple[_ComplexArray, _FullFitResult]: ...\n\n @overload\n def __call__(\n self,\n /,\n x: _SeriesLikeComplex_co,\n y: _ArrayLikeCoef_co,\n deg: int | _SeriesLikeInt_co,\n rcond: float | None = ...,\n full: Literal[False] = ...,\n w: _SeriesLikeFloat_co | None = ...,\n ) -> _ObjectArray: ...\n @overload\n def __call__(\n self,\n x: _SeriesLikeComplex_co,\n y: _ArrayLikeCoef_co,\n deg: int | _SeriesLikeInt_co,\n rcond: float | None,\n full: Literal[True],\n /,\n w: _SeriesLikeFloat_co | None = ...,\n ) -> tuple[_ObjectArray, _FullFitResult]: ...\n @overload\n def __call__(\n self,\n /,\n x: _SeriesLikeComplex_co,\n y: _ArrayLikeCoef_co,\n deg: int | _SeriesLikeInt_co,\n rcond: float | None = ...,\n *,\n full: Literal[True],\n w: _SeriesLikeFloat_co | None = ...,\n ) -> tuple[_ObjectArray, _FullFitResult]: ...\n\n@type_check_only\nclass _FuncRoots(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n c: _SeriesLikeFloat_co,\n ) -> _Series[np.float64]: ...\n @overload\n def __call__(\n self,\n /,\n c: _SeriesLikeComplex_co,\n ) -> _Series[np.complex128]: ...\n @overload\n def __call__(self, /, c: _SeriesLikeCoef_co) -> _ObjectSeries: ...\n\n_Companion: TypeAlias = np.ndarray[tuple[int, int], np.dtype[_ScalarT]]\n\n@type_check_only\nclass _FuncCompanion(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n c: _SeriesLikeFloat_co,\n ) -> _Companion[np.float64]: ...\n @overload\n def __call__(\n self,\n /,\n c: _SeriesLikeComplex_co,\n ) -> _Companion[np.complex128]: ...\n @overload\n def __call__(self, /, c: _SeriesLikeCoef_co) -> _Companion[np.object_]: ...\n\n@type_check_only\nclass _FuncGauss(_Named[_Name_co], Protocol[_Name_co]):\n def __call__(\n self,\n /,\n deg: SupportsIndex,\n ) -> _Tuple2[_Series[np.float64]]: ...\n\n@type_check_only\nclass _FuncWeight(_Named[_Name_co], Protocol[_Name_co]):\n @overload\n def __call__(\n self,\n /,\n c: _ArrayLikeFloat_co,\n ) -> npt.NDArray[np.float64]: ...\n @overload\n def __call__(\n self,\n /,\n c: _ArrayLikeComplex_co,\n ) -> npt.NDArray[np.complex128]: ...\n @overload\n def __call__(self, /, c: _ArrayLikeCoef_co) -> _ObjectArray: ...\n\n@type_check_only\nclass _FuncPts(_Named[_Name_co], Protocol[_Name_co]):\n def __call__(self, /, npts: _AnyInt) -> _Series[np.float64]: ...\n | .venv\Lib\site-packages\numpy\polynomial\_polytypes.pyi | _polytypes.pyi | Other | 23,274 | 0.95 | 0.14574 | 0.017773 | node-utils | 272 | 2025-01-11T11:27:17.950881 | BSD-3-Clause | false | 65ae25a87a258cc70d342ff378fbddc1 |
"""\nA sub-package for efficiently dealing with polynomials.\n\nWithin the documentation for this sub-package, a "finite power series,"\ni.e., a polynomial (also referred to simply as a "series") is represented\nby a 1-D numpy array of the polynomial's coefficients, ordered from lowest\norder term to highest. For example, array([1,2,3]) represents\n``P_0 + 2*P_1 + 3*P_2``, where P_n is the n-th order basis polynomial\napplicable to the specific module in question, e.g., `polynomial` (which\n"wraps" the "standard" basis) or `chebyshev`. For optimal performance,\nall operations on polynomials, including evaluation at an argument, are\nimplemented as operations on the coefficients. Additional (module-specific)\ninformation can be found in the docstring for the module of interest.\n\nThis package provides *convenience classes* for each of six different kinds\nof polynomials:\n\n======================== ================\n**Name** **Provides**\n======================== ================\n`~polynomial.Polynomial` Power series\n`~chebyshev.Chebyshev` Chebyshev series\n`~legendre.Legendre` Legendre series\n`~laguerre.Laguerre` Laguerre series\n`~hermite.Hermite` Hermite series\n`~hermite_e.HermiteE` HermiteE series\n======================== ================\n\nThese *convenience classes* provide a consistent interface for creating,\nmanipulating, and fitting data with polynomials of different bases.\nThe convenience classes are the preferred interface for the `~numpy.polynomial`\npackage, and are available from the ``numpy.polynomial`` namespace.\nThis eliminates the need to navigate to the corresponding submodules, e.g.\n``np.polynomial.Polynomial`` or ``np.polynomial.Chebyshev`` instead of\n``np.polynomial.polynomial.Polynomial`` or\n``np.polynomial.chebyshev.Chebyshev``, respectively.\nThe classes provide a more consistent and concise interface than the\ntype-specific functions defined in the submodules for each type of polynomial.\nFor example, to fit a Chebyshev polynomial with degree ``1`` to data given\nby arrays ``xdata`` and ``ydata``, the\n`~chebyshev.Chebyshev.fit` class method::\n\n >>> from numpy.polynomial import Chebyshev\n >>> xdata = [1, 2, 3, 4]\n >>> ydata = [1, 4, 9, 16]\n >>> c = Chebyshev.fit(xdata, ydata, deg=1)\n\nis preferred over the `chebyshev.chebfit` function from the\n``np.polynomial.chebyshev`` module::\n\n >>> from numpy.polynomial.chebyshev import chebfit\n >>> c = chebfit(xdata, ydata, deg=1)\n\nSee :doc:`routines.polynomials.classes` for more details.\n\nConvenience Classes\n===================\n\nThe following lists the various constants and methods common to all of\nthe classes representing the various kinds of polynomials. In the following,\nthe term ``Poly`` represents any one of the convenience classes (e.g.\n`~polynomial.Polynomial`, `~chebyshev.Chebyshev`, `~hermite.Hermite`, etc.)\nwhile the lowercase ``p`` represents an **instance** of a polynomial class.\n\nConstants\n---------\n\n- ``Poly.domain`` -- Default domain\n- ``Poly.window`` -- Default window\n- ``Poly.basis_name`` -- String used to represent the basis\n- ``Poly.maxpower`` -- Maximum value ``n`` such that ``p**n`` is allowed\n\nCreation\n--------\n\nMethods for creating polynomial instances.\n\n- ``Poly.basis(degree)`` -- Basis polynomial of given degree\n- ``Poly.identity()`` -- ``p`` where ``p(x) = x`` for all ``x``\n- ``Poly.fit(x, y, deg)`` -- ``p`` of degree ``deg`` with coefficients\n determined by the least-squares fit to the data ``x``, ``y``\n- ``Poly.fromroots(roots)`` -- ``p`` with specified roots\n- ``p.copy()`` -- Create a copy of ``p``\n\nConversion\n----------\n\nMethods for converting a polynomial instance of one kind to another.\n\n- ``p.cast(Poly)`` -- Convert ``p`` to instance of kind ``Poly``\n- ``p.convert(Poly)`` -- Convert ``p`` to instance of kind ``Poly`` or map\n between ``domain`` and ``window``\n\nCalculus\n--------\n- ``p.deriv()`` -- Take the derivative of ``p``\n- ``p.integ()`` -- Integrate ``p``\n\nValidation\n----------\n- ``Poly.has_samecoef(p1, p2)`` -- Check if coefficients match\n- ``Poly.has_samedomain(p1, p2)`` -- Check if domains match\n- ``Poly.has_sametype(p1, p2)`` -- Check if types match\n- ``Poly.has_samewindow(p1, p2)`` -- Check if windows match\n\nMisc\n----\n- ``p.linspace()`` -- Return ``x, p(x)`` at equally-spaced points in ``domain``\n- ``p.mapparms()`` -- Return the parameters for the linear mapping between\n ``domain`` and ``window``.\n- ``p.roots()`` -- Return the roots of ``p``.\n- ``p.trim()`` -- Remove trailing coefficients.\n- ``p.cutdeg(degree)`` -- Truncate ``p`` to given degree\n- ``p.truncate(size)`` -- Truncate ``p`` to given size\n\n"""\nfrom .chebyshev import Chebyshev\nfrom .hermite import Hermite\nfrom .hermite_e import HermiteE\nfrom .laguerre import Laguerre\nfrom .legendre import Legendre\nfrom .polynomial import Polynomial\n\n__all__ = [ # noqa: F822\n "set_default_printstyle",\n "polynomial", "Polynomial",\n "chebyshev", "Chebyshev",\n "legendre", "Legendre",\n "hermite", "Hermite",\n "hermite_e", "HermiteE",\n "laguerre", "Laguerre",\n]\n\n\ndef set_default_printstyle(style):\n """\n Set the default format for the string representation of polynomials.\n\n Values for ``style`` must be valid inputs to ``__format__``, i.e. 'ascii'\n or 'unicode'.\n\n Parameters\n ----------\n style : str\n Format string for default printing style. Must be either 'ascii' or\n 'unicode'.\n\n Notes\n -----\n The default format depends on the platform: 'unicode' is used on\n Unix-based systems and 'ascii' on Windows. This determination is based on\n default font support for the unicode superscript and subscript ranges.\n\n Examples\n --------\n >>> p = np.polynomial.Polynomial([1, 2, 3])\n >>> c = np.polynomial.Chebyshev([1, 2, 3])\n >>> np.polynomial.set_default_printstyle('unicode')\n >>> print(p)\n 1.0 + 2.0·x + 3.0·x²\n >>> print(c)\n 1.0 + 2.0·T₁(x) + 3.0·T₂(x)\n >>> np.polynomial.set_default_printstyle('ascii')\n >>> print(p)\n 1.0 + 2.0 x + 3.0 x**2\n >>> print(c)\n 1.0 + 2.0 T_1(x) + 3.0 T_2(x)\n >>> # Formatting supersedes all class/package-level defaults\n >>> print(f"{p:unicode}")\n 1.0 + 2.0·x + 3.0·x²\n """\n if style not in ('unicode', 'ascii'):\n raise ValueError(\n f"Unsupported format string '{style}'. Valid options are 'ascii' "\n f"and 'unicode'"\n )\n _use_unicode = True\n if style == 'ascii':\n _use_unicode = False\n from ._polybase import ABCPolyBase\n ABCPolyBase._use_unicode = _use_unicode\n\n\nfrom numpy._pytesttester import PytestTester\n\ntest = PytestTester(__name__)\ndel PytestTester\n | .venv\Lib\site-packages\numpy\polynomial\__init__.py | __init__.py | Python | 6,913 | 0.95 | 0.149733 | 0.006452 | node-utils | 384 | 2024-12-13T03:07:34.869111 | GPL-3.0 | false | 665c38237cac093a51c4ab2b734fa659 |
from typing import Final, Literal\n\nfrom . import chebyshev, hermite, hermite_e, laguerre, legendre, polynomial\nfrom .chebyshev import Chebyshev\nfrom .hermite import Hermite\nfrom .hermite_e import HermiteE\nfrom .laguerre import Laguerre\nfrom .legendre import Legendre\nfrom .polynomial import Polynomial\n\n__all__ = [\n "set_default_printstyle",\n "polynomial", "Polynomial",\n "chebyshev", "Chebyshev",\n "legendre", "Legendre",\n "hermite", "Hermite",\n "hermite_e", "HermiteE",\n "laguerre", "Laguerre",\n]\n\ndef set_default_printstyle(style: Literal["ascii", "unicode"]) -> None: ...\n\nfrom numpy._pytesttester import PytestTester as _PytestTester\n\ntest: Final[_PytestTester]\n | .venv\Lib\site-packages\numpy\polynomial\__init__.pyi | __init__.pyi | Other | 713 | 0.85 | 0.04 | 0 | awesome-app | 759 | 2024-07-26T23:00:54.523472 | BSD-3-Clause | false | 9f8ff8c5548e7c0c4ddf43f92c579f4b |
"""Tests for chebyshev module.\n\n"""\nfrom functools import reduce\n\nimport numpy as np\nimport numpy.polynomial.chebyshev as cheb\nfrom numpy.polynomial.polynomial import polyval\nfrom numpy.testing import (\n assert_,\n assert_almost_equal,\n assert_equal,\n assert_raises,\n)\n\n\ndef trim(x):\n return cheb.chebtrim(x, tol=1e-6)\n\n\nT0 = [1]\nT1 = [0, 1]\nT2 = [-1, 0, 2]\nT3 = [0, -3, 0, 4]\nT4 = [1, 0, -8, 0, 8]\nT5 = [0, 5, 0, -20, 0, 16]\nT6 = [-1, 0, 18, 0, -48, 0, 32]\nT7 = [0, -7, 0, 56, 0, -112, 0, 64]\nT8 = [1, 0, -32, 0, 160, 0, -256, 0, 128]\nT9 = [0, 9, 0, -120, 0, 432, 0, -576, 0, 256]\n\nTlist = [T0, T1, T2, T3, T4, T5, T6, T7, T8, T9]\n\n\nclass TestPrivate:\n\n def test__cseries_to_zseries(self):\n for i in range(5):\n inp = np.array([2] + [1] * i, np.double)\n tgt = np.array([.5] * i + [2] + [.5] * i, np.double)\n res = cheb._cseries_to_zseries(inp)\n assert_equal(res, tgt)\n\n def test__zseries_to_cseries(self):\n for i in range(5):\n inp = np.array([.5] * i + [2] + [.5] * i, np.double)\n tgt = np.array([2] + [1] * i, np.double)\n res = cheb._zseries_to_cseries(inp)\n assert_equal(res, tgt)\n\n\nclass TestConstants:\n\n def test_chebdomain(self):\n assert_equal(cheb.chebdomain, [-1, 1])\n\n def test_chebzero(self):\n assert_equal(cheb.chebzero, [0])\n\n def test_chebone(self):\n assert_equal(cheb.chebone, [1])\n\n def test_chebx(self):\n assert_equal(cheb.chebx, [0, 1])\n\n\nclass TestArithmetic:\n\n def test_chebadd(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n tgt = np.zeros(max(i, j) + 1)\n tgt[i] += 1\n tgt[j] += 1\n res = cheb.chebadd([0] * i + [1], [0] * j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_chebsub(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n tgt = np.zeros(max(i, j) + 1)\n tgt[i] += 1\n tgt[j] -= 1\n res = cheb.chebsub([0] * i + [1], [0] * j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_chebmulx(self):\n assert_equal(cheb.chebmulx([0]), [0])\n assert_equal(cheb.chebmulx([1]), [0, 1])\n for i in range(1, 5):\n ser = [0] * i + [1]\n tgt = [0] * (i - 1) + [.5, 0, .5]\n assert_equal(cheb.chebmulx(ser), tgt)\n\n def test_chebmul(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n tgt = np.zeros(i + j + 1)\n tgt[i + j] += .5\n tgt[abs(i - j)] += .5\n res = cheb.chebmul([0] * i + [1], [0] * j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_chebdiv(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n ci = [0] * i + [1]\n cj = [0] * j + [1]\n tgt = cheb.chebadd(ci, cj)\n quo, rem = cheb.chebdiv(tgt, ci)\n res = cheb.chebadd(cheb.chebmul(quo, ci), rem)\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_chebpow(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n c = np.arange(i + 1)\n tgt = reduce(cheb.chebmul, [c] * j, np.array([1]))\n res = cheb.chebpow(c, j)\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n\nclass TestEvaluation:\n # coefficients of 1 + 2*x + 3*x**2\n c1d = np.array([2.5, 2., 1.5])\n c2d = np.einsum('i,j->ij', c1d, c1d)\n c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)\n\n # some random values in [-1, 1)\n x = np.random.random((3, 5)) * 2 - 1\n y = polyval(x, [1., 2., 3.])\n\n def test_chebval(self):\n # check empty input\n assert_equal(cheb.chebval([], [1]).size, 0)\n\n # check normal input)\n x = np.linspace(-1, 1)\n y = [polyval(x, c) for c in Tlist]\n for i in range(10):\n msg = f"At i={i}"\n tgt = y[i]\n res = cheb.chebval(x, [0] * i + [1])\n assert_almost_equal(res, tgt, err_msg=msg)\n\n # check that shape is preserved\n for i in range(3):\n dims = [2] * i\n x = np.zeros(dims)\n assert_equal(cheb.chebval(x, [1]).shape, dims)\n assert_equal(cheb.chebval(x, [1, 0]).shape, dims)\n assert_equal(cheb.chebval(x, [1, 0, 0]).shape, dims)\n\n def test_chebval2d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test exceptions\n assert_raises(ValueError, cheb.chebval2d, x1, x2[:2], self.c2d)\n\n # test values\n tgt = y1 * y2\n res = cheb.chebval2d(x1, x2, self.c2d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = cheb.chebval2d(z, z, self.c2d)\n assert_(res.shape == (2, 3))\n\n def test_chebval3d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test exceptions\n assert_raises(ValueError, cheb.chebval3d, x1, x2, x3[:2], self.c3d)\n\n # test values\n tgt = y1 * y2 * y3\n res = cheb.chebval3d(x1, x2, x3, self.c3d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = cheb.chebval3d(z, z, z, self.c3d)\n assert_(res.shape == (2, 3))\n\n def test_chebgrid2d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test values\n tgt = np.einsum('i,j->ij', y1, y2)\n res = cheb.chebgrid2d(x1, x2, self.c2d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = cheb.chebgrid2d(z, z, self.c2d)\n assert_(res.shape == (2, 3) * 2)\n\n def test_chebgrid3d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test values\n tgt = np.einsum('i,j,k->ijk', y1, y2, y3)\n res = cheb.chebgrid3d(x1, x2, x3, self.c3d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = cheb.chebgrid3d(z, z, z, self.c3d)\n assert_(res.shape == (2, 3) * 3)\n\n\nclass TestIntegral:\n\n def test_chebint(self):\n # check exceptions\n assert_raises(TypeError, cheb.chebint, [0], .5)\n assert_raises(ValueError, cheb.chebint, [0], -1)\n assert_raises(ValueError, cheb.chebint, [0], 1, [0, 0])\n assert_raises(ValueError, cheb.chebint, [0], lbnd=[0])\n assert_raises(ValueError, cheb.chebint, [0], scl=[0])\n assert_raises(TypeError, cheb.chebint, [0], axis=.5)\n\n # test integration of zero polynomial\n for i in range(2, 5):\n k = [0] * (i - 2) + [1]\n res = cheb.chebint([0], m=i, k=k)\n assert_almost_equal(res, [0, 1])\n\n # check single integration with integration constant\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n tgt = [i] + [0] * i + [1 / scl]\n chebpol = cheb.poly2cheb(pol)\n chebint = cheb.chebint(chebpol, m=1, k=[i])\n res = cheb.cheb2poly(chebint)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check single integration with integration constant and lbnd\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n chebpol = cheb.poly2cheb(pol)\n chebint = cheb.chebint(chebpol, m=1, k=[i], lbnd=-1)\n assert_almost_equal(cheb.chebval(-1, chebint), i)\n\n # check single integration with integration constant and scaling\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n tgt = [i] + [0] * i + [2 / scl]\n chebpol = cheb.poly2cheb(pol)\n chebint = cheb.chebint(chebpol, m=1, k=[i], scl=2)\n res = cheb.cheb2poly(chebint)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with default k\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = cheb.chebint(tgt, m=1)\n res = cheb.chebint(pol, m=j)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with defined k\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = cheb.chebint(tgt, m=1, k=[k])\n res = cheb.chebint(pol, m=j, k=list(range(j)))\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with lbnd\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = cheb.chebint(tgt, m=1, k=[k], lbnd=-1)\n res = cheb.chebint(pol, m=j, k=list(range(j)), lbnd=-1)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with scaling\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = cheb.chebint(tgt, m=1, k=[k], scl=2)\n res = cheb.chebint(pol, m=j, k=list(range(j)), scl=2)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_chebint_axis(self):\n # check that axis keyword works\n c2d = np.random.random((3, 4))\n\n tgt = np.vstack([cheb.chebint(c) for c in c2d.T]).T\n res = cheb.chebint(c2d, axis=0)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([cheb.chebint(c) for c in c2d])\n res = cheb.chebint(c2d, axis=1)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([cheb.chebint(c, k=3) for c in c2d])\n res = cheb.chebint(c2d, k=3, axis=1)\n assert_almost_equal(res, tgt)\n\n\nclass TestDerivative:\n\n def test_chebder(self):\n # check exceptions\n assert_raises(TypeError, cheb.chebder, [0], .5)\n assert_raises(ValueError, cheb.chebder, [0], -1)\n\n # check that zeroth derivative does nothing\n for i in range(5):\n tgt = [0] * i + [1]\n res = cheb.chebder(tgt, m=0)\n assert_equal(trim(res), trim(tgt))\n\n # check that derivation is the inverse of integration\n for i in range(5):\n for j in range(2, 5):\n tgt = [0] * i + [1]\n res = cheb.chebder(cheb.chebint(tgt, m=j), m=j)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check derivation with scaling\n for i in range(5):\n for j in range(2, 5):\n tgt = [0] * i + [1]\n res = cheb.chebder(cheb.chebint(tgt, m=j, scl=2), m=j, scl=.5)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_chebder_axis(self):\n # check that axis keyword works\n c2d = np.random.random((3, 4))\n\n tgt = np.vstack([cheb.chebder(c) for c in c2d.T]).T\n res = cheb.chebder(c2d, axis=0)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([cheb.chebder(c) for c in c2d])\n res = cheb.chebder(c2d, axis=1)\n assert_almost_equal(res, tgt)\n\n\nclass TestVander:\n # some random values in [-1, 1)\n x = np.random.random((3, 5)) * 2 - 1\n\n def test_chebvander(self):\n # check for 1d x\n x = np.arange(3)\n v = cheb.chebvander(x, 3)\n assert_(v.shape == (3, 4))\n for i in range(4):\n coef = [0] * i + [1]\n assert_almost_equal(v[..., i], cheb.chebval(x, coef))\n\n # check for 2d x\n x = np.array([[1, 2], [3, 4], [5, 6]])\n v = cheb.chebvander(x, 3)\n assert_(v.shape == (3, 2, 4))\n for i in range(4):\n coef = [0] * i + [1]\n assert_almost_equal(v[..., i], cheb.chebval(x, coef))\n\n def test_chebvander2d(self):\n # also tests chebval2d for non-square coefficient array\n x1, x2, x3 = self.x\n c = np.random.random((2, 3))\n van = cheb.chebvander2d(x1, x2, [1, 2])\n tgt = cheb.chebval2d(x1, x2, c)\n res = np.dot(van, c.flat)\n assert_almost_equal(res, tgt)\n\n # check shape\n van = cheb.chebvander2d([x1], [x2], [1, 2])\n assert_(van.shape == (1, 5, 6))\n\n def test_chebvander3d(self):\n # also tests chebval3d for non-square coefficient array\n x1, x2, x3 = self.x\n c = np.random.random((2, 3, 4))\n van = cheb.chebvander3d(x1, x2, x3, [1, 2, 3])\n tgt = cheb.chebval3d(x1, x2, x3, c)\n res = np.dot(van, c.flat)\n assert_almost_equal(res, tgt)\n\n # check shape\n van = cheb.chebvander3d([x1], [x2], [x3], [1, 2, 3])\n assert_(van.shape == (1, 5, 24))\n\n\nclass TestFitting:\n\n def test_chebfit(self):\n def f(x):\n return x * (x - 1) * (x - 2)\n\n def f2(x):\n return x**4 + x**2 + 1\n\n # Test exceptions\n assert_raises(ValueError, cheb.chebfit, [1], [1], -1)\n assert_raises(TypeError, cheb.chebfit, [[1]], [1], 0)\n assert_raises(TypeError, cheb.chebfit, [], [1], 0)\n assert_raises(TypeError, cheb.chebfit, [1], [[[1]]], 0)\n assert_raises(TypeError, cheb.chebfit, [1, 2], [1], 0)\n assert_raises(TypeError, cheb.chebfit, [1], [1, 2], 0)\n assert_raises(TypeError, cheb.chebfit, [1], [1], 0, w=[[1]])\n assert_raises(TypeError, cheb.chebfit, [1], [1], 0, w=[1, 1])\n assert_raises(ValueError, cheb.chebfit, [1], [1], [-1,])\n assert_raises(ValueError, cheb.chebfit, [1], [1], [2, -1, 6])\n assert_raises(TypeError, cheb.chebfit, [1], [1], [])\n\n # Test fit\n x = np.linspace(0, 2)\n y = f(x)\n #\n coef3 = cheb.chebfit(x, y, 3)\n assert_equal(len(coef3), 4)\n assert_almost_equal(cheb.chebval(x, coef3), y)\n coef3 = cheb.chebfit(x, y, [0, 1, 2, 3])\n assert_equal(len(coef3), 4)\n assert_almost_equal(cheb.chebval(x, coef3), y)\n #\n coef4 = cheb.chebfit(x, y, 4)\n assert_equal(len(coef4), 5)\n assert_almost_equal(cheb.chebval(x, coef4), y)\n coef4 = cheb.chebfit(x, y, [0, 1, 2, 3, 4])\n assert_equal(len(coef4), 5)\n assert_almost_equal(cheb.chebval(x, coef4), y)\n # check things still work if deg is not in strict increasing\n coef4 = cheb.chebfit(x, y, [2, 3, 4, 1, 0])\n assert_equal(len(coef4), 5)\n assert_almost_equal(cheb.chebval(x, coef4), y)\n #\n coef2d = cheb.chebfit(x, np.array([y, y]).T, 3)\n assert_almost_equal(coef2d, np.array([coef3, coef3]).T)\n coef2d = cheb.chebfit(x, np.array([y, y]).T, [0, 1, 2, 3])\n assert_almost_equal(coef2d, np.array([coef3, coef3]).T)\n # test weighting\n w = np.zeros_like(x)\n yw = y.copy()\n w[1::2] = 1\n y[0::2] = 0\n wcoef3 = cheb.chebfit(x, yw, 3, w=w)\n assert_almost_equal(wcoef3, coef3)\n wcoef3 = cheb.chebfit(x, yw, [0, 1, 2, 3], w=w)\n assert_almost_equal(wcoef3, coef3)\n #\n wcoef2d = cheb.chebfit(x, np.array([yw, yw]).T, 3, w=w)\n assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)\n wcoef2d = cheb.chebfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)\n assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)\n # test scaling with complex values x points whose square\n # is zero when summed.\n x = [1, 1j, -1, -1j]\n assert_almost_equal(cheb.chebfit(x, x, 1), [0, 1])\n assert_almost_equal(cheb.chebfit(x, x, [0, 1]), [0, 1])\n # test fitting only even polynomials\n x = np.linspace(-1, 1)\n y = f2(x)\n coef1 = cheb.chebfit(x, y, 4)\n assert_almost_equal(cheb.chebval(x, coef1), y)\n coef2 = cheb.chebfit(x, y, [0, 2, 4])\n assert_almost_equal(cheb.chebval(x, coef2), y)\n assert_almost_equal(coef1, coef2)\n\n\nclass TestInterpolate:\n\n def f(self, x):\n return x * (x - 1) * (x - 2)\n\n def test_raises(self):\n assert_raises(ValueError, cheb.chebinterpolate, self.f, -1)\n assert_raises(TypeError, cheb.chebinterpolate, self.f, 10.)\n\n def test_dimensions(self):\n for deg in range(1, 5):\n assert_(cheb.chebinterpolate(self.f, deg).shape == (deg + 1,))\n\n def test_approximation(self):\n\n def powx(x, p):\n return x**p\n\n x = np.linspace(-1, 1, 10)\n for deg in range(10):\n for p in range(deg + 1):\n c = cheb.chebinterpolate(powx, deg, (p,))\n assert_almost_equal(cheb.chebval(x, c), powx(x, p), decimal=12)\n\n\nclass TestCompanion:\n\n def test_raises(self):\n assert_raises(ValueError, cheb.chebcompanion, [])\n assert_raises(ValueError, cheb.chebcompanion, [1])\n\n def test_dimensions(self):\n for i in range(1, 5):\n coef = [0] * i + [1]\n assert_(cheb.chebcompanion(coef).shape == (i, i))\n\n def test_linear_root(self):\n assert_(cheb.chebcompanion([1, 2])[0, 0] == -.5)\n\n\nclass TestGauss:\n\n def test_100(self):\n x, w = cheb.chebgauss(100)\n\n # test orthogonality. Note that the results need to be normalized,\n # otherwise the huge values that can arise from fast growing\n # functions like Laguerre can be very confusing.\n v = cheb.chebvander(x, 99)\n vv = np.dot(v.T * w, v)\n vd = 1 / np.sqrt(vv.diagonal())\n vv = vd[:, None] * vv * vd\n assert_almost_equal(vv, np.eye(100))\n\n # check that the integral of 1 is correct\n tgt = np.pi\n assert_almost_equal(w.sum(), tgt)\n\n\nclass TestMisc:\n\n def test_chebfromroots(self):\n res = cheb.chebfromroots([])\n assert_almost_equal(trim(res), [1])\n for i in range(1, 5):\n roots = np.cos(np.linspace(-np.pi, 0, 2 * i + 1)[1::2])\n tgt = [0] * i + [1]\n res = cheb.chebfromroots(roots) * 2**(i - 1)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_chebroots(self):\n assert_almost_equal(cheb.chebroots([1]), [])\n assert_almost_equal(cheb.chebroots([1, 2]), [-.5])\n for i in range(2, 5):\n tgt = np.linspace(-1, 1, i)\n res = cheb.chebroots(cheb.chebfromroots(tgt))\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_chebtrim(self):\n coef = [2, -1, 1, 0]\n\n # Test exceptions\n assert_raises(ValueError, cheb.chebtrim, coef, -1)\n\n # Test results\n assert_equal(cheb.chebtrim(coef), coef[:-1])\n assert_equal(cheb.chebtrim(coef, 1), coef[:-3])\n assert_equal(cheb.chebtrim(coef, 2), [0])\n\n def test_chebline(self):\n assert_equal(cheb.chebline(3, 4), [3, 4])\n\n def test_cheb2poly(self):\n for i in range(10):\n assert_almost_equal(cheb.cheb2poly([0] * i + [1]), Tlist[i])\n\n def test_poly2cheb(self):\n for i in range(10):\n assert_almost_equal(cheb.poly2cheb(Tlist[i]), [0] * i + [1])\n\n def test_weight(self):\n x = np.linspace(-1, 1, 11)[1:-1]\n tgt = 1. / (np.sqrt(1 + x) * np.sqrt(1 - x))\n res = cheb.chebweight(x)\n assert_almost_equal(res, tgt)\n\n def test_chebpts1(self):\n # test exceptions\n assert_raises(ValueError, cheb.chebpts1, 1.5)\n assert_raises(ValueError, cheb.chebpts1, 0)\n\n # test points\n tgt = [0]\n assert_almost_equal(cheb.chebpts1(1), tgt)\n tgt = [-0.70710678118654746, 0.70710678118654746]\n assert_almost_equal(cheb.chebpts1(2), tgt)\n tgt = [-0.86602540378443871, 0, 0.86602540378443871]\n assert_almost_equal(cheb.chebpts1(3), tgt)\n tgt = [-0.9238795325, -0.3826834323, 0.3826834323, 0.9238795325]\n assert_almost_equal(cheb.chebpts1(4), tgt)\n\n def test_chebpts2(self):\n # test exceptions\n assert_raises(ValueError, cheb.chebpts2, 1.5)\n assert_raises(ValueError, cheb.chebpts2, 1)\n\n # test points\n tgt = [-1, 1]\n assert_almost_equal(cheb.chebpts2(2), tgt)\n tgt = [-1, 0, 1]\n assert_almost_equal(cheb.chebpts2(3), tgt)\n tgt = [-1, -0.5, .5, 1]\n assert_almost_equal(cheb.chebpts2(4), tgt)\n tgt = [-1.0, -0.707106781187, 0, 0.707106781187, 1.0]\n assert_almost_equal(cheb.chebpts2(5), tgt)\n | .venv\Lib\site-packages\numpy\polynomial\tests\test_chebyshev.py | test_chebyshev.py | Python | 21,273 | 0.95 | 0.186196 | 0.114398 | vue-tools | 719 | 2024-04-06T08:14:00.453497 | MIT | true | 5456674811bcd2af436cf3c0ef10bdbd |
"""Test inter-conversion of different polynomial classes.\n\nThis tests the convert and cast methods of all the polynomial classes.\n\n"""\nimport operator as op\nfrom numbers import Number\n\nimport pytest\n\nimport numpy as np\nfrom numpy.exceptions import RankWarning\nfrom numpy.polynomial import (\n Chebyshev,\n Hermite,\n HermiteE,\n Laguerre,\n Legendre,\n Polynomial,\n)\nfrom numpy.testing import (\n assert_,\n assert_almost_equal,\n assert_equal,\n assert_raises,\n)\n\n#\n# fixtures\n#\n\nclasses = (\n Polynomial, Legendre, Chebyshev, Laguerre,\n Hermite, HermiteE\n )\nclassids = tuple(cls.__name__ for cls in classes)\n\n@pytest.fixture(params=classes, ids=classids)\ndef Poly(request):\n return request.param\n\n\n#\n# helper functions\n#\nrandom = np.random.random\n\n\ndef assert_poly_almost_equal(p1, p2, msg=""):\n try:\n assert_(np.all(p1.domain == p2.domain))\n assert_(np.all(p1.window == p2.window))\n assert_almost_equal(p1.coef, p2.coef)\n except AssertionError:\n msg = f"Result: {p1}\nTarget: {p2}"\n raise AssertionError(msg)\n\n\n#\n# Test conversion methods that depend on combinations of two classes.\n#\n\nPoly1 = Poly\nPoly2 = Poly\n\n\ndef test_conversion(Poly1, Poly2):\n x = np.linspace(0, 1, 10)\n coef = random((3,))\n\n d1 = Poly1.domain + random((2,)) * .25\n w1 = Poly1.window + random((2,)) * .25\n p1 = Poly1(coef, domain=d1, window=w1)\n\n d2 = Poly2.domain + random((2,)) * .25\n w2 = Poly2.window + random((2,)) * .25\n p2 = p1.convert(kind=Poly2, domain=d2, window=w2)\n\n assert_almost_equal(p2.domain, d2)\n assert_almost_equal(p2.window, w2)\n assert_almost_equal(p2(x), p1(x))\n\n\ndef test_cast(Poly1, Poly2):\n x = np.linspace(0, 1, 10)\n coef = random((3,))\n\n d1 = Poly1.domain + random((2,)) * .25\n w1 = Poly1.window + random((2,)) * .25\n p1 = Poly1(coef, domain=d1, window=w1)\n\n d2 = Poly2.domain + random((2,)) * .25\n w2 = Poly2.window + random((2,)) * .25\n p2 = Poly2.cast(p1, domain=d2, window=w2)\n\n assert_almost_equal(p2.domain, d2)\n assert_almost_equal(p2.window, w2)\n assert_almost_equal(p2(x), p1(x))\n\n\n#\n# test methods that depend on one class\n#\n\n\ndef test_identity(Poly):\n d = Poly.domain + random((2,)) * .25\n w = Poly.window + random((2,)) * .25\n x = np.linspace(d[0], d[1], 11)\n p = Poly.identity(domain=d, window=w)\n assert_equal(p.domain, d)\n assert_equal(p.window, w)\n assert_almost_equal(p(x), x)\n\n\ndef test_basis(Poly):\n d = Poly.domain + random((2,)) * .25\n w = Poly.window + random((2,)) * .25\n p = Poly.basis(5, domain=d, window=w)\n assert_equal(p.domain, d)\n assert_equal(p.window, w)\n assert_equal(p.coef, [0] * 5 + [1])\n\n\ndef test_fromroots(Poly):\n # check that requested roots are zeros of a polynomial\n # of correct degree, domain, and window.\n d = Poly.domain + random((2,)) * .25\n w = Poly.window + random((2,)) * .25\n r = random((5,))\n p1 = Poly.fromroots(r, domain=d, window=w)\n assert_equal(p1.degree(), len(r))\n assert_equal(p1.domain, d)\n assert_equal(p1.window, w)\n assert_almost_equal(p1(r), 0)\n\n # check that polynomial is monic\n pdom = Polynomial.domain\n pwin = Polynomial.window\n p2 = Polynomial.cast(p1, domain=pdom, window=pwin)\n assert_almost_equal(p2.coef[-1], 1)\n\n\ndef test_bad_conditioned_fit(Poly):\n\n x = [0., 0., 1.]\n y = [1., 2., 3.]\n\n # check RankWarning is raised\n with pytest.warns(RankWarning) as record:\n Poly.fit(x, y, 2)\n assert record[0].message.args[0] == "The fit may be poorly conditioned"\n\n\ndef test_fit(Poly):\n\n def f(x):\n return x * (x - 1) * (x - 2)\n x = np.linspace(0, 3)\n y = f(x)\n\n # check default value of domain and window\n p = Poly.fit(x, y, 3)\n assert_almost_equal(p.domain, [0, 3])\n assert_almost_equal(p(x), y)\n assert_equal(p.degree(), 3)\n\n # check with given domains and window\n d = Poly.domain + random((2,)) * .25\n w = Poly.window + random((2,)) * .25\n p = Poly.fit(x, y, 3, domain=d, window=w)\n assert_almost_equal(p(x), y)\n assert_almost_equal(p.domain, d)\n assert_almost_equal(p.window, w)\n p = Poly.fit(x, y, [0, 1, 2, 3], domain=d, window=w)\n assert_almost_equal(p(x), y)\n assert_almost_equal(p.domain, d)\n assert_almost_equal(p.window, w)\n\n # check with class domain default\n p = Poly.fit(x, y, 3, [])\n assert_equal(p.domain, Poly.domain)\n assert_equal(p.window, Poly.window)\n p = Poly.fit(x, y, [0, 1, 2, 3], [])\n assert_equal(p.domain, Poly.domain)\n assert_equal(p.window, Poly.window)\n\n # check that fit accepts weights.\n w = np.zeros_like(x)\n z = y + random(y.shape) * .25\n w[::2] = 1\n p1 = Poly.fit(x[::2], z[::2], 3)\n p2 = Poly.fit(x, z, 3, w=w)\n p3 = Poly.fit(x, z, [0, 1, 2, 3], w=w)\n assert_almost_equal(p1(x), p2(x))\n assert_almost_equal(p2(x), p3(x))\n\n\ndef test_equal(Poly):\n p1 = Poly([1, 2, 3], domain=[0, 1], window=[2, 3])\n p2 = Poly([1, 1, 1], domain=[0, 1], window=[2, 3])\n p3 = Poly([1, 2, 3], domain=[1, 2], window=[2, 3])\n p4 = Poly([1, 2, 3], domain=[0, 1], window=[1, 2])\n assert_(p1 == p1)\n assert_(not p1 == p2)\n assert_(not p1 == p3)\n assert_(not p1 == p4)\n\n\ndef test_not_equal(Poly):\n p1 = Poly([1, 2, 3], domain=[0, 1], window=[2, 3])\n p2 = Poly([1, 1, 1], domain=[0, 1], window=[2, 3])\n p3 = Poly([1, 2, 3], domain=[1, 2], window=[2, 3])\n p4 = Poly([1, 2, 3], domain=[0, 1], window=[1, 2])\n assert_(not p1 != p1)\n assert_(p1 != p2)\n assert_(p1 != p3)\n assert_(p1 != p4)\n\n\ndef test_add(Poly):\n # This checks commutation, not numerical correctness\n c1 = list(random((4,)) + .5)\n c2 = list(random((3,)) + .5)\n p1 = Poly(c1)\n p2 = Poly(c2)\n p3 = p1 + p2\n assert_poly_almost_equal(p2 + p1, p3)\n assert_poly_almost_equal(p1 + c2, p3)\n assert_poly_almost_equal(c2 + p1, p3)\n assert_poly_almost_equal(p1 + tuple(c2), p3)\n assert_poly_almost_equal(tuple(c2) + p1, p3)\n assert_poly_almost_equal(p1 + np.array(c2), p3)\n assert_poly_almost_equal(np.array(c2) + p1, p3)\n assert_raises(TypeError, op.add, p1, Poly([0], domain=Poly.domain + 1))\n assert_raises(TypeError, op.add, p1, Poly([0], window=Poly.window + 1))\n if Poly is Polynomial:\n assert_raises(TypeError, op.add, p1, Chebyshev([0]))\n else:\n assert_raises(TypeError, op.add, p1, Polynomial([0]))\n\n\ndef test_sub(Poly):\n # This checks commutation, not numerical correctness\n c1 = list(random((4,)) + .5)\n c2 = list(random((3,)) + .5)\n p1 = Poly(c1)\n p2 = Poly(c2)\n p3 = p1 - p2\n assert_poly_almost_equal(p2 - p1, -p3)\n assert_poly_almost_equal(p1 - c2, p3)\n assert_poly_almost_equal(c2 - p1, -p3)\n assert_poly_almost_equal(p1 - tuple(c2), p3)\n assert_poly_almost_equal(tuple(c2) - p1, -p3)\n assert_poly_almost_equal(p1 - np.array(c2), p3)\n assert_poly_almost_equal(np.array(c2) - p1, -p3)\n assert_raises(TypeError, op.sub, p1, Poly([0], domain=Poly.domain + 1))\n assert_raises(TypeError, op.sub, p1, Poly([0], window=Poly.window + 1))\n if Poly is Polynomial:\n assert_raises(TypeError, op.sub, p1, Chebyshev([0]))\n else:\n assert_raises(TypeError, op.sub, p1, Polynomial([0]))\n\n\ndef test_mul(Poly):\n c1 = list(random((4,)) + .5)\n c2 = list(random((3,)) + .5)\n p1 = Poly(c1)\n p2 = Poly(c2)\n p3 = p1 * p2\n assert_poly_almost_equal(p2 * p1, p3)\n assert_poly_almost_equal(p1 * c2, p3)\n assert_poly_almost_equal(c2 * p1, p3)\n assert_poly_almost_equal(p1 * tuple(c2), p3)\n assert_poly_almost_equal(tuple(c2) * p1, p3)\n assert_poly_almost_equal(p1 * np.array(c2), p3)\n assert_poly_almost_equal(np.array(c2) * p1, p3)\n assert_poly_almost_equal(p1 * 2, p1 * Poly([2]))\n assert_poly_almost_equal(2 * p1, p1 * Poly([2]))\n assert_raises(TypeError, op.mul, p1, Poly([0], domain=Poly.domain + 1))\n assert_raises(TypeError, op.mul, p1, Poly([0], window=Poly.window + 1))\n if Poly is Polynomial:\n assert_raises(TypeError, op.mul, p1, Chebyshev([0]))\n else:\n assert_raises(TypeError, op.mul, p1, Polynomial([0]))\n\n\ndef test_floordiv(Poly):\n c1 = list(random((4,)) + .5)\n c2 = list(random((3,)) + .5)\n c3 = list(random((2,)) + .5)\n p1 = Poly(c1)\n p2 = Poly(c2)\n p3 = Poly(c3)\n p4 = p1 * p2 + p3\n c4 = list(p4.coef)\n assert_poly_almost_equal(p4 // p2, p1)\n assert_poly_almost_equal(p4 // c2, p1)\n assert_poly_almost_equal(c4 // p2, p1)\n assert_poly_almost_equal(p4 // tuple(c2), p1)\n assert_poly_almost_equal(tuple(c4) // p2, p1)\n assert_poly_almost_equal(p4 // np.array(c2), p1)\n assert_poly_almost_equal(np.array(c4) // p2, p1)\n assert_poly_almost_equal(2 // p2, Poly([0]))\n assert_poly_almost_equal(p2 // 2, 0.5 * p2)\n assert_raises(\n TypeError, op.floordiv, p1, Poly([0], domain=Poly.domain + 1))\n assert_raises(\n TypeError, op.floordiv, p1, Poly([0], window=Poly.window + 1))\n if Poly is Polynomial:\n assert_raises(TypeError, op.floordiv, p1, Chebyshev([0]))\n else:\n assert_raises(TypeError, op.floordiv, p1, Polynomial([0]))\n\n\ndef test_truediv(Poly):\n # true division is valid only if the denominator is a Number and\n # not a python bool.\n p1 = Poly([1, 2, 3])\n p2 = p1 * 5\n\n for stype in np.ScalarType:\n if not issubclass(stype, Number) or issubclass(stype, bool):\n continue\n s = stype(5)\n assert_poly_almost_equal(op.truediv(p2, s), p1)\n assert_raises(TypeError, op.truediv, s, p2)\n for stype in (int, float):\n s = stype(5)\n assert_poly_almost_equal(op.truediv(p2, s), p1)\n assert_raises(TypeError, op.truediv, s, p2)\n for stype in [complex]:\n s = stype(5, 0)\n assert_poly_almost_equal(op.truediv(p2, s), p1)\n assert_raises(TypeError, op.truediv, s, p2)\n for s in [(), [], {}, False, np.array([1])]:\n assert_raises(TypeError, op.truediv, p2, s)\n assert_raises(TypeError, op.truediv, s, p2)\n for ptype in classes:\n assert_raises(TypeError, op.truediv, p2, ptype(1))\n\n\ndef test_mod(Poly):\n # This checks commutation, not numerical correctness\n c1 = list(random((4,)) + .5)\n c2 = list(random((3,)) + .5)\n c3 = list(random((2,)) + .5)\n p1 = Poly(c1)\n p2 = Poly(c2)\n p3 = Poly(c3)\n p4 = p1 * p2 + p3\n c4 = list(p4.coef)\n assert_poly_almost_equal(p4 % p2, p3)\n assert_poly_almost_equal(p4 % c2, p3)\n assert_poly_almost_equal(c4 % p2, p3)\n assert_poly_almost_equal(p4 % tuple(c2), p3)\n assert_poly_almost_equal(tuple(c4) % p2, p3)\n assert_poly_almost_equal(p4 % np.array(c2), p3)\n assert_poly_almost_equal(np.array(c4) % p2, p3)\n assert_poly_almost_equal(2 % p2, Poly([2]))\n assert_poly_almost_equal(p2 % 2, Poly([0]))\n assert_raises(TypeError, op.mod, p1, Poly([0], domain=Poly.domain + 1))\n assert_raises(TypeError, op.mod, p1, Poly([0], window=Poly.window + 1))\n if Poly is Polynomial:\n assert_raises(TypeError, op.mod, p1, Chebyshev([0]))\n else:\n assert_raises(TypeError, op.mod, p1, Polynomial([0]))\n\n\ndef test_divmod(Poly):\n # This checks commutation, not numerical correctness\n c1 = list(random((4,)) + .5)\n c2 = list(random((3,)) + .5)\n c3 = list(random((2,)) + .5)\n p1 = Poly(c1)\n p2 = Poly(c2)\n p3 = Poly(c3)\n p4 = p1 * p2 + p3\n c4 = list(p4.coef)\n quo, rem = divmod(p4, p2)\n assert_poly_almost_equal(quo, p1)\n assert_poly_almost_equal(rem, p3)\n quo, rem = divmod(p4, c2)\n assert_poly_almost_equal(quo, p1)\n assert_poly_almost_equal(rem, p3)\n quo, rem = divmod(c4, p2)\n assert_poly_almost_equal(quo, p1)\n assert_poly_almost_equal(rem, p3)\n quo, rem = divmod(p4, tuple(c2))\n assert_poly_almost_equal(quo, p1)\n assert_poly_almost_equal(rem, p3)\n quo, rem = divmod(tuple(c4), p2)\n assert_poly_almost_equal(quo, p1)\n assert_poly_almost_equal(rem, p3)\n quo, rem = divmod(p4, np.array(c2))\n assert_poly_almost_equal(quo, p1)\n assert_poly_almost_equal(rem, p3)\n quo, rem = divmod(np.array(c4), p2)\n assert_poly_almost_equal(quo, p1)\n assert_poly_almost_equal(rem, p3)\n quo, rem = divmod(p2, 2)\n assert_poly_almost_equal(quo, 0.5 * p2)\n assert_poly_almost_equal(rem, Poly([0]))\n quo, rem = divmod(2, p2)\n assert_poly_almost_equal(quo, Poly([0]))\n assert_poly_almost_equal(rem, Poly([2]))\n assert_raises(TypeError, divmod, p1, Poly([0], domain=Poly.domain + 1))\n assert_raises(TypeError, divmod, p1, Poly([0], window=Poly.window + 1))\n if Poly is Polynomial:\n assert_raises(TypeError, divmod, p1, Chebyshev([0]))\n else:\n assert_raises(TypeError, divmod, p1, Polynomial([0]))\n\n\ndef test_roots(Poly):\n d = Poly.domain * 1.25 + .25\n w = Poly.window\n tgt = np.linspace(d[0], d[1], 5)\n res = np.sort(Poly.fromroots(tgt, domain=d, window=w).roots())\n assert_almost_equal(res, tgt)\n # default domain and window\n res = np.sort(Poly.fromroots(tgt).roots())\n assert_almost_equal(res, tgt)\n\n\ndef test_degree(Poly):\n p = Poly.basis(5)\n assert_equal(p.degree(), 5)\n\n\ndef test_copy(Poly):\n p1 = Poly.basis(5)\n p2 = p1.copy()\n assert_(p1 == p2)\n assert_(p1 is not p2)\n assert_(p1.coef is not p2.coef)\n assert_(p1.domain is not p2.domain)\n assert_(p1.window is not p2.window)\n\n\ndef test_integ(Poly):\n P = Polynomial\n # Check defaults\n p0 = Poly.cast(P([1 * 2, 2 * 3, 3 * 4]))\n p1 = P.cast(p0.integ())\n p2 = P.cast(p0.integ(2))\n assert_poly_almost_equal(p1, P([0, 2, 3, 4]))\n assert_poly_almost_equal(p2, P([0, 0, 1, 1, 1]))\n # Check with k\n p0 = Poly.cast(P([1 * 2, 2 * 3, 3 * 4]))\n p1 = P.cast(p0.integ(k=1))\n p2 = P.cast(p0.integ(2, k=[1, 1]))\n assert_poly_almost_equal(p1, P([1, 2, 3, 4]))\n assert_poly_almost_equal(p2, P([1, 1, 1, 1, 1]))\n # Check with lbnd\n p0 = Poly.cast(P([1 * 2, 2 * 3, 3 * 4]))\n p1 = P.cast(p0.integ(lbnd=1))\n p2 = P.cast(p0.integ(2, lbnd=1))\n assert_poly_almost_equal(p1, P([-9, 2, 3, 4]))\n assert_poly_almost_equal(p2, P([6, -9, 1, 1, 1]))\n # Check scaling\n d = 2 * Poly.domain\n p0 = Poly.cast(P([1 * 2, 2 * 3, 3 * 4]), domain=d)\n p1 = P.cast(p0.integ())\n p2 = P.cast(p0.integ(2))\n assert_poly_almost_equal(p1, P([0, 2, 3, 4]))\n assert_poly_almost_equal(p2, P([0, 0, 1, 1, 1]))\n\n\ndef test_deriv(Poly):\n # Check that the derivative is the inverse of integration. It is\n # assumes that the integration has been checked elsewhere.\n d = Poly.domain + random((2,)) * .25\n w = Poly.window + random((2,)) * .25\n p1 = Poly([1, 2, 3], domain=d, window=w)\n p2 = p1.integ(2, k=[1, 2])\n p3 = p1.integ(1, k=[1])\n assert_almost_equal(p2.deriv(1).coef, p3.coef)\n assert_almost_equal(p2.deriv(2).coef, p1.coef)\n # default domain and window\n p1 = Poly([1, 2, 3])\n p2 = p1.integ(2, k=[1, 2])\n p3 = p1.integ(1, k=[1])\n assert_almost_equal(p2.deriv(1).coef, p3.coef)\n assert_almost_equal(p2.deriv(2).coef, p1.coef)\n\n\ndef test_linspace(Poly):\n d = Poly.domain + random((2,)) * .25\n w = Poly.window + random((2,)) * .25\n p = Poly([1, 2, 3], domain=d, window=w)\n # check default domain\n xtgt = np.linspace(d[0], d[1], 20)\n ytgt = p(xtgt)\n xres, yres = p.linspace(20)\n assert_almost_equal(xres, xtgt)\n assert_almost_equal(yres, ytgt)\n # check specified domain\n xtgt = np.linspace(0, 2, 20)\n ytgt = p(xtgt)\n xres, yres = p.linspace(20, domain=[0, 2])\n assert_almost_equal(xres, xtgt)\n assert_almost_equal(yres, ytgt)\n\n\ndef test_pow(Poly):\n d = Poly.domain + random((2,)) * .25\n w = Poly.window + random((2,)) * .25\n tgt = Poly([1], domain=d, window=w)\n tst = Poly([1, 2, 3], domain=d, window=w)\n for i in range(5):\n assert_poly_almost_equal(tst**i, tgt)\n tgt = tgt * tst\n # default domain and window\n tgt = Poly([1])\n tst = Poly([1, 2, 3])\n for i in range(5):\n assert_poly_almost_equal(tst**i, tgt)\n tgt = tgt * tst\n # check error for invalid powers\n assert_raises(ValueError, op.pow, tgt, 1.5)\n assert_raises(ValueError, op.pow, tgt, -1)\n\n\ndef test_call(Poly):\n P = Polynomial\n d = Poly.domain\n x = np.linspace(d[0], d[1], 11)\n\n # Check defaults\n p = Poly.cast(P([1, 2, 3]))\n tgt = 1 + x * (2 + 3 * x)\n res = p(x)\n assert_almost_equal(res, tgt)\n\n\ndef test_call_with_list(Poly):\n p = Poly([1, 2, 3])\n x = [-1, 0, 2]\n res = p(x)\n assert_equal(res, p(np.array(x)))\n\n\ndef test_cutdeg(Poly):\n p = Poly([1, 2, 3])\n assert_raises(ValueError, p.cutdeg, .5)\n assert_raises(ValueError, p.cutdeg, -1)\n assert_equal(len(p.cutdeg(3)), 3)\n assert_equal(len(p.cutdeg(2)), 3)\n assert_equal(len(p.cutdeg(1)), 2)\n assert_equal(len(p.cutdeg(0)), 1)\n\n\ndef test_truncate(Poly):\n p = Poly([1, 2, 3])\n assert_raises(ValueError, p.truncate, .5)\n assert_raises(ValueError, p.truncate, 0)\n assert_equal(len(p.truncate(4)), 3)\n assert_equal(len(p.truncate(3)), 3)\n assert_equal(len(p.truncate(2)), 2)\n assert_equal(len(p.truncate(1)), 1)\n\n\ndef test_trim(Poly):\n c = [1, 1e-6, 1e-12, 0]\n p = Poly(c)\n assert_equal(p.trim().coef, c[:3])\n assert_equal(p.trim(1e-10).coef, c[:2])\n assert_equal(p.trim(1e-5).coef, c[:1])\n\n\ndef test_mapparms(Poly):\n # check with defaults. Should be identity.\n d = Poly.domain\n w = Poly.window\n p = Poly([1], domain=d, window=w)\n assert_almost_equal([0, 1], p.mapparms())\n #\n w = 2 * d + 1\n p = Poly([1], domain=d, window=w)\n assert_almost_equal([1, 2], p.mapparms())\n\n\ndef test_ufunc_override(Poly):\n p = Poly([1, 2, 3])\n x = np.ones(3)\n assert_raises(TypeError, np.add, p, x)\n assert_raises(TypeError, np.add, x, p)\n\n\n#\n# Test class method that only exists for some classes\n#\n\n\nclass TestInterpolate:\n\n def f(self, x):\n return x * (x - 1) * (x - 2)\n\n def test_raises(self):\n assert_raises(ValueError, Chebyshev.interpolate, self.f, -1)\n assert_raises(TypeError, Chebyshev.interpolate, self.f, 10.)\n\n def test_dimensions(self):\n for deg in range(1, 5):\n assert_(Chebyshev.interpolate(self.f, deg).degree() == deg)\n\n def test_approximation(self):\n\n def powx(x, p):\n return x**p\n\n x = np.linspace(0, 2, 10)\n for deg in range(10):\n for t in range(deg + 1):\n p = Chebyshev.interpolate(powx, deg, domain=[0, 2], args=(t,))\n assert_almost_equal(p(x), powx(x, t), decimal=11)\n | .venv\Lib\site-packages\numpy\polynomial\tests\test_classes.py | test_classes.py | Python | 19,170 | 0.95 | 0.10356 | 0.085271 | node-utils | 994 | 2024-09-28T19:51:11.453861 | Apache-2.0 | true | 7fcbcb38f4b422cdaf02d03dfc7e0898 |
"""Tests for hermite module.\n\n"""\nfrom functools import reduce\n\nimport numpy as np\nimport numpy.polynomial.hermite as herm\nfrom numpy.polynomial.polynomial import polyval\nfrom numpy.testing import (\n assert_,\n assert_almost_equal,\n assert_equal,\n assert_raises,\n)\n\nH0 = np.array([1])\nH1 = np.array([0, 2])\nH2 = np.array([-2, 0, 4])\nH3 = np.array([0, -12, 0, 8])\nH4 = np.array([12, 0, -48, 0, 16])\nH5 = np.array([0, 120, 0, -160, 0, 32])\nH6 = np.array([-120, 0, 720, 0, -480, 0, 64])\nH7 = np.array([0, -1680, 0, 3360, 0, -1344, 0, 128])\nH8 = np.array([1680, 0, -13440, 0, 13440, 0, -3584, 0, 256])\nH9 = np.array([0, 30240, 0, -80640, 0, 48384, 0, -9216, 0, 512])\n\nHlist = [H0, H1, H2, H3, H4, H5, H6, H7, H8, H9]\n\n\ndef trim(x):\n return herm.hermtrim(x, tol=1e-6)\n\n\nclass TestConstants:\n\n def test_hermdomain(self):\n assert_equal(herm.hermdomain, [-1, 1])\n\n def test_hermzero(self):\n assert_equal(herm.hermzero, [0])\n\n def test_hermone(self):\n assert_equal(herm.hermone, [1])\n\n def test_hermx(self):\n assert_equal(herm.hermx, [0, .5])\n\n\nclass TestArithmetic:\n x = np.linspace(-3, 3, 100)\n\n def test_hermadd(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n tgt = np.zeros(max(i, j) + 1)\n tgt[i] += 1\n tgt[j] += 1\n res = herm.hermadd([0] * i + [1], [0] * j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_hermsub(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n tgt = np.zeros(max(i, j) + 1)\n tgt[i] += 1\n tgt[j] -= 1\n res = herm.hermsub([0] * i + [1], [0] * j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_hermmulx(self):\n assert_equal(herm.hermmulx([0]), [0])\n assert_equal(herm.hermmulx([1]), [0, .5])\n for i in range(1, 5):\n ser = [0] * i + [1]\n tgt = [0] * (i - 1) + [i, 0, .5]\n assert_equal(herm.hermmulx(ser), tgt)\n\n def test_hermmul(self):\n # check values of result\n for i in range(5):\n pol1 = [0] * i + [1]\n val1 = herm.hermval(self.x, pol1)\n for j in range(5):\n msg = f"At i={i}, j={j}"\n pol2 = [0] * j + [1]\n val2 = herm.hermval(self.x, pol2)\n pol3 = herm.hermmul(pol1, pol2)\n val3 = herm.hermval(self.x, pol3)\n assert_(len(pol3) == i + j + 1, msg)\n assert_almost_equal(val3, val1 * val2, err_msg=msg)\n\n def test_hermdiv(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n ci = [0] * i + [1]\n cj = [0] * j + [1]\n tgt = herm.hermadd(ci, cj)\n quo, rem = herm.hermdiv(tgt, ci)\n res = herm.hermadd(herm.hermmul(quo, ci), rem)\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_hermpow(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n c = np.arange(i + 1)\n tgt = reduce(herm.hermmul, [c] * j, np.array([1]))\n res = herm.hermpow(c, j)\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n\nclass TestEvaluation:\n # coefficients of 1 + 2*x + 3*x**2\n c1d = np.array([2.5, 1., .75])\n c2d = np.einsum('i,j->ij', c1d, c1d)\n c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)\n\n # some random values in [-1, 1)\n x = np.random.random((3, 5)) * 2 - 1\n y = polyval(x, [1., 2., 3.])\n\n def test_hermval(self):\n # check empty input\n assert_equal(herm.hermval([], [1]).size, 0)\n\n # check normal input)\n x = np.linspace(-1, 1)\n y = [polyval(x, c) for c in Hlist]\n for i in range(10):\n msg = f"At i={i}"\n tgt = y[i]\n res = herm.hermval(x, [0] * i + [1])\n assert_almost_equal(res, tgt, err_msg=msg)\n\n # check that shape is preserved\n for i in range(3):\n dims = [2] * i\n x = np.zeros(dims)\n assert_equal(herm.hermval(x, [1]).shape, dims)\n assert_equal(herm.hermval(x, [1, 0]).shape, dims)\n assert_equal(herm.hermval(x, [1, 0, 0]).shape, dims)\n\n def test_hermval2d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test exceptions\n assert_raises(ValueError, herm.hermval2d, x1, x2[:2], self.c2d)\n\n # test values\n tgt = y1 * y2\n res = herm.hermval2d(x1, x2, self.c2d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = herm.hermval2d(z, z, self.c2d)\n assert_(res.shape == (2, 3))\n\n def test_hermval3d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test exceptions\n assert_raises(ValueError, herm.hermval3d, x1, x2, x3[:2], self.c3d)\n\n # test values\n tgt = y1 * y2 * y3\n res = herm.hermval3d(x1, x2, x3, self.c3d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = herm.hermval3d(z, z, z, self.c3d)\n assert_(res.shape == (2, 3))\n\n def test_hermgrid2d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test values\n tgt = np.einsum('i,j->ij', y1, y2)\n res = herm.hermgrid2d(x1, x2, self.c2d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = herm.hermgrid2d(z, z, self.c2d)\n assert_(res.shape == (2, 3) * 2)\n\n def test_hermgrid3d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test values\n tgt = np.einsum('i,j,k->ijk', y1, y2, y3)\n res = herm.hermgrid3d(x1, x2, x3, self.c3d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = herm.hermgrid3d(z, z, z, self.c3d)\n assert_(res.shape == (2, 3) * 3)\n\n\nclass TestIntegral:\n\n def test_hermint(self):\n # check exceptions\n assert_raises(TypeError, herm.hermint, [0], .5)\n assert_raises(ValueError, herm.hermint, [0], -1)\n assert_raises(ValueError, herm.hermint, [0], 1, [0, 0])\n assert_raises(ValueError, herm.hermint, [0], lbnd=[0])\n assert_raises(ValueError, herm.hermint, [0], scl=[0])\n assert_raises(TypeError, herm.hermint, [0], axis=.5)\n\n # test integration of zero polynomial\n for i in range(2, 5):\n k = [0] * (i - 2) + [1]\n res = herm.hermint([0], m=i, k=k)\n assert_almost_equal(res, [0, .5])\n\n # check single integration with integration constant\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n tgt = [i] + [0] * i + [1 / scl]\n hermpol = herm.poly2herm(pol)\n hermint = herm.hermint(hermpol, m=1, k=[i])\n res = herm.herm2poly(hermint)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check single integration with integration constant and lbnd\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n hermpol = herm.poly2herm(pol)\n hermint = herm.hermint(hermpol, m=1, k=[i], lbnd=-1)\n assert_almost_equal(herm.hermval(-1, hermint), i)\n\n # check single integration with integration constant and scaling\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n tgt = [i] + [0] * i + [2 / scl]\n hermpol = herm.poly2herm(pol)\n hermint = herm.hermint(hermpol, m=1, k=[i], scl=2)\n res = herm.herm2poly(hermint)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with default k\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = herm.hermint(tgt, m=1)\n res = herm.hermint(pol, m=j)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with defined k\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = herm.hermint(tgt, m=1, k=[k])\n res = herm.hermint(pol, m=j, k=list(range(j)))\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with lbnd\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = herm.hermint(tgt, m=1, k=[k], lbnd=-1)\n res = herm.hermint(pol, m=j, k=list(range(j)), lbnd=-1)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with scaling\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = herm.hermint(tgt, m=1, k=[k], scl=2)\n res = herm.hermint(pol, m=j, k=list(range(j)), scl=2)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_hermint_axis(self):\n # check that axis keyword works\n c2d = np.random.random((3, 4))\n\n tgt = np.vstack([herm.hermint(c) for c in c2d.T]).T\n res = herm.hermint(c2d, axis=0)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([herm.hermint(c) for c in c2d])\n res = herm.hermint(c2d, axis=1)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([herm.hermint(c, k=3) for c in c2d])\n res = herm.hermint(c2d, k=3, axis=1)\n assert_almost_equal(res, tgt)\n\n\nclass TestDerivative:\n\n def test_hermder(self):\n # check exceptions\n assert_raises(TypeError, herm.hermder, [0], .5)\n assert_raises(ValueError, herm.hermder, [0], -1)\n\n # check that zeroth derivative does nothing\n for i in range(5):\n tgt = [0] * i + [1]\n res = herm.hermder(tgt, m=0)\n assert_equal(trim(res), trim(tgt))\n\n # check that derivation is the inverse of integration\n for i in range(5):\n for j in range(2, 5):\n tgt = [0] * i + [1]\n res = herm.hermder(herm.hermint(tgt, m=j), m=j)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check derivation with scaling\n for i in range(5):\n for j in range(2, 5):\n tgt = [0] * i + [1]\n res = herm.hermder(herm.hermint(tgt, m=j, scl=2), m=j, scl=.5)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_hermder_axis(self):\n # check that axis keyword works\n c2d = np.random.random((3, 4))\n\n tgt = np.vstack([herm.hermder(c) for c in c2d.T]).T\n res = herm.hermder(c2d, axis=0)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([herm.hermder(c) for c in c2d])\n res = herm.hermder(c2d, axis=1)\n assert_almost_equal(res, tgt)\n\n\nclass TestVander:\n # some random values in [-1, 1)\n x = np.random.random((3, 5)) * 2 - 1\n\n def test_hermvander(self):\n # check for 1d x\n x = np.arange(3)\n v = herm.hermvander(x, 3)\n assert_(v.shape == (3, 4))\n for i in range(4):\n coef = [0] * i + [1]\n assert_almost_equal(v[..., i], herm.hermval(x, coef))\n\n # check for 2d x\n x = np.array([[1, 2], [3, 4], [5, 6]])\n v = herm.hermvander(x, 3)\n assert_(v.shape == (3, 2, 4))\n for i in range(4):\n coef = [0] * i + [1]\n assert_almost_equal(v[..., i], herm.hermval(x, coef))\n\n def test_hermvander2d(self):\n # also tests hermval2d for non-square coefficient array\n x1, x2, x3 = self.x\n c = np.random.random((2, 3))\n van = herm.hermvander2d(x1, x2, [1, 2])\n tgt = herm.hermval2d(x1, x2, c)\n res = np.dot(van, c.flat)\n assert_almost_equal(res, tgt)\n\n # check shape\n van = herm.hermvander2d([x1], [x2], [1, 2])\n assert_(van.shape == (1, 5, 6))\n\n def test_hermvander3d(self):\n # also tests hermval3d for non-square coefficient array\n x1, x2, x3 = self.x\n c = np.random.random((2, 3, 4))\n van = herm.hermvander3d(x1, x2, x3, [1, 2, 3])\n tgt = herm.hermval3d(x1, x2, x3, c)\n res = np.dot(van, c.flat)\n assert_almost_equal(res, tgt)\n\n # check shape\n van = herm.hermvander3d([x1], [x2], [x3], [1, 2, 3])\n assert_(van.shape == (1, 5, 24))\n\n\nclass TestFitting:\n\n def test_hermfit(self):\n def f(x):\n return x * (x - 1) * (x - 2)\n\n def f2(x):\n return x**4 + x**2 + 1\n\n # Test exceptions\n assert_raises(ValueError, herm.hermfit, [1], [1], -1)\n assert_raises(TypeError, herm.hermfit, [[1]], [1], 0)\n assert_raises(TypeError, herm.hermfit, [], [1], 0)\n assert_raises(TypeError, herm.hermfit, [1], [[[1]]], 0)\n assert_raises(TypeError, herm.hermfit, [1, 2], [1], 0)\n assert_raises(TypeError, herm.hermfit, [1], [1, 2], 0)\n assert_raises(TypeError, herm.hermfit, [1], [1], 0, w=[[1]])\n assert_raises(TypeError, herm.hermfit, [1], [1], 0, w=[1, 1])\n assert_raises(ValueError, herm.hermfit, [1], [1], [-1,])\n assert_raises(ValueError, herm.hermfit, [1], [1], [2, -1, 6])\n assert_raises(TypeError, herm.hermfit, [1], [1], [])\n\n # Test fit\n x = np.linspace(0, 2)\n y = f(x)\n #\n coef3 = herm.hermfit(x, y, 3)\n assert_equal(len(coef3), 4)\n assert_almost_equal(herm.hermval(x, coef3), y)\n coef3 = herm.hermfit(x, y, [0, 1, 2, 3])\n assert_equal(len(coef3), 4)\n assert_almost_equal(herm.hermval(x, coef3), y)\n #\n coef4 = herm.hermfit(x, y, 4)\n assert_equal(len(coef4), 5)\n assert_almost_equal(herm.hermval(x, coef4), y)\n coef4 = herm.hermfit(x, y, [0, 1, 2, 3, 4])\n assert_equal(len(coef4), 5)\n assert_almost_equal(herm.hermval(x, coef4), y)\n # check things still work if deg is not in strict increasing\n coef4 = herm.hermfit(x, y, [2, 3, 4, 1, 0])\n assert_equal(len(coef4), 5)\n assert_almost_equal(herm.hermval(x, coef4), y)\n #\n coef2d = herm.hermfit(x, np.array([y, y]).T, 3)\n assert_almost_equal(coef2d, np.array([coef3, coef3]).T)\n coef2d = herm.hermfit(x, np.array([y, y]).T, [0, 1, 2, 3])\n assert_almost_equal(coef2d, np.array([coef3, coef3]).T)\n # test weighting\n w = np.zeros_like(x)\n yw = y.copy()\n w[1::2] = 1\n y[0::2] = 0\n wcoef3 = herm.hermfit(x, yw, 3, w=w)\n assert_almost_equal(wcoef3, coef3)\n wcoef3 = herm.hermfit(x, yw, [0, 1, 2, 3], w=w)\n assert_almost_equal(wcoef3, coef3)\n #\n wcoef2d = herm.hermfit(x, np.array([yw, yw]).T, 3, w=w)\n assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)\n wcoef2d = herm.hermfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)\n assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)\n # test scaling with complex values x points whose square\n # is zero when summed.\n x = [1, 1j, -1, -1j]\n assert_almost_equal(herm.hermfit(x, x, 1), [0, .5])\n assert_almost_equal(herm.hermfit(x, x, [0, 1]), [0, .5])\n # test fitting only even Legendre polynomials\n x = np.linspace(-1, 1)\n y = f2(x)\n coef1 = herm.hermfit(x, y, 4)\n assert_almost_equal(herm.hermval(x, coef1), y)\n coef2 = herm.hermfit(x, y, [0, 2, 4])\n assert_almost_equal(herm.hermval(x, coef2), y)\n assert_almost_equal(coef1, coef2)\n\n\nclass TestCompanion:\n\n def test_raises(self):\n assert_raises(ValueError, herm.hermcompanion, [])\n assert_raises(ValueError, herm.hermcompanion, [1])\n\n def test_dimensions(self):\n for i in range(1, 5):\n coef = [0] * i + [1]\n assert_(herm.hermcompanion(coef).shape == (i, i))\n\n def test_linear_root(self):\n assert_(herm.hermcompanion([1, 2])[0, 0] == -.25)\n\n\nclass TestGauss:\n\n def test_100(self):\n x, w = herm.hermgauss(100)\n\n # test orthogonality. Note that the results need to be normalized,\n # otherwise the huge values that can arise from fast growing\n # functions like Laguerre can be very confusing.\n v = herm.hermvander(x, 99)\n vv = np.dot(v.T * w, v)\n vd = 1 / np.sqrt(vv.diagonal())\n vv = vd[:, None] * vv * vd\n assert_almost_equal(vv, np.eye(100))\n\n # check that the integral of 1 is correct\n tgt = np.sqrt(np.pi)\n assert_almost_equal(w.sum(), tgt)\n\n\nclass TestMisc:\n\n def test_hermfromroots(self):\n res = herm.hermfromroots([])\n assert_almost_equal(trim(res), [1])\n for i in range(1, 5):\n roots = np.cos(np.linspace(-np.pi, 0, 2 * i + 1)[1::2])\n pol = herm.hermfromroots(roots)\n res = herm.hermval(roots, pol)\n tgt = 0\n assert_(len(pol) == i + 1)\n assert_almost_equal(herm.herm2poly(pol)[-1], 1)\n assert_almost_equal(res, tgt)\n\n def test_hermroots(self):\n assert_almost_equal(herm.hermroots([1]), [])\n assert_almost_equal(herm.hermroots([1, 1]), [-.5])\n for i in range(2, 5):\n tgt = np.linspace(-1, 1, i)\n res = herm.hermroots(herm.hermfromroots(tgt))\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_hermtrim(self):\n coef = [2, -1, 1, 0]\n\n # Test exceptions\n assert_raises(ValueError, herm.hermtrim, coef, -1)\n\n # Test results\n assert_equal(herm.hermtrim(coef), coef[:-1])\n assert_equal(herm.hermtrim(coef, 1), coef[:-3])\n assert_equal(herm.hermtrim(coef, 2), [0])\n\n def test_hermline(self):\n assert_equal(herm.hermline(3, 4), [3, 2])\n\n def test_herm2poly(self):\n for i in range(10):\n assert_almost_equal(herm.herm2poly([0] * i + [1]), Hlist[i])\n\n def test_poly2herm(self):\n for i in range(10):\n assert_almost_equal(herm.poly2herm(Hlist[i]), [0] * i + [1])\n\n def test_weight(self):\n x = np.linspace(-5, 5, 11)\n tgt = np.exp(-x**2)\n res = herm.hermweight(x)\n assert_almost_equal(res, tgt)\n | .venv\Lib\site-packages\numpy\polynomial\tests\test_hermite.py | test_hermite.py | Python | 19,245 | 0.95 | 0.179211 | 0.119826 | awesome-app | 300 | 2024-04-22T10:21:35.586156 | BSD-3-Clause | true | 819512e2794b23d0e57b4abda2108e7f |
"""Tests for hermite_e module.\n\n"""\nfrom functools import reduce\n\nimport numpy as np\nimport numpy.polynomial.hermite_e as herme\nfrom numpy.polynomial.polynomial import polyval\nfrom numpy.testing import (\n assert_,\n assert_almost_equal,\n assert_equal,\n assert_raises,\n)\n\nHe0 = np.array([1])\nHe1 = np.array([0, 1])\nHe2 = np.array([-1, 0, 1])\nHe3 = np.array([0, -3, 0, 1])\nHe4 = np.array([3, 0, -6, 0, 1])\nHe5 = np.array([0, 15, 0, -10, 0, 1])\nHe6 = np.array([-15, 0, 45, 0, -15, 0, 1])\nHe7 = np.array([0, -105, 0, 105, 0, -21, 0, 1])\nHe8 = np.array([105, 0, -420, 0, 210, 0, -28, 0, 1])\nHe9 = np.array([0, 945, 0, -1260, 0, 378, 0, -36, 0, 1])\n\nHelist = [He0, He1, He2, He3, He4, He5, He6, He7, He8, He9]\n\n\ndef trim(x):\n return herme.hermetrim(x, tol=1e-6)\n\n\nclass TestConstants:\n\n def test_hermedomain(self):\n assert_equal(herme.hermedomain, [-1, 1])\n\n def test_hermezero(self):\n assert_equal(herme.hermezero, [0])\n\n def test_hermeone(self):\n assert_equal(herme.hermeone, [1])\n\n def test_hermex(self):\n assert_equal(herme.hermex, [0, 1])\n\n\nclass TestArithmetic:\n x = np.linspace(-3, 3, 100)\n\n def test_hermeadd(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n tgt = np.zeros(max(i, j) + 1)\n tgt[i] += 1\n tgt[j] += 1\n res = herme.hermeadd([0] * i + [1], [0] * j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_hermesub(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n tgt = np.zeros(max(i, j) + 1)\n tgt[i] += 1\n tgt[j] -= 1\n res = herme.hermesub([0] * i + [1], [0] * j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_hermemulx(self):\n assert_equal(herme.hermemulx([0]), [0])\n assert_equal(herme.hermemulx([1]), [0, 1])\n for i in range(1, 5):\n ser = [0] * i + [1]\n tgt = [0] * (i - 1) + [i, 0, 1]\n assert_equal(herme.hermemulx(ser), tgt)\n\n def test_hermemul(self):\n # check values of result\n for i in range(5):\n pol1 = [0] * i + [1]\n val1 = herme.hermeval(self.x, pol1)\n for j in range(5):\n msg = f"At i={i}, j={j}"\n pol2 = [0] * j + [1]\n val2 = herme.hermeval(self.x, pol2)\n pol3 = herme.hermemul(pol1, pol2)\n val3 = herme.hermeval(self.x, pol3)\n assert_(len(pol3) == i + j + 1, msg)\n assert_almost_equal(val3, val1 * val2, err_msg=msg)\n\n def test_hermediv(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n ci = [0] * i + [1]\n cj = [0] * j + [1]\n tgt = herme.hermeadd(ci, cj)\n quo, rem = herme.hermediv(tgt, ci)\n res = herme.hermeadd(herme.hermemul(quo, ci), rem)\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_hermepow(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n c = np.arange(i + 1)\n tgt = reduce(herme.hermemul, [c] * j, np.array([1]))\n res = herme.hermepow(c, j)\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n\nclass TestEvaluation:\n # coefficients of 1 + 2*x + 3*x**2\n c1d = np.array([4., 2., 3.])\n c2d = np.einsum('i,j->ij', c1d, c1d)\n c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)\n\n # some random values in [-1, 1)\n x = np.random.random((3, 5)) * 2 - 1\n y = polyval(x, [1., 2., 3.])\n\n def test_hermeval(self):\n # check empty input\n assert_equal(herme.hermeval([], [1]).size, 0)\n\n # check normal input)\n x = np.linspace(-1, 1)\n y = [polyval(x, c) for c in Helist]\n for i in range(10):\n msg = f"At i={i}"\n tgt = y[i]\n res = herme.hermeval(x, [0] * i + [1])\n assert_almost_equal(res, tgt, err_msg=msg)\n\n # check that shape is preserved\n for i in range(3):\n dims = [2] * i\n x = np.zeros(dims)\n assert_equal(herme.hermeval(x, [1]).shape, dims)\n assert_equal(herme.hermeval(x, [1, 0]).shape, dims)\n assert_equal(herme.hermeval(x, [1, 0, 0]).shape, dims)\n\n def test_hermeval2d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test exceptions\n assert_raises(ValueError, herme.hermeval2d, x1, x2[:2], self.c2d)\n\n # test values\n tgt = y1 * y2\n res = herme.hermeval2d(x1, x2, self.c2d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = herme.hermeval2d(z, z, self.c2d)\n assert_(res.shape == (2, 3))\n\n def test_hermeval3d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test exceptions\n assert_raises(ValueError, herme.hermeval3d, x1, x2, x3[:2], self.c3d)\n\n # test values\n tgt = y1 * y2 * y3\n res = herme.hermeval3d(x1, x2, x3, self.c3d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = herme.hermeval3d(z, z, z, self.c3d)\n assert_(res.shape == (2, 3))\n\n def test_hermegrid2d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test values\n tgt = np.einsum('i,j->ij', y1, y2)\n res = herme.hermegrid2d(x1, x2, self.c2d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = herme.hermegrid2d(z, z, self.c2d)\n assert_(res.shape == (2, 3) * 2)\n\n def test_hermegrid3d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test values\n tgt = np.einsum('i,j,k->ijk', y1, y2, y3)\n res = herme.hermegrid3d(x1, x2, x3, self.c3d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = herme.hermegrid3d(z, z, z, self.c3d)\n assert_(res.shape == (2, 3) * 3)\n\n\nclass TestIntegral:\n\n def test_hermeint(self):\n # check exceptions\n assert_raises(TypeError, herme.hermeint, [0], .5)\n assert_raises(ValueError, herme.hermeint, [0], -1)\n assert_raises(ValueError, herme.hermeint, [0], 1, [0, 0])\n assert_raises(ValueError, herme.hermeint, [0], lbnd=[0])\n assert_raises(ValueError, herme.hermeint, [0], scl=[0])\n assert_raises(TypeError, herme.hermeint, [0], axis=.5)\n\n # test integration of zero polynomial\n for i in range(2, 5):\n k = [0] * (i - 2) + [1]\n res = herme.hermeint([0], m=i, k=k)\n assert_almost_equal(res, [0, 1])\n\n # check single integration with integration constant\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n tgt = [i] + [0] * i + [1 / scl]\n hermepol = herme.poly2herme(pol)\n hermeint = herme.hermeint(hermepol, m=1, k=[i])\n res = herme.herme2poly(hermeint)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check single integration with integration constant and lbnd\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n hermepol = herme.poly2herme(pol)\n hermeint = herme.hermeint(hermepol, m=1, k=[i], lbnd=-1)\n assert_almost_equal(herme.hermeval(-1, hermeint), i)\n\n # check single integration with integration constant and scaling\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n tgt = [i] + [0] * i + [2 / scl]\n hermepol = herme.poly2herme(pol)\n hermeint = herme.hermeint(hermepol, m=1, k=[i], scl=2)\n res = herme.herme2poly(hermeint)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with default k\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = herme.hermeint(tgt, m=1)\n res = herme.hermeint(pol, m=j)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with defined k\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = herme.hermeint(tgt, m=1, k=[k])\n res = herme.hermeint(pol, m=j, k=list(range(j)))\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with lbnd\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = herme.hermeint(tgt, m=1, k=[k], lbnd=-1)\n res = herme.hermeint(pol, m=j, k=list(range(j)), lbnd=-1)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with scaling\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = herme.hermeint(tgt, m=1, k=[k], scl=2)\n res = herme.hermeint(pol, m=j, k=list(range(j)), scl=2)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_hermeint_axis(self):\n # check that axis keyword works\n c2d = np.random.random((3, 4))\n\n tgt = np.vstack([herme.hermeint(c) for c in c2d.T]).T\n res = herme.hermeint(c2d, axis=0)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([herme.hermeint(c) for c in c2d])\n res = herme.hermeint(c2d, axis=1)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([herme.hermeint(c, k=3) for c in c2d])\n res = herme.hermeint(c2d, k=3, axis=1)\n assert_almost_equal(res, tgt)\n\n\nclass TestDerivative:\n\n def test_hermeder(self):\n # check exceptions\n assert_raises(TypeError, herme.hermeder, [0], .5)\n assert_raises(ValueError, herme.hermeder, [0], -1)\n\n # check that zeroth derivative does nothing\n for i in range(5):\n tgt = [0] * i + [1]\n res = herme.hermeder(tgt, m=0)\n assert_equal(trim(res), trim(tgt))\n\n # check that derivation is the inverse of integration\n for i in range(5):\n for j in range(2, 5):\n tgt = [0] * i + [1]\n res = herme.hermeder(herme.hermeint(tgt, m=j), m=j)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check derivation with scaling\n for i in range(5):\n for j in range(2, 5):\n tgt = [0] * i + [1]\n res = herme.hermeder(\n herme.hermeint(tgt, m=j, scl=2), m=j, scl=.5)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_hermeder_axis(self):\n # check that axis keyword works\n c2d = np.random.random((3, 4))\n\n tgt = np.vstack([herme.hermeder(c) for c in c2d.T]).T\n res = herme.hermeder(c2d, axis=0)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([herme.hermeder(c) for c in c2d])\n res = herme.hermeder(c2d, axis=1)\n assert_almost_equal(res, tgt)\n\n\nclass TestVander:\n # some random values in [-1, 1)\n x = np.random.random((3, 5)) * 2 - 1\n\n def test_hermevander(self):\n # check for 1d x\n x = np.arange(3)\n v = herme.hermevander(x, 3)\n assert_(v.shape == (3, 4))\n for i in range(4):\n coef = [0] * i + [1]\n assert_almost_equal(v[..., i], herme.hermeval(x, coef))\n\n # check for 2d x\n x = np.array([[1, 2], [3, 4], [5, 6]])\n v = herme.hermevander(x, 3)\n assert_(v.shape == (3, 2, 4))\n for i in range(4):\n coef = [0] * i + [1]\n assert_almost_equal(v[..., i], herme.hermeval(x, coef))\n\n def test_hermevander2d(self):\n # also tests hermeval2d for non-square coefficient array\n x1, x2, x3 = self.x\n c = np.random.random((2, 3))\n van = herme.hermevander2d(x1, x2, [1, 2])\n tgt = herme.hermeval2d(x1, x2, c)\n res = np.dot(van, c.flat)\n assert_almost_equal(res, tgt)\n\n # check shape\n van = herme.hermevander2d([x1], [x2], [1, 2])\n assert_(van.shape == (1, 5, 6))\n\n def test_hermevander3d(self):\n # also tests hermeval3d for non-square coefficient array\n x1, x2, x3 = self.x\n c = np.random.random((2, 3, 4))\n van = herme.hermevander3d(x1, x2, x3, [1, 2, 3])\n tgt = herme.hermeval3d(x1, x2, x3, c)\n res = np.dot(van, c.flat)\n assert_almost_equal(res, tgt)\n\n # check shape\n van = herme.hermevander3d([x1], [x2], [x3], [1, 2, 3])\n assert_(van.shape == (1, 5, 24))\n\n\nclass TestFitting:\n\n def test_hermefit(self):\n def f(x):\n return x * (x - 1) * (x - 2)\n\n def f2(x):\n return x**4 + x**2 + 1\n\n # Test exceptions\n assert_raises(ValueError, herme.hermefit, [1], [1], -1)\n assert_raises(TypeError, herme.hermefit, [[1]], [1], 0)\n assert_raises(TypeError, herme.hermefit, [], [1], 0)\n assert_raises(TypeError, herme.hermefit, [1], [[[1]]], 0)\n assert_raises(TypeError, herme.hermefit, [1, 2], [1], 0)\n assert_raises(TypeError, herme.hermefit, [1], [1, 2], 0)\n assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[[1]])\n assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[1, 1])\n assert_raises(ValueError, herme.hermefit, [1], [1], [-1,])\n assert_raises(ValueError, herme.hermefit, [1], [1], [2, -1, 6])\n assert_raises(TypeError, herme.hermefit, [1], [1], [])\n\n # Test fit\n x = np.linspace(0, 2)\n y = f(x)\n #\n coef3 = herme.hermefit(x, y, 3)\n assert_equal(len(coef3), 4)\n assert_almost_equal(herme.hermeval(x, coef3), y)\n coef3 = herme.hermefit(x, y, [0, 1, 2, 3])\n assert_equal(len(coef3), 4)\n assert_almost_equal(herme.hermeval(x, coef3), y)\n #\n coef4 = herme.hermefit(x, y, 4)\n assert_equal(len(coef4), 5)\n assert_almost_equal(herme.hermeval(x, coef4), y)\n coef4 = herme.hermefit(x, y, [0, 1, 2, 3, 4])\n assert_equal(len(coef4), 5)\n assert_almost_equal(herme.hermeval(x, coef4), y)\n # check things still work if deg is not in strict increasing\n coef4 = herme.hermefit(x, y, [2, 3, 4, 1, 0])\n assert_equal(len(coef4), 5)\n assert_almost_equal(herme.hermeval(x, coef4), y)\n #\n coef2d = herme.hermefit(x, np.array([y, y]).T, 3)\n assert_almost_equal(coef2d, np.array([coef3, coef3]).T)\n coef2d = herme.hermefit(x, np.array([y, y]).T, [0, 1, 2, 3])\n assert_almost_equal(coef2d, np.array([coef3, coef3]).T)\n # test weighting\n w = np.zeros_like(x)\n yw = y.copy()\n w[1::2] = 1\n y[0::2] = 0\n wcoef3 = herme.hermefit(x, yw, 3, w=w)\n assert_almost_equal(wcoef3, coef3)\n wcoef3 = herme.hermefit(x, yw, [0, 1, 2, 3], w=w)\n assert_almost_equal(wcoef3, coef3)\n #\n wcoef2d = herme.hermefit(x, np.array([yw, yw]).T, 3, w=w)\n assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)\n wcoef2d = herme.hermefit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)\n assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)\n # test scaling with complex values x points whose square\n # is zero when summed.\n x = [1, 1j, -1, -1j]\n assert_almost_equal(herme.hermefit(x, x, 1), [0, 1])\n assert_almost_equal(herme.hermefit(x, x, [0, 1]), [0, 1])\n # test fitting only even Legendre polynomials\n x = np.linspace(-1, 1)\n y = f2(x)\n coef1 = herme.hermefit(x, y, 4)\n assert_almost_equal(herme.hermeval(x, coef1), y)\n coef2 = herme.hermefit(x, y, [0, 2, 4])\n assert_almost_equal(herme.hermeval(x, coef2), y)\n assert_almost_equal(coef1, coef2)\n\n\nclass TestCompanion:\n\n def test_raises(self):\n assert_raises(ValueError, herme.hermecompanion, [])\n assert_raises(ValueError, herme.hermecompanion, [1])\n\n def test_dimensions(self):\n for i in range(1, 5):\n coef = [0] * i + [1]\n assert_(herme.hermecompanion(coef).shape == (i, i))\n\n def test_linear_root(self):\n assert_(herme.hermecompanion([1, 2])[0, 0] == -.5)\n\n\nclass TestGauss:\n\n def test_100(self):\n x, w = herme.hermegauss(100)\n\n # test orthogonality. Note that the results need to be normalized,\n # otherwise the huge values that can arise from fast growing\n # functions like Laguerre can be very confusing.\n v = herme.hermevander(x, 99)\n vv = np.dot(v.T * w, v)\n vd = 1 / np.sqrt(vv.diagonal())\n vv = vd[:, None] * vv * vd\n assert_almost_equal(vv, np.eye(100))\n\n # check that the integral of 1 is correct\n tgt = np.sqrt(2 * np.pi)\n assert_almost_equal(w.sum(), tgt)\n\n\nclass TestMisc:\n\n def test_hermefromroots(self):\n res = herme.hermefromroots([])\n assert_almost_equal(trim(res), [1])\n for i in range(1, 5):\n roots = np.cos(np.linspace(-np.pi, 0, 2 * i + 1)[1::2])\n pol = herme.hermefromroots(roots)\n res = herme.hermeval(roots, pol)\n tgt = 0\n assert_(len(pol) == i + 1)\n assert_almost_equal(herme.herme2poly(pol)[-1], 1)\n assert_almost_equal(res, tgt)\n\n def test_hermeroots(self):\n assert_almost_equal(herme.hermeroots([1]), [])\n assert_almost_equal(herme.hermeroots([1, 1]), [-1])\n for i in range(2, 5):\n tgt = np.linspace(-1, 1, i)\n res = herme.hermeroots(herme.hermefromroots(tgt))\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_hermetrim(self):\n coef = [2, -1, 1, 0]\n\n # Test exceptions\n assert_raises(ValueError, herme.hermetrim, coef, -1)\n\n # Test results\n assert_equal(herme.hermetrim(coef), coef[:-1])\n assert_equal(herme.hermetrim(coef, 1), coef[:-3])\n assert_equal(herme.hermetrim(coef, 2), [0])\n\n def test_hermeline(self):\n assert_equal(herme.hermeline(3, 4), [3, 4])\n\n def test_herme2poly(self):\n for i in range(10):\n assert_almost_equal(herme.herme2poly([0] * i + [1]), Helist[i])\n\n def test_poly2herme(self):\n for i in range(10):\n assert_almost_equal(herme.poly2herme(Helist[i]), [0] * i + [1])\n\n def test_weight(self):\n x = np.linspace(-5, 5, 11)\n tgt = np.exp(-.5 * x**2)\n res = herme.hermeweight(x)\n assert_almost_equal(res, tgt)\n | .venv\Lib\site-packages\numpy\polynomial\tests\test_hermite_e.py | test_hermite_e.py | Python | 19,585 | 0.95 | 0.178891 | 0.119565 | vue-tools | 970 | 2024-02-20T19:49:31.394143 | Apache-2.0 | true | f6944afb3eccf77ae9ec7738758da184 |
"""Tests for laguerre module.\n\n"""\nfrom functools import reduce\n\nimport numpy as np\nimport numpy.polynomial.laguerre as lag\nfrom numpy.polynomial.polynomial import polyval\nfrom numpy.testing import (\n assert_,\n assert_almost_equal,\n assert_equal,\n assert_raises,\n)\n\nL0 = np.array([1]) / 1\nL1 = np.array([1, -1]) / 1\nL2 = np.array([2, -4, 1]) / 2\nL3 = np.array([6, -18, 9, -1]) / 6\nL4 = np.array([24, -96, 72, -16, 1]) / 24\nL5 = np.array([120, -600, 600, -200, 25, -1]) / 120\nL6 = np.array([720, -4320, 5400, -2400, 450, -36, 1]) / 720\n\nLlist = [L0, L1, L2, L3, L4, L5, L6]\n\n\ndef trim(x):\n return lag.lagtrim(x, tol=1e-6)\n\n\nclass TestConstants:\n\n def test_lagdomain(self):\n assert_equal(lag.lagdomain, [0, 1])\n\n def test_lagzero(self):\n assert_equal(lag.lagzero, [0])\n\n def test_lagone(self):\n assert_equal(lag.lagone, [1])\n\n def test_lagx(self):\n assert_equal(lag.lagx, [1, -1])\n\n\nclass TestArithmetic:\n x = np.linspace(-3, 3, 100)\n\n def test_lagadd(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n tgt = np.zeros(max(i, j) + 1)\n tgt[i] += 1\n tgt[j] += 1\n res = lag.lagadd([0] * i + [1], [0] * j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_lagsub(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n tgt = np.zeros(max(i, j) + 1)\n tgt[i] += 1\n tgt[j] -= 1\n res = lag.lagsub([0] * i + [1], [0] * j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_lagmulx(self):\n assert_equal(lag.lagmulx([0]), [0])\n assert_equal(lag.lagmulx([1]), [1, -1])\n for i in range(1, 5):\n ser = [0] * i + [1]\n tgt = [0] * (i - 1) + [-i, 2 * i + 1, -(i + 1)]\n assert_almost_equal(lag.lagmulx(ser), tgt)\n\n def test_lagmul(self):\n # check values of result\n for i in range(5):\n pol1 = [0] * i + [1]\n val1 = lag.lagval(self.x, pol1)\n for j in range(5):\n msg = f"At i={i}, j={j}"\n pol2 = [0] * j + [1]\n val2 = lag.lagval(self.x, pol2)\n pol3 = lag.lagmul(pol1, pol2)\n val3 = lag.lagval(self.x, pol3)\n assert_(len(pol3) == i + j + 1, msg)\n assert_almost_equal(val3, val1 * val2, err_msg=msg)\n\n def test_lagdiv(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n ci = [0] * i + [1]\n cj = [0] * j + [1]\n tgt = lag.lagadd(ci, cj)\n quo, rem = lag.lagdiv(tgt, ci)\n res = lag.lagadd(lag.lagmul(quo, ci), rem)\n assert_almost_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_lagpow(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n c = np.arange(i + 1)\n tgt = reduce(lag.lagmul, [c] * j, np.array([1]))\n res = lag.lagpow(c, j)\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n\nclass TestEvaluation:\n # coefficients of 1 + 2*x + 3*x**2\n c1d = np.array([9., -14., 6.])\n c2d = np.einsum('i,j->ij', c1d, c1d)\n c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)\n\n # some random values in [-1, 1)\n x = np.random.random((3, 5)) * 2 - 1\n y = polyval(x, [1., 2., 3.])\n\n def test_lagval(self):\n # check empty input\n assert_equal(lag.lagval([], [1]).size, 0)\n\n # check normal input)\n x = np.linspace(-1, 1)\n y = [polyval(x, c) for c in Llist]\n for i in range(7):\n msg = f"At i={i}"\n tgt = y[i]\n res = lag.lagval(x, [0] * i + [1])\n assert_almost_equal(res, tgt, err_msg=msg)\n\n # check that shape is preserved\n for i in range(3):\n dims = [2] * i\n x = np.zeros(dims)\n assert_equal(lag.lagval(x, [1]).shape, dims)\n assert_equal(lag.lagval(x, [1, 0]).shape, dims)\n assert_equal(lag.lagval(x, [1, 0, 0]).shape, dims)\n\n def test_lagval2d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test exceptions\n assert_raises(ValueError, lag.lagval2d, x1, x2[:2], self.c2d)\n\n # test values\n tgt = y1 * y2\n res = lag.lagval2d(x1, x2, self.c2d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = lag.lagval2d(z, z, self.c2d)\n assert_(res.shape == (2, 3))\n\n def test_lagval3d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test exceptions\n assert_raises(ValueError, lag.lagval3d, x1, x2, x3[:2], self.c3d)\n\n # test values\n tgt = y1 * y2 * y3\n res = lag.lagval3d(x1, x2, x3, self.c3d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = lag.lagval3d(z, z, z, self.c3d)\n assert_(res.shape == (2, 3))\n\n def test_laggrid2d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test values\n tgt = np.einsum('i,j->ij', y1, y2)\n res = lag.laggrid2d(x1, x2, self.c2d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = lag.laggrid2d(z, z, self.c2d)\n assert_(res.shape == (2, 3) * 2)\n\n def test_laggrid3d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test values\n tgt = np.einsum('i,j,k->ijk', y1, y2, y3)\n res = lag.laggrid3d(x1, x2, x3, self.c3d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = lag.laggrid3d(z, z, z, self.c3d)\n assert_(res.shape == (2, 3) * 3)\n\n\nclass TestIntegral:\n\n def test_lagint(self):\n # check exceptions\n assert_raises(TypeError, lag.lagint, [0], .5)\n assert_raises(ValueError, lag.lagint, [0], -1)\n assert_raises(ValueError, lag.lagint, [0], 1, [0, 0])\n assert_raises(ValueError, lag.lagint, [0], lbnd=[0])\n assert_raises(ValueError, lag.lagint, [0], scl=[0])\n assert_raises(TypeError, lag.lagint, [0], axis=.5)\n\n # test integration of zero polynomial\n for i in range(2, 5):\n k = [0] * (i - 2) + [1]\n res = lag.lagint([0], m=i, k=k)\n assert_almost_equal(res, [1, -1])\n\n # check single integration with integration constant\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n tgt = [i] + [0] * i + [1 / scl]\n lagpol = lag.poly2lag(pol)\n lagint = lag.lagint(lagpol, m=1, k=[i])\n res = lag.lag2poly(lagint)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check single integration with integration constant and lbnd\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n lagpol = lag.poly2lag(pol)\n lagint = lag.lagint(lagpol, m=1, k=[i], lbnd=-1)\n assert_almost_equal(lag.lagval(-1, lagint), i)\n\n # check single integration with integration constant and scaling\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n tgt = [i] + [0] * i + [2 / scl]\n lagpol = lag.poly2lag(pol)\n lagint = lag.lagint(lagpol, m=1, k=[i], scl=2)\n res = lag.lag2poly(lagint)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with default k\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = lag.lagint(tgt, m=1)\n res = lag.lagint(pol, m=j)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with defined k\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = lag.lagint(tgt, m=1, k=[k])\n res = lag.lagint(pol, m=j, k=list(range(j)))\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with lbnd\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = lag.lagint(tgt, m=1, k=[k], lbnd=-1)\n res = lag.lagint(pol, m=j, k=list(range(j)), lbnd=-1)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with scaling\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = lag.lagint(tgt, m=1, k=[k], scl=2)\n res = lag.lagint(pol, m=j, k=list(range(j)), scl=2)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_lagint_axis(self):\n # check that axis keyword works\n c2d = np.random.random((3, 4))\n\n tgt = np.vstack([lag.lagint(c) for c in c2d.T]).T\n res = lag.lagint(c2d, axis=0)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([lag.lagint(c) for c in c2d])\n res = lag.lagint(c2d, axis=1)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([lag.lagint(c, k=3) for c in c2d])\n res = lag.lagint(c2d, k=3, axis=1)\n assert_almost_equal(res, tgt)\n\n\nclass TestDerivative:\n\n def test_lagder(self):\n # check exceptions\n assert_raises(TypeError, lag.lagder, [0], .5)\n assert_raises(ValueError, lag.lagder, [0], -1)\n\n # check that zeroth derivative does nothing\n for i in range(5):\n tgt = [0] * i + [1]\n res = lag.lagder(tgt, m=0)\n assert_equal(trim(res), trim(tgt))\n\n # check that derivation is the inverse of integration\n for i in range(5):\n for j in range(2, 5):\n tgt = [0] * i + [1]\n res = lag.lagder(lag.lagint(tgt, m=j), m=j)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check derivation with scaling\n for i in range(5):\n for j in range(2, 5):\n tgt = [0] * i + [1]\n res = lag.lagder(lag.lagint(tgt, m=j, scl=2), m=j, scl=.5)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_lagder_axis(self):\n # check that axis keyword works\n c2d = np.random.random((3, 4))\n\n tgt = np.vstack([lag.lagder(c) for c in c2d.T]).T\n res = lag.lagder(c2d, axis=0)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([lag.lagder(c) for c in c2d])\n res = lag.lagder(c2d, axis=1)\n assert_almost_equal(res, tgt)\n\n\nclass TestVander:\n # some random values in [-1, 1)\n x = np.random.random((3, 5)) * 2 - 1\n\n def test_lagvander(self):\n # check for 1d x\n x = np.arange(3)\n v = lag.lagvander(x, 3)\n assert_(v.shape == (3, 4))\n for i in range(4):\n coef = [0] * i + [1]\n assert_almost_equal(v[..., i], lag.lagval(x, coef))\n\n # check for 2d x\n x = np.array([[1, 2], [3, 4], [5, 6]])\n v = lag.lagvander(x, 3)\n assert_(v.shape == (3, 2, 4))\n for i in range(4):\n coef = [0] * i + [1]\n assert_almost_equal(v[..., i], lag.lagval(x, coef))\n\n def test_lagvander2d(self):\n # also tests lagval2d for non-square coefficient array\n x1, x2, x3 = self.x\n c = np.random.random((2, 3))\n van = lag.lagvander2d(x1, x2, [1, 2])\n tgt = lag.lagval2d(x1, x2, c)\n res = np.dot(van, c.flat)\n assert_almost_equal(res, tgt)\n\n # check shape\n van = lag.lagvander2d([x1], [x2], [1, 2])\n assert_(van.shape == (1, 5, 6))\n\n def test_lagvander3d(self):\n # also tests lagval3d for non-square coefficient array\n x1, x2, x3 = self.x\n c = np.random.random((2, 3, 4))\n van = lag.lagvander3d(x1, x2, x3, [1, 2, 3])\n tgt = lag.lagval3d(x1, x2, x3, c)\n res = np.dot(van, c.flat)\n assert_almost_equal(res, tgt)\n\n # check shape\n van = lag.lagvander3d([x1], [x2], [x3], [1, 2, 3])\n assert_(van.shape == (1, 5, 24))\n\n\nclass TestFitting:\n\n def test_lagfit(self):\n def f(x):\n return x * (x - 1) * (x - 2)\n\n # Test exceptions\n assert_raises(ValueError, lag.lagfit, [1], [1], -1)\n assert_raises(TypeError, lag.lagfit, [[1]], [1], 0)\n assert_raises(TypeError, lag.lagfit, [], [1], 0)\n assert_raises(TypeError, lag.lagfit, [1], [[[1]]], 0)\n assert_raises(TypeError, lag.lagfit, [1, 2], [1], 0)\n assert_raises(TypeError, lag.lagfit, [1], [1, 2], 0)\n assert_raises(TypeError, lag.lagfit, [1], [1], 0, w=[[1]])\n assert_raises(TypeError, lag.lagfit, [1], [1], 0, w=[1, 1])\n assert_raises(ValueError, lag.lagfit, [1], [1], [-1,])\n assert_raises(ValueError, lag.lagfit, [1], [1], [2, -1, 6])\n assert_raises(TypeError, lag.lagfit, [1], [1], [])\n\n # Test fit\n x = np.linspace(0, 2)\n y = f(x)\n #\n coef3 = lag.lagfit(x, y, 3)\n assert_equal(len(coef3), 4)\n assert_almost_equal(lag.lagval(x, coef3), y)\n coef3 = lag.lagfit(x, y, [0, 1, 2, 3])\n assert_equal(len(coef3), 4)\n assert_almost_equal(lag.lagval(x, coef3), y)\n #\n coef4 = lag.lagfit(x, y, 4)\n assert_equal(len(coef4), 5)\n assert_almost_equal(lag.lagval(x, coef4), y)\n coef4 = lag.lagfit(x, y, [0, 1, 2, 3, 4])\n assert_equal(len(coef4), 5)\n assert_almost_equal(lag.lagval(x, coef4), y)\n #\n coef2d = lag.lagfit(x, np.array([y, y]).T, 3)\n assert_almost_equal(coef2d, np.array([coef3, coef3]).T)\n coef2d = lag.lagfit(x, np.array([y, y]).T, [0, 1, 2, 3])\n assert_almost_equal(coef2d, np.array([coef3, coef3]).T)\n # test weighting\n w = np.zeros_like(x)\n yw = y.copy()\n w[1::2] = 1\n y[0::2] = 0\n wcoef3 = lag.lagfit(x, yw, 3, w=w)\n assert_almost_equal(wcoef3, coef3)\n wcoef3 = lag.lagfit(x, yw, [0, 1, 2, 3], w=w)\n assert_almost_equal(wcoef3, coef3)\n #\n wcoef2d = lag.lagfit(x, np.array([yw, yw]).T, 3, w=w)\n assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)\n wcoef2d = lag.lagfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)\n assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)\n # test scaling with complex values x points whose square\n # is zero when summed.\n x = [1, 1j, -1, -1j]\n assert_almost_equal(lag.lagfit(x, x, 1), [1, -1])\n assert_almost_equal(lag.lagfit(x, x, [0, 1]), [1, -1])\n\n\nclass TestCompanion:\n\n def test_raises(self):\n assert_raises(ValueError, lag.lagcompanion, [])\n assert_raises(ValueError, lag.lagcompanion, [1])\n\n def test_dimensions(self):\n for i in range(1, 5):\n coef = [0] * i + [1]\n assert_(lag.lagcompanion(coef).shape == (i, i))\n\n def test_linear_root(self):\n assert_(lag.lagcompanion([1, 2])[0, 0] == 1.5)\n\n\nclass TestGauss:\n\n def test_100(self):\n x, w = lag.laggauss(100)\n\n # test orthogonality. Note that the results need to be normalized,\n # otherwise the huge values that can arise from fast growing\n # functions like Laguerre can be very confusing.\n v = lag.lagvander(x, 99)\n vv = np.dot(v.T * w, v)\n vd = 1 / np.sqrt(vv.diagonal())\n vv = vd[:, None] * vv * vd\n assert_almost_equal(vv, np.eye(100))\n\n # check that the integral of 1 is correct\n tgt = 1.0\n assert_almost_equal(w.sum(), tgt)\n\n\nclass TestMisc:\n\n def test_lagfromroots(self):\n res = lag.lagfromroots([])\n assert_almost_equal(trim(res), [1])\n for i in range(1, 5):\n roots = np.cos(np.linspace(-np.pi, 0, 2 * i + 1)[1::2])\n pol = lag.lagfromroots(roots)\n res = lag.lagval(roots, pol)\n tgt = 0\n assert_(len(pol) == i + 1)\n assert_almost_equal(lag.lag2poly(pol)[-1], 1)\n assert_almost_equal(res, tgt)\n\n def test_lagroots(self):\n assert_almost_equal(lag.lagroots([1]), [])\n assert_almost_equal(lag.lagroots([0, 1]), [1])\n for i in range(2, 5):\n tgt = np.linspace(0, 3, i)\n res = lag.lagroots(lag.lagfromroots(tgt))\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_lagtrim(self):\n coef = [2, -1, 1, 0]\n\n # Test exceptions\n assert_raises(ValueError, lag.lagtrim, coef, -1)\n\n # Test results\n assert_equal(lag.lagtrim(coef), coef[:-1])\n assert_equal(lag.lagtrim(coef, 1), coef[:-3])\n assert_equal(lag.lagtrim(coef, 2), [0])\n\n def test_lagline(self):\n assert_equal(lag.lagline(3, 4), [7, -4])\n\n def test_lag2poly(self):\n for i in range(7):\n assert_almost_equal(lag.lag2poly([0] * i + [1]), Llist[i])\n\n def test_poly2lag(self):\n for i in range(7):\n assert_almost_equal(lag.poly2lag(Llist[i]), [0] * i + [1])\n\n def test_weight(self):\n x = np.linspace(0, 10, 11)\n tgt = np.exp(-x)\n res = lag.lagweight(x)\n assert_almost_equal(res, tgt)\n | .venv\Lib\site-packages\numpy\polynomial\tests\test_laguerre.py | test_laguerre.py | Python | 18,177 | 0.95 | 0.181481 | 0.11991 | vue-tools | 586 | 2023-09-10T03:03:09.447607 | BSD-3-Clause | true | c60937ddcde7e4beea7f7676642b8dc3 |
"""Tests for legendre module.\n\n"""\nfrom functools import reduce\n\nimport numpy as np\nimport numpy.polynomial.legendre as leg\nfrom numpy.polynomial.polynomial import polyval\nfrom numpy.testing import (\n assert_,\n assert_almost_equal,\n assert_equal,\n assert_raises,\n)\n\nL0 = np.array([1])\nL1 = np.array([0, 1])\nL2 = np.array([-1, 0, 3]) / 2\nL3 = np.array([0, -3, 0, 5]) / 2\nL4 = np.array([3, 0, -30, 0, 35]) / 8\nL5 = np.array([0, 15, 0, -70, 0, 63]) / 8\nL6 = np.array([-5, 0, 105, 0, -315, 0, 231]) / 16\nL7 = np.array([0, -35, 0, 315, 0, -693, 0, 429]) / 16\nL8 = np.array([35, 0, -1260, 0, 6930, 0, -12012, 0, 6435]) / 128\nL9 = np.array([0, 315, 0, -4620, 0, 18018, 0, -25740, 0, 12155]) / 128\n\nLlist = [L0, L1, L2, L3, L4, L5, L6, L7, L8, L9]\n\n\ndef trim(x):\n return leg.legtrim(x, tol=1e-6)\n\n\nclass TestConstants:\n\n def test_legdomain(self):\n assert_equal(leg.legdomain, [-1, 1])\n\n def test_legzero(self):\n assert_equal(leg.legzero, [0])\n\n def test_legone(self):\n assert_equal(leg.legone, [1])\n\n def test_legx(self):\n assert_equal(leg.legx, [0, 1])\n\n\nclass TestArithmetic:\n x = np.linspace(-1, 1, 100)\n\n def test_legadd(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n tgt = np.zeros(max(i, j) + 1)\n tgt[i] += 1\n tgt[j] += 1\n res = leg.legadd([0] * i + [1], [0] * j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_legsub(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n tgt = np.zeros(max(i, j) + 1)\n tgt[i] += 1\n tgt[j] -= 1\n res = leg.legsub([0] * i + [1], [0] * j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_legmulx(self):\n assert_equal(leg.legmulx([0]), [0])\n assert_equal(leg.legmulx([1]), [0, 1])\n for i in range(1, 5):\n tmp = 2 * i + 1\n ser = [0] * i + [1]\n tgt = [0] * (i - 1) + [i / tmp, 0, (i + 1) / tmp]\n assert_equal(leg.legmulx(ser), tgt)\n\n def test_legmul(self):\n # check values of result\n for i in range(5):\n pol1 = [0] * i + [1]\n val1 = leg.legval(self.x, pol1)\n for j in range(5):\n msg = f"At i={i}, j={j}"\n pol2 = [0] * j + [1]\n val2 = leg.legval(self.x, pol2)\n pol3 = leg.legmul(pol1, pol2)\n val3 = leg.legval(self.x, pol3)\n assert_(len(pol3) == i + j + 1, msg)\n assert_almost_equal(val3, val1 * val2, err_msg=msg)\n\n def test_legdiv(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n ci = [0] * i + [1]\n cj = [0] * j + [1]\n tgt = leg.legadd(ci, cj)\n quo, rem = leg.legdiv(tgt, ci)\n res = leg.legadd(leg.legmul(quo, ci), rem)\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_legpow(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n c = np.arange(i + 1)\n tgt = reduce(leg.legmul, [c] * j, np.array([1]))\n res = leg.legpow(c, j)\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n\nclass TestEvaluation:\n # coefficients of 1 + 2*x + 3*x**2\n c1d = np.array([2., 2., 2.])\n c2d = np.einsum('i,j->ij', c1d, c1d)\n c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)\n\n # some random values in [-1, 1)\n x = np.random.random((3, 5)) * 2 - 1\n y = polyval(x, [1., 2., 3.])\n\n def test_legval(self):\n # check empty input\n assert_equal(leg.legval([], [1]).size, 0)\n\n # check normal input)\n x = np.linspace(-1, 1)\n y = [polyval(x, c) for c in Llist]\n for i in range(10):\n msg = f"At i={i}"\n tgt = y[i]\n res = leg.legval(x, [0] * i + [1])\n assert_almost_equal(res, tgt, err_msg=msg)\n\n # check that shape is preserved\n for i in range(3):\n dims = [2] * i\n x = np.zeros(dims)\n assert_equal(leg.legval(x, [1]).shape, dims)\n assert_equal(leg.legval(x, [1, 0]).shape, dims)\n assert_equal(leg.legval(x, [1, 0, 0]).shape, dims)\n\n def test_legval2d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test exceptions\n assert_raises(ValueError, leg.legval2d, x1, x2[:2], self.c2d)\n\n # test values\n tgt = y1 * y2\n res = leg.legval2d(x1, x2, self.c2d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = leg.legval2d(z, z, self.c2d)\n assert_(res.shape == (2, 3))\n\n def test_legval3d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test exceptions\n assert_raises(ValueError, leg.legval3d, x1, x2, x3[:2], self.c3d)\n\n # test values\n tgt = y1 * y2 * y3\n res = leg.legval3d(x1, x2, x3, self.c3d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = leg.legval3d(z, z, z, self.c3d)\n assert_(res.shape == (2, 3))\n\n def test_leggrid2d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test values\n tgt = np.einsum('i,j->ij', y1, y2)\n res = leg.leggrid2d(x1, x2, self.c2d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = leg.leggrid2d(z, z, self.c2d)\n assert_(res.shape == (2, 3) * 2)\n\n def test_leggrid3d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test values\n tgt = np.einsum('i,j,k->ijk', y1, y2, y3)\n res = leg.leggrid3d(x1, x2, x3, self.c3d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = leg.leggrid3d(z, z, z, self.c3d)\n assert_(res.shape == (2, 3) * 3)\n\n\nclass TestIntegral:\n\n def test_legint(self):\n # check exceptions\n assert_raises(TypeError, leg.legint, [0], .5)\n assert_raises(ValueError, leg.legint, [0], -1)\n assert_raises(ValueError, leg.legint, [0], 1, [0, 0])\n assert_raises(ValueError, leg.legint, [0], lbnd=[0])\n assert_raises(ValueError, leg.legint, [0], scl=[0])\n assert_raises(TypeError, leg.legint, [0], axis=.5)\n\n # test integration of zero polynomial\n for i in range(2, 5):\n k = [0] * (i - 2) + [1]\n res = leg.legint([0], m=i, k=k)\n assert_almost_equal(res, [0, 1])\n\n # check single integration with integration constant\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n tgt = [i] + [0] * i + [1 / scl]\n legpol = leg.poly2leg(pol)\n legint = leg.legint(legpol, m=1, k=[i])\n res = leg.leg2poly(legint)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check single integration with integration constant and lbnd\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n legpol = leg.poly2leg(pol)\n legint = leg.legint(legpol, m=1, k=[i], lbnd=-1)\n assert_almost_equal(leg.legval(-1, legint), i)\n\n # check single integration with integration constant and scaling\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n tgt = [i] + [0] * i + [2 / scl]\n legpol = leg.poly2leg(pol)\n legint = leg.legint(legpol, m=1, k=[i], scl=2)\n res = leg.leg2poly(legint)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with default k\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = leg.legint(tgt, m=1)\n res = leg.legint(pol, m=j)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with defined k\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = leg.legint(tgt, m=1, k=[k])\n res = leg.legint(pol, m=j, k=list(range(j)))\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with lbnd\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = leg.legint(tgt, m=1, k=[k], lbnd=-1)\n res = leg.legint(pol, m=j, k=list(range(j)), lbnd=-1)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with scaling\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = leg.legint(tgt, m=1, k=[k], scl=2)\n res = leg.legint(pol, m=j, k=list(range(j)), scl=2)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_legint_axis(self):\n # check that axis keyword works\n c2d = np.random.random((3, 4))\n\n tgt = np.vstack([leg.legint(c) for c in c2d.T]).T\n res = leg.legint(c2d, axis=0)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([leg.legint(c) for c in c2d])\n res = leg.legint(c2d, axis=1)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([leg.legint(c, k=3) for c in c2d])\n res = leg.legint(c2d, k=3, axis=1)\n assert_almost_equal(res, tgt)\n\n def test_legint_zerointord(self):\n assert_equal(leg.legint((1, 2, 3), 0), (1, 2, 3))\n\n\nclass TestDerivative:\n\n def test_legder(self):\n # check exceptions\n assert_raises(TypeError, leg.legder, [0], .5)\n assert_raises(ValueError, leg.legder, [0], -1)\n\n # check that zeroth derivative does nothing\n for i in range(5):\n tgt = [0] * i + [1]\n res = leg.legder(tgt, m=0)\n assert_equal(trim(res), trim(tgt))\n\n # check that derivation is the inverse of integration\n for i in range(5):\n for j in range(2, 5):\n tgt = [0] * i + [1]\n res = leg.legder(leg.legint(tgt, m=j), m=j)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check derivation with scaling\n for i in range(5):\n for j in range(2, 5):\n tgt = [0] * i + [1]\n res = leg.legder(leg.legint(tgt, m=j, scl=2), m=j, scl=.5)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_legder_axis(self):\n # check that axis keyword works\n c2d = np.random.random((3, 4))\n\n tgt = np.vstack([leg.legder(c) for c in c2d.T]).T\n res = leg.legder(c2d, axis=0)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([leg.legder(c) for c in c2d])\n res = leg.legder(c2d, axis=1)\n assert_almost_equal(res, tgt)\n\n def test_legder_orderhigherthancoeff(self):\n c = (1, 2, 3, 4)\n assert_equal(leg.legder(c, 4), [0])\n\nclass TestVander:\n # some random values in [-1, 1)\n x = np.random.random((3, 5)) * 2 - 1\n\n def test_legvander(self):\n # check for 1d x\n x = np.arange(3)\n v = leg.legvander(x, 3)\n assert_(v.shape == (3, 4))\n for i in range(4):\n coef = [0] * i + [1]\n assert_almost_equal(v[..., i], leg.legval(x, coef))\n\n # check for 2d x\n x = np.array([[1, 2], [3, 4], [5, 6]])\n v = leg.legvander(x, 3)\n assert_(v.shape == (3, 2, 4))\n for i in range(4):\n coef = [0] * i + [1]\n assert_almost_equal(v[..., i], leg.legval(x, coef))\n\n def test_legvander2d(self):\n # also tests polyval2d for non-square coefficient array\n x1, x2, x3 = self.x\n c = np.random.random((2, 3))\n van = leg.legvander2d(x1, x2, [1, 2])\n tgt = leg.legval2d(x1, x2, c)\n res = np.dot(van, c.flat)\n assert_almost_equal(res, tgt)\n\n # check shape\n van = leg.legvander2d([x1], [x2], [1, 2])\n assert_(van.shape == (1, 5, 6))\n\n def test_legvander3d(self):\n # also tests polyval3d for non-square coefficient array\n x1, x2, x3 = self.x\n c = np.random.random((2, 3, 4))\n van = leg.legvander3d(x1, x2, x3, [1, 2, 3])\n tgt = leg.legval3d(x1, x2, x3, c)\n res = np.dot(van, c.flat)\n assert_almost_equal(res, tgt)\n\n # check shape\n van = leg.legvander3d([x1], [x2], [x3], [1, 2, 3])\n assert_(van.shape == (1, 5, 24))\n\n def test_legvander_negdeg(self):\n assert_raises(ValueError, leg.legvander, (1, 2, 3), -1)\n\n\nclass TestFitting:\n\n def test_legfit(self):\n def f(x):\n return x * (x - 1) * (x - 2)\n\n def f2(x):\n return x**4 + x**2 + 1\n\n # Test exceptions\n assert_raises(ValueError, leg.legfit, [1], [1], -1)\n assert_raises(TypeError, leg.legfit, [[1]], [1], 0)\n assert_raises(TypeError, leg.legfit, [], [1], 0)\n assert_raises(TypeError, leg.legfit, [1], [[[1]]], 0)\n assert_raises(TypeError, leg.legfit, [1, 2], [1], 0)\n assert_raises(TypeError, leg.legfit, [1], [1, 2], 0)\n assert_raises(TypeError, leg.legfit, [1], [1], 0, w=[[1]])\n assert_raises(TypeError, leg.legfit, [1], [1], 0, w=[1, 1])\n assert_raises(ValueError, leg.legfit, [1], [1], [-1,])\n assert_raises(ValueError, leg.legfit, [1], [1], [2, -1, 6])\n assert_raises(TypeError, leg.legfit, [1], [1], [])\n\n # Test fit\n x = np.linspace(0, 2)\n y = f(x)\n #\n coef3 = leg.legfit(x, y, 3)\n assert_equal(len(coef3), 4)\n assert_almost_equal(leg.legval(x, coef3), y)\n coef3 = leg.legfit(x, y, [0, 1, 2, 3])\n assert_equal(len(coef3), 4)\n assert_almost_equal(leg.legval(x, coef3), y)\n #\n coef4 = leg.legfit(x, y, 4)\n assert_equal(len(coef4), 5)\n assert_almost_equal(leg.legval(x, coef4), y)\n coef4 = leg.legfit(x, y, [0, 1, 2, 3, 4])\n assert_equal(len(coef4), 5)\n assert_almost_equal(leg.legval(x, coef4), y)\n # check things still work if deg is not in strict increasing\n coef4 = leg.legfit(x, y, [2, 3, 4, 1, 0])\n assert_equal(len(coef4), 5)\n assert_almost_equal(leg.legval(x, coef4), y)\n #\n coef2d = leg.legfit(x, np.array([y, y]).T, 3)\n assert_almost_equal(coef2d, np.array([coef3, coef3]).T)\n coef2d = leg.legfit(x, np.array([y, y]).T, [0, 1, 2, 3])\n assert_almost_equal(coef2d, np.array([coef3, coef3]).T)\n # test weighting\n w = np.zeros_like(x)\n yw = y.copy()\n w[1::2] = 1\n y[0::2] = 0\n wcoef3 = leg.legfit(x, yw, 3, w=w)\n assert_almost_equal(wcoef3, coef3)\n wcoef3 = leg.legfit(x, yw, [0, 1, 2, 3], w=w)\n assert_almost_equal(wcoef3, coef3)\n #\n wcoef2d = leg.legfit(x, np.array([yw, yw]).T, 3, w=w)\n assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)\n wcoef2d = leg.legfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)\n assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)\n # test scaling with complex values x points whose square\n # is zero when summed.\n x = [1, 1j, -1, -1j]\n assert_almost_equal(leg.legfit(x, x, 1), [0, 1])\n assert_almost_equal(leg.legfit(x, x, [0, 1]), [0, 1])\n # test fitting only even Legendre polynomials\n x = np.linspace(-1, 1)\n y = f2(x)\n coef1 = leg.legfit(x, y, 4)\n assert_almost_equal(leg.legval(x, coef1), y)\n coef2 = leg.legfit(x, y, [0, 2, 4])\n assert_almost_equal(leg.legval(x, coef2), y)\n assert_almost_equal(coef1, coef2)\n\n\nclass TestCompanion:\n\n def test_raises(self):\n assert_raises(ValueError, leg.legcompanion, [])\n assert_raises(ValueError, leg.legcompanion, [1])\n\n def test_dimensions(self):\n for i in range(1, 5):\n coef = [0] * i + [1]\n assert_(leg.legcompanion(coef).shape == (i, i))\n\n def test_linear_root(self):\n assert_(leg.legcompanion([1, 2])[0, 0] == -.5)\n\n\nclass TestGauss:\n\n def test_100(self):\n x, w = leg.leggauss(100)\n\n # test orthogonality. Note that the results need to be normalized,\n # otherwise the huge values that can arise from fast growing\n # functions like Laguerre can be very confusing.\n v = leg.legvander(x, 99)\n vv = np.dot(v.T * w, v)\n vd = 1 / np.sqrt(vv.diagonal())\n vv = vd[:, None] * vv * vd\n assert_almost_equal(vv, np.eye(100))\n\n # check that the integral of 1 is correct\n tgt = 2.0\n assert_almost_equal(w.sum(), tgt)\n\n\nclass TestMisc:\n\n def test_legfromroots(self):\n res = leg.legfromroots([])\n assert_almost_equal(trim(res), [1])\n for i in range(1, 5):\n roots = np.cos(np.linspace(-np.pi, 0, 2 * i + 1)[1::2])\n pol = leg.legfromroots(roots)\n res = leg.legval(roots, pol)\n tgt = 0\n assert_(len(pol) == i + 1)\n assert_almost_equal(leg.leg2poly(pol)[-1], 1)\n assert_almost_equal(res, tgt)\n\n def test_legroots(self):\n assert_almost_equal(leg.legroots([1]), [])\n assert_almost_equal(leg.legroots([1, 2]), [-.5])\n for i in range(2, 5):\n tgt = np.linspace(-1, 1, i)\n res = leg.legroots(leg.legfromroots(tgt))\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_legtrim(self):\n coef = [2, -1, 1, 0]\n\n # Test exceptions\n assert_raises(ValueError, leg.legtrim, coef, -1)\n\n # Test results\n assert_equal(leg.legtrim(coef), coef[:-1])\n assert_equal(leg.legtrim(coef, 1), coef[:-3])\n assert_equal(leg.legtrim(coef, 2), [0])\n\n def test_legline(self):\n assert_equal(leg.legline(3, 4), [3, 4])\n\n def test_legline_zeroscl(self):\n assert_equal(leg.legline(3, 0), [3])\n\n def test_leg2poly(self):\n for i in range(10):\n assert_almost_equal(leg.leg2poly([0] * i + [1]), Llist[i])\n\n def test_poly2leg(self):\n for i in range(10):\n assert_almost_equal(leg.poly2leg(Llist[i]), [0] * i + [1])\n\n def test_weight(self):\n x = np.linspace(-1, 1, 11)\n tgt = 1.\n res = leg.legweight(x)\n assert_almost_equal(res, tgt)\n | .venv\Lib\site-packages\numpy\polynomial\tests\test_legendre.py | test_legendre.py | Python | 19,376 | 0.95 | 0.182137 | 0.117271 | python-kit | 734 | 2024-08-19T09:26:42.693100 | MIT | true | f542afe97ff45c27421790aa4ff759a5 |
"""Tests for polynomial module.\n\n"""\nimport pickle\nfrom copy import deepcopy\nfrom fractions import Fraction\nfrom functools import reduce\n\nimport numpy as np\nimport numpy.polynomial.polynomial as poly\nimport numpy.polynomial.polyutils as pu\nfrom numpy.testing import (\n assert_,\n assert_almost_equal,\n assert_array_equal,\n assert_equal,\n assert_raises,\n assert_raises_regex,\n assert_warns,\n)\n\n\ndef trim(x):\n return poly.polytrim(x, tol=1e-6)\n\n\nT0 = [1]\nT1 = [0, 1]\nT2 = [-1, 0, 2]\nT3 = [0, -3, 0, 4]\nT4 = [1, 0, -8, 0, 8]\nT5 = [0, 5, 0, -20, 0, 16]\nT6 = [-1, 0, 18, 0, -48, 0, 32]\nT7 = [0, -7, 0, 56, 0, -112, 0, 64]\nT8 = [1, 0, -32, 0, 160, 0, -256, 0, 128]\nT9 = [0, 9, 0, -120, 0, 432, 0, -576, 0, 256]\n\nTlist = [T0, T1, T2, T3, T4, T5, T6, T7, T8, T9]\n\n\nclass TestConstants:\n\n def test_polydomain(self):\n assert_equal(poly.polydomain, [-1, 1])\n\n def test_polyzero(self):\n assert_equal(poly.polyzero, [0])\n\n def test_polyone(self):\n assert_equal(poly.polyone, [1])\n\n def test_polyx(self):\n assert_equal(poly.polyx, [0, 1])\n\n def test_copy(self):\n x = poly.Polynomial([1, 2, 3])\n y = deepcopy(x)\n assert_equal(x, y)\n\n def test_pickle(self):\n x = poly.Polynomial([1, 2, 3])\n y = pickle.loads(pickle.dumps(x))\n assert_equal(x, y)\n\nclass TestArithmetic:\n\n def test_polyadd(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n tgt = np.zeros(max(i, j) + 1)\n tgt[i] += 1\n tgt[j] += 1\n res = poly.polyadd([0] * i + [1], [0] * j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_polysub(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n tgt = np.zeros(max(i, j) + 1)\n tgt[i] += 1\n tgt[j] -= 1\n res = poly.polysub([0] * i + [1], [0] * j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_polymulx(self):\n assert_equal(poly.polymulx([0]), [0])\n assert_equal(poly.polymulx([1]), [0, 1])\n for i in range(1, 5):\n ser = [0] * i + [1]\n tgt = [0] * (i + 1) + [1]\n assert_equal(poly.polymulx(ser), tgt)\n\n def test_polymul(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n tgt = np.zeros(i + j + 1)\n tgt[i + j] += 1\n res = poly.polymul([0] * i + [1], [0] * j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_polydiv(self):\n # check zero division\n assert_raises(ZeroDivisionError, poly.polydiv, [1], [0])\n\n # check scalar division\n quo, rem = poly.polydiv([2], [2])\n assert_equal((quo, rem), (1, 0))\n quo, rem = poly.polydiv([2, 2], [2])\n assert_equal((quo, rem), ((1, 1), 0))\n\n # check rest.\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n ci = [0] * i + [1, 2]\n cj = [0] * j + [1, 2]\n tgt = poly.polyadd(ci, cj)\n quo, rem = poly.polydiv(tgt, ci)\n res = poly.polyadd(poly.polymul(quo, ci), rem)\n assert_equal(res, tgt, err_msg=msg)\n\n def test_polypow(self):\n for i in range(5):\n for j in range(5):\n msg = f"At i={i}, j={j}"\n c = np.arange(i + 1)\n tgt = reduce(poly.polymul, [c] * j, np.array([1]))\n res = poly.polypow(c, j)\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\nclass TestFraction:\n\n def test_Fraction(self):\n # assert we can use Polynomials with coefficients of object dtype\n f = Fraction(2, 3)\n one = Fraction(1, 1)\n zero = Fraction(0, 1)\n p = poly.Polynomial([f, f], domain=[zero, one], window=[zero, one])\n\n x = 2 * p + p ** 2\n assert_equal(x.coef, np.array([Fraction(16, 9), Fraction(20, 9),\n Fraction(4, 9)], dtype=object))\n assert_equal(p.domain, [zero, one])\n assert_equal(p.coef.dtype, np.dtypes.ObjectDType())\n assert_(isinstance(p(f), Fraction))\n assert_equal(p(f), Fraction(10, 9))\n p_deriv = poly.Polynomial([Fraction(2, 3)], domain=[zero, one],\n window=[zero, one])\n assert_equal(p.deriv(), p_deriv)\n\nclass TestEvaluation:\n # coefficients of 1 + 2*x + 3*x**2\n c1d = np.array([1., 2., 3.])\n c2d = np.einsum('i,j->ij', c1d, c1d)\n c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)\n\n # some random values in [-1, 1)\n x = np.random.random((3, 5)) * 2 - 1\n y = poly.polyval(x, [1., 2., 3.])\n\n def test_polyval(self):\n # check empty input\n assert_equal(poly.polyval([], [1]).size, 0)\n\n # check normal input)\n x = np.linspace(-1, 1)\n y = [x**i for i in range(5)]\n for i in range(5):\n tgt = y[i]\n res = poly.polyval(x, [0] * i + [1])\n assert_almost_equal(res, tgt)\n tgt = x * (x**2 - 1)\n res = poly.polyval(x, [0, -1, 0, 1])\n assert_almost_equal(res, tgt)\n\n # check that shape is preserved\n for i in range(3):\n dims = [2] * i\n x = np.zeros(dims)\n assert_equal(poly.polyval(x, [1]).shape, dims)\n assert_equal(poly.polyval(x, [1, 0]).shape, dims)\n assert_equal(poly.polyval(x, [1, 0, 0]).shape, dims)\n\n # check masked arrays are processed correctly\n mask = [False, True, False]\n mx = np.ma.array([1, 2, 3], mask=mask)\n res = np.polyval([7, 5, 3], mx)\n assert_array_equal(res.mask, mask)\n\n # check subtypes of ndarray are preserved\n class C(np.ndarray):\n pass\n\n cx = np.array([1, 2, 3]).view(C)\n assert_equal(type(np.polyval([2, 3, 4], cx)), C)\n\n def test_polyvalfromroots(self):\n # check exception for broadcasting x values over root array with\n # too few dimensions\n assert_raises(ValueError, poly.polyvalfromroots,\n [1], [1], tensor=False)\n\n # check empty input\n assert_equal(poly.polyvalfromroots([], [1]).size, 0)\n assert_(poly.polyvalfromroots([], [1]).shape == (0,))\n\n # check empty input + multidimensional roots\n assert_equal(poly.polyvalfromroots([], [[1] * 5]).size, 0)\n assert_(poly.polyvalfromroots([], [[1] * 5]).shape == (5, 0))\n\n # check scalar input\n assert_equal(poly.polyvalfromroots(1, 1), 0)\n assert_(poly.polyvalfromroots(1, np.ones((3, 3))).shape == (3,))\n\n # check normal input)\n x = np.linspace(-1, 1)\n y = [x**i for i in range(5)]\n for i in range(1, 5):\n tgt = y[i]\n res = poly.polyvalfromroots(x, [0] * i)\n assert_almost_equal(res, tgt)\n tgt = x * (x - 1) * (x + 1)\n res = poly.polyvalfromroots(x, [-1, 0, 1])\n assert_almost_equal(res, tgt)\n\n # check that shape is preserved\n for i in range(3):\n dims = [2] * i\n x = np.zeros(dims)\n assert_equal(poly.polyvalfromroots(x, [1]).shape, dims)\n assert_equal(poly.polyvalfromroots(x, [1, 0]).shape, dims)\n assert_equal(poly.polyvalfromroots(x, [1, 0, 0]).shape, dims)\n\n # check compatibility with factorization\n ptest = [15, 2, -16, -2, 1]\n r = poly.polyroots(ptest)\n x = np.linspace(-1, 1)\n assert_almost_equal(poly.polyval(x, ptest),\n poly.polyvalfromroots(x, r))\n\n # check multidimensional arrays of roots and values\n # check tensor=False\n rshape = (3, 5)\n x = np.arange(-3, 2)\n r = np.random.randint(-5, 5, size=rshape)\n res = poly.polyvalfromroots(x, r, tensor=False)\n tgt = np.empty(r.shape[1:])\n for ii in range(tgt.size):\n tgt[ii] = poly.polyvalfromroots(x[ii], r[:, ii])\n assert_equal(res, tgt)\n\n # check tensor=True\n x = np.vstack([x, 2 * x])\n res = poly.polyvalfromroots(x, r, tensor=True)\n tgt = np.empty(r.shape[1:] + x.shape)\n for ii in range(r.shape[1]):\n for jj in range(x.shape[0]):\n tgt[ii, jj, :] = poly.polyvalfromroots(x[jj], r[:, ii])\n assert_equal(res, tgt)\n\n def test_polyval2d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test exceptions\n assert_raises_regex(ValueError, 'incompatible',\n poly.polyval2d, x1, x2[:2], self.c2d)\n\n # test values\n tgt = y1 * y2\n res = poly.polyval2d(x1, x2, self.c2d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = poly.polyval2d(z, z, self.c2d)\n assert_(res.shape == (2, 3))\n\n def test_polyval3d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test exceptions\n assert_raises_regex(ValueError, 'incompatible',\n poly.polyval3d, x1, x2, x3[:2], self.c3d)\n\n # test values\n tgt = y1 * y2 * y3\n res = poly.polyval3d(x1, x2, x3, self.c3d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = poly.polyval3d(z, z, z, self.c3d)\n assert_(res.shape == (2, 3))\n\n def test_polygrid2d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test values\n tgt = np.einsum('i,j->ij', y1, y2)\n res = poly.polygrid2d(x1, x2, self.c2d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = poly.polygrid2d(z, z, self.c2d)\n assert_(res.shape == (2, 3) * 2)\n\n def test_polygrid3d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n # test values\n tgt = np.einsum('i,j,k->ijk', y1, y2, y3)\n res = poly.polygrid3d(x1, x2, x3, self.c3d)\n assert_almost_equal(res, tgt)\n\n # test shape\n z = np.ones((2, 3))\n res = poly.polygrid3d(z, z, z, self.c3d)\n assert_(res.shape == (2, 3) * 3)\n\n\nclass TestIntegral:\n\n def test_polyint(self):\n # check exceptions\n assert_raises(TypeError, poly.polyint, [0], .5)\n assert_raises(ValueError, poly.polyint, [0], -1)\n assert_raises(ValueError, poly.polyint, [0], 1, [0, 0])\n assert_raises(ValueError, poly.polyint, [0], lbnd=[0])\n assert_raises(ValueError, poly.polyint, [0], scl=[0])\n assert_raises(TypeError, poly.polyint, [0], axis=.5)\n assert_raises(TypeError, poly.polyint, [1, 1], 1.)\n\n # test integration of zero polynomial\n for i in range(2, 5):\n k = [0] * (i - 2) + [1]\n res = poly.polyint([0], m=i, k=k)\n assert_almost_equal(res, [0, 1])\n\n # check single integration with integration constant\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n tgt = [i] + [0] * i + [1 / scl]\n res = poly.polyint(pol, m=1, k=[i])\n assert_almost_equal(trim(res), trim(tgt))\n\n # check single integration with integration constant and lbnd\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n res = poly.polyint(pol, m=1, k=[i], lbnd=-1)\n assert_almost_equal(poly.polyval(-1, res), i)\n\n # check single integration with integration constant and scaling\n for i in range(5):\n scl = i + 1\n pol = [0] * i + [1]\n tgt = [i] + [0] * i + [2 / scl]\n res = poly.polyint(pol, m=1, k=[i], scl=2)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with default k\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = poly.polyint(tgt, m=1)\n res = poly.polyint(pol, m=j)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with defined k\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = poly.polyint(tgt, m=1, k=[k])\n res = poly.polyint(pol, m=j, k=list(range(j)))\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with lbnd\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = poly.polyint(tgt, m=1, k=[k], lbnd=-1)\n res = poly.polyint(pol, m=j, k=list(range(j)), lbnd=-1)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with scaling\n for i in range(5):\n for j in range(2, 5):\n pol = [0] * i + [1]\n tgt = pol[:]\n for k in range(j):\n tgt = poly.polyint(tgt, m=1, k=[k], scl=2)\n res = poly.polyint(pol, m=j, k=list(range(j)), scl=2)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_polyint_axis(self):\n # check that axis keyword works\n c2d = np.random.random((3, 4))\n\n tgt = np.vstack([poly.polyint(c) for c in c2d.T]).T\n res = poly.polyint(c2d, axis=0)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([poly.polyint(c) for c in c2d])\n res = poly.polyint(c2d, axis=1)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([poly.polyint(c, k=3) for c in c2d])\n res = poly.polyint(c2d, k=3, axis=1)\n assert_almost_equal(res, tgt)\n\n\nclass TestDerivative:\n\n def test_polyder(self):\n # check exceptions\n assert_raises(TypeError, poly.polyder, [0], .5)\n assert_raises(ValueError, poly.polyder, [0], -1)\n\n # check that zeroth derivative does nothing\n for i in range(5):\n tgt = [0] * i + [1]\n res = poly.polyder(tgt, m=0)\n assert_equal(trim(res), trim(tgt))\n\n # check that derivation is the inverse of integration\n for i in range(5):\n for j in range(2, 5):\n tgt = [0] * i + [1]\n res = poly.polyder(poly.polyint(tgt, m=j), m=j)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check derivation with scaling\n for i in range(5):\n for j in range(2, 5):\n tgt = [0] * i + [1]\n res = poly.polyder(poly.polyint(tgt, m=j, scl=2), m=j, scl=.5)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_polyder_axis(self):\n # check that axis keyword works\n c2d = np.random.random((3, 4))\n\n tgt = np.vstack([poly.polyder(c) for c in c2d.T]).T\n res = poly.polyder(c2d, axis=0)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([poly.polyder(c) for c in c2d])\n res = poly.polyder(c2d, axis=1)\n assert_almost_equal(res, tgt)\n\n\nclass TestVander:\n # some random values in [-1, 1)\n x = np.random.random((3, 5)) * 2 - 1\n\n def test_polyvander(self):\n # check for 1d x\n x = np.arange(3)\n v = poly.polyvander(x, 3)\n assert_(v.shape == (3, 4))\n for i in range(4):\n coef = [0] * i + [1]\n assert_almost_equal(v[..., i], poly.polyval(x, coef))\n\n # check for 2d x\n x = np.array([[1, 2], [3, 4], [5, 6]])\n v = poly.polyvander(x, 3)\n assert_(v.shape == (3, 2, 4))\n for i in range(4):\n coef = [0] * i + [1]\n assert_almost_equal(v[..., i], poly.polyval(x, coef))\n\n def test_polyvander2d(self):\n # also tests polyval2d for non-square coefficient array\n x1, x2, x3 = self.x\n c = np.random.random((2, 3))\n van = poly.polyvander2d(x1, x2, [1, 2])\n tgt = poly.polyval2d(x1, x2, c)\n res = np.dot(van, c.flat)\n assert_almost_equal(res, tgt)\n\n # check shape\n van = poly.polyvander2d([x1], [x2], [1, 2])\n assert_(van.shape == (1, 5, 6))\n\n def test_polyvander3d(self):\n # also tests polyval3d for non-square coefficient array\n x1, x2, x3 = self.x\n c = np.random.random((2, 3, 4))\n van = poly.polyvander3d(x1, x2, x3, [1, 2, 3])\n tgt = poly.polyval3d(x1, x2, x3, c)\n res = np.dot(van, c.flat)\n assert_almost_equal(res, tgt)\n\n # check shape\n van = poly.polyvander3d([x1], [x2], [x3], [1, 2, 3])\n assert_(van.shape == (1, 5, 24))\n\n def test_polyvandernegdeg(self):\n x = np.arange(3)\n assert_raises(ValueError, poly.polyvander, x, -1)\n\n\nclass TestCompanion:\n\n def test_raises(self):\n assert_raises(ValueError, poly.polycompanion, [])\n assert_raises(ValueError, poly.polycompanion, [1])\n\n def test_dimensions(self):\n for i in range(1, 5):\n coef = [0] * i + [1]\n assert_(poly.polycompanion(coef).shape == (i, i))\n\n def test_linear_root(self):\n assert_(poly.polycompanion([1, 2])[0, 0] == -.5)\n\n\nclass TestMisc:\n\n def test_polyfromroots(self):\n res = poly.polyfromroots([])\n assert_almost_equal(trim(res), [1])\n for i in range(1, 5):\n roots = np.cos(np.linspace(-np.pi, 0, 2 * i + 1)[1::2])\n tgt = Tlist[i]\n res = poly.polyfromroots(roots) * 2**(i - 1)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_polyroots(self):\n assert_almost_equal(poly.polyroots([1]), [])\n assert_almost_equal(poly.polyroots([1, 2]), [-.5])\n for i in range(2, 5):\n tgt = np.linspace(-1, 1, i)\n res = poly.polyroots(poly.polyfromroots(tgt))\n assert_almost_equal(trim(res), trim(tgt))\n\n # Testing for larger root values\n for i in np.logspace(10, 25, num=1000, base=10):\n tgt = np.array([-1, 1, i])\n res = poly.polyroots(poly.polyfromroots(tgt))\n # Adapting the expected precision according to the root value,\n # to take into account numerical calculation error.\n assert_almost_equal(res, tgt, 15 - int(np.log10(i)))\n for i in np.logspace(10, 25, num=1000, base=10):\n tgt = np.array([-1, 1.01, i])\n res = poly.polyroots(poly.polyfromroots(tgt))\n # Adapting the expected precision according to the root value,\n # to take into account numerical calculation error.\n assert_almost_equal(res, tgt, 14 - int(np.log10(i)))\n\n def test_polyfit(self):\n def f(x):\n return x * (x - 1) * (x - 2)\n\n def f2(x):\n return x**4 + x**2 + 1\n\n # Test exceptions\n assert_raises(ValueError, poly.polyfit, [1], [1], -1)\n assert_raises(TypeError, poly.polyfit, [[1]], [1], 0)\n assert_raises(TypeError, poly.polyfit, [], [1], 0)\n assert_raises(TypeError, poly.polyfit, [1], [[[1]]], 0)\n assert_raises(TypeError, poly.polyfit, [1, 2], [1], 0)\n assert_raises(TypeError, poly.polyfit, [1], [1, 2], 0)\n assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[[1]])\n assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[1, 1])\n assert_raises(ValueError, poly.polyfit, [1], [1], [-1,])\n assert_raises(ValueError, poly.polyfit, [1], [1], [2, -1, 6])\n assert_raises(TypeError, poly.polyfit, [1], [1], [])\n\n # Test fit\n x = np.linspace(0, 2)\n y = f(x)\n #\n coef3 = poly.polyfit(x, y, 3)\n assert_equal(len(coef3), 4)\n assert_almost_equal(poly.polyval(x, coef3), y)\n coef3 = poly.polyfit(x, y, [0, 1, 2, 3])\n assert_equal(len(coef3), 4)\n assert_almost_equal(poly.polyval(x, coef3), y)\n #\n coef4 = poly.polyfit(x, y, 4)\n assert_equal(len(coef4), 5)\n assert_almost_equal(poly.polyval(x, coef4), y)\n coef4 = poly.polyfit(x, y, [0, 1, 2, 3, 4])\n assert_equal(len(coef4), 5)\n assert_almost_equal(poly.polyval(x, coef4), y)\n #\n coef2d = poly.polyfit(x, np.array([y, y]).T, 3)\n assert_almost_equal(coef2d, np.array([coef3, coef3]).T)\n coef2d = poly.polyfit(x, np.array([y, y]).T, [0, 1, 2, 3])\n assert_almost_equal(coef2d, np.array([coef3, coef3]).T)\n # test weighting\n w = np.zeros_like(x)\n yw = y.copy()\n w[1::2] = 1\n yw[0::2] = 0\n wcoef3 = poly.polyfit(x, yw, 3, w=w)\n assert_almost_equal(wcoef3, coef3)\n wcoef3 = poly.polyfit(x, yw, [0, 1, 2, 3], w=w)\n assert_almost_equal(wcoef3, coef3)\n #\n wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, 3, w=w)\n assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)\n wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)\n assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)\n # test scaling with complex values x points whose square\n # is zero when summed.\n x = [1, 1j, -1, -1j]\n assert_almost_equal(poly.polyfit(x, x, 1), [0, 1])\n assert_almost_equal(poly.polyfit(x, x, [0, 1]), [0, 1])\n # test fitting only even Polyendre polynomials\n x = np.linspace(-1, 1)\n y = f2(x)\n coef1 = poly.polyfit(x, y, 4)\n assert_almost_equal(poly.polyval(x, coef1), y)\n coef2 = poly.polyfit(x, y, [0, 2, 4])\n assert_almost_equal(poly.polyval(x, coef2), y)\n assert_almost_equal(coef1, coef2)\n\n def test_polytrim(self):\n coef = [2, -1, 1, 0]\n\n # Test exceptions\n assert_raises(ValueError, poly.polytrim, coef, -1)\n\n # Test results\n assert_equal(poly.polytrim(coef), coef[:-1])\n assert_equal(poly.polytrim(coef, 1), coef[:-3])\n assert_equal(poly.polytrim(coef, 2), [0])\n\n def test_polyline(self):\n assert_equal(poly.polyline(3, 4), [3, 4])\n\n def test_polyline_zero(self):\n assert_equal(poly.polyline(3, 0), [3])\n\n def test_fit_degenerate_domain(self):\n p = poly.Polynomial.fit([1], [2], deg=0)\n assert_equal(p.coef, [2.])\n p = poly.Polynomial.fit([1, 1], [2, 2.1], deg=0)\n assert_almost_equal(p.coef, [2.05])\n with assert_warns(pu.RankWarning):\n p = poly.Polynomial.fit([1, 1], [2, 2.1], deg=1)\n\n def test_result_type(self):\n w = np.array([-1, 1], dtype=np.float32)\n p = np.polynomial.Polynomial(w, domain=w, window=w)\n v = p(2)\n assert_equal(v.dtype, np.float32)\n\n arr = np.polydiv(1, np.float32(1))\n assert_equal(arr[0].dtype, np.float64)\n | .venv\Lib\site-packages\numpy\polynomial\tests\test_polynomial.py | test_polynomial.py | Python | 23,580 | 0.95 | 0.165919 | 0.127698 | vue-tools | 286 | 2025-02-09T08:05:23.615004 | GPL-3.0 | true | c256efa10ba3cff3fccd86cf9553073d |
"""Tests for polyutils module.\n\n"""\nimport numpy as np\nimport numpy.polynomial.polyutils as pu\nfrom numpy.testing import (\n assert_,\n assert_almost_equal,\n assert_equal,\n assert_raises,\n)\n\n\nclass TestMisc:\n\n def test_trimseq(self):\n tgt = [1]\n for num_trailing_zeros in range(5):\n res = pu.trimseq([1] + [0] * num_trailing_zeros)\n assert_equal(res, tgt)\n\n def test_trimseq_empty_input(self):\n for empty_seq in [[], np.array([], dtype=np.int32)]:\n assert_equal(pu.trimseq(empty_seq), empty_seq)\n\n def test_as_series(self):\n # check exceptions\n assert_raises(ValueError, pu.as_series, [[]])\n assert_raises(ValueError, pu.as_series, [[[1, 2]]])\n assert_raises(ValueError, pu.as_series, [[1], ['a']])\n # check common types\n types = ['i', 'd', 'O']\n for i in range(len(types)):\n for j in range(i):\n ci = np.ones(1, types[i])\n cj = np.ones(1, types[j])\n [resi, resj] = pu.as_series([ci, cj])\n assert_(resi.dtype.char == resj.dtype.char)\n assert_(resj.dtype.char == types[i])\n\n def test_trimcoef(self):\n coef = [2, -1, 1, 0]\n # Test exceptions\n assert_raises(ValueError, pu.trimcoef, coef, -1)\n # Test results\n assert_equal(pu.trimcoef(coef), coef[:-1])\n assert_equal(pu.trimcoef(coef, 1), coef[:-3])\n assert_equal(pu.trimcoef(coef, 2), [0])\n\n def test_vander_nd_exception(self):\n # n_dims != len(points)\n assert_raises(ValueError, pu._vander_nd, (), (1, 2, 3), [90])\n # n_dims != len(degrees)\n assert_raises(ValueError, pu._vander_nd, (), (), [90.65])\n # n_dims == 0\n assert_raises(ValueError, pu._vander_nd, (), (), [])\n\n def test_div_zerodiv(self):\n # c2[-1] == 0\n assert_raises(ZeroDivisionError, pu._div, pu._div, (1, 2, 3), [0])\n\n def test_pow_too_large(self):\n # power > maxpower\n assert_raises(ValueError, pu._pow, (), [1, 2, 3], 5, 4)\n\nclass TestDomain:\n\n def test_getdomain(self):\n # test for real values\n x = [1, 10, 3, -1]\n tgt = [-1, 10]\n res = pu.getdomain(x)\n assert_almost_equal(res, tgt)\n\n # test for complex values\n x = [1 + 1j, 1 - 1j, 0, 2]\n tgt = [-1j, 2 + 1j]\n res = pu.getdomain(x)\n assert_almost_equal(res, tgt)\n\n def test_mapdomain(self):\n # test for real values\n dom1 = [0, 4]\n dom2 = [1, 3]\n tgt = dom2\n res = pu.mapdomain(dom1, dom1, dom2)\n assert_almost_equal(res, tgt)\n\n # test for complex values\n dom1 = [0 - 1j, 2 + 1j]\n dom2 = [-2, 2]\n tgt = dom2\n x = dom1\n res = pu.mapdomain(x, dom1, dom2)\n assert_almost_equal(res, tgt)\n\n # test for multidimensional arrays\n dom1 = [0, 4]\n dom2 = [1, 3]\n tgt = np.array([dom2, dom2])\n x = np.array([dom1, dom1])\n res = pu.mapdomain(x, dom1, dom2)\n assert_almost_equal(res, tgt)\n\n # test that subtypes are preserved.\n class MyNDArray(np.ndarray):\n pass\n\n dom1 = [0, 4]\n dom2 = [1, 3]\n x = np.array([dom1, dom1]).view(MyNDArray)\n res = pu.mapdomain(x, dom1, dom2)\n assert_(isinstance(res, MyNDArray))\n\n def test_mapparms(self):\n # test for real values\n dom1 = [0, 4]\n dom2 = [1, 3]\n tgt = [1, .5]\n res = pu. mapparms(dom1, dom2)\n assert_almost_equal(res, tgt)\n\n # test for complex values\n dom1 = [0 - 1j, 2 + 1j]\n dom2 = [-2, 2]\n tgt = [-1 + 1j, 1 - 1j]\n res = pu.mapparms(dom1, dom2)\n assert_almost_equal(res, tgt)\n | .venv\Lib\site-packages\numpy\polynomial\tests\test_polyutils.py | test_polyutils.py | Python | 3,908 | 0.95 | 0.195313 | 0.157407 | awesome-app | 534 | 2024-03-14T00:36:11.822988 | Apache-2.0 | true | bce9f9d35643efd723ec2de1ac8be064 |
from decimal import Decimal\n\n# For testing polynomial printing with object arrays\nfrom fractions import Fraction\nfrom math import inf, nan\n\nimport pytest\n\nimport numpy.polynomial as poly\nfrom numpy._core import arange, array, printoptions\nfrom numpy.testing import assert_, assert_equal\n\n\nclass TestStrUnicodeSuperSubscripts:\n\n @pytest.fixture(scope='class', autouse=True)\n def use_unicode(self):\n poly.set_default_printstyle('unicode')\n\n @pytest.mark.parametrize(('inp', 'tgt'), (\n ([1, 2, 3], "1.0 + 2.0·x + 3.0·x²"),\n ([-1, 0, 3, -1], "-1.0 + 0.0·x + 3.0·x² - 1.0·x³"),\n (arange(12), ("0.0 + 1.0·x + 2.0·x² + 3.0·x³ + 4.0·x⁴ + 5.0·x⁵ + "\n "6.0·x⁶ + 7.0·x⁷ +\n8.0·x⁸ + 9.0·x⁹ + 10.0·x¹⁰ + "\n "11.0·x¹¹")),\n ))\n def test_polynomial_str(self, inp, tgt):\n p = poly.Polynomial(inp)\n res = str(p)\n assert_equal(res, tgt)\n\n @pytest.mark.parametrize(('inp', 'tgt'), (\n ([1, 2, 3], "1.0 + 2.0·T₁(x) + 3.0·T₂(x)"),\n ([-1, 0, 3, -1], "-1.0 + 0.0·T₁(x) + 3.0·T₂(x) - 1.0·T₃(x)"),\n (arange(12), ("0.0 + 1.0·T₁(x) + 2.0·T₂(x) + 3.0·T₃(x) + 4.0·T₄(x) + "\n "5.0·T₅(x) +\n6.0·T₆(x) + 7.0·T₇(x) + 8.0·T₈(x) + "\n "9.0·T₉(x) + 10.0·T₁₀(x) + 11.0·T₁₁(x)")),\n ))\n def test_chebyshev_str(self, inp, tgt):\n res = str(poly.Chebyshev(inp))\n assert_equal(res, tgt)\n\n @pytest.mark.parametrize(('inp', 'tgt'), (\n ([1, 2, 3], "1.0 + 2.0·P₁(x) + 3.0·P₂(x)"),\n ([-1, 0, 3, -1], "-1.0 + 0.0·P₁(x) + 3.0·P₂(x) - 1.0·P₃(x)"),\n (arange(12), ("0.0 + 1.0·P₁(x) + 2.0·P₂(x) + 3.0·P₃(x) + 4.0·P₄(x) + "\n "5.0·P₅(x) +\n6.0·P₆(x) + 7.0·P₇(x) + 8.0·P₈(x) + "\n "9.0·P₉(x) + 10.0·P₁₀(x) + 11.0·P₁₁(x)")),\n ))\n def test_legendre_str(self, inp, tgt):\n res = str(poly.Legendre(inp))\n assert_equal(res, tgt)\n\n @pytest.mark.parametrize(('inp', 'tgt'), (\n ([1, 2, 3], "1.0 + 2.0·H₁(x) + 3.0·H₂(x)"),\n ([-1, 0, 3, -1], "-1.0 + 0.0·H₁(x) + 3.0·H₂(x) - 1.0·H₃(x)"),\n (arange(12), ("0.0 + 1.0·H₁(x) + 2.0·H₂(x) + 3.0·H₃(x) + 4.0·H₄(x) + "\n "5.0·H₅(x) +\n6.0·H₆(x) + 7.0·H₇(x) + 8.0·H₈(x) + "\n "9.0·H₉(x) + 10.0·H₁₀(x) + 11.0·H₁₁(x)")),\n ))\n def test_hermite_str(self, inp, tgt):\n res = str(poly.Hermite(inp))\n assert_equal(res, tgt)\n\n @pytest.mark.parametrize(('inp', 'tgt'), (\n ([1, 2, 3], "1.0 + 2.0·He₁(x) + 3.0·He₂(x)"),\n ([-1, 0, 3, -1], "-1.0 + 0.0·He₁(x) + 3.0·He₂(x) - 1.0·He₃(x)"),\n (arange(12), ("0.0 + 1.0·He₁(x) + 2.0·He₂(x) + 3.0·He₃(x) + "\n "4.0·He₄(x) + 5.0·He₅(x) +\n6.0·He₆(x) + 7.0·He₇(x) + "\n "8.0·He₈(x) + 9.0·He₉(x) + 10.0·He₁₀(x) +\n"\n "11.0·He₁₁(x)")),\n ))\n def test_hermiteE_str(self, inp, tgt):\n res = str(poly.HermiteE(inp))\n assert_equal(res, tgt)\n\n @pytest.mark.parametrize(('inp', 'tgt'), (\n ([1, 2, 3], "1.0 + 2.0·L₁(x) + 3.0·L₂(x)"),\n ([-1, 0, 3, -1], "-1.0 + 0.0·L₁(x) + 3.0·L₂(x) - 1.0·L₃(x)"),\n (arange(12), ("0.0 + 1.0·L₁(x) + 2.0·L₂(x) + 3.0·L₃(x) + 4.0·L₄(x) + "\n "5.0·L₅(x) +\n6.0·L₆(x) + 7.0·L₇(x) + 8.0·L₈(x) + "\n "9.0·L₉(x) + 10.0·L₁₀(x) + 11.0·L₁₁(x)")),\n ))\n def test_laguerre_str(self, inp, tgt):\n res = str(poly.Laguerre(inp))\n assert_equal(res, tgt)\n\n def test_polynomial_str_domains(self):\n res = str(poly.Polynomial([0, 1]))\n tgt = '0.0 + 1.0·x'\n assert_equal(res, tgt)\n\n res = str(poly.Polynomial([0, 1], domain=[1, 2]))\n tgt = '0.0 + 1.0·(-3.0 + 2.0x)'\n assert_equal(res, tgt)\n\nclass TestStrAscii:\n\n @pytest.fixture(scope='class', autouse=True)\n def use_ascii(self):\n poly.set_default_printstyle('ascii')\n\n @pytest.mark.parametrize(('inp', 'tgt'), (\n ([1, 2, 3], "1.0 + 2.0 x + 3.0 x**2"),\n ([-1, 0, 3, -1], "-1.0 + 0.0 x + 3.0 x**2 - 1.0 x**3"),\n (arange(12), ("0.0 + 1.0 x + 2.0 x**2 + 3.0 x**3 + 4.0 x**4 + "\n "5.0 x**5 + 6.0 x**6 +\n7.0 x**7 + 8.0 x**8 + "\n "9.0 x**9 + 10.0 x**10 + 11.0 x**11")),\n ))\n def test_polynomial_str(self, inp, tgt):\n res = str(poly.Polynomial(inp))\n assert_equal(res, tgt)\n\n @pytest.mark.parametrize(('inp', 'tgt'), (\n ([1, 2, 3], "1.0 + 2.0 T_1(x) + 3.0 T_2(x)"),\n ([-1, 0, 3, -1], "-1.0 + 0.0 T_1(x) + 3.0 T_2(x) - 1.0 T_3(x)"),\n (arange(12), ("0.0 + 1.0 T_1(x) + 2.0 T_2(x) + 3.0 T_3(x) + "\n "4.0 T_4(x) + 5.0 T_5(x) +\n6.0 T_6(x) + 7.0 T_7(x) + "\n "8.0 T_8(x) + 9.0 T_9(x) + 10.0 T_10(x) +\n"\n "11.0 T_11(x)")),\n ))\n def test_chebyshev_str(self, inp, tgt):\n res = str(poly.Chebyshev(inp))\n assert_equal(res, tgt)\n\n @pytest.mark.parametrize(('inp', 'tgt'), (\n ([1, 2, 3], "1.0 + 2.0 P_1(x) + 3.0 P_2(x)"),\n ([-1, 0, 3, -1], "-1.0 + 0.0 P_1(x) + 3.0 P_2(x) - 1.0 P_3(x)"),\n (arange(12), ("0.0 + 1.0 P_1(x) + 2.0 P_2(x) + 3.0 P_3(x) + "\n "4.0 P_4(x) + 5.0 P_5(x) +\n6.0 P_6(x) + 7.0 P_7(x) + "\n "8.0 P_8(x) + 9.0 P_9(x) + 10.0 P_10(x) +\n"\n "11.0 P_11(x)")),\n ))\n def test_legendre_str(self, inp, tgt):\n res = str(poly.Legendre(inp))\n assert_equal(res, tgt)\n\n @pytest.mark.parametrize(('inp', 'tgt'), (\n ([1, 2, 3], "1.0 + 2.0 H_1(x) + 3.0 H_2(x)"),\n ([-1, 0, 3, -1], "-1.0 + 0.0 H_1(x) + 3.0 H_2(x) - 1.0 H_3(x)"),\n (arange(12), ("0.0 + 1.0 H_1(x) + 2.0 H_2(x) + 3.0 H_3(x) + "\n "4.0 H_4(x) + 5.0 H_5(x) +\n6.0 H_6(x) + 7.0 H_7(x) + "\n "8.0 H_8(x) + 9.0 H_9(x) + 10.0 H_10(x) +\n"\n "11.0 H_11(x)")),\n ))\n def test_hermite_str(self, inp, tgt):\n res = str(poly.Hermite(inp))\n assert_equal(res, tgt)\n\n @pytest.mark.parametrize(('inp', 'tgt'), (\n ([1, 2, 3], "1.0 + 2.0 He_1(x) + 3.0 He_2(x)"),\n ([-1, 0, 3, -1], "-1.0 + 0.0 He_1(x) + 3.0 He_2(x) - 1.0 He_3(x)"),\n (arange(12), ("0.0 + 1.0 He_1(x) + 2.0 He_2(x) + 3.0 He_3(x) + "\n "4.0 He_4(x) +\n5.0 He_5(x) + 6.0 He_6(x) + "\n "7.0 He_7(x) + 8.0 He_8(x) + 9.0 He_9(x) +\n"\n "10.0 He_10(x) + 11.0 He_11(x)")),\n ))\n def test_hermiteE_str(self, inp, tgt):\n res = str(poly.HermiteE(inp))\n assert_equal(res, tgt)\n\n @pytest.mark.parametrize(('inp', 'tgt'), (\n ([1, 2, 3], "1.0 + 2.0 L_1(x) + 3.0 L_2(x)"),\n ([-1, 0, 3, -1], "-1.0 + 0.0 L_1(x) + 3.0 L_2(x) - 1.0 L_3(x)"),\n (arange(12), ("0.0 + 1.0 L_1(x) + 2.0 L_2(x) + 3.0 L_3(x) + "\n "4.0 L_4(x) + 5.0 L_5(x) +\n6.0 L_6(x) + 7.0 L_7(x) + "\n "8.0 L_8(x) + 9.0 L_9(x) + 10.0 L_10(x) +\n"\n "11.0 L_11(x)")),\n ))\n def test_laguerre_str(self, inp, tgt):\n res = str(poly.Laguerre(inp))\n assert_equal(res, tgt)\n\n def test_polynomial_str_domains(self):\n res = str(poly.Polynomial([0, 1]))\n tgt = '0.0 + 1.0 x'\n assert_equal(res, tgt)\n\n res = str(poly.Polynomial([0, 1], domain=[1, 2]))\n tgt = '0.0 + 1.0 (-3.0 + 2.0x)'\n assert_equal(res, tgt)\n\nclass TestLinebreaking:\n\n @pytest.fixture(scope='class', autouse=True)\n def use_ascii(self):\n poly.set_default_printstyle('ascii')\n\n def test_single_line_one_less(self):\n # With 'ascii' style, len(str(p)) is default linewidth - 1 (i.e. 74)\n p = poly.Polynomial([12345678, 12345678, 12345678, 12345678, 123])\n assert_equal(len(str(p)), 74)\n assert_equal(str(p), (\n '12345678.0 + 12345678.0 x + 12345678.0 x**2 + '\n '12345678.0 x**3 + 123.0 x**4'\n ))\n\n def test_num_chars_is_linewidth(self):\n # len(str(p)) == default linewidth == 75\n p = poly.Polynomial([12345678, 12345678, 12345678, 12345678, 1234])\n assert_equal(len(str(p)), 75)\n assert_equal(str(p), (\n '12345678.0 + 12345678.0 x + 12345678.0 x**2 + '\n '12345678.0 x**3 +\n1234.0 x**4'\n ))\n\n def test_first_linebreak_multiline_one_less_than_linewidth(self):\n # Multiline str where len(first_line) + len(next_term) == lw - 1 == 74\n p = poly.Polynomial(\n [12345678, 12345678, 12345678, 12345678, 1, 12345678]\n )\n assert_equal(len(str(p).split('\n')[0]), 74)\n assert_equal(str(p), (\n '12345678.0 + 12345678.0 x + 12345678.0 x**2 + '\n '12345678.0 x**3 + 1.0 x**4 +\n12345678.0 x**5'\n ))\n\n def test_first_linebreak_multiline_on_linewidth(self):\n # First line is one character longer than previous test\n p = poly.Polynomial(\n [12345678, 12345678, 12345678, 12345678.12, 1, 12345678]\n )\n assert_equal(str(p), (\n '12345678.0 + 12345678.0 x + 12345678.0 x**2 + '\n '12345678.12 x**3 +\n1.0 x**4 + 12345678.0 x**5'\n ))\n\n @pytest.mark.parametrize(('lw', 'tgt'), (\n (75, ('0.0 + 10.0 x + 200.0 x**2 + 3000.0 x**3 + 40000.0 x**4 + '\n '500000.0 x**5 +\n600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 + '\n '900.0 x**9')),\n (45, ('0.0 + 10.0 x + 200.0 x**2 + 3000.0 x**3 +\n40000.0 x**4 + '\n '500000.0 x**5 +\n600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 +\n'\n '900.0 x**9')),\n (132, ('0.0 + 10.0 x + 200.0 x**2 + 3000.0 x**3 + 40000.0 x**4 + '\n '500000.0 x**5 + 600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 + '\n '900.0 x**9')),\n ))\n def test_linewidth_printoption(self, lw, tgt):\n p = poly.Polynomial(\n [0, 10, 200, 3000, 40000, 500000, 600000, 70000, 8000, 900]\n )\n with printoptions(linewidth=lw):\n assert_equal(str(p), tgt)\n for line in str(p).split('\n'):\n assert_(len(line) < lw)\n\n\ndef test_set_default_printoptions():\n p = poly.Polynomial([1, 2, 3])\n c = poly.Chebyshev([1, 2, 3])\n poly.set_default_printstyle('ascii')\n assert_equal(str(p), "1.0 + 2.0 x + 3.0 x**2")\n assert_equal(str(c), "1.0 + 2.0 T_1(x) + 3.0 T_2(x)")\n poly.set_default_printstyle('unicode')\n assert_equal(str(p), "1.0 + 2.0·x + 3.0·x²")\n assert_equal(str(c), "1.0 + 2.0·T₁(x) + 3.0·T₂(x)")\n with pytest.raises(ValueError):\n poly.set_default_printstyle('invalid_input')\n\n\ndef test_complex_coefficients():\n """Test both numpy and built-in complex."""\n coefs = [0 + 1j, 1 + 1j, -2 + 2j, 3 + 0j]\n # numpy complex\n p1 = poly.Polynomial(coefs)\n # Python complex\n p2 = poly.Polynomial(array(coefs, dtype=object))\n poly.set_default_printstyle('unicode')\n assert_equal(str(p1), "1j + (1+1j)·x - (2-2j)·x² + (3+0j)·x³")\n assert_equal(str(p2), "1j + (1+1j)·x + (-2+2j)·x² + (3+0j)·x³")\n poly.set_default_printstyle('ascii')\n assert_equal(str(p1), "1j + (1+1j) x - (2-2j) x**2 + (3+0j) x**3")\n assert_equal(str(p2), "1j + (1+1j) x + (-2+2j) x**2 + (3+0j) x**3")\n\n\n@pytest.mark.parametrize(('coefs', 'tgt'), (\n (array([Fraction(1, 2), Fraction(3, 4)], dtype=object), (\n "1/2 + 3/4·x"\n )),\n (array([1, 2, Fraction(5, 7)], dtype=object), (\n "1 + 2·x + 5/7·x²"\n )),\n (array([Decimal('1.00'), Decimal('2.2'), 3], dtype=object), (\n "1.00 + 2.2·x + 3·x²"\n )),\n))\ndef test_numeric_object_coefficients(coefs, tgt):\n p = poly.Polynomial(coefs)\n poly.set_default_printstyle('unicode')\n assert_equal(str(p), tgt)\n\n\n@pytest.mark.parametrize(('coefs', 'tgt'), (\n (array([1, 2, 'f'], dtype=object), '1 + 2·x + f·x²'),\n (array([1, 2, [3, 4]], dtype=object), '1 + 2·x + [3, 4]·x²'),\n))\ndef test_nonnumeric_object_coefficients(coefs, tgt):\n """\n Test coef fallback for object arrays of non-numeric coefficients.\n """\n p = poly.Polynomial(coefs)\n poly.set_default_printstyle('unicode')\n assert_equal(str(p), tgt)\n\n\nclass TestFormat:\n def test_format_unicode(self):\n poly.set_default_printstyle('ascii')\n p = poly.Polynomial([1, 2, 0, -1])\n assert_equal(format(p, 'unicode'), "1.0 + 2.0·x + 0.0·x² - 1.0·x³")\n\n def test_format_ascii(self):\n poly.set_default_printstyle('unicode')\n p = poly.Polynomial([1, 2, 0, -1])\n assert_equal(\n format(p, 'ascii'), "1.0 + 2.0 x + 0.0 x**2 - 1.0 x**3"\n )\n\n def test_empty_formatstr(self):\n poly.set_default_printstyle('ascii')\n p = poly.Polynomial([1, 2, 3])\n assert_equal(format(p), "1.0 + 2.0 x + 3.0 x**2")\n assert_equal(f"{p}", "1.0 + 2.0 x + 3.0 x**2")\n\n def test_bad_formatstr(self):\n p = poly.Polynomial([1, 2, 0, -1])\n with pytest.raises(ValueError):\n format(p, '.2f')\n\n\n@pytest.mark.parametrize(('poly', 'tgt'), (\n (poly.Polynomial, '1.0 + 2.0·z + 3.0·z²'),\n (poly.Chebyshev, '1.0 + 2.0·T₁(z) + 3.0·T₂(z)'),\n (poly.Hermite, '1.0 + 2.0·H₁(z) + 3.0·H₂(z)'),\n (poly.HermiteE, '1.0 + 2.0·He₁(z) + 3.0·He₂(z)'),\n (poly.Laguerre, '1.0 + 2.0·L₁(z) + 3.0·L₂(z)'),\n (poly.Legendre, '1.0 + 2.0·P₁(z) + 3.0·P₂(z)'),\n))\ndef test_symbol(poly, tgt):\n p = poly([1, 2, 3], symbol='z')\n assert_equal(f"{p:unicode}", tgt)\n\n\nclass TestRepr:\n def test_polynomial_repr(self):\n res = repr(poly.Polynomial([0, 1]))\n tgt = (\n "Polynomial([0., 1.], domain=[-1., 1.], window=[-1., 1.], "\n "symbol='x')"\n )\n assert_equal(res, tgt)\n\n def test_chebyshev_repr(self):\n res = repr(poly.Chebyshev([0, 1]))\n tgt = (\n "Chebyshev([0., 1.], domain=[-1., 1.], window=[-1., 1.], "\n "symbol='x')"\n )\n assert_equal(res, tgt)\n\n def test_legendre_repr(self):\n res = repr(poly.Legendre([0, 1]))\n tgt = (\n "Legendre([0., 1.], domain=[-1., 1.], window=[-1., 1.], "\n "symbol='x')"\n )\n assert_equal(res, tgt)\n\n def test_hermite_repr(self):\n res = repr(poly.Hermite([0, 1]))\n tgt = (\n "Hermite([0., 1.], domain=[-1., 1.], window=[-1., 1.], "\n "symbol='x')"\n )\n assert_equal(res, tgt)\n\n def test_hermiteE_repr(self):\n res = repr(poly.HermiteE([0, 1]))\n tgt = (\n "HermiteE([0., 1.], domain=[-1., 1.], window=[-1., 1.], "\n "symbol='x')"\n )\n assert_equal(res, tgt)\n\n def test_laguerre_repr(self):\n res = repr(poly.Laguerre([0, 1]))\n tgt = (\n "Laguerre([0., 1.], domain=[0., 1.], window=[0., 1.], "\n "symbol='x')"\n )\n assert_equal(res, tgt)\n\n\nclass TestLatexRepr:\n """Test the latex repr used by Jupyter"""\n\n @staticmethod\n def as_latex(obj):\n # right now we ignore the formatting of scalars in our tests, since\n # it makes them too verbose. Ideally, the formatting of scalars will\n # be fixed such that tests below continue to pass\n obj._repr_latex_scalar = lambda x, parens=False: str(x)\n try:\n return obj._repr_latex_()\n finally:\n del obj._repr_latex_scalar\n\n def test_simple_polynomial(self):\n # default input\n p = poly.Polynomial([1, 2, 3])\n assert_equal(self.as_latex(p),\n r'$x \mapsto 1.0 + 2.0\,x + 3.0\,x^{2}$')\n\n # translated input\n p = poly.Polynomial([1, 2, 3], domain=[-2, 0])\n assert_equal(self.as_latex(p),\n r'$x \mapsto 1.0 + 2.0\,\left(1.0 + x\right) + 3.0\,\left(1.0 + x\right)^{2}$') # noqa: E501\n\n # scaled input\n p = poly.Polynomial([1, 2, 3], domain=[-0.5, 0.5])\n assert_equal(self.as_latex(p),\n r'$x \mapsto 1.0 + 2.0\,\left(2.0x\right) + 3.0\,\left(2.0x\right)^{2}$')\n\n # affine input\n p = poly.Polynomial([1, 2, 3], domain=[-1, 0])\n assert_equal(self.as_latex(p),\n r'$x \mapsto 1.0 + 2.0\,\left(1.0 + 2.0x\right) + 3.0\,\left(1.0 + 2.0x\right)^{2}$') # noqa: E501\n\n def test_basis_func(self):\n p = poly.Chebyshev([1, 2, 3])\n assert_equal(self.as_latex(p),\n r'$x \mapsto 1.0\,{T}_{0}(x) + 2.0\,{T}_{1}(x) + 3.0\,{T}_{2}(x)$')\n # affine input - check no surplus parens are added\n p = poly.Chebyshev([1, 2, 3], domain=[-1, 0])\n assert_equal(self.as_latex(p),\n r'$x \mapsto 1.0\,{T}_{0}(1.0 + 2.0x) + 2.0\,{T}_{1}(1.0 + 2.0x) + 3.0\,{T}_{2}(1.0 + 2.0x)$') # noqa: E501\n\n def test_multichar_basis_func(self):\n p = poly.HermiteE([1, 2, 3])\n assert_equal(self.as_latex(p),\n r'$x \mapsto 1.0\,{He}_{0}(x) + 2.0\,{He}_{1}(x) + 3.0\,{He}_{2}(x)$')\n\n def test_symbol_basic(self):\n # default input\n p = poly.Polynomial([1, 2, 3], symbol='z')\n assert_equal(self.as_latex(p),\n r'$z \mapsto 1.0 + 2.0\,z + 3.0\,z^{2}$')\n\n # translated input\n p = poly.Polynomial([1, 2, 3], domain=[-2, 0], symbol='z')\n assert_equal(\n self.as_latex(p),\n (\n r'$z \mapsto 1.0 + 2.0\,\left(1.0 + z\right) + 3.0\,'\n r'\left(1.0 + z\right)^{2}$'\n ),\n )\n\n # scaled input\n p = poly.Polynomial([1, 2, 3], domain=[-0.5, 0.5], symbol='z')\n assert_equal(\n self.as_latex(p),\n (\n r'$z \mapsto 1.0 + 2.0\,\left(2.0z\right) + 3.0\,'\n r'\left(2.0z\right)^{2}$'\n ),\n )\n\n # affine input\n p = poly.Polynomial([1, 2, 3], domain=[-1, 0], symbol='z')\n assert_equal(\n self.as_latex(p),\n (\n r'$z \mapsto 1.0 + 2.0\,\left(1.0 + 2.0z\right) + 3.0\,'\n r'\left(1.0 + 2.0z\right)^{2}$'\n ),\n )\n\n def test_numeric_object_coefficients(self):\n coefs = array([Fraction(1, 2), Fraction(1)])\n p = poly.Polynomial(coefs)\n assert_equal(self.as_latex(p), '$x \\mapsto 1/2 + 1\\,x$')\n\n\nSWITCH_TO_EXP = (\n '1.0 + (1.0e-01) x + (1.0e-02) x**2',\n '1.2 + (1.2e-01) x + (1.2e-02) x**2',\n '1.23 + 0.12 x + (1.23e-02) x**2 + (1.23e-03) x**3',\n '1.235 + 0.123 x + (1.235e-02) x**2 + (1.235e-03) x**3',\n '1.2346 + 0.1235 x + 0.0123 x**2 + (1.2346e-03) x**3 + (1.2346e-04) x**4',\n '1.23457 + 0.12346 x + 0.01235 x**2 + (1.23457e-03) x**3 + '\n '(1.23457e-04) x**4',\n '1.234568 + 0.123457 x + 0.012346 x**2 + 0.001235 x**3 + '\n '(1.234568e-04) x**4 + (1.234568e-05) x**5',\n '1.2345679 + 0.1234568 x + 0.0123457 x**2 + 0.0012346 x**3 + '\n '(1.2345679e-04) x**4 + (1.2345679e-05) x**5')\n\nclass TestPrintOptions:\n """\n Test the output is properly configured via printoptions.\n The exponential notation is enabled automatically when the values\n are too small or too large.\n """\n\n @pytest.fixture(scope='class', autouse=True)\n def use_ascii(self):\n poly.set_default_printstyle('ascii')\n\n def test_str(self):\n p = poly.Polynomial([1 / 2, 1 / 7, 1 / 7 * 10**8, 1 / 7 * 10**9])\n assert_equal(str(p), '0.5 + 0.14285714 x + 14285714.28571429 x**2 '\n '+ (1.42857143e+08) x**3')\n\n with printoptions(precision=3):\n assert_equal(str(p), '0.5 + 0.143 x + 14285714.286 x**2 '\n '+ (1.429e+08) x**3')\n\n def test_latex(self):\n p = poly.Polynomial([1 / 2, 1 / 7, 1 / 7 * 10**8, 1 / 7 * 10**9])\n assert_equal(p._repr_latex_(),\n r'$x \mapsto \text{0.5} + \text{0.14285714}\,x + '\n r'\text{14285714.28571429}\,x^{2} + '\n r'\text{(1.42857143e+08)}\,x^{3}$')\n\n with printoptions(precision=3):\n assert_equal(p._repr_latex_(),\n r'$x \mapsto \text{0.5} + \text{0.143}\,x + '\n r'\text{14285714.286}\,x^{2} + \text{(1.429e+08)}\,x^{3}$')\n\n def test_fixed(self):\n p = poly.Polynomial([1 / 2])\n assert_equal(str(p), '0.5')\n\n with printoptions(floatmode='fixed'):\n assert_equal(str(p), '0.50000000')\n\n with printoptions(floatmode='fixed', precision=4):\n assert_equal(str(p), '0.5000')\n\n def test_switch_to_exp(self):\n for i, s in enumerate(SWITCH_TO_EXP):\n with printoptions(precision=i):\n p = poly.Polynomial([1.23456789 * 10**-i\n for i in range(i // 2 + 3)])\n assert str(p).replace('\n', ' ') == s\n\n def test_non_finite(self):\n p = poly.Polynomial([nan, inf])\n assert str(p) == 'nan + inf x'\n assert p._repr_latex_() == r'$x \mapsto \text{nan} + \text{inf}\,x$' # noqa: RUF027\n with printoptions(nanstr='NAN', infstr='INF'):\n assert str(p) == 'NAN + INF x'\n assert p._repr_latex_() == \\n r'$x \mapsto \text{NAN} + \text{INF}\,x$'\n | .venv\Lib\site-packages\numpy\polynomial\tests\test_printing.py | test_printing.py | Python | 21,958 | 0.95 | 0.117117 | 0.04 | python-kit | 62 | 2024-12-06T05:44:27.755385 | MIT | true | 53b4608d428fe37509e214b383c0fdd9 |
"""\nTests related to the ``symbol`` attribute of the ABCPolyBase class.\n"""\n\nimport pytest\n\nimport numpy.polynomial as poly\nfrom numpy._core import array\nfrom numpy.testing import assert_, assert_equal, assert_raises\n\n\nclass TestInit:\n """\n Test polynomial creation with symbol kwarg.\n """\n c = [1, 2, 3]\n\n def test_default_symbol(self):\n p = poly.Polynomial(self.c)\n assert_equal(p.symbol, 'x')\n\n @pytest.mark.parametrize(('bad_input', 'exception'), (\n ('', ValueError),\n ('3', ValueError),\n (None, TypeError),\n (1, TypeError),\n ))\n def test_symbol_bad_input(self, bad_input, exception):\n with pytest.raises(exception):\n p = poly.Polynomial(self.c, symbol=bad_input)\n\n @pytest.mark.parametrize('symbol', (\n 'x',\n 'x_1',\n 'A',\n 'xyz',\n 'β',\n ))\n def test_valid_symbols(self, symbol):\n """\n Values for symbol that should pass input validation.\n """\n p = poly.Polynomial(self.c, symbol=symbol)\n assert_equal(p.symbol, symbol)\n\n def test_property(self):\n """\n 'symbol' attribute is read only.\n """\n p = poly.Polynomial(self.c, symbol='x')\n with pytest.raises(AttributeError):\n p.symbol = 'z'\n\n def test_change_symbol(self):\n p = poly.Polynomial(self.c, symbol='y')\n # Create new polynomial from p with different symbol\n pt = poly.Polynomial(p.coef, symbol='t')\n assert_equal(pt.symbol, 't')\n\n\nclass TestUnaryOperators:\n p = poly.Polynomial([1, 2, 3], symbol='z')\n\n def test_neg(self):\n n = -self.p\n assert_equal(n.symbol, 'z')\n\n def test_scalarmul(self):\n out = self.p * 10\n assert_equal(out.symbol, 'z')\n\n def test_rscalarmul(self):\n out = 10 * self.p\n assert_equal(out.symbol, 'z')\n\n def test_pow(self):\n out = self.p ** 3\n assert_equal(out.symbol, 'z')\n\n\n@pytest.mark.parametrize(\n 'rhs',\n (\n poly.Polynomial([4, 5, 6], symbol='z'),\n array([4, 5, 6]),\n ),\n)\nclass TestBinaryOperatorsSameSymbol:\n """\n Ensure symbol is preserved for numeric operations on polynomials with\n the same symbol\n """\n p = poly.Polynomial([1, 2, 3], symbol='z')\n\n def test_add(self, rhs):\n out = self.p + rhs\n assert_equal(out.symbol, 'z')\n\n def test_sub(self, rhs):\n out = self.p - rhs\n assert_equal(out.symbol, 'z')\n\n def test_polymul(self, rhs):\n out = self.p * rhs\n assert_equal(out.symbol, 'z')\n\n def test_divmod(self, rhs):\n for out in divmod(self.p, rhs):\n assert_equal(out.symbol, 'z')\n\n def test_radd(self, rhs):\n out = rhs + self.p\n assert_equal(out.symbol, 'z')\n\n def test_rsub(self, rhs):\n out = rhs - self.p\n assert_equal(out.symbol, 'z')\n\n def test_rmul(self, rhs):\n out = rhs * self.p\n assert_equal(out.symbol, 'z')\n\n def test_rdivmod(self, rhs):\n for out in divmod(rhs, self.p):\n assert_equal(out.symbol, 'z')\n\n\nclass TestBinaryOperatorsDifferentSymbol:\n p = poly.Polynomial([1, 2, 3], symbol='x')\n other = poly.Polynomial([4, 5, 6], symbol='y')\n ops = (p.__add__, p.__sub__, p.__mul__, p.__floordiv__, p.__mod__)\n\n @pytest.mark.parametrize('f', ops)\n def test_binops_fails(self, f):\n assert_raises(ValueError, f, self.other)\n\n\nclass TestEquality:\n p = poly.Polynomial([1, 2, 3], symbol='x')\n\n def test_eq(self):\n other = poly.Polynomial([1, 2, 3], symbol='x')\n assert_(self.p == other)\n\n def test_neq(self):\n other = poly.Polynomial([1, 2, 3], symbol='y')\n assert_(not self.p == other)\n\n\nclass TestExtraMethods:\n """\n Test other methods for manipulating/creating polynomial objects.\n """\n p = poly.Polynomial([1, 2, 3, 0], symbol='z')\n\n def test_copy(self):\n other = self.p.copy()\n assert_equal(other.symbol, 'z')\n\n def test_trim(self):\n other = self.p.trim()\n assert_equal(other.symbol, 'z')\n\n def test_truncate(self):\n other = self.p.truncate(2)\n assert_equal(other.symbol, 'z')\n\n @pytest.mark.parametrize('kwarg', (\n {'domain': [-10, 10]},\n {'window': [-10, 10]},\n {'kind': poly.Chebyshev},\n ))\n def test_convert(self, kwarg):\n other = self.p.convert(**kwarg)\n assert_equal(other.symbol, 'z')\n\n def test_integ(self):\n other = self.p.integ()\n assert_equal(other.symbol, 'z')\n\n def test_deriv(self):\n other = self.p.deriv()\n assert_equal(other.symbol, 'z')\n\n\ndef test_composition():\n p = poly.Polynomial([3, 2, 1], symbol="t")\n q = poly.Polynomial([5, 1, 0, -1], symbol="λ_1")\n r = p(q)\n assert r.symbol == "λ_1"\n\n\n#\n# Class methods that result in new polynomial class instances\n#\n\n\ndef test_fit():\n x, y = (range(10),) * 2\n p = poly.Polynomial.fit(x, y, deg=1, symbol='z')\n assert_equal(p.symbol, 'z')\n\n\ndef test_froomroots():\n roots = [-2, 2]\n p = poly.Polynomial.fromroots(roots, symbol='z')\n assert_equal(p.symbol, 'z')\n\n\ndef test_identity():\n p = poly.Polynomial.identity(domain=[-1, 1], window=[5, 20], symbol='z')\n assert_equal(p.symbol, 'z')\n\n\ndef test_basis():\n p = poly.Polynomial.basis(3, symbol='z')\n assert_equal(p.symbol, 'z')\n | .venv\Lib\site-packages\numpy\polynomial\tests\test_symbol.py | test_symbol.py | Python | 5,592 | 0.95 | 0.202765 | 0.024242 | vue-tools | 618 | 2023-09-18T00:27:25.650369 | Apache-2.0 | true | deefbd7800b82c54b2f47d45a1d1ceef |
\n\n | .venv\Lib\site-packages\numpy\polynomial\tests\__pycache__\test_chebyshev.cpython-313.pyc | test_chebyshev.cpython-313.pyc | Other | 38,469 | 0.8 | 0.004274 | 0 | vue-tools | 459 | 2023-07-20T21:22:13.740636 | BSD-3-Clause | true | 103728ad28304c47a7434ebd450e0e82 |
\n\n | .venv\Lib\site-packages\numpy\polynomial\tests\__pycache__\test_classes.cpython-313.pyc | test_classes.cpython-313.pyc | Other | 32,969 | 0.8 | 0 | 0.008403 | vue-tools | 723 | 2023-11-30T05:06:22.298727 | GPL-3.0 | true | c730696646fbd43f42ba8605268f7836 |
\n\n | .venv\Lib\site-packages\numpy\polynomial\tests\__pycache__\test_hermite.cpython-313.pyc | test_hermite.cpython-313.pyc | Other | 34,309 | 0.8 | 0.004167 | 0 | python-kit | 950 | 2025-02-05T17:00:20.931689 | MIT | true | 0b177082a6bdf8a22a959e90277f04bb |
\n\n | .venv\Lib\site-packages\numpy\polynomial\tests\__pycache__\test_hermite_e.cpython-313.pyc | test_hermite_e.cpython-313.pyc | Other | 34,482 | 0.8 | 0.004405 | 0 | node-utils | 442 | 2024-05-13T19:48:23.394116 | Apache-2.0 | true | 19bda37e508c42742ef17ca09d76c519 |
\n\n | .venv\Lib\site-packages\numpy\polynomial\tests\__pycache__\test_laguerre.cpython-313.pyc | test_laguerre.cpython-313.pyc | Other | 33,068 | 0.8 | 0.004329 | 0 | vue-tools | 409 | 2024-05-09T14:05:59.145299 | MIT | true | f9a7a5400c6d89dfd8391f02162597c9 |
\n\n | .venv\Lib\site-packages\numpy\polynomial\tests\__pycache__\test_legendre.cpython-313.pyc | test_legendre.cpython-313.pyc | Other | 35,282 | 0.8 | 0.004219 | 0 | vue-tools | 927 | 2024-06-12T01:16:50.416544 | BSD-3-Clause | true | f7e74c3b7f37f2fc978f67c5510b3147 |
\n\n | .venv\Lib\site-packages\numpy\polynomial\tests\__pycache__\test_polynomial.cpython-313.pyc | test_polynomial.cpython-313.pyc | Other | 40,834 | 0.8 | 0.003704 | 0 | vue-tools | 138 | 2024-05-29T22:11:20.693614 | Apache-2.0 | true | eb9847ad9f8f21443fa0538225f6130f |
\n\n | .venv\Lib\site-packages\numpy\polynomial\tests\__pycache__\test_polyutils.cpython-313.pyc | test_polyutils.cpython-313.pyc | Other | 6,770 | 0.8 | 0.027027 | 0.03125 | vue-tools | 607 | 2023-10-29T20:08:13.772760 | GPL-3.0 | true | 47a1da60c06f452cc286e7b5917259f0 |
\n\n | .venv\Lib\site-packages\numpy\polynomial\tests\__pycache__\test_printing.cpython-313.pyc | test_printing.cpython-313.pyc | Other | 31,632 | 0.8 | 0.005076 | 0.005102 | python-kit | 170 | 2025-03-09T17:17:04.759971 | Apache-2.0 | true | 33f959e503aa3618ca4088e8a12bd06b |
\n\n | .venv\Lib\site-packages\numpy\polynomial\tests\__pycache__\test_symbol.cpython-313.pyc | test_symbol.cpython-313.pyc | Other | 12,638 | 0.8 | 0.041237 | 0.03125 | react-lib | 762 | 2024-01-22T15:12:45.103611 | BSD-3-Clause | true | 1e20f1ef5cf26258834862ab6f7c8f18 |
\n\n | .venv\Lib\site-packages\numpy\polynomial\tests\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 197 | 0.7 | 0 | 0 | node-utils | 545 | 2023-09-14T19:28:12.756163 | Apache-2.0 | true | f65c239edf10a61696cc3898fc0876b0 |
\n\n | .venv\Lib\site-packages\numpy\polynomial\__pycache__\chebyshev.cpython-313.pyc | chebyshev.cpython-313.pyc | Other | 67,226 | 0.75 | 0.055361 | 0.004888 | react-lib | 120 | 2024-07-20T05:08:46.988201 | BSD-3-Clause | false | 32c3d585d1274491c8f369fc53c61bb2 |
\n\n | .venv\Lib\site-packages\numpy\polynomial\__pycache__\hermite.cpython-313.pyc | hermite.cpython-313.pyc | Other | 58,535 | 0.75 | 0.049613 | 0.004615 | vue-tools | 284 | 2024-02-05T13:16:24.950394 | GPL-3.0 | false | 90f668a384053ba2c404a245cbd56934 |
\n\n | .venv\Lib\site-packages\numpy\polynomial\__pycache__\hermite_e.cpython-313.pyc | hermite_e.cpython-313.pyc | Other | 56,207 | 0.75 | 0.053324 | 0.004946 | awesome-app | 364 | 2024-10-01T20:31:00.593178 | BSD-3-Clause | false | d0ff80f954d47562c543b051076d72b5 |
\n\n | .venv\Lib\site-packages\numpy\polynomial\__pycache__\laguerre.cpython-313.pyc | laguerre.cpython-313.pyc | Other | 55,773 | 0.75 | 0.046496 | 0.006436 | vue-tools | 427 | 2024-09-05T23:21:40.018197 | Apache-2.0 | false | 5084383c5c7e0f20eb1e4e03b8c742db |
\n\n | .venv\Lib\site-packages\numpy\polynomial\__pycache__\legendre.cpython-313.pyc | legendre.cpython-313.pyc | Other | 54,613 | 0.75 | 0.050283 | 0.005063 | node-utils | 776 | 2025-05-15T02:51:13.079143 | Apache-2.0 | false | 679b6b9c6ffbfb78257fb06f6b459a17 |
\n\n | .venv\Lib\site-packages\numpy\polynomial\__pycache__\polynomial.cpython-313.pyc | polynomial.cpython-313.pyc | Other | 54,368 | 0.75 | 0.048421 | 0.003336 | python-kit | 282 | 2025-06-13T05:51:59.502584 | Apache-2.0 | false | 307ad39103211f0d823af20b4d402e84 |
\n\n | .venv\Lib\site-packages\numpy\polynomial\__pycache__\polyutils.cpython-313.pyc | polyutils.cpython-313.pyc | Other | 27,695 | 0.95 | 0.088129 | 0.006303 | vue-tools | 762 | 2023-10-08T04:57:45.366987 | MIT | false | c421264001b7304f442db3b09aa0d443 |
\n\n | .venv\Lib\site-packages\numpy\polynomial\__pycache__\_polybase.cpython-313.pyc | _polybase.cpython-313.pyc | Other | 45,868 | 0.95 | 0.102493 | 0 | awesome-app | 776 | 2024-12-20T07:28:49.032821 | GPL-3.0 | false | 8205bb14cc814cf0621fae7edb742c61 |
\n\n | .venv\Lib\site-packages\numpy\polynomial\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 6,812 | 0.95 | 0.14881 | 0.007092 | react-lib | 203 | 2024-03-03T18:32:22.077137 | GPL-3.0 | false | 1a4eb1b0dba1db5c18a99ad6246a7ae7 |
!<arch>\n/ -1 0 194 `\n | .venv\Lib\site-packages\numpy\random\bit_generator.cp313-win_amd64.lib | bit_generator.cp313-win_amd64.lib | Other | 2,120 | 0.8 | 0 | 0 | awesome-app | 369 | 2025-05-03T10:54:02.162878 | GPL-3.0 | false | dc1de00876a25a08a53f5b478b3b5b80 |
cimport numpy as np\nfrom libc.stdint cimport uint32_t, uint64_t\n\ncdef extern from "numpy/random/bitgen.h":\n struct bitgen:\n void *state\n uint64_t (*next_uint64)(void *st) nogil\n uint32_t (*next_uint32)(void *st) nogil\n double (*next_double)(void *st) nogil\n uint64_t (*next_raw)(void *st) nogil\n\n ctypedef bitgen bitgen_t\n\ncdef class BitGenerator():\n cdef readonly object _seed_seq\n cdef readonly object lock\n cdef bitgen_t _bitgen\n cdef readonly object _ctypes\n cdef readonly object _cffi\n cdef readonly object capsule\n\n\ncdef class SeedSequence():\n cdef readonly object entropy\n cdef readonly tuple spawn_key\n cdef readonly Py_ssize_t pool_size\n cdef readonly object pool\n cdef readonly uint32_t n_children_spawned\n\n cdef mix_entropy(self, np.ndarray[np.npy_uint32, ndim=1] mixer,\n np.ndarray[np.npy_uint32, ndim=1] entropy_array)\n cdef get_assembled_entropy(self)\n\ncdef class SeedlessSequence():\n pass\n | .venv\Lib\site-packages\numpy\random\bit_generator.pxd | bit_generator.pxd | Other | 1,042 | 0.85 | 0.085714 | 0 | awesome-app | 348 | 2025-03-14T13:20:37.223490 | MIT | false | de57fbbeaf4ec95b9d17509ec886e3e9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.