Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
exceptions.py247 linesDownload Raw Back to numpy
1"""
2Exceptions and Warnings
3=======================
4
5General exceptions used by NumPy.  Note that some exceptions may be module
6specific, such as linear algebra errors.
7
8.. versionadded:: NumPy 1.25
9
10    The exceptions module is new in NumPy 1.25.
11
12.. currentmodule:: numpy.exceptions
13
14Warnings
15--------
16.. autosummary::
17   :toctree: generated/
18
19   ComplexWarning             Given when converting complex to real.
20   VisibleDeprecationWarning  Same as a DeprecationWarning, but more visible.
21   RankWarning                Issued when the design matrix is rank deficient.
22
23Exceptions
24----------
25.. autosummary::
26   :toctree: generated/
27
28    AxisError          Given when an axis was invalid.
29    DTypePromotionError   Given when no common dtype could be found.
30    TooHardError       Error specific to `numpy.shares_memory`.
31
32"""
33
34
35__all__ = [
36    "ComplexWarning", "VisibleDeprecationWarning", "ModuleDeprecationWarning",
37    "TooHardError", "AxisError", "DTypePromotionError"]
38
39
40# Disallow reloading this module so as to preserve the identities of the
41# classes defined here.
42if '_is_loaded' in globals():
43    raise RuntimeError('Reloading numpy._globals is not allowed')
44_is_loaded = True
45
46
47class ComplexWarning(RuntimeWarning):
48    """
49    The warning raised when casting a complex dtype to a real dtype.
50
51    As implemented, casting a complex number to a real discards its imaginary
52    part, but this behavior may not be what the user actually wants.
53
54    """
55    pass
56
57
58class ModuleDeprecationWarning(DeprecationWarning):
59    """Module deprecation warning.
60
61    .. warning::
62
63        This warning should not be used, since nose testing is not relevant
64        anymore.
65
66    The nose tester turns ordinary Deprecation warnings into test failures.
67    That makes it hard to deprecate whole modules, because they get
68    imported by default. So this is a special Deprecation warning that the
69    nose tester will let pass without making tests fail.
70
71    """
72    pass
73
74
75class VisibleDeprecationWarning(UserWarning):
76    """Visible deprecation warning.
77
78    By default, python will not show deprecation warnings, so this class
79    can be used when a very visible warning is helpful, for example because
80    the usage is most likely a user bug.
81
82    """
83    pass
84
85
86class RankWarning(RuntimeWarning):
87    """Matrix rank warning.
88
89    Issued by polynomial functions when the design matrix is rank deficient.
90
91    """
92    pass
93
94
95# Exception used in shares_memory()
96class TooHardError(RuntimeError):
97    """``max_work`` was exceeded.
98
99    This is raised whenever the maximum number of candidate solutions
100    to consider specified by the ``max_work`` parameter is exceeded.
101    Assigning a finite number to ``max_work`` may have caused the operation
102    to fail.
103
104    """
105    pass
106
107
108class AxisError(ValueError, IndexError):
109    """Axis supplied was invalid.
110
111    This is raised whenever an ``axis`` parameter is specified that is larger
112    than the number of array dimensions.
113    For compatibility with code written against older numpy versions, which
114    raised a mixture of :exc:`ValueError` and :exc:`IndexError` for this
115    situation, this exception subclasses both to ensure that
116    ``except ValueError`` and ``except IndexError`` statements continue
117    to catch ``AxisError``.
118
119    Parameters
120    ----------
121    axis : int or str
122        The out of bounds axis or a custom exception message.
123        If an axis is provided, then `ndim` should be specified as well.
124    ndim : int, optional
125        The number of array dimensions.
126    msg_prefix : str, optional
127        A prefix for the exception message.
128
129    Attributes
130    ----------
131    axis : int, optional
132        The out of bounds axis or ``None`` if a custom exception
133        message was provided. This should be the axis as passed by
134        the user, before any normalization to resolve negative indices.
135
136        .. versionadded:: 1.22
137    ndim : int, optional
138        The number of array dimensions or ``None`` if a custom exception
139        message was provided.
140
141        .. versionadded:: 1.22
142
143
144    Examples
145    --------
146    >>> import numpy as np
147    >>> array_1d = np.arange(10)
148    >>> np.cumsum(array_1d, axis=1)
149    Traceback (most recent call last):
150      ...
151    numpy.exceptions.AxisError: axis 1 is out of bounds for array of dimension 1
152
153    Negative axes are preserved:
154
155    >>> np.cumsum(array_1d, axis=-2)
156    Traceback (most recent call last):
157      ...
158    numpy.exceptions.AxisError: axis -2 is out of bounds for array of dimension 1
159
160    The class constructor generally takes the axis and arrays'
161    dimensionality as arguments:
162
163    >>> print(np.exceptions.AxisError(2, 1, msg_prefix='error'))
164    error: axis 2 is out of bounds for array of dimension 1
165
166    Alternatively, a custom exception message can be passed:
167
168    >>> print(np.exceptions.AxisError('Custom error message'))
169    Custom error message
170
171    """
172
173    __slots__ = ("_msg", "axis", "ndim")
174
175    def __init__(self, axis, ndim=None, msg_prefix=None):
176        if ndim is msg_prefix is None:
177            # single-argument form: directly set the error message
178            self._msg = axis
179            self.axis = None
180            self.ndim = None
181        else:
182            self._msg = msg_prefix
183            self.axis = axis
184            self.ndim = ndim
185
186    def __str__(self):
187        axis = self.axis
188        ndim = self.ndim
189
190        if axis is ndim is None:
191            return self._msg
192        else:
193            msg = f"axis {axis} is out of bounds for array of dimension {ndim}"
194            if self._msg is not None:
195                msg = f"{self._msg}: {msg}"
196            return msg
197
198
199class DTypePromotionError(TypeError):
200    """Multiple DTypes could not be converted to a common one.
201
202    This exception derives from ``TypeError`` and is raised whenever dtypes
203    cannot be converted to a single common one.  This can be because they
204    are of a different category/class or incompatible instances of the same
205    one (see Examples).
206
207    Notes
208    -----
209    Many functions will use promotion to find the correct result and
210    implementation.  For these functions the error will typically be chained
211    with a more specific error indicating that no implementation was found
212    for the input dtypes.
213
214    Typically promotion should be considered "invalid" between the dtypes of
215    two arrays when `arr1 == arr2` can safely return all ``False`` because the
216    dtypes are fundamentally different.
217
218    Examples
219    --------
220    Datetimes and complex numbers are incompatible classes and cannot be
221    promoted:
222
223    >>> import numpy as np
224    >>> np.result_type(np.dtype("M8[s]"), np.complex128)  # doctest: +IGNORE_EXCEPTION_DETAIL
225    Traceback (most recent call last):
226     ...
227    DTypePromotionError: The DType <class 'numpy.dtype[datetime64]'> could not
228    be promoted by <class 'numpy.dtype[complex128]'>. This means that no common
229    DType exists for the given inputs. For example they cannot be stored in a
230    single array unless the dtype is `object`. The full list of DTypes is:
231    (<class 'numpy.dtype[datetime64]'>, <class 'numpy.dtype[complex128]'>)
232
233    For example for structured dtypes, the structure can mismatch and the
234    same ``DTypePromotionError`` is given when two structured dtypes with
235    a mismatch in their number of fields is given:
236
237    >>> dtype1 = np.dtype([("field1", np.float64), ("field2", np.int64)])
238    >>> dtype2 = np.dtype([("field1", np.float64)])
239    >>> np.promote_types(dtype1, dtype2)  # doctest: +IGNORE_EXCEPTION_DETAIL
240    Traceback (most recent call last):
241     ...
242    DTypePromotionError: field names `('field1', 'field2')` and `('field1',)`
243    mismatch.
244
245    """  # noqa: E501
246    pass
247 
codekingpro/portable-devtools · Team Ai