assassinlike commited on
Commit
c00558f
·
verified ·
1 Parent(s): 09152ac

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/__init__.py +95 -0
  2. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/__init__.pyi +28 -0
  3. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/_convertions.py +18 -0
  4. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/_convertions.pyi +4 -0
  5. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/_inspect.py +192 -0
  6. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/_inspect.pyi +70 -0
  7. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/_pep440.py +486 -0
  8. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/_pep440.pyi +118 -0
  9. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/doc/ufuncs.py +138 -0
  10. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/fft/_helper.pyi +44 -0
  11. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/API_CHANGES.txt +135 -0
  12. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/LICENSE +24 -0
  13. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/README.rst +236 -0
  14. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/__init__.py +53 -0
  15. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/__init__.pyi +458 -0
  16. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/core.py +0 -0
  17. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/core.pyi +0 -0
  18. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/extras.py +2266 -0
  19. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/extras.pyi +297 -0
  20. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/mrecords.py +762 -0
  21. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/mrecords.pyi +96 -0
  22. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/testutils.py +294 -0
  23. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/testutils.pyi +69 -0
  24. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/matrixlib/__init__.py +12 -0
  25. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/matrixlib/__init__.pyi +3 -0
  26. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/matrixlib/defmatrix.py +1119 -0
  27. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/matrixlib/defmatrix.pyi +218 -0
  28. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/__init__.py +0 -0
  29. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test__all__.py +10 -0
  30. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_configtool.py +51 -0
  31. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_ctypeslib.py +383 -0
  32. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_lazyloading.py +42 -0
  33. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_matlib.py +59 -0
  34. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_numpy_config.py +47 -0
  35. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_numpy_version.py +54 -0
  36. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_public_api.py +807 -0
  37. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_reloading.py +76 -0
  38. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_scripts.py +48 -0
  39. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_warnings.py +79 -0
  40. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/typing/__init__.py +233 -0
  41. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/typing/__init__.pyi +3 -0
  42. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/typing/mypy_plugin.py +200 -0
  43. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/__init__.cpython-311.pyc +0 -0
  44. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_core_metadata.cpython-311.pyc +0 -0
  45. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_core_utils.cpython-311.pyc +0 -0
  46. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_decorators.cpython-311.pyc +0 -0
  47. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_decorators_v1.cpython-311.pyc +0 -0
  48. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_discriminated_union.cpython-311.pyc +0 -0
  49. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_docs_extraction.cpython-311.pyc +0 -0
  50. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_forward_ref.cpython-311.pyc +0 -0
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/__init__.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This is a module for defining private helpers which do not depend on the
3
+ rest of NumPy.
4
+
5
+ Everything in here must be self-contained so that it can be
6
+ imported anywhere else without creating circular imports.
7
+ If a utility requires the import of NumPy, it probably belongs
8
+ in ``numpy._core``.
9
+ """
10
+
11
+ import functools
12
+ import warnings
13
+
14
+ from ._convertions import asbytes, asunicode
15
+
16
+
17
+ def set_module(module):
18
+ """Private decorator for overriding __module__ on a function or class.
19
+
20
+ Example usage::
21
+
22
+ @set_module('numpy')
23
+ def example():
24
+ pass
25
+
26
+ assert example.__module__ == 'numpy'
27
+ """
28
+ def decorator(func):
29
+ if module is not None:
30
+ if isinstance(func, type):
31
+ try:
32
+ func._module_source = func.__module__
33
+ except (AttributeError):
34
+ pass
35
+
36
+ func.__module__ = module
37
+ return func
38
+ return decorator
39
+
40
+
41
+ def _rename_parameter(old_names, new_names, dep_version=None):
42
+ """
43
+ Generate decorator for backward-compatible keyword renaming.
44
+
45
+ Apply the decorator generated by `_rename_parameter` to functions with a
46
+ renamed parameter to maintain backward-compatibility.
47
+
48
+ After decoration, the function behaves as follows:
49
+ If only the new parameter is passed into the function, behave as usual.
50
+ If only the old parameter is passed into the function (as a keyword), raise
51
+ a DeprecationWarning if `dep_version` is provided, and behave as usual
52
+ otherwise.
53
+ If both old and new parameters are passed into the function, raise a
54
+ DeprecationWarning if `dep_version` is provided, and raise the appropriate
55
+ TypeError (function got multiple values for argument).
56
+
57
+ Parameters
58
+ ----------
59
+ old_names : list of str
60
+ Old names of parameters
61
+ new_name : list of str
62
+ New names of parameters
63
+ dep_version : str, optional
64
+ Version of NumPy in which old parameter was deprecated in the format
65
+ 'X.Y.Z'. If supplied, the deprecation message will indicate that
66
+ support for the old parameter will be removed in version 'X.Y+2.Z'
67
+
68
+ Notes
69
+ -----
70
+ Untested with functions that accept *args. Probably won't work as written.
71
+
72
+ """
73
+ def decorator(fun):
74
+ @functools.wraps(fun)
75
+ def wrapper(*args, **kwargs):
76
+ __tracebackhide__ = True # Hide traceback for py.test
77
+ for old_name, new_name in zip(old_names, new_names):
78
+ if old_name in kwargs:
79
+ if dep_version:
80
+ end_version = dep_version.split('.')
81
+ end_version[1] = str(int(end_version[1]) + 2)
82
+ end_version = '.'.join(end_version)
83
+ msg = (f"Use of keyword argument `{old_name}` is "
84
+ f"deprecated and replaced by `{new_name}`. "
85
+ f"Support for `{old_name}` will be removed "
86
+ f"in NumPy {end_version}.")
87
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
88
+ if new_name in kwargs:
89
+ msg = (f"{fun.__name__}() got multiple values for "
90
+ f"argument now known as `{new_name}`")
91
+ raise TypeError(msg)
92
+ kwargs[new_name] = kwargs.pop(old_name)
93
+ return fun(*args, **kwargs)
94
+ return wrapper
95
+ return decorator
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/__init__.pyi ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from _typeshed import IdentityFunction
2
+ from collections.abc import Callable, Iterable
3
+ from typing import Protocol, TypeVar, overload, type_check_only
4
+
5
+ from ._convertions import asbytes as asbytes, asunicode as asunicode
6
+
7
+ ###
8
+
9
+ _T = TypeVar("_T")
10
+ _HasModuleT = TypeVar("_HasModuleT", bound=_HasModule)
11
+
12
+ @type_check_only
13
+ class _HasModule(Protocol):
14
+ __module__: str
15
+
16
+ ###
17
+
18
+ @overload
19
+ def set_module(module: None) -> IdentityFunction: ...
20
+ @overload
21
+ def set_module(module: str) -> Callable[[_HasModuleT], _HasModuleT]: ...
22
+
23
+ #
24
+ def _rename_parameter(
25
+ old_names: Iterable[str],
26
+ new_names: Iterable[str],
27
+ dep_version: str | None = None,
28
+ ) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ...
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/_convertions.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A set of methods retained from np.compat module that
3
+ are still used across codebase.
4
+ """
5
+
6
+ __all__ = ["asunicode", "asbytes"]
7
+
8
+
9
+ def asunicode(s):
10
+ if isinstance(s, bytes):
11
+ return s.decode('latin1')
12
+ return str(s)
13
+
14
+
15
+ def asbytes(s):
16
+ if isinstance(s, bytes):
17
+ return s
18
+ return str(s).encode('latin1')
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/_convertions.pyi ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ __all__ = ["asbytes", "asunicode"]
2
+
3
+ def asunicode(s: bytes | str) -> str: ...
4
+ def asbytes(s: bytes | str) -> str: ...
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/_inspect.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Subset of inspect module from upstream python
2
+
3
+ We use this instead of upstream because upstream inspect is slow to import, and
4
+ significantly contributes to numpy import times. Importing this copy has almost
5
+ no overhead.
6
+
7
+ """
8
+ import types
9
+
10
+ __all__ = ['getargspec', 'formatargspec']
11
+
12
+ # ----------------------------------------------------------- type-checking
13
+ def ismethod(object):
14
+ """Return true if the object is an instance method.
15
+
16
+ Instance method objects provide these attributes:
17
+ __doc__ documentation string
18
+ __name__ name with which this method was defined
19
+ im_class class object in which this method belongs
20
+ im_func function object containing implementation of method
21
+ im_self instance to which this method is bound, or None
22
+
23
+ """
24
+ return isinstance(object, types.MethodType)
25
+
26
+ def isfunction(object):
27
+ """Return true if the object is a user-defined function.
28
+
29
+ Function objects provide these attributes:
30
+ __doc__ documentation string
31
+ __name__ name with which this function was defined
32
+ func_code code object containing compiled function bytecode
33
+ func_defaults tuple of any default values for arguments
34
+ func_doc (same as __doc__)
35
+ func_globals global namespace in which this function was defined
36
+ func_name (same as __name__)
37
+
38
+ """
39
+ return isinstance(object, types.FunctionType)
40
+
41
+ def iscode(object):
42
+ """Return true if the object is a code object.
43
+
44
+ Code objects provide these attributes:
45
+ co_argcount number of arguments (not including * or ** args)
46
+ co_code string of raw compiled bytecode
47
+ co_consts tuple of constants used in the bytecode
48
+ co_filename name of file in which this code object was created
49
+ co_firstlineno number of first line in Python source code
50
+ co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
51
+ co_lnotab encoded mapping of line numbers to bytecode indices
52
+ co_name name with which this code object was defined
53
+ co_names tuple of names of local variables
54
+ co_nlocals number of local variables
55
+ co_stacksize virtual machine stack space required
56
+ co_varnames tuple of names of arguments and local variables
57
+
58
+ """
59
+ return isinstance(object, types.CodeType)
60
+
61
+
62
+ # ------------------------------------------------ argument list extraction
63
+ # These constants are from Python's compile.h.
64
+ CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8
65
+
66
+ def getargs(co):
67
+ """Get information about the arguments accepted by a code object.
68
+
69
+ Three things are returned: (args, varargs, varkw), where 'args' is
70
+ a list of argument names (possibly containing nested lists), and
71
+ 'varargs' and 'varkw' are the names of the * and ** arguments or None.
72
+
73
+ """
74
+
75
+ if not iscode(co):
76
+ raise TypeError('arg is not a code object')
77
+
78
+ nargs = co.co_argcount
79
+ names = co.co_varnames
80
+ args = list(names[:nargs])
81
+
82
+ # The following acrobatics are for anonymous (tuple) arguments.
83
+ # Which we do not need to support, so remove to avoid importing
84
+ # the dis module.
85
+ for i in range(nargs):
86
+ if args[i][:1] in ['', '.']:
87
+ raise TypeError("tuple function arguments are not supported")
88
+ varargs = None
89
+ if co.co_flags & CO_VARARGS:
90
+ varargs = co.co_varnames[nargs]
91
+ nargs = nargs + 1
92
+ varkw = None
93
+ if co.co_flags & CO_VARKEYWORDS:
94
+ varkw = co.co_varnames[nargs]
95
+ return args, varargs, varkw
96
+
97
+ def getargspec(func):
98
+ """Get the names and default values of a function's arguments.
99
+
100
+ A tuple of four things is returned: (args, varargs, varkw, defaults).
101
+ 'args' is a list of the argument names (it may contain nested lists).
102
+ 'varargs' and 'varkw' are the names of the * and ** arguments or None.
103
+ 'defaults' is an n-tuple of the default values of the last n arguments.
104
+
105
+ """
106
+
107
+ if ismethod(func):
108
+ func = func.__func__
109
+ if not isfunction(func):
110
+ raise TypeError('arg is not a Python function')
111
+ args, varargs, varkw = getargs(func.__code__)
112
+ return args, varargs, varkw, func.__defaults__
113
+
114
+ def getargvalues(frame):
115
+ """Get information about arguments passed into a particular frame.
116
+
117
+ A tuple of four things is returned: (args, varargs, varkw, locals).
118
+ 'args' is a list of the argument names (it may contain nested lists).
119
+ 'varargs' and 'varkw' are the names of the * and ** arguments or None.
120
+ 'locals' is the locals dictionary of the given frame.
121
+
122
+ """
123
+ args, varargs, varkw = getargs(frame.f_code)
124
+ return args, varargs, varkw, frame.f_locals
125
+
126
+ def joinseq(seq):
127
+ if len(seq) == 1:
128
+ return '(' + seq[0] + ',)'
129
+ else:
130
+ return '(' + ', '.join(seq) + ')'
131
+
132
+ def strseq(object, convert, join=joinseq):
133
+ """Recursively walk a sequence, stringifying each element.
134
+
135
+ """
136
+ if type(object) in [list, tuple]:
137
+ return join([strseq(_o, convert, join) for _o in object])
138
+ else:
139
+ return convert(object)
140
+
141
+ def formatargspec(args, varargs=None, varkw=None, defaults=None,
142
+ formatarg=str,
143
+ formatvarargs=lambda name: '*' + name,
144
+ formatvarkw=lambda name: '**' + name,
145
+ formatvalue=lambda value: '=' + repr(value),
146
+ join=joinseq):
147
+ """Format an argument spec from the 4 values returned by getargspec.
148
+
149
+ The first four arguments are (args, varargs, varkw, defaults). The
150
+ other four arguments are the corresponding optional formatting functions
151
+ that are called to turn names and values into strings. The ninth
152
+ argument is an optional function to format the sequence of arguments.
153
+
154
+ """
155
+ specs = []
156
+ if defaults:
157
+ firstdefault = len(args) - len(defaults)
158
+ for i in range(len(args)):
159
+ spec = strseq(args[i], formatarg, join)
160
+ if defaults and i >= firstdefault:
161
+ spec = spec + formatvalue(defaults[i - firstdefault])
162
+ specs.append(spec)
163
+ if varargs is not None:
164
+ specs.append(formatvarargs(varargs))
165
+ if varkw is not None:
166
+ specs.append(formatvarkw(varkw))
167
+ return '(' + ', '.join(specs) + ')'
168
+
169
+ def formatargvalues(args, varargs, varkw, locals,
170
+ formatarg=str,
171
+ formatvarargs=lambda name: '*' + name,
172
+ formatvarkw=lambda name: '**' + name,
173
+ formatvalue=lambda value: '=' + repr(value),
174
+ join=joinseq):
175
+ """Format an argument spec from the 4 values returned by getargvalues.
176
+
177
+ The first four arguments are (args, varargs, varkw, locals). The
178
+ next four arguments are the corresponding optional formatting functions
179
+ that are called to turn names and values into strings. The ninth
180
+ argument is an optional function to format the sequence of arguments.
181
+
182
+ """
183
+ def convert(name, locals=locals,
184
+ formatarg=formatarg, formatvalue=formatvalue):
185
+ return formatarg(name) + formatvalue(locals[name])
186
+ specs = [strseq(arg, convert, join) for arg in args]
187
+
188
+ if varargs:
189
+ specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
190
+ if varkw:
191
+ specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
192
+ return '(' + ', '.join(specs) + ')'
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/_inspect.pyi ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import types
2
+ from _typeshed import SupportsLenAndGetItem
3
+ from collections.abc import Callable, Mapping
4
+ from typing import Any, Final, TypeAlias, TypeVar, overload
5
+ from typing_extensions import TypeIs
6
+
7
+ __all__ = ["formatargspec", "getargspec"]
8
+
9
+ ###
10
+
11
+ _T = TypeVar("_T")
12
+ _RT = TypeVar("_RT")
13
+
14
+ _StrSeq: TypeAlias = SupportsLenAndGetItem[str]
15
+ _NestedSeq: TypeAlias = list[_T | _NestedSeq[_T]] | tuple[_T | _NestedSeq[_T], ...]
16
+
17
+ _JoinFunc: TypeAlias = Callable[[list[_T]], _T]
18
+ _FormatFunc: TypeAlias = Callable[[_T], str]
19
+
20
+ ###
21
+
22
+ CO_OPTIMIZED: Final = 1
23
+ CO_NEWLOCALS: Final = 2
24
+ CO_VARARGS: Final = 4
25
+ CO_VARKEYWORDS: Final = 8
26
+
27
+ ###
28
+
29
+ def ismethod(object: object) -> TypeIs[types.MethodType]: ...
30
+ def isfunction(object: object) -> TypeIs[types.FunctionType]: ...
31
+ def iscode(object: object) -> TypeIs[types.CodeType]: ...
32
+
33
+ ###
34
+
35
+ def getargs(co: types.CodeType) -> tuple[list[str], str | None, str | None]: ...
36
+ def getargspec(func: types.MethodType | types.FunctionType) -> tuple[list[str], str | None, str | None, tuple[Any, ...]]: ...
37
+ def getargvalues(frame: types.FrameType) -> tuple[list[str], str | None, str | None, dict[str, Any]]: ...
38
+
39
+ #
40
+ def joinseq(seq: _StrSeq) -> str: ...
41
+
42
+ #
43
+ @overload
44
+ def strseq(object: _NestedSeq[str], convert: Callable[[Any], Any], join: _JoinFunc[str] = ...) -> str: ...
45
+ @overload
46
+ def strseq(object: _NestedSeq[_T], convert: Callable[[_T], _RT], join: _JoinFunc[_RT]) -> _RT: ...
47
+
48
+ #
49
+ def formatargspec(
50
+ args: _StrSeq,
51
+ varargs: str | None = None,
52
+ varkw: str | None = None,
53
+ defaults: SupportsLenAndGetItem[object] | None = None,
54
+ formatarg: _FormatFunc[str] = ..., # str
55
+ formatvarargs: _FormatFunc[str] = ..., # "*{}".format
56
+ formatvarkw: _FormatFunc[str] = ..., # "**{}".format
57
+ formatvalue: _FormatFunc[object] = ..., # "={!r}".format
58
+ join: _JoinFunc[str] = ..., # joinseq
59
+ ) -> str: ...
60
+ def formatargvalues(
61
+ args: _StrSeq,
62
+ varargs: str | None,
63
+ varkw: str | None,
64
+ locals: Mapping[str, object] | None,
65
+ formatarg: _FormatFunc[str] = ..., # str
66
+ formatvarargs: _FormatFunc[str] = ..., # "*{}".format
67
+ formatvarkw: _FormatFunc[str] = ..., # "**{}".format
68
+ formatvalue: _FormatFunc[object] = ..., # "={!r}".format
69
+ join: _JoinFunc[str] = ..., # joinseq
70
+ ) -> str: ...
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/_pep440.py ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility to compare pep440 compatible version strings.
2
+
3
+ The LooseVersion and StrictVersion classes that distutils provides don't
4
+ work; they don't recognize anything like alpha/beta/rc/dev versions.
5
+ """
6
+
7
+ # Copyright (c) Donald Stufft and individual contributors.
8
+ # All rights reserved.
9
+
10
+ # Redistribution and use in source and binary forms, with or without
11
+ # modification, are permitted provided that the following conditions are met:
12
+
13
+ # 1. Redistributions of source code must retain the above copyright notice,
14
+ # this list of conditions and the following disclaimer.
15
+
16
+ # 2. Redistributions in binary form must reproduce the above copyright
17
+ # notice, this list of conditions and the following disclaimer in the
18
+ # documentation and/or other materials provided with the distribution.
19
+
20
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
+ # POSSIBILITY OF SUCH DAMAGE.
31
+
32
+ import collections
33
+ import itertools
34
+ import re
35
+
36
+ __all__ = [
37
+ "parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN",
38
+ ]
39
+
40
+
41
+ # BEGIN packaging/_structures.py
42
+
43
+
44
+ class Infinity:
45
+ def __repr__(self):
46
+ return "Infinity"
47
+
48
+ def __hash__(self):
49
+ return hash(repr(self))
50
+
51
+ def __lt__(self, other):
52
+ return False
53
+
54
+ def __le__(self, other):
55
+ return False
56
+
57
+ def __eq__(self, other):
58
+ return isinstance(other, self.__class__)
59
+
60
+ def __ne__(self, other):
61
+ return not isinstance(other, self.__class__)
62
+
63
+ def __gt__(self, other):
64
+ return True
65
+
66
+ def __ge__(self, other):
67
+ return True
68
+
69
+ def __neg__(self):
70
+ return NegativeInfinity
71
+
72
+
73
+ Infinity = Infinity()
74
+
75
+
76
+ class NegativeInfinity:
77
+ def __repr__(self):
78
+ return "-Infinity"
79
+
80
+ def __hash__(self):
81
+ return hash(repr(self))
82
+
83
+ def __lt__(self, other):
84
+ return True
85
+
86
+ def __le__(self, other):
87
+ return True
88
+
89
+ def __eq__(self, other):
90
+ return isinstance(other, self.__class__)
91
+
92
+ def __ne__(self, other):
93
+ return not isinstance(other, self.__class__)
94
+
95
+ def __gt__(self, other):
96
+ return False
97
+
98
+ def __ge__(self, other):
99
+ return False
100
+
101
+ def __neg__(self):
102
+ return Infinity
103
+
104
+
105
+ # BEGIN packaging/version.py
106
+
107
+
108
+ NegativeInfinity = NegativeInfinity()
109
+
110
+ _Version = collections.namedtuple(
111
+ "_Version",
112
+ ["epoch", "release", "dev", "pre", "post", "local"],
113
+ )
114
+
115
+
116
+ def parse(version):
117
+ """
118
+ Parse the given version string and return either a :class:`Version` object
119
+ or a :class:`LegacyVersion` object depending on if the given version is
120
+ a valid PEP 440 version or a legacy version.
121
+ """
122
+ try:
123
+ return Version(version)
124
+ except InvalidVersion:
125
+ return LegacyVersion(version)
126
+
127
+
128
+ class InvalidVersion(ValueError):
129
+ """
130
+ An invalid version was found, users should refer to PEP 440.
131
+ """
132
+
133
+
134
+ class _BaseVersion:
135
+
136
+ def __hash__(self):
137
+ return hash(self._key)
138
+
139
+ def __lt__(self, other):
140
+ return self._compare(other, lambda s, o: s < o)
141
+
142
+ def __le__(self, other):
143
+ return self._compare(other, lambda s, o: s <= o)
144
+
145
+ def __eq__(self, other):
146
+ return self._compare(other, lambda s, o: s == o)
147
+
148
+ def __ge__(self, other):
149
+ return self._compare(other, lambda s, o: s >= o)
150
+
151
+ def __gt__(self, other):
152
+ return self._compare(other, lambda s, o: s > o)
153
+
154
+ def __ne__(self, other):
155
+ return self._compare(other, lambda s, o: s != o)
156
+
157
+ def _compare(self, other, method):
158
+ if not isinstance(other, _BaseVersion):
159
+ return NotImplemented
160
+
161
+ return method(self._key, other._key)
162
+
163
+
164
+ class LegacyVersion(_BaseVersion):
165
+
166
+ def __init__(self, version):
167
+ self._version = str(version)
168
+ self._key = _legacy_cmpkey(self._version)
169
+
170
+ def __str__(self):
171
+ return self._version
172
+
173
+ def __repr__(self):
174
+ return f"<LegacyVersion({str(self)!r})>"
175
+
176
+ @property
177
+ def public(self):
178
+ return self._version
179
+
180
+ @property
181
+ def base_version(self):
182
+ return self._version
183
+
184
+ @property
185
+ def local(self):
186
+ return None
187
+
188
+ @property
189
+ def is_prerelease(self):
190
+ return False
191
+
192
+ @property
193
+ def is_postrelease(self):
194
+ return False
195
+
196
+
197
+ _legacy_version_component_re = re.compile(
198
+ r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE,
199
+ )
200
+
201
+ _legacy_version_replacement_map = {
202
+ "pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@",
203
+ }
204
+
205
+
206
+ def _parse_version_parts(s):
207
+ for part in _legacy_version_component_re.split(s):
208
+ part = _legacy_version_replacement_map.get(part, part)
209
+
210
+ if not part or part == ".":
211
+ continue
212
+
213
+ if part[:1] in "0123456789":
214
+ # pad for numeric comparison
215
+ yield part.zfill(8)
216
+ else:
217
+ yield "*" + part
218
+
219
+ # ensure that alpha/beta/candidate are before final
220
+ yield "*final"
221
+
222
+
223
+ def _legacy_cmpkey(version):
224
+ # We hardcode an epoch of -1 here. A PEP 440 version can only have an epoch
225
+ # greater than or equal to 0. This will effectively put the LegacyVersion,
226
+ # which uses the defacto standard originally implemented by setuptools,
227
+ # as before all PEP 440 versions.
228
+ epoch = -1
229
+
230
+ # This scheme is taken from pkg_resources.parse_version setuptools prior to
231
+ # its adoption of the packaging library.
232
+ parts = []
233
+ for part in _parse_version_parts(version.lower()):
234
+ if part.startswith("*"):
235
+ # remove "-" before a prerelease tag
236
+ if part < "*final":
237
+ while parts and parts[-1] == "*final-":
238
+ parts.pop()
239
+
240
+ # remove trailing zeros from each series of numeric parts
241
+ while parts and parts[-1] == "00000000":
242
+ parts.pop()
243
+
244
+ parts.append(part)
245
+ parts = tuple(parts)
246
+
247
+ return epoch, parts
248
+
249
+
250
+ # Deliberately not anchored to the start and end of the string, to make it
251
+ # easier for 3rd party code to reuse
252
+ VERSION_PATTERN = r"""
253
+ v?
254
+ (?:
255
+ (?:(?P<epoch>[0-9]+)!)? # epoch
256
+ (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
257
+ (?P<pre> # pre-release
258
+ [-_\.]?
259
+ (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
260
+ [-_\.]?
261
+ (?P<pre_n>[0-9]+)?
262
+ )?
263
+ (?P<post> # post release
264
+ (?:-(?P<post_n1>[0-9]+))
265
+ |
266
+ (?:
267
+ [-_\.]?
268
+ (?P<post_l>post|rev|r)
269
+ [-_\.]?
270
+ (?P<post_n2>[0-9]+)?
271
+ )
272
+ )?
273
+ (?P<dev> # dev release
274
+ [-_\.]?
275
+ (?P<dev_l>dev)
276
+ [-_\.]?
277
+ (?P<dev_n>[0-9]+)?
278
+ )?
279
+ )
280
+ (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
281
+ """
282
+
283
+
284
+ class Version(_BaseVersion):
285
+
286
+ _regex = re.compile(
287
+ r"^\s*" + VERSION_PATTERN + r"\s*$",
288
+ re.VERBOSE | re.IGNORECASE,
289
+ )
290
+
291
+ def __init__(self, version):
292
+ # Validate the version and parse it into pieces
293
+ match = self._regex.search(version)
294
+ if not match:
295
+ raise InvalidVersion(f"Invalid version: '{version}'")
296
+
297
+ # Store the parsed out pieces of the version
298
+ self._version = _Version(
299
+ epoch=int(match.group("epoch")) if match.group("epoch") else 0,
300
+ release=tuple(int(i) for i in match.group("release").split(".")),
301
+ pre=_parse_letter_version(
302
+ match.group("pre_l"),
303
+ match.group("pre_n"),
304
+ ),
305
+ post=_parse_letter_version(
306
+ match.group("post_l"),
307
+ match.group("post_n1") or match.group("post_n2"),
308
+ ),
309
+ dev=_parse_letter_version(
310
+ match.group("dev_l"),
311
+ match.group("dev_n"),
312
+ ),
313
+ local=_parse_local_version(match.group("local")),
314
+ )
315
+
316
+ # Generate a key which will be used for sorting
317
+ self._key = _cmpkey(
318
+ self._version.epoch,
319
+ self._version.release,
320
+ self._version.pre,
321
+ self._version.post,
322
+ self._version.dev,
323
+ self._version.local,
324
+ )
325
+
326
+ def __repr__(self):
327
+ return f"<Version({str(self)!r})>"
328
+
329
+ def __str__(self):
330
+ parts = []
331
+
332
+ # Epoch
333
+ if self._version.epoch != 0:
334
+ parts.append(f"{self._version.epoch}!")
335
+
336
+ # Release segment
337
+ parts.append(".".join(str(x) for x in self._version.release))
338
+
339
+ # Pre-release
340
+ if self._version.pre is not None:
341
+ parts.append("".join(str(x) for x in self._version.pre))
342
+
343
+ # Post-release
344
+ if self._version.post is not None:
345
+ parts.append(f".post{self._version.post[1]}")
346
+
347
+ # Development release
348
+ if self._version.dev is not None:
349
+ parts.append(f".dev{self._version.dev[1]}")
350
+
351
+ # Local version segment
352
+ if self._version.local is not None:
353
+ parts.append(
354
+ f"+{'.'.join(str(x) for x in self._version.local)}"
355
+ )
356
+
357
+ return "".join(parts)
358
+
359
+ @property
360
+ def public(self):
361
+ return str(self).split("+", 1)[0]
362
+
363
+ @property
364
+ def base_version(self):
365
+ parts = []
366
+
367
+ # Epoch
368
+ if self._version.epoch != 0:
369
+ parts.append(f"{self._version.epoch}!")
370
+
371
+ # Release segment
372
+ parts.append(".".join(str(x) for x in self._version.release))
373
+
374
+ return "".join(parts)
375
+
376
+ @property
377
+ def local(self):
378
+ version_string = str(self)
379
+ if "+" in version_string:
380
+ return version_string.split("+", 1)[1]
381
+
382
+ @property
383
+ def is_prerelease(self):
384
+ return bool(self._version.dev or self._version.pre)
385
+
386
+ @property
387
+ def is_postrelease(self):
388
+ return bool(self._version.post)
389
+
390
+
391
+ def _parse_letter_version(letter, number):
392
+ if letter:
393
+ # We assume there is an implicit 0 in a pre-release if there is
394
+ # no numeral associated with it.
395
+ if number is None:
396
+ number = 0
397
+
398
+ # We normalize any letters to their lower-case form
399
+ letter = letter.lower()
400
+
401
+ # We consider some words to be alternate spellings of other words and
402
+ # in those cases we want to normalize the spellings to our preferred
403
+ # spelling.
404
+ if letter == "alpha":
405
+ letter = "a"
406
+ elif letter == "beta":
407
+ letter = "b"
408
+ elif letter in ["c", "pre", "preview"]:
409
+ letter = "rc"
410
+ elif letter in ["rev", "r"]:
411
+ letter = "post"
412
+
413
+ return letter, int(number)
414
+ if not letter and number:
415
+ # We assume that if we are given a number but not given a letter,
416
+ # then this is using the implicit post release syntax (e.g., 1.0-1)
417
+ letter = "post"
418
+
419
+ return letter, int(number)
420
+
421
+
422
+ _local_version_seperators = re.compile(r"[\._-]")
423
+
424
+
425
+ def _parse_local_version(local):
426
+ """
427
+ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
428
+ """
429
+ if local is not None:
430
+ return tuple(
431
+ part.lower() if not part.isdigit() else int(part)
432
+ for part in _local_version_seperators.split(local)
433
+ )
434
+
435
+
436
+ def _cmpkey(epoch, release, pre, post, dev, local):
437
+ # When we compare a release version, we want to compare it with all of the
438
+ # trailing zeros removed. So we'll use a reverse the list, drop all the now
439
+ # leading zeros until we come to something non-zero, then take the rest,
440
+ # re-reverse it back into the correct order, and make it a tuple and use
441
+ # that for our sorting key.
442
+ release = tuple(
443
+ reversed(list(
444
+ itertools.dropwhile(
445
+ lambda x: x == 0,
446
+ reversed(release),
447
+ )
448
+ ))
449
+ )
450
+
451
+ # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
452
+ # We'll do this by abusing the pre-segment, but we _only_ want to do this
453
+ # if there is no pre- or a post-segment. If we have one of those, then
454
+ # the normal sorting rules will handle this case correctly.
455
+ if pre is None and post is None and dev is not None:
456
+ pre = -Infinity
457
+ # Versions without a pre-release (except as noted above) should sort after
458
+ # those with one.
459
+ elif pre is None:
460
+ pre = Infinity
461
+
462
+ # Versions without a post-segment should sort before those with one.
463
+ if post is None:
464
+ post = -Infinity
465
+
466
+ # Versions without a development segment should sort after those with one.
467
+ if dev is None:
468
+ dev = Infinity
469
+
470
+ if local is None:
471
+ # Versions without a local segment should sort before those with one.
472
+ local = -Infinity
473
+ else:
474
+ # Versions with a local segment need that segment parsed to implement
475
+ # the sorting rules in PEP440.
476
+ # - Alphanumeric segments sort before numeric segments
477
+ # - Alphanumeric segments sort lexicographically
478
+ # - Numeric segments sort numerically
479
+ # - Shorter versions sort before longer versions when the prefixes
480
+ # match exactly
481
+ local = tuple(
482
+ (i, "") if isinstance(i, int) else (-Infinity, i)
483
+ for i in local
484
+ )
485
+
486
+ return epoch, release, pre, post, dev, local
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/_utils/_pep440.pyi ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from collections.abc import Callable
3
+ from typing import (
4
+ Any,
5
+ ClassVar,
6
+ Final,
7
+ Generic,
8
+ Literal as L,
9
+ NamedTuple,
10
+ TypeVar,
11
+ final,
12
+ type_check_only,
13
+ )
14
+ from typing_extensions import TypeIs
15
+
16
+ __all__ = ["VERSION_PATTERN", "InvalidVersion", "LegacyVersion", "Version", "parse"]
17
+
18
+ ###
19
+
20
+ _CmpKeyT = TypeVar("_CmpKeyT", bound=tuple[object, ...])
21
+ _CmpKeyT_co = TypeVar("_CmpKeyT_co", bound=tuple[object, ...], default=tuple[Any, ...], covariant=True)
22
+
23
+ ###
24
+
25
+ VERSION_PATTERN: Final[str] = ...
26
+
27
+ class InvalidVersion(ValueError): ...
28
+
29
+ @type_check_only
30
+ @final
31
+ class _InfinityType:
32
+ def __hash__(self) -> int: ...
33
+ def __eq__(self, other: object, /) -> TypeIs[_InfinityType]: ...
34
+ def __ne__(self, other: object, /) -> bool: ...
35
+ def __lt__(self, other: object, /) -> L[False]: ...
36
+ def __le__(self, other: object, /) -> L[False]: ...
37
+ def __gt__(self, other: object, /) -> L[True]: ...
38
+ def __ge__(self, other: object, /) -> L[True]: ...
39
+ def __neg__(self) -> _NegativeInfinityType: ...
40
+
41
+ Infinity: Final[_InfinityType] = ...
42
+
43
+ @type_check_only
44
+ @final
45
+ class _NegativeInfinityType:
46
+ def __hash__(self) -> int: ...
47
+ def __eq__(self, other: object, /) -> TypeIs[_NegativeInfinityType]: ...
48
+ def __ne__(self, other: object, /) -> bool: ...
49
+ def __lt__(self, other: object, /) -> L[True]: ...
50
+ def __le__(self, other: object, /) -> L[True]: ...
51
+ def __gt__(self, other: object, /) -> L[False]: ...
52
+ def __ge__(self, other: object, /) -> L[False]: ...
53
+ def __neg__(self) -> _InfinityType: ...
54
+
55
+ NegativeInfinity: Final[_NegativeInfinityType] = ...
56
+
57
+ class _Version(NamedTuple):
58
+ epoch: int
59
+ release: tuple[int, ...]
60
+ dev: tuple[str, int] | None
61
+ pre: tuple[str, int] | None
62
+ post: tuple[str, int] | None
63
+ local: tuple[str | int, ...] | None
64
+
65
+ class _BaseVersion(Generic[_CmpKeyT_co]):
66
+ _key: _CmpKeyT_co
67
+ def __hash__(self) -> int: ...
68
+ def __eq__(self, other: _BaseVersion, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
69
+ def __ne__(self, other: _BaseVersion, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
70
+ def __lt__(self, other: _BaseVersion, /) -> bool: ...
71
+ def __le__(self, other: _BaseVersion, /) -> bool: ...
72
+ def __ge__(self, other: _BaseVersion, /) -> bool: ...
73
+ def __gt__(self, other: _BaseVersion, /) -> bool: ...
74
+ def _compare(self, /, other: _BaseVersion[_CmpKeyT], method: Callable[[_CmpKeyT_co, _CmpKeyT], bool]) -> bool: ...
75
+
76
+ class LegacyVersion(_BaseVersion[tuple[L[-1], tuple[str, ...]]]):
77
+ _version: Final[str]
78
+ def __init__(self, /, version: str) -> None: ...
79
+ @property
80
+ def public(self) -> str: ...
81
+ @property
82
+ def base_version(self) -> str: ...
83
+ @property
84
+ def local(self) -> None: ...
85
+ @property
86
+ def is_prerelease(self) -> L[False]: ...
87
+ @property
88
+ def is_postrelease(self) -> L[False]: ...
89
+
90
+ class Version(
91
+ _BaseVersion[
92
+ tuple[
93
+ int, # epoch
94
+ tuple[int, ...], # release
95
+ tuple[str, int] | _InfinityType | _NegativeInfinityType, # pre
96
+ tuple[str, int] | _NegativeInfinityType, # post
97
+ tuple[str, int] | _InfinityType, # dev
98
+ tuple[tuple[int, L[""]] | tuple[_NegativeInfinityType, str], ...] | _NegativeInfinityType, # local
99
+ ],
100
+ ],
101
+ ):
102
+ _regex: ClassVar[re.Pattern[str]] = ...
103
+ _version: Final[str]
104
+
105
+ def __init__(self, /, version: str) -> None: ...
106
+ @property
107
+ def public(self) -> str: ...
108
+ @property
109
+ def base_version(self) -> str: ...
110
+ @property
111
+ def local(self) -> str | None: ...
112
+ @property
113
+ def is_prerelease(self) -> bool: ...
114
+ @property
115
+ def is_postrelease(self) -> bool: ...
116
+
117
+ #
118
+ def parse(version: str) -> Version | LegacyVersion: ...
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/doc/ufuncs.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ===================
3
+ Universal Functions
4
+ ===================
5
+
6
+ Ufuncs are, generally speaking, mathematical functions or operations that are
7
+ applied element-by-element to the contents of an array. That is, the result
8
+ in each output array element only depends on the value in the corresponding
9
+ input array (or arrays) and on no other array elements. NumPy comes with a
10
+ large suite of ufuncs, and scipy extends that suite substantially. The simplest
11
+ example is the addition operator: ::
12
+
13
+ >>> np.array([0,2,3,4]) + np.array([1,1,-1,2])
14
+ array([1, 3, 2, 6])
15
+
16
+ The ufunc module lists all the available ufuncs in numpy. Documentation on
17
+ the specific ufuncs may be found in those modules. This documentation is
18
+ intended to address the more general aspects of ufuncs common to most of
19
+ them. All of the ufuncs that make use of Python operators (e.g., +, -, etc.)
20
+ have equivalent functions defined (e.g. add() for +)
21
+
22
+ Type coercion
23
+ =============
24
+
25
+ What happens when a binary operator (e.g., +,-,\\*,/, etc) deals with arrays of
26
+ two different types? What is the type of the result? Typically, the result is
27
+ the higher of the two types. For example: ::
28
+
29
+ float32 + float64 -> float64
30
+ int8 + int32 -> int32
31
+ int16 + float32 -> float32
32
+ float32 + complex64 -> complex64
33
+
34
+ There are some less obvious cases generally involving mixes of types
35
+ (e.g. uints, ints and floats) where equal bit sizes for each are not
36
+ capable of saving all the information in a different type of equivalent
37
+ bit size. Some examples are int32 vs float32 or uint32 vs int32.
38
+ Generally, the result is the higher type of larger size than both
39
+ (if available). So: ::
40
+
41
+ int32 + float32 -> float64
42
+ uint32 + int32 -> int64
43
+
44
+ Finally, the type coercion behavior when expressions involve Python
45
+ scalars is different than that seen for arrays. Since Python has a
46
+ limited number of types, combining a Python int with a dtype=np.int8
47
+ array does not coerce to the higher type but instead, the type of the
48
+ array prevails. So the rules for Python scalars combined with arrays is
49
+ that the result will be that of the array equivalent the Python scalar
50
+ if the Python scalar is of a higher 'kind' than the array (e.g., float
51
+ vs. int), otherwise the resultant type will be that of the array.
52
+ For example: ::
53
+
54
+ Python int + int8 -> int8
55
+ Python float + int8 -> float64
56
+
57
+ ufunc methods
58
+ =============
59
+
60
+ Binary ufuncs support 4 methods.
61
+
62
+ **.reduce(arr)** applies the binary operator to elements of the array in
63
+ sequence. For example: ::
64
+
65
+ >>> np.add.reduce(np.arange(10)) # adds all elements of array
66
+ 45
67
+
68
+ For multidimensional arrays, the first dimension is reduced by default: ::
69
+
70
+ >>> np.add.reduce(np.arange(10).reshape(2,5))
71
+ array([ 5, 7, 9, 11, 13])
72
+
73
+ The axis keyword can be used to specify different axes to reduce: ::
74
+
75
+ >>> np.add.reduce(np.arange(10).reshape(2,5),axis=1)
76
+ array([10, 35])
77
+
78
+ **.accumulate(arr)** applies the binary operator and generates an
79
+ equivalently shaped array that includes the accumulated amount for each
80
+ element of the array. A couple examples: ::
81
+
82
+ >>> np.add.accumulate(np.arange(10))
83
+ array([ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
84
+ >>> np.multiply.accumulate(np.arange(1,9))
85
+ array([ 1, 2, 6, 24, 120, 720, 5040, 40320])
86
+
87
+ The behavior for multidimensional arrays is the same as for .reduce(),
88
+ as is the use of the axis keyword).
89
+
90
+ **.reduceat(arr,indices)** allows one to apply reduce to selected parts
91
+ of an array. It is a difficult method to understand. See the documentation
92
+ at:
93
+
94
+ **.outer(arr1,arr2)** generates an outer operation on the two arrays arr1 and
95
+ arr2. It will work on multidimensional arrays (the shape of the result is
96
+ the concatenation of the two input shapes.: ::
97
+
98
+ >>> np.multiply.outer(np.arange(3),np.arange(4))
99
+ array([[0, 0, 0, 0],
100
+ [0, 1, 2, 3],
101
+ [0, 2, 4, 6]])
102
+
103
+ Output arguments
104
+ ================
105
+
106
+ All ufuncs accept an optional output array. The array must be of the expected
107
+ output shape. Beware that if the type of the output array is of a different
108
+ (and lower) type than the output result, the results may be silently truncated
109
+ or otherwise corrupted in the downcast to the lower type. This usage is useful
110
+ when one wants to avoid creating large temporary arrays and instead allows one
111
+ to reuse the same array memory repeatedly (at the expense of not being able to
112
+ use more convenient operator notation in expressions). Note that when the
113
+ output argument is used, the ufunc still returns a reference to the result.
114
+
115
+ >>> x = np.arange(2)
116
+ >>> np.add(np.arange(2, dtype=float), np.arange(2, dtype=float), x,
117
+ ... casting='unsafe')
118
+ array([0, 2])
119
+ >>> x
120
+ array([0, 2])
121
+
122
+ and & or as ufuncs
123
+ ==================
124
+
125
+ Invariably people try to use the python 'and' and 'or' as logical operators
126
+ (and quite understandably). But these operators do not behave as normal
127
+ operators since Python treats these quite differently. They cannot be
128
+ overloaded with array equivalents. Thus using 'and' or 'or' with an array
129
+ results in an error. There are two alternatives:
130
+
131
+ 1) use the ufunc functions logical_and() and logical_or().
132
+ 2) use the bitwise operators & and \\|. The drawback of these is that if
133
+ the arguments to these operators are not boolean arrays, the result is
134
+ likely incorrect. On the other hand, most usages of logical_and and
135
+ logical_or are with boolean arrays. As long as one is careful, this is
136
+ a convenient way to apply these operators.
137
+
138
+ """
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/fft/_helper.pyi ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Final, Literal as L, TypeVar, overload
2
+
3
+ from numpy import complexfloating, floating, generic, integer
4
+ from numpy._typing import (
5
+ ArrayLike,
6
+ NDArray,
7
+ _ArrayLike,
8
+ _ArrayLikeComplex_co,
9
+ _ArrayLikeFloat_co,
10
+ _ShapeLike,
11
+ )
12
+
13
+ __all__ = ["fftfreq", "fftshift", "ifftshift", "rfftfreq"]
14
+
15
+ _ScalarT = TypeVar("_ScalarT", bound=generic)
16
+
17
+ ###
18
+
19
+ integer_types: Final[tuple[type[int], type[integer]]] = ...
20
+
21
+ ###
22
+
23
+ @overload
24
+ def fftshift(x: _ArrayLike[_ScalarT], axes: _ShapeLike | None = None) -> NDArray[_ScalarT]: ...
25
+ @overload
26
+ def fftshift(x: ArrayLike, axes: _ShapeLike | None = None) -> NDArray[Any]: ...
27
+
28
+ #
29
+ @overload
30
+ def ifftshift(x: _ArrayLike[_ScalarT], axes: _ShapeLike | None = None) -> NDArray[_ScalarT]: ...
31
+ @overload
32
+ def ifftshift(x: ArrayLike, axes: _ShapeLike | None = None) -> NDArray[Any]: ...
33
+
34
+ #
35
+ @overload
36
+ def fftfreq(n: int | integer, d: _ArrayLikeFloat_co = 1.0, device: L["cpu"] | None = None) -> NDArray[floating]: ...
37
+ @overload
38
+ def fftfreq(n: int | integer, d: _ArrayLikeComplex_co = 1.0, device: L["cpu"] | None = None) -> NDArray[complexfloating]: ...
39
+
40
+ #
41
+ @overload
42
+ def rfftfreq(n: int | integer, d: _ArrayLikeFloat_co = 1.0, device: L["cpu"] | None = None) -> NDArray[floating]: ...
43
+ @overload
44
+ def rfftfreq(n: int | integer, d: _ArrayLikeComplex_co = 1.0, device: L["cpu"] | None = None) -> NDArray[complexfloating]: ...
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/API_CHANGES.txt ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. -*- rest -*-
2
+
3
+ ==================================================
4
+ API changes in the new masked array implementation
5
+ ==================================================
6
+
7
+ Masked arrays are subclasses of ndarray
8
+ ---------------------------------------
9
+
10
+ Contrary to the original implementation, masked arrays are now regular
11
+ ndarrays::
12
+
13
+ >>> x = masked_array([1,2,3],mask=[0,0,1])
14
+ >>> print isinstance(x, numpy.ndarray)
15
+ True
16
+
17
+
18
+ ``_data`` returns a view of the masked array
19
+ --------------------------------------------
20
+
21
+ Masked arrays are composed of a ``_data`` part and a ``_mask``. Accessing the
22
+ ``_data`` part will return a regular ndarray or any of its subclass, depending
23
+ on the initial data::
24
+
25
+ >>> x = masked_array(numpy.matrix([[1,2],[3,4]]),mask=[[0,0],[0,1]])
26
+ >>> print x._data
27
+ [[1 2]
28
+ [3 4]]
29
+ >>> print type(x._data)
30
+ <class 'numpy.matrixlib.defmatrix.matrix'>
31
+
32
+
33
+ In practice, ``_data`` is implemented as a property, not as an attribute.
34
+ Therefore, you cannot access it directly, and some simple tests such as the
35
+ following one will fail::
36
+
37
+ >>>x._data is x._data
38
+ False
39
+
40
+
41
+ ``filled(x)`` can return a subclass of ndarray
42
+ ----------------------------------------------
43
+ The function ``filled(a)`` returns an array of the same type as ``a._data``::
44
+
45
+ >>> x = masked_array(numpy.matrix([[1,2],[3,4]]),mask=[[0,0],[0,1]])
46
+ >>> y = filled(x)
47
+ >>> print type(y)
48
+ <class 'numpy.matrixlib.defmatrix.matrix'>
49
+ >>> print y
50
+ matrix([[ 1, 2],
51
+ [ 3, 999999]])
52
+
53
+
54
+ ``put``, ``putmask`` behave like their ndarray counterparts
55
+ -----------------------------------------------------------
56
+
57
+ Previously, ``putmask`` was used like this::
58
+
59
+ mask = [False,True,True]
60
+ x = array([1,4,7],mask=mask)
61
+ putmask(x,mask,[3])
62
+
63
+ which translated to::
64
+
65
+ x[~mask] = [3]
66
+
67
+ (Note that a ``True``-value in a mask suppresses a value.)
68
+
69
+ In other words, the mask had the same length as ``x``, whereas
70
+ ``values`` had ``sum(~mask)`` elements.
71
+
72
+ Now, the behaviour is similar to that of ``ndarray.putmask``, where
73
+ the mask and the values are both the same length as ``x``, i.e.
74
+
75
+ ::
76
+
77
+ putmask(x,mask,[3,0,0])
78
+
79
+
80
+ ``fill_value`` is a property
81
+ ----------------------------
82
+
83
+ ``fill_value`` is no longer a method, but a property::
84
+
85
+ >>> print x.fill_value
86
+ 999999
87
+
88
+ ``cumsum`` and ``cumprod`` ignore missing values
89
+ ------------------------------------------------
90
+
91
+ Missing values are assumed to be the identity element, i.e. 0 for
92
+ ``cumsum`` and 1 for ``cumprod``::
93
+
94
+ >>> x = N.ma.array([1,2,3,4],mask=[False,True,False,False])
95
+ >>> print x
96
+ [1 -- 3 4]
97
+ >>> print x.cumsum()
98
+ [1 -- 4 8]
99
+ >> print x.cumprod()
100
+ [1 -- 3 12]
101
+
102
+ ``bool(x)`` raises a ValueError
103
+ -------------------------------
104
+
105
+ Masked arrays now behave like regular ``ndarrays``, in that they cannot be
106
+ converted to booleans:
107
+
108
+ ::
109
+
110
+ >>> x = N.ma.array([1,2,3])
111
+ >>> bool(x)
112
+ Traceback (most recent call last):
113
+ File "<stdin>", line 1, in <module>
114
+ ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
115
+
116
+
117
+ ==================================
118
+ New features (non exhaustive list)
119
+ ==================================
120
+
121
+ ``mr_``
122
+ -------
123
+
124
+ ``mr_`` mimics the behavior of ``r_`` for masked arrays::
125
+
126
+ >>> np.ma.mr_[3,4,5]
127
+ masked_array(data = [3 4 5],
128
+ mask = False,
129
+ fill_value=999999)
130
+
131
+
132
+ ``anom``
133
+ --------
134
+
135
+ The ``anom`` method returns the deviations from the average (anomalies).
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/LICENSE ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ * Copyright (c) 2006, University of Georgia and Pierre G.F. Gerard-Marchant
2
+ * All rights reserved.
3
+ * Redistribution and use in source and binary forms, with or without
4
+ * modification, are permitted provided that the following conditions are met:
5
+ *
6
+ * * Redistributions of source code must retain the above copyright
7
+ * notice, this list of conditions and the following disclaimer.
8
+ * * Redistributions in binary form must reproduce the above copyright
9
+ * notice, this list of conditions and the following disclaimer in the
10
+ * documentation and/or other materials provided with the distribution.
11
+ * * Neither the name of the University of Georgia nor the
12
+ * names of its contributors may be used to endorse or promote products
13
+ * derived from this software without specific prior written permission.
14
+ *
15
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
16
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18
+ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
19
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/README.rst ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ==================================
2
+ A guide to masked arrays in NumPy
3
+ ==================================
4
+
5
+ .. Contents::
6
+
7
+ See http://www.scipy.org/scipy/numpy/wiki/MaskedArray (dead link)
8
+ for updates of this document.
9
+
10
+
11
+ History
12
+ -------
13
+
14
+ As a regular user of MaskedArray, I (Pierre G.F. Gerard-Marchant) became
15
+ increasingly frustrated with the subclassing of masked arrays (even if
16
+ I can only blame my inexperience). I needed to develop a class of arrays
17
+ that could store some additional information along with numerical values,
18
+ while keeping the possibility for missing data (picture storing a series
19
+ of dates along with measurements, what would later become the `TimeSeries
20
+ Scikit <http://projects.scipy.org/scipy/scikits/wiki/TimeSeries>`__
21
+ (dead link).
22
+
23
+ I started to implement such a class, but then quickly realized that
24
+ any additional information disappeared when processing these subarrays
25
+ (for example, adding a constant value to a subarray would erase its
26
+ dates). I ended up writing the equivalent of *numpy.core.ma* for my
27
+ particular class, ufuncs included. Everything went fine until I needed to
28
+ subclass my new class, when more problems showed up: some attributes of
29
+ the new subclass were lost during processing. I identified the culprit as
30
+ MaskedArray, which returns masked ndarrays when I expected masked
31
+ arrays of my class. I was preparing myself to rewrite *numpy.core.ma*
32
+ when I forced myself to learn how to subclass ndarrays. As I became more
33
+ familiar with the *__new__* and *__array_finalize__* methods,
34
+ I started to wonder why masked arrays were objects, and not ndarrays,
35
+ and whether it wouldn't be more convenient for subclassing if they did
36
+ behave like regular ndarrays.
37
+
38
+ The new *maskedarray* is what I eventually come up with. The
39
+ main differences with the initial *numpy.core.ma* package are
40
+ that MaskedArray is now a subclass of *ndarray* and that the
41
+ *_data* section can now be any subclass of *ndarray*. Apart from a
42
+ couple of issues listed below, the behavior of the new MaskedArray
43
+ class reproduces the old one. Initially the *maskedarray*
44
+ implementation was marginally slower than *numpy.ma* in some areas,
45
+ but work is underway to speed it up; the expectation is that it can be
46
+ made substantially faster than the present *numpy.ma*.
47
+
48
+
49
+ Note that if the subclass has some special methods and
50
+ attributes, they are not propagated to the masked version:
51
+ this would require a modification of the *__getattribute__*
52
+ method (first trying *ndarray.__getattribute__*, then trying
53
+ *self._data.__getattribute__* if an exception is raised in the first
54
+ place), which really slows things down.
55
+
56
+ Main differences
57
+ ----------------
58
+
59
+ * The *_data* part of the masked array can be any subclass of ndarray (but not recarray, cf below).
60
+ * *fill_value* is now a property, not a function.
61
+ * 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.
62
+ * I got rid of the *share_mask* flag, I never understood its purpose.
63
+ * *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.
64
+ * in the same way, the comparison of two masked arrays is a masked array, not a boolean
65
+ * *filled(a)* returns an array of the same subclass as *a._data*, and no test is performed on whether it is contiguous or not.
66
+ * 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.
67
+ * *cumsum* works as if the *_data* array was filled with 0. The mask is preserved, but not updated.
68
+ * *cumprod* works as if the *_data* array was filled with 1. The mask is preserved, but not updated.
69
+
70
+ New features
71
+ ------------
72
+
73
+ This list is non-exhaustive...
74
+
75
+ * the *mr_* function mimics *r_* for masked arrays.
76
+ * the *anom* method returns the anomalies (deviations from the average)
77
+
78
+ Using the new package with numpy.core.ma
79
+ ----------------------------------------
80
+
81
+ I tried to make sure that the new package can understand old masked
82
+ arrays. Unfortunately, there's no upward compatibility.
83
+
84
+ For example:
85
+
86
+ >>> import numpy.core.ma as old_ma
87
+ >>> import maskedarray as new_ma
88
+ >>> x = old_ma.array([1,2,3,4,5], mask=[0,0,1,0,0])
89
+ >>> x
90
+ array(data =
91
+ [ 1 2 999999 4 5],
92
+ mask =
93
+ [False False True False False],
94
+ fill_value=999999)
95
+ >>> y = new_ma.array([1,2,3,4,5], mask=[0,0,1,0,0])
96
+ >>> y
97
+ array(data = [1 2 -- 4 5],
98
+ mask = [False False True False False],
99
+ fill_value=999999)
100
+ >>> x==y
101
+ array(data =
102
+ [True True True True True],
103
+ mask =
104
+ [False False True False False],
105
+ fill_value=?)
106
+ >>> old_ma.getmask(x) == new_ma.getmask(x)
107
+ array([True, True, True, True, True])
108
+ >>> old_ma.getmask(y) == new_ma.getmask(y)
109
+ array([True, True, False, True, True])
110
+ >>> old_ma.getmask(y)
111
+ False
112
+
113
+
114
+ Using maskedarray with matplotlib
115
+ ---------------------------------
116
+
117
+ Starting with matplotlib 0.91.2, the masked array importing will work with
118
+ the maskedarray branch) as well as with earlier versions.
119
+
120
+ By default matplotlib still uses numpy.ma, but there is an rcParams setting
121
+ that you can use to select maskedarray instead. In the matplotlibrc file
122
+ you will find::
123
+
124
+ #maskedarray : False # True to use external maskedarray module
125
+ # instead of numpy.ma; this is a temporary #
126
+ setting for testing maskedarray.
127
+
128
+
129
+ Uncomment and set to True to select maskedarray everywhere.
130
+ Alternatively, you can test a script with maskedarray by using a
131
+ command-line option, e.g.::
132
+
133
+ python simple_plot.py --maskedarray
134
+
135
+
136
+ Masked records
137
+ --------------
138
+
139
+ Like *numpy.ma.core*, the *ndarray*-based implementation
140
+ of MaskedArray is limited when working with records: you can
141
+ mask any record of the array, but not a field in a record. If you
142
+ need this feature, you may want to give the *mrecords* package
143
+ a try (available in the *maskedarray* directory in the scipy
144
+ sandbox). This module defines a new class, *MaskedRecord*. An
145
+ instance of this class accepts a *recarray* as data, and uses two
146
+ masks: the *fieldmask* has as many entries as records in the array,
147
+ each entry with the same fields as a record, but of boolean types:
148
+ they indicate whether the field is masked or not; a record entry
149
+ is flagged as masked in the *mask* array if all the fields are
150
+ masked. A few examples in the file should give you an idea of what
151
+ can be done. Note that *mrecords* is still experimental...
152
+
153
+ Optimizing maskedarray
154
+ ----------------------
155
+
156
+ Should masked arrays be filled before processing or not?
157
+ --------------------------------------------------------
158
+
159
+ In the current implementation, most operations on masked arrays involve
160
+ the following steps:
161
+
162
+ * the input arrays are filled
163
+ * the operation is performed on the filled arrays
164
+ * the mask is set for the results, from the combination of the input masks and the mask corresponding to the domain of the operation.
165
+
166
+ For example, consider the division of two masked arrays::
167
+
168
+ import numpy
169
+ import maskedarray as ma
170
+ x = ma.array([1,2,3,4],mask=[1,0,0,0], dtype=numpy.float64)
171
+ y = ma.array([-1,0,1,2], mask=[0,0,0,1], dtype=numpy.float64)
172
+
173
+ The division of x by y is then computed as::
174
+
175
+ d1 = x.filled(0) # d1 = array([0., 2., 3., 4.])
176
+ d2 = y.filled(1) # array([-1., 0., 1., 1.])
177
+ m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m =
178
+ array([True,False,False,True])
179
+ dm = ma.divide.domain(d1,d2) # array([False, True, False, False])
180
+ result = (d1/d2).view(MaskedArray) # masked_array([-0. inf, 3., 4.])
181
+ result._mask = logical_or(m, dm)
182
+
183
+ Note that a division by zero takes place. To avoid it, we can consider
184
+ to fill the input arrays, taking the domain mask into account, so that::
185
+
186
+ d1 = x._data.copy() # d1 = array([1., 2., 3., 4.])
187
+ d2 = y._data.copy() # array([-1., 0., 1., 2.])
188
+ dm = ma.divide.domain(d1,d2) # array([False, True, False, False])
189
+ numpy.putmask(d2, dm, 1) # d2 = array([-1., 1., 1., 2.])
190
+ m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m =
191
+ array([True,False,False,True])
192
+ result = (d1/d2).view(MaskedArray) # masked_array([-1. 0., 3., 2.])
193
+ result._mask = logical_or(m, dm)
194
+
195
+ Note that the *.copy()* is required to avoid updating the inputs with
196
+ *putmask*. The *.filled()* method also involves a *.copy()*.
197
+
198
+ A third possibility consists in avoid filling the arrays::
199
+
200
+ d1 = x._data # d1 = array([1., 2., 3., 4.])
201
+ d2 = y._data # array([-1., 0., 1., 2.])
202
+ dm = ma.divide.domain(d1,d2) # array([False, True, False, False])
203
+ m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m =
204
+ array([True,False,False,True])
205
+ result = (d1/d2).view(MaskedArray) # masked_array([-1. inf, 3., 2.])
206
+ result._mask = logical_or(m, dm)
207
+
208
+ Note that here again the division by zero takes place.
209
+
210
+ A quick benchmark gives the following results:
211
+
212
+ * *numpy.ma.divide* : 2.69 ms per loop
213
+ * classical division : 2.21 ms per loop
214
+ * division w/ prefilling : 2.34 ms per loop
215
+ * division w/o filling : 1.55 ms per loop
216
+
217
+ So, is it worth filling the arrays beforehand ? Yes, if we are interested
218
+ in avoiding floating-point exceptions that may fill the result with infs
219
+ and nans. No, if we are only interested into speed...
220
+
221
+
222
+ Thanks
223
+ ------
224
+
225
+ I'd like to thank Paul Dubois, Travis Oliphant and Sasha for the
226
+ original masked array package: without you, I would never have started
227
+ that (it might be argued that I shouldn't have anyway, but that's
228
+ another story...). I also wish to extend these thanks to Reggie Dugard
229
+ and Eric Firing for their suggestions and numerous improvements.
230
+
231
+
232
+ Revision notes
233
+ --------------
234
+
235
+ * 08/25/2007 : Creation of this page
236
+ * 01/23/2007 : The package has been moved to the SciPy sandbox, and is regularly updated: please check out your SVN version!
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/__init__.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =============
3
+ Masked Arrays
4
+ =============
5
+
6
+ Arrays sometimes contain invalid or missing data. When doing operations
7
+ on such arrays, we wish to suppress invalid values, which is the purpose masked
8
+ arrays fulfill (an example of typical use is given below).
9
+
10
+ For example, examine the following array:
11
+
12
+ >>> x = np.array([2, 1, 3, np.nan, 5, 2, 3, np.nan])
13
+
14
+ When we try to calculate the mean of the data, the result is undetermined:
15
+
16
+ >>> np.mean(x)
17
+ nan
18
+
19
+ The mean is calculated using roughly ``np.sum(x)/len(x)``, but since
20
+ any number added to ``NaN`` [1]_ produces ``NaN``, this doesn't work. Enter
21
+ masked arrays:
22
+
23
+ >>> m = np.ma.masked_array(x, np.isnan(x))
24
+ >>> m
25
+ masked_array(data=[2.0, 1.0, 3.0, --, 5.0, 2.0, 3.0, --],
26
+ mask=[False, False, False, True, False, False, False, True],
27
+ fill_value=1e+20)
28
+
29
+ Here, we construct a masked array that suppress all ``NaN`` values. We
30
+ may now proceed to calculate the mean of the other values:
31
+
32
+ >>> np.mean(m)
33
+ 2.6666666666666665
34
+
35
+ .. [1] Not-a-Number, a floating point value that is the result of an
36
+ invalid operation.
37
+
38
+ .. moduleauthor:: Pierre Gerard-Marchant
39
+ .. moduleauthor:: Jarrod Millman
40
+
41
+ """
42
+ from . import core, extras
43
+ from .core import *
44
+ from .extras import *
45
+
46
+ __all__ = ['core', 'extras']
47
+ __all__ += core.__all__
48
+ __all__ += extras.__all__
49
+
50
+ from numpy._pytesttester import PytestTester
51
+
52
+ test = PytestTester(__name__)
53
+ del PytestTester
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/__init__.pyi ADDED
@@ -0,0 +1,458 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import core, extras
2
+ from .core import (
3
+ MAError,
4
+ MaskedArray,
5
+ MaskError,
6
+ MaskType,
7
+ abs,
8
+ absolute,
9
+ add,
10
+ all,
11
+ allclose,
12
+ allequal,
13
+ alltrue,
14
+ amax,
15
+ amin,
16
+ angle,
17
+ anom,
18
+ anomalies,
19
+ any,
20
+ append,
21
+ arange,
22
+ arccos,
23
+ arccosh,
24
+ arcsin,
25
+ arcsinh,
26
+ arctan,
27
+ arctan2,
28
+ arctanh,
29
+ argmax,
30
+ argmin,
31
+ argsort,
32
+ around,
33
+ array,
34
+ asanyarray,
35
+ asarray,
36
+ bitwise_and,
37
+ bitwise_or,
38
+ bitwise_xor,
39
+ bool_,
40
+ ceil,
41
+ choose,
42
+ clip,
43
+ common_fill_value,
44
+ compress,
45
+ compressed,
46
+ concatenate,
47
+ conjugate,
48
+ convolve,
49
+ copy,
50
+ correlate,
51
+ cos,
52
+ cosh,
53
+ count,
54
+ cumprod,
55
+ cumsum,
56
+ default_fill_value,
57
+ diag,
58
+ diagonal,
59
+ diff,
60
+ divide,
61
+ empty,
62
+ empty_like,
63
+ equal,
64
+ exp,
65
+ expand_dims,
66
+ fabs,
67
+ filled,
68
+ fix_invalid,
69
+ flatten_mask,
70
+ flatten_structured_array,
71
+ floor,
72
+ floor_divide,
73
+ fmod,
74
+ frombuffer,
75
+ fromflex,
76
+ fromfunction,
77
+ getdata,
78
+ getmask,
79
+ getmaskarray,
80
+ greater,
81
+ greater_equal,
82
+ harden_mask,
83
+ hypot,
84
+ identity,
85
+ ids,
86
+ indices,
87
+ inner,
88
+ innerproduct,
89
+ is_mask,
90
+ is_masked,
91
+ isarray,
92
+ isMA,
93
+ isMaskedArray,
94
+ left_shift,
95
+ less,
96
+ less_equal,
97
+ log,
98
+ log2,
99
+ log10,
100
+ logical_and,
101
+ logical_not,
102
+ logical_or,
103
+ logical_xor,
104
+ make_mask,
105
+ make_mask_descr,
106
+ make_mask_none,
107
+ mask_or,
108
+ masked,
109
+ masked_array,
110
+ masked_equal,
111
+ masked_greater,
112
+ masked_greater_equal,
113
+ masked_inside,
114
+ masked_invalid,
115
+ masked_less,
116
+ masked_less_equal,
117
+ masked_not_equal,
118
+ masked_object,
119
+ masked_outside,
120
+ masked_print_option,
121
+ masked_singleton,
122
+ masked_values,
123
+ masked_where,
124
+ max,
125
+ maximum,
126
+ maximum_fill_value,
127
+ mean,
128
+ min,
129
+ minimum,
130
+ minimum_fill_value,
131
+ mod,
132
+ multiply,
133
+ mvoid,
134
+ ndim,
135
+ negative,
136
+ nomask,
137
+ nonzero,
138
+ not_equal,
139
+ ones,
140
+ ones_like,
141
+ outer,
142
+ outerproduct,
143
+ power,
144
+ prod,
145
+ product,
146
+ ptp,
147
+ put,
148
+ putmask,
149
+ ravel,
150
+ remainder,
151
+ repeat,
152
+ reshape,
153
+ resize,
154
+ right_shift,
155
+ round,
156
+ round_,
157
+ set_fill_value,
158
+ shape,
159
+ sin,
160
+ sinh,
161
+ size,
162
+ soften_mask,
163
+ sometrue,
164
+ sort,
165
+ sqrt,
166
+ squeeze,
167
+ std,
168
+ subtract,
169
+ sum,
170
+ swapaxes,
171
+ take,
172
+ tan,
173
+ tanh,
174
+ trace,
175
+ transpose,
176
+ true_divide,
177
+ var,
178
+ where,
179
+ zeros,
180
+ zeros_like,
181
+ )
182
+ from .extras import (
183
+ apply_along_axis,
184
+ apply_over_axes,
185
+ atleast_1d,
186
+ atleast_2d,
187
+ atleast_3d,
188
+ average,
189
+ clump_masked,
190
+ clump_unmasked,
191
+ column_stack,
192
+ compress_cols,
193
+ compress_nd,
194
+ compress_rowcols,
195
+ compress_rows,
196
+ corrcoef,
197
+ count_masked,
198
+ cov,
199
+ diagflat,
200
+ dot,
201
+ dstack,
202
+ ediff1d,
203
+ flatnotmasked_contiguous,
204
+ flatnotmasked_edges,
205
+ hsplit,
206
+ hstack,
207
+ in1d,
208
+ intersect1d,
209
+ isin,
210
+ mask_cols,
211
+ mask_rowcols,
212
+ mask_rows,
213
+ masked_all,
214
+ masked_all_like,
215
+ median,
216
+ mr_,
217
+ ndenumerate,
218
+ notmasked_contiguous,
219
+ notmasked_edges,
220
+ polyfit,
221
+ row_stack,
222
+ setdiff1d,
223
+ setxor1d,
224
+ stack,
225
+ union1d,
226
+ unique,
227
+ vander,
228
+ vstack,
229
+ )
230
+
231
+ __all__ = [
232
+ "core",
233
+ "extras",
234
+ "MAError",
235
+ "MaskError",
236
+ "MaskType",
237
+ "MaskedArray",
238
+ "abs",
239
+ "absolute",
240
+ "add",
241
+ "all",
242
+ "allclose",
243
+ "allequal",
244
+ "alltrue",
245
+ "amax",
246
+ "amin",
247
+ "angle",
248
+ "anom",
249
+ "anomalies",
250
+ "any",
251
+ "append",
252
+ "arange",
253
+ "arccos",
254
+ "arccosh",
255
+ "arcsin",
256
+ "arcsinh",
257
+ "arctan",
258
+ "arctan2",
259
+ "arctanh",
260
+ "argmax",
261
+ "argmin",
262
+ "argsort",
263
+ "around",
264
+ "array",
265
+ "asanyarray",
266
+ "asarray",
267
+ "bitwise_and",
268
+ "bitwise_or",
269
+ "bitwise_xor",
270
+ "bool_",
271
+ "ceil",
272
+ "choose",
273
+ "clip",
274
+ "common_fill_value",
275
+ "compress",
276
+ "compressed",
277
+ "concatenate",
278
+ "conjugate",
279
+ "convolve",
280
+ "copy",
281
+ "correlate",
282
+ "cos",
283
+ "cosh",
284
+ "count",
285
+ "cumprod",
286
+ "cumsum",
287
+ "default_fill_value",
288
+ "diag",
289
+ "diagonal",
290
+ "diff",
291
+ "divide",
292
+ "empty",
293
+ "empty_like",
294
+ "equal",
295
+ "exp",
296
+ "expand_dims",
297
+ "fabs",
298
+ "filled",
299
+ "fix_invalid",
300
+ "flatten_mask",
301
+ "flatten_structured_array",
302
+ "floor",
303
+ "floor_divide",
304
+ "fmod",
305
+ "frombuffer",
306
+ "fromflex",
307
+ "fromfunction",
308
+ "getdata",
309
+ "getmask",
310
+ "getmaskarray",
311
+ "greater",
312
+ "greater_equal",
313
+ "harden_mask",
314
+ "hypot",
315
+ "identity",
316
+ "ids",
317
+ "indices",
318
+ "inner",
319
+ "innerproduct",
320
+ "isMA",
321
+ "isMaskedArray",
322
+ "is_mask",
323
+ "is_masked",
324
+ "isarray",
325
+ "left_shift",
326
+ "less",
327
+ "less_equal",
328
+ "log",
329
+ "log10",
330
+ "log2",
331
+ "logical_and",
332
+ "logical_not",
333
+ "logical_or",
334
+ "logical_xor",
335
+ "make_mask",
336
+ "make_mask_descr",
337
+ "make_mask_none",
338
+ "mask_or",
339
+ "masked",
340
+ "masked_array",
341
+ "masked_equal",
342
+ "masked_greater",
343
+ "masked_greater_equal",
344
+ "masked_inside",
345
+ "masked_invalid",
346
+ "masked_less",
347
+ "masked_less_equal",
348
+ "masked_not_equal",
349
+ "masked_object",
350
+ "masked_outside",
351
+ "masked_print_option",
352
+ "masked_singleton",
353
+ "masked_values",
354
+ "masked_where",
355
+ "max",
356
+ "maximum",
357
+ "maximum_fill_value",
358
+ "mean",
359
+ "min",
360
+ "minimum",
361
+ "minimum_fill_value",
362
+ "mod",
363
+ "multiply",
364
+ "mvoid",
365
+ "ndim",
366
+ "negative",
367
+ "nomask",
368
+ "nonzero",
369
+ "not_equal",
370
+ "ones",
371
+ "ones_like",
372
+ "outer",
373
+ "outerproduct",
374
+ "power",
375
+ "prod",
376
+ "product",
377
+ "ptp",
378
+ "put",
379
+ "putmask",
380
+ "ravel",
381
+ "remainder",
382
+ "repeat",
383
+ "reshape",
384
+ "resize",
385
+ "right_shift",
386
+ "round",
387
+ "round_",
388
+ "set_fill_value",
389
+ "shape",
390
+ "sin",
391
+ "sinh",
392
+ "size",
393
+ "soften_mask",
394
+ "sometrue",
395
+ "sort",
396
+ "sqrt",
397
+ "squeeze",
398
+ "std",
399
+ "subtract",
400
+ "sum",
401
+ "swapaxes",
402
+ "take",
403
+ "tan",
404
+ "tanh",
405
+ "trace",
406
+ "transpose",
407
+ "true_divide",
408
+ "var",
409
+ "where",
410
+ "zeros",
411
+ "zeros_like",
412
+ "apply_along_axis",
413
+ "apply_over_axes",
414
+ "atleast_1d",
415
+ "atleast_2d",
416
+ "atleast_3d",
417
+ "average",
418
+ "clump_masked",
419
+ "clump_unmasked",
420
+ "column_stack",
421
+ "compress_cols",
422
+ "compress_nd",
423
+ "compress_rowcols",
424
+ "compress_rows",
425
+ "count_masked",
426
+ "corrcoef",
427
+ "cov",
428
+ "diagflat",
429
+ "dot",
430
+ "dstack",
431
+ "ediff1d",
432
+ "flatnotmasked_contiguous",
433
+ "flatnotmasked_edges",
434
+ "hsplit",
435
+ "hstack",
436
+ "isin",
437
+ "in1d",
438
+ "intersect1d",
439
+ "mask_cols",
440
+ "mask_rowcols",
441
+ "mask_rows",
442
+ "masked_all",
443
+ "masked_all_like",
444
+ "median",
445
+ "mr_",
446
+ "ndenumerate",
447
+ "notmasked_contiguous",
448
+ "notmasked_edges",
449
+ "polyfit",
450
+ "row_stack",
451
+ "setdiff1d",
452
+ "setxor1d",
453
+ "stack",
454
+ "unique",
455
+ "union1d",
456
+ "vander",
457
+ "vstack",
458
+ ]
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/core.py ADDED
The diff for this file is too large to render. See raw diff
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/core.pyi ADDED
The diff for this file is too large to render. See raw diff
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/extras.py ADDED
@@ -0,0 +1,2266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Masked arrays add-ons.
3
+
4
+ A collection of utilities for `numpy.ma`.
5
+
6
+ :author: Pierre Gerard-Marchant
7
+ :contact: pierregm_at_uga_dot_edu
8
+
9
+ """
10
+ __all__ = [
11
+ 'apply_along_axis', 'apply_over_axes', 'atleast_1d', 'atleast_2d',
12
+ 'atleast_3d', 'average', 'clump_masked', 'clump_unmasked', 'column_stack',
13
+ 'compress_cols', 'compress_nd', 'compress_rowcols', 'compress_rows',
14
+ 'count_masked', 'corrcoef', 'cov', 'diagflat', 'dot', 'dstack', 'ediff1d',
15
+ 'flatnotmasked_contiguous', 'flatnotmasked_edges', 'hsplit', 'hstack',
16
+ 'isin', 'in1d', 'intersect1d', 'mask_cols', 'mask_rowcols', 'mask_rows',
17
+ 'masked_all', 'masked_all_like', 'median', 'mr_', 'ndenumerate',
18
+ 'notmasked_contiguous', 'notmasked_edges', 'polyfit', 'row_stack',
19
+ 'setdiff1d', 'setxor1d', 'stack', 'unique', 'union1d', 'vander', 'vstack',
20
+ ]
21
+
22
+ import functools
23
+ import itertools
24
+ import warnings
25
+
26
+ import numpy as np
27
+ from numpy import array as nxarray, ndarray
28
+ from numpy.lib._function_base_impl import _ureduce
29
+ from numpy.lib._index_tricks_impl import AxisConcatenator
30
+ from numpy.lib.array_utils import normalize_axis_index, normalize_axis_tuple
31
+
32
+ from . import core as ma
33
+ from .core import ( # noqa: F401
34
+ MAError,
35
+ MaskedArray,
36
+ add,
37
+ array,
38
+ asarray,
39
+ concatenate,
40
+ count,
41
+ dot,
42
+ filled,
43
+ get_masked_subclass,
44
+ getdata,
45
+ getmask,
46
+ getmaskarray,
47
+ make_mask_descr,
48
+ mask_or,
49
+ masked,
50
+ masked_array,
51
+ nomask,
52
+ ones,
53
+ sort,
54
+ zeros,
55
+ )
56
+
57
+
58
+ def issequence(seq):
59
+ """
60
+ Is seq a sequence (ndarray, list or tuple)?
61
+
62
+ """
63
+ return isinstance(seq, (ndarray, tuple, list))
64
+
65
+
66
+ def count_masked(arr, axis=None):
67
+ """
68
+ Count the number of masked elements along the given axis.
69
+
70
+ Parameters
71
+ ----------
72
+ arr : array_like
73
+ An array with (possibly) masked elements.
74
+ axis : int, optional
75
+ Axis along which to count. If None (default), a flattened
76
+ version of the array is used.
77
+
78
+ Returns
79
+ -------
80
+ count : int, ndarray
81
+ The total number of masked elements (axis=None) or the number
82
+ of masked elements along each slice of the given axis.
83
+
84
+ See Also
85
+ --------
86
+ MaskedArray.count : Count non-masked elements.
87
+
88
+ Examples
89
+ --------
90
+ >>> import numpy as np
91
+ >>> a = np.arange(9).reshape((3,3))
92
+ >>> a = np.ma.array(a)
93
+ >>> a[1, 0] = np.ma.masked
94
+ >>> a[1, 2] = np.ma.masked
95
+ >>> a[2, 1] = np.ma.masked
96
+ >>> a
97
+ masked_array(
98
+ data=[[0, 1, 2],
99
+ [--, 4, --],
100
+ [6, --, 8]],
101
+ mask=[[False, False, False],
102
+ [ True, False, True],
103
+ [False, True, False]],
104
+ fill_value=999999)
105
+ >>> np.ma.count_masked(a)
106
+ 3
107
+
108
+ When the `axis` keyword is used an array is returned.
109
+
110
+ >>> np.ma.count_masked(a, axis=0)
111
+ array([1, 1, 1])
112
+ >>> np.ma.count_masked(a, axis=1)
113
+ array([0, 2, 1])
114
+
115
+ """
116
+ m = getmaskarray(arr)
117
+ return m.sum(axis)
118
+
119
+
120
+ def masked_all(shape, dtype=float):
121
+ """
122
+ Empty masked array with all elements masked.
123
+
124
+ Return an empty masked array of the given shape and dtype, where all the
125
+ data are masked.
126
+
127
+ Parameters
128
+ ----------
129
+ shape : int or tuple of ints
130
+ Shape of the required MaskedArray, e.g., ``(2, 3)`` or ``2``.
131
+ dtype : dtype, optional
132
+ Data type of the output.
133
+
134
+ Returns
135
+ -------
136
+ a : MaskedArray
137
+ A masked array with all data masked.
138
+
139
+ See Also
140
+ --------
141
+ masked_all_like : Empty masked array modelled on an existing array.
142
+
143
+ Notes
144
+ -----
145
+ Unlike other masked array creation functions (e.g. `numpy.ma.zeros`,
146
+ `numpy.ma.ones`, `numpy.ma.full`), `masked_all` does not initialize the
147
+ values of the array, and may therefore be marginally faster. However,
148
+ the values stored in the newly allocated array are arbitrary. For
149
+ reproducible behavior, be sure to set each element of the array before
150
+ reading.
151
+
152
+ Examples
153
+ --------
154
+ >>> import numpy as np
155
+ >>> np.ma.masked_all((3, 3))
156
+ masked_array(
157
+ data=[[--, --, --],
158
+ [--, --, --],
159
+ [--, --, --]],
160
+ mask=[[ True, True, True],
161
+ [ True, True, True],
162
+ [ True, True, True]],
163
+ fill_value=1e+20,
164
+ dtype=float64)
165
+
166
+ The `dtype` parameter defines the underlying data type.
167
+
168
+ >>> a = np.ma.masked_all((3, 3))
169
+ >>> a.dtype
170
+ dtype('float64')
171
+ >>> a = np.ma.masked_all((3, 3), dtype=np.int32)
172
+ >>> a.dtype
173
+ dtype('int32')
174
+
175
+ """
176
+ a = masked_array(np.empty(shape, dtype),
177
+ mask=np.ones(shape, make_mask_descr(dtype)))
178
+ return a
179
+
180
+
181
+ def masked_all_like(arr):
182
+ """
183
+ Empty masked array with the properties of an existing array.
184
+
185
+ Return an empty masked array of the same shape and dtype as
186
+ the array `arr`, where all the data are masked.
187
+
188
+ Parameters
189
+ ----------
190
+ arr : ndarray
191
+ An array describing the shape and dtype of the required MaskedArray.
192
+
193
+ Returns
194
+ -------
195
+ a : MaskedArray
196
+ A masked array with all data masked.
197
+
198
+ Raises
199
+ ------
200
+ AttributeError
201
+ If `arr` doesn't have a shape attribute (i.e. not an ndarray)
202
+
203
+ See Also
204
+ --------
205
+ masked_all : Empty masked array with all elements masked.
206
+
207
+ Notes
208
+ -----
209
+ Unlike other masked array creation functions (e.g. `numpy.ma.zeros_like`,
210
+ `numpy.ma.ones_like`, `numpy.ma.full_like`), `masked_all_like` does not
211
+ initialize the values of the array, and may therefore be marginally
212
+ faster. However, the values stored in the newly allocated array are
213
+ arbitrary. For reproducible behavior, be sure to set each element of the
214
+ array before reading.
215
+
216
+ Examples
217
+ --------
218
+ >>> import numpy as np
219
+ >>> arr = np.zeros((2, 3), dtype=np.float32)
220
+ >>> arr
221
+ array([[0., 0., 0.],
222
+ [0., 0., 0.]], dtype=float32)
223
+ >>> np.ma.masked_all_like(arr)
224
+ masked_array(
225
+ data=[[--, --, --],
226
+ [--, --, --]],
227
+ mask=[[ True, True, True],
228
+ [ True, True, True]],
229
+ fill_value=np.float64(1e+20),
230
+ dtype=float32)
231
+
232
+ The dtype of the masked array matches the dtype of `arr`.
233
+
234
+ >>> arr.dtype
235
+ dtype('float32')
236
+ >>> np.ma.masked_all_like(arr).dtype
237
+ dtype('float32')
238
+
239
+ """
240
+ a = np.empty_like(arr).view(MaskedArray)
241
+ a._mask = np.ones(a.shape, dtype=make_mask_descr(a.dtype))
242
+ return a
243
+
244
+
245
+ #####--------------------------------------------------------------------------
246
+ #---- --- Standard functions ---
247
+ #####--------------------------------------------------------------------------
248
+
249
+ def _fromnxfunction_function(_fromnxfunction):
250
+ """
251
+ Decorator to wrap a "_fromnxfunction" function, wrapping a numpy function as a
252
+ masked array function, with proper docstring and name.
253
+
254
+ Parameters
255
+ ----------
256
+ _fromnxfunction : ({params}) -> ndarray, {params}) -> masked_array
257
+ Wrapper function that calls the wrapped numpy function
258
+
259
+ Returns
260
+ -------
261
+ decorator : (f: ({params}) -> ndarray) -> ({params}) -> masked_array
262
+ Function that accepts a numpy function and returns a masked array function
263
+
264
+ """
265
+ def decorator(npfunc, /):
266
+ def wrapper(*args, **kwargs):
267
+ return _fromnxfunction(npfunc, *args, **kwargs)
268
+
269
+ functools.update_wrapper(wrapper, npfunc, assigned=("__name__", "__qualname__"))
270
+ wrapper.__doc__ = ma.doc_note(
271
+ npfunc.__doc__,
272
+ "The function is applied to both the ``_data`` and the ``_mask``, if any.",
273
+ )
274
+ return wrapper
275
+
276
+ return decorator
277
+
278
+
279
+ @_fromnxfunction_function
280
+ def _fromnxfunction_single(npfunc, a, /, *args, **kwargs):
281
+ """
282
+ Wraps a NumPy function that can be called with a single array argument followed by
283
+ auxiliary args that are passed verbatim for both the data and mask calls.
284
+ """
285
+ return masked_array(
286
+ data=npfunc(np.asarray(a), *args, **kwargs),
287
+ mask=npfunc(getmaskarray(a), *args, **kwargs),
288
+ )
289
+
290
+
291
+ @_fromnxfunction_function
292
+ def _fromnxfunction_seq(npfunc, arys, /, *args, **kwargs):
293
+ """
294
+ Wraps a NumPy function that can be called with a single sequence of arrays followed
295
+ by auxiliary args that are passed verbatim for both the data and mask calls.
296
+ """
297
+ return masked_array(
298
+ data=npfunc(tuple(np.asarray(a) for a in arys), *args, **kwargs),
299
+ mask=npfunc(tuple(getmaskarray(a) for a in arys), *args, **kwargs),
300
+ )
301
+
302
+ @_fromnxfunction_function
303
+ def _fromnxfunction_allargs(npfunc, /, *arys, **kwargs):
304
+ """
305
+ Wraps a NumPy function that can be called with multiple array arguments.
306
+ All args are converted to arrays even if they are not so already.
307
+ This makes it possible to process scalars as 1-D arrays.
308
+ Only keyword arguments are passed through verbatim for the data and mask calls.
309
+ Arrays arguments are processed independently and the results are returned in a list.
310
+ If only one arg is present, the return value is just the processed array instead of
311
+ a list.
312
+ """
313
+ out = tuple(
314
+ masked_array(
315
+ data=npfunc(np.asarray(a), **kwargs),
316
+ mask=npfunc(getmaskarray(a), **kwargs),
317
+ )
318
+ for a in arys
319
+ )
320
+ return out[0] if len(out) == 1 else out
321
+
322
+
323
+ atleast_1d = _fromnxfunction_allargs(np.atleast_1d)
324
+ atleast_2d = _fromnxfunction_allargs(np.atleast_2d)
325
+ atleast_3d = _fromnxfunction_allargs(np.atleast_3d)
326
+
327
+ vstack = row_stack = _fromnxfunction_seq(np.vstack)
328
+ hstack = _fromnxfunction_seq(np.hstack)
329
+ column_stack = _fromnxfunction_seq(np.column_stack)
330
+ dstack = _fromnxfunction_seq(np.dstack)
331
+ stack = _fromnxfunction_seq(np.stack)
332
+
333
+ hsplit = _fromnxfunction_single(np.hsplit)
334
+ diagflat = _fromnxfunction_single(np.diagflat)
335
+
336
+
337
+ #####--------------------------------------------------------------------------
338
+ #----
339
+ #####--------------------------------------------------------------------------
340
+ def flatten_inplace(seq):
341
+ """Flatten a sequence in place."""
342
+ k = 0
343
+ while (k != len(seq)):
344
+ while hasattr(seq[k], '__iter__'):
345
+ seq[k:(k + 1)] = seq[k]
346
+ k += 1
347
+ return seq
348
+
349
+
350
+ def apply_along_axis(func1d, axis, arr, *args, **kwargs):
351
+ """
352
+ (This docstring should be overwritten)
353
+ """
354
+ arr = array(arr, copy=False, subok=True)
355
+ nd = arr.ndim
356
+ axis = normalize_axis_index(axis, nd)
357
+ ind = [0] * (nd - 1)
358
+ i = np.zeros(nd, 'O')
359
+ indlist = list(range(nd))
360
+ indlist.remove(axis)
361
+ i[axis] = slice(None, None)
362
+ outshape = np.asarray(arr.shape).take(indlist)
363
+ i.put(indlist, ind)
364
+ res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
365
+ # if res is a number, then we have a smaller output array
366
+ asscalar = np.isscalar(res)
367
+ if not asscalar:
368
+ try:
369
+ len(res)
370
+ except TypeError:
371
+ asscalar = True
372
+ # Note: we shouldn't set the dtype of the output from the first result
373
+ # so we force the type to object, and build a list of dtypes. We'll
374
+ # just take the largest, to avoid some downcasting
375
+ dtypes = []
376
+ if asscalar:
377
+ dtypes.append(np.asarray(res).dtype)
378
+ outarr = zeros(outshape, object)
379
+ outarr[tuple(ind)] = res
380
+ Ntot = np.prod(outshape)
381
+ k = 1
382
+ while k < Ntot:
383
+ # increment the index
384
+ ind[-1] += 1
385
+ n = -1
386
+ while (ind[n] >= outshape[n]) and (n > (1 - nd)):
387
+ ind[n - 1] += 1
388
+ ind[n] = 0
389
+ n -= 1
390
+ i.put(indlist, ind)
391
+ res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
392
+ outarr[tuple(ind)] = res
393
+ dtypes.append(asarray(res).dtype)
394
+ k += 1
395
+ else:
396
+ res = array(res, copy=False, subok=True)
397
+ j = i.copy()
398
+ j[axis] = ([slice(None, None)] * res.ndim)
399
+ j.put(indlist, ind)
400
+ Ntot = np.prod(outshape)
401
+ holdshape = outshape
402
+ outshape = list(arr.shape)
403
+ outshape[axis] = res.shape
404
+ dtypes.append(asarray(res).dtype)
405
+ outshape = flatten_inplace(outshape)
406
+ outarr = zeros(outshape, object)
407
+ outarr[tuple(flatten_inplace(j.tolist()))] = res
408
+ k = 1
409
+ while k < Ntot:
410
+ # increment the index
411
+ ind[-1] += 1
412
+ n = -1
413
+ while (ind[n] >= holdshape[n]) and (n > (1 - nd)):
414
+ ind[n - 1] += 1
415
+ ind[n] = 0
416
+ n -= 1
417
+ i.put(indlist, ind)
418
+ j.put(indlist, ind)
419
+ res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
420
+ outarr[tuple(flatten_inplace(j.tolist()))] = res
421
+ dtypes.append(asarray(res).dtype)
422
+ k += 1
423
+ max_dtypes = np.dtype(np.asarray(dtypes).max())
424
+ if not hasattr(arr, '_mask'):
425
+ result = np.asarray(outarr, dtype=max_dtypes)
426
+ else:
427
+ result = asarray(outarr, dtype=max_dtypes)
428
+ result.fill_value = ma.default_fill_value(result)
429
+ return result
430
+
431
+
432
+ apply_along_axis.__doc__ = np.apply_along_axis.__doc__
433
+
434
+
435
+ def apply_over_axes(func, a, axes):
436
+ """
437
+ (This docstring will be overwritten)
438
+ """
439
+ val = asarray(a)
440
+ N = a.ndim
441
+ if array(axes).ndim == 0:
442
+ axes = (axes,)
443
+ for axis in axes:
444
+ if axis < 0:
445
+ axis = N + axis
446
+ args = (val, axis)
447
+ res = func(*args)
448
+ if res.ndim == val.ndim:
449
+ val = res
450
+ else:
451
+ res = ma.expand_dims(res, axis)
452
+ if res.ndim == val.ndim:
453
+ val = res
454
+ else:
455
+ raise ValueError("function is not returning "
456
+ "an array of the correct shape")
457
+ return val
458
+
459
+
460
+ if apply_over_axes.__doc__ is not None:
461
+ apply_over_axes.__doc__ = np.apply_over_axes.__doc__[
462
+ :np.apply_over_axes.__doc__.find('Notes')].rstrip() + \
463
+ """
464
+
465
+ Examples
466
+ --------
467
+ >>> import numpy as np
468
+ >>> a = np.ma.arange(24).reshape(2,3,4)
469
+ >>> a[:,0,1] = np.ma.masked
470
+ >>> a[:,1,:] = np.ma.masked
471
+ >>> a
472
+ masked_array(
473
+ data=[[[0, --, 2, 3],
474
+ [--, --, --, --],
475
+ [8, 9, 10, 11]],
476
+ [[12, --, 14, 15],
477
+ [--, --, --, --],
478
+ [20, 21, 22, 23]]],
479
+ mask=[[[False, True, False, False],
480
+ [ True, True, True, True],
481
+ [False, False, False, False]],
482
+ [[False, True, False, False],
483
+ [ True, True, True, True],
484
+ [False, False, False, False]]],
485
+ fill_value=999999)
486
+ >>> np.ma.apply_over_axes(np.ma.sum, a, [0,2])
487
+ masked_array(
488
+ data=[[[46],
489
+ [--],
490
+ [124]]],
491
+ mask=[[[False],
492
+ [ True],
493
+ [False]]],
494
+ fill_value=999999)
495
+
496
+ Tuple axis arguments to ufuncs are equivalent:
497
+
498
+ >>> np.ma.sum(a, axis=(0,2)).reshape((1,-1,1))
499
+ masked_array(
500
+ data=[[[46],
501
+ [--],
502
+ [124]]],
503
+ mask=[[[False],
504
+ [ True],
505
+ [False]]],
506
+ fill_value=999999)
507
+ """
508
+
509
+
510
+ def average(a, axis=None, weights=None, returned=False, *,
511
+ keepdims=np._NoValue):
512
+ """
513
+ Return the weighted average of array over the given axis.
514
+
515
+ Parameters
516
+ ----------
517
+ a : array_like
518
+ Data to be averaged.
519
+ Masked entries are not taken into account in the computation.
520
+ axis : None or int or tuple of ints, optional
521
+ Axis or axes along which to average `a`. The default,
522
+ `axis=None`, will average over all of the elements of the input array.
523
+ If axis is a tuple of ints, averaging is performed on all of the axes
524
+ specified in the tuple instead of a single axis or all the axes as
525
+ before.
526
+ weights : array_like, optional
527
+ An array of weights associated with the values in `a`. Each value in
528
+ `a` contributes to the average according to its associated weight.
529
+ The array of weights must be the same shape as `a` if no axis is
530
+ specified, otherwise the weights must have dimensions and shape
531
+ consistent with `a` along the specified axis.
532
+ If `weights=None`, then all data in `a` are assumed to have a
533
+ weight equal to one.
534
+ The calculation is::
535
+
536
+ avg = sum(a * weights) / sum(weights)
537
+
538
+ where the sum is over all included elements.
539
+ The only constraint on the values of `weights` is that `sum(weights)`
540
+ must not be 0.
541
+ returned : bool, optional
542
+ Flag indicating whether a tuple ``(result, sum of weights)``
543
+ should be returned as output (True), or just the result (False).
544
+ Default is False.
545
+ keepdims : bool, optional
546
+ If this is set to True, the axes which are reduced are left
547
+ in the result as dimensions with size one. With this option,
548
+ the result will broadcast correctly against the original `a`.
549
+ *Note:* `keepdims` will not work with instances of `numpy.matrix`
550
+ or other classes whose methods do not support `keepdims`.
551
+
552
+ .. versionadded:: 1.23.0
553
+
554
+ Returns
555
+ -------
556
+ average, [sum_of_weights] : (tuple of) scalar or MaskedArray
557
+ The average along the specified axis. When returned is `True`,
558
+ return a tuple with the average as the first element and the sum
559
+ of the weights as the second element. The return type is `np.float64`
560
+ if `a` is of integer type and floats smaller than `float64`, or the
561
+ input data-type, otherwise. If returned, `sum_of_weights` is always
562
+ `float64`.
563
+
564
+ Raises
565
+ ------
566
+ ZeroDivisionError
567
+ When all weights along axis are zero. See `numpy.ma.average` for a
568
+ version robust to this type of error.
569
+ TypeError
570
+ When `weights` does not have the same shape as `a`, and `axis=None`.
571
+ ValueError
572
+ When `weights` does not have dimensions and shape consistent with `a`
573
+ along specified `axis`.
574
+
575
+ Examples
576
+ --------
577
+ >>> import numpy as np
578
+ >>> a = np.ma.array([1., 2., 3., 4.], mask=[False, False, True, True])
579
+ >>> np.ma.average(a, weights=[3, 1, 0, 0])
580
+ 1.25
581
+
582
+ >>> x = np.ma.arange(6.).reshape(3, 2)
583
+ >>> x
584
+ masked_array(
585
+ data=[[0., 1.],
586
+ [2., 3.],
587
+ [4., 5.]],
588
+ mask=False,
589
+ fill_value=1e+20)
590
+ >>> data = np.arange(8).reshape((2, 2, 2))
591
+ >>> data
592
+ array([[[0, 1],
593
+ [2, 3]],
594
+ [[4, 5],
595
+ [6, 7]]])
596
+ >>> np.ma.average(data, axis=(0, 1), weights=[[1./4, 3./4], [1., 1./2]])
597
+ masked_array(data=[3.4, 4.4],
598
+ mask=[False, False],
599
+ fill_value=1e+20)
600
+ >>> np.ma.average(data, axis=0, weights=[[1./4, 3./4], [1., 1./2]])
601
+ Traceback (most recent call last):
602
+ ...
603
+ ValueError: Shape of weights must be consistent
604
+ with shape of a along specified axis.
605
+
606
+ >>> avg, sumweights = np.ma.average(x, axis=0, weights=[1, 2, 3],
607
+ ... returned=True)
608
+ >>> avg
609
+ masked_array(data=[2.6666666666666665, 3.6666666666666665],
610
+ mask=[False, False],
611
+ fill_value=1e+20)
612
+
613
+ With ``keepdims=True``, the following result has shape (3, 1).
614
+
615
+ >>> np.ma.average(x, axis=1, keepdims=True)
616
+ masked_array(
617
+ data=[[0.5],
618
+ [2.5],
619
+ [4.5]],
620
+ mask=False,
621
+ fill_value=1e+20)
622
+ """
623
+ a = asarray(a)
624
+ m = getmask(a)
625
+
626
+ if axis is not None:
627
+ axis = normalize_axis_tuple(axis, a.ndim, argname="axis")
628
+
629
+ if keepdims is np._NoValue:
630
+ # Don't pass on the keepdims argument if one wasn't given.
631
+ keepdims_kw = {}
632
+ else:
633
+ keepdims_kw = {'keepdims': keepdims}
634
+
635
+ if weights is None:
636
+ avg = a.mean(axis, **keepdims_kw)
637
+ scl = avg.dtype.type(a.count(axis))
638
+ else:
639
+ wgt = asarray(weights)
640
+
641
+ if issubclass(a.dtype.type, (np.integer, np.bool)):
642
+ result_dtype = np.result_type(a.dtype, wgt.dtype, 'f8')
643
+ else:
644
+ result_dtype = np.result_type(a.dtype, wgt.dtype)
645
+
646
+ # Sanity checks
647
+ if a.shape != wgt.shape:
648
+ if axis is None:
649
+ raise TypeError(
650
+ "Axis must be specified when shapes of a and weights "
651
+ "differ.")
652
+ if wgt.shape != tuple(a.shape[ax] for ax in axis):
653
+ raise ValueError(
654
+ "Shape of weights must be consistent with "
655
+ "shape of a along specified axis.")
656
+
657
+ # setup wgt to broadcast along axis
658
+ wgt = wgt.transpose(np.argsort(axis))
659
+ wgt = wgt.reshape(tuple((s if ax in axis else 1)
660
+ for ax, s in enumerate(a.shape)))
661
+
662
+ if m is not nomask:
663
+ wgt = wgt * (~a.mask)
664
+ wgt.mask |= a.mask
665
+
666
+ scl = wgt.sum(axis=axis, dtype=result_dtype, **keepdims_kw)
667
+ avg = np.multiply(a, wgt,
668
+ dtype=result_dtype).sum(axis, **keepdims_kw) / scl
669
+
670
+ if returned:
671
+ if scl.shape != avg.shape:
672
+ scl = np.broadcast_to(scl, avg.shape).copy()
673
+ return avg, scl
674
+ else:
675
+ return avg
676
+
677
+
678
+ def median(a, axis=None, out=None, overwrite_input=False, keepdims=False):
679
+ """
680
+ Compute the median along the specified axis.
681
+
682
+ Returns the median of the array elements.
683
+
684
+ Parameters
685
+ ----------
686
+ a : array_like
687
+ Input array or object that can be converted to an array.
688
+ axis : int, optional
689
+ Axis along which the medians are computed. The default (None) is
690
+ to compute the median along a flattened version of the array.
691
+ out : ndarray, optional
692
+ Alternative output array in which to place the result. It must
693
+ have the same shape and buffer length as the expected output
694
+ but the type will be cast if necessary.
695
+ overwrite_input : bool, optional
696
+ If True, then allow use of memory of input array (a) for
697
+ calculations. The input array will be modified by the call to
698
+ median. This will save memory when you do not need to preserve
699
+ the contents of the input array. Treat the input as undefined,
700
+ but it will probably be fully or partially sorted. Default is
701
+ False. Note that, if `overwrite_input` is True, and the input
702
+ is not already an `ndarray`, an error will be raised.
703
+ keepdims : bool, optional
704
+ If this is set to True, the axes which are reduced are left
705
+ in the result as dimensions with size one. With this option,
706
+ the result will broadcast correctly against the input array.
707
+
708
+ Returns
709
+ -------
710
+ median : ndarray
711
+ A new array holding the result is returned unless out is
712
+ specified, in which case a reference to out is returned.
713
+ Return data-type is `float64` for integers and floats smaller than
714
+ `float64`, or the input data-type, otherwise.
715
+
716
+ See Also
717
+ --------
718
+ mean
719
+
720
+ Notes
721
+ -----
722
+ Given a vector ``V`` with ``N`` non masked values, the median of ``V``
723
+ is the middle value of a sorted copy of ``V`` (``Vs``) - i.e.
724
+ ``Vs[(N-1)/2]``, when ``N`` is odd, or ``{Vs[N/2 - 1] + Vs[N/2]}/2``
725
+ when ``N`` is even.
726
+
727
+ Examples
728
+ --------
729
+ >>> import numpy as np
730
+ >>> x = np.ma.array(np.arange(8), mask=[0]*4 + [1]*4)
731
+ >>> np.ma.median(x)
732
+ 1.5
733
+
734
+ >>> x = np.ma.array(np.arange(10).reshape(2, 5), mask=[0]*6 + [1]*4)
735
+ >>> np.ma.median(x)
736
+ 2.5
737
+ >>> np.ma.median(x, axis=-1, overwrite_input=True)
738
+ masked_array(data=[2.0, 5.0],
739
+ mask=[False, False],
740
+ fill_value=1e+20)
741
+
742
+ """
743
+ if not hasattr(a, 'mask'):
744
+ m = np.median(getdata(a, subok=True), axis=axis,
745
+ out=out, overwrite_input=overwrite_input,
746
+ keepdims=keepdims)
747
+ if isinstance(m, np.ndarray) and 1 <= m.ndim:
748
+ return masked_array(m, copy=False)
749
+ else:
750
+ return m
751
+
752
+ return _ureduce(a, func=_median, keepdims=keepdims, axis=axis, out=out,
753
+ overwrite_input=overwrite_input)
754
+
755
+
756
+ def _median(a, axis=None, out=None, overwrite_input=False):
757
+ # when an unmasked NaN is present return it, so we need to sort the NaN
758
+ # values behind the mask
759
+ if np.issubdtype(a.dtype, np.inexact):
760
+ fill_value = np.inf
761
+ else:
762
+ fill_value = None
763
+ if overwrite_input:
764
+ if axis is None:
765
+ asorted = a.ravel()
766
+ asorted.sort(fill_value=fill_value)
767
+ else:
768
+ a.sort(axis=axis, fill_value=fill_value)
769
+ asorted = a
770
+ else:
771
+ asorted = sort(a, axis=axis, fill_value=fill_value)
772
+
773
+ if axis is None:
774
+ axis = 0
775
+ else:
776
+ axis = normalize_axis_index(axis, asorted.ndim)
777
+
778
+ if asorted.shape[axis] == 0:
779
+ # for empty axis integer indices fail so use slicing to get same result
780
+ # as median (which is mean of empty slice = nan)
781
+ indexer = [slice(None)] * asorted.ndim
782
+ indexer[axis] = slice(0, 0)
783
+ indexer = tuple(indexer)
784
+ return np.ma.mean(asorted[indexer], axis=axis, out=out)
785
+
786
+ if asorted.ndim == 1:
787
+ idx, odd = divmod(count(asorted), 2)
788
+ mid = asorted[idx + odd - 1:idx + 1]
789
+ if np.issubdtype(asorted.dtype, np.inexact) and asorted.size > 0:
790
+ # avoid inf / x = masked
791
+ s = mid.sum(out=out)
792
+ if not odd:
793
+ s = np.true_divide(s, 2., casting='safe', out=out)
794
+ s = np.lib._utils_impl._median_nancheck(asorted, s, axis)
795
+ else:
796
+ s = mid.mean(out=out)
797
+
798
+ # if result is masked either the input contained enough
799
+ # minimum_fill_value so that it would be the median or all values
800
+ # masked
801
+ if np.ma.is_masked(s) and not np.all(asorted.mask):
802
+ return np.ma.minimum_fill_value(asorted)
803
+ return s
804
+
805
+ counts = count(asorted, axis=axis, keepdims=True)
806
+ h = counts // 2
807
+
808
+ # duplicate high if odd number of elements so mean does nothing
809
+ odd = counts % 2 == 1
810
+ l = np.where(odd, h, h - 1)
811
+
812
+ lh = np.concatenate([l, h], axis=axis)
813
+
814
+ # get low and high median
815
+ low_high = np.take_along_axis(asorted, lh, axis=axis)
816
+
817
+ def replace_masked(s):
818
+ # Replace masked entries with minimum_full_value unless it all values
819
+ # are masked. This is required as the sort order of values equal or
820
+ # larger than the fill value is undefined and a valid value placed
821
+ # elsewhere, e.g. [4, --, inf].
822
+ if np.ma.is_masked(s):
823
+ rep = (~np.all(asorted.mask, axis=axis, keepdims=True)) & s.mask
824
+ s.data[rep] = np.ma.minimum_fill_value(asorted)
825
+ s.mask[rep] = False
826
+
827
+ replace_masked(low_high)
828
+
829
+ if np.issubdtype(asorted.dtype, np.inexact):
830
+ # avoid inf / x = masked
831
+ s = np.ma.sum(low_high, axis=axis, out=out)
832
+ np.true_divide(s.data, 2., casting='unsafe', out=s.data)
833
+
834
+ s = np.lib._utils_impl._median_nancheck(asorted, s, axis)
835
+ else:
836
+ s = np.ma.mean(low_high, axis=axis, out=out)
837
+
838
+ return s
839
+
840
+
841
+ def compress_nd(x, axis=None):
842
+ """Suppress slices from multiple dimensions which contain masked values.
843
+
844
+ Parameters
845
+ ----------
846
+ x : array_like, MaskedArray
847
+ The array to operate on. If not a MaskedArray instance (or if no array
848
+ elements are masked), `x` is interpreted as a MaskedArray with `mask`
849
+ set to `nomask`.
850
+ axis : tuple of ints or int, optional
851
+ Which dimensions to suppress slices from can be configured with this
852
+ parameter.
853
+ - If axis is a tuple of ints, those are the axes to suppress slices from.
854
+ - If axis is an int, then that is the only axis to suppress slices from.
855
+ - If axis is None, all axis are selected.
856
+
857
+ Returns
858
+ -------
859
+ compress_array : ndarray
860
+ The compressed array.
861
+
862
+ Examples
863
+ --------
864
+ >>> import numpy as np
865
+ >>> arr = [[1, 2], [3, 4]]
866
+ >>> mask = [[0, 1], [0, 0]]
867
+ >>> x = np.ma.array(arr, mask=mask)
868
+ >>> np.ma.compress_nd(x, axis=0)
869
+ array([[3, 4]])
870
+ >>> np.ma.compress_nd(x, axis=1)
871
+ array([[1],
872
+ [3]])
873
+ >>> np.ma.compress_nd(x)
874
+ array([[3]])
875
+
876
+ """
877
+ x = asarray(x)
878
+ m = getmask(x)
879
+ # Set axis to tuple of ints
880
+ if axis is None:
881
+ axis = tuple(range(x.ndim))
882
+ else:
883
+ axis = normalize_axis_tuple(axis, x.ndim)
884
+
885
+ # Nothing is masked: return x
886
+ if m is nomask or not m.any():
887
+ return x._data
888
+ # All is masked: return empty
889
+ if m.all():
890
+ return nxarray([])
891
+ # Filter elements through boolean indexing
892
+ data = x._data
893
+ for ax in axis:
894
+ axes = tuple(list(range(ax)) + list(range(ax + 1, x.ndim)))
895
+ data = data[(slice(None),) * ax + (~m.any(axis=axes),)]
896
+ return data
897
+
898
+
899
+ def compress_rowcols(x, axis=None):
900
+ """
901
+ Suppress the rows and/or columns of a 2-D array that contain
902
+ masked values.
903
+
904
+ The suppression behavior is selected with the `axis` parameter.
905
+
906
+ - If axis is None, both rows and columns are suppressed.
907
+ - If axis is 0, only rows are suppressed.
908
+ - If axis is 1 or -1, only columns are suppressed.
909
+
910
+ Parameters
911
+ ----------
912
+ x : array_like, MaskedArray
913
+ The array to operate on. If not a MaskedArray instance (or if no array
914
+ elements are masked), `x` is interpreted as a MaskedArray with
915
+ `mask` set to `nomask`. Must be a 2D array.
916
+ axis : int, optional
917
+ Axis along which to perform the operation. Default is None.
918
+
919
+ Returns
920
+ -------
921
+ compressed_array : ndarray
922
+ The compressed array.
923
+
924
+ Examples
925
+ --------
926
+ >>> import numpy as np
927
+ >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
928
+ ... [1, 0, 0],
929
+ ... [0, 0, 0]])
930
+ >>> x
931
+ masked_array(
932
+ data=[[--, 1, 2],
933
+ [--, 4, 5],
934
+ [6, 7, 8]],
935
+ mask=[[ True, False, False],
936
+ [ True, False, False],
937
+ [False, False, False]],
938
+ fill_value=999999)
939
+
940
+ >>> np.ma.compress_rowcols(x)
941
+ array([[7, 8]])
942
+ >>> np.ma.compress_rowcols(x, 0)
943
+ array([[6, 7, 8]])
944
+ >>> np.ma.compress_rowcols(x, 1)
945
+ array([[1, 2],
946
+ [4, 5],
947
+ [7, 8]])
948
+
949
+ """
950
+ if asarray(x).ndim != 2:
951
+ raise NotImplementedError("compress_rowcols works for 2D arrays only.")
952
+ return compress_nd(x, axis=axis)
953
+
954
+
955
+ def compress_rows(a):
956
+ """
957
+ Suppress whole rows of a 2-D array that contain masked values.
958
+
959
+ This is equivalent to ``np.ma.compress_rowcols(a, 0)``, see
960
+ `compress_rowcols` for details.
961
+
962
+ Parameters
963
+ ----------
964
+ x : array_like, MaskedArray
965
+ The array to operate on. If not a MaskedArray instance (or if no array
966
+ elements are masked), `x` is interpreted as a MaskedArray with
967
+ `mask` set to `nomask`. Must be a 2D array.
968
+
969
+ Returns
970
+ -------
971
+ compressed_array : ndarray
972
+ The compressed array.
973
+
974
+ See Also
975
+ --------
976
+ compress_rowcols
977
+
978
+ Examples
979
+ --------
980
+ >>> import numpy as np
981
+ >>> a = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
982
+ ... [1, 0, 0],
983
+ ... [0, 0, 0]])
984
+ >>> np.ma.compress_rows(a)
985
+ array([[6, 7, 8]])
986
+
987
+ """
988
+ a = asarray(a)
989
+ if a.ndim != 2:
990
+ raise NotImplementedError("compress_rows works for 2D arrays only.")
991
+ return compress_rowcols(a, 0)
992
+
993
+
994
+ def compress_cols(a):
995
+ """
996
+ Suppress whole columns of a 2-D array that contain masked values.
997
+
998
+ This is equivalent to ``np.ma.compress_rowcols(a, 1)``, see
999
+ `compress_rowcols` for details.
1000
+
1001
+ Parameters
1002
+ ----------
1003
+ x : array_like, MaskedArray
1004
+ The array to operate on. If not a MaskedArray instance (or if no array
1005
+ elements are masked), `x` is interpreted as a MaskedArray with
1006
+ `mask` set to `nomask`. Must be a 2D array.
1007
+
1008
+ Returns
1009
+ -------
1010
+ compressed_array : ndarray
1011
+ The compressed array.
1012
+
1013
+ See Also
1014
+ --------
1015
+ compress_rowcols
1016
+
1017
+ Examples
1018
+ --------
1019
+ >>> import numpy as np
1020
+ >>> a = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
1021
+ ... [1, 0, 0],
1022
+ ... [0, 0, 0]])
1023
+ >>> np.ma.compress_cols(a)
1024
+ array([[1, 2],
1025
+ [4, 5],
1026
+ [7, 8]])
1027
+
1028
+ """
1029
+ a = asarray(a)
1030
+ if a.ndim != 2:
1031
+ raise NotImplementedError("compress_cols works for 2D arrays only.")
1032
+ return compress_rowcols(a, 1)
1033
+
1034
+
1035
+ def mask_rowcols(a, axis=None):
1036
+ """
1037
+ Mask rows and/or columns of a 2D array that contain masked values.
1038
+
1039
+ Mask whole rows and/or columns of a 2D array that contain
1040
+ masked values. The masking behavior is selected using the
1041
+ `axis` parameter.
1042
+
1043
+ - If `axis` is None, rows *and* columns are masked.
1044
+ - If `axis` is 0, only rows are masked.
1045
+ - If `axis` is 1 or -1, only columns are masked.
1046
+
1047
+ Parameters
1048
+ ----------
1049
+ a : array_like, MaskedArray
1050
+ The array to mask. If not a MaskedArray instance (or if no array
1051
+ elements are masked), the result is a MaskedArray with `mask` set
1052
+ to `nomask` (False). Must be a 2D array.
1053
+ axis : int, optional
1054
+ Axis along which to perform the operation. If None, applies to a
1055
+ flattened version of the array.
1056
+
1057
+ Returns
1058
+ -------
1059
+ a : MaskedArray
1060
+ A modified version of the input array, masked depending on the value
1061
+ of the `axis` parameter.
1062
+
1063
+ Raises
1064
+ ------
1065
+ NotImplementedError
1066
+ If input array `a` is not 2D.
1067
+
1068
+ See Also
1069
+ --------
1070
+ mask_rows : Mask rows of a 2D array that contain masked values.
1071
+ mask_cols : Mask cols of a 2D array that contain masked values.
1072
+ masked_where : Mask where a condition is met.
1073
+
1074
+ Notes
1075
+ -----
1076
+ The input array's mask is modified by this function.
1077
+
1078
+ Examples
1079
+ --------
1080
+ >>> import numpy as np
1081
+ >>> a = np.zeros((3, 3), dtype=int)
1082
+ >>> a[1, 1] = 1
1083
+ >>> a
1084
+ array([[0, 0, 0],
1085
+ [0, 1, 0],
1086
+ [0, 0, 0]])
1087
+ >>> a = np.ma.masked_equal(a, 1)
1088
+ >>> a
1089
+ masked_array(
1090
+ data=[[0, 0, 0],
1091
+ [0, --, 0],
1092
+ [0, 0, 0]],
1093
+ mask=[[False, False, False],
1094
+ [False, True, False],
1095
+ [False, False, False]],
1096
+ fill_value=1)
1097
+ >>> np.ma.mask_rowcols(a)
1098
+ masked_array(
1099
+ data=[[0, --, 0],
1100
+ [--, --, --],
1101
+ [0, --, 0]],
1102
+ mask=[[False, True, False],
1103
+ [ True, True, True],
1104
+ [False, True, False]],
1105
+ fill_value=1)
1106
+
1107
+ """
1108
+ a = array(a, subok=False)
1109
+ if a.ndim != 2:
1110
+ raise NotImplementedError("mask_rowcols works for 2D arrays only.")
1111
+ m = getmask(a)
1112
+ # Nothing is masked: return a
1113
+ if m is nomask or not m.any():
1114
+ return a
1115
+ maskedval = m.nonzero()
1116
+ a._mask = a._mask.copy()
1117
+ if not axis:
1118
+ a[np.unique(maskedval[0])] = masked
1119
+ if axis in [None, 1, -1]:
1120
+ a[:, np.unique(maskedval[1])] = masked
1121
+ return a
1122
+
1123
+
1124
+ def mask_rows(a, axis=np._NoValue):
1125
+ """
1126
+ Mask rows of a 2D array that contain masked values.
1127
+
1128
+ This function is a shortcut to ``mask_rowcols`` with `axis` equal to 0.
1129
+
1130
+ See Also
1131
+ --------
1132
+ mask_rowcols : Mask rows and/or columns of a 2D array.
1133
+ masked_where : Mask where a condition is met.
1134
+
1135
+ Examples
1136
+ --------
1137
+ >>> import numpy as np
1138
+ >>> a = np.zeros((3, 3), dtype=int)
1139
+ >>> a[1, 1] = 1
1140
+ >>> a
1141
+ array([[0, 0, 0],
1142
+ [0, 1, 0],
1143
+ [0, 0, 0]])
1144
+ >>> a = np.ma.masked_equal(a, 1)
1145
+ >>> a
1146
+ masked_array(
1147
+ data=[[0, 0, 0],
1148
+ [0, --, 0],
1149
+ [0, 0, 0]],
1150
+ mask=[[False, False, False],
1151
+ [False, True, False],
1152
+ [False, False, False]],
1153
+ fill_value=1)
1154
+
1155
+ >>> np.ma.mask_rows(a)
1156
+ masked_array(
1157
+ data=[[0, 0, 0],
1158
+ [--, --, --],
1159
+ [0, 0, 0]],
1160
+ mask=[[False, False, False],
1161
+ [ True, True, True],
1162
+ [False, False, False]],
1163
+ fill_value=1)
1164
+
1165
+ """
1166
+ if axis is not np._NoValue:
1167
+ # remove the axis argument when this deprecation expires
1168
+ # NumPy 1.18.0, 2019-11-28
1169
+ warnings.warn(
1170
+ "The axis argument has always been ignored, in future passing it "
1171
+ "will raise TypeError", DeprecationWarning, stacklevel=2)
1172
+ return mask_rowcols(a, 0)
1173
+
1174
+
1175
+ def mask_cols(a, axis=np._NoValue):
1176
+ """
1177
+ Mask columns of a 2D array that contain masked values.
1178
+
1179
+ This function is a shortcut to ``mask_rowcols`` with `axis` equal to 1.
1180
+
1181
+ See Also
1182
+ --------
1183
+ mask_rowcols : Mask rows and/or columns of a 2D array.
1184
+ masked_where : Mask where a condition is met.
1185
+
1186
+ Examples
1187
+ --------
1188
+ >>> import numpy as np
1189
+ >>> a = np.zeros((3, 3), dtype=int)
1190
+ >>> a[1, 1] = 1
1191
+ >>> a
1192
+ array([[0, 0, 0],
1193
+ [0, 1, 0],
1194
+ [0, 0, 0]])
1195
+ >>> a = np.ma.masked_equal(a, 1)
1196
+ >>> a
1197
+ masked_array(
1198
+ data=[[0, 0, 0],
1199
+ [0, --, 0],
1200
+ [0, 0, 0]],
1201
+ mask=[[False, False, False],
1202
+ [False, True, False],
1203
+ [False, False, False]],
1204
+ fill_value=1)
1205
+ >>> np.ma.mask_cols(a)
1206
+ masked_array(
1207
+ data=[[0, --, 0],
1208
+ [0, --, 0],
1209
+ [0, --, 0]],
1210
+ mask=[[False, True, False],
1211
+ [False, True, False],
1212
+ [False, True, False]],
1213
+ fill_value=1)
1214
+
1215
+ """
1216
+ if axis is not np._NoValue:
1217
+ # remove the axis argument when this deprecation expires
1218
+ # NumPy 1.18.0, 2019-11-28
1219
+ warnings.warn(
1220
+ "The axis argument has always been ignored, in future passing it "
1221
+ "will raise TypeError", DeprecationWarning, stacklevel=2)
1222
+ return mask_rowcols(a, 1)
1223
+
1224
+
1225
+ #####--------------------------------------------------------------------------
1226
+ #---- --- arraysetops ---
1227
+ #####--------------------------------------------------------------------------
1228
+
1229
+ def ediff1d(arr, to_end=None, to_begin=None):
1230
+ """
1231
+ Compute the differences between consecutive elements of an array.
1232
+
1233
+ This function is the equivalent of `numpy.ediff1d` that takes masked
1234
+ values into account, see `numpy.ediff1d` for details.
1235
+
1236
+ See Also
1237
+ --------
1238
+ numpy.ediff1d : Equivalent function for ndarrays.
1239
+
1240
+ Examples
1241
+ --------
1242
+ >>> import numpy as np
1243
+ >>> arr = np.ma.array([1, 2, 4, 7, 0])
1244
+ >>> np.ma.ediff1d(arr)
1245
+ masked_array(data=[ 1, 2, 3, -7],
1246
+ mask=False,
1247
+ fill_value=999999)
1248
+
1249
+ """
1250
+ arr = ma.asanyarray(arr).flat
1251
+ ed = arr[1:] - arr[:-1]
1252
+ arrays = [ed]
1253
+ #
1254
+ if to_begin is not None:
1255
+ arrays.insert(0, to_begin)
1256
+ if to_end is not None:
1257
+ arrays.append(to_end)
1258
+ #
1259
+ if len(arrays) != 1:
1260
+ # We'll save ourselves a copy of a potentially large array in the common
1261
+ # case where neither to_begin or to_end was given.
1262
+ ed = hstack(arrays)
1263
+ #
1264
+ return ed
1265
+
1266
+
1267
+ def unique(ar1, return_index=False, return_inverse=False):
1268
+ """
1269
+ Finds the unique elements of an array.
1270
+
1271
+ Masked values are considered the same element (masked). The output array
1272
+ is always a masked array. See `numpy.unique` for more details.
1273
+
1274
+ See Also
1275
+ --------
1276
+ numpy.unique : Equivalent function for ndarrays.
1277
+
1278
+ Examples
1279
+ --------
1280
+ >>> import numpy as np
1281
+ >>> a = [1, 2, 1000, 2, 3]
1282
+ >>> mask = [0, 0, 1, 0, 0]
1283
+ >>> masked_a = np.ma.masked_array(a, mask)
1284
+ >>> masked_a
1285
+ masked_array(data=[1, 2, --, 2, 3],
1286
+ mask=[False, False, True, False, False],
1287
+ fill_value=999999)
1288
+ >>> np.ma.unique(masked_a)
1289
+ masked_array(data=[1, 2, 3, --],
1290
+ mask=[False, False, False, True],
1291
+ fill_value=999999)
1292
+ >>> np.ma.unique(masked_a, return_index=True)
1293
+ (masked_array(data=[1, 2, 3, --],
1294
+ mask=[False, False, False, True],
1295
+ fill_value=999999), array([0, 1, 4, 2]))
1296
+ >>> np.ma.unique(masked_a, return_inverse=True)
1297
+ (masked_array(data=[1, 2, 3, --],
1298
+ mask=[False, False, False, True],
1299
+ fill_value=999999), array([0, 1, 3, 1, 2]))
1300
+ >>> np.ma.unique(masked_a, return_index=True, return_inverse=True)
1301
+ (masked_array(data=[1, 2, 3, --],
1302
+ mask=[False, False, False, True],
1303
+ fill_value=999999), array([0, 1, 4, 2]), array([0, 1, 3, 1, 2]))
1304
+ """
1305
+ output = np.unique(ar1,
1306
+ return_index=return_index,
1307
+ return_inverse=return_inverse)
1308
+ if isinstance(output, tuple):
1309
+ output = list(output)
1310
+ output[0] = output[0].view(MaskedArray)
1311
+ output = tuple(output)
1312
+ else:
1313
+ output = output.view(MaskedArray)
1314
+ return output
1315
+
1316
+
1317
+ def intersect1d(ar1, ar2, assume_unique=False):
1318
+ """
1319
+ Returns the unique elements common to both arrays.
1320
+
1321
+ Masked values are considered equal one to the other.
1322
+ The output is always a masked array.
1323
+
1324
+ See `numpy.intersect1d` for more details.
1325
+
1326
+ See Also
1327
+ --------
1328
+ numpy.intersect1d : Equivalent function for ndarrays.
1329
+
1330
+ Examples
1331
+ --------
1332
+ >>> import numpy as np
1333
+ >>> x = np.ma.array([1, 3, 3, 3], mask=[0, 0, 0, 1])
1334
+ >>> y = np.ma.array([3, 1, 1, 1], mask=[0, 0, 0, 1])
1335
+ >>> np.ma.intersect1d(x, y)
1336
+ masked_array(data=[1, 3, --],
1337
+ mask=[False, False, True],
1338
+ fill_value=999999)
1339
+
1340
+ """
1341
+ if assume_unique:
1342
+ aux = ma.concatenate((ar1, ar2))
1343
+ else:
1344
+ # Might be faster than unique( intersect1d( ar1, ar2 ) )?
1345
+ aux = ma.concatenate((unique(ar1), unique(ar2)))
1346
+ aux.sort()
1347
+ return aux[:-1][aux[1:] == aux[:-1]]
1348
+
1349
+
1350
+ def setxor1d(ar1, ar2, assume_unique=False):
1351
+ """
1352
+ Set exclusive-or of 1-D arrays with unique elements.
1353
+
1354
+ The output is always a masked array. See `numpy.setxor1d` for more details.
1355
+
1356
+ See Also
1357
+ --------
1358
+ numpy.setxor1d : Equivalent function for ndarrays.
1359
+
1360
+ Examples
1361
+ --------
1362
+ >>> import numpy as np
1363
+ >>> ar1 = np.ma.array([1, 2, 3, 2, 4])
1364
+ >>> ar2 = np.ma.array([2, 3, 5, 7, 5])
1365
+ >>> np.ma.setxor1d(ar1, ar2)
1366
+ masked_array(data=[1, 4, 5, 7],
1367
+ mask=False,
1368
+ fill_value=999999)
1369
+
1370
+ """
1371
+ if not assume_unique:
1372
+ ar1 = unique(ar1)
1373
+ ar2 = unique(ar2)
1374
+
1375
+ aux = ma.concatenate((ar1, ar2), axis=None)
1376
+ if aux.size == 0:
1377
+ return aux
1378
+ aux.sort()
1379
+ auxf = aux.filled()
1380
+ # flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0
1381
+ flag = ma.concatenate(([True], (auxf[1:] != auxf[:-1]), [True]))
1382
+ # flag2 = ediff1d( flag ) == 0
1383
+ flag2 = (flag[1:] == flag[:-1])
1384
+ return aux[flag2]
1385
+
1386
+
1387
+ def in1d(ar1, ar2, assume_unique=False, invert=False):
1388
+ """
1389
+ Test whether each element of an array is also present in a second
1390
+ array.
1391
+
1392
+ The output is always a masked array.
1393
+
1394
+ We recommend using :func:`isin` instead of `in1d` for new code.
1395
+
1396
+ See Also
1397
+ --------
1398
+ isin : Version of this function that preserves the shape of ar1.
1399
+
1400
+ Examples
1401
+ --------
1402
+ >>> import numpy as np
1403
+ >>> ar1 = np.ma.array([0, 1, 2, 5, 0])
1404
+ >>> ar2 = [0, 2]
1405
+ >>> np.ma.in1d(ar1, ar2)
1406
+ masked_array(data=[ True, False, True, False, True],
1407
+ mask=False,
1408
+ fill_value=True)
1409
+
1410
+ """
1411
+ if not assume_unique:
1412
+ ar1, rev_idx = unique(ar1, return_inverse=True)
1413
+ ar2 = unique(ar2)
1414
+
1415
+ ar = ma.concatenate((ar1, ar2))
1416
+ # We need this to be a stable sort, so always use 'mergesort'
1417
+ # here. The values from the first array should always come before
1418
+ # the values from the second array.
1419
+ order = ar.argsort(kind='mergesort')
1420
+ sar = ar[order]
1421
+ if invert:
1422
+ bool_ar = (sar[1:] != sar[:-1])
1423
+ else:
1424
+ bool_ar = (sar[1:] == sar[:-1])
1425
+ flag = ma.concatenate((bool_ar, [invert]))
1426
+ indx = order.argsort(kind='mergesort')[:len(ar1)]
1427
+
1428
+ if assume_unique:
1429
+ return flag[indx]
1430
+ else:
1431
+ return flag[indx][rev_idx]
1432
+
1433
+
1434
+ def isin(element, test_elements, assume_unique=False, invert=False):
1435
+ """
1436
+ Calculates `element in test_elements`, broadcasting over
1437
+ `element` only.
1438
+
1439
+ The output is always a masked array of the same shape as `element`.
1440
+ See `numpy.isin` for more details.
1441
+
1442
+ See Also
1443
+ --------
1444
+ in1d : Flattened version of this function.
1445
+ numpy.isin : Equivalent function for ndarrays.
1446
+
1447
+ Examples
1448
+ --------
1449
+ >>> import numpy as np
1450
+ >>> element = np.ma.array([1, 2, 3, 4, 5, 6])
1451
+ >>> test_elements = [0, 2]
1452
+ >>> np.ma.isin(element, test_elements)
1453
+ masked_array(data=[False, True, False, False, False, False],
1454
+ mask=False,
1455
+ fill_value=True)
1456
+
1457
+ """
1458
+ element = ma.asarray(element)
1459
+ return in1d(element, test_elements, assume_unique=assume_unique,
1460
+ invert=invert).reshape(element.shape)
1461
+
1462
+
1463
+ def union1d(ar1, ar2):
1464
+ """
1465
+ Union of two arrays.
1466
+
1467
+ The output is always a masked array. See `numpy.union1d` for more details.
1468
+
1469
+ See Also
1470
+ --------
1471
+ numpy.union1d : Equivalent function for ndarrays.
1472
+
1473
+ Examples
1474
+ --------
1475
+ >>> import numpy as np
1476
+ >>> ar1 = np.ma.array([1, 2, 3, 4])
1477
+ >>> ar2 = np.ma.array([3, 4, 5, 6])
1478
+ >>> np.ma.union1d(ar1, ar2)
1479
+ masked_array(data=[1, 2, 3, 4, 5, 6],
1480
+ mask=False,
1481
+ fill_value=999999)
1482
+
1483
+ """
1484
+ return unique(ma.concatenate((ar1, ar2), axis=None))
1485
+
1486
+
1487
+ def setdiff1d(ar1, ar2, assume_unique=False):
1488
+ """
1489
+ Set difference of 1D arrays with unique elements.
1490
+
1491
+ The output is always a masked array. See `numpy.setdiff1d` for more
1492
+ details.
1493
+
1494
+ See Also
1495
+ --------
1496
+ numpy.setdiff1d : Equivalent function for ndarrays.
1497
+
1498
+ Examples
1499
+ --------
1500
+ >>> import numpy as np
1501
+ >>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1])
1502
+ >>> np.ma.setdiff1d(x, [1, 2])
1503
+ masked_array(data=[3, --],
1504
+ mask=[False, True],
1505
+ fill_value=999999)
1506
+
1507
+ """
1508
+ if assume_unique:
1509
+ ar1 = ma.asarray(ar1).ravel()
1510
+ else:
1511
+ ar1 = unique(ar1)
1512
+ ar2 = unique(ar2)
1513
+ return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)]
1514
+
1515
+
1516
+ ###############################################################################
1517
+ # Covariance #
1518
+ ###############################################################################
1519
+
1520
+
1521
+ def _covhelper(x, y=None, rowvar=True, allow_masked=True):
1522
+ """
1523
+ Private function for the computation of covariance and correlation
1524
+ coefficients.
1525
+
1526
+ """
1527
+ x = ma.array(x, ndmin=2, copy=True, dtype=float)
1528
+ xmask = ma.getmaskarray(x)
1529
+ # Quick exit if we can't process masked data
1530
+ if not allow_masked and xmask.any():
1531
+ raise ValueError("Cannot process masked data.")
1532
+ #
1533
+ if x.shape[0] == 1:
1534
+ rowvar = True
1535
+ # Make sure that rowvar is either 0 or 1
1536
+ rowvar = int(bool(rowvar))
1537
+ axis = 1 - rowvar
1538
+ if rowvar:
1539
+ tup = (slice(None), None)
1540
+ else:
1541
+ tup = (None, slice(None))
1542
+ #
1543
+ if y is None:
1544
+ # Check if we can guarantee that the integers in the (N - ddof)
1545
+ # normalisation can be accurately represented with single-precision
1546
+ # before computing the dot product.
1547
+ if x.shape[0] > 2 ** 24 or x.shape[1] > 2 ** 24:
1548
+ xnm_dtype = np.float64
1549
+ else:
1550
+ xnm_dtype = np.float32
1551
+ xnotmask = np.logical_not(xmask).astype(xnm_dtype)
1552
+ else:
1553
+ y = array(y, copy=False, ndmin=2, dtype=float)
1554
+ ymask = ma.getmaskarray(y)
1555
+ if not allow_masked and ymask.any():
1556
+ raise ValueError("Cannot process masked data.")
1557
+ if xmask.any() or ymask.any():
1558
+ if y.shape == x.shape:
1559
+ # Define some common mask
1560
+ common_mask = np.logical_or(xmask, ymask)
1561
+ if common_mask is not nomask:
1562
+ xmask = x._mask = y._mask = ymask = common_mask
1563
+ x._sharedmask = False
1564
+ y._sharedmask = False
1565
+ x = ma.concatenate((x, y), axis)
1566
+ # Check if we can guarantee that the integers in the (N - ddof)
1567
+ # normalisation can be accurately represented with single-precision
1568
+ # before computing the dot product.
1569
+ if x.shape[0] > 2 ** 24 or x.shape[1] > 2 ** 24:
1570
+ xnm_dtype = np.float64
1571
+ else:
1572
+ xnm_dtype = np.float32
1573
+ xnotmask = np.logical_not(np.concatenate((xmask, ymask), axis)).astype(
1574
+ xnm_dtype
1575
+ )
1576
+ x -= x.mean(axis=rowvar)[tup]
1577
+ return (x, xnotmask, rowvar)
1578
+
1579
+
1580
+ def cov(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None):
1581
+ """
1582
+ Estimate the covariance matrix.
1583
+
1584
+ Except for the handling of missing data this function does the same as
1585
+ `numpy.cov`. For more details and examples, see `numpy.cov`.
1586
+
1587
+ By default, masked values are recognized as such. If `x` and `y` have the
1588
+ same shape, a common mask is allocated: if ``x[i,j]`` is masked, then
1589
+ ``y[i,j]`` will also be masked.
1590
+ Setting `allow_masked` to False will raise an exception if values are
1591
+ missing in either of the input arrays.
1592
+
1593
+ Parameters
1594
+ ----------
1595
+ x : array_like
1596
+ A 1-D or 2-D array containing multiple variables and observations.
1597
+ Each row of `x` represents a variable, and each column a single
1598
+ observation of all those variables. Also see `rowvar` below.
1599
+ y : array_like, optional
1600
+ An additional set of variables and observations. `y` has the same
1601
+ shape as `x`.
1602
+ rowvar : bool, optional
1603
+ If `rowvar` is True (default), then each row represents a
1604
+ variable, with observations in the columns. Otherwise, the relationship
1605
+ is transposed: each column represents a variable, while the rows
1606
+ contain observations.
1607
+ bias : bool, optional
1608
+ Default normalization (False) is by ``(N-1)``, where ``N`` is the
1609
+ number of observations given (unbiased estimate). If `bias` is True,
1610
+ then normalization is by ``N``. This keyword can be overridden by
1611
+ the keyword ``ddof`` in numpy versions >= 1.5.
1612
+ allow_masked : bool, optional
1613
+ If True, masked values are propagated pair-wise: if a value is masked
1614
+ in `x`, the corresponding value is masked in `y`.
1615
+ If False, raises a `ValueError` exception when some values are missing.
1616
+ ddof : {None, int}, optional
1617
+ If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is
1618
+ the number of observations; this overrides the value implied by
1619
+ ``bias``. The default value is ``None``.
1620
+
1621
+ Raises
1622
+ ------
1623
+ ValueError
1624
+ Raised if some values are missing and `allow_masked` is False.
1625
+
1626
+ See Also
1627
+ --------
1628
+ numpy.cov
1629
+
1630
+ Examples
1631
+ --------
1632
+ >>> import numpy as np
1633
+ >>> x = np.ma.array([[0, 1], [1, 1]], mask=[0, 1, 0, 1])
1634
+ >>> y = np.ma.array([[1, 0], [0, 1]], mask=[0, 0, 1, 1])
1635
+ >>> np.ma.cov(x, y)
1636
+ masked_array(
1637
+ data=[[--, --, --, --],
1638
+ [--, --, --, --],
1639
+ [--, --, --, --],
1640
+ [--, --, --, --]],
1641
+ mask=[[ True, True, True, True],
1642
+ [ True, True, True, True],
1643
+ [ True, True, True, True],
1644
+ [ True, True, True, True]],
1645
+ fill_value=1e+20,
1646
+ dtype=float64)
1647
+
1648
+ """
1649
+ # Check inputs
1650
+ if ddof is not None and ddof != int(ddof):
1651
+ raise ValueError("ddof must be an integer")
1652
+ # Set up ddof
1653
+ if ddof is None:
1654
+ if bias:
1655
+ ddof = 0
1656
+ else:
1657
+ ddof = 1
1658
+
1659
+ (x, xnotmask, rowvar) = _covhelper(x, y, rowvar, allow_masked)
1660
+ if not rowvar:
1661
+ fact = np.dot(xnotmask.T, xnotmask) - ddof
1662
+ mask = np.less_equal(fact, 0, dtype=bool)
1663
+ with np.errstate(divide="ignore", invalid="ignore"):
1664
+ data = np.dot(filled(x.T, 0), filled(x.conj(), 0)) / fact
1665
+ result = ma.array(data, mask=mask).squeeze()
1666
+ else:
1667
+ fact = np.dot(xnotmask, xnotmask.T) - ddof
1668
+ mask = np.less_equal(fact, 0, dtype=bool)
1669
+ with np.errstate(divide="ignore", invalid="ignore"):
1670
+ data = np.dot(filled(x, 0), filled(x.T.conj(), 0)) / fact
1671
+ result = ma.array(data, mask=mask).squeeze()
1672
+ return result
1673
+
1674
+
1675
+ def corrcoef(x, y=None, rowvar=True, allow_masked=True,
1676
+ ):
1677
+ """
1678
+ Return Pearson product-moment correlation coefficients.
1679
+
1680
+ Except for the handling of missing data this function does the same as
1681
+ `numpy.corrcoef`. For more details and examples, see `numpy.corrcoef`.
1682
+
1683
+ Parameters
1684
+ ----------
1685
+ x : array_like
1686
+ A 1-D or 2-D array containing multiple variables and observations.
1687
+ Each row of `x` represents a variable, and each column a single
1688
+ observation of all those variables. Also see `rowvar` below.
1689
+ y : array_like, optional
1690
+ An additional set of variables and observations. `y` has the same
1691
+ shape as `x`.
1692
+ rowvar : bool, optional
1693
+ If `rowvar` is True (default), then each row represents a
1694
+ variable, with observations in the columns. Otherwise, the relationship
1695
+ is transposed: each column represents a variable, while the rows
1696
+ contain observations.
1697
+ allow_masked : bool, optional
1698
+ If True, masked values are propagated pair-wise: if a value is masked
1699
+ in `x`, the corresponding value is masked in `y`.
1700
+ If False, raises an exception. Because `bias` is deprecated, this
1701
+ argument needs to be treated as keyword only to avoid a warning.
1702
+
1703
+ See Also
1704
+ --------
1705
+ numpy.corrcoef : Equivalent function in top-level NumPy module.
1706
+ cov : Estimate the covariance matrix.
1707
+
1708
+ Examples
1709
+ --------
1710
+ >>> import numpy as np
1711
+ >>> x = np.ma.array([[0, 1], [1, 1]], mask=[0, 1, 0, 1])
1712
+ >>> np.ma.corrcoef(x)
1713
+ masked_array(
1714
+ data=[[--, --],
1715
+ [--, --]],
1716
+ mask=[[ True, True],
1717
+ [ True, True]],
1718
+ fill_value=1e+20,
1719
+ dtype=float64)
1720
+
1721
+ """
1722
+ # Estimate the covariance matrix.
1723
+ corr = cov(x, y, rowvar, allow_masked=allow_masked)
1724
+ # The non-masked version returns a masked value for a scalar.
1725
+ try:
1726
+ std = ma.sqrt(ma.diagonal(corr))
1727
+ except ValueError:
1728
+ return ma.MaskedConstant()
1729
+ corr /= ma.multiply.outer(std, std)
1730
+ return corr
1731
+
1732
+ #####--------------------------------------------------------------------------
1733
+ #---- --- Concatenation helpers ---
1734
+ #####--------------------------------------------------------------------------
1735
+
1736
+ class MAxisConcatenator(AxisConcatenator):
1737
+ """
1738
+ Translate slice objects to concatenation along an axis.
1739
+
1740
+ For documentation on usage, see `mr_class`.
1741
+
1742
+ See Also
1743
+ --------
1744
+ mr_class
1745
+
1746
+ """
1747
+ __slots__ = ()
1748
+
1749
+ concatenate = staticmethod(concatenate)
1750
+
1751
+ @classmethod
1752
+ def makemat(cls, arr):
1753
+ # There used to be a view as np.matrix here, but we may eventually
1754
+ # deprecate that class. In preparation, we use the unmasked version
1755
+ # to construct the matrix (with copy=False for backwards compatibility
1756
+ # with the .view)
1757
+ data = super().makemat(arr.data, copy=False)
1758
+ return array(data, mask=arr.mask)
1759
+
1760
+ def __getitem__(self, key):
1761
+ # matrix builder syntax, like 'a, b; c, d'
1762
+ if isinstance(key, str):
1763
+ raise MAError("Unavailable for masked array.")
1764
+
1765
+ return super().__getitem__(key)
1766
+
1767
+
1768
+ class mr_class(MAxisConcatenator):
1769
+ """
1770
+ Translate slice objects to concatenation along the first axis.
1771
+
1772
+ This is the masked array version of `r_`.
1773
+
1774
+ See Also
1775
+ --------
1776
+ r_
1777
+
1778
+ Examples
1779
+ --------
1780
+ >>> import numpy as np
1781
+ >>> np.ma.mr_[np.ma.array([1,2,3]), 0, 0, np.ma.array([4,5,6])]
1782
+ masked_array(data=[1, 2, 3, ..., 4, 5, 6],
1783
+ mask=False,
1784
+ fill_value=999999)
1785
+
1786
+ """
1787
+ __slots__ = ()
1788
+
1789
+ def __init__(self):
1790
+ MAxisConcatenator.__init__(self, 0)
1791
+
1792
+
1793
+ mr_ = mr_class()
1794
+
1795
+
1796
+ #####--------------------------------------------------------------------------
1797
+ #---- Find unmasked data ---
1798
+ #####--------------------------------------------------------------------------
1799
+
1800
+ def ndenumerate(a, compressed=True):
1801
+ """
1802
+ Multidimensional index iterator.
1803
+
1804
+ Return an iterator yielding pairs of array coordinates and values,
1805
+ skipping elements that are masked. With `compressed=False`,
1806
+ `ma.masked` is yielded as the value of masked elements. This
1807
+ behavior differs from that of `numpy.ndenumerate`, which yields the
1808
+ value of the underlying data array.
1809
+
1810
+ Notes
1811
+ -----
1812
+ .. versionadded:: 1.23.0
1813
+
1814
+ Parameters
1815
+ ----------
1816
+ a : array_like
1817
+ An array with (possibly) masked elements.
1818
+ compressed : bool, optional
1819
+ If True (default), masked elements are skipped.
1820
+
1821
+ See Also
1822
+ --------
1823
+ numpy.ndenumerate : Equivalent function ignoring any mask.
1824
+
1825
+ Examples
1826
+ --------
1827
+ >>> import numpy as np
1828
+ >>> a = np.ma.arange(9).reshape((3, 3))
1829
+ >>> a[1, 0] = np.ma.masked
1830
+ >>> a[1, 2] = np.ma.masked
1831
+ >>> a[2, 1] = np.ma.masked
1832
+ >>> a
1833
+ masked_array(
1834
+ data=[[0, 1, 2],
1835
+ [--, 4, --],
1836
+ [6, --, 8]],
1837
+ mask=[[False, False, False],
1838
+ [ True, False, True],
1839
+ [False, True, False]],
1840
+ fill_value=999999)
1841
+ >>> for index, x in np.ma.ndenumerate(a):
1842
+ ... print(index, x)
1843
+ (0, 0) 0
1844
+ (0, 1) 1
1845
+ (0, 2) 2
1846
+ (1, 1) 4
1847
+ (2, 0) 6
1848
+ (2, 2) 8
1849
+
1850
+ >>> for index, x in np.ma.ndenumerate(a, compressed=False):
1851
+ ... print(index, x)
1852
+ (0, 0) 0
1853
+ (0, 1) 1
1854
+ (0, 2) 2
1855
+ (1, 0) --
1856
+ (1, 1) 4
1857
+ (1, 2) --
1858
+ (2, 0) 6
1859
+ (2, 1) --
1860
+ (2, 2) 8
1861
+ """
1862
+ for it, mask in zip(np.ndenumerate(a), getmaskarray(a).flat):
1863
+ if not mask:
1864
+ yield it
1865
+ elif not compressed:
1866
+ yield it[0], masked
1867
+
1868
+
1869
+ def flatnotmasked_edges(a):
1870
+ """
1871
+ Find the indices of the first and last unmasked values.
1872
+
1873
+ Expects a 1-D `MaskedArray`, returns None if all values are masked.
1874
+
1875
+ Parameters
1876
+ ----------
1877
+ a : array_like
1878
+ Input 1-D `MaskedArray`
1879
+
1880
+ Returns
1881
+ -------
1882
+ edges : ndarray or None
1883
+ The indices of first and last non-masked value in the array.
1884
+ Returns None if all values are masked.
1885
+
1886
+ See Also
1887
+ --------
1888
+ flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges
1889
+ clump_masked, clump_unmasked
1890
+
1891
+ Notes
1892
+ -----
1893
+ Only accepts 1-D arrays.
1894
+
1895
+ Examples
1896
+ --------
1897
+ >>> import numpy as np
1898
+ >>> a = np.ma.arange(10)
1899
+ >>> np.ma.flatnotmasked_edges(a)
1900
+ array([0, 9])
1901
+
1902
+ >>> mask = (a < 3) | (a > 8) | (a == 5)
1903
+ >>> a[mask] = np.ma.masked
1904
+ >>> np.array(a[~a.mask])
1905
+ array([3, 4, 6, 7, 8])
1906
+
1907
+ >>> np.ma.flatnotmasked_edges(a)
1908
+ array([3, 8])
1909
+
1910
+ >>> a[:] = np.ma.masked
1911
+ >>> print(np.ma.flatnotmasked_edges(a))
1912
+ None
1913
+
1914
+ """
1915
+ m = getmask(a)
1916
+ if m is nomask or not np.any(m):
1917
+ return np.array([0, a.size - 1])
1918
+ unmasked = np.flatnonzero(~m)
1919
+ if len(unmasked) > 0:
1920
+ return unmasked[[0, -1]]
1921
+ else:
1922
+ return None
1923
+
1924
+
1925
+ def notmasked_edges(a, axis=None):
1926
+ """
1927
+ Find the indices of the first and last unmasked values along an axis.
1928
+
1929
+ If all values are masked, return None. Otherwise, return a list
1930
+ of two tuples, corresponding to the indices of the first and last
1931
+ unmasked values respectively.
1932
+
1933
+ Parameters
1934
+ ----------
1935
+ a : array_like
1936
+ The input array.
1937
+ axis : int, optional
1938
+ Axis along which to perform the operation.
1939
+ If None (default), applies to a flattened version of the array.
1940
+
1941
+ Returns
1942
+ -------
1943
+ edges : ndarray or list
1944
+ An array of start and end indexes if there are any masked data in
1945
+ the array. If there are no masked data in the array, `edges` is a
1946
+ list of the first and last index.
1947
+
1948
+ See Also
1949
+ --------
1950
+ flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous
1951
+ clump_masked, clump_unmasked
1952
+
1953
+ Examples
1954
+ --------
1955
+ >>> import numpy as np
1956
+ >>> a = np.arange(9).reshape((3, 3))
1957
+ >>> m = np.zeros_like(a)
1958
+ >>> m[1:, 1:] = 1
1959
+
1960
+ >>> am = np.ma.array(a, mask=m)
1961
+ >>> np.array(am[~am.mask])
1962
+ array([0, 1, 2, 3, 6])
1963
+
1964
+ >>> np.ma.notmasked_edges(am)
1965
+ array([0, 6])
1966
+
1967
+ """
1968
+ a = asarray(a)
1969
+ if axis is None or a.ndim == 1:
1970
+ return flatnotmasked_edges(a)
1971
+ m = getmaskarray(a)
1972
+ idx = array(np.indices(a.shape), mask=np.asarray([m] * a.ndim))
1973
+ return [tuple(idx[i].min(axis).compressed() for i in range(a.ndim)),
1974
+ tuple(idx[i].max(axis).compressed() for i in range(a.ndim)), ]
1975
+
1976
+
1977
+ def flatnotmasked_contiguous(a):
1978
+ """
1979
+ Find contiguous unmasked data in a masked array.
1980
+
1981
+ Parameters
1982
+ ----------
1983
+ a : array_like
1984
+ The input array.
1985
+
1986
+ Returns
1987
+ -------
1988
+ slice_list : list
1989
+ A sorted sequence of `slice` objects (start index, end index).
1990
+
1991
+ See Also
1992
+ --------
1993
+ flatnotmasked_edges, notmasked_contiguous, notmasked_edges
1994
+ clump_masked, clump_unmasked
1995
+
1996
+ Notes
1997
+ -----
1998
+ Only accepts 2-D arrays at most.
1999
+
2000
+ Examples
2001
+ --------
2002
+ >>> import numpy as np
2003
+ >>> a = np.ma.arange(10)
2004
+ >>> np.ma.flatnotmasked_contiguous(a)
2005
+ [slice(0, 10, None)]
2006
+
2007
+ >>> mask = (a < 3) | (a > 8) | (a == 5)
2008
+ >>> a[mask] = np.ma.masked
2009
+ >>> np.array(a[~a.mask])
2010
+ array([3, 4, 6, 7, 8])
2011
+
2012
+ >>> np.ma.flatnotmasked_contiguous(a)
2013
+ [slice(3, 5, None), slice(6, 9, None)]
2014
+ >>> a[:] = np.ma.masked
2015
+ >>> np.ma.flatnotmasked_contiguous(a)
2016
+ []
2017
+
2018
+ """
2019
+ m = getmask(a)
2020
+ if m is nomask:
2021
+ return [slice(0, a.size)]
2022
+ i = 0
2023
+ result = []
2024
+ for (k, g) in itertools.groupby(m.ravel()):
2025
+ n = len(list(g))
2026
+ if not k:
2027
+ result.append(slice(i, i + n))
2028
+ i += n
2029
+ return result
2030
+
2031
+
2032
+ def notmasked_contiguous(a, axis=None):
2033
+ """
2034
+ Find contiguous unmasked data in a masked array along the given axis.
2035
+
2036
+ Parameters
2037
+ ----------
2038
+ a : array_like
2039
+ The input array.
2040
+ axis : int, optional
2041
+ Axis along which to perform the operation.
2042
+ If None (default), applies to a flattened version of the array, and this
2043
+ is the same as `flatnotmasked_contiguous`.
2044
+
2045
+ Returns
2046
+ -------
2047
+ endpoints : list
2048
+ A list of slices (start and end indexes) of unmasked indexes
2049
+ in the array.
2050
+
2051
+ If the input is 2d and axis is specified, the result is a list of lists.
2052
+
2053
+ See Also
2054
+ --------
2055
+ flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges
2056
+ clump_masked, clump_unmasked
2057
+
2058
+ Notes
2059
+ -----
2060
+ Only accepts 2-D arrays at most.
2061
+
2062
+ Examples
2063
+ --------
2064
+ >>> import numpy as np
2065
+ >>> a = np.arange(12).reshape((3, 4))
2066
+ >>> mask = np.zeros_like(a)
2067
+ >>> mask[1:, :-1] = 1; mask[0, 1] = 1; mask[-1, 0] = 0
2068
+ >>> ma = np.ma.array(a, mask=mask)
2069
+ >>> ma
2070
+ masked_array(
2071
+ data=[[0, --, 2, 3],
2072
+ [--, --, --, 7],
2073
+ [8, --, --, 11]],
2074
+ mask=[[False, True, False, False],
2075
+ [ True, True, True, False],
2076
+ [False, True, True, False]],
2077
+ fill_value=999999)
2078
+ >>> np.array(ma[~ma.mask])
2079
+ array([ 0, 2, 3, 7, 8, 11])
2080
+
2081
+ >>> np.ma.notmasked_contiguous(ma)
2082
+ [slice(0, 1, None), slice(2, 4, None), slice(7, 9, None), slice(11, 12, None)]
2083
+
2084
+ >>> np.ma.notmasked_contiguous(ma, axis=0)
2085
+ [[slice(0, 1, None), slice(2, 3, None)], [], [slice(0, 1, None)], [slice(0, 3, None)]]
2086
+
2087
+ >>> np.ma.notmasked_contiguous(ma, axis=1)
2088
+ [[slice(0, 1, None), slice(2, 4, None)], [slice(3, 4, None)], [slice(0, 1, None), slice(3, 4, None)]]
2089
+
2090
+ """ # noqa: E501
2091
+ a = asarray(a)
2092
+ nd = a.ndim
2093
+ if nd > 2:
2094
+ raise NotImplementedError("Currently limited to at most 2D array.")
2095
+ if axis is None or nd == 1:
2096
+ return flatnotmasked_contiguous(a)
2097
+ #
2098
+ result = []
2099
+ #
2100
+ other = (axis + 1) % 2
2101
+ idx = [0, 0]
2102
+ idx[axis] = slice(None, None)
2103
+ #
2104
+ for i in range(a.shape[other]):
2105
+ idx[other] = i
2106
+ result.append(flatnotmasked_contiguous(a[tuple(idx)]))
2107
+ return result
2108
+
2109
+
2110
+ def _ezclump(mask):
2111
+ """
2112
+ Finds the clumps (groups of data with the same values) for a 1D bool array.
2113
+
2114
+ Returns a series of slices.
2115
+ """
2116
+ if mask.ndim > 1:
2117
+ mask = mask.ravel()
2118
+ idx = (mask[1:] ^ mask[:-1]).nonzero()
2119
+ idx = idx[0] + 1
2120
+
2121
+ if mask[0]:
2122
+ if len(idx) == 0:
2123
+ return [slice(0, mask.size)]
2124
+
2125
+ r = [slice(0, idx[0])]
2126
+ r.extend((slice(left, right)
2127
+ for left, right in zip(idx[1:-1:2], idx[2::2])))
2128
+ else:
2129
+ if len(idx) == 0:
2130
+ return []
2131
+
2132
+ r = [slice(left, right) for left, right in zip(idx[:-1:2], idx[1::2])]
2133
+
2134
+ if mask[-1]:
2135
+ r.append(slice(idx[-1], mask.size))
2136
+ return r
2137
+
2138
+
2139
+ def clump_unmasked(a):
2140
+ """
2141
+ Return list of slices corresponding to the unmasked clumps of a 1-D array.
2142
+ (A "clump" is defined as a contiguous region of the array).
2143
+
2144
+ Parameters
2145
+ ----------
2146
+ a : ndarray
2147
+ A one-dimensional masked array.
2148
+
2149
+ Returns
2150
+ -------
2151
+ slices : list of slice
2152
+ The list of slices, one for each continuous region of unmasked
2153
+ elements in `a`.
2154
+
2155
+ See Also
2156
+ --------
2157
+ flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges
2158
+ notmasked_contiguous, clump_masked
2159
+
2160
+ Examples
2161
+ --------
2162
+ >>> import numpy as np
2163
+ >>> a = np.ma.masked_array(np.arange(10))
2164
+ >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked
2165
+ >>> np.ma.clump_unmasked(a)
2166
+ [slice(3, 6, None), slice(7, 8, None)]
2167
+
2168
+ """
2169
+ mask = getattr(a, '_mask', nomask)
2170
+ if mask is nomask:
2171
+ return [slice(0, a.size)]
2172
+ return _ezclump(~mask)
2173
+
2174
+
2175
+ def clump_masked(a):
2176
+ """
2177
+ Returns a list of slices corresponding to the masked clumps of a 1-D array.
2178
+ (A "clump" is defined as a contiguous region of the array).
2179
+
2180
+ Parameters
2181
+ ----------
2182
+ a : ndarray
2183
+ A one-dimensional masked array.
2184
+
2185
+ Returns
2186
+ -------
2187
+ slices : list of slice
2188
+ The list of slices, one for each continuous region of masked elements
2189
+ in `a`.
2190
+
2191
+ See Also
2192
+ --------
2193
+ flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges
2194
+ notmasked_contiguous, clump_unmasked
2195
+
2196
+ Examples
2197
+ --------
2198
+ >>> import numpy as np
2199
+ >>> a = np.ma.masked_array(np.arange(10))
2200
+ >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked
2201
+ >>> np.ma.clump_masked(a)
2202
+ [slice(0, 3, None), slice(6, 7, None), slice(8, 10, None)]
2203
+
2204
+ """
2205
+ mask = ma.getmask(a)
2206
+ if mask is nomask:
2207
+ return []
2208
+ return _ezclump(mask)
2209
+
2210
+
2211
+ ###############################################################################
2212
+ # Polynomial fit #
2213
+ ###############################################################################
2214
+
2215
+
2216
+ def vander(x, n=None):
2217
+ """
2218
+ Masked values in the input array result in rows of zeros.
2219
+
2220
+ """
2221
+ _vander = np.vander(x, n)
2222
+ m = getmask(x)
2223
+ if m is not nomask:
2224
+ _vander[m] = 0
2225
+ return _vander
2226
+
2227
+
2228
+ vander.__doc__ = ma.doc_note(np.vander.__doc__, vander.__doc__)
2229
+
2230
+
2231
+ def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
2232
+ """
2233
+ Any masked values in x is propagated in y, and vice-versa.
2234
+
2235
+ """
2236
+ x = asarray(x)
2237
+ y = asarray(y)
2238
+
2239
+ m = getmask(x)
2240
+ if y.ndim == 1:
2241
+ m = mask_or(m, getmask(y))
2242
+ elif y.ndim == 2:
2243
+ my = getmask(mask_rows(y))
2244
+ if my is not nomask:
2245
+ m = mask_or(m, my[:, 0])
2246
+ else:
2247
+ raise TypeError("Expected a 1D or 2D array for y!")
2248
+
2249
+ if w is not None:
2250
+ w = asarray(w)
2251
+ if w.ndim != 1:
2252
+ raise TypeError("expected a 1-d array for weights")
2253
+ if w.shape[0] != y.shape[0]:
2254
+ raise TypeError("expected w and y to have the same length")
2255
+ m = mask_or(m, getmask(w))
2256
+
2257
+ if m is not nomask:
2258
+ not_m = ~m
2259
+ if w is not None:
2260
+ w = w[not_m]
2261
+ return np.polyfit(x[not_m], y[not_m], deg, rcond, full, w, cov)
2262
+ else:
2263
+ return np.polyfit(x, y, deg, rcond, full, w, cov)
2264
+
2265
+
2266
+ polyfit.__doc__ = ma.doc_note(np.polyfit.__doc__, polyfit.__doc__)
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/extras.pyi ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from _typeshed import Incomplete
2
+ from collections.abc import Sequence
3
+ from typing import SupportsIndex, TypeAlias, TypeVar, overload
4
+
5
+ import numpy as np
6
+ from numpy import _CastingKind
7
+ from numpy._typing import (
8
+ ArrayLike,
9
+ DTypeLike,
10
+ _AnyShape,
11
+ _ArrayLike,
12
+ _DTypeLike,
13
+ _ShapeLike,
14
+ )
15
+ from numpy.lib._function_base_impl import average
16
+ from numpy.lib._index_tricks_impl import AxisConcatenator
17
+
18
+ from .core import MaskedArray, dot
19
+
20
+ __all__ = [
21
+ "apply_along_axis",
22
+ "apply_over_axes",
23
+ "atleast_1d",
24
+ "atleast_2d",
25
+ "atleast_3d",
26
+ "average",
27
+ "clump_masked",
28
+ "clump_unmasked",
29
+ "column_stack",
30
+ "compress_cols",
31
+ "compress_nd",
32
+ "compress_rowcols",
33
+ "compress_rows",
34
+ "corrcoef",
35
+ "count_masked",
36
+ "cov",
37
+ "diagflat",
38
+ "dot",
39
+ "dstack",
40
+ "ediff1d",
41
+ "flatnotmasked_contiguous",
42
+ "flatnotmasked_edges",
43
+ "hsplit",
44
+ "hstack",
45
+ "in1d",
46
+ "intersect1d",
47
+ "isin",
48
+ "mask_cols",
49
+ "mask_rowcols",
50
+ "mask_rows",
51
+ "masked_all",
52
+ "masked_all_like",
53
+ "median",
54
+ "mr_",
55
+ "ndenumerate",
56
+ "notmasked_contiguous",
57
+ "notmasked_edges",
58
+ "polyfit",
59
+ "row_stack",
60
+ "setdiff1d",
61
+ "setxor1d",
62
+ "stack",
63
+ "union1d",
64
+ "unique",
65
+ "vander",
66
+ "vstack",
67
+ ]
68
+
69
+ _ScalarT = TypeVar("_ScalarT", bound=np.generic)
70
+ _ScalarT1 = TypeVar("_ScalarT1", bound=np.generic)
71
+ _ScalarT2 = TypeVar("_ScalarT2", bound=np.generic)
72
+ _MArrayT = TypeVar("_MArrayT", bound=MaskedArray)
73
+
74
+ _MArray: TypeAlias = MaskedArray[_AnyShape, np.dtype[_ScalarT]]
75
+
76
+ ###
77
+
78
+ # keep in sync with `numpy._core.shape_base.atleast_1d`
79
+ @overload
80
+ def atleast_1d(a0: _ArrayLike[_ScalarT], /) -> _MArray[_ScalarT]: ...
81
+ @overload
82
+ def atleast_1d(a0: _ArrayLike[_ScalarT1], a1: _ArrayLike[_ScalarT2], /) -> tuple[_MArray[_ScalarT1], _MArray[_ScalarT2]]: ...
83
+ @overload
84
+ def atleast_1d(
85
+ a0: _ArrayLike[_ScalarT], a1: _ArrayLike[_ScalarT], /, *arys: _ArrayLike[_ScalarT]
86
+ ) -> tuple[_MArray[_ScalarT], ...]: ...
87
+ @overload
88
+ def atleast_1d(a0: ArrayLike, /) -> _MArray[Incomplete]: ...
89
+ @overload
90
+ def atleast_1d(a0: ArrayLike, a1: ArrayLike, /) -> tuple[_MArray[Incomplete], _MArray[Incomplete]]: ...
91
+ @overload
92
+ def atleast_1d(a0: ArrayLike, a1: ArrayLike, /, *ai: ArrayLike) -> tuple[_MArray[Incomplete], ...]: ...
93
+
94
+ # keep in sync with `numpy._core.shape_base.atleast_2d`
95
+ @overload
96
+ def atleast_2d(a0: _ArrayLike[_ScalarT], /) -> _MArray[_ScalarT]: ...
97
+ @overload
98
+ def atleast_2d(a0: _ArrayLike[_ScalarT1], a1: _ArrayLike[_ScalarT2], /) -> tuple[_MArray[_ScalarT1], _MArray[_ScalarT2]]: ...
99
+ @overload
100
+ def atleast_2d(
101
+ a0: _ArrayLike[_ScalarT], a1: _ArrayLike[_ScalarT], /, *arys: _ArrayLike[_ScalarT]
102
+ ) -> tuple[_MArray[_ScalarT], ...]: ...
103
+ @overload
104
+ def atleast_2d(a0: ArrayLike, /) -> _MArray[Incomplete]: ...
105
+ @overload
106
+ def atleast_2d(a0: ArrayLike, a1: ArrayLike, /) -> tuple[_MArray[Incomplete], _MArray[Incomplete]]: ...
107
+ @overload
108
+ def atleast_2d(a0: ArrayLike, a1: ArrayLike, /, *ai: ArrayLike) -> tuple[_MArray[Incomplete], ...]: ...
109
+
110
+ # keep in sync with `numpy._core.shape_base.atleast_2d`
111
+ @overload
112
+ def atleast_3d(a0: _ArrayLike[_ScalarT], /) -> _MArray[_ScalarT]: ...
113
+ @overload
114
+ def atleast_3d(a0: _ArrayLike[_ScalarT1], a1: _ArrayLike[_ScalarT2], /) -> tuple[_MArray[_ScalarT1], _MArray[_ScalarT2]]: ...
115
+ @overload
116
+ def atleast_3d(
117
+ a0: _ArrayLike[_ScalarT], a1: _ArrayLike[_ScalarT], /, *arys: _ArrayLike[_ScalarT]
118
+ ) -> tuple[_MArray[_ScalarT], ...]: ...
119
+ @overload
120
+ def atleast_3d(a0: ArrayLike, /) -> _MArray[Incomplete]: ...
121
+ @overload
122
+ def atleast_3d(a0: ArrayLike, a1: ArrayLike, /) -> tuple[_MArray[Incomplete], _MArray[Incomplete]]: ...
123
+ @overload
124
+ def atleast_3d(a0: ArrayLike, a1: ArrayLike, /, *ai: ArrayLike) -> tuple[_MArray[Incomplete], ...]: ...
125
+
126
+ # keep in sync with `numpy._core.shape_base.vstack`
127
+ @overload
128
+ def vstack(
129
+ tup: Sequence[_ArrayLike[_ScalarT]],
130
+ *,
131
+ dtype: None = None,
132
+ casting: _CastingKind = "same_kind"
133
+ ) -> _MArray[_ScalarT]: ...
134
+ @overload
135
+ def vstack(
136
+ tup: Sequence[ArrayLike],
137
+ *,
138
+ dtype: _DTypeLike[_ScalarT],
139
+ casting: _CastingKind = "same_kind"
140
+ ) -> _MArray[_ScalarT]: ...
141
+ @overload
142
+ def vstack(
143
+ tup: Sequence[ArrayLike],
144
+ *,
145
+ dtype: DTypeLike | None = None,
146
+ casting: _CastingKind = "same_kind"
147
+ ) -> _MArray[Incomplete]: ...
148
+
149
+ row_stack = vstack
150
+
151
+ # keep in sync with `numpy._core.shape_base.hstack`
152
+ @overload
153
+ def hstack(
154
+ tup: Sequence[_ArrayLike[_ScalarT]],
155
+ *,
156
+ dtype: None = None,
157
+ casting: _CastingKind = "same_kind"
158
+ ) -> _MArray[_ScalarT]: ...
159
+ @overload
160
+ def hstack(
161
+ tup: Sequence[ArrayLike],
162
+ *,
163
+ dtype: _DTypeLike[_ScalarT],
164
+ casting: _CastingKind = "same_kind"
165
+ ) -> _MArray[_ScalarT]: ...
166
+ @overload
167
+ def hstack(
168
+ tup: Sequence[ArrayLike],
169
+ *,
170
+ dtype: DTypeLike | None = None,
171
+ casting: _CastingKind = "same_kind"
172
+ ) -> _MArray[Incomplete]: ...
173
+
174
+ # keep in sync with `numpy._core.shape_base_impl.column_stack`
175
+ @overload
176
+ def column_stack(tup: Sequence[_ArrayLike[_ScalarT]]) -> _MArray[_ScalarT]: ...
177
+ @overload
178
+ def column_stack(tup: Sequence[ArrayLike]) -> _MArray[Incomplete]: ...
179
+
180
+ # keep in sync with `numpy._core.shape_base_impl.dstack`
181
+ @overload
182
+ def dstack(tup: Sequence[_ArrayLike[_ScalarT]]) -> _MArray[_ScalarT]: ...
183
+ @overload
184
+ def dstack(tup: Sequence[ArrayLike]) -> _MArray[Incomplete]: ...
185
+
186
+ # keep in sync with `numpy._core.shape_base.stack`
187
+ @overload
188
+ def stack(
189
+ arrays: Sequence[_ArrayLike[_ScalarT]],
190
+ axis: SupportsIndex = 0,
191
+ out: None = None,
192
+ *,
193
+ dtype: None = None,
194
+ casting: _CastingKind = "same_kind"
195
+ ) -> _MArray[_ScalarT]: ...
196
+ @overload
197
+ def stack(
198
+ arrays: Sequence[ArrayLike],
199
+ axis: SupportsIndex = 0,
200
+ out: None = None,
201
+ *,
202
+ dtype: _DTypeLike[_ScalarT],
203
+ casting: _CastingKind = "same_kind"
204
+ ) -> _MArray[_ScalarT]: ...
205
+ @overload
206
+ def stack(
207
+ arrays: Sequence[ArrayLike],
208
+ axis: SupportsIndex = 0,
209
+ out: None = None,
210
+ *,
211
+ dtype: DTypeLike | None = None,
212
+ casting: _CastingKind = "same_kind"
213
+ ) -> _MArray[Incomplete]: ...
214
+ @overload
215
+ def stack(
216
+ arrays: Sequence[ArrayLike],
217
+ axis: SupportsIndex,
218
+ out: _MArrayT,
219
+ *,
220
+ dtype: DTypeLike | None = None,
221
+ casting: _CastingKind = "same_kind",
222
+ ) -> _MArrayT: ...
223
+ @overload
224
+ def stack(
225
+ arrays: Sequence[ArrayLike],
226
+ axis: SupportsIndex = 0,
227
+ *,
228
+ out: _MArrayT,
229
+ dtype: DTypeLike | None = None,
230
+ casting: _CastingKind = "same_kind",
231
+ ) -> _MArrayT: ...
232
+
233
+ # keep in sync with `numpy._core.shape_base_impl.hsplit`
234
+ @overload
235
+ def hsplit(ary: _ArrayLike[_ScalarT], indices_or_sections: _ShapeLike) -> list[_MArray[_ScalarT]]: ...
236
+ @overload
237
+ def hsplit(ary: ArrayLike, indices_or_sections: _ShapeLike) -> list[_MArray[Incomplete]]: ...
238
+
239
+ # keep in sync with `numpy._core.twodim_base_impl.hsplit`
240
+ @overload
241
+ def diagflat(v: _ArrayLike[_ScalarT], k: int = 0) -> _MArray[_ScalarT]: ...
242
+ @overload
243
+ def diagflat(v: ArrayLike, k: int = 0) -> _MArray[Incomplete]: ...
244
+
245
+ # TODO: everything below
246
+
247
+ def count_masked(arr, axis=None): ...
248
+ def masked_all(shape, dtype=float): ... # noqa: PYI014
249
+ def masked_all_like(arr): ...
250
+
251
+ def apply_along_axis(func1d, axis, arr, *args, **kwargs): ...
252
+ def apply_over_axes(func, a, axes): ...
253
+ def median(a, axis=None, out=None, overwrite_input=False, keepdims=False): ...
254
+ def compress_nd(x, axis=None): ...
255
+ def compress_rowcols(x, axis=None): ...
256
+ def compress_rows(a): ...
257
+ def compress_cols(a): ...
258
+ def mask_rows(a, axis=...): ...
259
+ def mask_cols(a, axis=...): ...
260
+ def ediff1d(arr, to_end=None, to_begin=None): ...
261
+ def unique(ar1, return_index=False, return_inverse=False): ...
262
+ def intersect1d(ar1, ar2, assume_unique=False): ...
263
+ def setxor1d(ar1, ar2, assume_unique=False): ...
264
+ def in1d(ar1, ar2, assume_unique=False, invert=False): ...
265
+ def isin(element, test_elements, assume_unique=False, invert=False): ...
266
+ def union1d(ar1, ar2): ...
267
+ def setdiff1d(ar1, ar2, assume_unique=False): ...
268
+ def cov(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None): ...
269
+ def corrcoef(x, y=None, rowvar=True, allow_masked=True): ...
270
+
271
+ class MAxisConcatenator(AxisConcatenator):
272
+ __slots__ = ()
273
+
274
+ @staticmethod
275
+ def concatenate(arrays: Incomplete, axis: int = 0) -> Incomplete: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
276
+ @classmethod
277
+ def makemat(cls, arr: Incomplete) -> Incomplete: ... # type: ignore[override] # pyright: ignore[reportIncompatibleVariableOverride]
278
+
279
+ class mr_class(MAxisConcatenator):
280
+ __slots__ = ()
281
+
282
+ def __init__(self) -> None: ...
283
+
284
+ mr_: mr_class
285
+
286
+ def ndenumerate(a, compressed=True): ...
287
+ def flatnotmasked_edges(a): ...
288
+ def notmasked_edges(a, axis=None): ...
289
+ def flatnotmasked_contiguous(a): ...
290
+ def notmasked_contiguous(a, axis=None): ...
291
+ def clump_unmasked(a): ...
292
+ def clump_masked(a): ...
293
+ def vander(x, n=None): ...
294
+ def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False): ...
295
+
296
+ #
297
+ def mask_rowcols(a: Incomplete, axis: Incomplete | None = None) -> MaskedArray[Incomplete, np.dtype[Incomplete]]: ...
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/mrecords.py ADDED
@@ -0,0 +1,762 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """:mod:`numpy.ma..mrecords`
2
+
3
+ Defines the equivalent of :class:`numpy.recarrays` for masked arrays,
4
+ where fields can be accessed as attributes.
5
+ Note that :class:`numpy.ma.MaskedArray` already supports structured datatypes
6
+ and the masking of individual fields.
7
+
8
+ .. moduleauthor:: Pierre Gerard-Marchant
9
+
10
+ """
11
+ # We should make sure that no field is called '_mask','mask','_fieldmask',
12
+ # or whatever restricted keywords. An idea would be to no bother in the
13
+ # first place, and then rename the invalid fields with a trailing
14
+ # underscore. Maybe we could just overload the parser function ?
15
+
16
+ import warnings
17
+
18
+ import numpy as np
19
+ import numpy.ma as ma
20
+
21
+ _byteorderconv = np._core.records._byteorderconv
22
+
23
+
24
+ _check_fill_value = ma.core._check_fill_value
25
+
26
+
27
+ __all__ = [
28
+ 'MaskedRecords', 'mrecarray', 'fromarrays', 'fromrecords',
29
+ 'fromtextfile', 'addfield',
30
+ ]
31
+
32
+ reserved_fields = ['_data', '_mask', '_fieldmask', 'dtype']
33
+
34
+
35
+ def _checknames(descr, names=None):
36
+ """
37
+ Checks that field names ``descr`` are not reserved keywords.
38
+
39
+ If this is the case, a default 'f%i' is substituted. If the argument
40
+ `names` is not None, updates the field names to valid names.
41
+
42
+ """
43
+ ndescr = len(descr)
44
+ default_names = [f'f{i}' for i in range(ndescr)]
45
+ if names is None:
46
+ new_names = default_names
47
+ else:
48
+ if isinstance(names, (tuple, list)):
49
+ new_names = names
50
+ elif isinstance(names, str):
51
+ new_names = names.split(',')
52
+ else:
53
+ raise NameError(f'illegal input names {names!r}')
54
+ nnames = len(new_names)
55
+ if nnames < ndescr:
56
+ new_names += default_names[nnames:]
57
+ ndescr = []
58
+ for (n, d, t) in zip(new_names, default_names, descr.descr):
59
+ if n in reserved_fields:
60
+ if t[0] in reserved_fields:
61
+ ndescr.append((d, t[1]))
62
+ else:
63
+ ndescr.append(t)
64
+ else:
65
+ ndescr.append((n, t[1]))
66
+ return np.dtype(ndescr)
67
+
68
+
69
+ def _get_fieldmask(self):
70
+ mdescr = [(n, '|b1') for n in self.dtype.names]
71
+ fdmask = np.empty(self.shape, dtype=mdescr)
72
+ fdmask.flat = tuple([False] * len(mdescr))
73
+ return fdmask
74
+
75
+
76
+ class MaskedRecords(ma.MaskedArray):
77
+ """
78
+
79
+ Attributes
80
+ ----------
81
+ _data : recarray
82
+ Underlying data, as a record array.
83
+ _mask : boolean array
84
+ Mask of the records. A record is masked when all its fields are
85
+ masked.
86
+ _fieldmask : boolean recarray
87
+ Record array of booleans, setting the mask of each individual field
88
+ of each record.
89
+ _fill_value : record
90
+ Filling values for each field.
91
+
92
+ """
93
+
94
+ def __new__(cls, shape, dtype=None, buf=None, offset=0, strides=None,
95
+ formats=None, names=None, titles=None,
96
+ byteorder=None, aligned=False,
97
+ mask=ma.nomask, hard_mask=False, fill_value=None, keep_mask=True,
98
+ copy=False,
99
+ **options):
100
+
101
+ self = np.recarray.__new__(cls, shape, dtype=dtype, buf=buf, offset=offset,
102
+ strides=strides, formats=formats, names=names,
103
+ titles=titles, byteorder=byteorder,
104
+ aligned=aligned,)
105
+
106
+ mdtype = ma.make_mask_descr(self.dtype)
107
+ if mask is ma.nomask or not np.size(mask):
108
+ if not keep_mask:
109
+ self._mask = tuple([False] * len(mdtype))
110
+ else:
111
+ mask = np.array(mask, copy=copy)
112
+ if mask.shape != self.shape:
113
+ (nd, nm) = (self.size, mask.size)
114
+ if nm == 1:
115
+ mask = np.resize(mask, self.shape)
116
+ elif nm == nd:
117
+ mask = np.reshape(mask, self.shape)
118
+ else:
119
+ msg = (f"Mask and data not compatible: data size is {nd},"
120
+ " mask size is {nm}.")
121
+ raise ma.MAError(msg)
122
+ if not keep_mask:
123
+ self.__setmask__(mask)
124
+ self._sharedmask = True
125
+ else:
126
+ if mask.dtype == mdtype:
127
+ _mask = mask
128
+ else:
129
+ _mask = np.array([tuple([m] * len(mdtype)) for m in mask],
130
+ dtype=mdtype)
131
+ self._mask = _mask
132
+ return self
133
+
134
+ def __array_finalize__(self, obj):
135
+ # Make sure we have a _fieldmask by default
136
+ _mask = getattr(obj, '_mask', None)
137
+ if _mask is None:
138
+ objmask = getattr(obj, '_mask', ma.nomask)
139
+ _dtype = np.ndarray.__getattribute__(self, 'dtype')
140
+ if objmask is ma.nomask:
141
+ _mask = ma.make_mask_none(self.shape, dtype=_dtype)
142
+ else:
143
+ mdescr = ma.make_mask_descr(_dtype)
144
+ _mask = np.array([tuple([m] * len(mdescr)) for m in objmask],
145
+ dtype=mdescr).view(np.recarray)
146
+ # Update some of the attributes
147
+ _dict = self.__dict__
148
+ _dict.update(_mask=_mask)
149
+ self._update_from(obj)
150
+ if _dict['_baseclass'] == np.ndarray:
151
+ _dict['_baseclass'] = np.recarray
152
+
153
+ @property
154
+ def _data(self):
155
+ """
156
+ Returns the data as a recarray.
157
+
158
+ """
159
+ return np.ndarray.view(self, np.recarray)
160
+
161
+ @property
162
+ def _fieldmask(self):
163
+ """
164
+ Alias to mask.
165
+
166
+ """
167
+ return self._mask
168
+
169
+ def __len__(self):
170
+ """
171
+ Returns the length
172
+
173
+ """
174
+ # We have more than one record
175
+ if self.ndim:
176
+ return len(self._data)
177
+ # We have only one record: return the nb of fields
178
+ return len(self.dtype)
179
+
180
+ def __getattribute__(self, attr):
181
+ try:
182
+ return object.__getattribute__(self, attr)
183
+ except AttributeError:
184
+ # attr must be a fieldname
185
+ pass
186
+ fielddict = np.ndarray.__getattribute__(self, 'dtype').fields
187
+ try:
188
+ res = fielddict[attr][:2]
189
+ except (TypeError, KeyError) as e:
190
+ raise AttributeError(
191
+ f'record array has no attribute {attr}') from e
192
+ # So far, so good
193
+ _localdict = np.ndarray.__getattribute__(self, '__dict__')
194
+ _data = np.ndarray.view(self, _localdict['_baseclass'])
195
+ obj = _data.getfield(*res)
196
+ if obj.dtype.names is not None:
197
+ raise NotImplementedError("MaskedRecords is currently limited to"
198
+ "simple records.")
199
+ # Get some special attributes
200
+ # Reset the object's mask
201
+ hasmasked = False
202
+ _mask = _localdict.get('_mask', None)
203
+ if _mask is not None:
204
+ try:
205
+ _mask = _mask[attr]
206
+ except IndexError:
207
+ # Couldn't find a mask: use the default (nomask)
208
+ pass
209
+ tp_len = len(_mask.dtype)
210
+ hasmasked = _mask.view((bool, ((tp_len,) if tp_len else ()))).any()
211
+ if (obj.shape or hasmasked):
212
+ obj = obj.view(ma.MaskedArray)
213
+ obj._baseclass = np.ndarray
214
+ obj._isfield = True
215
+ obj._mask = _mask
216
+ # Reset the field values
217
+ _fill_value = _localdict.get('_fill_value', None)
218
+ if _fill_value is not None:
219
+ try:
220
+ obj._fill_value = _fill_value[attr]
221
+ except ValueError:
222
+ obj._fill_value = None
223
+ else:
224
+ obj = obj.item()
225
+ return obj
226
+
227
+ def __setattr__(self, attr, val):
228
+ """
229
+ Sets the attribute attr to the value val.
230
+
231
+ """
232
+ # Should we call __setmask__ first ?
233
+ if attr in ['mask', 'fieldmask']:
234
+ self.__setmask__(val)
235
+ return
236
+ # Create a shortcut (so that we don't have to call getattr all the time)
237
+ _localdict = object.__getattribute__(self, '__dict__')
238
+ # Check whether we're creating a new field
239
+ newattr = attr not in _localdict
240
+ try:
241
+ # Is attr a generic attribute ?
242
+ ret = object.__setattr__(self, attr, val)
243
+ except Exception:
244
+ # Not a generic attribute: exit if it's not a valid field
245
+ fielddict = np.ndarray.__getattribute__(self, 'dtype').fields or {}
246
+ optinfo = np.ndarray.__getattribute__(self, '_optinfo') or {}
247
+ if not (attr in fielddict or attr in optinfo):
248
+ raise
249
+ else:
250
+ # Get the list of names
251
+ fielddict = np.ndarray.__getattribute__(self, 'dtype').fields or {}
252
+ # Check the attribute
253
+ if attr not in fielddict:
254
+ return ret
255
+ if newattr:
256
+ # We just added this one or this setattr worked on an
257
+ # internal attribute.
258
+ try:
259
+ object.__delattr__(self, attr)
260
+ except Exception:
261
+ return ret
262
+ # Let's try to set the field
263
+ try:
264
+ res = fielddict[attr][:2]
265
+ except (TypeError, KeyError) as e:
266
+ raise AttributeError(
267
+ f'record array has no attribute {attr}') from e
268
+
269
+ if val is ma.masked:
270
+ _fill_value = _localdict['_fill_value']
271
+ if _fill_value is not None:
272
+ dval = _localdict['_fill_value'][attr]
273
+ else:
274
+ dval = val
275
+ mval = True
276
+ else:
277
+ dval = ma.filled(val)
278
+ mval = ma.getmaskarray(val)
279
+ obj = np.ndarray.__getattribute__(self, '_data').setfield(dval, *res)
280
+ _localdict['_mask'].__setitem__(attr, mval)
281
+ return obj
282
+
283
+ def __getitem__(self, indx):
284
+ """
285
+ Returns all the fields sharing the same fieldname base.
286
+
287
+ The fieldname base is either `_data` or `_mask`.
288
+
289
+ """
290
+ _localdict = self.__dict__
291
+ _mask = np.ndarray.__getattribute__(self, '_mask')
292
+ _data = np.ndarray.view(self, _localdict['_baseclass'])
293
+ # We want a field
294
+ if isinstance(indx, str):
295
+ # Make sure _sharedmask is True to propagate back to _fieldmask
296
+ # Don't use _set_mask, there are some copies being made that
297
+ # break propagation Don't force the mask to nomask, that wreaks
298
+ # easy masking
299
+ obj = _data[indx].view(ma.MaskedArray)
300
+ obj._mask = _mask[indx]
301
+ obj._sharedmask = True
302
+ fval = _localdict['_fill_value']
303
+ if fval is not None:
304
+ obj._fill_value = fval[indx]
305
+ # Force to masked if the mask is True
306
+ if not obj.ndim and obj._mask:
307
+ return ma.masked
308
+ return obj
309
+ # We want some elements.
310
+ # First, the data.
311
+ obj = np.asarray(_data[indx]).view(mrecarray)
312
+ obj._mask = np.asarray(_mask[indx]).view(np.recarray)
313
+ return obj
314
+
315
+ def __setitem__(self, indx, value):
316
+ """
317
+ Sets the given record to value.
318
+
319
+ """
320
+ ma.MaskedArray.__setitem__(self, indx, value)
321
+ if isinstance(indx, str):
322
+ self._mask[indx] = ma.getmaskarray(value)
323
+
324
+ def __str__(self):
325
+ """
326
+ Calculates the string representation.
327
+
328
+ """
329
+ if self.size > 1:
330
+ mstr = [f"({','.join([str(i) for i in s])})"
331
+ for s in zip(*[getattr(self, f) for f in self.dtype.names])]
332
+ return f"[{', '.join(mstr)}]"
333
+ else:
334
+ mstr = [f"{','.join([str(i) for i in s])}"
335
+ for s in zip([getattr(self, f) for f in self.dtype.names])]
336
+ return f"({', '.join(mstr)})"
337
+
338
+ def __repr__(self):
339
+ """
340
+ Calculates the repr representation.
341
+
342
+ """
343
+ _names = self.dtype.names
344
+ fmt = f"%{max(len(n) for n in _names) + 4}s : %s"
345
+ reprstr = [fmt % (f, getattr(self, f)) for f in self.dtype.names]
346
+ reprstr.insert(0, 'masked_records(')
347
+ reprstr.extend([fmt % (' fill_value', self.fill_value),
348
+ ' )'])
349
+ return str("\n".join(reprstr))
350
+
351
+ def view(self, dtype=None, type=None):
352
+ """
353
+ Returns a view of the mrecarray.
354
+
355
+ """
356
+ # OK, basic copy-paste from MaskedArray.view.
357
+ if dtype is None:
358
+ if type is None:
359
+ output = np.ndarray.view(self)
360
+ else:
361
+ output = np.ndarray.view(self, type)
362
+ # Here again.
363
+ elif type is None:
364
+ try:
365
+ if issubclass(dtype, np.ndarray):
366
+ output = np.ndarray.view(self, dtype)
367
+ else:
368
+ output = np.ndarray.view(self, dtype)
369
+ # OK, there's the change
370
+ except TypeError:
371
+ dtype = np.dtype(dtype)
372
+ # we need to revert to MaskedArray, but keeping the possibility
373
+ # of subclasses (eg, TimeSeriesRecords), so we'll force a type
374
+ # set to the first parent
375
+ if dtype.fields is None:
376
+ basetype = self.__class__.__bases__[0]
377
+ output = self.__array__().view(dtype, basetype)
378
+ output._update_from(self)
379
+ else:
380
+ output = np.ndarray.view(self, dtype)
381
+ output._fill_value = None
382
+ else:
383
+ output = np.ndarray.view(self, dtype, type)
384
+ # Update the mask, just like in MaskedArray.view
385
+ if (getattr(output, '_mask', ma.nomask) is not ma.nomask):
386
+ mdtype = ma.make_mask_descr(output.dtype)
387
+ output._mask = self._mask.view(mdtype, np.ndarray)
388
+ output._mask.shape = output.shape
389
+ return output
390
+
391
+ def harden_mask(self):
392
+ """
393
+ Forces the mask to hard.
394
+
395
+ """
396
+ self._hardmask = True
397
+
398
+ def soften_mask(self):
399
+ """
400
+ Forces the mask to soft
401
+
402
+ """
403
+ self._hardmask = False
404
+
405
+ def copy(self):
406
+ """
407
+ Returns a copy of the masked record.
408
+
409
+ """
410
+ copied = self._data.copy().view(type(self))
411
+ copied._mask = self._mask.copy()
412
+ return copied
413
+
414
+ def tolist(self, fill_value=None):
415
+ """
416
+ Return the data portion of the array as a list.
417
+
418
+ Data items are converted to the nearest compatible Python type.
419
+ Masked values are converted to fill_value. If fill_value is None,
420
+ the corresponding entries in the output list will be ``None``.
421
+
422
+ """
423
+ if fill_value is not None:
424
+ return self.filled(fill_value).tolist()
425
+ result = np.array(self.filled().tolist(), dtype=object)
426
+ mask = np.array(self._mask.tolist())
427
+ result[mask] = None
428
+ return result.tolist()
429
+
430
+ def __getstate__(self):
431
+ """Return the internal state of the masked array.
432
+
433
+ This is for pickling.
434
+
435
+ """
436
+ state = (1,
437
+ self.shape,
438
+ self.dtype,
439
+ self.flags.fnc,
440
+ self._data.tobytes(),
441
+ self._mask.tobytes(),
442
+ self._fill_value,
443
+ )
444
+ return state
445
+
446
+ def __setstate__(self, state):
447
+ """
448
+ Restore the internal state of the masked array.
449
+
450
+ This is for pickling. ``state`` is typically the output of the
451
+ ``__getstate__`` output, and is a 5-tuple:
452
+
453
+ - class name
454
+ - a tuple giving the shape of the data
455
+ - a typecode for the data
456
+ - a binary string for the data
457
+ - a binary string for the mask.
458
+
459
+ """
460
+ (ver, shp, typ, isf, raw, msk, flv) = state
461
+ np.ndarray.__setstate__(self, (shp, typ, isf, raw))
462
+ mdtype = np.dtype([(k, np.bool) for (k, _) in self.dtype.descr])
463
+ self.__dict__['_mask'].__setstate__((shp, mdtype, isf, msk))
464
+ self.fill_value = flv
465
+
466
+ def __reduce__(self):
467
+ """
468
+ Return a 3-tuple for pickling a MaskedArray.
469
+
470
+ """
471
+ return (_mrreconstruct,
472
+ (self.__class__, self._baseclass, (0,), 'b',),
473
+ self.__getstate__())
474
+
475
+
476
+ def _mrreconstruct(subtype, baseclass, baseshape, basetype,):
477
+ """
478
+ Build a new MaskedArray from the information stored in a pickle.
479
+
480
+ """
481
+ _data = np.ndarray.__new__(baseclass, baseshape, basetype).view(subtype)
482
+ _mask = np.ndarray.__new__(np.ndarray, baseshape, 'b1')
483
+ return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype,)
484
+
485
+
486
+ mrecarray = MaskedRecords
487
+
488
+
489
+ ###############################################################################
490
+ # Constructors #
491
+ ###############################################################################
492
+
493
+
494
+ def fromarrays(arraylist, dtype=None, shape=None, formats=None,
495
+ names=None, titles=None, aligned=False, byteorder=None,
496
+ fill_value=None):
497
+ """
498
+ Creates a mrecarray from a (flat) list of masked arrays.
499
+
500
+ Parameters
501
+ ----------
502
+ arraylist : sequence
503
+ A list of (masked) arrays. Each element of the sequence is first converted
504
+ to a masked array if needed. If a 2D array is passed as argument, it is
505
+ processed line by line
506
+ dtype : {None, dtype}, optional
507
+ Data type descriptor.
508
+ shape : {None, integer}, optional
509
+ Number of records. If None, shape is defined from the shape of the
510
+ first array in the list.
511
+ formats : {None, sequence}, optional
512
+ Sequence of formats for each individual field. If None, the formats will
513
+ be autodetected by inspecting the fields and selecting the highest dtype
514
+ possible.
515
+ names : {None, sequence}, optional
516
+ Sequence of the names of each field.
517
+ fill_value : {None, sequence}, optional
518
+ Sequence of data to be used as filling values.
519
+
520
+ Notes
521
+ -----
522
+ Lists of tuples should be preferred over lists of lists for faster processing.
523
+
524
+ """
525
+ datalist = [ma.getdata(x) for x in arraylist]
526
+ masklist = [np.atleast_1d(ma.getmaskarray(x)) for x in arraylist]
527
+ _array = np.rec.fromarrays(datalist,
528
+ dtype=dtype, shape=shape, formats=formats,
529
+ names=names, titles=titles, aligned=aligned,
530
+ byteorder=byteorder).view(mrecarray)
531
+ _array._mask.flat = list(zip(*masklist))
532
+ if fill_value is not None:
533
+ _array.fill_value = fill_value
534
+ return _array
535
+
536
+
537
+ def fromrecords(reclist, dtype=None, shape=None, formats=None, names=None,
538
+ titles=None, aligned=False, byteorder=None,
539
+ fill_value=None, mask=ma.nomask):
540
+ """
541
+ Creates a MaskedRecords from a list of records.
542
+
543
+ Parameters
544
+ ----------
545
+ reclist : sequence
546
+ A list of records. Each element of the sequence is first converted
547
+ to a masked array if needed. If a 2D array is passed as argument, it is
548
+ processed line by line
549
+ dtype : {None, dtype}, optional
550
+ Data type descriptor.
551
+ shape : {None,int}, optional
552
+ Number of records. If None, ``shape`` is defined from the shape of the
553
+ first array in the list.
554
+ formats : {None, sequence}, optional
555
+ Sequence of formats for each individual field. If None, the formats will
556
+ be autodetected by inspecting the fields and selecting the highest dtype
557
+ possible.
558
+ names : {None, sequence}, optional
559
+ Sequence of the names of each field.
560
+ fill_value : {None, sequence}, optional
561
+ Sequence of data to be used as filling values.
562
+ mask : {nomask, sequence}, optional.
563
+ External mask to apply on the data.
564
+
565
+ Notes
566
+ -----
567
+ Lists of tuples should be preferred over lists of lists for faster processing.
568
+
569
+ """
570
+ # Grab the initial _fieldmask, if needed:
571
+ _mask = getattr(reclist, '_mask', None)
572
+ # Get the list of records.
573
+ if isinstance(reclist, np.ndarray):
574
+ # Make sure we don't have some hidden mask
575
+ if isinstance(reclist, ma.MaskedArray):
576
+ reclist = reclist.filled().view(np.ndarray)
577
+ # Grab the initial dtype, just in case
578
+ if dtype is None:
579
+ dtype = reclist.dtype
580
+ reclist = reclist.tolist()
581
+ mrec = np.rec.fromrecords(reclist, dtype=dtype, shape=shape, formats=formats,
582
+ names=names, titles=titles,
583
+ aligned=aligned, byteorder=byteorder).view(mrecarray)
584
+ # Set the fill_value if needed
585
+ if fill_value is not None:
586
+ mrec.fill_value = fill_value
587
+ # Now, let's deal w/ the mask
588
+ if mask is not ma.nomask:
589
+ mask = np.asarray(mask)
590
+ maskrecordlength = len(mask.dtype)
591
+ if maskrecordlength:
592
+ mrec._mask.flat = mask
593
+ elif mask.ndim == 2:
594
+ mrec._mask.flat = [tuple(m) for m in mask]
595
+ else:
596
+ mrec.__setmask__(mask)
597
+ if _mask is not None:
598
+ mrec._mask[:] = _mask
599
+ return mrec
600
+
601
+
602
+ def _guessvartypes(arr):
603
+ """
604
+ Tries to guess the dtypes of the str_ ndarray `arr`.
605
+
606
+ Guesses by testing element-wise conversion. Returns a list of dtypes.
607
+ The array is first converted to ndarray. If the array is 2D, the test
608
+ is performed on the first line. An exception is raised if the file is
609
+ 3D or more.
610
+
611
+ """
612
+ vartypes = []
613
+ arr = np.asarray(arr)
614
+ if arr.ndim == 2:
615
+ arr = arr[0]
616
+ elif arr.ndim > 2:
617
+ raise ValueError("The array should be 2D at most!")
618
+ # Start the conversion loop.
619
+ for f in arr:
620
+ try:
621
+ int(f)
622
+ except (ValueError, TypeError):
623
+ try:
624
+ float(f)
625
+ except (ValueError, TypeError):
626
+ try:
627
+ complex(f)
628
+ except (ValueError, TypeError):
629
+ vartypes.append(arr.dtype)
630
+ else:
631
+ vartypes.append(np.dtype(complex))
632
+ else:
633
+ vartypes.append(np.dtype(float))
634
+ else:
635
+ vartypes.append(np.dtype(int))
636
+ return vartypes
637
+
638
+
639
+ def openfile(fname):
640
+ """
641
+ Opens the file handle of file `fname`.
642
+
643
+ """
644
+ # A file handle
645
+ if hasattr(fname, 'readline'):
646
+ return fname
647
+ # Try to open the file and guess its type
648
+ try:
649
+ f = open(fname)
650
+ except FileNotFoundError as e:
651
+ raise FileNotFoundError(f"No such file: '{fname}'") from e
652
+ if f.readline()[:2] != "\\x":
653
+ f.seek(0, 0)
654
+ return f
655
+ f.close()
656
+ raise NotImplementedError("Wow, binary file")
657
+
658
+
659
+ def fromtextfile(fname, delimiter=None, commentchar='#', missingchar='',
660
+ varnames=None, vartypes=None):
661
+ """
662
+ Creates a mrecarray from data stored in the file `filename`.
663
+
664
+ Parameters
665
+ ----------
666
+ fname : {file name/handle}
667
+ Handle of an opened file.
668
+ delimiter : {None, string}, optional
669
+ Alphanumeric character used to separate columns in the file.
670
+ If None, any (group of) white spacestring(s) will be used.
671
+ commentchar : {'#', string}, optional
672
+ Alphanumeric character used to mark the start of a comment.
673
+ missingchar : {'', string}, optional
674
+ String indicating missing data, and used to create the masks.
675
+ varnames : {None, sequence}, optional
676
+ Sequence of the variable names. If None, a list will be created from
677
+ the first non empty line of the file.
678
+ vartypes : {None, sequence}, optional
679
+ Sequence of the variables dtypes. If None, it will be estimated from
680
+ the first non-commented line.
681
+
682
+
683
+ Ultra simple: the varnames are in the header, one line"""
684
+
685
+ # Try to open the file.
686
+ ftext = openfile(fname)
687
+
688
+ # Get the first non-empty line as the varnames
689
+ while True:
690
+ line = ftext.readline()
691
+ firstline = line[:line.find(commentchar)].strip()
692
+ _varnames = firstline.split(delimiter)
693
+ if len(_varnames) > 1:
694
+ break
695
+ if varnames is None:
696
+ varnames = _varnames
697
+
698
+ # Get the data.
699
+ _variables = ma.masked_array([line.strip().split(delimiter) for line in ftext
700
+ if line[0] != commentchar and len(line) > 1])
701
+ (_, nfields) = _variables.shape
702
+ ftext.close()
703
+
704
+ # Try to guess the dtype.
705
+ if vartypes is None:
706
+ vartypes = _guessvartypes(_variables[0])
707
+ else:
708
+ vartypes = [np.dtype(v) for v in vartypes]
709
+ if len(vartypes) != nfields:
710
+ msg = f"Attempting to {len(vartypes)} dtypes for {nfields} fields!"
711
+ msg += " Reverting to default."
712
+ warnings.warn(msg, stacklevel=2)
713
+ vartypes = _guessvartypes(_variables[0])
714
+
715
+ # Construct the descriptor.
716
+ mdescr = list(zip(varnames, vartypes))
717
+ mfillv = [ma.default_fill_value(f) for f in vartypes]
718
+
719
+ # Get the data and the mask.
720
+ # We just need a list of masked_arrays. It's easier to create it like that:
721
+ _mask = (_variables.T == missingchar)
722
+ _datalist = [ma.masked_array(a, mask=m, dtype=t, fill_value=f)
723
+ for (a, m, t, f) in zip(_variables.T, _mask, vartypes, mfillv)]
724
+
725
+ return fromarrays(_datalist, dtype=mdescr)
726
+
727
+
728
+ def addfield(mrecord, newfield, newfieldname=None):
729
+ """Adds a new field to the masked record array
730
+
731
+ Uses `newfield` as data and `newfieldname` as name. If `newfieldname`
732
+ is None, the new field name is set to 'fi', where `i` is the number of
733
+ existing fields.
734
+
735
+ """
736
+ _data = mrecord._data
737
+ _mask = mrecord._mask
738
+ if newfieldname is None or newfieldname in reserved_fields:
739
+ newfieldname = f'f{len(_data.dtype)}'
740
+ newfield = ma.array(newfield)
741
+ # Get the new data.
742
+ # Create a new empty recarray
743
+ newdtype = np.dtype(_data.dtype.descr + [(newfieldname, newfield.dtype)])
744
+ newdata = np.recarray(_data.shape, newdtype)
745
+ # Add the existing field
746
+ [newdata.setfield(_data.getfield(*f), *f)
747
+ for f in _data.dtype.fields.values()]
748
+ # Add the new field
749
+ newdata.setfield(newfield._data, *newdata.dtype.fields[newfieldname])
750
+ newdata = newdata.view(MaskedRecords)
751
+ # Get the new mask
752
+ # Create a new empty recarray
753
+ newmdtype = np.dtype([(n, np.bool) for n in newdtype.names])
754
+ newmask = np.recarray(_data.shape, newmdtype)
755
+ # Add the old masks
756
+ [newmask.setfield(_mask.getfield(*f), *f)
757
+ for f in _mask.dtype.fields.values()]
758
+ # Add the mask of the new field
759
+ newmask.setfield(ma.getmaskarray(newfield),
760
+ *newmask.dtype.fields[newfieldname])
761
+ newdata._mask = newmask
762
+ return newdata
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/mrecords.pyi ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Generic
2
+ from typing_extensions import TypeVar
3
+
4
+ import numpy as np
5
+ from numpy._typing import _AnyShape
6
+
7
+ from .core import MaskedArray
8
+
9
+ __all__ = [
10
+ "MaskedRecords",
11
+ "mrecarray",
12
+ "fromarrays",
13
+ "fromrecords",
14
+ "fromtextfile",
15
+ "addfield",
16
+ ]
17
+
18
+ _ShapeT_co = TypeVar("_ShapeT_co", bound=tuple[int, ...], default=_AnyShape, covariant=True)
19
+ _DTypeT_co = TypeVar("_DTypeT_co", bound=np.dtype, default=np.dtype, covariant=True)
20
+
21
+ class MaskedRecords(MaskedArray[_ShapeT_co, _DTypeT_co], Generic[_ShapeT_co, _DTypeT_co]):
22
+ def __new__(
23
+ cls,
24
+ shape,
25
+ dtype=...,
26
+ buf=...,
27
+ offset=...,
28
+ strides=...,
29
+ formats=...,
30
+ names=...,
31
+ titles=...,
32
+ byteorder=...,
33
+ aligned=...,
34
+ mask=...,
35
+ hard_mask=...,
36
+ fill_value=...,
37
+ keep_mask=...,
38
+ copy=...,
39
+ **options,
40
+ ): ...
41
+ _mask: Any
42
+ _fill_value: Any
43
+ @property
44
+ def _data(self): ...
45
+ @property
46
+ def _fieldmask(self): ...
47
+ def __array_finalize__(self, obj): ...
48
+ def __len__(self): ...
49
+ def __getattribute__(self, attr): ...
50
+ def __setattr__(self, attr, val): ...
51
+ def __getitem__(self, indx): ...
52
+ def __setitem__(self, indx, value): ...
53
+ def view(self, dtype=None, type=None): ...
54
+ def harden_mask(self): ...
55
+ def soften_mask(self): ...
56
+ def copy(self): ...
57
+ def tolist(self, fill_value=None): ...
58
+ def __reduce__(self): ...
59
+
60
+ mrecarray = MaskedRecords
61
+
62
+ def fromarrays(
63
+ arraylist,
64
+ dtype=None,
65
+ shape=None,
66
+ formats=None,
67
+ names=None,
68
+ titles=None,
69
+ aligned=False,
70
+ byteorder=None,
71
+ fill_value=None,
72
+ ): ...
73
+
74
+ def fromrecords(
75
+ reclist,
76
+ dtype=None,
77
+ shape=None,
78
+ formats=None,
79
+ names=None,
80
+ titles=None,
81
+ aligned=False,
82
+ byteorder=None,
83
+ fill_value=None,
84
+ mask=...,
85
+ ): ...
86
+
87
+ def fromtextfile(
88
+ fname,
89
+ delimiter=None,
90
+ commentchar="#",
91
+ missingchar="",
92
+ varnames=None,
93
+ vartypes=None,
94
+ ): ...
95
+
96
+ def addfield(mrecord, newfield, newfieldname=None): ...
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/testutils.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Miscellaneous functions for testing masked arrays and subclasses
2
+
3
+ :author: Pierre Gerard-Marchant
4
+ :contact: pierregm_at_uga_dot_edu
5
+
6
+ """
7
+ import operator
8
+
9
+ import numpy as np
10
+ import numpy._core.umath as umath
11
+ import numpy.testing
12
+ from numpy import ndarray
13
+ from numpy.testing import ( # noqa: F401
14
+ assert_,
15
+ assert_allclose,
16
+ assert_array_almost_equal_nulp,
17
+ assert_raises,
18
+ build_err_msg,
19
+ )
20
+
21
+ from .core import filled, getmask, mask_or, masked, masked_array, nomask
22
+
23
+ __all__masked = [
24
+ 'almost', 'approx', 'assert_almost_equal', 'assert_array_almost_equal',
25
+ 'assert_array_approx_equal', 'assert_array_compare',
26
+ 'assert_array_equal', 'assert_array_less', 'assert_close',
27
+ 'assert_equal', 'assert_equal_records', 'assert_mask_equal',
28
+ 'assert_not_equal', 'fail_if_array_equal',
29
+ ]
30
+
31
+ # Include some normal test functions to avoid breaking other projects who
32
+ # have mistakenly included them from this file. SciPy is one. That is
33
+ # unfortunate, as some of these functions are not intended to work with
34
+ # masked arrays. But there was no way to tell before.
35
+ from unittest import TestCase # noqa: F401
36
+
37
+ __some__from_testing = [
38
+ 'TestCase', 'assert_', 'assert_allclose', 'assert_array_almost_equal_nulp',
39
+ 'assert_raises'
40
+ ]
41
+
42
+ __all__ = __all__masked + __some__from_testing # noqa: PLE0605
43
+
44
+
45
+ def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
46
+ """
47
+ Returns true if all components of a and b are equal to given tolerances.
48
+
49
+ If fill_value is True, masked values considered equal. Otherwise,
50
+ masked values are considered unequal. The relative error rtol should
51
+ be positive and << 1.0 The absolute error atol comes into play for
52
+ those elements of b that are very small or zero; it says how small a
53
+ must be also.
54
+
55
+ """
56
+ m = mask_or(getmask(a), getmask(b))
57
+ d1 = filled(a)
58
+ d2 = filled(b)
59
+ if d1.dtype.char == "O" or d2.dtype.char == "O":
60
+ return np.equal(d1, d2).ravel()
61
+ x = filled(
62
+ masked_array(d1, copy=False, mask=m), fill_value
63
+ ).astype(np.float64)
64
+ y = filled(masked_array(d2, copy=False, mask=m), 1).astype(np.float64)
65
+ d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
66
+ return d.ravel()
67
+
68
+
69
+ def almost(a, b, decimal=6, fill_value=True):
70
+ """
71
+ Returns True if a and b are equal up to decimal places.
72
+
73
+ If fill_value is True, masked values considered equal. Otherwise,
74
+ masked values are considered unequal.
75
+
76
+ """
77
+ m = mask_or(getmask(a), getmask(b))
78
+ d1 = filled(a)
79
+ d2 = filled(b)
80
+ if d1.dtype.char == "O" or d2.dtype.char == "O":
81
+ return np.equal(d1, d2).ravel()
82
+ x = filled(
83
+ masked_array(d1, copy=False, mask=m), fill_value
84
+ ).astype(np.float64)
85
+ y = filled(masked_array(d2, copy=False, mask=m), 1).astype(np.float64)
86
+ d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
87
+ return d.ravel()
88
+
89
+
90
+ def _assert_equal_on_sequences(actual, desired, err_msg=''):
91
+ """
92
+ Asserts the equality of two non-array sequences.
93
+
94
+ """
95
+ assert_equal(len(actual), len(desired), err_msg)
96
+ for k in range(len(desired)):
97
+ assert_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}')
98
+
99
+
100
+ def assert_equal_records(a, b):
101
+ """
102
+ Asserts that two records are equal.
103
+
104
+ Pretty crude for now.
105
+
106
+ """
107
+ assert_equal(a.dtype, b.dtype)
108
+ for f in a.dtype.names:
109
+ (af, bf) = (operator.getitem(a, f), operator.getitem(b, f))
110
+ if not (af is masked) and not (bf is masked):
111
+ assert_equal(operator.getitem(a, f), operator.getitem(b, f))
112
+
113
+
114
+ def assert_equal(actual, desired, err_msg=''):
115
+ """
116
+ Asserts that two items are equal.
117
+
118
+ """
119
+ # Case #1: dictionary .....
120
+ if isinstance(desired, dict):
121
+ if not isinstance(actual, dict):
122
+ raise AssertionError(repr(type(actual)))
123
+ assert_equal(len(actual), len(desired), err_msg)
124
+ for k in desired:
125
+ if k not in actual:
126
+ raise AssertionError(f"{k} not in {actual}")
127
+ assert_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}')
128
+ return
129
+ # Case #2: lists .....
130
+ if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):
131
+ return _assert_equal_on_sequences(actual, desired, err_msg='')
132
+ if not (isinstance(actual, ndarray) or isinstance(desired, ndarray)):
133
+ msg = build_err_msg([actual, desired], err_msg,)
134
+ if not desired == actual:
135
+ raise AssertionError(msg)
136
+ return
137
+ # Case #4. arrays or equivalent
138
+ if ((actual is masked) and not (desired is masked)) or \
139
+ ((desired is masked) and not (actual is masked)):
140
+ msg = build_err_msg([actual, desired],
141
+ err_msg, header='', names=('x', 'y'))
142
+ raise ValueError(msg)
143
+ actual = np.asanyarray(actual)
144
+ desired = np.asanyarray(desired)
145
+ (actual_dtype, desired_dtype) = (actual.dtype, desired.dtype)
146
+ if actual_dtype.char == "S" and desired_dtype.char == "S":
147
+ return _assert_equal_on_sequences(actual.tolist(),
148
+ desired.tolist(),
149
+ err_msg='')
150
+ return assert_array_equal(actual, desired, err_msg)
151
+
152
+
153
+ def fail_if_equal(actual, desired, err_msg='',):
154
+ """
155
+ Raises an assertion error if two items are equal.
156
+
157
+ """
158
+ if isinstance(desired, dict):
159
+ if not isinstance(actual, dict):
160
+ raise AssertionError(repr(type(actual)))
161
+ fail_if_equal(len(actual), len(desired), err_msg)
162
+ for k in desired:
163
+ if k not in actual:
164
+ raise AssertionError(repr(k))
165
+ fail_if_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}')
166
+ return
167
+ if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):
168
+ fail_if_equal(len(actual), len(desired), err_msg)
169
+ for k in range(len(desired)):
170
+ fail_if_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}')
171
+ return
172
+ if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray):
173
+ return fail_if_array_equal(actual, desired, err_msg)
174
+ msg = build_err_msg([actual, desired], err_msg)
175
+ if not desired != actual:
176
+ raise AssertionError(msg)
177
+
178
+
179
+ assert_not_equal = fail_if_equal
180
+
181
+
182
+ def assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True):
183
+ """
184
+ Asserts that two items are almost equal.
185
+
186
+ The test is equivalent to abs(desired-actual) < 0.5 * 10**(-decimal).
187
+
188
+ """
189
+ if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray):
190
+ return assert_array_almost_equal(actual, desired, decimal=decimal,
191
+ err_msg=err_msg, verbose=verbose)
192
+ msg = build_err_msg([actual, desired],
193
+ err_msg=err_msg, verbose=verbose)
194
+ if not round(abs(desired - actual), decimal) == 0:
195
+ raise AssertionError(msg)
196
+
197
+
198
+ assert_close = assert_almost_equal
199
+
200
+
201
+ def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='',
202
+ fill_value=True):
203
+ """
204
+ Asserts that comparison between two masked arrays is satisfied.
205
+
206
+ The comparison is elementwise.
207
+
208
+ """
209
+ # Allocate a common mask and refill
210
+ m = mask_or(getmask(x), getmask(y))
211
+ x = masked_array(x, copy=False, mask=m, keep_mask=False, subok=False)
212
+ y = masked_array(y, copy=False, mask=m, keep_mask=False, subok=False)
213
+ if ((x is masked) and not (y is masked)) or \
214
+ ((y is masked) and not (x is masked)):
215
+ msg = build_err_msg([x, y], err_msg=err_msg, verbose=verbose,
216
+ header=header, names=('x', 'y'))
217
+ raise ValueError(msg)
218
+ # OK, now run the basic tests on filled versions
219
+ return np.testing.assert_array_compare(comparison,
220
+ x.filled(fill_value),
221
+ y.filled(fill_value),
222
+ err_msg=err_msg,
223
+ verbose=verbose, header=header)
224
+
225
+
226
+ def assert_array_equal(x, y, err_msg='', verbose=True):
227
+ """
228
+ Checks the elementwise equality of two masked arrays.
229
+
230
+ """
231
+ assert_array_compare(operator.__eq__, x, y,
232
+ err_msg=err_msg, verbose=verbose,
233
+ header='Arrays are not equal')
234
+
235
+
236
+ def fail_if_array_equal(x, y, err_msg='', verbose=True):
237
+ """
238
+ Raises an assertion error if two masked arrays are not equal elementwise.
239
+
240
+ """
241
+ def compare(x, y):
242
+ return (not np.all(approx(x, y)))
243
+ assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,
244
+ header='Arrays are not equal')
245
+
246
+
247
+ def assert_array_approx_equal(x, y, decimal=6, err_msg='', verbose=True):
248
+ """
249
+ Checks the equality of two masked arrays, up to given number odecimals.
250
+
251
+ The equality is checked elementwise.
252
+
253
+ """
254
+ def compare(x, y):
255
+ "Returns the result of the loose comparison between x and y)."
256
+ return approx(x, y, rtol=10. ** -decimal)
257
+ assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,
258
+ header='Arrays are not almost equal')
259
+
260
+
261
+ def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True):
262
+ """
263
+ Checks the equality of two masked arrays, up to given number odecimals.
264
+
265
+ The equality is checked elementwise.
266
+
267
+ """
268
+ def compare(x, y):
269
+ "Returns the result of the loose comparison between x and y)."
270
+ return almost(x, y, decimal)
271
+ assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,
272
+ header='Arrays are not almost equal')
273
+
274
+
275
+ def assert_array_less(x, y, err_msg='', verbose=True):
276
+ """
277
+ Checks that x is smaller than y elementwise.
278
+
279
+ """
280
+ assert_array_compare(operator.__lt__, x, y,
281
+ err_msg=err_msg, verbose=verbose,
282
+ header='Arrays are not less-ordered')
283
+
284
+
285
+ def assert_mask_equal(m1, m2, err_msg=''):
286
+ """
287
+ Asserts the equality of two masks.
288
+
289
+ """
290
+ if m1 is nomask:
291
+ assert_(m2 is nomask)
292
+ if m2 is nomask:
293
+ assert_(m1 is nomask)
294
+ assert_array_equal(m1, m2, err_msg=err_msg)
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/ma/testutils.pyi ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy._typing import NDArray
3
+ from numpy.testing import (
4
+ TestCase,
5
+ assert_,
6
+ assert_allclose,
7
+ assert_array_almost_equal_nulp,
8
+ assert_raises,
9
+ )
10
+ from numpy.testing._private.utils import _ComparisonFunc
11
+
12
+ __all__ = [
13
+ "TestCase",
14
+ "almost",
15
+ "approx",
16
+ "assert_",
17
+ "assert_allclose",
18
+ "assert_almost_equal",
19
+ "assert_array_almost_equal",
20
+ "assert_array_almost_equal_nulp",
21
+ "assert_array_approx_equal",
22
+ "assert_array_compare",
23
+ "assert_array_equal",
24
+ "assert_array_less",
25
+ "assert_close",
26
+ "assert_equal",
27
+ "assert_equal_records",
28
+ "assert_mask_equal",
29
+ "assert_not_equal",
30
+ "assert_raises",
31
+ "fail_if_array_equal",
32
+ ]
33
+
34
+ def approx(
35
+ a: object, b: object, fill_value: bool = True, rtol: float = 1e-5, atol: float = 1e-8
36
+ ) -> np.ndarray[tuple[int], np.dtype[np.bool]]: ...
37
+ def almost(a: object, b: object, decimal: int = 6, fill_value: bool = True) -> np.ndarray[tuple[int], np.dtype[np.bool]]: ...
38
+
39
+ #
40
+ def assert_equal_records(a: NDArray[np.void], b: NDArray[np.void]) -> None: ...
41
+ def assert_equal(actual: object, desired: object, err_msg: str = "") -> None: ...
42
+ def fail_if_equal(actual: object, desired: object, err_msg: str = "") -> None: ...
43
+ def assert_almost_equal(
44
+ actual: object, desired: object, decimal: int = 7, err_msg: str = "", verbose: bool = True
45
+ ) -> None: ...
46
+
47
+ #
48
+ def assert_array_compare(
49
+ comparison: _ComparisonFunc,
50
+ x: object,
51
+ y: object,
52
+ err_msg: str = "",
53
+ verbose: bool = True,
54
+ header: str = "",
55
+ fill_value: bool = True,
56
+ ) -> None: ...
57
+ def assert_array_equal(x: object, y: object, err_msg: str = "", verbose: bool = True) -> None: ...
58
+ def fail_if_array_equal(x: object, y: object, err_msg: str = "", verbose: bool = True) -> None: ...
59
+ def assert_array_approx_equal(
60
+ x: object, y: object, decimal: int = 6, err_msg: str = "", verbose: bool = True
61
+ ) -> None: ...
62
+ def assert_array_almost_equal(
63
+ x: object, y: object, decimal: int = 6, err_msg: str = "", verbose: bool = True
64
+ ) -> None: ...
65
+ def assert_array_less(x: object, y: object, err_msg: str = "", verbose: bool = True) -> None: ...
66
+ def assert_mask_equal(m1: object, m2: object, err_msg: str = "") -> None: ...
67
+
68
+ assert_not_equal = fail_if_equal
69
+ assert_close = assert_almost_equal
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/matrixlib/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sub-package containing the matrix class and related functions.
2
+
3
+ """
4
+ from . import defmatrix
5
+ from .defmatrix import *
6
+
7
+ __all__ = defmatrix.__all__
8
+
9
+ from numpy._pytesttester import PytestTester
10
+
11
+ test = PytestTester(__name__)
12
+ del PytestTester
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/matrixlib/__init__.pyi ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .defmatrix import asmatrix, bmat, matrix
2
+
3
+ __all__ = ["matrix", "bmat", "asmatrix"]
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/matrixlib/defmatrix.py ADDED
@@ -0,0 +1,1119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ['matrix', 'bmat', 'asmatrix']
2
+
3
+ import ast
4
+ import sys
5
+ import warnings
6
+
7
+ import numpy._core.numeric as N
8
+ from numpy._core.numeric import concatenate, isscalar
9
+ from numpy._utils import set_module
10
+
11
+ # While not in __all__, matrix_power used to be defined here, so we import
12
+ # it for backward compatibility.
13
+ from numpy.linalg import matrix_power
14
+
15
+
16
+ def _convert_from_string(data):
17
+ for char in '[]':
18
+ data = data.replace(char, '')
19
+
20
+ rows = data.split(';')
21
+ newdata = []
22
+ for count, row in enumerate(rows):
23
+ trow = row.split(',')
24
+ newrow = []
25
+ for col in trow:
26
+ temp = col.split()
27
+ newrow.extend(map(ast.literal_eval, temp))
28
+ if count == 0:
29
+ Ncols = len(newrow)
30
+ elif len(newrow) != Ncols:
31
+ raise ValueError("Rows not the same size.")
32
+ newdata.append(newrow)
33
+ return newdata
34
+
35
+
36
+ @set_module('numpy')
37
+ def asmatrix(data, dtype=None):
38
+ """
39
+ Interpret the input as a matrix.
40
+
41
+ Unlike `matrix`, `asmatrix` does not make a copy if the input is already
42
+ a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``.
43
+
44
+ Parameters
45
+ ----------
46
+ data : array_like
47
+ Input data.
48
+ dtype : data-type
49
+ Data-type of the output matrix.
50
+
51
+ Returns
52
+ -------
53
+ mat : matrix
54
+ `data` interpreted as a matrix.
55
+
56
+ Examples
57
+ --------
58
+ >>> import numpy as np
59
+ >>> x = np.array([[1, 2], [3, 4]])
60
+
61
+ >>> m = np.asmatrix(x)
62
+
63
+ >>> x[0,0] = 5
64
+
65
+ >>> m
66
+ matrix([[5, 2],
67
+ [3, 4]])
68
+
69
+ """
70
+ return matrix(data, dtype=dtype, copy=False)
71
+
72
+
73
+ @set_module('numpy')
74
+ class matrix(N.ndarray):
75
+ """
76
+ matrix(data, dtype=None, copy=True)
77
+
78
+ Returns a matrix from an array-like object, or from a string of data.
79
+
80
+ A matrix is a specialized 2-D array that retains its 2-D nature
81
+ through operations. It has certain special operators, such as ``*``
82
+ (matrix multiplication) and ``**`` (matrix power).
83
+
84
+ .. note:: It is no longer recommended to use this class, even for linear
85
+ algebra. Instead use regular arrays. The class may be removed
86
+ in the future.
87
+
88
+ Parameters
89
+ ----------
90
+ data : array_like or string
91
+ If `data` is a string, it is interpreted as a matrix with commas
92
+ or spaces separating columns, and semicolons separating rows.
93
+ dtype : data-type
94
+ Data-type of the output matrix.
95
+ copy : bool
96
+ If `data` is already an `ndarray`, then this flag determines
97
+ whether the data is copied (the default), or whether a view is
98
+ constructed.
99
+
100
+ See Also
101
+ --------
102
+ array
103
+
104
+ Examples
105
+ --------
106
+ >>> import numpy as np
107
+ >>> a = np.matrix('1 2; 3 4')
108
+ >>> a
109
+ matrix([[1, 2],
110
+ [3, 4]])
111
+
112
+ >>> np.matrix([[1, 2], [3, 4]])
113
+ matrix([[1, 2],
114
+ [3, 4]])
115
+
116
+ """
117
+ __array_priority__ = 10.0
118
+
119
+ def __new__(subtype, data, dtype=None, copy=True):
120
+ warnings.warn('the matrix subclass is not the recommended way to '
121
+ 'represent matrices or deal with linear algebra (see '
122
+ 'https://docs.scipy.org/doc/numpy/user/'
123
+ 'numpy-for-matlab-users.html). '
124
+ 'Please adjust your code to use regular ndarray.',
125
+ PendingDeprecationWarning, stacklevel=2)
126
+ if isinstance(data, matrix):
127
+ dtype2 = data.dtype
128
+ if (dtype is None):
129
+ dtype = dtype2
130
+ if (dtype2 == dtype) and (not copy):
131
+ return data
132
+ return data.astype(dtype)
133
+
134
+ if isinstance(data, N.ndarray):
135
+ if dtype is None:
136
+ intype = data.dtype
137
+ else:
138
+ intype = N.dtype(dtype)
139
+ new = data.view(subtype)
140
+ if intype != data.dtype:
141
+ return new.astype(intype)
142
+ if copy:
143
+ return new.copy()
144
+ else:
145
+ return new
146
+
147
+ if isinstance(data, str):
148
+ data = _convert_from_string(data)
149
+
150
+ # now convert data to an array
151
+ copy = None if not copy else True
152
+ arr = N.array(data, dtype=dtype, copy=copy)
153
+ ndim = arr.ndim
154
+ shape = arr.shape
155
+ if (ndim > 2):
156
+ raise ValueError("matrix must be 2-dimensional")
157
+ elif ndim == 0:
158
+ shape = (1, 1)
159
+ elif ndim == 1:
160
+ shape = (1, shape[0])
161
+
162
+ order = 'C'
163
+ if (ndim == 2) and arr.flags.fortran:
164
+ order = 'F'
165
+
166
+ if not (order or arr.flags.contiguous):
167
+ arr = arr.copy()
168
+
169
+ ret = N.ndarray.__new__(subtype, shape, arr.dtype,
170
+ buffer=arr,
171
+ order=order)
172
+ return ret
173
+
174
+ def __array_finalize__(self, obj):
175
+ self._getitem = False
176
+ if (isinstance(obj, matrix) and obj._getitem):
177
+ return
178
+ ndim = self.ndim
179
+ if (ndim == 2):
180
+ return
181
+ if (ndim > 2):
182
+ newshape = tuple(x for x in self.shape if x > 1)
183
+ ndim = len(newshape)
184
+ if ndim == 2:
185
+ self.shape = newshape
186
+ return
187
+ elif (ndim > 2):
188
+ raise ValueError("shape too large to be a matrix.")
189
+ else:
190
+ newshape = self.shape
191
+ if ndim == 0:
192
+ self.shape = (1, 1)
193
+ elif ndim == 1:
194
+ self.shape = (1, newshape[0])
195
+ return
196
+
197
+ def __getitem__(self, index):
198
+ self._getitem = True
199
+
200
+ try:
201
+ out = N.ndarray.__getitem__(self, index)
202
+ finally:
203
+ self._getitem = False
204
+
205
+ if not isinstance(out, N.ndarray):
206
+ return out
207
+
208
+ if out.ndim == 0:
209
+ return out[()]
210
+ if out.ndim == 1:
211
+ sh = out.shape[0]
212
+ # Determine when we should have a column array
213
+ try:
214
+ n = len(index)
215
+ except Exception:
216
+ n = 0
217
+ if n > 1 and isscalar(index[1]):
218
+ out.shape = (sh, 1)
219
+ else:
220
+ out.shape = (1, sh)
221
+ return out
222
+
223
+ def __mul__(self, other):
224
+ if isinstance(other, (N.ndarray, list, tuple)):
225
+ # This promotes 1-D vectors to row vectors
226
+ return N.dot(self, asmatrix(other))
227
+ if isscalar(other) or not hasattr(other, '__rmul__'):
228
+ return N.dot(self, other)
229
+ return NotImplemented
230
+
231
+ def __rmul__(self, other):
232
+ return N.dot(other, self)
233
+
234
+ def __imul__(self, other):
235
+ self[:] = self * other
236
+ return self
237
+
238
+ def __pow__(self, other):
239
+ return matrix_power(self, other)
240
+
241
+ def __ipow__(self, other):
242
+ self[:] = self ** other
243
+ return self
244
+
245
+ def __rpow__(self, other):
246
+ return NotImplemented
247
+
248
+ def _align(self, axis):
249
+ """A convenience function for operations that need to preserve axis
250
+ orientation.
251
+ """
252
+ if axis is None:
253
+ return self[0, 0]
254
+ elif axis == 0:
255
+ return self
256
+ elif axis == 1:
257
+ return self.transpose()
258
+ else:
259
+ raise ValueError("unsupported axis")
260
+
261
+ def _collapse(self, axis):
262
+ """A convenience function for operations that want to collapse
263
+ to a scalar like _align, but are using keepdims=True
264
+ """
265
+ if axis is None:
266
+ return self[0, 0]
267
+ else:
268
+ return self
269
+
270
+ # Necessary because base-class tolist expects dimension
271
+ # reduction by x[0]
272
+ def tolist(self):
273
+ """
274
+ Return the matrix as a (possibly nested) list.
275
+
276
+ See `ndarray.tolist` for full documentation.
277
+
278
+ See Also
279
+ --------
280
+ ndarray.tolist
281
+
282
+ Examples
283
+ --------
284
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
285
+ matrix([[ 0, 1, 2, 3],
286
+ [ 4, 5, 6, 7],
287
+ [ 8, 9, 10, 11]])
288
+ >>> x.tolist()
289
+ [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
290
+
291
+ """
292
+ return self.__array__().tolist()
293
+
294
+ # To preserve orientation of result...
295
+ def sum(self, axis=None, dtype=None, out=None):
296
+ """
297
+ Returns the sum of the matrix elements, along the given axis.
298
+
299
+ Refer to `numpy.sum` for full documentation.
300
+
301
+ See Also
302
+ --------
303
+ numpy.sum
304
+
305
+ Notes
306
+ -----
307
+ This is the same as `ndarray.sum`, except that where an `ndarray` would
308
+ be returned, a `matrix` object is returned instead.
309
+
310
+ Examples
311
+ --------
312
+ >>> x = np.matrix([[1, 2], [4, 3]])
313
+ >>> x.sum()
314
+ 10
315
+ >>> x.sum(axis=1)
316
+ matrix([[3],
317
+ [7]])
318
+ >>> x.sum(axis=1, dtype='float')
319
+ matrix([[3.],
320
+ [7.]])
321
+ >>> out = np.zeros((2, 1), dtype='float')
322
+ >>> x.sum(axis=1, dtype='float', out=np.asmatrix(out))
323
+ matrix([[3.],
324
+ [7.]])
325
+
326
+ """
327
+ return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)
328
+
329
+ # To update docstring from array to matrix...
330
+ def squeeze(self, axis=None):
331
+ """
332
+ Return a possibly reshaped matrix.
333
+
334
+ Refer to `numpy.squeeze` for more documentation.
335
+
336
+ Parameters
337
+ ----------
338
+ axis : None or int or tuple of ints, optional
339
+ Selects a subset of the axes of length one in the shape.
340
+ If an axis is selected with shape entry greater than one,
341
+ an error is raised.
342
+
343
+ Returns
344
+ -------
345
+ squeezed : matrix
346
+ The matrix, but as a (1, N) matrix if it had shape (N, 1).
347
+
348
+ See Also
349
+ --------
350
+ numpy.squeeze : related function
351
+
352
+ Notes
353
+ -----
354
+ If `m` has a single column then that column is returned
355
+ as the single row of a matrix. Otherwise `m` is returned.
356
+ The returned matrix is always either `m` itself or a view into `m`.
357
+ Supplying an axis keyword argument will not affect the returned matrix
358
+ but it may cause an error to be raised.
359
+
360
+ Examples
361
+ --------
362
+ >>> c = np.matrix([[1], [2]])
363
+ >>> c
364
+ matrix([[1],
365
+ [2]])
366
+ >>> c.squeeze()
367
+ matrix([[1, 2]])
368
+ >>> r = c.T
369
+ >>> r
370
+ matrix([[1, 2]])
371
+ >>> r.squeeze()
372
+ matrix([[1, 2]])
373
+ >>> m = np.matrix([[1, 2], [3, 4]])
374
+ >>> m.squeeze()
375
+ matrix([[1, 2],
376
+ [3, 4]])
377
+
378
+ """
379
+ return N.ndarray.squeeze(self, axis=axis)
380
+
381
+ # To update docstring from array to matrix...
382
+ def flatten(self, order='C'):
383
+ """
384
+ Return a flattened copy of the matrix.
385
+
386
+ All `N` elements of the matrix are placed into a single row.
387
+
388
+ Parameters
389
+ ----------
390
+ order : {'C', 'F', 'A', 'K'}, optional
391
+ 'C' means to flatten in row-major (C-style) order. 'F' means to
392
+ flatten in column-major (Fortran-style) order. 'A' means to
393
+ flatten in column-major order if `m` is Fortran *contiguous* in
394
+ memory, row-major order otherwise. 'K' means to flatten `m` in
395
+ the order the elements occur in memory. The default is 'C'.
396
+
397
+ Returns
398
+ -------
399
+ y : matrix
400
+ A copy of the matrix, flattened to a `(1, N)` matrix where `N`
401
+ is the number of elements in the original matrix.
402
+
403
+ See Also
404
+ --------
405
+ ravel : Return a flattened array.
406
+ flat : A 1-D flat iterator over the matrix.
407
+
408
+ Examples
409
+ --------
410
+ >>> m = np.matrix([[1,2], [3,4]])
411
+ >>> m.flatten()
412
+ matrix([[1, 2, 3, 4]])
413
+ >>> m.flatten('F')
414
+ matrix([[1, 3, 2, 4]])
415
+
416
+ """
417
+ return N.ndarray.flatten(self, order=order)
418
+
419
+ def mean(self, axis=None, dtype=None, out=None):
420
+ """
421
+ Returns the average of the matrix elements along the given axis.
422
+
423
+ Refer to `numpy.mean` for full documentation.
424
+
425
+ See Also
426
+ --------
427
+ numpy.mean
428
+
429
+ Notes
430
+ -----
431
+ Same as `ndarray.mean` except that, where that returns an `ndarray`,
432
+ this returns a `matrix` object.
433
+
434
+ Examples
435
+ --------
436
+ >>> x = np.matrix(np.arange(12).reshape((3, 4)))
437
+ >>> x
438
+ matrix([[ 0, 1, 2, 3],
439
+ [ 4, 5, 6, 7],
440
+ [ 8, 9, 10, 11]])
441
+ >>> x.mean()
442
+ 5.5
443
+ >>> x.mean(0)
444
+ matrix([[4., 5., 6., 7.]])
445
+ >>> x.mean(1)
446
+ matrix([[ 1.5],
447
+ [ 5.5],
448
+ [ 9.5]])
449
+
450
+ """
451
+ return N.ndarray.mean(self, axis, dtype, out, keepdims=True)._collapse(axis)
452
+
453
+ def std(self, axis=None, dtype=None, out=None, ddof=0):
454
+ """
455
+ Return the standard deviation of the array elements along the given axis.
456
+
457
+ Refer to `numpy.std` for full documentation.
458
+
459
+ See Also
460
+ --------
461
+ numpy.std
462
+
463
+ Notes
464
+ -----
465
+ This is the same as `ndarray.std`, except that where an `ndarray` would
466
+ be returned, a `matrix` object is returned instead.
467
+
468
+ Examples
469
+ --------
470
+ >>> x = np.matrix(np.arange(12).reshape((3, 4)))
471
+ >>> x
472
+ matrix([[ 0, 1, 2, 3],
473
+ [ 4, 5, 6, 7],
474
+ [ 8, 9, 10, 11]])
475
+ >>> x.std()
476
+ 3.4520525295346629 # may vary
477
+ >>> x.std(0)
478
+ matrix([[ 3.26598632, 3.26598632, 3.26598632, 3.26598632]]) # may vary
479
+ >>> x.std(1)
480
+ matrix([[ 1.11803399],
481
+ [ 1.11803399],
482
+ [ 1.11803399]])
483
+
484
+ """
485
+ return N.ndarray.std(self, axis, dtype, out, ddof,
486
+ keepdims=True)._collapse(axis)
487
+
488
+ def var(self, axis=None, dtype=None, out=None, ddof=0):
489
+ """
490
+ Returns the variance of the matrix elements, along the given axis.
491
+
492
+ Refer to `numpy.var` for full documentation.
493
+
494
+ See Also
495
+ --------
496
+ numpy.var
497
+
498
+ Notes
499
+ -----
500
+ This is the same as `ndarray.var`, except that where an `ndarray` would
501
+ be returned, a `matrix` object is returned instead.
502
+
503
+ Examples
504
+ --------
505
+ >>> x = np.matrix(np.arange(12).reshape((3, 4)))
506
+ >>> x
507
+ matrix([[ 0, 1, 2, 3],
508
+ [ 4, 5, 6, 7],
509
+ [ 8, 9, 10, 11]])
510
+ >>> x.var()
511
+ 11.916666666666666
512
+ >>> x.var(0)
513
+ matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) # may vary
514
+ >>> x.var(1)
515
+ matrix([[1.25],
516
+ [1.25],
517
+ [1.25]])
518
+
519
+ """
520
+ return N.ndarray.var(self, axis, dtype, out, ddof,
521
+ keepdims=True)._collapse(axis)
522
+
523
+ def prod(self, axis=None, dtype=None, out=None):
524
+ """
525
+ Return the product of the array elements over the given axis.
526
+
527
+ Refer to `prod` for full documentation.
528
+
529
+ See Also
530
+ --------
531
+ prod, ndarray.prod
532
+
533
+ Notes
534
+ -----
535
+ Same as `ndarray.prod`, except, where that returns an `ndarray`, this
536
+ returns a `matrix` object instead.
537
+
538
+ Examples
539
+ --------
540
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
541
+ matrix([[ 0, 1, 2, 3],
542
+ [ 4, 5, 6, 7],
543
+ [ 8, 9, 10, 11]])
544
+ >>> x.prod()
545
+ 0
546
+ >>> x.prod(0)
547
+ matrix([[ 0, 45, 120, 231]])
548
+ >>> x.prod(1)
549
+ matrix([[ 0],
550
+ [ 840],
551
+ [7920]])
552
+
553
+ """
554
+ return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis)
555
+
556
+ def any(self, axis=None, out=None):
557
+ """
558
+ Test whether any array element along a given axis evaluates to True.
559
+
560
+ Refer to `numpy.any` for full documentation.
561
+
562
+ Parameters
563
+ ----------
564
+ axis : int, optional
565
+ Axis along which logical OR is performed
566
+ out : ndarray, optional
567
+ Output to existing array instead of creating new one, must have
568
+ same shape as expected output
569
+
570
+ Returns
571
+ -------
572
+ any : bool, ndarray
573
+ Returns a single bool if `axis` is ``None``; otherwise,
574
+ returns `ndarray`
575
+
576
+ """
577
+ return N.ndarray.any(self, axis, out, keepdims=True)._collapse(axis)
578
+
579
+ def all(self, axis=None, out=None):
580
+ """
581
+ Test whether all matrix elements along a given axis evaluate to True.
582
+
583
+ Parameters
584
+ ----------
585
+ See `numpy.all` for complete descriptions
586
+
587
+ See Also
588
+ --------
589
+ numpy.all
590
+
591
+ Notes
592
+ -----
593
+ This is the same as `ndarray.all`, but it returns a `matrix` object.
594
+
595
+ Examples
596
+ --------
597
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
598
+ matrix([[ 0, 1, 2, 3],
599
+ [ 4, 5, 6, 7],
600
+ [ 8, 9, 10, 11]])
601
+ >>> y = x[0]; y
602
+ matrix([[0, 1, 2, 3]])
603
+ >>> (x == y)
604
+ matrix([[ True, True, True, True],
605
+ [False, False, False, False],
606
+ [False, False, False, False]])
607
+ >>> (x == y).all()
608
+ False
609
+ >>> (x == y).all(0)
610
+ matrix([[False, False, False, False]])
611
+ >>> (x == y).all(1)
612
+ matrix([[ True],
613
+ [False],
614
+ [False]])
615
+
616
+ """
617
+ return N.ndarray.all(self, axis, out, keepdims=True)._collapse(axis)
618
+
619
+ def max(self, axis=None, out=None):
620
+ """
621
+ Return the maximum value along an axis.
622
+
623
+ Parameters
624
+ ----------
625
+ See `amax` for complete descriptions
626
+
627
+ See Also
628
+ --------
629
+ amax, ndarray.max
630
+
631
+ Notes
632
+ -----
633
+ This is the same as `ndarray.max`, but returns a `matrix` object
634
+ where `ndarray.max` would return an ndarray.
635
+
636
+ Examples
637
+ --------
638
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
639
+ matrix([[ 0, 1, 2, 3],
640
+ [ 4, 5, 6, 7],
641
+ [ 8, 9, 10, 11]])
642
+ >>> x.max()
643
+ 11
644
+ >>> x.max(0)
645
+ matrix([[ 8, 9, 10, 11]])
646
+ >>> x.max(1)
647
+ matrix([[ 3],
648
+ [ 7],
649
+ [11]])
650
+
651
+ """
652
+ return N.ndarray.max(self, axis, out, keepdims=True)._collapse(axis)
653
+
654
+ def argmax(self, axis=None, out=None):
655
+ """
656
+ Indexes of the maximum values along an axis.
657
+
658
+ Return the indexes of the first occurrences of the maximum values
659
+ along the specified axis. If axis is None, the index is for the
660
+ flattened matrix.
661
+
662
+ Parameters
663
+ ----------
664
+ See `numpy.argmax` for complete descriptions
665
+
666
+ See Also
667
+ --------
668
+ numpy.argmax
669
+
670
+ Notes
671
+ -----
672
+ This is the same as `ndarray.argmax`, but returns a `matrix` object
673
+ where `ndarray.argmax` would return an `ndarray`.
674
+
675
+ Examples
676
+ --------
677
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
678
+ matrix([[ 0, 1, 2, 3],
679
+ [ 4, 5, 6, 7],
680
+ [ 8, 9, 10, 11]])
681
+ >>> x.argmax()
682
+ 11
683
+ >>> x.argmax(0)
684
+ matrix([[2, 2, 2, 2]])
685
+ >>> x.argmax(1)
686
+ matrix([[3],
687
+ [3],
688
+ [3]])
689
+
690
+ """
691
+ return N.ndarray.argmax(self, axis, out)._align(axis)
692
+
693
+ def min(self, axis=None, out=None):
694
+ """
695
+ Return the minimum value along an axis.
696
+
697
+ Parameters
698
+ ----------
699
+ See `amin` for complete descriptions.
700
+
701
+ See Also
702
+ --------
703
+ amin, ndarray.min
704
+
705
+ Notes
706
+ -----
707
+ This is the same as `ndarray.min`, but returns a `matrix` object
708
+ where `ndarray.min` would return an ndarray.
709
+
710
+ Examples
711
+ --------
712
+ >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
713
+ matrix([[ 0, -1, -2, -3],
714
+ [ -4, -5, -6, -7],
715
+ [ -8, -9, -10, -11]])
716
+ >>> x.min()
717
+ -11
718
+ >>> x.min(0)
719
+ matrix([[ -8, -9, -10, -11]])
720
+ >>> x.min(1)
721
+ matrix([[ -3],
722
+ [ -7],
723
+ [-11]])
724
+
725
+ """
726
+ return N.ndarray.min(self, axis, out, keepdims=True)._collapse(axis)
727
+
728
+ def argmin(self, axis=None, out=None):
729
+ """
730
+ Indexes of the minimum values along an axis.
731
+
732
+ Return the indexes of the first occurrences of the minimum values
733
+ along the specified axis. If axis is None, the index is for the
734
+ flattened matrix.
735
+
736
+ Parameters
737
+ ----------
738
+ See `numpy.argmin` for complete descriptions.
739
+
740
+ See Also
741
+ --------
742
+ numpy.argmin
743
+
744
+ Notes
745
+ -----
746
+ This is the same as `ndarray.argmin`, but returns a `matrix` object
747
+ where `ndarray.argmin` would return an `ndarray`.
748
+
749
+ Examples
750
+ --------
751
+ >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
752
+ matrix([[ 0, -1, -2, -3],
753
+ [ -4, -5, -6, -7],
754
+ [ -8, -9, -10, -11]])
755
+ >>> x.argmin()
756
+ 11
757
+ >>> x.argmin(0)
758
+ matrix([[2, 2, 2, 2]])
759
+ >>> x.argmin(1)
760
+ matrix([[3],
761
+ [3],
762
+ [3]])
763
+
764
+ """
765
+ return N.ndarray.argmin(self, axis, out)._align(axis)
766
+
767
+ def ptp(self, axis=None, out=None):
768
+ """
769
+ Peak-to-peak (maximum - minimum) value along the given axis.
770
+
771
+ Refer to `numpy.ptp` for full documentation.
772
+
773
+ See Also
774
+ --------
775
+ numpy.ptp
776
+
777
+ Notes
778
+ -----
779
+ Same as `ndarray.ptp`, except, where that would return an `ndarray` object,
780
+ this returns a `matrix` object.
781
+
782
+ Examples
783
+ --------
784
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
785
+ matrix([[ 0, 1, 2, 3],
786
+ [ 4, 5, 6, 7],
787
+ [ 8, 9, 10, 11]])
788
+ >>> x.ptp()
789
+ 11
790
+ >>> x.ptp(0)
791
+ matrix([[8, 8, 8, 8]])
792
+ >>> x.ptp(1)
793
+ matrix([[3],
794
+ [3],
795
+ [3]])
796
+
797
+ """
798
+ return N.ptp(self, axis, out)._align(axis)
799
+
800
+ @property
801
+ def I(self): # noqa: E743
802
+ """
803
+ Returns the (multiplicative) inverse of invertible `self`.
804
+
805
+ Parameters
806
+ ----------
807
+ None
808
+
809
+ Returns
810
+ -------
811
+ ret : matrix object
812
+ If `self` is non-singular, `ret` is such that ``ret * self`` ==
813
+ ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return
814
+ ``True``.
815
+
816
+ Raises
817
+ ------
818
+ numpy.linalg.LinAlgError: Singular matrix
819
+ If `self` is singular.
820
+
821
+ See Also
822
+ --------
823
+ linalg.inv
824
+
825
+ Examples
826
+ --------
827
+ >>> m = np.matrix('[1, 2; 3, 4]'); m
828
+ matrix([[1, 2],
829
+ [3, 4]])
830
+ >>> m.getI()
831
+ matrix([[-2. , 1. ],
832
+ [ 1.5, -0.5]])
833
+ >>> m.getI() * m
834
+ matrix([[ 1., 0.], # may vary
835
+ [ 0., 1.]])
836
+
837
+ """
838
+ M, N = self.shape
839
+ if M == N:
840
+ from numpy.linalg import inv as func
841
+ else:
842
+ from numpy.linalg import pinv as func
843
+ return asmatrix(func(self))
844
+
845
+ @property
846
+ def A(self):
847
+ """
848
+ Return `self` as an `ndarray` object.
849
+
850
+ Equivalent to ``np.asarray(self)``.
851
+
852
+ Parameters
853
+ ----------
854
+ None
855
+
856
+ Returns
857
+ -------
858
+ ret : ndarray
859
+ `self` as an `ndarray`
860
+
861
+ Examples
862
+ --------
863
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
864
+ matrix([[ 0, 1, 2, 3],
865
+ [ 4, 5, 6, 7],
866
+ [ 8, 9, 10, 11]])
867
+ >>> x.getA()
868
+ array([[ 0, 1, 2, 3],
869
+ [ 4, 5, 6, 7],
870
+ [ 8, 9, 10, 11]])
871
+
872
+ """
873
+ return self.__array__()
874
+
875
+ @property
876
+ def A1(self):
877
+ """
878
+ Return `self` as a flattened `ndarray`.
879
+
880
+ Equivalent to ``np.asarray(x).ravel()``
881
+
882
+ Parameters
883
+ ----------
884
+ None
885
+
886
+ Returns
887
+ -------
888
+ ret : ndarray
889
+ `self`, 1-D, as an `ndarray`
890
+
891
+ Examples
892
+ --------
893
+ >>> x = np.matrix(np.arange(12).reshape((3,4))); x
894
+ matrix([[ 0, 1, 2, 3],
895
+ [ 4, 5, 6, 7],
896
+ [ 8, 9, 10, 11]])
897
+ >>> x.getA1()
898
+ array([ 0, 1, 2, ..., 9, 10, 11])
899
+
900
+
901
+ """
902
+ return self.__array__().ravel()
903
+
904
+ def ravel(self, order='C'):
905
+ """
906
+ Return a flattened matrix.
907
+
908
+ Refer to `numpy.ravel` for more documentation.
909
+
910
+ Parameters
911
+ ----------
912
+ order : {'C', 'F', 'A', 'K'}, optional
913
+ The elements of `m` are read using this index order. 'C' means to
914
+ index the elements in C-like order, with the last axis index
915
+ changing fastest, back to the first axis index changing slowest.
916
+ 'F' means to index the elements in Fortran-like index order, with
917
+ the first index changing fastest, and the last index changing
918
+ slowest. Note that the 'C' and 'F' options take no account of the
919
+ memory layout of the underlying array, and only refer to the order
920
+ of axis indexing. 'A' means to read the elements in Fortran-like
921
+ index order if `m` is Fortran *contiguous* in memory, C-like order
922
+ otherwise. 'K' means to read the elements in the order they occur
923
+ in memory, except for reversing the data when strides are negative.
924
+ By default, 'C' index order is used.
925
+
926
+ Returns
927
+ -------
928
+ ret : matrix
929
+ Return the matrix flattened to shape `(1, N)` where `N`
930
+ is the number of elements in the original matrix.
931
+ A copy is made only if necessary.
932
+
933
+ See Also
934
+ --------
935
+ matrix.flatten : returns a similar output matrix but always a copy
936
+ matrix.flat : a flat iterator on the array.
937
+ numpy.ravel : related function which returns an ndarray
938
+
939
+ """
940
+ return N.ndarray.ravel(self, order=order)
941
+
942
+ @property
943
+ def T(self):
944
+ """
945
+ Returns the transpose of the matrix.
946
+
947
+ Does *not* conjugate! For the complex conjugate transpose, use ``.H``.
948
+
949
+ Parameters
950
+ ----------
951
+ None
952
+
953
+ Returns
954
+ -------
955
+ ret : matrix object
956
+ The (non-conjugated) transpose of the matrix.
957
+
958
+ See Also
959
+ --------
960
+ transpose, getH
961
+
962
+ Examples
963
+ --------
964
+ >>> m = np.matrix('[1, 2; 3, 4]')
965
+ >>> m
966
+ matrix([[1, 2],
967
+ [3, 4]])
968
+ >>> m.getT()
969
+ matrix([[1, 3],
970
+ [2, 4]])
971
+
972
+ """
973
+ return self.transpose()
974
+
975
+ @property
976
+ def H(self):
977
+ """
978
+ Returns the (complex) conjugate transpose of `self`.
979
+
980
+ Equivalent to ``np.transpose(self)`` if `self` is real-valued.
981
+
982
+ Parameters
983
+ ----------
984
+ None
985
+
986
+ Returns
987
+ -------
988
+ ret : matrix object
989
+ complex conjugate transpose of `self`
990
+
991
+ Examples
992
+ --------
993
+ >>> x = np.matrix(np.arange(12).reshape((3,4)))
994
+ >>> z = x - 1j*x; z
995
+ matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j],
996
+ [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j],
997
+ [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]])
998
+ >>> z.getH()
999
+ matrix([[ 0. -0.j, 4. +4.j, 8. +8.j],
1000
+ [ 1. +1.j, 5. +5.j, 9. +9.j],
1001
+ [ 2. +2.j, 6. +6.j, 10.+10.j],
1002
+ [ 3. +3.j, 7. +7.j, 11.+11.j]])
1003
+
1004
+ """
1005
+ if issubclass(self.dtype.type, N.complexfloating):
1006
+ return self.transpose().conjugate()
1007
+ else:
1008
+ return self.transpose()
1009
+
1010
+ # kept for compatibility
1011
+ getT = T.fget
1012
+ getA = A.fget
1013
+ getA1 = A1.fget
1014
+ getH = H.fget
1015
+ getI = I.fget
1016
+
1017
+ def _from_string(str, gdict, ldict):
1018
+ rows = str.split(';')
1019
+ rowtup = []
1020
+ for row in rows:
1021
+ trow = row.split(',')
1022
+ newrow = []
1023
+ for x in trow:
1024
+ newrow.extend(x.split())
1025
+ trow = newrow
1026
+ coltup = []
1027
+ for col in trow:
1028
+ col = col.strip()
1029
+ try:
1030
+ thismat = ldict[col]
1031
+ except KeyError:
1032
+ try:
1033
+ thismat = gdict[col]
1034
+ except KeyError as e:
1035
+ raise NameError(f"name {col!r} is not defined") from None
1036
+
1037
+ coltup.append(thismat)
1038
+ rowtup.append(concatenate(coltup, axis=-1))
1039
+ return concatenate(rowtup, axis=0)
1040
+
1041
+
1042
+ @set_module('numpy')
1043
+ def bmat(obj, ldict=None, gdict=None):
1044
+ """
1045
+ Build a matrix object from a string, nested sequence, or array.
1046
+
1047
+ Parameters
1048
+ ----------
1049
+ obj : str or array_like
1050
+ Input data. If a string, variables in the current scope may be
1051
+ referenced by name.
1052
+ ldict : dict, optional
1053
+ A dictionary that replaces local operands in current frame.
1054
+ Ignored if `obj` is not a string or `gdict` is None.
1055
+ gdict : dict, optional
1056
+ A dictionary that replaces global operands in current frame.
1057
+ Ignored if `obj` is not a string.
1058
+
1059
+ Returns
1060
+ -------
1061
+ out : matrix
1062
+ Returns a matrix object, which is a specialized 2-D array.
1063
+
1064
+ See Also
1065
+ --------
1066
+ block :
1067
+ A generalization of this function for N-d arrays, that returns normal
1068
+ ndarrays.
1069
+
1070
+ Examples
1071
+ --------
1072
+ >>> import numpy as np
1073
+ >>> A = np.asmatrix('1 1; 1 1')
1074
+ >>> B = np.asmatrix('2 2; 2 2')
1075
+ >>> C = np.asmatrix('3 4; 5 6')
1076
+ >>> D = np.asmatrix('7 8; 9 0')
1077
+
1078
+ All the following expressions construct the same block matrix:
1079
+
1080
+ >>> np.bmat([[A, B], [C, D]])
1081
+ matrix([[1, 1, 2, 2],
1082
+ [1, 1, 2, 2],
1083
+ [3, 4, 7, 8],
1084
+ [5, 6, 9, 0]])
1085
+ >>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])
1086
+ matrix([[1, 1, 2, 2],
1087
+ [1, 1, 2, 2],
1088
+ [3, 4, 7, 8],
1089
+ [5, 6, 9, 0]])
1090
+ >>> np.bmat('A,B; C,D')
1091
+ matrix([[1, 1, 2, 2],
1092
+ [1, 1, 2, 2],
1093
+ [3, 4, 7, 8],
1094
+ [5, 6, 9, 0]])
1095
+
1096
+ """
1097
+ if isinstance(obj, str):
1098
+ if gdict is None:
1099
+ # get previous frame
1100
+ frame = sys._getframe().f_back
1101
+ glob_dict = frame.f_globals
1102
+ loc_dict = frame.f_locals
1103
+ else:
1104
+ glob_dict = gdict
1105
+ loc_dict = ldict
1106
+
1107
+ return matrix(_from_string(obj, glob_dict, loc_dict))
1108
+
1109
+ if isinstance(obj, (tuple, list)):
1110
+ # [[A,B],[C,D]]
1111
+ arr_rows = []
1112
+ for row in obj:
1113
+ if isinstance(row, N.ndarray): # not 2-d
1114
+ return matrix(concatenate(obj, axis=-1))
1115
+ else:
1116
+ arr_rows.append(concatenate(row, axis=-1))
1117
+ return matrix(concatenate(arr_rows, axis=0))
1118
+ if isinstance(obj, N.ndarray):
1119
+ return matrix(obj)
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/matrixlib/defmatrix.pyi ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from _typeshed import Incomplete
2
+ from collections.abc import Mapping, Sequence
3
+ from types import EllipsisType
4
+ from typing import Any, ClassVar, Literal as L, Self, SupportsIndex, TypeAlias, overload
5
+ from typing_extensions import TypeVar
6
+
7
+ import numpy as np
8
+ from numpy._typing import (
9
+ ArrayLike,
10
+ DTypeLike,
11
+ NDArray,
12
+ _AnyShape,
13
+ _ArrayLikeInt_co,
14
+ _NestedSequence,
15
+ _ShapeLike,
16
+ )
17
+
18
+ __all__ = ["asmatrix", "bmat", "matrix"]
19
+
20
+ _T = TypeVar("_T")
21
+ _ArrayT = TypeVar("_ArrayT", bound=np.ndarray)
22
+ _BoolOrIntArrayT = TypeVar("_BoolOrIntArrayT", bound=NDArray[np.integer | np.bool])
23
+ _ScalarT = TypeVar("_ScalarT", bound=np.generic)
24
+ _ShapeT_co = TypeVar("_ShapeT_co", bound=_2D, default=_2D, covariant=True)
25
+ _DTypeT_co = TypeVar("_DTypeT_co", bound=np.dtype, default=np.dtype, covariant=True)
26
+
27
+ _2D: TypeAlias = tuple[int, int]
28
+ _Matrix: TypeAlias = matrix[_2D, np.dtype[_ScalarT]]
29
+ _ToIndex1: TypeAlias = slice | EllipsisType | NDArray[np.integer | np.bool] | _NestedSequence[int] | None
30
+ _ToIndex2: TypeAlias = tuple[_ToIndex1, _ToIndex1 | SupportsIndex] | tuple[_ToIndex1 | SupportsIndex, _ToIndex1]
31
+
32
+ class matrix(np.ndarray[_ShapeT_co, _DTypeT_co]):
33
+ __array_priority__: ClassVar[float] = 10.0 # pyright: ignore[reportIncompatibleMethodOverride]
34
+
35
+ def __new__(
36
+ subtype, # pyright: ignore[reportSelfClsParameterName]
37
+ data: ArrayLike,
38
+ dtype: DTypeLike | None = None,
39
+ copy: bool = True,
40
+ ) -> _Matrix[Incomplete]: ...
41
+
42
+ #
43
+ @overload # type: ignore[override]
44
+ def __getitem__(
45
+ self, key: SupportsIndex | _ArrayLikeInt_co | tuple[SupportsIndex | _ArrayLikeInt_co, ...], /
46
+ ) -> Incomplete: ...
47
+ @overload
48
+ def __getitem__(self, key: _ToIndex1 | _ToIndex2, /) -> matrix[_2D, _DTypeT_co]: ...
49
+ @overload
50
+ def __getitem__(self: _Matrix[np.void], key: str, /) -> _Matrix[Incomplete]: ...
51
+ @overload
52
+ def __getitem__(self: _Matrix[np.void], key: list[str], /) -> matrix[_2D, _DTypeT_co]: ... # pyright: ignore[reportIncompatibleMethodOverride]
53
+
54
+ #
55
+ def __mul__(self, other: ArrayLike, /) -> _Matrix[Incomplete]: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
56
+ def __rmul__(self, other: ArrayLike, /) -> _Matrix[Incomplete]: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
57
+
58
+ #
59
+ def __pow__(self, other: ArrayLike, /) -> _Matrix[Incomplete]: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
60
+ def __rpow__(self, other: ArrayLike, /) -> _Matrix[Incomplete]: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
61
+
62
+ # keep in sync with `prod` and `mean`
63
+ @overload # type: ignore[override]
64
+ def sum(self, axis: None = None, dtype: DTypeLike | None = None, out: None = None) -> Incomplete: ...
65
+ @overload
66
+ def sum(self, axis: _ShapeLike, dtype: DTypeLike | None = None, out: None = None) -> _Matrix[Incomplete]: ...
67
+ @overload
68
+ def sum(self, axis: _ShapeLike | None, dtype: DTypeLike | None, out: _ArrayT) -> _ArrayT: ...
69
+ @overload
70
+ def sum(self, axis: _ShapeLike | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride]
71
+
72
+ # keep in sync with `sum` and `mean`
73
+ @overload # type: ignore[override]
74
+ def prod(self, axis: None = None, dtype: DTypeLike | None = None, out: None = None) -> Incomplete: ...
75
+ @overload
76
+ def prod(self, axis: _ShapeLike, dtype: DTypeLike | None = None, out: None = None) -> _Matrix[Incomplete]: ...
77
+ @overload
78
+ def prod(self, axis: _ShapeLike | None, dtype: DTypeLike | None, out: _ArrayT) -> _ArrayT: ...
79
+ @overload
80
+ def prod(self, axis: _ShapeLike | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride]
81
+
82
+ # keep in sync with `sum` and `prod`
83
+ @overload # type: ignore[override]
84
+ def mean(self, axis: None = None, dtype: DTypeLike | None = None, out: None = None) -> Incomplete: ...
85
+ @overload
86
+ def mean(self, axis: _ShapeLike, dtype: DTypeLike | None = None, out: None = None) -> _Matrix[Incomplete]: ...
87
+ @overload
88
+ def mean(self, axis: _ShapeLike | None, dtype: DTypeLike | None, out: _ArrayT) -> _ArrayT: ...
89
+ @overload
90
+ def mean(self, axis: _ShapeLike | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride]
91
+
92
+ # keep in sync with `var`
93
+ @overload # type: ignore[override]
94
+ def std(self, axis: None = None, dtype: DTypeLike | None = None, out: None = None, ddof: float = 0) -> Incomplete: ...
95
+ @overload
96
+ def std(self, axis: _ShapeLike, dtype: DTypeLike | None = None, out: None = None, ddof: float = 0) -> _Matrix[Incomplete]: ...
97
+ @overload
98
+ def std(self, axis: _ShapeLike | None, dtype: DTypeLike | None, out: _ArrayT, ddof: float = 0) -> _ArrayT: ...
99
+ @overload
100
+ def std( # pyright: ignore[reportIncompatibleMethodOverride]
101
+ self, axis: _ShapeLike | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT, ddof: float = 0
102
+ ) -> _ArrayT: ...
103
+
104
+ # keep in sync with `std`
105
+ @overload # type: ignore[override]
106
+ def var(self, axis: None = None, dtype: DTypeLike | None = None, out: None = None, ddof: float = 0) -> Incomplete: ...
107
+ @overload
108
+ def var(self, axis: _ShapeLike, dtype: DTypeLike | None = None, out: None = None, ddof: float = 0) -> _Matrix[Incomplete]: ...
109
+ @overload
110
+ def var(self, axis: _ShapeLike | None, dtype: DTypeLike | None, out: _ArrayT, ddof: float = 0) -> _ArrayT: ...
111
+ @overload
112
+ def var( # pyright: ignore[reportIncompatibleMethodOverride]
113
+ self, axis: _ShapeLike | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT, ddof: float = 0
114
+ ) -> _ArrayT: ...
115
+
116
+ # keep in sync with `all`
117
+ @overload # type: ignore[override]
118
+ def any(self, axis: None = None, out: None = None) -> np.bool: ...
119
+ @overload
120
+ def any(self, axis: _ShapeLike, out: None = None) -> _Matrix[np.bool]: ...
121
+ @overload
122
+ def any(self, axis: _ShapeLike | None, out: _ArrayT) -> _ArrayT: ...
123
+ @overload
124
+ def any(self, axis: _ShapeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride]
125
+
126
+ # keep in sync with `any`
127
+ @overload # type: ignore[override]
128
+ def all(self, axis: None = None, out: None = None) -> np.bool: ...
129
+ @overload
130
+ def all(self, axis: _ShapeLike, out: None = None) -> _Matrix[np.bool]: ...
131
+ @overload
132
+ def all(self, axis: _ShapeLike | None, out: _ArrayT) -> _ArrayT: ...
133
+ @overload
134
+ def all(self, axis: _ShapeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride]
135
+
136
+ # keep in sync with `min` and `ptp`
137
+ @overload # type: ignore[override]
138
+ def max(self: NDArray[_ScalarT], axis: None = None, out: None = None) -> _ScalarT: ...
139
+ @overload
140
+ def max(self, axis: _ShapeLike, out: None = None) -> matrix[_2D, _DTypeT_co]: ...
141
+ @overload
142
+ def max(self, axis: _ShapeLike | None, out: _ArrayT) -> _ArrayT: ...
143
+ @overload
144
+ def max(self, axis: _ShapeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride]
145
+
146
+ # keep in sync with `max` and `ptp`
147
+ @overload # type: ignore[override]
148
+ def min(self: NDArray[_ScalarT], axis: None = None, out: None = None) -> _ScalarT: ...
149
+ @overload
150
+ def min(self, axis: _ShapeLike, out: None = None) -> matrix[_2D, _DTypeT_co]: ...
151
+ @overload
152
+ def min(self, axis: _ShapeLike | None, out: _ArrayT) -> _ArrayT: ...
153
+ @overload
154
+ def min(self, axis: _ShapeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride]
155
+
156
+ # keep in sync with `max` and `min`
157
+ @overload
158
+ def ptp(self: NDArray[_ScalarT], axis: None = None, out: None = None) -> _ScalarT: ...
159
+ @overload
160
+ def ptp(self, axis: _ShapeLike, out: None = None) -> matrix[_2D, _DTypeT_co]: ...
161
+ @overload
162
+ def ptp(self, axis: _ShapeLike | None, out: _ArrayT) -> _ArrayT: ...
163
+ @overload
164
+ def ptp(self, axis: _ShapeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride]
165
+
166
+ # keep in sync with `argmin`
167
+ @overload # type: ignore[override]
168
+ def argmax(self: NDArray[_ScalarT], axis: None = None, out: None = None) -> np.intp: ...
169
+ @overload
170
+ def argmax(self, axis: _ShapeLike, out: None = None) -> _Matrix[np.intp]: ...
171
+ @overload
172
+ def argmax(self, axis: _ShapeLike | None, out: _BoolOrIntArrayT) -> _BoolOrIntArrayT: ...
173
+ @overload
174
+ def argmax(self, axis: _ShapeLike | None = None, *, out: _BoolOrIntArrayT) -> _BoolOrIntArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride]
175
+
176
+ # keep in sync with `argmax`
177
+ @overload # type: ignore[override]
178
+ def argmin(self: NDArray[_ScalarT], axis: None = None, out: None = None) -> np.intp: ...
179
+ @overload
180
+ def argmin(self, axis: _ShapeLike, out: None = None) -> _Matrix[np.intp]: ...
181
+ @overload
182
+ def argmin(self, axis: _ShapeLike | None, out: _BoolOrIntArrayT) -> _BoolOrIntArrayT: ...
183
+ @overload
184
+ def argmin(self, axis: _ShapeLike | None = None, *, out: _BoolOrIntArrayT) -> _BoolOrIntArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride]
185
+
186
+ # the second overload handles the (rare) case that the matrix is not 2-d
187
+ @overload
188
+ def tolist(self: _Matrix[np.generic[_T]]) -> list[list[_T]]: ... # pyright: ignore[reportIncompatibleMethodOverride]
189
+ @overload
190
+ def tolist(self) -> Incomplete: ... # pyright: ignore[reportIncompatibleMethodOverride]
191
+
192
+ # these three methods will at least return a `2-d` array of shape (1, n)
193
+ def squeeze(self, /, axis: _ShapeLike | None = None) -> matrix[_2D, _DTypeT_co]: ...
194
+ def ravel(self, /, order: L["K", "A", "C", "F"] | None = "C") -> matrix[_2D, _DTypeT_co]: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
195
+ def flatten(self, /, order: L["K", "A", "C", "F"] | None = "C") -> matrix[_2D, _DTypeT_co]: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
196
+
197
+ # matrix.T is inherited from _ScalarOrArrayCommon
198
+ def getT(self) -> Self: ...
199
+ @property
200
+ def I(self) -> _Matrix[Incomplete]: ... # noqa: E743
201
+ def getI(self) -> _Matrix[Incomplete]: ...
202
+ @property
203
+ def A(self) -> np.ndarray[_2D, _DTypeT_co]: ...
204
+ def getA(self) -> np.ndarray[_2D, _DTypeT_co]: ...
205
+ @property
206
+ def A1(self) -> np.ndarray[_AnyShape, _DTypeT_co]: ...
207
+ def getA1(self) -> np.ndarray[_AnyShape, _DTypeT_co]: ...
208
+ @property
209
+ def H(self) -> matrix[_2D, _DTypeT_co]: ...
210
+ def getH(self) -> matrix[_2D, _DTypeT_co]: ...
211
+
212
+ def bmat(
213
+ obj: str | Sequence[ArrayLike] | NDArray[Any],
214
+ ldict: Mapping[str, Any] | None = None,
215
+ gdict: Mapping[str, Any] | None = None,
216
+ ) -> _Matrix[Incomplete]: ...
217
+
218
+ def asmatrix(data: ArrayLike, dtype: DTypeLike | None = None) -> _Matrix[Incomplete]: ...
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/__init__.py ADDED
File without changes
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test__all__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import collections
3
+
4
+ import numpy as np
5
+
6
+
7
+ def test_no_duplicates_in_np__all__():
8
+ # Regression test for gh-10198.
9
+ dups = {k: v for k, v in collections.Counter(np.__all__).items() if v > 1}
10
+ assert len(dups) == 0
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_configtool.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.metadata
2
+ import os
3
+ import pathlib
4
+ import subprocess
5
+
6
+ import pytest
7
+
8
+ import numpy as np
9
+ import numpy._core.include
10
+ import numpy._core.lib.pkgconfig
11
+ from numpy.testing import IS_EDITABLE, IS_INSTALLED, IS_WASM, NUMPY_ROOT
12
+
13
+ INCLUDE_DIR = NUMPY_ROOT / '_core' / 'include'
14
+ PKG_CONFIG_DIR = NUMPY_ROOT / '_core' / 'lib' / 'pkgconfig'
15
+
16
+
17
+ @pytest.mark.skipif(not IS_INSTALLED,
18
+ reason="`numpy-config` not expected to be installed")
19
+ @pytest.mark.skipif(IS_WASM,
20
+ reason="wasm interpreter cannot start subprocess")
21
+ class TestNumpyConfig:
22
+ def check_numpyconfig(self, arg):
23
+ p = subprocess.run(['numpy-config', arg], capture_output=True, text=True)
24
+ p.check_returncode()
25
+ return p.stdout.strip()
26
+
27
+ def test_configtool_version(self):
28
+ stdout = self.check_numpyconfig('--version')
29
+ assert stdout == np.__version__
30
+
31
+ def test_configtool_cflags(self):
32
+ stdout = self.check_numpyconfig('--cflags')
33
+ assert f'-I{os.fspath(INCLUDE_DIR)}' in stdout
34
+
35
+ def test_configtool_pkgconfigdir(self):
36
+ stdout = self.check_numpyconfig('--pkgconfigdir')
37
+ assert pathlib.Path(stdout) == PKG_CONFIG_DIR.resolve()
38
+
39
+
40
+ @pytest.mark.skipif(not IS_INSTALLED,
41
+ reason="numpy must be installed to check its entrypoints")
42
+ def test_pkg_config_entrypoint():
43
+ (entrypoint,) = importlib.metadata.entry_points(group='pkg_config', name='numpy')
44
+ assert entrypoint.value == numpy._core.lib.pkgconfig.__name__
45
+
46
+
47
+ @pytest.mark.skipif(not IS_INSTALLED,
48
+ reason="numpy.pc is only available when numpy is installed")
49
+ @pytest.mark.skipif(IS_EDITABLE, reason="editable installs don't have a numpy.pc")
50
+ def test_pkg_config_config_exists():
51
+ assert PKG_CONFIG_DIR.joinpath('numpy.pc').is_file()
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_ctypeslib.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import sysconfig
3
+ import weakref
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+
8
+ import numpy as np
9
+ from numpy.ctypeslib import as_array, load_library, ndpointer
10
+ from numpy.testing import assert_, assert_array_equal, assert_equal, assert_raises
11
+
12
+ try:
13
+ import ctypes
14
+ except ImportError:
15
+ ctypes = None
16
+ else:
17
+ cdll = None
18
+ test_cdll = None
19
+ if hasattr(sys, 'gettotalrefcount'):
20
+ try:
21
+ cdll = load_library(
22
+ '_multiarray_umath_d', np._core._multiarray_umath.__file__
23
+ )
24
+ except OSError:
25
+ pass
26
+ try:
27
+ test_cdll = load_library(
28
+ '_multiarray_tests', np._core._multiarray_tests.__file__
29
+ )
30
+ except OSError:
31
+ pass
32
+ if cdll is None:
33
+ cdll = load_library(
34
+ '_multiarray_umath', np._core._multiarray_umath.__file__)
35
+ if test_cdll is None:
36
+ test_cdll = load_library(
37
+ '_multiarray_tests', np._core._multiarray_tests.__file__
38
+ )
39
+
40
+ c_forward_pointer = test_cdll.forward_pointer
41
+
42
+
43
+ @pytest.mark.skipif(ctypes is None,
44
+ reason="ctypes not available in this python")
45
+ @pytest.mark.skipif(sys.platform == 'cygwin',
46
+ reason="Known to fail on cygwin")
47
+ class TestLoadLibrary:
48
+ def test_basic(self):
49
+ loader_path = np._core._multiarray_umath.__file__
50
+
51
+ out1 = load_library('_multiarray_umath', loader_path)
52
+ out2 = load_library(Path('_multiarray_umath'), loader_path)
53
+ out3 = load_library('_multiarray_umath', Path(loader_path))
54
+ out4 = load_library(b'_multiarray_umath', loader_path)
55
+
56
+ assert isinstance(out1, ctypes.CDLL)
57
+ assert out1 is out2 is out3 is out4
58
+
59
+ def test_basic2(self):
60
+ # Regression for #801: load_library with a full library name
61
+ # (including extension) does not work.
62
+ try:
63
+ so_ext = sysconfig.get_config_var('EXT_SUFFIX')
64
+ load_library(f'_multiarray_umath{so_ext}',
65
+ np._core._multiarray_umath.__file__)
66
+ except ImportError as e:
67
+ msg = ("ctypes is not available on this python: skipping the test"
68
+ " (import error was: %s)" % str(e))
69
+ print(msg)
70
+
71
+
72
+ class TestNdpointer:
73
+ def test_dtype(self):
74
+ dt = np.intc
75
+ p = ndpointer(dtype=dt)
76
+ assert_(p.from_param(np.array([1], dt)))
77
+ dt = '<i4'
78
+ p = ndpointer(dtype=dt)
79
+ assert_(p.from_param(np.array([1], dt)))
80
+ dt = np.dtype('>i4')
81
+ p = ndpointer(dtype=dt)
82
+ p.from_param(np.array([1], dt))
83
+ assert_raises(TypeError, p.from_param,
84
+ np.array([1], dt.newbyteorder('swap')))
85
+ dtnames = ['x', 'y']
86
+ dtformats = [np.intc, np.float64]
87
+ dtdescr = {'names': dtnames, 'formats': dtformats}
88
+ dt = np.dtype(dtdescr)
89
+ p = ndpointer(dtype=dt)
90
+ assert_(p.from_param(np.zeros((10,), dt)))
91
+ samedt = np.dtype(dtdescr)
92
+ p = ndpointer(dtype=samedt)
93
+ assert_(p.from_param(np.zeros((10,), dt)))
94
+ dt2 = np.dtype(dtdescr, align=True)
95
+ if dt.itemsize != dt2.itemsize:
96
+ assert_raises(TypeError, p.from_param, np.zeros((10,), dt2))
97
+ else:
98
+ assert_(p.from_param(np.zeros((10,), dt2)))
99
+
100
+ def test_ndim(self):
101
+ p = ndpointer(ndim=0)
102
+ assert_(p.from_param(np.array(1)))
103
+ assert_raises(TypeError, p.from_param, np.array([1]))
104
+ p = ndpointer(ndim=1)
105
+ assert_raises(TypeError, p.from_param, np.array(1))
106
+ assert_(p.from_param(np.array([1])))
107
+ p = ndpointer(ndim=2)
108
+ assert_(p.from_param(np.array([[1]])))
109
+
110
+ def test_shape(self):
111
+ p = ndpointer(shape=(1, 2))
112
+ assert_(p.from_param(np.array([[1, 2]])))
113
+ assert_raises(TypeError, p.from_param, np.array([[1], [2]]))
114
+ p = ndpointer(shape=())
115
+ assert_(p.from_param(np.array(1)))
116
+
117
+ def test_flags(self):
118
+ x = np.array([[1, 2], [3, 4]], order='F')
119
+ p = ndpointer(flags='FORTRAN')
120
+ assert_(p.from_param(x))
121
+ p = ndpointer(flags='CONTIGUOUS')
122
+ assert_raises(TypeError, p.from_param, x)
123
+ p = ndpointer(flags=x.flags.num)
124
+ assert_(p.from_param(x))
125
+ assert_raises(TypeError, p.from_param, np.array([[1, 2], [3, 4]]))
126
+
127
+ @pytest.mark.thread_unsafe(reason="checks that global ndpointer cache is updating")
128
+ def test_cache(self):
129
+ assert_(ndpointer(dtype=np.float64) is ndpointer(dtype=np.float64))
130
+
131
+ # shapes are normalized
132
+ assert_(ndpointer(shape=2) is ndpointer(shape=(2,)))
133
+
134
+ # 1.12 <= v < 1.16 had a bug that made these fail
135
+ assert_(ndpointer(shape=2) is not ndpointer(ndim=2))
136
+ assert_(ndpointer(ndim=2) is not ndpointer(shape=2))
137
+
138
+ @pytest.mark.skipif(ctypes is None,
139
+ reason="ctypes not available on this python installation")
140
+ class TestNdpointerCFunc:
141
+ def test_arguments(self):
142
+ """ Test that arguments are coerced from arrays """
143
+ c_forward_pointer.restype = ctypes.c_void_p
144
+ c_forward_pointer.argtypes = (ndpointer(ndim=2),)
145
+
146
+ c_forward_pointer(np.zeros((2, 3)))
147
+ # too many dimensions
148
+ assert_raises(
149
+ ctypes.ArgumentError, c_forward_pointer, np.zeros((2, 3, 4)))
150
+
151
+ @pytest.mark.parametrize(
152
+ 'dt', [
153
+ float,
154
+ np.dtype({
155
+ 'formats': ['<i4', '<i4'],
156
+ 'names': ['a', 'b'],
157
+ 'offsets': [0, 2],
158
+ 'itemsize': 6
159
+ })
160
+ ], ids=[
161
+ 'float',
162
+ 'overlapping-fields'
163
+ ]
164
+ )
165
+ def test_return(self, dt):
166
+ """ Test that return values are coerced to arrays """
167
+ arr = np.zeros((2, 3), dt)
168
+ ptr_type = ndpointer(shape=arr.shape, dtype=arr.dtype)
169
+
170
+ c_forward_pointer.restype = ptr_type
171
+ c_forward_pointer.argtypes = (ptr_type,)
172
+
173
+ # check that the arrays are equivalent views on the same data
174
+ arr2 = c_forward_pointer(arr)
175
+ assert_equal(arr2.dtype, arr.dtype)
176
+ assert_equal(arr2.shape, arr.shape)
177
+ assert_equal(
178
+ arr2.__array_interface__['data'],
179
+ arr.__array_interface__['data']
180
+ )
181
+
182
+ @pytest.mark.thread_unsafe(reason="mutates global test vars")
183
+ def test_vague_return_value(self):
184
+ """ Test that vague ndpointer return values do not promote to arrays """
185
+ arr = np.zeros((2, 3))
186
+ ptr_type = ndpointer(dtype=arr.dtype)
187
+
188
+ c_forward_pointer.restype = ptr_type
189
+ c_forward_pointer.argtypes = (ptr_type,)
190
+
191
+ ret = c_forward_pointer(arr)
192
+ assert_(isinstance(ret, ptr_type))
193
+
194
+
195
+ @pytest.mark.skipif(ctypes is None,
196
+ reason="ctypes not available on this python installation")
197
+ class TestAsArray:
198
+ def test_array(self):
199
+ from ctypes import c_int
200
+
201
+ pair_t = c_int * 2
202
+ a = as_array(pair_t(1, 2))
203
+ assert_equal(a.shape, (2,))
204
+ assert_array_equal(a, np.array([1, 2]))
205
+ a = as_array((pair_t * 3)(pair_t(1, 2), pair_t(3, 4), pair_t(5, 6)))
206
+ assert_equal(a.shape, (3, 2))
207
+ assert_array_equal(a, np.array([[1, 2], [3, 4], [5, 6]]))
208
+
209
+ def test_pointer(self):
210
+ from ctypes import POINTER, c_int, cast
211
+
212
+ p = cast((c_int * 10)(*range(10)), POINTER(c_int))
213
+
214
+ a = as_array(p, shape=(10,))
215
+ assert_equal(a.shape, (10,))
216
+ assert_array_equal(a, np.arange(10))
217
+
218
+ a = as_array(p, shape=(2, 5))
219
+ assert_equal(a.shape, (2, 5))
220
+ assert_array_equal(a, np.arange(10).reshape((2, 5)))
221
+
222
+ # shape argument is required
223
+ assert_raises(TypeError, as_array, p)
224
+
225
+ @pytest.mark.skipif(
226
+ sys.version_info[:2] == (3, 12),
227
+ reason="Broken in 3.12.0rc1, see gh-24399",
228
+ )
229
+ def test_struct_array_pointer(self):
230
+ from ctypes import Structure, c_int16, pointer
231
+
232
+ class Struct(Structure):
233
+ _fields_ = [('a', c_int16)]
234
+
235
+ Struct3 = 3 * Struct
236
+
237
+ c_array = (2 * Struct3)(
238
+ Struct3(Struct(a=1), Struct(a=2), Struct(a=3)),
239
+ Struct3(Struct(a=4), Struct(a=5), Struct(a=6))
240
+ )
241
+
242
+ expected = np.array([
243
+ [(1,), (2,), (3,)],
244
+ [(4,), (5,), (6,)],
245
+ ], dtype=[('a', np.int16)])
246
+
247
+ def check(x):
248
+ assert_equal(x.dtype, expected.dtype)
249
+ assert_equal(x, expected)
250
+
251
+ # all of these should be equivalent
252
+ check(as_array(c_array))
253
+ check(as_array(pointer(c_array), shape=()))
254
+ check(as_array(pointer(c_array[0]), shape=(2,)))
255
+ check(as_array(pointer(c_array[0][0]), shape=(2, 3)))
256
+
257
+ @pytest.mark.thread_unsafe(reason="garbage collector is global state")
258
+ def test_reference_cycles(self):
259
+ # related to gh-6511
260
+ import ctypes
261
+
262
+ # create array to work with
263
+ # don't use int/long to avoid running into bpo-10746
264
+ N = 100
265
+ a = np.arange(N, dtype=np.short)
266
+
267
+ # get pointer to array
268
+ pnt = np.ctypeslib.as_ctypes(a)
269
+
270
+ with np.testing.assert_no_gc_cycles():
271
+ # decay the array above to a pointer to its first element
272
+ newpnt = ctypes.cast(pnt, ctypes.POINTER(ctypes.c_short))
273
+ # and construct an array using this data
274
+ b = np.ctypeslib.as_array(newpnt, (N,))
275
+ # now delete both, which should cleanup both objects
276
+ del newpnt, b
277
+
278
+ def test_segmentation_fault(self):
279
+ arr = np.zeros((224, 224, 3))
280
+ c_arr = np.ctypeslib.as_ctypes(arr)
281
+ arr_ref = weakref.ref(arr)
282
+ del arr
283
+
284
+ # check the reference wasn't cleaned up
285
+ assert_(arr_ref() is not None)
286
+
287
+ # check we avoid the segfault
288
+ c_arr[0][0][0]
289
+
290
+
291
+ @pytest.mark.skipif(ctypes is None,
292
+ reason="ctypes not available on this python installation")
293
+ class TestAsCtypesType:
294
+ """ Test conversion from dtypes to ctypes types """
295
+ def test_scalar(self):
296
+ dt = np.dtype('<u2')
297
+ ct = np.ctypeslib.as_ctypes_type(dt)
298
+ assert_equal(ct, ctypes.c_uint16.__ctype_le__)
299
+
300
+ dt = np.dtype('>u2')
301
+ ct = np.ctypeslib.as_ctypes_type(dt)
302
+ assert_equal(ct, ctypes.c_uint16.__ctype_be__)
303
+
304
+ dt = np.dtype('u2')
305
+ ct = np.ctypeslib.as_ctypes_type(dt)
306
+ assert_equal(ct, ctypes.c_uint16)
307
+
308
+ @pytest.mark.thread_unsafe(reason="some sort of data race? (gh-29943)")
309
+ def test_subarray(self):
310
+ dt = np.dtype((np.int32, (2, 3)))
311
+ ct = np.ctypeslib.as_ctypes_type(dt)
312
+ assert_equal(ct, 2 * (3 * ctypes.c_int32))
313
+
314
+ def test_structure(self):
315
+ dt = np.dtype([
316
+ ('a', np.uint16),
317
+ ('b', np.uint32),
318
+ ])
319
+
320
+ ct = np.ctypeslib.as_ctypes_type(dt)
321
+ assert_(issubclass(ct, ctypes.Structure))
322
+ assert_equal(ctypes.sizeof(ct), dt.itemsize)
323
+ assert_equal(ct._fields_, [
324
+ ('a', ctypes.c_uint16),
325
+ ('b', ctypes.c_uint32),
326
+ ])
327
+
328
+ @pytest.mark.thread_unsafe(reason="some sort of data race? (gh-29943)")
329
+ def test_structure_aligned(self):
330
+ dt = np.dtype([
331
+ ('a', np.uint16),
332
+ ('b', np.uint32),
333
+ ], align=True)
334
+
335
+ ct = np.ctypeslib.as_ctypes_type(dt)
336
+ assert_(issubclass(ct, ctypes.Structure))
337
+ assert_equal(ctypes.sizeof(ct), dt.itemsize)
338
+ assert_equal(ct._fields_, [
339
+ ('a', ctypes.c_uint16),
340
+ ('', ctypes.c_char * 2), # padding
341
+ ('b', ctypes.c_uint32),
342
+ ])
343
+
344
+ def test_union(self):
345
+ dt = np.dtype({
346
+ 'names': ['a', 'b'],
347
+ 'offsets': [0, 0],
348
+ 'formats': [np.uint16, np.uint32]
349
+ })
350
+
351
+ ct = np.ctypeslib.as_ctypes_type(dt)
352
+ assert_(issubclass(ct, ctypes.Union))
353
+ assert_equal(ctypes.sizeof(ct), dt.itemsize)
354
+ assert_equal(ct._fields_, [
355
+ ('a', ctypes.c_uint16),
356
+ ('b', ctypes.c_uint32),
357
+ ])
358
+
359
+ @pytest.mark.thread_unsafe(reason="some sort of data race? (gh-29943)")
360
+ def test_padded_union(self):
361
+ dt = np.dtype({
362
+ 'names': ['a', 'b'],
363
+ 'offsets': [0, 0],
364
+ 'formats': [np.uint16, np.uint32],
365
+ 'itemsize': 5,
366
+ })
367
+
368
+ ct = np.ctypeslib.as_ctypes_type(dt)
369
+ assert_(issubclass(ct, ctypes.Union))
370
+ assert_equal(ctypes.sizeof(ct), dt.itemsize)
371
+ assert_equal(ct._fields_, [
372
+ ('a', ctypes.c_uint16),
373
+ ('b', ctypes.c_uint32),
374
+ ('', ctypes.c_char * 5), # padding
375
+ ])
376
+
377
+ def test_overlapping(self):
378
+ dt = np.dtype({
379
+ 'names': ['a', 'b'],
380
+ 'offsets': [0, 2],
381
+ 'formats': [np.uint32, np.uint32]
382
+ })
383
+ assert_raises(NotImplementedError, np.ctypeslib.as_ctypes_type, dt)
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_lazyloading.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+ import textwrap
4
+
5
+ import pytest
6
+
7
+ from numpy.testing import IS_WASM
8
+
9
+
10
+ @pytest.mark.skipif(IS_WASM, reason="can't start subprocess")
11
+ def test_lazy_load():
12
+ # gh-22045. lazyload doesn't import submodule names into the namespace
13
+
14
+ # Test within a new process, to ensure that we do not mess with the
15
+ # global state during the test run (could lead to cryptic test failures).
16
+ # This is generally unsafe, especially, since we also reload the C-modules.
17
+ code = textwrap.dedent(r"""
18
+ import sys
19
+ from importlib.util import LazyLoader, find_spec, module_from_spec
20
+
21
+ # create lazy load of numpy as np
22
+ spec = find_spec("numpy")
23
+ module = module_from_spec(spec)
24
+ sys.modules["numpy"] = module
25
+ loader = LazyLoader(spec.loader)
26
+ loader.exec_module(module)
27
+ np = module
28
+
29
+ # test a subpackage import
30
+ from numpy.lib import recfunctions # noqa: F401
31
+
32
+ # test triggering the import of the package
33
+ np.ndarray
34
+ """)
35
+ p = subprocess.run(
36
+ (sys.executable, '-c', code),
37
+ stdout=subprocess.PIPE,
38
+ stderr=subprocess.STDOUT,
39
+ encoding='utf-8',
40
+ check=False,
41
+ )
42
+ assert p.returncode == 0, p.stdout
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_matlib.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import numpy.matlib
3
+ from numpy.testing import assert_, assert_array_equal
4
+
5
+
6
+ def test_empty():
7
+ x = numpy.matlib.empty((2,))
8
+ assert_(isinstance(x, np.matrix))
9
+ assert_(x.shape, (1, 2))
10
+
11
+ def test_ones():
12
+ assert_array_equal(numpy.matlib.ones((2, 3)),
13
+ np.matrix([[ 1., 1., 1.],
14
+ [ 1., 1., 1.]]))
15
+
16
+ assert_array_equal(numpy.matlib.ones(2), np.matrix([[ 1., 1.]]))
17
+
18
+ def test_zeros():
19
+ assert_array_equal(numpy.matlib.zeros((2, 3)),
20
+ np.matrix([[ 0., 0., 0.],
21
+ [ 0., 0., 0.]]))
22
+
23
+ assert_array_equal(numpy.matlib.zeros(2), np.matrix([[0., 0.]]))
24
+
25
+ def test_identity():
26
+ x = numpy.matlib.identity(2, dtype=int)
27
+ assert_array_equal(x, np.matrix([[1, 0], [0, 1]]))
28
+
29
+ def test_eye():
30
+ xc = numpy.matlib.eye(3, k=1, dtype=int)
31
+ assert_array_equal(xc, np.matrix([[ 0, 1, 0],
32
+ [ 0, 0, 1],
33
+ [ 0, 0, 0]]))
34
+ assert xc.flags.c_contiguous
35
+ assert not xc.flags.f_contiguous
36
+
37
+ xf = numpy.matlib.eye(3, 4, dtype=int, order='F')
38
+ assert_array_equal(xf, np.matrix([[ 1, 0, 0, 0],
39
+ [ 0, 1, 0, 0],
40
+ [ 0, 0, 1, 0]]))
41
+ assert not xf.flags.c_contiguous
42
+ assert xf.flags.f_contiguous
43
+
44
+ def test_rand():
45
+ x = numpy.matlib.rand(3)
46
+ # check matrix type, array would have shape (3,)
47
+ assert_(x.ndim == 2)
48
+
49
+ def test_randn():
50
+ x = np.matlib.randn(3)
51
+ # check matrix type, array would have shape (3,)
52
+ assert_(x.ndim == 2)
53
+
54
+ def test_repmat():
55
+ a1 = np.arange(4)
56
+ x = numpy.matlib.repmat(a1, 2, 2)
57
+ y = np.array([[0, 1, 2, 3, 0, 1, 2, 3],
58
+ [0, 1, 2, 3, 0, 1, 2, 3]])
59
+ assert_array_equal(x, y)
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_numpy_config.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Check the numpy config is valid.
3
+ """
4
+ from unittest.mock import patch
5
+
6
+ import pytest
7
+
8
+ import numpy as np
9
+
10
+ pytestmark = pytest.mark.skipif(
11
+ not hasattr(np.__config__, "_built_with_meson"),
12
+ reason="Requires Meson builds",
13
+ )
14
+
15
+
16
+ class TestNumPyConfigs:
17
+ REQUIRED_CONFIG_KEYS = [
18
+ "Compilers",
19
+ "Machine Information",
20
+ "Python Information",
21
+ ]
22
+
23
+ @patch("numpy.__config__._check_pyyaml")
24
+ @pytest.mark.thread_unsafe(reason="unittest.mock.patch updates global state")
25
+ def test_pyyaml_not_found(self, mock_yaml_importer):
26
+ mock_yaml_importer.side_effect = ModuleNotFoundError()
27
+ with pytest.warns(UserWarning):
28
+ np.show_config()
29
+
30
+ def test_dict_mode(self):
31
+ config = np.show_config(mode="dicts")
32
+
33
+ assert isinstance(config, dict)
34
+ assert all(key in config for key in self.REQUIRED_CONFIG_KEYS), (
35
+ "Required key missing,"
36
+ " see index of `False` with `REQUIRED_CONFIG_KEYS`"
37
+ )
38
+
39
+ def test_invalid_mode(self):
40
+ with pytest.raises(AttributeError):
41
+ np.show_config(mode="foo")
42
+
43
+ def test_warn_to_add_tests(self):
44
+ assert len(np.__config__.DisplayModes) == 2, (
45
+ "New mode detected,"
46
+ " please add UT if applicable and increment this count"
47
+ )
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_numpy_version.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Check the numpy version is valid.
3
+
4
+ Note that a development version is marked by the presence of 'dev0' or '+'
5
+ in the version string, all else is treated as a release. The version string
6
+ itself is set from the output of ``git describe`` which relies on tags.
7
+
8
+ Examples
9
+ --------
10
+
11
+ Valid Development: 1.22.0.dev0 1.22.0.dev0+5-g7999db4df2 1.22.0+5-g7999db4df2
12
+ Valid Release: 1.21.0.rc1, 1.21.0.b1, 1.21.0
13
+ Invalid: 1.22.0.dev, 1.22.0.dev0-5-g7999db4dfB, 1.21.0.d1, 1.21.a
14
+
15
+ Note that a release is determined by the version string, which in turn
16
+ is controlled by the result of the ``git describe`` command.
17
+ """
18
+ import re
19
+
20
+ import numpy as np
21
+ from numpy.testing import assert_
22
+
23
+
24
+ def test_valid_numpy_version():
25
+ # Verify that the numpy version is a valid one (no .post suffix or other
26
+ # nonsense). See gh-6431 for an issue caused by an invalid version.
27
+ version_pattern = r"^[0-9]+\.[0-9]+\.[0-9]+(a[0-9]|b[0-9]|rc[0-9])?"
28
+ dev_suffix = r"(\.dev[0-9]+(\+git[0-9]+\.[0-9a-f]+)?)?"
29
+ res = re.match(version_pattern + dev_suffix + '$', np.__version__)
30
+
31
+ assert_(res is not None, np.__version__)
32
+
33
+
34
+ def test_short_version():
35
+ # Check numpy.short_version actually exists
36
+ if np.version.release:
37
+ assert_(np.__version__ == np.version.short_version,
38
+ "short_version mismatch in release version")
39
+ else:
40
+ assert_(np.__version__.split("+")[0] == np.version.short_version,
41
+ "short_version mismatch in development version")
42
+
43
+
44
+ def test_version_module():
45
+ contents = {s for s in dir(np.version) if not s.startswith('_')}
46
+ expected = {
47
+ 'full_version',
48
+ 'git_revision',
49
+ 'release',
50
+ 'short_version',
51
+ 'version',
52
+ }
53
+
54
+ assert contents == expected
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_public_api.py ADDED
@@ -0,0 +1,807 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import importlib
3
+ import inspect
4
+ import pkgutil
5
+ import subprocess
6
+ import sys
7
+ import sysconfig
8
+ import types
9
+ import warnings
10
+
11
+ import pytest
12
+
13
+ import numpy
14
+ import numpy as np
15
+ from numpy.testing import IS_WASM
16
+
17
+ try:
18
+ import ctypes
19
+ except ImportError:
20
+ ctypes = None
21
+
22
+
23
+ def check_dir(module, module_name=None):
24
+ """Returns a mapping of all objects with the wrong __module__ attribute."""
25
+ if module_name is None:
26
+ module_name = module.__name__
27
+ results = {}
28
+ for name in dir(module):
29
+ if name == "core":
30
+ continue
31
+ item = getattr(module, name)
32
+ if (hasattr(item, '__module__') and hasattr(item, '__name__')
33
+ and item.__module__ != module_name):
34
+ results[name] = item.__module__ + '.' + item.__name__
35
+ return results
36
+
37
+
38
+ def test_numpy_namespace():
39
+ # We override dir to not show these members
40
+ allowlist = {
41
+ 'recarray': 'numpy.rec.recarray',
42
+ }
43
+ bad_results = check_dir(np)
44
+ # pytest gives better error messages with the builtin assert than with
45
+ # assert_equal
46
+ assert bad_results == allowlist
47
+
48
+
49
+ @pytest.mark.skipif(IS_WASM, reason="can't start subprocess")
50
+ @pytest.mark.parametrize('name', ['testing'])
51
+ def test_import_lazy_import(name):
52
+ """Make sure we can actually use the modules we lazy load.
53
+
54
+ While not exported as part of the public API, it was accessible. With the
55
+ use of __getattr__ and __dir__, this isn't always true It can happen that
56
+ an infinite recursion may happen.
57
+
58
+ This is the only way I found that would force the failure to appear on the
59
+ badly implemented code.
60
+
61
+ We also test for the presence of the lazily imported modules in dir
62
+
63
+ """
64
+ exe = (sys.executable, '-c', "import numpy; numpy." + name)
65
+ result = subprocess.check_output(exe)
66
+ assert not result
67
+
68
+ # Make sure they are still in the __dir__
69
+ assert name in dir(np)
70
+
71
+
72
+ def test_dir_testing():
73
+ """Assert that output of dir has only one "testing/tester"
74
+ attribute without duplicate"""
75
+ assert len(dir(np)) == len(set(dir(np)))
76
+
77
+
78
+ def test_numpy_linalg():
79
+ bad_results = check_dir(np.linalg)
80
+ assert bad_results == {}
81
+
82
+
83
+ def test_numpy_fft():
84
+ bad_results = check_dir(np.fft)
85
+ assert bad_results == {}
86
+
87
+
88
+ @pytest.mark.skipif(ctypes is None,
89
+ reason="ctypes not available in this python")
90
+ def test_NPY_NO_EXPORT():
91
+ cdll = ctypes.CDLL(np._core._multiarray_tests.__file__)
92
+ # Make sure an arbitrary NPY_NO_EXPORT function is actually hidden
93
+ f = getattr(cdll, 'test_not_exported', None)
94
+ assert f is None, ("'test_not_exported' is mistakenly exported, "
95
+ "NPY_NO_EXPORT does not work")
96
+
97
+
98
+ # Historically NumPy has not used leading underscores for private submodules
99
+ # much. This has resulted in lots of things that look like public modules
100
+ # (i.e. things that can be imported as `import numpy.somesubmodule.somefile`),
101
+ # but were never intended to be public. The PUBLIC_MODULES list contains
102
+ # modules that are either public because they were meant to be, or because they
103
+ # contain public functions/objects that aren't present in any other namespace
104
+ # for whatever reason and therefore should be treated as public.
105
+ #
106
+ # The PRIVATE_BUT_PRESENT_MODULES list contains modules that look public (lack
107
+ # of underscores) but should not be used. For many of those modules the
108
+ # current status is fine. For others it may make sense to work on making them
109
+ # private, to clean up our public API and avoid confusion.
110
+ PUBLIC_MODULES = ['numpy.' + s for s in [
111
+ "ctypeslib",
112
+ "dtypes",
113
+ "exceptions",
114
+ "f2py",
115
+ "fft",
116
+ "lib",
117
+ "lib.array_utils",
118
+ "lib.format",
119
+ "lib.introspect",
120
+ "lib.mixins",
121
+ "lib.npyio",
122
+ "lib.recfunctions", # note: still needs cleaning, was forgotten for 2.0
123
+ "lib.scimath",
124
+ "lib.stride_tricks",
125
+ "linalg",
126
+ "ma",
127
+ "ma.extras",
128
+ "ma.mrecords",
129
+ "polynomial",
130
+ "polynomial.chebyshev",
131
+ "polynomial.hermite",
132
+ "polynomial.hermite_e",
133
+ "polynomial.laguerre",
134
+ "polynomial.legendre",
135
+ "polynomial.polynomial",
136
+ "random",
137
+ "strings",
138
+ "testing",
139
+ "testing.overrides",
140
+ "typing",
141
+ "typing.mypy_plugin",
142
+ "version",
143
+ ]]
144
+ if sys.version_info < (3, 12):
145
+ PUBLIC_MODULES += [
146
+ 'numpy.' + s for s in [
147
+ "distutils",
148
+ "distutils.cpuinfo",
149
+ "distutils.exec_command",
150
+ "distutils.misc_util",
151
+ "distutils.log",
152
+ "distutils.system_info",
153
+ ]
154
+ ]
155
+
156
+
157
+ PUBLIC_ALIASED_MODULES = [
158
+ "numpy.char",
159
+ "numpy.emath",
160
+ "numpy.rec",
161
+ ]
162
+
163
+
164
+ PRIVATE_BUT_PRESENT_MODULES = ['numpy.' + s for s in [
165
+ "conftest",
166
+ "core",
167
+ "core.multiarray",
168
+ "core.numeric",
169
+ "core.umath",
170
+ "core.arrayprint",
171
+ "core.defchararray",
172
+ "core.einsumfunc",
173
+ "core.fromnumeric",
174
+ "core.function_base",
175
+ "core.getlimits",
176
+ "core.numerictypes",
177
+ "core.overrides",
178
+ "core.records",
179
+ "core.shape_base",
180
+ "f2py.auxfuncs",
181
+ "f2py.capi_maps",
182
+ "f2py.cb_rules",
183
+ "f2py.cfuncs",
184
+ "f2py.common_rules",
185
+ "f2py.crackfortran",
186
+ "f2py.diagnose",
187
+ "f2py.f2py2e",
188
+ "f2py.f90mod_rules",
189
+ "f2py.func2subr",
190
+ "f2py.rules",
191
+ "f2py.symbolic",
192
+ "f2py.use_rules",
193
+ "lib.user_array", # note: not in np.lib, but probably should just be deleted
194
+ "linalg.lapack_lite",
195
+ "ma.core",
196
+ "ma.testutils",
197
+ "matlib",
198
+ "matrixlib",
199
+ "matrixlib.defmatrix",
200
+ "polynomial.polyutils",
201
+ "random.mtrand",
202
+ "random.bit_generator",
203
+ "testing.print_coercion_tables",
204
+ ]]
205
+ if sys.version_info < (3, 12):
206
+ PRIVATE_BUT_PRESENT_MODULES += [
207
+ 'numpy.' + s for s in [
208
+ "distutils.armccompiler",
209
+ "distutils.fujitsuccompiler",
210
+ "distutils.ccompiler",
211
+ 'distutils.ccompiler_opt',
212
+ "distutils.command",
213
+ "distutils.command.autodist",
214
+ "distutils.command.bdist_rpm",
215
+ "distutils.command.build",
216
+ "distutils.command.build_clib",
217
+ "distutils.command.build_ext",
218
+ "distutils.command.build_py",
219
+ "distutils.command.build_scripts",
220
+ "distutils.command.build_src",
221
+ "distutils.command.config",
222
+ "distutils.command.config_compiler",
223
+ "distutils.command.develop",
224
+ "distutils.command.egg_info",
225
+ "distutils.command.install",
226
+ "distutils.command.install_clib",
227
+ "distutils.command.install_data",
228
+ "distutils.command.install_headers",
229
+ "distutils.command.sdist",
230
+ "distutils.conv_template",
231
+ "distutils.core",
232
+ "distutils.extension",
233
+ "distutils.fcompiler",
234
+ "distutils.fcompiler.absoft",
235
+ "distutils.fcompiler.arm",
236
+ "distutils.fcompiler.compaq",
237
+ "distutils.fcompiler.environment",
238
+ "distutils.fcompiler.g95",
239
+ "distutils.fcompiler.gnu",
240
+ "distutils.fcompiler.hpux",
241
+ "distutils.fcompiler.ibm",
242
+ "distutils.fcompiler.intel",
243
+ "distutils.fcompiler.lahey",
244
+ "distutils.fcompiler.mips",
245
+ "distutils.fcompiler.nag",
246
+ "distutils.fcompiler.none",
247
+ "distutils.fcompiler.pathf95",
248
+ "distutils.fcompiler.pg",
249
+ "distutils.fcompiler.nv",
250
+ "distutils.fcompiler.sun",
251
+ "distutils.fcompiler.vast",
252
+ "distutils.fcompiler.fujitsu",
253
+ "distutils.from_template",
254
+ "distutils.intelccompiler",
255
+ "distutils.lib2def",
256
+ "distutils.line_endings",
257
+ "distutils.mingw32ccompiler",
258
+ "distutils.msvccompiler",
259
+ "distutils.npy_pkg_config",
260
+ "distutils.numpy_distribution",
261
+ "distutils.pathccompiler",
262
+ "distutils.unixccompiler",
263
+ ]
264
+ ]
265
+
266
+
267
+ def is_unexpected(name):
268
+ """Check if this needs to be considered."""
269
+ return (
270
+ '._' not in name and '.tests' not in name and '.setup' not in name
271
+ and name not in PUBLIC_MODULES
272
+ and name not in PUBLIC_ALIASED_MODULES
273
+ and name not in PRIVATE_BUT_PRESENT_MODULES
274
+ )
275
+
276
+
277
+ if sys.version_info >= (3, 12):
278
+ SKIP_LIST = []
279
+ else:
280
+ SKIP_LIST = ["numpy.distutils.msvc9compiler"]
281
+
282
+
283
+ def test_all_modules_are_expected():
284
+ """
285
+ Test that we don't add anything that looks like a new public module by
286
+ accident. Check is based on filenames.
287
+ """
288
+
289
+ modnames = []
290
+ for _, modname, ispkg in pkgutil.walk_packages(path=np.__path__,
291
+ prefix=np.__name__ + '.',
292
+ onerror=None):
293
+ if is_unexpected(modname) and modname not in SKIP_LIST:
294
+ # We have a name that is new. If that's on purpose, add it to
295
+ # PUBLIC_MODULES. We don't expect to have to add anything to
296
+ # PRIVATE_BUT_PRESENT_MODULES. Use an underscore in the name!
297
+ modnames.append(modname)
298
+
299
+ if modnames:
300
+ raise AssertionError(f'Found unexpected modules: {modnames}')
301
+
302
+
303
+ # Stuff that clearly shouldn't be in the API and is detected by the next test
304
+ # below
305
+ SKIP_LIST_2 = [
306
+ 'numpy.lib.math',
307
+ 'numpy.matlib.char',
308
+ 'numpy.matlib.rec',
309
+ 'numpy.matlib.emath',
310
+ 'numpy.matlib.exceptions',
311
+ 'numpy.matlib.math',
312
+ 'numpy.matlib.linalg',
313
+ 'numpy.matlib.fft',
314
+ 'numpy.matlib.random',
315
+ 'numpy.matlib.ctypeslib',
316
+ 'numpy.matlib.ma',
317
+ ]
318
+ if sys.version_info < (3, 12):
319
+ SKIP_LIST_2 += [
320
+ 'numpy.distutils.log.sys',
321
+ 'numpy.distutils.log.logging',
322
+ 'numpy.distutils.log.warnings',
323
+ ]
324
+
325
+
326
+ def test_all_modules_are_expected_2():
327
+ """
328
+ Method checking all objects. The pkgutil-based method in
329
+ `test_all_modules_are_expected` does not catch imports into a namespace,
330
+ only filenames. So this test is more thorough, and checks this like:
331
+
332
+ import .lib.scimath as emath
333
+
334
+ To check if something in a module is (effectively) public, one can check if
335
+ there's anything in that namespace that's a public function/object but is
336
+ not exposed in a higher-level namespace. For example for a `numpy.lib`
337
+ submodule::
338
+
339
+ mod = np.lib.mixins
340
+ for obj in mod.__all__:
341
+ if obj in np.__all__:
342
+ continue
343
+ elif obj in np.lib.__all__:
344
+ continue
345
+
346
+ else:
347
+ print(obj)
348
+
349
+ """
350
+
351
+ def find_unexpected_members(mod_name):
352
+ members = []
353
+ module = importlib.import_module(mod_name)
354
+ if hasattr(module, '__all__'):
355
+ objnames = module.__all__
356
+ else:
357
+ objnames = dir(module)
358
+
359
+ for objname in objnames:
360
+ if not objname.startswith('_'):
361
+ fullobjname = mod_name + '.' + objname
362
+ if isinstance(getattr(module, objname), types.ModuleType):
363
+ if is_unexpected(fullobjname):
364
+ if fullobjname not in SKIP_LIST_2:
365
+ members.append(fullobjname)
366
+
367
+ return members
368
+
369
+ unexpected_members = find_unexpected_members("numpy")
370
+ for modname in PUBLIC_MODULES:
371
+ unexpected_members.extend(find_unexpected_members(modname))
372
+
373
+ if unexpected_members:
374
+ raise AssertionError("Found unexpected object(s) that look like "
375
+ f"modules: {unexpected_members}")
376
+
377
+
378
+ def test_api_importable():
379
+ """
380
+ Check that all submodules listed higher up in this file can be imported
381
+
382
+ Note that if a PRIVATE_BUT_PRESENT_MODULES entry goes missing, it may
383
+ simply need to be removed from the list (deprecation may or may not be
384
+ needed - apply common sense).
385
+ """
386
+ def check_importable(module_name):
387
+ try:
388
+ importlib.import_module(module_name)
389
+ except (ImportError, AttributeError):
390
+ return False
391
+
392
+ return True
393
+
394
+ module_names = []
395
+ for module_name in PUBLIC_MODULES:
396
+ if not check_importable(module_name):
397
+ module_names.append(module_name)
398
+
399
+ if module_names:
400
+ raise AssertionError("Modules in the public API that cannot be "
401
+ f"imported: {module_names}")
402
+
403
+ for module_name in PUBLIC_ALIASED_MODULES:
404
+ try:
405
+ eval(module_name)
406
+ except AttributeError:
407
+ module_names.append(module_name)
408
+
409
+ if module_names:
410
+ raise AssertionError("Modules in the public API that were not "
411
+ f"found: {module_names}")
412
+
413
+ with warnings.catch_warnings(record=True) as w:
414
+ warnings.filterwarnings('always', category=DeprecationWarning)
415
+ warnings.filterwarnings('always', category=ImportWarning)
416
+ for module_name in PRIVATE_BUT_PRESENT_MODULES:
417
+ if not check_importable(module_name):
418
+ # Nasty hack to avoid new FreeBSD failures. This
419
+ # is only needed for NumPy 2.4.x, so go with it
420
+ if not module_name == 'numpy.distutils.msvccompiler':
421
+ module_names.append(module_name)
422
+
423
+ if module_names:
424
+ raise AssertionError("Modules that are not really public but looked "
425
+ "public and can not be imported: "
426
+ f"{module_names}")
427
+
428
+
429
+ @pytest.mark.xfail(
430
+ sysconfig.get_config_var("Py_DEBUG") not in (None, 0, "0"),
431
+ reason=(
432
+ "NumPy possibly built with `USE_DEBUG=True ./tools/travis-test.sh`, "
433
+ "which does not expose the `array_api` entry point. "
434
+ "See https://github.com/numpy/numpy/pull/19800"
435
+ ),
436
+ )
437
+ def test_array_api_entry_point():
438
+ """
439
+ Entry point for Array API implementation can be found with importlib and
440
+ returns the main numpy namespace.
441
+ """
442
+ # For a development install that did not go through meson-python,
443
+ # the entrypoint will not have been installed. So ensure this test fails
444
+ # only if numpy is inside site-packages.
445
+ numpy_in_sitepackages = sysconfig.get_path('platlib') in np.__file__
446
+
447
+ eps = importlib.metadata.entry_points()
448
+ xp_eps = eps.select(group="array_api")
449
+ if len(xp_eps) == 0:
450
+ if numpy_in_sitepackages:
451
+ msg = "No entry points for 'array_api' found"
452
+ raise AssertionError(msg) from None
453
+ return
454
+
455
+ try:
456
+ ep = next(ep for ep in xp_eps if ep.name == "numpy")
457
+ except StopIteration:
458
+ if numpy_in_sitepackages:
459
+ msg = "'numpy' not in array_api entry points"
460
+ raise AssertionError(msg) from None
461
+ return
462
+
463
+ if ep.value == 'numpy.array_api':
464
+ # Looks like the entrypoint for the current numpy build isn't
465
+ # installed, but an older numpy is also installed and hence the
466
+ # entrypoint is pointing to the old (no longer existing) location.
467
+ # This isn't a problem except for when running tests with `spin` or an
468
+ # in-place build.
469
+ return
470
+
471
+ xp = ep.load()
472
+ msg = (
473
+ f"numpy entry point value '{ep.value}' "
474
+ "does not point to our Array API implementation"
475
+ )
476
+ assert xp is numpy, msg
477
+
478
+
479
+ def test_main_namespace_all_dir_coherence():
480
+ """
481
+ Checks if `dir(np)` and `np.__all__` are consistent and return
482
+ the same content, excluding exceptions and private members.
483
+ """
484
+ def _remove_private_members(member_set):
485
+ return {m for m in member_set if not m.startswith('_')}
486
+
487
+ def _remove_exceptions(member_set):
488
+ return member_set.difference({
489
+ "bool" # included only in __dir__
490
+ })
491
+
492
+ all_members = _remove_private_members(np.__all__)
493
+ all_members = _remove_exceptions(all_members)
494
+
495
+ dir_members = _remove_private_members(np.__dir__())
496
+ dir_members = _remove_exceptions(dir_members)
497
+
498
+ assert all_members == dir_members, (
499
+ "Members that break symmetry: "
500
+ f"{all_members.symmetric_difference(dir_members)}"
501
+ )
502
+
503
+
504
+ @pytest.mark.filterwarnings(
505
+ r"ignore:numpy.core(\.\w+)? is deprecated:DeprecationWarning"
506
+ )
507
+ def test_core_shims_coherence():
508
+ """
509
+ Check that all "semi-public" members of `numpy._core` are also accessible
510
+ from `numpy.core` shims.
511
+ """
512
+ import numpy.core as core
513
+
514
+ for member_name in dir(np._core):
515
+ # Skip private and test members. Also if a module is aliased,
516
+ # no need to add it to np.core
517
+ if (
518
+ member_name.startswith("_")
519
+ or member_name in ["tests", "strings"]
520
+ or f"numpy.{member_name}" in PUBLIC_ALIASED_MODULES
521
+ ):
522
+ continue
523
+
524
+ member = getattr(np._core, member_name)
525
+
526
+ # np.core is a shim and all submodules of np.core are shims
527
+ # but we should be able to import everything in those shims
528
+ # that are available in the "real" modules in np._core, with
529
+ # the exception of the namespace packages (__spec__.origin is None),
530
+ # like numpy._core.include, or numpy._core.lib.pkgconfig.
531
+ if (
532
+ inspect.ismodule(member)
533
+ and member.__spec__ and member.__spec__.origin is not None
534
+ ):
535
+ submodule = member
536
+ submodule_name = member_name
537
+ for submodule_member_name in dir(submodule):
538
+ # ignore dunder names
539
+ if submodule_member_name.startswith("__"):
540
+ continue
541
+ submodule_member = getattr(submodule, submodule_member_name)
542
+
543
+ core_submodule = __import__(
544
+ f"numpy.core.{submodule_name}",
545
+ fromlist=[submodule_member_name]
546
+ )
547
+
548
+ assert submodule_member is getattr(
549
+ core_submodule, submodule_member_name
550
+ )
551
+
552
+ else:
553
+ assert member is getattr(core, member_name)
554
+
555
+
556
+ def test_functions_single_location():
557
+ """
558
+ Check that each public function is available from one location only.
559
+
560
+ Test performs BFS search traversing NumPy's public API. It flags
561
+ any function-like object that is accessible from more that one place.
562
+ """
563
+ from collections.abc import Callable
564
+ from typing import Any
565
+
566
+ from numpy._core._multiarray_umath import (
567
+ _ArrayFunctionDispatcher as dispatched_function,
568
+ )
569
+
570
+ visited_modules: set[types.ModuleType] = {np}
571
+ visited_functions: set[Callable[..., Any]] = set()
572
+ # Functions often have `__name__` overridden, therefore we need
573
+ # to keep track of locations where functions have been found.
574
+ functions_original_paths: dict[Callable[..., Any], str] = {}
575
+
576
+ # Here we aggregate functions with more than one location.
577
+ # It must be empty for the test to pass.
578
+ duplicated_functions: list[tuple] = []
579
+
580
+ modules_queue = [np]
581
+
582
+ while len(modules_queue) > 0:
583
+
584
+ module = modules_queue.pop()
585
+
586
+ for member_name in dir(module):
587
+ member = getattr(module, member_name)
588
+
589
+ # first check if we got a module
590
+ if (
591
+ inspect.ismodule(member) and # it's a module
592
+ "numpy" in member.__name__ and # inside NumPy
593
+ not member_name.startswith("_") and # not private
594
+ "numpy._core" not in member.__name__ and # outside _core
595
+ # not a legacy or testing module
596
+ member_name not in ["f2py", "ma", "testing", "tests"] and
597
+ member not in visited_modules # not visited yet
598
+ ):
599
+ modules_queue.append(member)
600
+ visited_modules.add(member)
601
+
602
+ # else check if we got a function-like object
603
+ elif (
604
+ inspect.isfunction(member) or
605
+ isinstance(member, (dispatched_function, np.ufunc))
606
+ ):
607
+ if member in visited_functions:
608
+
609
+ # skip main namespace functions with aliases
610
+ if (
611
+ member.__name__ in [
612
+ "absolute", # np.abs
613
+ "arccos", # np.acos
614
+ "arccosh", # np.acosh
615
+ "arcsin", # np.asin
616
+ "arcsinh", # np.asinh
617
+ "arctan", # np.atan
618
+ "arctan2", # np.atan2
619
+ "arctanh", # np.atanh
620
+ "left_shift", # np.bitwise_left_shift
621
+ "right_shift", # np.bitwise_right_shift
622
+ "conjugate", # np.conj
623
+ "invert", # np.bitwise_not & np.bitwise_invert
624
+ "remainder", # np.mod
625
+ "divide", # np.true_divide
626
+ "concatenate", # np.concat
627
+ "power", # np.pow
628
+ "transpose", # np.permute_dims
629
+ ] and
630
+ module.__name__ == "numpy"
631
+ ):
632
+ continue
633
+ # skip trimcoef from numpy.polynomial as it is
634
+ # duplicated by design.
635
+ if (
636
+ member.__name__ == "trimcoef" and
637
+ module.__name__.startswith("numpy.polynomial")
638
+ ):
639
+ continue
640
+
641
+ # skip ufuncs that are exported in np.strings as well
642
+ if member.__name__ in (
643
+ "add",
644
+ "equal",
645
+ "not_equal",
646
+ "greater",
647
+ "greater_equal",
648
+ "less",
649
+ "less_equal",
650
+ ) and module.__name__ == "numpy.strings":
651
+ continue
652
+
653
+ # numpy.char reexports all numpy.strings functions for
654
+ # backwards-compatibility
655
+ if module.__name__ == "numpy.char":
656
+ continue
657
+
658
+ # function is present in more than one location!
659
+ duplicated_functions.append(
660
+ (member.__name__,
661
+ module.__name__,
662
+ functions_original_paths[member])
663
+ )
664
+ else:
665
+ visited_functions.add(member)
666
+ functions_original_paths[member] = module.__name__
667
+
668
+ del visited_functions, visited_modules, functions_original_paths
669
+
670
+ assert len(duplicated_functions) == 0, duplicated_functions
671
+
672
+
673
+ def test___module___attribute():
674
+ modules_queue = [np]
675
+ visited_modules = {np}
676
+ visited_functions = set()
677
+ incorrect_entries = []
678
+
679
+ while len(modules_queue) > 0:
680
+ module = modules_queue.pop()
681
+ for member_name in dir(module):
682
+ member = getattr(module, member_name)
683
+ # first check if we got a module
684
+ if (
685
+ inspect.ismodule(member) and # it's a module
686
+ "numpy" in member.__name__ and # inside NumPy
687
+ not member_name.startswith("_") and # not private
688
+ "numpy._core" not in member.__name__ and # outside _core
689
+ # not in a skip module list
690
+ member_name not in [
691
+ "char", "core", "f2py", "ma", "lapack_lite", "mrecords",
692
+ "testing", "tests", "polynomial", "typing", "mtrand",
693
+ "bit_generator",
694
+ ] and
695
+ member not in visited_modules # not visited yet
696
+ ):
697
+ modules_queue.append(member)
698
+ visited_modules.add(member)
699
+ elif (
700
+ not inspect.ismodule(member) and
701
+ hasattr(member, "__name__") and
702
+ not member.__name__.startswith("_") and
703
+ member.__module__ != module.__name__ and
704
+ member not in visited_functions
705
+ ):
706
+ # skip ufuncs that are exported in np.strings as well
707
+ if member.__name__ in (
708
+ "add", "equal", "not_equal", "greater", "greater_equal",
709
+ "less", "less_equal",
710
+ ) and module.__name__ == "numpy.strings":
711
+ continue
712
+
713
+ # recarray and record are exported in np and np.rec
714
+ if (
715
+ (member.__name__ == "recarray" and module.__name__ == "numpy") or
716
+ (member.__name__ == "record" and module.__name__ == "numpy.rec")
717
+ ):
718
+ continue
719
+
720
+ # ctypeslib exports ctypes c_long/c_longlong
721
+ if (
722
+ member.__name__ in ("c_long", "c_longlong") and
723
+ module.__name__ == "numpy.ctypeslib"
724
+ ):
725
+ continue
726
+
727
+ # skip cdef classes
728
+ if member.__name__ in (
729
+ "BitGenerator", "Generator", "MT19937", "PCG64", "PCG64DXSM",
730
+ "Philox", "RandomState", "SFC64", "SeedSequence",
731
+ ):
732
+ continue
733
+
734
+ incorrect_entries.append(
735
+ {
736
+ "Func": member.__name__,
737
+ "actual": member.__module__,
738
+ "expected": module.__name__,
739
+ }
740
+ )
741
+ visited_functions.add(member)
742
+
743
+ if incorrect_entries:
744
+ assert len(incorrect_entries) == 0, incorrect_entries
745
+
746
+
747
+ def _check_correct_qualname_and_module(obj) -> bool:
748
+ qualname = obj.__qualname__
749
+ name = obj.__name__
750
+ module_name = obj.__module__
751
+ assert name == qualname.split(".")[-1]
752
+
753
+ module = sys.modules[module_name]
754
+ actual_obj = functools.reduce(getattr, qualname.split("."), module)
755
+ return (
756
+ actual_obj is obj or
757
+ # `obj` may be a bound method/property of `actual_obj`:
758
+ (
759
+ hasattr(actual_obj, "__get__") and hasattr(obj, "__self__") and
760
+ actual_obj.__module__ == obj.__module__ and
761
+ actual_obj.__qualname__ == qualname
762
+ )
763
+ )
764
+
765
+
766
+ def test___qualname___and___module___attribute():
767
+ # NumPy messes with module and name/qualname attributes, but any object
768
+ # should be discoverable based on its module and qualname, so test that.
769
+ # We do this for anything with a name (ensuring qualname is also set).
770
+ modules_queue = [np]
771
+ visited_modules = {np}
772
+ visited_functions = set()
773
+ incorrect_entries = []
774
+
775
+ while len(modules_queue) > 0:
776
+ module = modules_queue.pop()
777
+ for member_name in dir(module):
778
+ member = getattr(module, member_name)
779
+ # first check if we got a module
780
+ if (
781
+ inspect.ismodule(member) and # it's a module
782
+ "numpy" in member.__name__ and # inside NumPy
783
+ not member_name.startswith("_") and # not private
784
+ member_name not in {"tests", "typing"} and # type names don't match
785
+ "numpy._core" not in member.__name__ and # outside _core
786
+ member not in visited_modules # not visited yet
787
+ ):
788
+ modules_queue.append(member)
789
+ visited_modules.add(member)
790
+ elif (
791
+ not inspect.ismodule(member) and
792
+ hasattr(member, "__name__") and
793
+ not member.__name__.startswith("_") and
794
+ not member_name.startswith("_") and
795
+ not _check_correct_qualname_and_module(member) and
796
+ member not in visited_functions
797
+ ):
798
+ incorrect_entries.append(
799
+ {
800
+ "found_at": f"{module.__name__}:{member_name}",
801
+ "advertises": f"{member.__module__}:{member.__qualname__}",
802
+ }
803
+ )
804
+ visited_functions.add(member)
805
+
806
+ if incorrect_entries:
807
+ assert len(incorrect_entries) == 0, incorrect_entries
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_reloading.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ import subprocess
3
+ import sys
4
+ import textwrap
5
+ from importlib import reload
6
+
7
+ import pytest
8
+
9
+ import numpy.exceptions as ex
10
+ from numpy.testing import IS_WASM, assert_, assert_equal, assert_raises
11
+
12
+
13
+ @pytest.mark.thread_unsafe(reason="reloads global module")
14
+ def test_numpy_reloading():
15
+ # gh-7844. Also check that relevant globals retain their identity.
16
+ import numpy as np
17
+ import numpy._globals
18
+
19
+ _NoValue = np._NoValue
20
+ VisibleDeprecationWarning = ex.VisibleDeprecationWarning
21
+ ModuleDeprecationWarning = ex.ModuleDeprecationWarning
22
+
23
+ with pytest.warns(UserWarning):
24
+ reload(np)
25
+ assert_(_NoValue is np._NoValue)
26
+ assert_(ModuleDeprecationWarning is ex.ModuleDeprecationWarning)
27
+ assert_(VisibleDeprecationWarning is ex.VisibleDeprecationWarning)
28
+
29
+ assert_raises(RuntimeError, reload, numpy._globals)
30
+ with pytest.warns(UserWarning):
31
+ reload(np)
32
+ assert_(_NoValue is np._NoValue)
33
+ assert_(ModuleDeprecationWarning is ex.ModuleDeprecationWarning)
34
+ assert_(VisibleDeprecationWarning is ex.VisibleDeprecationWarning)
35
+
36
+ def test_novalue():
37
+ import numpy as np
38
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
39
+ assert_equal(repr(np._NoValue), '<no value>')
40
+ assert_(pickle.loads(pickle.dumps(np._NoValue,
41
+ protocol=proto)) is np._NoValue)
42
+
43
+
44
+ @pytest.mark.skipif(IS_WASM, reason="can't start subprocess")
45
+ def test_full_reimport():
46
+ # Reimporting numpy like this is not safe due to use of global C state,
47
+ # and has unexpected side effects. Test that an ImportError is raised.
48
+ # When all extension modules are isolated, this should test that clearing
49
+ # sys.modules and reimporting numpy works without error.
50
+
51
+ # Test within a new process, to ensure that we do not mess with the
52
+ # global state during the test run (could lead to cryptic test failures).
53
+ # This is generally unsafe, especially, since we also reload the C-modules.
54
+ code = textwrap.dedent(r"""
55
+ import sys
56
+ import numpy as np
57
+
58
+ for k in [k for k in sys.modules if k.startswith('numpy')]:
59
+ del sys.modules[k]
60
+
61
+ try:
62
+ import numpy as np
63
+ except ImportError as err:
64
+ if str(err) != "cannot load module more than once per process":
65
+ raise SystemExit(f"Unexpected ImportError: {err}")
66
+ else:
67
+ raise SystemExit("DID NOT RAISE ImportError")
68
+ """)
69
+ p = subprocess.run(
70
+ (sys.executable, '-c', code),
71
+ stdout=subprocess.PIPE,
72
+ stderr=subprocess.STDOUT,
73
+ encoding='utf-8',
74
+ check=False,
75
+ )
76
+ assert p.returncode == 0, p.stdout
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_scripts.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Test scripts
2
+
3
+ Test that we can run executable scripts that have been installed with numpy.
4
+ """
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ from os.path import dirname, isfile, join as pathjoin
9
+
10
+ import pytest
11
+
12
+ import numpy as np
13
+ from numpy.testing import IS_WASM, assert_equal
14
+
15
+ is_inplace = isfile(pathjoin(dirname(np.__file__), '..', 'setup.py'))
16
+
17
+
18
+ def find_f2py_commands():
19
+ if sys.platform == 'win32':
20
+ exe_dir = dirname(sys.executable)
21
+ if exe_dir.endswith('Scripts'): # virtualenv
22
+ return [os.path.join(exe_dir, 'f2py')]
23
+ else:
24
+ return [os.path.join(exe_dir, "Scripts", 'f2py')]
25
+ else:
26
+ # Three scripts are installed in Unix-like systems:
27
+ # 'f2py', 'f2py{major}', and 'f2py{major.minor}'. For example,
28
+ # if installed with python3.9 the scripts would be named
29
+ # 'f2py', 'f2py3', and 'f2py3.9'.
30
+ version = sys.version_info
31
+ major = str(version.major)
32
+ minor = str(version.minor)
33
+ return ['f2py', 'f2py' + major, 'f2py' + major + '.' + minor]
34
+
35
+
36
+ @pytest.mark.skipif(is_inplace, reason="Cannot test f2py command inplace")
37
+ @pytest.mark.xfail(reason="Test is unreliable")
38
+ @pytest.mark.parametrize('f2py_cmd', find_f2py_commands())
39
+ def test_f2py(f2py_cmd):
40
+ # test that we can run f2py script
41
+ stdout = subprocess.check_output([f2py_cmd, '-v'])
42
+ assert_equal(stdout.strip(), np.__version__.encode('ascii'))
43
+
44
+
45
+ @pytest.mark.skipif(IS_WASM, reason="Cannot start subprocess")
46
+ def test_pep338():
47
+ stdout = subprocess.check_output([sys.executable, '-mnumpy.f2py', '-v'])
48
+ assert_equal(stdout.strip(), np.__version__.encode('ascii'))
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/tests/test_warnings.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests which scan for certain occurrences in the code, they may not find
3
+ all of these occurrences but should catch almost all.
4
+ """
5
+ import ast
6
+ import tokenize
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+
11
+ import numpy
12
+
13
+
14
+ class ParseCall(ast.NodeVisitor):
15
+ def __init__(self):
16
+ self.ls = []
17
+
18
+ def visit_Attribute(self, node):
19
+ ast.NodeVisitor.generic_visit(self, node)
20
+ self.ls.append(node.attr)
21
+
22
+ def visit_Name(self, node):
23
+ self.ls.append(node.id)
24
+
25
+
26
+ class FindFuncs(ast.NodeVisitor):
27
+ def __init__(self, filename):
28
+ super().__init__()
29
+ self.__filename = filename
30
+
31
+ def visit_Call(self, node):
32
+ p = ParseCall()
33
+ p.visit(node.func)
34
+ ast.NodeVisitor.generic_visit(self, node)
35
+
36
+ if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings':
37
+ if getattr(node.args[0], "value", None) == "ignore":
38
+ if not self.__filename.name.startswith("test_"):
39
+ raise AssertionError(
40
+ "ignore filters should only be used in tests; "
41
+ f"found in {self.__filename} on line {node.lineno}")
42
+
43
+ if p.ls[-1] == 'warn' and (
44
+ len(p.ls) == 1 or p.ls[-2] == 'warnings'):
45
+
46
+ if "testing/tests/test_warnings.py" == self.__filename:
47
+ # This file
48
+ return
49
+
50
+ # See if stacklevel exists:
51
+ if len(node.args) == 3:
52
+ return
53
+ args = {kw.arg for kw in node.keywords}
54
+ if "stacklevel" in args:
55
+ return
56
+ raise AssertionError(
57
+ "warnings should have an appropriate stacklevel; "
58
+ f"found in {self.__filename} on line {node.lineno}")
59
+
60
+
61
+ @pytest.mark.slow
62
+ def test_warning_calls():
63
+ # combined "ignore" and stacklevel error
64
+ base = Path(numpy.__file__).parent
65
+
66
+ for path in base.rglob("*.py"):
67
+ if base / "testing" in path.parents:
68
+ continue
69
+ if path == base / "__init__.py":
70
+ continue
71
+ if path == base / "random" / "__init__.py":
72
+ continue
73
+ if path == base / "conftest.py":
74
+ continue
75
+ # use tokenize to auto-detect encoding on systems where no
76
+ # default encoding is defined (e.g. LANG='C')
77
+ with tokenize.open(str(path)) as file:
78
+ tree = ast.parse(file.read())
79
+ FindFuncs(path).visit(tree)
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/typing/__init__.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ============================
3
+ Typing (:mod:`numpy.typing`)
4
+ ============================
5
+
6
+ .. versionadded:: 1.20
7
+
8
+ Large parts of the NumPy API have :pep:`484`-style type annotations. In
9
+ addition a number of type aliases are available to users, most prominently
10
+ the two below:
11
+
12
+ - `ArrayLike`: objects that can be converted to arrays
13
+ - `DTypeLike`: objects that can be converted to dtypes
14
+
15
+ .. _typing-extensions: https://pypi.org/project/typing-extensions/
16
+
17
+ Mypy plugin
18
+ -----------
19
+
20
+ .. versionadded:: 1.21
21
+
22
+ .. automodule:: numpy.typing.mypy_plugin
23
+
24
+ .. currentmodule:: numpy.typing
25
+
26
+ Differences from the runtime NumPy API
27
+ --------------------------------------
28
+
29
+ NumPy is very flexible. Trying to describe the full range of
30
+ possibilities statically would result in types that are not very
31
+ helpful. For that reason, the typed NumPy API is often stricter than
32
+ the runtime NumPy API. This section describes some notable
33
+ differences.
34
+
35
+ ArrayLike
36
+ ~~~~~~~~~
37
+
38
+ The `ArrayLike` type tries to avoid creating object arrays. For
39
+ example,
40
+
41
+ .. code-block:: python
42
+
43
+ >>> np.array(x**2 for x in range(10))
44
+ array(<generator object <genexpr> at ...>, dtype=object)
45
+
46
+ is valid NumPy code which will create a 0-dimensional object
47
+ array. Type checkers will complain about the above example when using
48
+ the NumPy types however. If you really intended to do the above, then
49
+ you can either use a ``# type: ignore`` comment:
50
+
51
+ .. code-block:: python
52
+
53
+ >>> np.array(x**2 for x in range(10)) # type: ignore
54
+
55
+ or explicitly type the array like object as `~typing.Any`:
56
+
57
+ .. code-block:: python
58
+
59
+ >>> from typing import Any
60
+ >>> array_like: Any = (x**2 for x in range(10))
61
+ >>> np.array(array_like)
62
+ array(<generator object <genexpr> at ...>, dtype=object)
63
+
64
+ ndarray
65
+ ~~~~~~~
66
+
67
+ It's possible to mutate the dtype of an array at runtime. For example,
68
+ the following code is valid:
69
+
70
+ .. code-block:: python
71
+
72
+ >>> x = np.array([1, 2])
73
+ >>> x.dtype = np.bool
74
+
75
+ This sort of mutation is not allowed by the types. Users who want to
76
+ write statically typed code should instead use the `numpy.ndarray.view`
77
+ method to create a view of the array with a different dtype.
78
+
79
+ DTypeLike
80
+ ~~~~~~~~~
81
+
82
+ The `DTypeLike` type tries to avoid creation of dtype objects using
83
+ dictionary of fields like below:
84
+
85
+ .. code-block:: python
86
+
87
+ >>> x = np.dtype({"field1": (float, 1), "field2": (int, 3)})
88
+
89
+ Although this is valid NumPy code, the type checker will complain about it,
90
+ since its usage is discouraged.
91
+ Please see : :ref:`Data type objects <arrays.dtypes>`
92
+
93
+ Number precision
94
+ ~~~~~~~~~~~~~~~~
95
+
96
+ The precision of `numpy.number` subclasses is treated as a invariant generic
97
+ parameter (see :class:`~NBitBase`), simplifying the annotating of processes
98
+ involving precision-based casting.
99
+
100
+ .. code-block:: python
101
+
102
+ >>> from typing import TypeVar
103
+ >>> import numpy as np
104
+ >>> import numpy.typing as npt
105
+
106
+ >>> T = TypeVar("T", bound=npt.NBitBase)
107
+ >>> def func(a: np.floating[T], b: np.floating[T]) -> np.floating[T]:
108
+ ... ...
109
+
110
+ Consequently, the likes of `~numpy.float16`, `~numpy.float32` and
111
+ `~numpy.float64` are still sub-types of `~numpy.floating`, but, contrary to
112
+ runtime, they're not necessarily considered as sub-classes.
113
+
114
+ .. deprecated:: 2.3
115
+ The :class:`~numpy.typing.NBitBase` helper is deprecated and will be
116
+ removed in a future release. Prefer expressing precision relationships via
117
+ ``typing.overload`` or ``TypeVar`` definitions bounded by concrete scalar
118
+ classes. For example:
119
+
120
+ .. code-block:: python
121
+
122
+ from typing import TypeVar
123
+ import numpy as np
124
+
125
+ S = TypeVar("S", bound=np.floating)
126
+
127
+ def func(a: S, b: S) -> S:
128
+ ...
129
+
130
+ or in the case of different input types mapping to different output types:
131
+
132
+ .. code-block:: python
133
+
134
+ from typing import overload
135
+ import numpy as np
136
+
137
+ @overload
138
+ def phase(x: np.complex64) -> np.float32: ...
139
+ @overload
140
+ def phase(x: np.complex128) -> np.float64: ...
141
+ @overload
142
+ def phase(x: np.clongdouble) -> np.longdouble: ...
143
+ def phase(x: np.complexfloating) -> np.floating:
144
+ ...
145
+
146
+ Timedelta64
147
+ ~~~~~~~~~~~
148
+
149
+ The `~numpy.timedelta64` class is not considered a subclass of
150
+ `~numpy.signedinteger`, the former only inheriting from `~numpy.generic`
151
+ while static type checking.
152
+
153
+ 0D arrays
154
+ ~~~~~~~~~
155
+
156
+ During runtime numpy aggressively casts any passed 0D arrays into their
157
+ corresponding `~numpy.generic` instance. Until the introduction of shape
158
+ typing (see :pep:`646`) it is unfortunately not possible to make the
159
+ necessary distinction between 0D and >0D arrays. While thus not strictly
160
+ correct, all operations that can potentially perform a 0D-array -> scalar
161
+ cast are currently annotated as exclusively returning an `~numpy.ndarray`.
162
+
163
+ If it is known in advance that an operation *will* perform a
164
+ 0D-array -> scalar cast, then one can consider manually remedying the
165
+ situation with either `typing.cast` or a ``# type: ignore`` comment.
166
+
167
+ Record array dtypes
168
+ ~~~~~~~~~~~~~~~~~~~
169
+
170
+ The dtype of `numpy.recarray`, and the :ref:`routines.array-creation.rec`
171
+ functions in general, can be specified in one of two ways:
172
+
173
+ * Directly via the ``dtype`` argument.
174
+ * With up to five helper arguments that operate via `numpy.rec.format_parser`:
175
+ ``formats``, ``names``, ``titles``, ``aligned`` and ``byteorder``.
176
+
177
+ These two approaches are currently typed as being mutually exclusive,
178
+ *i.e.* if ``dtype`` is specified than one may not specify ``formats``.
179
+ While this mutual exclusivity is not (strictly) enforced during runtime,
180
+ combining both dtype specifiers can lead to unexpected or even downright
181
+ buggy behavior.
182
+
183
+ API
184
+ ---
185
+
186
+ """
187
+ # NOTE: The API section will be appended with additional entries
188
+ # further down in this file
189
+
190
+ # pyright: reportDeprecated=false
191
+
192
+ from numpy._typing import ArrayLike, DTypeLike, NBitBase, NDArray
193
+
194
+ __all__ = ["ArrayLike", "DTypeLike", "NBitBase", "NDArray"]
195
+
196
+
197
+ __DIR = __all__ + [k for k in globals() if k.startswith("__") and k.endswith("__")]
198
+ __DIR_SET = frozenset(__DIR)
199
+
200
+
201
+ def __dir__() -> list[str]:
202
+ return __DIR
203
+
204
+ def __getattr__(name: str) -> object:
205
+ if name == "NBitBase":
206
+ import warnings
207
+
208
+ # Deprecated in NumPy 2.3, 2025-05-01
209
+ warnings.warn(
210
+ "`NBitBase` is deprecated and will be removed from numpy.typing in the "
211
+ "future. Use `@typing.overload` or a `TypeVar` with a scalar-type as upper "
212
+ "bound, instead. (deprecated in NumPy 2.3)",
213
+ DeprecationWarning,
214
+ stacklevel=2,
215
+ )
216
+ return NBitBase
217
+
218
+ if name in __DIR_SET:
219
+ return globals()[name]
220
+
221
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
222
+
223
+
224
+ if __doc__ is not None:
225
+ from numpy._typing._add_docstring import _docstrings
226
+ __doc__ += _docstrings
227
+ __doc__ += '\n.. autoclass:: numpy.typing.NBitBase\n'
228
+ del _docstrings
229
+
230
+ from numpy._pytesttester import PytestTester
231
+
232
+ test = PytestTester(__name__)
233
+ del PytestTester
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/typing/__init__.pyi ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from numpy._typing import ArrayLike, DTypeLike, NBitBase, NDArray
2
+
3
+ __all__ = ["ArrayLike", "DTypeLike", "NBitBase", "NDArray"]
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/numpy/typing/mypy_plugin.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A mypy_ plugin for managing a number of platform-specific annotations.
2
+ Its functionality can be split into three distinct parts:
3
+
4
+ * Assigning the (platform-dependent) precisions of certain `~numpy.number`
5
+ subclasses, including the likes of `~numpy.int_`, `~numpy.intp` and
6
+ `~numpy.longlong`. See the documentation on
7
+ :ref:`scalar types <arrays.scalars.built-in>` for a comprehensive overview
8
+ of the affected classes. Without the plugin the precision of all relevant
9
+ classes will be inferred as `~typing.Any`.
10
+ * Removing all extended-precision `~numpy.number` subclasses that are
11
+ unavailable for the platform in question. Most notably this includes the
12
+ likes of `~numpy.float128` and `~numpy.complex256`. Without the plugin *all*
13
+ extended-precision types will, as far as mypy is concerned, be available
14
+ to all platforms.
15
+ * Assigning the (platform-dependent) precision of `~numpy.ctypeslib.c_intp`.
16
+ Without the plugin the type will default to `ctypes.c_int64`.
17
+
18
+ .. versionadded:: 1.22
19
+
20
+ .. deprecated:: 2.3
21
+ The :mod:`numpy.typing.mypy_plugin` entry-point is deprecated in favor of
22
+ platform-agnostic static type inference. Remove
23
+ ``numpy.typing.mypy_plugin`` from the ``plugins`` section of your mypy
24
+ configuration; if that surfaces new errors, please open an issue with a
25
+ minimal reproducer.
26
+
27
+ Examples
28
+ --------
29
+ To enable the plugin, one must add it to their mypy `configuration file`_:
30
+
31
+ .. code-block:: ini
32
+
33
+ [mypy]
34
+ plugins = numpy.typing.mypy_plugin
35
+
36
+ .. _mypy: https://mypy-lang.org/
37
+ .. _configuration file: https://mypy.readthedocs.io/en/stable/config_file.html
38
+
39
+ """
40
+
41
+ from collections.abc import Callable, Iterable
42
+ from typing import TYPE_CHECKING, Final, TypeAlias, cast
43
+
44
+ import numpy as np
45
+
46
+ __all__: list[str] = []
47
+
48
+
49
+ def _get_precision_dict() -> dict[str, str]:
50
+ names = [
51
+ ("_NBitByte", np.byte),
52
+ ("_NBitShort", np.short),
53
+ ("_NBitIntC", np.intc),
54
+ ("_NBitIntP", np.intp),
55
+ ("_NBitInt", np.int_),
56
+ ("_NBitLong", np.long),
57
+ ("_NBitLongLong", np.longlong),
58
+
59
+ ("_NBitHalf", np.half),
60
+ ("_NBitSingle", np.single),
61
+ ("_NBitDouble", np.double),
62
+ ("_NBitLongDouble", np.longdouble),
63
+ ]
64
+ ret: dict[str, str] = {}
65
+ for name, typ in names:
66
+ n = 8 * np.dtype(typ).itemsize
67
+ ret[f"{_MODULE}._nbit.{name}"] = f"{_MODULE}._nbit_base._{n}Bit"
68
+ return ret
69
+
70
+
71
+ def _get_extended_precision_list() -> list[str]:
72
+ extended_names = [
73
+ "float96",
74
+ "float128",
75
+ "complex192",
76
+ "complex256",
77
+ ]
78
+ return [i for i in extended_names if hasattr(np, i)]
79
+
80
+ def _get_c_intp_name() -> str:
81
+ # Adapted from `np.core._internal._getintp_ctype`
82
+ return {
83
+ "i": "c_int",
84
+ "l": "c_long",
85
+ "q": "c_longlong",
86
+ }.get(np.dtype("n").char, "c_long")
87
+
88
+
89
+ _MODULE: Final = "numpy._typing"
90
+
91
+ #: A dictionary mapping type-aliases in `numpy._typing._nbit` to
92
+ #: concrete `numpy.typing.NBitBase` subclasses.
93
+ _PRECISION_DICT: Final = _get_precision_dict()
94
+
95
+ #: A list with the names of all extended precision `np.number` subclasses.
96
+ _EXTENDED_PRECISION_LIST: Final = _get_extended_precision_list()
97
+
98
+ #: The name of the ctypes equivalent of `np.intp`
99
+ _C_INTP: Final = _get_c_intp_name()
100
+
101
+
102
+ try:
103
+ if TYPE_CHECKING:
104
+ from mypy.typeanal import TypeAnalyser
105
+
106
+ import mypy.types
107
+ from mypy.build import PRI_MED
108
+ from mypy.nodes import ImportFrom, MypyFile, Statement
109
+ from mypy.plugin import AnalyzeTypeContext, Plugin
110
+
111
+ except ModuleNotFoundError as e:
112
+
113
+ def plugin(version: str) -> type:
114
+ raise e
115
+
116
+ else:
117
+
118
+ _HookFunc: TypeAlias = Callable[[AnalyzeTypeContext], mypy.types.Type]
119
+
120
+ def _hook(ctx: AnalyzeTypeContext) -> mypy.types.Type:
121
+ """Replace a type-alias with a concrete ``NBitBase`` subclass."""
122
+ typ, _, api = ctx
123
+ name = typ.name.split(".")[-1]
124
+ name_new = _PRECISION_DICT[f"{_MODULE}._nbit.{name}"]
125
+ return cast("TypeAnalyser", api).named_type(name_new)
126
+
127
+ def _index(iterable: Iterable[Statement], id: str) -> int:
128
+ """Identify the first ``ImportFrom`` instance the specified `id`."""
129
+ for i, value in enumerate(iterable):
130
+ if getattr(value, "id", None) == id:
131
+ return i
132
+ raise ValueError("Failed to identify a `ImportFrom` instance "
133
+ f"with the following id: {id!r}")
134
+
135
+ def _override_imports(
136
+ file: MypyFile,
137
+ module: str,
138
+ imports: list[tuple[str, str | None]],
139
+ ) -> None:
140
+ """Override the first `module`-based import with new `imports`."""
141
+ # Construct a new `from module import y` statement
142
+ import_obj = ImportFrom(module, 0, names=imports)
143
+ import_obj.is_top_level = True
144
+
145
+ # Replace the first `module`-based import statement with `import_obj`
146
+ for lst in [file.defs, cast("list[Statement]", file.imports)]:
147
+ i = _index(lst, module)
148
+ lst[i] = import_obj
149
+
150
+ class _NumpyPlugin(Plugin):
151
+ """A mypy plugin for handling versus numpy-specific typing tasks."""
152
+
153
+ def get_type_analyze_hook(self, fullname: str) -> _HookFunc | None:
154
+ """Set the precision of platform-specific `numpy.number`
155
+ subclasses.
156
+
157
+ For example: `numpy.int_`, `numpy.longlong` and `numpy.longdouble`.
158
+ """
159
+ if fullname in _PRECISION_DICT:
160
+ return _hook
161
+ return None
162
+
163
+ def get_additional_deps(
164
+ self, file: MypyFile
165
+ ) -> list[tuple[int, str, int]]:
166
+ """Handle all import-based overrides.
167
+
168
+ * Import platform-specific extended-precision `numpy.number`
169
+ subclasses (*e.g.* `numpy.float96` and `numpy.float128`).
170
+ * Import the appropriate `ctypes` equivalent to `numpy.intp`.
171
+
172
+ """
173
+ fullname = file.fullname
174
+ if fullname == "numpy":
175
+ _override_imports(
176
+ file,
177
+ f"{_MODULE}._extended_precision",
178
+ imports=[(v, v) for v in _EXTENDED_PRECISION_LIST],
179
+ )
180
+ elif fullname == "numpy.ctypeslib":
181
+ _override_imports(
182
+ file,
183
+ "ctypes",
184
+ imports=[(_C_INTP, "_c_intp")],
185
+ )
186
+ return [(PRI_MED, fullname, -1)]
187
+
188
+ def plugin(version: str) -> type:
189
+ import warnings
190
+
191
+ plugin = "numpy.typing.mypy_plugin"
192
+ # Deprecated 2025-01-10, NumPy 2.3
193
+ warn_msg = (
194
+ f"`{plugin}` is deprecated, and will be removed in a future "
195
+ f"release. Please remove `plugins = {plugin}` in your mypy config."
196
+ f"(deprecated in NumPy 2.3)"
197
+ )
198
+ warnings.warn(warn_msg, DeprecationWarning, stacklevel=3)
199
+
200
+ return _NumpyPlugin
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (209 Bytes). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_core_metadata.cpython-311.pyc ADDED
Binary file (5.08 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_core_utils.cpython-311.pyc ADDED
Binary file (8.59 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_decorators.cpython-311.pyc ADDED
Binary file (41.6 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_decorators_v1.cpython-311.pyc ADDED
Binary file (9.93 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_discriminated_union.cpython-311.pyc ADDED
Binary file (23.3 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_docs_extraction.cpython-311.pyc ADDED
Binary file (5.79 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_forward_ref.cpython-311.pyc ADDED
Binary file (1.48 kB). View file